from mod_python import apache
import sql_io
import web_gp_manager
#import file_io
import os
import sys
from elementtree import ElementTree
import cElementTree
import datetime
import random
import string
import smtplib
from email.MIMEText import MIMEText

phone_charset = "1234567890+ "
date_charset = "1234567890-"
email_charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890@.~-"
ascii_charset = string.digits + string.letters + string.punctuation + " \r\n" 
# "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+-={}[]:\";',.<>/?\\|`~ " 
replaces = (("\x0a", "<a>"), ("\n", "<br>"), ("<", "&lt;"), (">", "&gt;"))

class system_info:
    def __init__(self, req):
        # system paths        
        if sys.platform == "win32":
            self.local_root = "d:/webpages/conference/"
            self.page_script = "http://kolenaty/conference/index.py"  
        elif sys.platform == "linux2":
            self.local_root = "/home/conference/public_html/"
            self.page_script = "http://ribosome.natur.cuni.cz/~conference/index.py"  
        else:
             raise RuntimeError, "Unknown system."
        # DB connection
        try:
            self.dbhandler = sql_io.DBHandler()
        except IOError, e:
            raise RuntimeError, "Error: " + str(e) + "<br>\n"

        self.site_email = "conference@ribosome.natur.cuni.cz"
        self.smtp = "195.113.56.6" 
        #"natur.cuni.cz" 
        # input params
        self._GET = web_gp_manager.get_get(req)
        self._POST = web_gp_manager.get_post(req.form)
        # get page    
        if self._GET.has_key("page"):
            self.page = self._GET["page"][0]
        else:
            self.page = "default"
        # get conference
        if self._GET.has_key("conference"):
            self.conference = self._GET["conference"][0].replace("'","").replace("%","").replace('"','').replace('&','') # BUG! strip away suspicious chars, like in case of "TCNCRNA'%22'"
        else:
            self.conference = "TCNCRNA"
            
        self._newly_saved = 0
            

class conference:
    def __init__(self, si):
        # conference check
        result = si.dbhandler.do_sql_cmd("SELECT id, conference_name, conference_short, conference_period, conference_deadline, conference_subtitle, registration_details, conference_note FROM conferences WHERE conference_short = '"+si.conference+"'")
        if len(result) == 0:
            raise RuntimeError, "Conference '%s' was not found!<br>\n"%si.conference
        else:
            self.conference = si.conference
            self.conference_id = result[0][0]
            self.conference_name = result[0][1]
            self.conference_period = result[0][3]
            self.conference_deadline = result[0][4]
            self.conference_subtitle = result[0][5]    
            _registration_details = result[0][6].split("\n")            
            self.registration_details = {}
            for _registration_detail in _registration_details:
                _defs = _registration_detail.split(";")                 
                if not self.registration_details.has_key(_defs[1]):
                    self.registration_details[_defs[1]] = []
                self.registration_details[_defs[1]].append([_defs[0], _defs[2]])
            self.conference_note = result[0][7]
        # xml_def
        _file_name = si.local_root+"defs/"+si.conference+".xml"
        if os.path.isfile(_file_name):
            try:
                self.xml_def = ElementTree.parse(_file_name)._root
            except IOError, e:
                raise RuntimeError, "ElementTree.parse(" + str(_file_name) + ")._root failed with: " + str(e)
        else:
            raise RuntimeError, "No definition file for conference '%s'!<br>\n" % si.conference
        

def make_command(page_script, page, conference, _dict, _sublink = None):
    s = ""
    s += page_script
    s += "?page=" + page
    s += "&conference=" + conference
    for _key in _dict.keys():
        s += "&" + _key + "=" + _dict[_key]
    if not _sublink is None and _sublink != "":
        s += "#" + _sublink
    return s

def check_string(string, charset):
    r = 1; s = ""
    for _char in string:
        if not _char in charset:
            r = 0
            if not _char in s:
                s += _char 
    return r, s
    
    
def empty_input(string):
    if string is None or string == "" or string == "please select":
        return 1
    else:
        return 0 
        
def check_input(string, charset, field_name, nonempty = 1):
    if nonempty and empty_input(string):
        return (0, "Field <b>%s</b> should not be <i>empty</i>.<br>\n"%field_name)
    chs = check_string(string, charset)     
    if not chs[0]:
        return (0, "Field <b>%s</b> contains <i>unallowed character(s)</i> '%s'.<br>\n"%(field_name, chs[1]))
    return (1, "")       

    
def my_format_string(string):
    for _replace in replaces:
        string = string.replace(_replace[0], _replace[1])
    string = string.replace('&lt;i&gt;', '<i>')
    string = string.replace('&lt;I&gt;', '<i>')
    string = string.replace('&lt;/i&gt;', '</i>')
    string = string.replace('&lt;/I&gt;', '</i>')
    string = string.replace('&lt;b&gt;', '<b>')
    string = string.replace('&lt;B&gt;', '<b>')
    string = string.replace('&lt;/b&gt;', '</b>')
    string = string.replace('&lt;/B&gt;', '</b>')
    string = string.replace('&lt;u&gt;', '<u>')
    string = string.replace('&lt;U&gt;', '<u>')
    string = string.replace('&lt;/u&gt;', '</u>')
    string = string.replace('&lt;/U&gt;', '</u>')
    return string  


def make_select_input(item_name, caption, help, _dict, default, value):
    s = ""
    s += "<b>"+caption+"</b><br>\n"
    if not help is None and help != "":
        s += help + "<br>\n"
    if value is None or value == "" or not value in _dict:
        value = default    
    s += "<SELECT name=\""+item_name+"\">\n"
    for _value in _dict:
        s += "<OPTION value=\""+_value+"\""
        if value == _value:
            s += " SELECTED"
        s += ">"+_value+"</OPTION>\n"
    s += "</SELECT><br>\n"
    return s
    

def make_radios_input(item_name, _dict, _captions, value):
    s = ""
    for i in range(0, len(_dict)):
        s += "<INPUT type=\"radio\" name=\"" + item_name + "\" value=\"" + _dict[i] + "\""
        if value == _dict[i]:
            s += " CHECKED"
        s += ">" + _captions[i] + "<br>\n"
    return s  
      

def make_checkbox_input(item_name, checked_value, caption, value):
    s = ""
    s += "<INPUT type=\"checkbox\" name=\"" + item_name + "\" value=\"" + checked_value + "\""
    if value == checked_value:
        s += " CHECKED"
    s += ">" + caption + "<br>\n"
    return s  


def make_text(caption, value):
    s = ""
    s += "<b>"+caption+"</b><br>\n"
    if value:
        s += str(value)
    s += "<br><br>\n"    
    return s  

  
def make_text_input(item_name, caption, help, maxlength, value, size = 50):
    s = ""
    s += "<b>"+caption+"</b><br>\n"
    if not help is None and help != "":
        s += help + "<br>\n"
    if value is None:
        value = ""    
    s += "<INPUT type=\"text\" name=\""+item_name+"\" maxlength=\""+str(maxlength)+"\" size=\""+str(size)+"\" value=\""+value+"\"><br>\n"
    return s  


def make_area_input(item_name, caption, help, cols, rows, value):
    s = ""
    s += "<b>"+caption+"</b><br>\n"
    if not help is None and help != "":
        s += help + "<br>\n"    
    s += "<TEXTAREA name=\""+item_name+"\" cols=\""+str(cols)+"\" rows=\""+str(rows)+"\">\n"
    s += value
    s += "</TEXTAREA><br>\n"    
    return s

def end_table():
    s = ""
    s += "    <TR>\n"
    s += "      <TD colspan=\"2\" height=\"40px\">\n"
    s += "\n"
    s += "      </TD>\n"
    s += "    </TR>\n"
    s += "</TABLE>\n"
    return s  

 
def begin_captioned_table(cpt1, cpt2, cpt3):
    s = ""
    s += "<TABLE width=\"70%\">\n"
    s += "    <TR>\n"
    s += "      <TD class=\"header_caption\" align=\"left\">\n"
    s += cpt1+"\n"
    s += "      </TD>\n"
    s += "    </TR>\n"
    # subtitle
    s += "    <TR>\n"
    s += "      <TD class=\"header_subtitle\" align=\"left\">\n"
    s += cpt2+"\n"
    s += "      </TD>\n"
    s += "    </TR>\n"
    # subnote
    if cpt3:
        s += "    <TR>\n"
        s += "      <TD class=\"header_note\" align=\"left\">\n"
        s += cpt3+"\n"
        s += "      </TD>\n"
        s += "    </TR>\n"
    return s


