//valida el campo del NIE
function calcularNIE(dni) {
	if ((!/^[Yy]{1}\d{1,8}[A-Za-z]{1}$/.test(dni)) && (!/^[Xx]{1}\d{1,8}[A-Za-z]{1}$/.test(dni))) {
		return false;
	} else {
		var letras = 'TRWAGMYFPDXBNJZSQVHLCKE';
		var numero = dni.substr(1,dni.length-1);
		while (numero.substr(0,1) == '0') {
			numero = numero.substr(1,numero.length);
		}
		numero = parseInt(numero)%23;
		if (letras.substring(numero,numero+1) != dni.substring(dni.length-1).toUpperCase()) {return false;}
		else {return true;}
	}
}
function isNie(nie) {

if (!(/^[XxTtYy]{1}[0-9]{7}[a-zA-Z]{1}$/.test(nie)) && nie!=""){
	return false;
}
return true;
}

var calloption =0;	

$(document).ready(function ()
{
	
	
	$(".print").click(function(){
		window.print();
	});

	$(".popupAvisoLegal").click(function(){
		window.open(this.href,null,'width=440,height=510,scrollbars=yes');
		return false;
	});
	
	$(".popupBasesLegales").click(function(){
		window.open(this.href,null,'width=700,height=510,scrollbars=yes');
		return false;
	});

	$(".popupFormacionAcreditada").click(function(){
		window.open(this.href,null,'width=700,height=450,scrollbars=yes,toolbar=no,resizable=no');
		return false;
	});


	$(".callEstara").click(function(){
		var callphone = $("div#estara").getValueFromVarInClass('phoneToCall');
		var template = $("div#estara").getValueFromVarInClass('template');
		var leadId = $("div#estara").getValueFromVarInClass('linkId');

		jsUri = 'https://as00.estara.com/as/InitiateCall2.jsp?accountid=200106282377&Template='+template;
		$.getScript(jsUri, function(){
			$.post("estara-precallback", { linkId: leadId },
				function(data){
					webCallBack('Template='+template,'phone1=34'+callphone);
			}, "json");
		});
	});
	/* ----------------------- LEAD-2-CALL ------------------------------ */
	if(calloption == 1){
		$("select#pais").change(function(){
			$(".callnow").css('display','none');
			if($(this).val()=='España'){			
				if (estara_hash !='undefined')
			 	{					
					$.getJSON("http://callcenter.ulisesinteractive.com/estara/activo-"+estara_hash+"-"+$("#pais option:selected").text()+".html?callback=?",function(data){
				 		estara_active = data.active;			 		
				 		if(estara_active)
				 		{
				 			$(".callnow").css('display','block');
				 		}
			 		});
			 	}				
			}	
		});
		$("select#pais").change();
	}
	/* ----------------------------------------------------------------- */
	$(".usoLegal").click(function(){
		window.open(this.href,null,'width=465, height=278, scrollbars=yes');
		return false;
	});

	$("#robinson").click(function(){
		checkParentField('robinson',$(this).is(':checked') );
	});

	$("#lssi").click(function(){
		checkParentField('lssi',$(this).is(':checked') );
	});

	$("#lssi2").click(function(){
		checkParentField('lssi2',$(this).is(':checked') );
	});


	$("#aceptarAviso").click(function(){
		checkParentField('robinson',$("#robinson").is(':checked') );
		checkParentField('lssi',$("#lssi").is(':checked') );
		checkParentField('lssi2',$("#lssi2").is(':checked') );
		window.opener.$("#inputAvisoLegal").attr("checked","checked");
		window.close();
	});

	var checkParentField = function(parentFieldName, checked) {
		if(checked){
			window.opener.$("#"+parentFieldName).attr("value","1");
		}else{
			window.opener.$("#"+parentFieldName).attr("value","0");
		}
	};

	$("select#nacionalidad").change(function(){
		setNifLabel();
	});

	var setNifLabel = function(){
		if (isEuropeanCountry($("select#nacionalidad").val())){
			$("#DNITexto").show();
			$("#NIETexto").hide();
		} else {
			$("#DNITexto").hide();
			$("#NIETexto").show();
		}
	};
	setNifLabel();

	var newsletterEmailValue = $('#newsletterEmail').val();
	$('#newsletterEmail')
	.click(function(){
		if($(this).val() != newsletterEmailValue) return;
		$(this).attr('value', '');
		$(this).addClass('normal');
	})
	.blur(function(){
		if($(this).val() != '') return;
		$(this).removeClass('normal');
		$(this).attr('value', newsletterEmailValue);
	});

	$('#submitNewsletter').click(function(){
		var email = $('#newsletterEmail').val();
		if((email == '') || (!validateEmail(email)))
		{
			alert('Por favor, revisa e introduce correctamente tu e-mail.');
			return false;
		}
		if(!$('#inputAvisoLegal').is(':checked'))
		{
			alert('Por favor, Lee el aviso legal y marca la casilla para aceptarlo.');
			return false;
		}
		$.post("newsletter-subscription", { 'email': email },
			function(resp){
				$('#newsletterResponse').remove();
				var className = 'newsletterOk';
				if(!resp['ok']) className = 'newsletterError';
				$('#newsletterEmail').before('<p id="newsletterResponse" class="'+className+'">'+resp['desc']+'</p>')
				$('#newsletterResponse').hide().slideDown("normal");
			}, "json");
		return false;
	});

	$("#sendLead").click(function () {

		//var es_telefono_fijo=/^(6|8|9)[0-9]{8}$/;
		//var es_telefono_movil=/^(6|8|9)[0-9]{8}$/;
		var es_telefono	=/^(6|8|9)[0-9]{8}$/;
		var telefono_incorrecto = /0{6,}|1{6,}|2{6,}|3{6,}|4{6,}|5{6,}|6{6,}|7{6,}|8{6,}|9{6,}/;
		var ok_cupon 	= true;
		var nombre 		= $('#nombre').val();
		var apellidos 	= $('#apellidos').val();
		var email 		= $('#email').val();
		var telefono 	= $('#telf1').val();
		var telefono2 	= $('#telf2').val();
		var sexo 		= $('input[name=sexo]:checked').val();
		var pais 		= $('#pais').val();
		var nacionalidad= $('#nacionalidad').val();
		var nif			= $('#nif').val();
		var dia 		= $('#dia').val();
		var mes 		= $('#mes').val();
		var anyo 		= $('#anyo').val();
		var alerta 		= '';
		
		if((nombre == '') || (!isNaN(nombre)))
		{
			alerta = "Debes introducir tu Nombre.\n";
			ok_cupon = false;
		}
		if((apellidos == '') || (!isNaN(apellidos)))
		{
			alerta = alerta + "Debes introducir tus Apellidos.\n";
			ok_cupon = false;
		}
		if(!isDate(anyo + '/' + mes + '/' + dia)){
			alerta = alerta + "Debes introducir un Año de nacimiento.\n";
			ok_cupon = false;
		}
		/*if(sexo == undefined)
		{
			alerta = alerta + "Debes introducir tu Sexo.\n";
			ok_cupon = false;
		}*/
		if( telefono == '' || isNaN(telefono) )
		{
			alerta = alerta + "Debes introducir tu Teléfono (Fijo o Móvil).\n";
			ok_cupon = false;
		}		

		if (pais == 'España')
		{
			if(telefono != '' && !isNaN(telefono) && (!es_telefono.test(telefono) || telefono_incorrecto.test(telefono)))
			{
				alerta = alerta + "El Teléfono 1 no es correcto.\n";
				ok_cupon = false;
			}

			if(telefono2 != '' && !isNaN(telefono2) && !es_telefono.test(telefono2))
			{
				alerta = alerta + "El Teléfono 2 no es correcto.\n";
				ok_cupon = false;
			}
		}
		if((email == '') || (!validateEmail(email)))
		{
			alerta = alerta + 'Debes introducir tu Email.\n';
			ok_cupon = false;
		}
		if((pais == '') || (!isNaN(pais)))
		{
			alerta = alerta + 'Debes introducir tu País de residencia.\n';
			ok_cupon = false;
		}
		if((nacionalidad == '') || (!isNaN(nacionalidad)))
		{
			alerta = alerta + 'Debes introducir tu Nacionalidad.\n';
			ok_cupon = false;
		}
		
		if(!isEuropeanCountry(nacionalidad) && nif == '')
		{
			alerta = alerta + 'Debes introducir tu NIE.\n';
			ok_cupon = false;
		}else if(!isEuropeanCountry(nacionalidad) && (nif == '' || !isNie(nif))){
			alerta = alerta + 'Introduce tu Número de Identificacion de Extranjero (NIE). No utilices ni puntos ni guiones.\nDebe tener un formato parecido al siguiente ejemplo: X/Y00000000A.\n';
			ok_cupon = false;
		}
		
		if ( $('#nivel').length > 0)
		{
			if ( $('#nivel').val() < 4)
			{
				alerta = alerta + 'Para poder realizar este Programa de Especialización es necesario haber superado el bachillerato, formación de Grado Medio, o superior. Tus datos no han sido almacenados.\n';
				ok_cupon = false;
			}
		}
		
		if (!$('#inputAvisoLegal').is(':checked'))
		{
			alerta = alerta + "Lee el aviso legal y marca la casilla para aceptarlo.";
			ok_cupon = false;
		}

		if( ok_cupon )
		{
			if(calloption == 1){
				if($('.callnow').css('display')=='none'){			
					$('#calloption').val('0');			
				}else{
					if($('#click2call').is(':checked')){				
						$('#calloption').val('2');
					}else{
						$('#calloption').val('1');
					}
				}
			}
			$('#sendLead').attr('disabled', 'disabled');
			$("#leadForm").submit();
		}
		else
		{
			alert("Hemos detectado datos incorrectos en el formulario. Por favor, revisa los siguientes campos:\n\n"+alerta);
			return false;
		}
	});
});

