// Validation functions

//automatically set to false
var hasErrors = new Boolean();
var errorMsg = null;

// official RFC 2822 email format regular expression
var EmailPatternRFC2822 = new RegExp(/^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/);
var _emptyRegEx = new RegExp(/^\s*$/);

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };
String.prototype.trimEnd = function() { return this.replace(/\s+$/, ''); };
String.prototype.trimStart = function() { return this.replace(/^\s+/, ''); };
String.prototype.isEmpty = function () { return (this.length == 0 || _emptyRegEx.test(this)); }
String.prototype.isMatch = function (regex) {
    if (regex == null || typeof(regex) == 'undefined') return true;
    return (typeof(regex) == "RegExp" ? regex.test(this) : new RegExp(regex).test(this));
}

function getElem(o) { return (typeof(o) == "string" ? document.getElementById(o) : o); } 

function valueOf(o) {    
    var elem = getElem(o);
      
    switch (elem.nodeName) {
        case 'INPUT': return elem.value.toString(); break;
        case 'SELECT': return elem.value.toString(); break;
    }
        
    return null;
}

function isEmpty(o) { return (o == null || typeof(o) == "undefined" || o.toString().isEmpty()); }

function validate(what) {
    if (typeof(what.beforevalidate) == "function")
        what.beforevalidate();
    
    var valid = (typeof(what.expr) == "function" ? what.expr() : what.expr);
    
    if (valid)
    {
        if (typeof(what.show) == "string") $(what.show).hide();
        if (typeof(what.seterror) == "string") $(what.seterror).removeClass("error");
        if (typeof(what.onvalid) == "function") what.onvalid();
    }
    else
    {    
        if (typeof(what.show) == "string") $(what.show).show();
        if (typeof(what.seterror) == "string") $(what.seterror).addClass("error");
        if (typeof(what.oninvalid) == "function") what.oninvalid();
    }
    
    if (typeof(what.aftervalidate) == "function")
        what.aftervalidate(valid);
        
    return valid;
}

function ValidateField(txtObj, errorText, errorObj, regEx)
{   
    validate({
        expr: !isEmpty(valueOf(txtObj)) && valueOf(txtObj).isMatch(regEx),        
        seterror: '#' + errorObj,
        oninvalid: function () { 
            errorMsg += "- " + errorText + "\n" 
            hasErrors = true;
        }
    });
}