def conference_main_page(si, c):
    s = ""
    
    s += begin_captioned_table(c.conference_name, c.conference_subtitle, c.conference_note)
    # obrazek
    s += "<TABLE>\n"
    s += "    <TR>\n"
    s += "      <TD width=\"600\">\n"
    s += "        <IMG class=\"header_image\" src=\"images/"+c.conference+".jpg\">\n"
    s += "      </TD>\n"
    # menu
    s += "      <TD class=\"header_menu\" width=\"100%\" valign=\"top\">\n"
    for _item in c.xml_def:
        if _item.attrib["caption"]:
            s += "<a class=\"header_menu_item\" href=\""+make_command(si.page_script, si.page, c.conference, {}, _item.attrib["short"])+"\">"+_item.attrib["caption"]+"</a><br>\n"
        else:
            # items with empty caption are not shown
            pass
    s += "      </TD>\n"
    s += "    </TR>\n"
    # separator
    s += "    <TR>\n"
    s += "      <TD colspan=\"2\">\n"
    s += "&nbsp;\n"             
    s += "      </TD>\n"
    s += "    </TR>\n"
    # body
    for _item in c.xml_def:
        if _item.attrib["caption"]:
            s += "    <TR>\n"
            s += "      <TD class=\"body_item\" colspan=\"2\">\n"
            s += "        <TABLE width=\"70%\">\n"
            s += "           <TR><TD class=\"caption\">\n"
            s += "<a name=\""+_item.attrib["short"]+"\"></a>"+_item.attrib["caption"]+"\n"
            s += "           </TD></TR>\n"
            s += "           <TR><TD class=\"text\">\n"
            if not _item.text is None:
                s += _item.text.replace("###reg_page###", make_command(si.page_script, "register", c.conference, {}))
            s += "\n"
            s += "           </TD></TR>\n"
            s += "         </TABLE>\n"
            
            s += "      </TD>\n"
            s += "    </TR>\n"
        else:
            # items with empty caption are not shown
            pass
    s += "</TABLE>\n"
    s += end_table();
    return s

def payment_dump_page(si, c):
    if si._GET.has_key("ids"):
        bez_ids = si._GET["ids"][0]
    else:
        bez_ids = ''
    if not bez_ids:
        bez_ids = '0'
    regs = si.dbhandler.do_sql_cmd_dict("SELECT registration_number, registration_password, family_name, first_name, title, insitution, department, street, zip, city, country, phone, fax, email, position, employer, registration_type FROM registrations WHERE conference_id = " + str(c.conference_id) + " AND NOT registration_number IN (" + bez_ids + ") ORDER BY id")
    s = begin_captioned_table("Payment dump", c.conference_name, "")
    s += "<TR><TD>\n"
    for line in regs:
        for _key in line.keys():
            if not line[_key]:
                line[_key] = ""

        s += "INSERT INTO bio_users (user_active, payment_state_id, login, password, last_name, first_name, title, insitution, department, street, zip, city, country, phone, fax, email, position, employer, registration_type) VALUES (1, 1, "
        s += "'" + str(line["registration_number"]).replace("'", "''") + "', "
        s += "'" + str(line["registration_password"]).replace("'", "''") + "', "
        s += "'" + str(line["family_name"]).replace("'", "''") + "', "
        s += "'" + str(line["first_name"]).replace("'", "''") + "', "
        s += "'" + str(line["title"]).replace("'", "''") + "', "
        s += "'" + str(line["insitution"]).replace("'", "''") + "', "
        s += "'" + str(line["department"]).replace("'", "''") + "', "
        s += "'" + str(line["street"]).replace("'", "''") + "', "
        s += "'" + str(line["zip"]).replace("'", "''") + "', "
        s += "'" + str(line["city"]).replace("'", "''") + "', "
        s += "'" + str(line["country"]).replace("'", "''") + "', "
        s += "'" + str(line["phone"]).replace("'", "''") + "', "
        s += "'" + str(line["fax"]).replace("'", "''") + "', "
        s += "'" + str(line["email"]).replace("'", "''") + "', "
        s += "'" + str(line["position"]).replace("'", "''") + "', "
        s += "'" + str(line["employer"]).replace("'", "''") + "', "
        s += "'" + str(line["registration_type"]).replace("'", "''") + "');"
        s += "<BR><BR>\n";
    s += "</TD></TR>\n"
    return s

    
    
def list_page(si, c):
    if si._GET.has_key("delete"):
        try:
            si.dbhandler.do_sql_cmd("DELETE FROM registrations WHERE registration_number = '" + si._GET["delete"][0]+ "'")
        except:
            pass      
    regs = si.dbhandler.do_sql_cmd_dict("SELECT registration_number, registration_password, registration_type, family_name, first_name, title, email, insitution, department, city, country, registration_date, registration_abstract_date, registration_details, abstract, position FROM registrations WHERE conference_id = " + str(c.conference_id) + " ORDER BY family_name")
    s = begin_captioned_table("List of registered", c.conference_name, "")
    s += "<TABLE cellspacing=\"0\">\n"
    s += "<TR class=\"header_menu_item\">\n"
    s += "<TD class=\"list_table_header\"></TD>\n"
    s += "<TD class=\"list_table_header\"></TD>\n"
    s += "<TD class=\"list_table_header\"><nobr>Reg.number</nobr></TD>\n"
    s += "<TD class=\"list_table_header\"><nobr>Reg.pwd</nobr></TD>\n"
    s += "<TD class=\"list_table_header\"><nobr>Reg.type</nobr></TD>\n"
    s += "<TD class=\"list_table_header\"><nobr>Name</nobr></TD>\n"
    s += "<TD class=\"list_table_header\"><nobr>Email</nobr></TD>\n"
    s += "<TD class=\"list_table_header\"><nobr>Position</nobr></TD>\n"
    s += "<TD class=\"list_table_header\"><nobr>Insitution</nobr></TD>\n"
    s += "<TD class=\"list_table_header\"><nobr>Department</nobr></TD>\n"
    s += "<TD class=\"list_table_header\"><nobr>City</nobr></TD>\n"
    s += "<TD class=\"list_table_header\"><nobr>Country</nobr></TD>\n"
    s += "<TD class=\"list_table_header\"><nobr>Reg.date</nobr></TD>\n"
    s += "<TD class=\"list_table_header\"><nobr>Abstract.date</nobr></TD>\n"
    s += "<TD class=\"list_table_header\"><nobr>Reg.details</nobr></TD>\n"
    s += "<TD class=\"list_table_header\"><nobr>Abstract (25 chars.)</nobr></TD>\n"
    s += "</TR>\n"  
    for line in regs:
        for _key in line.keys():
            if not line[_key]:
                line[_key] = ""
        s += "<TR>\n"
        s += "<TD class=\"list_table\"><center><a class=\"header_menu_item\" href=\""+make_command(si.page_script, "list", c.conference, {"delete": str(line["registration_number"]), "password": si._GET["password"][0]}).replace("&", "&amp;")+"\" onclick=\"return confirm('Do you realy want to delete this registration?');\">Delete</a></nobr></center></TD>\n"
        s += "<TD class=\"list_table\"><center><a class=\"header_menu_item\" href=\""+make_command(si.page_script, "registration_form", c.conference, {"reg_number": str(line["registration_number"]), "reg_password": str(line["registration_password"])}).replace("&", "&amp;")+"\">Edit</a></nobr></center></TD>\n"
        s += "<TD class=\"list_table\"><center><a class=\"header_menu_item\" href=\""+make_command(si.page_script, "view_registration", c.conference, {"reg_number": str(line["registration_number"]), "reg_password": str(line["registration_password"])}).replace("&", "&amp;")+"\">" + str(line["registration_number"]) + "</a></nobr></center></TD>\n"
        s += "<TD class=\"list_table\"><nobr>" + str(line["registration_password"]) + "</nobr></TD>\n"
        s += "<TD class=\"list_table\"><nobr>" + str(line["registration_type"]) + "</nobr></TD>\n"
        s += "<TD class=\"list_table\"><nobr>" + str(line["title"]) + " " + str(line["family_name"]) + " " + str(line["first_name"]) + "</nobr></TD>\n"
        s += "<TD class=\"list_table\"><nobr>" + str(line["email"]) + "</nobr></TD>\n"
        s += "<TD class=\"list_table\"><nobr>" + str(line["position"]) + "</nobr></TD>\n"
        s += "<TD class=\"list_table\"><nobr>" + str(line["insitution"]) + "</nobr></TD>\n"
        s += "<TD class=\"list_table\"><nobr>" + str(line["department"]) + "</nobr></TD>\n"
        s += "<TD class=\"list_table\"><nobr>" + str(line["city"]) + "</nobr></TD>\n"
        s += "<TD class=\"list_table\"><nobr>" + str(line["country"]) + "</nobr></TD>\n"
        s += "<TD class=\"list_table\"><nobr>" + str(line["registration_date"]) + "</nobr></TD>\n"
        s += "<TD class=\"list_table\"><nobr>" + str(line["registration_abstract_date"]) + "</nobr></TD>\n"
        s += "<TD class=\"list_table\"><nobr>" + str(line["registration_details"]) + "</nobr></TD>\n"
        s += "<TD class=\"list_table\"><nobr>" + str(line["abstract"])[:25] + "</nobr></TD>\n"
        s += "</TR>\n"  
    s += "</TABLE>"
    return s

