var url = "http://www.touristik.at/";

function EMail(s) {
	var a = false;
	var res = false;
	if(typeof(RegExp) == 'function') {
		var b = new RegExp('abc');
		if(b.test('abc') == true) {
			a = true;
		} // if
	} // if
	if(a == true) {
		reg = new RegExp('^([a-zA-Z0-9\\-\\.\\_]+)'+'(\\@)([a-zA-Z0-9\\-\\.]+)'+'(\\.)([a-zA-Z]{2,4})$');
		res = (reg.test(s));
	} else {
		res = (s.search('@') >= 1 &&
		s.lastendexOf('.') > s.search('@') &&
		s.lastendexOf('.') >= s.length-5)
	} // if-lese
	return(res);
} // function

function validateEmail(lang, emailFields, error) {
    
	if (!error) {
		var error = false;
	} // if
    var errorMessages = setErrorMessages(lang);
    for(i=0; i<=emailFields.length-1; i++) {
        var val = jQuery.trim($("#"+emailFields[i]).val());
        if(val == "" || val == errorMessages[1] || EMail(val) == false) {
            error = true;
            $("#"+emailFields[i]).addClass('input_error').val(errorMessages[1]);
        } else {
            $("#"+emailFields[i]).removeClass('input_error');   
        } // if-else    
    } // for
    return error;
    
} // function

function validateFields(lang, fields, error) {

	if (!error) {
		var error = false;
	} // if
    var errorMessages = setErrorMessages(lang);
    if (fields.length > 0) {
        for(i=0; i<=fields.length-1; i++) {
            var val = jQuery.trim($("#"+fields[i]).val());
            if (val == "" ||  val == -1 || val == errorMessages[0]) {
                error = true;
				// check ob es eine personalisierte errorMessage gibt
				if ($("#"+fields[i]+"_errorMessage").length > 0) {
					$("#"+fields[i]).addClass('input_error').val($("#"+fields[i]+"_errorMessage").val());
				} else {
					$("#"+fields[i]).addClass('input_error').val(errorMessages[0]);	
				}
            } else {
				if ($("#"+fields[i]+"_errorMessage").length > 0 && val == $("#"+fields[i]+"_errorMessage").val()) {
					error = true;
					$("#"+fields[i]).addClass('input_error').val($("#"+fields[i]+"_errorMessage").val());
				} else {
	                $("#"+fields[i]).removeClass('input_error');
				} // if-else
            } // if-else
        } // for
    } // if
    
	return error;

} // function

function validateFiles(lang, fileFields, error) {
	
	if (!error) {
		var error = false;
	} // if
	// unbedingt neben dem dursuchen feld ein <span> mit der selben id+"_errorMessage" zur Ausgabe des Fehlers
	for(i=0; i<=fileFields.length-1; i++) {
		var fileName = $("#"+fileFields[i]).val();
		if (fileName == "") {
			error = true;
			$("#"+fileFields[i]+"_errorMessage").addClass('input_error').html('Please upload a *.jpg that proofs your student status');  
		} // if
		var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
        if (ext == "JPEG" || ext == "jpeg" || ext == "jpg" || ext == "JPG") {
            $("#"+fileFields[i]+"_errorMessage").removeClass('input_error').html(''); 
        } else {
            error = true;
            $("#"+fileFields[i]+"_errorMessage").addClass('input_error').html('Please upload a *.jpg that proofs your student status');
        } // if-else    
    } // for
	return error;
} // function

function setErrorMessages(lang) {
    
    if (lang == "de") {
	    var errorMessage = unescape("Bitte ausf%FCllen");
	    var errorMessageEmail = unescape("Keine g%FCltige e-Mail Adresse");
    } 
    if (lang == "en") {
        var errorMessage = unescape("Please fill in");
        var errorMessageEmail = unescape("No valid e-Mail Address");
    }
    if (lang == "fr") {
        var errorMessage = unescape("Complétez la case");
        var errorMessageEmail = unescape("L'e-Mail adresse n'est pas correct");
    }
    
    var errorMessages = new Array(errorMessage, errorMessageEmail);
    return errorMessages;
    
} // function