function validateForm(errorTarget){

    // reset error indicators
    hasErrors = false;
    errorMsg = ""; // reset error message

	//firstName
	ValidateField('firstName',"Por favor ingrese su nombre",'nameSpan');
	//lastName
	ValidateField('lastName',"Por favor ingrese sus apellidos",'lnameSpan');
	//date of birth
	var y = parseInt(document.getElementById('BirthDayY').value);
	var d = parseInt(document.getElementById('BirthDayD').value);
	var m = parseInt(document.getElementById('BirthDayM').value);
	//var fechaNac = new Date(m + '/' + d + '/' + y);
	//var fechaLimite = new Date('01/01/1990');
	//valid age ?
	//if ( fechaNac > fechaLimite){
	//	hasErrors = true;
	//	errorMsg += "- BECAS MEC es sólo para estudiantes entre 18 y 30 años de edad\n" + 
	//	            "nacidos entre el 01/01/1978 y el 01/01/1990\n";
	//	document.getElementById('fechaNacSpan').className = "error";
	//} else {

	    if (isValidDate(m, d, y) == "invalid") {
		    hasErrors = true;
		    errorMsg += "- Por favor corrija la fecha de nacimiento\n";
		    document.getElementById('fechaNacSpan').className = "error";
	    } else {
	        document.getElementById('fechaNacSpan').className = "std";
	    }
	//}
	
	//gender
	if(document.getElementById('gender').value == "-")
	{
	    hasErrors = true;
	    errorMsg += "- Por favor seleccione el sexo\n";
	    document.getElementById('genderSpan').className = "error"; 
	}
	else
	{
	    document.getElementById('genderSpan').className = "std";
	}
	
	//address1
	ValidateField('address1',"Por favor ingrese su dirección",'address1Span');
	//postCode
	ValidateField('postCode',"Por favor ingrese su código postal",'postCodeSpan'); //, /^([0][1-9]|[1-4[0-9]){2}[0-9]{3}$/); // == spanish postcode regex
	//city
	ValidateField('city',"Por favor ingrese su ciudad",'citySpan');	
	
	// validate phonenumbers
	var phoneValid = validate({
        expr: valueOf("telephone").isEmpty() || valueOf("telephone").isMatch(/^((\s*)|([0-9]{2,3}-?\s?[0-9]{6,7}))$/g),
        seterror: "#telephoneSpan",
        oninvalid: function () {
            hasErrors = true;
        }
    });

	var mobileValid = validate({
        expr: valueOf("mobile").isEmpty() || valueOf("mobile").isMatch(/^((\s*)|([0-9]{2,3}-?\s?[0-9]{6,7}))$/g),
        seterror: "#mobileSpan",
        oninvalid: function () { 
            hasErrors = true; 
        }
    });
		
	if (phoneValid && mobileValid) // NOTE: phone and mobile are also valid when they are empty, but we need at least one of them.
	{
		validate({
            expr: !valueOf("telephone").isEmpty() || !valueOf("mobile").isEmpty(),
            seterror: "#telephoneSpan, #mobileSpan",
            oninvalid: function () {
                errorMsg += "- Por favor ingrese su teléfono\n";
                hasErrors = true;
            }
        });
    }
	
	//email (and valid email)
	if (validate({expr: !isEmpty(valueOf(document.getElementById('email'))), seterror: "#emailSpan", oninvalid: function () { errorMsg += "- Por faor ingrese su dirección de email\n"; hasErrors = true; }}))	        
	{
        validate({
            expr: valueOf('email').isMatch(EmailPatternRFC2822),
            seterror: "#emailSpan",
            oninvalid: function () {
                errorMsg += "- Por favor ingrese una dirección válida de email\n";
                hasErrors = true;
            }
        });
    }
	
	//id number
	//check dropdown is not null value
	if(document.getElementById('idDropdown').value == 'null')
	{
		hasErrors = true;
		//errorMsg += "- Por favor seleccione un tipo de número de ID\n";
		errorMsg += "- Por favor seleccione un tipo DNI\n";
		document.getElementById('idSpan').className = "error";
	}
	else
	{
		//ValidateField('idText',"Por favor ingrese el número de ID",'idSpan');
		ValidateField('idText',"Por favor ingrese el número DNI",'idSpan');
	}
	
	//rep
	/*if(document.getElementById('representative').value == 'null')
	{
	    hasErrors = true;
	    errorMsg += "- Por favor seleccione un representante\n";
	    document.getElementById('repSpan').className = "error";
	}
	else
	{
	    errorMsg += "test";
	    document.getElementById('repSpan').className = "std";
	}*/
	

	if(!document.getElementById('chkTerms').checked){
	    hasErrors = true;
	    errorMsg += "- He leído y aceptado los Términos y Condiciones Generales de EF.";
	}

	if (hasErrors) {
	    if (typeof(errorTarget) != "undefined")
	        document.getElementById(errorTarget).innerHTML = errorMsg.replace(/\n/g, '<br />\n');
	    else
	        alert(errorMsg);

	    return false;
	}
	else
	{
	    document.calculationForm.submit();
	    return true;
	}
}

function blurCheck(object,errorObj){
    if(document.getElementById(errorObj).className = "error")
    {
        if(document.getElementById(object).value != '')
        {
            document.getElementById(errorObj).className = "std"
        }
    }
}

function validateIdDropdown(){
	var obj = document.getElementById('idDropdown');
	var idText = document.getElementById('idText');
	var nationalityDropdown = document.getElementById('nationality');

	if(obj.value == "DNI")
	{
		//set nationality to spanish
		nationalityDropdown.value = 'ES';
		//disable nationality dropdown
		nationalityDropdown.disabled = "disabled";
		//focus on id textbox
		idText.focus();
	}
	else if(obj.value == "NIE")
	{
		alert("Para residentes con número NIE, EF proveerá una carta de aceptación, " + 
		      "pero necesitarás solicitar una visa para entrar al país por tu cuenta.");
		
		//enable nationality dropdown
		nationalityDropdown.disabled = "";
		//focus on id textbox
		idText.focus();
	}
	else
	{
		///do nothing, main validation will take care of this	
	}
}

function stripOmnitureError(str) {
    if (str.indexOf("<!-- Omniture Tracking Error") == 0) {
        var index = str.lastIndexOf("-->");
        if (index != -1) {
            return str.substring(index + 3);
        }
    }

    return str;
}

//Other functions

function showDiv(object) { 
    $('#' + object).show();
    //document.getElementById(object).style.display = 'block'; 
}