def title_list_page(si, c):
    s = begin_captioned_table("Presentation title list of registered", c.conference_name, "")
    s += "<TR><TD>\n"
    regs = si.dbhandler.do_sql_cmd_dict("SELECT family_name, first_name, author_list, presentation_title FROM registrations WHERE contribution = 'Poster' AND conference_id = " + str(c.conference_id) + " ORDER BY family_name")
    s += "<h3>Poster</h3>\n"
    s += "<TABLE cellspacing=\"0\">\n"
    s += "<TR class=\"header_menu_item\">\n"
    s += "<TD class=\"list_table_header\"><nobr>Name</nobr></TD>\n"
    s += "<TD class=\"list_table_header\"><nobr>Autor List</nobr></TD>\n"
    s += "<TD class=\"list_table_header\"><nobr>Presentation title</nobr></TD>\n"
    s += "</TR>\n"  
    for line in regs:
        for _key in line.keys():
            if not line[_key]:
                line[_key] = ""
        s += "<TR>\n"
        s += "<TD class=\"list_table\"><nobr>" + str(line["family_name"]) + " " + str(line["first_name"]) + "</nobr></TD>\n"
        s += "<TD class=\"list_table\"><nobr>" + str(line["author_list"]) + "</nobr></TD>\n"
        s += "<TD class=\"list_table\"><nobr>" + str(line["presentation_title"]) + "</nobr></TD>\n"
        s += "</TR>\n"  
    s += "</TABLE>"
    regs = si.dbhandler.do_sql_cmd_dict("SELECT family_name, first_name, author_list, presentation_title FROM registrations WHERE contribution = 'Poster, would like to give an Oral Presentation' AND conference_id = " + str(c.conference_id) + " ORDER BY family_name")
    s += "<h3>Poster, would like to give an Oral Presentation</h3>\n"
    s += "<TABLE cellspacing=\"0\">\n"
    s += "<TR class=\"header_menu_item\">\n"
    s += "<TD class=\"list_table_header\"><nobr>Name</nobr></TD>\n"
    s += "<TD class=\"list_table_header\"><nobr>Autor List</nobr></TD>\n"
    s += "<TD class=\"list_table_header\"><nobr>Presentation title</nobr></TD>\n"
    s += "</TR>\n"  
    for line in regs:
        for _key in line.keys():
            if not line[_key]:
                line[_key] = ""
        s += "<TR>\n"
        s += "<TD class=\"list_table\"><nobr>" + str(line["family_name"]) + " " + str(line["first_name"]) + "</nobr></TD>\n"
        s += "<TD class=\"list_table\"><nobr>" + str(line["author_list"]) + "</nobr></TD>\n"
        s += "<TD class=\"list_table\"><nobr>" + str(line["presentation_title"]) + "</nobr></TD>\n"
        s += "</TR>\n"  
    s += "</TABLE>"
    regs = si.dbhandler.do_sql_cmd_dict("SELECT family_name, first_name, author_list, presentation_title FROM registrations WHERE contribution = 'None' AND conference_id = " + str(c.conference_id) + " ORDER BY family_name")
    s += "<h3>None</h3>\n"
    s += "<TABLE cellspacing=\"0\">\n"
    s += "<TR class=\"header_menu_item\">\n"
    s += "<TD class=\"list_table_header\"><nobr>Name</nobr></TD>\n"
    s += "<TD class=\"list_table_header\"><nobr>Autor List</nobr></TD>\n"
    s += "<TD class=\"list_table_header\"><nobr>Presentation title</nobr></TD>\n"
    s += "</TR>\n"  
    for line in regs:
        for _key in line.keys():
            if not line[_key]:
                line[_key] = ""
        s += "<TR>\n"
        s += "<TD class=\"list_table\"><nobr>" + str(line["family_name"]) + " " + str(line["first_name"]) + "</nobr></TD>\n"
        s += "<TD class=\"list_table\"><nobr>" + str(line["author_list"]) + "</nobr></TD>\n"
        s += "<TD class=\"list_table\"><nobr>" + str(line["presentation_title"]) + "</nobr></TD>\n"
        s += "</TR>\n"  
    s += "</TABLE>"
    s += "</TD></TR>\n"
    return s

def email_list_page(si, c):
    s = begin_captioned_table("List of emails", c.conference_name, "")
    s += "<TABLE cellspacing=\"0\">\n"
    s += "<TR><TD>\n"
    s += "<h3>Poster</h3>\n"
    regs = si.dbhandler.do_sql_cmd_dict("SELECT family_name, first_name, title, email FROM registrations WHERE contribution = 'Poster' AND conference_id = " + str(c.conference_id))
    for line in regs:
        for _key in line.keys():
            if not line[_key]:
                line[_key] = ""
        s += (str(line["family_name"]) + " " + str(line["first_name"])).strip()
        s += " &lt;" + str(line["email"]) + "&gt;;"
    s += "<h3>Poster, would like to give an Oral Presentation</h3>\n"
    regs = si.dbhandler.do_sql_cmd_dict("SELECT family_name, first_name, title, email FROM registrations WHERE contribution = 'Poster, would like to give an Oral Presentation' AND conference_id = " + str(c.conference_id))
    for line in regs:
        for _key in line.keys():
            if not line[_key]:
                line[_key] = ""
        s += (str(line["family_name"]) + " " + str(line["first_name"])).strip()
        s += " &lt;" + str(line["email"]) + "&gt;;"
    s += "<h3>None</h3>\n"
    regs = si.dbhandler.do_sql_cmd_dict("SELECT family_name, first_name, title, email FROM registrations WHERE contribution = 'None' AND conference_id = " + str(c.conference_id))
    for line in regs:
        for _key in line.keys():
            if not line[_key]:
                line[_key] = ""
        s += (str(line["family_name"]) + " " + str(line["first_name"])).strip()
        s += " &lt;" + str(line["email"]) + "&gt;;"
    s += "</TD></TR>\n"  
    s += "</TABLE>"
    return s

def abstract_list_page(si, c):
    regs = si.dbhandler.do_sql_cmd_dict("SELECT registration_number, registration_password, title, family_name, first_name, insitution, position, email, gender, roommate, registration_details, contribution, presentation_title, contribution, author_list, author_emails, abstract FROM registrations WHERE conference_id = " + str(c.conference_id) + " ORDER BY family_name")
    s = begin_captioned_table("List of registered", c.conference_name, "")
    s += "<TABLE cellspacing=\"0\">\n"
    s += "<TR><TD>\n"
    for line in regs:
        for _key in line.keys():
            if not line[_key]:
                line[_key] = ""
        s += "<b>Reg.number:</b> <a class=\"header_menu_item\" href=\""+make_command(si.page_script, "view_registration", c.conference, {"reg_number": str(line["registration_number"]), "reg_password": str(line["registration_password"])}).replace("&", "&amp;")+"\">" + str(line["registration_number"]) + "</a><br />\n"
        s += "<b>Name:</b> " + str(line["title"]) + " " + str(line["family_name"]) + " " + str(line["first_name"]) + "<br />\n"
        s += "<b>Institution:</b> " + str(line["insitution"]) + "<br />\n"
        s += "<b>Position:</b> " + str(line["position"]) + "<br />\n"
        s += "<b>Email:</b> <a href=\"mailto:" + str(line["email"]) + "\">" + str(line["email"]) + "</a><br />\n"
        s += "<b>Gender:</b> " + str(line["gender"]) + "<br />\n"
        s += "<b>Prefer to sleep with:</b> " + str(line["roommate"]) + "<br />\n"
        s += "<b>Registration details:</b> " + str(line["registration_details"]) + "<br /><br />\n"
        s += "<b>Contribution:</b> " + str(line["contribution"]) + "<br />\n"
        s += "<b>Presentation title:</b> " + str(line["presentation_title"]) + "<br />\n"
        s += "<b>Authors List:</b><br /> " + str(line["author_list"]) + "<br />\n"
        s += "<b>Correspondence adresses:</b><br /> " + str(line["author_emails"]) + "<br />\n"
        s += "<b>Abstract:</b><br /> " + str(line["abstract"]) + "<br /><br /><br /><hr />\n"
    s += "</TD></TR>\n"  
    s += "</TABLE>"
    return s