function validateForm(form, ajax) {
	
	var lang = "en";
	var error = false;
    var errorMessages = setErrorMessages(lang);
	if (form == "participationForm") {
		
		var fields = new Array("vorname", "nachname", "institution", "strasse", "plz", "ort", "telefon", "nationalitaet", "land");
		error = validateFields(lang, fields, error);
		
		var emailFields = new Array("email");
        error = validateEmail(lang, emailFields, error);
		
		if ($("#participant_full").attr("checked") == false && $("#participant_student").attr("checked") == false && $("#participant_one_day").attr("checked") == false) {
			alert('Please select your Participation Fee!');
			error = true;
		} // if
				
		if ($("#extra_ticket_dinner").attr("checked") == true && $.trim($("#name_conference_dinner").val()) == "") {
			$("#conferenceError").addClass("input_error");
			error = true;
		} else {
			$("#conferenceError").removeClass("input_error");
		} // if-else
		
		if ($("#participant_one_day").attr("checked") == true && $("#one_day_participation").val() == -1) {
			$("#one_day_participation").addClass("input_error");
			error = true;
		} else {
			$("#one_day_participation").removeClass("input_error");
		} // if-else

if ($("#creditcard").attr("checked") == false && $("#banktransfer").attr("checked") == false) {
			alert('Please select your Form of Payment !');
			error = true;
		} // if

		
		if ($("input[name='input[participant]']:checked").val() == "student") {
			var fileFields = new Array("document");
			error = validateFiles(lang, fileFields, error);
		} // if

	} // if
	
	if (error) return false;
	else return true;

	
} // function

/**
* clearInput
* just clears the input field
**/
function clearInput(id, lang) {
    
	var errorMessages = setErrorMessages(lang);	
	if ($("#"+id+"_errorMessage").length > 0) {
		if ($("#"+id).val() == $("#"+id+"_errorMessage").val()) {
			if ($("#"+id+"_clearValue").length > 0) {
				$("#"+id).val($("#"+id+"_clearValue").val());
			} else {
				$("#"+id).val('');
			} // if-else
			$("#"+id).removeClass('input_error');
		} // if
		if ($("#"+id+"_preFilledValue").length > 0) {
			if ($("#"+id).val() == $("#"+id+"_preFilledValue").val()) {
				if ($("#"+id+"_clearValue").length > 0) {
					$("#"+id).val($("#"+id+"_clearValue").val());
				} else {
					$("#"+id).val('');
				} // if-else
				$("#"+id).removeClass('input_error');
			} // if
		} // if
	} else {
		if ($("#"+id).val() == errorMessages[0] || $("#"+id).val() == errorMessages[1]) {
			$("#"+id).val('');
			$("#"+id).removeClass('input_error');
		} // if
	} // if-else

} // function

function addUploadStudent() {
	
	var html = "<tr id='uploadStudentDocument'>\
					<td>&nbsp;</td>\
                    <td colspan='3'><input type='file' name='input[student_document]' id='document'></td>\
				</tr>\
				<tr id='documentStudentErrorMessage'>\
					<td>&nbsp;</td>\
					<td colspan='3'><span id='document_errorMessage'></span></td>\
				</tr>\
				<tr id='uploadDocumentText'>\
					<td>&nbsp;</td>\
					<td colspan='3'>Please upload a proof for your student status (scan of your student ID, letter of your professor, ...) Otherwise you have to pay the full registration fee</td>\
				</tr>";
	if ($("#uploadStudentDocument").length <= 0) {
		$("#participantStudent").after(html);
	} // if
	
} // function