function swapDivs(){
	
	var object = document.getElementById('swapLink');
	
	if(object.innerHTML == "Ver los Paquetes Promocionales MEC")
	{
		document.getElementById('text').innerHTML = document.getElementById('specialOffersHolder').innerHTML;
		object.innerHTML = "< Atrás";   
		object.blur();
		
		document.getElementById('swapDivTableTwo').style.display = 'none';
	}
	/*
	else
	{
		document.getElementById('text').innerHTML = "<p style=\"text-align:\"><strong>Bienvenido a la p&aacute;gina de reserva de Cursos EF de Idiomas en el Extranjero para las becas MEC " + new Date().getFullYear() + ".</strong></p><p style=\"text-align:\">S&oacute;lo tardar&aacute;s un par de minutos.Ten a mano una tarjeta de d&eacute;bito o cr&eacute;dito para formalizar la reserva y abonar los 200&euro; que el Ministerio de Educaci&oacute;n y Ciencia solicita.<br /></p>";
		object.innerHTML = "Ver los Paquetes Promocionales MEC";
		object.blur();
		
		document.getElementById('swapDivTableTwo').style.display = '';		
	}
	*/
}

function swapDivsTwo()
{
	var object = document.getElementById('swapLinkTwo');
	
	if(object.innerHTML == "Condiciones de los vuelos")
	{
	    var str = "<p style=\"text-align:\">El viaje internacional se realizará en avión desde el punto de salida internacional " +
	              "definido por EF Education S.A. El viaje no es necesariamente directo desde el punto " + 
	              "de salida internacional hasta el destino, pudiendo existir conexiones y/o transbordos " + 
	              "durante el mismo. Dada la elevada ocupación en las fechas en las que viajan los estudiantes, " + 
	              "existe la posibilidad de que las líneas aéreas u otras compañías de transporte impongan cambios " + 
	              "de última hora en horarios, fechas, destinos, etc. que EF tratará que perjudiquen lo mínimo posible " + 
	              "a los clientes." + 
	              "<br>" + 
	              "EF Education S.A. no se hace responsable de los trastornos y costes que pudieran ocasionar " +
	              "estos cambios, ni los provocados por huelgas, retrasos, alteraciones, pérdidas de equipajes, " +
	              "ni ningún otro problema causado por las compañías de transporte.</p>";
	              
		document.getElementById('text').innerHTML = "<p style=\"text-align:\"><strong>Condiciones de los vuelos</strong></p>" + str + "";
		object.innerHTML = "< Atrás";
		object.blur();
		
		document.getElementById('swapDivTable').style.display = 'none';
	}
	else
	{
		document.getElementById('text').innerHTML = "<p style=\"text-align:\"><strong>Bienvenido a la p&aacute;gina de reserva de Cursos EF de Idiomas en el Extranjero para las becas MEC 2010.</strong></p><p style=\"text-align:\">S&oacute;lo tardar&aacute;s un par de minutos.Ten a mano una tarjeta de d&eacute;bito o cr&eacute;dito para formalizar la reserva y abonar los 200&euro; que el Ministerio de Educaci&oacute;n, Politica Social y Deporte solicita.<br /></p>";
		object.innerHTML = "Condiciones de los vuelos";
		object.blur();
		
		document.getElementById('swapDivTable').style.display = 'none';	
	}
}

function setBirthdayDropdowns()
{
	//days
	var days = "<select name='BirthDayD'>\n";
	
	for(i=1;i<=31;i++)
	{
		days += "\t<option value="+i+">"+i+"</option>\n";
	}
	
	days += "</select>\n\n";
	
	//months
	var months = "<select name='BirthDayM'>\n";
	
	for(i=1;i<=12;i++)
	{
		months += "\t<option value="+i+">"+i+"</option>\n";
	}
	
	months += "</select>\n\n";
	
	//years
	var years = "<select name='BirthDayY'>\n";
	
	for(i=2005;i>1950;i--)
	{
		years += "\t<option value="+i+">"+i+"</option>\n";
	}
	
	years += "</select>\n\n";
	
	return days + months + years;
}

 function isValidDate(Mn, Day, Yr) {
    var DateVal = Mn + "/" + Day + "/" + Yr;
    var dt = new Date(DateVal);

    if(dt.getDate()!=Day){
        return "invalid";
        }
    else if(dt.getMonth()!=Mn-1){
    //this is for the purpose JavaScript starts the month from 0
        return "invalid";
        }
    else if(dt.getFullYear()!=Yr){
        return "invalid";
        }
       
    return "valid";
 }