def abstract_list2_page(si, c):
    regs = si.dbhandler.do_sql_cmd_dict("SELECT registration_number, registration_password, title, family_name, first_name, insitution, position, email, gender, roommate, registration_details, contribution, presentation_title, contribution, author_list, author_emails, abstract FROM registrations WHERE conference_id = " + str(c.conference_id) + " ORDER BY family_name")
    s = begin_captioned_table("List of registered", c.conference_name, "")
    s += "<TABLE cellspacing=\"0\">\n"
    s += "<TR><TD>\n"
    for line in regs:
        for _key in line.keys():
            if not line[_key]:
                line[_key] = ""
        s += "<b>Contribution:</b> " + str(line["contribution"]) + "<br />\n"
        s += "<b>Presentation title:</b> " + str(line["presentation_title"]) + "<br />\n"
        s += "<b>Authors List:</b><br /> " + str(line["author_list"]) + "<br />\n"
        s += "<b>Correspondence adresses:</b><br /> " + str(line["author_emails"]) + "<br />\n"
        s += "<b>Abstract:</b><br /> " + str(line["abstract"]) + "<br /><br /><br /><hr />\n"
    s += "</TD></TR>\n"  
    s += "</TABLE>"
    return s



def register_page(si, c):
    s = ""        
    s += begin_captioned_table("Registration", c.conference_name, c.conference_note)
    s += "<TR><TD class=\"text\">\n"    
    s += "Welcome to the electronic registration interface to <i>"+c.conference_name+"</i>.<br><br>\n"
    s += "<il style=\"padding: 0px 0px 0px 0px;\">\n"
    if str(datetime.date.today())  <= c.conference_deadline:
          s += "<li>If you want to register for the meeting please follow this <a href=\""+make_command(si.page_script, "registration_form", c.conference, {})+"\">link</a> (new registrations are possible until "+c.conference_deadline+" MET.)<br><br><br>\n"
    s += "<li>If you already registered for the meeting please:\n"
    s += "<form id=\"form\" method=\"GET\" action=\""+si.page_script+"\">\n"
    s += "<input type=\"hidden\" name=\"conference\" value=\""+c.conference+"\">\n" 
    s += "<input type=\"hidden\" name=\"reg_action\" value=\"change\">\n" 
    s += "<ol style=\"padding: 0px 0px 0px 0px;\">"
    s += "<li>enter your registration number &nbsp;&nbsp;&nbsp;<input id=\"number\" type=\"text\" name=\"reg_number\">\n"
    s += "<li>enter your registration password <input id=\"password\" type=\"password\" name=\"reg_password\">\n"
    s += "<li>select an action regarding your registration:<br>\n"
    if str(datetime.date.today())  <= c.conference_deadline: 
        s += "<input type=\"radio\" name=\"page\" value=\"registration_form\">change the registration data. (Note: Changes are possible until "+c.conference_deadline+" MET)<br>"
        s += "<input type=\"radio\" name=\"page\" value=\"accomodation_form\">change the acomodation data. (Note: Changes are possible until "+c.conference_deadline+" MET)<br>"
    s += "<input type=\"radio\" name=\"page\" value=\"abstract\" checked=\"1\">show rtf version of the abstract. The rtf (rich text format) formatted text can e.g. be used by MS-Word."
    s += "<li>and press <input type=\"submit\" value=\"Go\" onClick=\"if (form.number.value=='') { alert('Please enter registration number'); return false; } if (form.password.value=='') { alert('Please enter registration password'); return false; } return true;\"><br>\n"
    s += "</ol>\n"
    s += "</form>\n"
    s += "</il>\n"
    s += "<br><br><br><br>\n"
    s += "If you need an assistance please contact <a href=\"mailto:martin@natur.cuni.cz\">martin@natur.cuni.cz</a>\n"
    s += "</TD></TR>\n"
    s += end_table()
    return s
    