(function($){
	$.fn.getValueFromVarInClass = function( varName ) {
		if(varName=='' || this.length==0) return false;
		var objFound = this.find("[class*="+varName+"]").andSelf();
		for (i=0; i<objFound.length; i++){
			var classes = $(objFound[i]).attr("class").split(' ');
			for (j in classes){
				var variable = classes[j].substr(0,classes[j].indexOf('='));
				if (variable == varName)
					return classes[j].substr(classes[j].indexOf('=')+1);
			}
		}
		return false;
	};
})(jQuery);

function validateEmail(email){
	var str = email;
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(str)){
		return true;
	} else {
		return false;
	}
}

function isEuropeanCountry(country){
	var europeanCountries = new Array("Andorra", "Alemania", "Austria", "Bélgica", "Chipre", "Dinamarca", "España", "Eslovaquia", "Eslovenia", "Estonia", "Finlandia", "Francia", "Grecia", "Holanda", "Hungría", "Irlanda", "Islandia", "Italia", "Letonia", "Liechtenstein", "Lituania", "Luxemburgo", "Malta", "Noruega", "Polonia", "Portugal", "Reino Unido", "República Checa", "Suecia");
	for(i=0;i<europeanCountries.length;i++) {
		if (country == europeanCountries[i]) return true;
	}
	return false;
}