function renderCountriesDropdown()
{
	var codesCountries = new Array(
		["AF","Afghanistan"],
		["AL","Albania"],
		["DZ","Algeria"],
		["AS","American Samoa"],
		["AD","Andorra"],
		["AO","Angola"],
		["AI","Anguilla"],
		["AQ","Antarctica"],
		["AG","Antigua and Barbuda"],
		["AR","Argentina"],
		["AM","Armenia"],
		["AW","Aruba"],
		["AC","Ascension Island"],
		["AU","Australia"],
		["AT","Austria"],
		["AZ","Azerbaijan"],
		["BS","Bahamas"],
		["BH","Bahrain"],
		["BD","Bangladesh"],
		["BB","Barbados"],
		["BY","Belarus"],
		["BX","Belgie"],
		["BE","Belgique"],
		["BZ","Belize"],
		["BJ","Benin"],
		["BM","Bermuda"],
		["BT","Bhutan"],
		["BO","Bolivia"],
		["BA","Bosnia and Herzegowina"],
		["BW","Botswana"],
		["BV","Bouvet Island"],
		["BR","Brasil"],
		["IO","British Indian Ocean Territory"],
		["BN","Brunei Darussalam"],
		["BG","Bulgaria"],
		["BF","Burkina Faso"],
		["BI","Burundi"],
		["KH","Cambodia"],
		["CM","Cameroon"],
		["CA","Canada (en)"],
		["FC","Canada (fr)"],
		["CV","Cape Verde"],
		["KY","Cayman Islands"],
		["CF","Central African Republic"],
		["CZ","Ceska Republika"],
		["TD","Chad"],
		["CL","Chile"],
		["CN","China"],
		["CX","Christmas Island"],
		["CC","Cocos (Keeling) Islands"],
		["CO","Colombia"],
		["KM","Comoros"],
		["CG","Congo"],
		["CK","Cook Islands"],
		["CR","Costa Rica"],
		["HR","Croatia"],
		["CU","Cuba"],
		["CY","Cyprus"],
		["DK","Danmark"],
		["CD","Democratic Republic of Congo"],
		["DE","Deutschland"],
		["DJ","Djibouti"],
		["DM","Dominica"],
		["DO","Dominican Republic"],
		["TP","East Timor"],
		["EC","Ecuador"],
		["EG","Egypt"],
		["SV","El Salvador"],
		["GQ","Equatorial Guinea"],
		["ER","Eritrea"],
		["EE","Estonia"],
		["ET","Ethiopia"],
		["FK","Falkland Islands"],
		["FO","Faroe Islands"],
		["FJ","Fiji"],
		["FI","Finland (Suomi)"],
		["FS","Finland (Svenska)"],
		["YU","FR Yugoslavia"],
		["FR","France"],
		["GF","French Guiana"],
		["PF","French Polynesia"],
		["TF","French Southern Territories"],
		["GA","Gabon"],
		["GM","Gambia"],
		["GE","Georgia"],
		["GH","Ghana"],
		["GI","Gibraltar"],
		["GR","Greece"],
		["GL","Greenland"],
		["GD","Grenada"],
		["GP","Guadeloupe"],
		["GU","Guam"],
		["GT","Guatemala"],
		["GG","Guernsey"],
		["GN","Guinea"],
		["GW","Guinea-Bissau"],
		["GY","Guyana"],
		["HT","Haiti"],
		["HM","Heard and McDonald Islands"],
		["VA","Holy See (City Vatican State)"],
		["HN","Honduras"],
		["HK","Hong Kong"],
		["IS","Iceland"],
		["IN","India"],
		["ID","Indonesia"],
		["IR","Iran"],
		["IQ","Iraq"],
		["IE","Ireland"],
		["IM","Isle of Man"],
		["IL","Israel"],
		["IT","Italia"],
		["CI","Ivory Coast"],
		["JM","Jamaica"],
		["JP","Japan"],
		["JE","Jersey"],
		["JO","Jordan"],
		["KZ","Kazakhstan"],
		["KE","Kenya"],
		["KI","Kiribati"],
		["KR","Korea"],
		["KW","Kuwait"],
		["KG","Kyrgyzstan"],
		["LA","Laos"],
		["LV","Latvia"],
		["LB","Lebanon"],
		["LS","Lesotho"],
		["LR","Liberia"],
		["LY","Libya"],
		["LI","Liechtenstein"],
		["LT","Lietuva"],
		["LU","Luxembourg"],
		["MO","Macau"],
		["MK","Macedonia"],
		["MG","Madagascar"],
		["HU","Magyarorsz&#225;g"],
		["MW","Malawi"],
		["MY","Malaysia"],
		["MV","Maldives"],
		["ML","Mali"],
		["MT","Malta"],
		["MA","Maroc"],
		["QT","Mars"],
		["MH","Marshall Islands"],
		["MQ","Martinique"],
		["MR","Mauritania"],
		["MU","Mauritius"],
		["YT","Mayotte"],
		["MX","Mexico"],
		["FM","Micronesia"],
		["MD","Moldova"],
		["MC","Monaco"],
		["MN","Mongolia"],
		["MS","Montserrat"],
		["MZ","Mozambique"],
		["MM","Myanmar"],
		["NA","Namibia"],
		["NR","Nauru"],
		["NL","Nederland"],
		["NP","Nepal"],
		["AN","Netherlands Antilles"],
		["NC","New Caledonia"],
		["NZ","New Zealand"],
		["NI","Nicaragua"],
		["NE","Niger"],
		["NG","Nigeria"],
		["NU","Niue"],
		["NF","Norfolk Island"],
		["NO","Norge"],
		["MP","Northern Mariana Islands"],
		["OM","Oman"],
		["XX","Other-Not Shown"],
		["PK","Pakistan"],
		["PW","Palau"],
		["PS","Palestinian Territories"],
		["PA","Panama"],
		["PG","Papua New Guinea"],
		["PY","Paraguay"],
		["PE","Peru"],
		["PH","Philippines"],
		["PN","Pitcairn"],
		["PL","Polska"],
		["PT","Portugal"],
		["PR","Puerto Rico"],
		["QA","Qatar"],
		["RE","Reunion"],
		["RO","Romania"],
		["RU","Russia"],
		["RW","Rwanda"],
		["KN","Saint Kitts and Nevis"],
		["LC","Saint Lucia"],
		["VC","Saint Vincent and the Grenadines"],
		["WS","Samoa"],
		["SM","San Marino"],
		["ST","Sao Tome and Principe"],
		["SA","Saudi Arabia"],
		["CS","Schweiz"],
		["SN","Senegal"],
		["SC","Seychelles"],
		["SL","Sierra Leone"],
		["SG","Singapore"],
		["SK","Slovakia"],
		["SI","Slovenija"],
		["SB","Solomon Islands"],
		["SO","Somalia"],
		["ZA","South Africa"],
		["GS","South Georgia and Sandwich Islands"],
		["ES","Spain"],
		["LK","Sri Lanka"],
		["SH","St Helena"],
		["PM","St Pierre and Miquelon"],
		["SD","Sudan"],
		["CH","Suisse"],
		["SR","Suriname"],
		["SJ","Svalbard and Jan Mayen"],
		["SE","Sverige"],
		["SZ","Swaziland"],
		["SY","Syria"],
		["TW","Taiwan"],
		["TJ","Tajikistan"],
		["TZ","Tanzania"],
		["TH","Thailand"],
		["TG","Togo"],
		["TK","Tokelau"],
		["TO","Tonga"],
		["TT","Trinidad and Tobago"],
		["TN","Tunisia"],
		["TR","Turkiye"],
		["TM","Turkmenistan"],
		["TC","Turks and Caicos Islands"],
		["TV","Tuvalu"],
		["UG","Uganda"],
		["UA","Ukraine"],
		["AE","United Arab Emirates"],
		["GB","United Kingdom (Study Abroad)"],
		["UK","United Kingdom (Study English)"],
		["US","United States (Study Abroad)"],
		["UD","United States (Study English)"],
		["UY","Uruguay"],
		["UM","US Minor Outlying Islands"],
		["UZ","Uzbekistan"],
		["VU","Vanuatu"],
		["VE","Venezuela"],
		["VN","Vietnam"],
		["VG","Virgin Islands (British)"],
		["VI","Virgin Islands (USA)"],
		["WF","Wallis and Futuna Islands"],
		["EH","Western Sahara"],
		["YE","Yemen"],
		["ZR","Zaire"],
		["ZM","Zambia"],
		["ZW","Zimbabwe"])
	
		var text = '';
		
		for(i=0;i<codesCountries.length;i++)
		{
			//default selected to spain
			if(i == 206)
			{
				text += "<option value='"+codesCountries[i][0]+"' selected='selected'>"+codesCountries[i][1]+"</option>";
			}
			else
			{
				text += "<option value='"+codesCountries[i][0]+"'>"+codesCountries[i][1]+"</option>";
			}
		}
		
		return text;
}

function goBack(){
    //enable dropdowns
    document.getElementById('startDates').disabled = ''
    document.getElementById('destinations').disabled = ''
    document.getElementById('flight').disabled = '';    
    document.getElementById('insurance').disabled = '';
    //show book now button
    document.getElementById('stepOneButton').style.display = '';
    //hide go back button
    document.getElementById('goBackButton').style.display = 'none';
    //hide form
    document.getElementById('form').style.display = 'none';
    //hide footer
    //document.getElementById('footer').style.display = 'none';    
}