def form_register(si, c, _data, errors):
    s = ""
    s += begin_captioned_table("Registration", c.conference_name, "")
    s += "<TR><TD class=\"text\">\n"    
    # print out errors
    if errors:
        s += "<div class=\"errors\">\n"
        s += "<b>There has been found following error(s):</b><br>\n"
        s += errors
        s += "</div><br>\n"
    # registration form
    s += "Please use <i>only normal characters</i>, numbers and brackets in all input fields (<i>no</i> 'special' characters, <i>no</i> TABs). Please do <u>not</u> use all CAPITAL in names, titles,...<br>\n"
    s += "Hints to insert special characters are located at the <a href=\"#specchars\">end</a> of this document.<br><br>\n"
    s += "<FORM method=\"POST\" action=\"" + make_command(si.page_script, "registration_form", c.conference, {}) + "\">\n"
    s += "<INPUT type=\"hidden\" name=\"form_name\" value=\"form_registration\">\n"
    s += "<INPUT type=\"hidden\" name=\"registration_number\" value=\""+str(_data["registration_number"])+"\">\n"
    s += make_text_input("family_name", "Family Name", "Please use no more than 250 characters.", 250, _data["family_name"])
    s += make_text_input("first_name", "First Name", "Please use no more than 250 characters.", 250, _data["first_name"])
    s += make_text_input("title", "Title", "Please use no more than 50 characters.", 50, _data["title"])
    s += make_select_input("gender", "Gender", "", ('male', 'female', 'not selected'), 'not selected', _data["gender"]) 
    s += make_text_input("date_of_birth", "Birth date", "(yyyy-mm-dd Optional field for statistical purposes)", 10, _data["date_of_birth"])
    s += make_text_input("insitution", "Name of Institution", "Please use no more than 250 characters.", 250, _data["insitution"]) 
    s += make_text_input("department", "Department", "Please use no more than 250 characters.", 250, _data["department"]) 
    s += make_text_input("street", "Street", "Please use no more than 250 characters.", 250, _data["street"]) 
    s += make_text_input("zip", "Postal code", "Please use no more than 20 characters.", 20, _data["zip"]) 
    s += make_text_input("city", "City", "Please use no more than 250 characters.", 250, _data["city"])
    s += make_select_input("country", "Country", "", ('Afghanistan', 'Albania', 'Algeria', 'Andorra', 'Angola', 'Antigua and Barbuda', 'Argentina', 'Armenia', 'Australia', 'Austria', 'Azerbaijan', 'Bahamas', 'Bahrain', 'Bangladesh', 'Barbados', 'Belarus', 'Belgium', 'Belize', 'Benin', 'Bhutan', 'Bolivia', 'Bosnia and Herzegovina', 'Botswana', 'Brazil', 'Brunei', 'Bulgaria', 'Burkina Faso', 'Burundi', 'Cambodia', 'Cameroon', 'Canada', 'Cape Verde', 'Central African Republic', 'Chad', 'Chile', 'Columbia', 'Comoros', 'Congo', 'Costa Rica', 'Croatia', 'Cuba', 'Cyprus', 'Czech Republic', "C\xf4te d'Ivoire", 'D.R. Congo', 'Denmark', 'Djibouti', 'Dominica', 'Dominican Republic', 'Ecuador', 'Egypt', 'El Salvador', 'Eq. Guinea', 'Eritrea', 'Estonia', 'Fiji', 'Finland', 'France', 'Gabon', 'Gambia', 'Georgia', 'Germany', 'Ghana', 'Greece', 'Grenada', 'Guatemala', 'Guinea', 'Guinea-Bissau', 'Guyana', 'Haiti', 'Honduras', 'Hungary', 'Iceland', 'India', 'Indonesia', 'Iran', 'Iraq', 'Ireland', 'Israel', 'Italy', 'Jamaica', 'Japan', 'Jordania', 'Kazakhstan', 'Kenya', 'Kiribati', 'Korea, North', 'Korea, South', 'Kuwait', 'Kyrgyzstan', 'Laos', 'Latvia', 'Lebanon', 'Lesotho', 'Liberia', 'Liechtenstein', 'Lithuania', 'Luxembourg', 'Lybia', 'Macedonia', 'Madagascar', 'Malawi', 'Malaysia', 'Maldives', 'Mali', 'Malta', 'Marshall Islands', 'Mauritania', 'Mauritius', 'Mexico', 'Micronesia', 'Moldova', 'Monaco', 'MongoliaMorocco', 'Mozambique', 'Myanmar', 'Namibia', 'Nauru', 'Nepal', 'New Zealand', 'Nicaragua', 'Niger', 'Nigeria', 'Norway', 'Oman', 'PR China', 'Pakistan', 'Palau', 'Panama', 'Papua New Guinea', 'Paraguay', 'Peru', 'Philippines', 'Poland', 'Portugal', 'Qatar', 'Romania', 'Russian Federation', 'Rwanda', 'Samoa', 'San Marino', 'Sao Tome & Principe', 'Saudi Arabia', 'Senegal', 'Serbia and Montenegro', 'Seychelles', 'Sierra Leone', 'Singapore', 'Slovakia', 'Slovenia', 'Solomon Islands', 'Somalia', 'South Africa', 'Spain', 'Sri Lanka', 'St Kitts and Nevis', 'St Lucia', 'St Vincent', 'Sudan', 'Suriname', 'Swaziland', 'Sweden', 'Switzerland', 'Syria', 'Taiwan', 'Tajikistan', 'Tanzania', 'Thailand', 'The Netherlands', 'Timor-Leste', 'Togo', 'Tonga', 'Trinidad & Tobago', 'Tunisia', 'TurkeyTurkmenistan', 'Tuvalu', 'Uganda', 'Ukraine', 'United Arab Emirates', 'United Kingdom', 'United States', 'Uruguay', 'Uzbekistan', 'Vanuatu', 'Venezuela', 'Vietnam', 'Yemen', 'Zambia', 'Zimbabwe', 'Other', 'please select'), 'please select', _data["country"])
    s += make_select_input("nationality", "Nationality", "", ('Afghanistan', 'Albania', 'Algeria', 'Andorra', 'Angola', 'Antigua and Barbuda', 'Argentina', 'Armenia', 'Australia', 'Austria', 'Azerbaijan', 'Bahamas', 'Bahrain', 'Bangladesh', 'Barbados', 'Belarus', 'Belgium', 'Belize', 'Benin', 'Bhutan', 'Bolivia', 'Bosnia and Herzegovina', 'Botswana', 'Brazil', 'Brunei', 'Bulgaria', 'Burkina Faso', 'Burundi', 'Cambodia', 'Cameroon', 'Canada', 'Cape Verde', 'Central African Republic', 'Chad', 'Chile', 'Columbia', 'Comoros', 'Congo', 'Costa Rica', 'Croatia', 'Cuba', 'Cyprus', 'Czech Republic', "C\xf4te d'Ivoire", 'D.R. Congo', 'Denmark', 'Djibouti', 'Dominica', 'Dominican Republic', 'Ecuador', 'Egypt', 'El Salvador', 'Eq. Guinea', 'Eritrea', 'Estonia', 'Fiji', 'Finland', 'France', 'Gabon', 'Gambia', 'Georgia', 'Germany', 'Ghana', 'Greece', 'Grenada', 'Guatemala', 'Guinea', 'Guinea-Bissau', 'Guyana', 'Haiti', 'Honduras', 'Hungary', 'Iceland', 'India', 'Indonesia', 'Iran', 'Iraq', 'Ireland', 'Israel', 'Italy', 'Jamaica', 'Japan', 'Jordania', 'Kazakhstan', 'Kenya', 'Kiribati', 'Korea, North', 'Korea, South', 'Kuwait', 'Kyrgyzstan', 'Laos', 'Latvia', 'Lebanon', 'Lesotho', 'Liberia', 'Liechtenstein', 'Lithuania', 'Luxembourg', 'Lybia', 'Macedonia', 'Madagascar', 'Malawi', 'Malaysia', 'Maldives', 'Mali', 'Malta', 'Marshall Islands', 'Mauritania', 'Mauritius', 'Mexico', 'Micronesia', 'Moldova', 'Monaco', 'MongoliaMorocco', 'Mozambique', 'Myanmar', 'Namibia', 'Nauru', 'Nepal', 'New Zealand', 'Nicaragua', 'Niger', 'Nigeria', 'Norway', 'Oman', 'PR China', 'Pakistan', 'Palau', 'Panama', 'Papua New Guinea', 'Paraguay', 'Peru', 'Philippines', 'Poland', 'Portugal', 'Qatar', 'Romania', 'Russian Federation', 'Rwanda', 'Samoa', 'San Marino', 'Sao Tome & Principe', 'Saudi Arabia', 'Senegal', 'Serbia and Montenegro', 'Seychelles', 'Sierra Leone', 'Singapore', 'Slovakia', 'Slovenia', 'Solomon Islands', 'Somalia', 'South Africa', 'Spain', 'Sri Lanka', 'St Kitts and Nevis', 'St Lucia', 'St Vincent', 'Sudan', 'Suriname', 'Swaziland', 'Sweden', 'Switzerland', 'Syria', 'Taiwan', 'Tajikistan', 'Tanzania', 'Thailand', 'The Netherlands', 'Timor-Leste', 'Togo', 'Tonga', 'Trinidad & Tobago', 'Tunisia', 'TurkeyTurkmenistan', 'Tuvalu', 'Uganda', 'Ukraine', 'United Arab Emirates', 'United Kingdom', 'United States', 'Uruguay', 'Uzbekistan', 'Vanuatu', 'Venezuela', 'Vietnam', 'Yemen', 'Zambia', 'Zimbabwe', 'Other', 'please select'), 'please select', _data["nationality"]) 
    s += make_text_input("phone", "Telephone No", "e.g. +420 221 951 710", 50, _data["phone"])
    s += make_text_input("fax", "FAX No", "e.g. +420 221 951 724", 50, _data["fax"])
    s += make_text_input("email", "Email address", "A copy of your registration will be sent to this address.", 250, _data["email"])
    s += make_select_input("position", "Current Position", "", ('PhD Student', 'Post Doc', 'Principal Investigator', 'Other'), 'Other', _data["position"]) 
    s += make_select_input("employer", "Employer", "", ('Industry', 'Institute', 'University', 'Other', 'not selected'), 'not selected', _data["employer"])
    s += make_select_input("source", "How did you learn about the meeting", "", ('Poster', 'Newspaper advertisement', 'RNAClub Website', 'from a colleague', 'other', 'not selected'), 'not selected', _data["source"])
    s += make_select_input("contribution", "Contribution", "", ('Poster', 'Poster, would like to give an Oral Presentation', 'None', 'please select'), 'please select', _data["contribution"])   
    s += make_text_input("presentation_title", "Presentation title", "Please use no more than 250 characters.", 250, _data["presentation_title"])
    s += make_area_input("author_list", "Authors List", "Please use no more than 300 characters.<br>Please use <i>lastname</i> initial and separate authors with ,(Comma). E.g. Reunis L.<br>In case of multiple addresses please use a (1). (2), after the initial to refer to the addresses (see box underneath).", 80, 6, _data["author_list"])
    s += make_area_input("author_emails", "Correspondence for each author (Mailing address)", "Please use no more than 500 characters.", 80, 6, _data["author_emails"])
    s += make_area_input("abstract", "Abstract", "Please use no more than 2000 characters.", 80, 15, _data["abstract"])
    s += make_select_input("registration_type", "Registration Type", "", ('Regular participant', 'Student', 'please select'), 'please select', _data["registration_type"])
    s += "<b>Registration details</b><br>\n"
    s += "I prefer:<br>\n"
    # raise RuntimeError, c.registration_details
    for _key in c.registration_details:
        if len(c.registration_details[_key]) == 1:
            # check box
            if c.registration_details[_key][0][0] in _data["registration_details"]: 
                _value = c.registration_details[_key][0][0]
            else:
                _value = ""
            s += make_checkbox_input("registration_details.x" + str(_key), c.registration_details[_key][0][0], c.registration_details[_key][0][1], _value)
        else:
            # radios
            _value = ""
            _dict = []
            _captions = []
            for _d in c.registration_details[_key]:
                _dict.append(_d[0])
                _captions.append(_d[1])
                if _d[0] in _data["registration_details"]: 
                    _value = _d[0]
                else:
                    pass
            s += make_radios_input("registration_details.x" + str(_key), _dict, _captions, _value)
        s += "<br>\n"
    s += make_text_input("registration_password", "Registration password", "For additional changes in your registration. Please use no more than 20 characters.", 20, _data["registration_password"])
    s += "<br>\n"
    if not _data["registration_number"]:
        s += "<INPUT type=\"submit\" value=\"Submit the registration\"><br>\n"    
    else:
        s += "<INPUT type=\"submit\" value=\"Change the registration\"><br>\n"
    s += "</FORM><br>\n"
    s += "<font color=\"red\">NOTE:</font>The system will send a confirmation email immediately after receiving a valid registration to the email address you provided. If you do NOT receive this confirmation email containing the text of your registration: PLEASE contact <a href=\"mailto:martin@natur.cuni.cz\">martin@natur.cuni.cz</a> because in that case something went wrong...<br><br>\n"
    s += "Hint: Clearing the cache of your browser may help if you can not submit.<br>\n"
    s += "<hr><br><br>"
    s += """<a name=\"specchars\"></a>Special characters in your input will be substituted by the following common HTML-style sequences:
<table border>
<tr>
<td>&iexcl; &amp;iexcl; <td>&cent; &amp;cent; <td>&pound; &amp;pound; <td>&curren; &amp;curren;
<td>&yen; &amp;yen; <td>&brvbar; &amp;brvbar; <td>&sect; &amp;sect; <td>&uml; &amp;uml; 
<tr>
<td>&copy; &amp;copy; <td>&ordf; &amp;ordf; <td>&laquo; &amp;laquo; <td>&not; &amp;not; 
<td>&reg; &amp;reg; <td>&macr; &amp;macr; <td>&deg; &amp;deg; <td>&plusmn; &amp;plusmn; 
<tr>
<td>&sup2; &amp;sup2; <td>&sup3; &amp;sup3; <td>&acute; &amp;acute; <td>&micro; &amp;micro; 
<td>&para; &amp;para; <td>&middot; &amp;middot; <td>&cedil; &amp;cedil; <td>&sup1; &amp;sup1; 
<tr>
<td>&ordm; &amp;ordm; <td>&raquo; &amp;raquo; <td>&frac14; &amp;frac14; <td>&frac12; &amp;frac12; 
<td>&frac34; &amp;frac34; <td>&iquest; &amp;iquest; <td>&Agrave; &amp;Agrave; <td>&Aacute; &amp;Aacute; 
<tr>
<td>&Acirc; &amp;Acirc; <td>&Atilde; &amp;Atilde; <td>&Auml; &amp;Auml; <td>&Aring; &amp;Aring;
<td>&AElig; &amp;AElig; <td>&Ccedil; &amp;Ccedil; <td>&Egrave; &amp;Egrave; <td>&Eacute; &amp;Eacute;
<tr>
<td>&Ecirc; &amp;Ecirc; <td>&Euml; &amp;Euml; <td>&Igrave; &amp;Igrave; <td>&Iacute; &amp;Iacute;
<td>&Icirc; &amp;Icirc; <td>&Iuml; &amp;Iuml; <td>&ETH; &amp;ETH; <td>&Ntilde; &amp;Ntilde;
<tr>
<td>&Ograve; &amp;Ograve; <td>&Oacute; &amp;Oacute; <td>&Ocirc; &amp;Ocirc; <td>&Otilde; &amp;Otilde; 
<td>&Ouml; &amp;Ouml; <td>&times; &amp;times; <td>&Oslash; &amp;Oslash; <td>&Ugrave; &amp;Ugrave; 
<tr>
<td>&Uacute; &amp;Uacute; <td>&Ucirc; &amp;Ucirc; <td>&Uuml; &amp;Uuml; <td>&Yacute; &amp;Yacute; 
<td>&THORN; &amp;THORN; <td>&szlig; &amp;szlig; <td>&agrave; &amp;agrave; <td>&aacute; &amp;aacute; 
<tr>
<td>&acirc; &amp;acirc; <td>&atilde; &amp;atilde; <td>&auml; &amp;auml; <td>&aring; &amp;aring; 
<td>&aelig; &amp;aelig; <td>&ccedil; &amp;ccedil; <td>&egrave; &amp;egrave; <td>&eacute; &amp;eacute;
<tr>
<td>&ecirc; &amp;ecirc; <td>&euml; &amp;euml; <td>&igrave; &amp;igrave; <td>&iacute; &amp;iacute;
<td>&icirc; &amp;icirc; <td>&iuml; &amp;iuml; <td>&eth; &amp;eth; <td>&ntilde; &amp;ntilde;
<tr>
<td>&ograve; &amp;ograve; <td>&oacute; &amp;oacute; <td>&ocirc; &amp;ocirc; <td>&otilde; &amp;otilde; 
<td>&ouml; &amp;ouml; <td>&divide; &amp;divide; <td>&oslash; &amp;oslash; <td>&ugrave; &amp;ugrave; 
<tr>
<td>&uacute; &amp;uacute; <td>&ucirc; &amp;ucirc; <td>&uuml; &amp;uuml; <td>&yacute; &amp;yacute; 
<td>&thorn; &amp;thorn; <td>&yuml; &amp;yuml; <td>&lt; &amp;lt; <td>&gt; &amp;gt; 
</table>
If you want to include an ampersand (&amp;) in the text, please use <cite>&amp;amp;</cite> (the system can not do this conversion automatically, because the &amp; is used to denote special characters).<br>In the title and text of the abstract you can also use the non-HTML tags &amp;alpha; ... &amp;omega; and &amp;Alpha; ... &amp;Omega; to 
include greek characters (these can not be displayed here). 
Please note that the &amp; (ampersand) at the beginning and the ; (semicolon) at the end must be used to allow the special characters to be recognized.<br>To write something in <i>italic</i> surround the word with &lt;i&gt; and &lt;/i&gt; (these are the HTML tags for start-of-italic and end-of-italic. Please note that the system will automatically replace your input to the very  unreadable (e.g.) &amp;lt;i&amp;gt;italic&amp;lt;/i&amp;gt; The outcome in the .rtf formatted printout is then the desired <i>italic</i> word.)<br>
Please do not use any other HTML-tags in your submission.<br><br>
A note regarding character count: The application counts each entered character. I.e. SPACE is counted as a character and an &amp;Eacute; counts for 8 characters. Each RETURN counts as four characters (RETURN in HTML is expressed &lt;br&gt;).
""" 
    s += "</TD></TR>\n"
    s += end_table()
    return s
    