/* Functions to check dates */
function isInteger(s){
	var i;
		for (i = 0; i < s.length; i++){
				// Check that current character is number.
				var c = s.charAt(i);
				if (((c < "0") || (c > "9"))) return false;
		}
		// All characters are numbers.
		return true;
}

function stripCharsInBag(s, bag){
	var i;
		var returnString = "";
		// Search through string's characters one by one.
		// If character is not in bag, append to returnString.
		for (i = 0; i < s.length; i++){
				var c = s.charAt(i);
				if (bag.indexOf(c) == -1) returnString += c;
		}
		return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
	// EXCEPT for centurial years which are not also divisible by 400.
	return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
	}
	return this
}

function isDate(dtStr){
	// Date must be in the format yyyy/mm/dd
	var dtCh= "/";
	var minYear=1900;
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	if (pos1==-1 || pos2==-1){
		return false
	}
	var year=parseInt(dtStr.substring(0,pos1));
	var month=parseInt(dtStr.substring(pos1+1,pos2));
	var day=parseInt(dtStr.substring(pos2+1));
	if (isNaN(year) || isNaN(month) || isNaN(day)){
		return false;
	}
	if (month<1 || month>12){
		return false
	}
	if (year==0 || year<minYear){
		return false
	}
	if (day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		return false
	}
	return true
}