function toggleUploadStudent(val) {
	
	var html = "<tr id='uploadStudentDocument'>\
					<td>&nbsp;</td>\
                    <td colspan='3'><input type='file' name='input[student_document]' id='document'></td>\
				</tr>\
				<tr id='documentStudentErrorMessage'>\
					<td>&nbsp;</td>\
					<td colspan='3'><span id='document_errorMessage'></span></td>\
				</tr>\
				<tr id='uploadDocumentText'>\
					<td>&nbsp;</td>\
					<td colspan='3'>Please upload a proof for your student status (scan of your student ID, letter of your professor, ...) Otherwise you have to pay the full registration fee</td>\
				</tr>";
				
	// uncheck student if full is clicked
	if (val == "full") {
		$("#participant_student").attr('checked', false);
		$("#participant_one_day").attr('checked', false);
		removeItem("oneDayDateRow");
	} // if
	
	if (val == "student") {
		$("#participant_full").attr('checked', false);
		$("#participant_one_day").attr('checked', false);
		removeItem("oneDayDateRow");
	} // if
	
	if (val == "one_day") {
		$("#participant_student").attr('checked', false);
		$("#participant_full").attr('checked', false);
	} // if
 	
	if ($("#participant_student").attr('checked') && $("#uploadStudentDocument").length <= 0 && val ==  "student") {
		$("#participantStudent").after(html);	
	} else {
		removeUploadStudent();
	} // if
	
} // function

function toggleExtraConferenceTicketName(val) {
	
	var html = "<tr id='conferenceTicketDinnerName'>\
					<td>&nbsp;</td>\
                    <td colspan='3'><input type='text' class='input' name='input[name_conference_dinner]' id='name_conference_dinner' style='width: 250px'>&nbsp; <span id='conferenceError'>Please fill in the name of the participant</span></td>\
				</tr>\
				";
				
	if ($("#extra_ticket_dinner").attr('checked')) {
		$("#extraDinner").after(html);	
	} else {
		removeItem("conferenceTicketDinnerName");
	} // if
	
} // function

function toggleOneDayPartipation(val) {
	
		var html = "<tr id='oneDayDateRow'>\
					<td>&nbsp;</td>\
                    <td colspan='3'>\
						<select id='one_day_participation' name='input[one_day_participation]'>\
							<option value='-1'>Please select a date</option>\
							<option value='17. September 2012'>17. September 2012</option>\
							<option value='18. September 2012'>18. September 2012</option>\
							<option value='19. September 2012'>19. September 2012</option>\
						</select>\
				</tr>\
				";
				
	if ($("#participant_one_day").attr('checked')) {
		$("#oneDayParticipationRow").after(html);	
	} else {
		removeItem("oneDayDateRow");
	} // if
	
} // function

function removeItem(id) {
	
	if ($("#"+id).length) {
		$("#"+id).remove();
	} // if
	
} // function
	
function removeUploadStudent() {
		
	if ($("#uploadStudentDocument").length > 0) {
		$("#uploadStudentDocument").remove();
	} // if
	if ($("#documentStudentErrorMessage").length > 0) {
		$("#documentStudentErrorMessage").remove();
	} // if
	if ($("#uploadDocumentText").length > 0) {
		$("#uploadDocumentText").remove();
	} // if
} // function