def view_register(si, c, _data):
    s = ""
    s += begin_captioned_table("View your registration", c.conference_name, "")
    s += "<TR><TD class=\"text\">\n"    
    # registration data
    s += make_text("Registration Number", _data["registration_number"])
    s += make_text("Family Name", _data["family_name"])
    s += make_text("First Name", _data["first_name"])
    s += make_text("Title", _data["title"])
    s += make_text("Gender", _data["gender"]) 
    s += make_text("Birth date", _data["date_of_birth"])
    s += make_text("Name of Institution", _data["insitution"]) 
    s += make_text("Department", _data["department"]) 
    s += make_text("Street", _data["street"]) 
    s += make_text("Postal code", _data["zip"]) 
    s += make_text("City", _data["city"])
    s += make_text("Country", _data["country"])
    s += make_text("Nationality", _data["nationality"]) 
    s += make_text("Telephone No", _data["phone"])
    s += make_text("FAX No", _data["fax"])
    s += make_text("Email address", _data["email"])
    s += make_text("Current Position", _data["position"]) 
    s += make_text("Employer", _data["employer"])
    s += make_text("How did you learn about the meeting", _data["source"])
    s += make_text("Contribution", _data["contribution"])   
    s += make_text("Presentation title", _data["presentation_title"])
    s += make_text("Authors List", _data["author_list"])
    s += make_text("Correspondence for each author (Mailing address)", _data["author_emails"])
    s += make_text("Abstract", _data["abstract"])
    s += make_text("Registration Type", _data["registration_type"])
    s += make_text("Registration details", _data["registration_details"])
    s += make_text("I would prefer to share my room with", _data["roommate"])
    s += end_table()
    return s

    
def get_register_data(si, c):
    if si._POST.has_key("registration_number") and si._POST.has_key("form_name") and si._POST["form_name"] == "form_registration":
        if si._POST.has_key("registration_details"):
            _registration_details = []
            for _key in si._POST["registration_details"]:
                _registration_details.append(si._POST["registration_details"][_key])
        else: 
            _registration_details = []
        _data = {
          "conference_id": c.conference_id, "registration_number": si._POST["registration_number"],
          "registration_password": si._POST["registration_password"], "family_name": si._POST["family_name"].strip(),
          "first_name": si._POST["first_name"].strip(), "title": si._POST["title"].strip(),  "gender": si._POST["gender"].strip(),
          "date_of_birth": si._POST["date_of_birth"].strip(), "insitution": si._POST["insitution"].strip(),
          "department": si._POST["department"].strip(), "street": si._POST["street"].strip(), "zip": si._POST["zip"].strip(),
          "city": si._POST["city"].strip(), "country": si._POST["country"].strip(), "nationality": si._POST["nationality"].strip(),
          "phone": si._POST["phone"].strip(), "fax": si._POST["fax"].strip(), "email": si._POST["email"].strip(),
          "position": si._POST["position"].strip(), "employer": si._POST["employer"].strip(), "source": si._POST["source"].strip(),
          "contribution": si._POST["contribution"].strip(), "presentation_title": si._POST["presentation_title"].strip(),
          "author_list": si._POST["author_list"].strip(), "author_emails": si._POST["author_emails"].strip(),
          "abstract": si._POST["abstract"].strip(), "registration_type": si._POST["registration_type"].strip(),
          "registration_details": _registration_details,
        }
        _reg_number = _data["registration_number"]
        _posted = 1
    elif si._GET.has_key("reg_number"):
        _data = si.dbhandler.do_sql_cmd_dict("SELECT * FROM registrations WHERE registration_number = '"+si._GET["reg_number"][0].strip()+"'")[0]
        _reg_number = _data["registration_number"]
        if _data["registration_details"]:
            _data["registration_details"] = _data["registration_details"].split(";")
        else: 
            _data["registration_details"] = []   
        _posted = 0
    else:
        _data = {
          "conference_id": "", "registration_number": "", "registration_password": "",
          "family_name": "", "first_name": "", "title": "", "gender": "", "date_of_birth": "",
          "insitution": "", "department": "", "street": "", "zip": "", "city": "",
          "country": "", "nationality": "", "phone": "", "fax": "", "email": "",
          "position": "", "employer": "", "source": "", "contribution": "",
          "presentation_title": "", "author_list": "", "author_emails": "",
          "abstract": "",  "registration_type": "", "registration_details": [],
          "roommate": "",                                   
                }
        _reg_number = None  
        _posted = 0
    return _data, _reg_number, _posted 


def check_register_data(si, c, _data):
    # check data                
    e = ""
    _data_check = check_input(_data["family_name"], ascii_charset, " Family Name")                
    if not _data_check[0]: e += _data_check[1]
    _data_check = check_input(_data["first_name"], ascii_charset, "First Name")                
    if not _data_check[0]: e += _data_check[1]
    _data_check = check_input(_data["title"], ascii_charset, "Title", 0)                
    if not _data_check[0]: e += _data_check[1]
    _data_check = check_input(_data["gender"], ascii_charset, "Gender", 0)                
    if not _data_check[0]: e += _data_check[1]
    _data_check = check_input(_data["date_of_birth"], date_charset, "Birth date", 0)                
    if not _data_check[0]: e += _data_check[1]
    _data_check = check_input(_data["insitution"], ascii_charset, "Name of Institution")                
    if not _data_check[0]: e += _data_check[1]
    _data_check = check_input(_data["department"], ascii_charset, "Department")                
    if not _data_check[0]: e += _data_check[1]
    _data_check = check_input(_data["street"], ascii_charset, "Street")                
    if not _data_check[0]: e += _data_check[1]
    _data_check = check_input(_data["zip"], ascii_charset, "Postal code")                
    if not _data_check[0]: e += _data_check[1]
    _data_check = check_input(_data["city"], ascii_charset, "City")                
    if not _data_check[0]: e += _data_check[1]
    _data_check = check_input(_data["country"], ascii_charset, "Country")                
    if not _data_check[0]: e += _data_check[1]
    _data_check = check_input(_data["nationality"], ascii_charset, "Nationality")                
    if not _data_check[0]: e += _data_check[1]
    _data_check = check_input(_data["phone"], phone_charset, "Telephone No")                
    if not _data_check[0]: e += _data_check[1]
    _data_check = check_input(_data["fax"], phone_charset, "FAX No")                
    if not _data_check[0]: e += _data_check[1]
    _data_check = check_input(_data["email"], email_charset, "Email address")                
    if not _data_check[0]: e += _data_check[1]
    _data_check = check_input(_data["position"], ascii_charset, "Current Position")                
    if not _data_check[0]: e += _data_check[1]
    _data_check = check_input(_data["employer"], ascii_charset, "Employer")                
    if not _data_check[0]: e += _data_check[1]
    _data_check = check_input(_data["source"], ascii_charset, "How did you learn about the meeting")                
    if not _data_check[0]: e += _data_check[1]
    _data_check = check_input(_data["contribution"], ascii_charset, "Contribution")                
    if not _data_check[0]: e += _data_check[1]                
   # format 
    _data["presentation_title"] = my_format_string(_data["presentation_title"])
    _data_check = check_input(_data["presentation_title"], ascii_charset, "Presentation title")                
    if not _data_check[0]: e += _data_check[1]
    _data_check = check_input(_data["author_list"], ascii_charset, "Authors List")                
    if not _data_check[0]: e += _data_check[1]
    _data_check = check_input(_data["author_emails"], ascii_charset, "Correspondence for each author")                
    if not _data_check[0]: e += _data_check[1]
   # format
    _data["abstract"] = my_format_string(_data["abstract"])
    _data_check = check_input(_data["abstract"], ascii_charset, "Abstract")                
    if not _data_check[0]: e += _data_check[1]
    _data_check = check_input(_data["registration_type"], ascii_charset, "Registration type")                
    if not _data_check[0]: e += _data_check[1]
    _data_check = check_input(_data["registration_password"], ascii_charset, "Registration password")                
    if not _data_check[0]: e += _data_check[1]
    return e
            
            
def form_accomodation(si, c, _data, errors):
    s = ""        
    s += begin_captioned_table("Accomodation specifications", c.conference_name, "")
    s += "<TR><TD class=\"text\">\n"    
    s += "Registration number: <b>" + str(_data["registration_number"]) + "</b><br>\n"
    s += "Registrated person: <b>" + _data["first_name"] + " " + _data["family_name"] + "</b><br>\n"
    s += "<br>\n"
    
    for _item in c.xml_def:
        if _item.attrib["short"] == "acc_spec":
            s += _item.text
        else:
            # looking only for short="acc_spec"
            pass                    
    s += "<br>\n"
    if errors:
          s += "<div class=\"errors\">\n"
          s += "<b>There has been found following error(s):</b><br>\n"
          s += errors
          s += "</div><br>\n"
    s += "<FORM method=\"POST\" action=\"" + make_command(si.page_script, "accomodation_form", c.conference, {}) + "\">\n"
    s += "<INPUT type=\"hidden\" name=\"form_name\" value=\"form_accomodation\">\n"
    s += "<INPUT type=\"hidden\" name=\"registration_number\" value=\""+str(_data["registration_number"])+"\">\n"
    s += make_text_input("roommate", "I would prefer to share my room with", "", 255, _data["roommate"])
    s += "<br>\n"
    if not _data["registration_number"] or si._newly_saved:
        s += "<INPUT type=\"submit\" value=\"Submit\"><br>\n"    
    else:
        s += "<INPUT type=\"submit\" value=\"Change\"><br>\n"
    s += "</FORM><br>\n"                    
    s += "</TD></TR>\n"
    s += end_table()
    return s
            

def get_accomodation_data(si, c):
    if si._POST.has_key("registration_number") and si._POST.has_key("form_name") and si._POST["form_name"] == "form_accomodation":
        result = si.dbhandler.do_sql_cmd_dict("SELECT * FROM registrations WHERE registration_number = '"+si._POST["registration_number"]+"'")[0]                    
        _data = {
          "registration_number": result["registration_number"],
          "roommate": si._POST["roommate"],
          "first_name": result["first_name"],
          "family_name": result["family_name"],
        }
        _posted = 1
    elif si._POST.has_key("registration_number") and si._POST.has_key("form_name") and si._POST["form_name"] == "form_registration":
        result = si.dbhandler.do_sql_cmd_dict("SELECT * FROM registrations WHERE registration_number = '"+str(si._POST["registration_number"])+"'")[0]                    
        _data = {
          "registration_number": result["registration_number"],
          "roommate": result["roommate"],
          "first_name": result["first_name"],
          "family_name": result["family_name"],
        }
        _posted = 0
    elif si._GET.has_key("reg_number"):
        result = si.dbhandler.do_sql_cmd_dict("SELECT * FROM registrations WHERE registration_number = '"+si._GET["reg_number"][0].strip()+"'")[0]                    
        _data = {
          "registration_number": result["registration_number"],
          "roommate": result["roommate"],
          "first_name": result["first_name"],
          "family_name": result["family_name"],
        }
        _posted = 0
    else: 
        raise RuntimeError, "Unable to get registration number. Please contact the administrator."        
    return _data, _posted 


def check_accomodation_data(si, c, _data):
    # check data                
    e = ""
    return e 
    
    
def get_abstract_data(si, c):
    if si._GET.has_key("reg_number"):
        result = si.dbhandler.do_sql_cmd_dict("SELECT * FROM registrations WHERE registration_number = '"+si._GET["reg_number"][0]+"'")[0]                    
        _data = {
          "registration_number": result["registration_number"],
          "first_name": result["first_name"],
          "family_name": result["family_name"],
          "abstract": result["abstract"],
        }
    else: 
        raise RuntimeError, "Unable to get reistration number. Please contact the administrator."        
    return _data 