function checkAccCheckBox() {

	var accVorname = jQuery.trim($("#acc_vorname").val());
	var accNachname = jQuery.trim($("#acc_nachname").val());
	if (accVorname != "" && accNachname != "") {
		$("#participant_acc").attr("checked", true);
	} // if	

} // function


    function emailCheck (emailStr) {

    /* The following variable tells the rest of the function whether or not
    to verify that the address ends in a two-letter country or well-known
    TLD.  1 means check it, 0 means don't. */

    var checkTLD=1;

    /* The following is the list of known TLDs that an e-mail address must end with. */

    var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;

    /* The following pattern is used to check if the entered e-mail address
    fits the user@domain format.  It also is used to separate the username
    from the domain. */

    var emailPat=/^(.+)@(.+)$/;

    /* The following string represents the pattern for matching all special
    characters.  We don't want to allow special characters in the address.
    These characters include ( ) < > @ , ; : \ " . [ ] */

    var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";

    /* The following string represents the range of characters allowed in a
    username or domainname.  It really states which chars aren't allowed.*/

    var validChars="\[^\\s" + specialChars + "\]";

    /* The following pattern applies if the "user" is a quoted string (in
    which case, there are no rules about which characters are allowed
    and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
    is a legal e-mail address. */

    var quotedUser="(\"[^\"]*\")";

    /* The following pattern applies for domains that are IP addresses,
    rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
    e-mail address. NOTE: The square brackets are required. */

    var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;

    /* The following string represents an atom (basically a series of non-special characters.) */

    var atom=validChars + '+';

    /* The following string represents one word in the typical username.
    For example, in john.doe@somewhere.com, john and doe are words.
    Basically, a word is either an atom or quoted string. */

    var word="(" + atom + "|" + quotedUser + ")";

    // The following pattern describes the structure of the user

    var userPat=new RegExp("^" + word + "(\\." + word + ")*$");

    /* The following pattern describes the structure of a normal symbolic
    domain, as opposed to ipDomainPat, shown above. */

    var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");

    /* Finally, let's start trying to figure out if the supplied address is valid. */

    /* Begin with the coarse pattern to simply break up user@domain into
    different pieces that are easy to analyze. */

    var matchArray=emailStr.match(emailPat);

    if (matchArray==null) {

    /* Too many/few @'s or something; basically, this address doesn't
    even fit the general mould of a valid e-mail address. */

    alert("Ungültige Email-Adresse (prüfen Sie @ and .'s)");
    return false;
    }
    var user=matchArray[1];
    var domain=matchArray[2];

    // Start by checking that only basic ASCII characters are in the strings (0-127).

    for (i=0; i<user.length; i++) {
    if (user.charCodeAt(i)>127) {
    alert("Ungültige Zeichen im Usernamen.");
    return false;
       }
    }
    for (i=0; i<domain.length; i++) {
    if (domain.charCodeAt(i)>127) {
    alert("Ungültige Zeichen im Domänennamen.");
    return false;
       }
    }

    // See if "user" is valid

    if (user.match(userPat)==null) {

    // user is not valid

    alert("Name ungültig.");
    return false;
    }

    /* if the e-mail address is at an IP address (as opposed to a symbolic
    host name) make sure the IP address is valid. */

    var IPArray=domain.match(ipDomainPat);
    if (IPArray!=null) {

    // this is an IP address

    for (var i=1;i<=4;i++) {
    if (IPArray[i]>255) {
    alert(" IP Address ungültig!");
    return false;
       }
    }
    return true;
    }

    // Domain is symbolic name.  Check if it's valid.

    var atomPat=new RegExp("^" + atom + "$");
    var domArr=domain.split(".");
    var len=domArr.length;
    for (i=0;i<len;i++) {
    if (domArr[i].search(atomPat)==-1) {
    alert("Ungültige Domäne.");
    return false;
       }
    }

    /* domain name seems valid, but now make sure that it ends in a
    known top-level domain (like com, edu, gov) or a two-letter word,
    representing country (uk, nl), and that there's a hostname preceding
    the domain or country. */

    if (checkTLD && domArr[domArr.length-1].length!=2 &&
    domArr[domArr.length-1].search(knownDomsPat)==-1) {
    alert("Ungültige TLD oder Land .");
    return false;
    }

    // Make sure there's a host name preceding the domain.

    if (len<2) {
    alert("Kein Host angegeben!");
    return false;
    }

    // If we've gotten this far, everything's valid!
    return true;
    }

    function isExpiryDate(year, month)
    {

      today = new Date();
      expiry = new Date(year, month);

      if (today.getTime() > expiry.getTime())
        return false;
      else
        return true;
    }

    function chkFormular()
    {
      if(document.fcustomer.Demo2Email.value == "")
       {
         alert("Bitte Mail-adresse eingeben!");
         document.fcustomer.Demo2Email.focus();
         return false;    }
      if (emailCheck(document.fcustomer.Demo2Email.value) == false)
      {
          document.fcustomer.Demo2Email.focus();
      return false; }

       if(document.fcustomer.Demo2FName.value == "")
        {
         alert("Bitte einen Vornamen eingeben!");
         document.fcustomer.Demo2FName.focus();
         return false;    }

      if(document.fcustomer.Demo2LName.value == "")
       {
         alert("Bitte Namen eingeben!");
         document.fcustomer.Demo2LName.focus();
         return false;    }
      window.document.fcustomer.CUSTOMER.value = window.document.fcustomer.Demo2FName.value + " " + window.document.fcustomer.Demo2LName.value;

      if(document.fcustomer.PRICE.value == "")
       {
         alert("Bitte Betrag eingeben!");
         document.fcustomer.PRICE.focus();
         return false;    }
      if(document.fcustomer.IDENTIFIER.value == "")
       {
         alert("Bitte Kartennummer eingeben!");
         document.fcustomer.IDENTIFIER.focus();
         return false;
       }

     window.document.fcustomer.EXPIRY.value = window.document.fcustomer.exp_year.value  + window.document.fcustomer.exp_month.value

      if(document.fcustomer.exp_month.value==0) {
        alert("Sie haben keinen Monat eingegeben.");
        document.fcustomer.exp_month.focus();
        return false;
      }

      if(document.fcustomer.exp_year.value==0){
         alert("Sie haben keine Jahr eingegeben.");
         document.fcustomer.exp_year.focus();
         return false;
      }

      if (document.fcustomer.exp_year.value>96)
        tmpyear = "19" + document.fcustomer.exp_year.value;

      else if (document.fcustomer.exp_year.value<21)
        tmpyear = "20" + document.fcustomer.exp_year.value;

      else {
        alert("Ablaufjahr ist nicht gültig.");
        document.fcustomer.exp_year.focus();
        return false;
      }

      tmpmonth = document.fcustomer.exp_month.value;

      if (!isExpiryDate(tmpyear, tmpmonth)) {
        alert("Die Karte ist schon abgelaufen.");
        document.fcustomer.exp_year.focus();
        return false;
      }
    }

    function kontonr()
    {
     var nr,l,lx,i,p,q,x,li,re,pz,br;
     nr=window.document.fcustomer.IDENTIFIER.value;
     if (nr != "")
     {
     lx=nr.length;
      l=lx-1;
       li = nr.substring(0,lx-1);
       re = nr.substring(lx-1,lx);
       b1 = nr.substring(0,1);
       b2 = nr.substring(0,2);

     {
      p=0;
      q=0;
      for (i=0;i<lx;i++)
      {
       x=(2-(i&1))*li.substring(l-i-1,l-i);
       p+=x;
       q+=x%10+Math.floor(x/10);
      }


        pz=(1000-q)%10;

     window.document.fcustomer.BRAND.value= ""


      if (pz != re )
       {
       alert (unescape("Die CC-nummer ist ung%FCltig%21"));
         window.document.fcustomer.IDENTIFIER.value=""
         window.document.fcustomer.IDENTIFIER.focus()
       }
      if (b1==4 && lx == 16)
      {
      window.document.fcustomer.BRAND.value= "VISA"
      window.document.fcustomer.OPERATION.value= "ACCEPTPAYMENT"
      }
      if (b1==5 && lx == 16)
      {
      window.document.fcustomer.BRAND.value= "MasterCard"
      window.document.fcustomer.OPERATION.value= "ACCEPTPAYMENT"
      }
      if (b2==37 && lx == 15)
      {
      window.document.fcustomer.BRAND.value= "AMEX"
      window.document.fcustomer.OPERATION.value= "ACCEPTPAYMENT"
      }
      if (b2==36 && lx == 14)
      {
      window.document.fcustomer.BRAND.value= "Diners"
      window.document.fcustomer.OPERATION.value= "ACCEPTPAYMENT"
      }
      if (b2==35 && lx == 16)
      {
      window.document.fcustomer.BRAND.value= "JCB"
      window.document.fcustomer.OPERATION.value= "ACCEPTPAYMENT"
      }

     }

     }
    }