def index(req):
    # init error variable
    err = ""
    # init system info
    try:
        si = system_info(req)
    except RuntimeError, e:
        err += str(e)
    else:   
        # init conference data  
        try:
            c = conference(si) # bug, it does not always return an exception!
	                       # for example when SELECT fails
			       # index.py, line 55, in __init__
        except RuntimeError, e:
            err += str(e)
    try:
        if c:
            pass
    except:
        req.content_type = "text/plain"
        req.write("Error: No connection to mysql: %s" % err)
        return apache.OK

    # header
    s = ""
    s += "<HTML>\n"
    s += "<HEAD>\n"  
    if c:  
        s += "  <TITLE>"+c.conference_name+"</TITLE>\n"
    s += "  <LINK rel=\"stylesheet\" type=\"text/css\" href=\"styles/style.css\">\n"
    s += "</HEAD>\n"
    s += "<BODY>\n"    
    if err != "":
        s += err
    else:
        if si.page == "default":
            s += conference_main_page(si, c)
        elif si.page == "list":
            if si._GET.has_key("password") and si._GET["password"][0] == "totivirus":
                s += list_page(si, c)
            else:
                s += "Invalid password for viewing the list."
        elif si.page == "payment_dump":
            if si._GET.has_key("password") and si._GET["password"][0] == "totivirus":
                s += payment_dump_page(si, c)
            else:
                s += "Invalid password for viewing the list."
        elif si.page == "email_list":
            if si._GET.has_key("password") and si._GET["password"][0] == "totivirus":
                s += email_list_page(si, c)
            else:
                s += "Invalid password for viewing the list."
        elif si.page == "title_list":
            if si._GET.has_key("password") and si._GET["password"][0] == "totivirus":
                s += title_list_page(si, c)
            else:
                s += "Invalid password for viewing the list."
        elif si.page == "abstract_list":
            if si._GET.has_key("password") and si._GET["password"][0] == "totivirus":
                s += abstract_list_page(si, c)
            else:
                s += "Invalid password for viewing the list."
        elif si.page == "abstract_list_short":
            if si._GET.has_key("password") and si._GET["password"][0] == "totivirus":
                s += abstract_list2_page(si, c)
            else:
                s += "Invalid password for viewing the list."
        elif si.page == "register":
            s += register_page(si, c)            
        elif si.page in ["registration_form", "accomodation_form", "abstract", "view_registration"]:
            _auth_failed = 0
            if si._GET.has_key("reg_action") and si._GET["reg_action"][0] == "change":
                if si._GET.has_key("reg_number") and si._GET.has_key("reg_password"):
                    _reg_number = si._GET["reg_number"][0].strip()
                    _reg_password = si._GET["reg_password"][0]
                    # check the numbber and pwd
                    result = si.dbhandler.do_sql_cmd_dict("SELECT * FROM registrations WHERE registration_number = '"+_reg_number+"' AND registration_password = '"+_reg_password+"'")
                    if len(result) == 0:
                        _auth_failed = 1                    
                    else: 
                        _auth_failed = 0
                else:
                    _auth_failed = 1                    
            if not _auth_failed: 
                if si.page == "registration_form":
                    # get registration data
                    _data, _reg_number, _posted = get_register_data(si, c)
                    if _posted:
                        # check posted data
                        _errors = check_register_data(si, c, _data)
                    else:
                        _errors = ""
                    if _posted and not _errors:
                        # store to DB
                        _save_ok = 0
                        if empty_input(_reg_number):
                            # generate registration number and insert to DB
                            i = int(10000*random.random())
                            _not_ok = 1
                            while _not_ok:
                                res = si.dbhandler.do_sql_cmd("SELECT registration_number FROM registrations WHERE registration_number = "+str(i))
                                if len(res) == 0:
                                    _not_ok = 0
                                else:
                                    i += 1
                            _data["registration_number"] = i
                            try:
                                _data["registration_details"] = ";".join(_data["registration_details"])
                                _data["registration_date"] = str(datetime.date.today())
                                _data["registration_abstract_date"] = str(datetime.date.today())
                                _data["id"] = si.dbhandler.do_sql_insert("registrations", ("id"), _data)
                                _save_ok = 1
                            except Exception, e:
                                s += "Some error occured on the server, while saving data to the database. Please contact the administrator." + str(e)
                            msg = MIMEText("Dear colleague,\r\nyour registration for the " + c.conference_name + " was successful.\r\nFor further changes in your registration use the following login:\r\nRegistration Number: " + str(_data["registration_number"]) + "\r\nPassword: " + str(_data["registration_password"]) + "\r\n\r\nYou can also review and edit your registration at this link: " + make_command(si.page_script, "registration_form", c.conference, {"reg_number": str(_data["registration_number"]), "reg_password": str(_data["registration_password"]), "reg_action": "change"}, "") + "\r\n\r\nSincerely, meeting organizers.")
                            msg['Subject'] = "Confirmation of your registration"
                            msg['From'] = si.site_email
                            msg['To'] = _data["email"]
                            try:
                                # send mail
                                server = smtplib.SMTP(si.smtp)
                                server.sendmail(msg['From'], msg['To'], msg.as_string())
                                server.sendmail(msg['From'], "martin@natur.cuni.cz", msg.as_string())
                                server.quit()                                 
                            except Exception, e:
                                s += "Some error occured on the server, while sending you a confirmation email. Please contact the administrator." + str(e)
                        else:
                            # update database record
                            try:
                                _data["registration_details"] = ";".join(_data["registration_details"])
                                _data["registration_abstract_date"] = str(datetime.date.today())
                                si.dbhandler.do_sql_update("registrations", _data, {"registration_number": _data["registration_number"]}, ignore_column_names = ["id"])
                                _save_ok = 1
                            except Exception, e:
                                s += "Some error occured on the server, while saving data to the database. Please contact the administrator." + str(e)
                        if _save_ok:
                            si._newly_saved = 1
                            si.page = "accomodation_form"
                            si._POST["registration_number"] = _data["registration_number"]           
                            # s += "Your registration was successfully stored. You should recieve a confirmation email. Your registration number is :"+str(_data["registration_number"])                        
                    else:
                        # reg_form
                        s += form_register(si, c, _data, _errors)
                if si.page == "accomodation_form":
                    _data, _posted = get_accomodation_data(si, c)
                    if _posted:
                        # check posted data
                        _errors = check_accomodation_data(si, c, _data)
                    else:
                        _errors = ""
                    if _posted and not _errors:
                        # store to DB
                        _save_ok = 0
                        # update database record
                        try:
                            si.dbhandler.do_sql_update("registrations", _data, {"registration_number": _data["registration_number"]}, ignore_column_names = ["id"])
                            _save_ok = 1
                        except:
                            s += "Some error occured on the server. Please contact the administrator.";
                        if _save_ok:
                            s += begin_captioned_table(c.conference_name, "", "")
                            s += "<TR><TD class=\"text\">\n"    
                            s += "Your accomodation request was successfully stored. You should recieve a confirmation email. Your registration number is :" + str(_data["registration_number"]) + "<br><br>\n"
                            s += "<a href=\"" + make_command(si.page_script, "default", c.conference, {}) + "\">Return to main page</a>"             
                            s += "</TD></TR>\n"
                            s += end_table()
                    else:
                        # accomodation_form
                        s += form_accomodation(si, c, _data, _errors)
                if si.page == "abstract":             
                    _data = get_abstract_data(si, c)
                    # view abstract
                    s += begin_captioned_table("Abstract preview", c.conference_name, "")
                    s += "<TR><TD class=\"text\">\n"    
                    s += "<b>Abstract of registrtation no. "+str(_data["registration_number"])+"</b><br><br>\n"
                    s += _data["abstract"]
                    s += "</TD></TR>\n"
                    s += end_table()
                if si.page == "view_registration":             
                    # get registration data
                    _data, _reg_number, _posted = get_register_data(si, c)
                    # view
                    s += view_register(si, c, _data)
            else:
                s += begin_captioned_table(c.conference_name, "", "")
                s += "<TR><TD class=\"error\">\n"    
                s += "Invalid registration number or password. Cannot proceed, please return back."
                s += "</TD></TR>\n"
                s += end_table()
        else:
            s += begin_captioned_table(c.conference_name, "", "")
            s += "<TR><TD class=\"error\">\n"    
            s += "Unknown page to show."
            s += "</TD></TR>\n"
            s += end_table()
    # footer
    s += "</BODY>\n"
    s += "</HTML>\n"
    
    if si.dbhandler:
        si.dbhandler.close()
    
    return s
