function closeModal()
	{
		$(".modalContainer").remove();
		$(".ui-widget-overlay").remove();
	}

function isCallNowCp(cp)
    {
    	if ( (cp == '') || (cp == null) ) {
    		return false;
    	}

    	if ( callnow_cps == undefined ) {
    		return true;
    	}

    	for ( var i = 0; i < callnow_cps.length; i++ ) {
    		var myregexp = new RegExp(callnow_cps[i] + '[09]*', "i");
    		if ( myregexp.test(cp) ) {
    			return true;
    		}
    	}

    	return false;
    }

    function getTrueOrFalse(true_percent)
    {
    	return true_percent >= Math.ceil((Math.random() * 100));
    }

$(document).ready(function ()
{
	if (estara_hash !='undefined')
 	{
 		$.getJSON("http://callcenter.ulisesinteractive.com/estara/activo-"+estara_hash+".html?callback=?",function(data){
 		estara_active = data.active;
 		if(estara_active)
 		{
 			$("#calloption").val(1);
 			$("#horario").prepend("<option value='0' selected='selected'>Selecciona...</option><option value='Ahora mismo'>Ahora mismo</option>");

 		}else{
 			$("#horario").prepend("<option value='0' selected='selected'>Selecciona...</option>");
 		}
 		});
 	}

	 $("#enviar").click(function () {
		 if( ($('#calloption').val() == 1) && ($('[name=horario]').val() != "Ahora mismo"))
		 {
			 $('#calloption').val(2);
		 }

		 if($('[name=horario]').val() == "Ahora mismo")
		 {
			 $('[name=pressed_btn]').val("callnow");
		 }

	 });

});

$(document).ready(function ()
{
    
    $("#nieTR").css('display','none');
    $("[name=nacionalidad]").change(function(){
		e = $(this);
		if(e.val() == '66'){
			 $("#nieTR").css('display','none');
		}else{
			 $("#nieTR").css('display','block');
		}
    });    
   
	//valida el campo del DNI
	function isDNI(dni) {
		numero = dni.substr(0,dni.length-1);
		let = dni.substr(dni.length-1,1);
		numero = numero % 23;
		letra='TRWAGMYFPDXBNJZSQVHLCKET';
		letra=letra.substring(numero,numero+1);
		if (letra!=let) {
			return true;
		}else{
			return false;
		}
	}
	
	// predicción a traves del CP
	$("#cp").blur(function(){
	 	$.getScript("http://services.ulisesmedia.es/getlocationdatafrompostalcode/JS/?cp="+$(this).val(),function(){
	 		if(($("#poblacion").val()=="")&&($("#pais").val()=="66")){
	 			$("#idprovincia").val(location_provincia);
	 			$("#poblacion").val(location_poblacion)
	 		}
 		});
	});

	
	$("[name=idconociste]").change(function(){
		e = $(this);
		var tipo= $("option:selected", this).attr("rel");		
		$.get("ajax-listado-conocio-"+e.val(),function(data){
			if(data){				
				$("#idconocistetipo").parent().css('display','block');				
				$("#tipoconocio").html(tipo);
				$("#idconocistetipo").html(data);
			}else{				
				$("#idconocistetipo").parent().css('display','none');
			}
			
		});
	});
	

        $("#enviar").click(function () {
     
		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 		= $('[name=nombre]').val();
		var apellidos   = $('[name=apellidos]').val();
		var edad 		= $('[name=edad]').val();
		var fechanac    = $('[name=fechanac]').val();
		var nac_d 		= $('[name=nac_d]').val();
		var nac_m 		= $('[name=nac_m]').val();
		var nac_y	 	= $('[name=nac_y]').val();
		var telefono    = $('[name=telefono]').val();
		var telefono2    = $('[name=telefono2]').val();
		var email 		= $('[name=email]').val();
		var direccion   = $('[name=direccion]').val();
		var numero 		= $('[name=numero]').val();
		var cp 			= $('[name=cp]').val();
		var poblacion   = $('[name=poblacion]').val();
		var provincia   = $('[name=idprovincia]').val();
        var pais  		= $('[name=pais]').val();
		var nacionalidad= $('[name=nacionalidad]').val();
		var nie 		= $('[name=dniNie]').val();
		var alerta 		= '';

               
                if ($('[name=nombre]').length > 0)
                {
                    if((nombre == '') || (!isNaN(nombre)))
                    {
                            alerta = "Debes introducir tu Nombre.\n";
                            ok_cupon = false;
                            //_gaq.push(['_trackEvent', 'Errores Formulario', 'Sin Nombre']);
                    }
                }

                 if ($('[name=apellidos]').length > 0)
                 {
                    if((apellidos == '') || (!isNaN(apellidos)))
                    {
                            alerta = alerta + "Debes introducir tus Apellidos.\n";
                            ok_cupon = false;
                            //_gaq.push(['_trackEvent', 'Errores Formulario', 'Sin Apellidos']);
                    }
                 }

                if ($('[name=edad]').length > 0)
                {
                    if(typeof edad != 'undefined' && ((edad == '') || (isNaN(edad)) || (edad.length != 2)))
                    {
                            alerta = alerta + 'Debes introducir tu Edad.\n';
                            ok_cupon = false;
                            //_gaq.push(['_trackEvent', 'Errores Formulario', 'Sin Edad']);
                    }
                }

                if ($('[name=nac_d]').length > 0 && $('[name=nac_m]').length > 0 && $('[name=nac_y]').length > 0)
                {
                    if((typeof nac_d != 'undefined' && typeof nac_m != 'undefined' && typeof nac_y != 'undefined') && ((nac_d == 0) || (nac_m == 0) || (nac_y == 0)))
                    {
                            alerta = alerta + 'Debes introducir tu Fecha de Nacimiento.\n';
                            ok_cupon = false;
                            //_gaq.push(['_trackEvent', 'Errores Formulario', 'Sin Fecha de Nacimiento']);
                    }
                }

                if ($('[name=fecha_nac]').length > 0)
                {
                    if(typeof fechanac != 'undefined' && (fechanac == '' || !/^((((0[13578])|([13578])|(1[02]))[\/](([1-9])|([0-2][0-9])|(3[01])))|(((0[469])|([469])|(11))[\/](([1-9])|([0-2][0-9])|(30)))|((2|02)[\/](([1-9])|([0-2][0-9]))))[\/]\d{4}$|^\d{4}$/.test(fechanac)))
                    {
                            alerta = alerta + "Debes introducir tu Fecha de Nacimiento (dd/mm/aaaa).\n";
                            ok_cupon = false;
                            //_gaq.push(['_trackEvent', 'Errores Formulario', 'Sin Fecha de Nacimiento']);
                    }
                }

                if ($('[name=telefono]').length > 0)
                {   
                	if ($('[name=telefono2]').length > 0)
                    { 
                		if((telefono == '')&&(telefono2 == '')){
                			alerta = alerta + "Debes introducir tu Teléfono o tu Móvil.\n";
                            ok_cupon = false;
                            //_gaq.push(['_trackEvent', 'Errores Formulario', 'Sin Telefono']);
                		}else if((telefono != '')&&(telefono2 == '')){
                			if(!es_telefono.test(telefono) || telefono_incorrecto.test(telefono)){
                				alerta = alerta + "El Teléfono no es correcto.\n";
	                            ok_cupon = false;
	                            //_gaq.push(['_trackEvent', 'Errores Formulario', 'Formato telefono no valido']);
                			}                			
                		}else if((telefono == '')&&(telefono2 != '')){
                			if(!es_telefono.test(telefono2) || telefono_incorrecto.test(telefono2)){
                				alerta = alerta + "El Móvil no es correcto.\n";
	                            ok_cupon = false;
	                            //_gaq.push(['_trackEvent', 'Errores Formulario', 'Formato Telefono no valido']);
                			}  
                		}else{
                			if(!es_telefono.test(telefono) || telefono_incorrecto.test(telefono)){
                				alerta = alerta + "El Teléfono no es correcto.\n";
	                            ok_cupon = false;
	                            //_gaq.push(['_trackEvent', 'Errores Formulario', 'Formato Telefono no valido']);
                			} 
                			if(!es_telefono.test(telefono2) || telefono_incorrecto.test(telefono2)){
                				alerta = alerta + "El Móvil no es correcto.\n";
	                            ok_cupon = false;
	                            //_gaq.push(['_trackEvent', 'Errores Formulario', 'Formato Telefono no valido']);
                			}
                		}
                		
                    	
                    }else{
	                	if((telefono == '') || (isNaN(telefono)) || ((telefono.length) > 9))
	                    {
	                            alerta = alerta + "Debes introducir tu Teléfono.\n";
	                            ok_cupon = false;
	                            //_gaq.push(['_trackEvent', 'Errores Formulario', 'Sin Telefono']);
	                    }
	                    else if(!es_telefono.test(telefono))
	                    {
	                            alerta = alerta + "El Teléfono no es correcto.\n";
	                            ok_cupon = false;
	                            //_gaq.push(['_trackEvent', 'Errores Formulario', 'Formato Telefono no valido']);
	                    }
	                    else if(telefono_incorrecto.test(telefono))
	                    {
	                            alerta = alerta + "El Teléfono no es correcto.\n";
	                            ok_cupon = false;
	                            //_gaq.push(['_trackEvent', 'Errores Formulario', 'Formato Telefono no valido']);
	                    }
                    }
                	
                }
              	

                if ($('[name=email]').length > 0)
                {
                    if((email == '') || (!validar_email(email)))
                    {
                            alerta = alerta + 'Debes introducir tu Email.\n';
                            ok_cupon = false;
                            //_gaq.push(['_trackEvent', 'Errores Formulario', 'Sin Email o no correcto']);
                    }
                }

                if ($('[name=direccion]').length > 0)
                {
                    if((direccion == '') || (!isNaN(direccion)))
                    {
                            alerta = alerta + "Debes introducir tu Dirección.\n";
                            ok_cupon = false;
                            //_gaq.push(['_trackEvent', 'Errores Formulario', 'Sin Direccion']);
                    }
                }
		
		if ($('[name=numero]').length > 0)
		{
                    if((numero == '') || (isNaN(numero)))
                    {
                            alerta = alerta + 'Debes introducir tu Número.\n';
                            ok_cupon = false;
                            //_gaq.push(['_trackEvent', 'Errores Formulario', 'Sin Numero en la Direccion']);
                    }
		}


		if ($('[name=cp]').length > 0)
                {
                    if (pais == 66)
                    {
                        if((isNaN(cp)) || (cp.length != 5))
                        {
                                alerta = alerta + 'Debes introducir el Código Postal.\n';
                                ok_cupon = false;
                                //_gaq.push(['_trackEvent', 'Errores Formulario', 'Codigo Postal ES, No valido']);
                        }
                    }
                    else
                    {
                                alerta = alerta + 'Debes introducir el Código Postal.\n';
                                ok_cupon = false;
                                //_gaq.push(['_trackEvent', 'Errores Formulario', 'Sin Codigo Postal']);
                    }
                }
		
                if ($('[name=poblacion]').length > 0)
                {
                    if(!isNaN(poblacion))
                    {
                            alerta = alerta + "Debes introducir tu Población.\n";
                            ok_cupon = false;
                            //_gaq.push(['_trackEvent', 'Errores Formulario', 'Sin Poblacion']);
                    }
                }

		//VALIDACION NIE
               
		if ($('#nieTR').css('display')!='none')
		{	
			
			if(nacionalidad != 66)
			{
				var numero = parseInt( nie.substr(1,nie.length-1))%23;
				
				if((nie == '') || (!isNaN(nie)))
				{
					alerta = alerta + "Debes introducir tu NIE.\n";
					ok_cupon = false;
					//_gaq.push(['_trackEvent', 'Errores Formulario', 'Sin NIE']);
				}
				else if ( (!/^[YyXx]\d{1,8}[A-Za-z]$/.test(nie)) || ('TRWAGMYFPDXBNJZSQVHLCKE'.substring(numero,numero+1) != nie.substring(nie.length-1).toUpperCase()) )
				{
					alerta = alerta + "Debes introducir un NIE válido.\n";
					ok_cupon = false;
					//_gaq.push(['_trackEvent', 'Errores Formulario', 'NIE no valido']);
				}
			}else{
				if((nie != '') && (isDNI(nie)))
				{
					alerta = alerta + "Debes introducir tu DNI.\n";
					ok_cupon = false;
					//_gaq.push(['_trackEvent', 'Errores Formulario', 'Sin DNI']);
				}
			}
		}

                if ($('[name=avisoLegal]').length > 0)
                {
                    if (!validaLegales())
                    {
                            alerta = alerta + "Debes leer y aceptar el aviso legal.\n";
                            ok_cupon = false;
                            //_gaq.push(['_trackEvent', 'Errores Formulario', 'Sin Aviso Legal']);
                    }
                }

		if( ok_cupon )
		{
			//_gaq.push(['_trackEvent', 'Formulario', 'Enviado Correctamente']);
			//_gaq.push(['_trackEvent', 'Formulario', 'Intento de envio']);
			//_gaq.push(['_trackEvent', 'Tiempo Formulario', $.time.getSeconds("display",20)]);
			//_gaq.push(['_trackEvent', 'Tiempo Solo Formulario', $.time.getSeconds("form",20)]);
			$('#enviar').attr('disabled', 'disabled');
			$('#cupon').submit();
			return true;
		}
		else
		{
		    //_gaq.push(['_trackEvent', 'Formulario', 'Intento de envio']);
		    //_gaq.push(['_trackEvent', 'Formulario', 'Envio Fallido']);
		    //_gaq.push(['_trackEvent', 'Errores Formulario', 'Total de Errores']);
			alert("Hemos detectado datos incorrectos en el formulario. Por favor, revisa los siguientes campos:\n\n"+alerta);
			return false;
			
		}
	});

	$(".modal").click(function(){
		  $("<iframe id='modalpage' src='"+$(this).attr('href')+"' border='0' scrolling='auto'  frameborder='0'></iframe>").dialog({
			modal:true,
			resizable:false,
			closeOnEscape: true,
			width:870,
			height:600,
			dialogClass : 'modalContainer',
			show: 'slide',
			hide: 'slide',
			overlay: { backgroundColor: "#000", opacity: 0.9 }
		});

		$('.modalContainer iframe').css({width:850,height:600});

		$(".ui-widget-overlay").click(function(){
		   $(".modalContainer").remove();
		   $(this).remove();
		});


		return false;
	});



	
});

function validar_email(email){
	var str = email;
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(str)){
		return true;
	} else {
		
		return false;
	}
}

function validaLegales()
{
	return $('#avisoLegal').is(':checked');
}

// Objeto para medir el tiempo de envio del formulario en Analytics

$.time = {
	timeStart : [],
	start : function (id) { var now = new Date(); this.timeStart[id] = now.getTime(); },
	getSeconds : function ( id, secondsIntervals ) {
		var now =  new Date();
		var seconds = now.getTime() - $.time.timeStart[id] - 10;
		var secondsGroup =  ( Math.ceil(seconds/(secondsIntervals*1000))  * secondsIntervals );
		return "de " + (secondsGroup-secondsIntervals) + " a " + secondsGroup + " segundos";  
	} 
}

/// Added
 var tracked_events = {
 	fields : []
 };
$(document).ready(function () {

// Empezando a medir
$.time.start("display");


 $('form#cupon input,form#cupon select').change(function () {
 	if (!tracked_events.inicioForm)
 	{
	     $.time.start("form");
 		//_gaq.push(['_trackEvent', 'Formulario', '1er campo form rellenado']);
 		tracked_events.inicioForm = true;
 	}
	else if (tracked_events.inicioForm && !tracked_events.secondFieldForm)
	{
	     //_gaq.push(['_trackEvent', 'Formulario', '2n campo form rellenado']);
 		tracked_events.secondFieldForm = true;
	}
	else if (tracked_events.inicioForm && tracked_events.secondFieldForm && !tracked_events.thirdFieldForm)
	{
	     //_gaq.push(['_trackEvent', 'Formulario', '3er campo form rellenado']);
 		tracked_events.thirdFieldForm = true;
	}
	else if (tracked_events.inicioForm && tracked_events.secondFieldForm && tracked_events.thirdFieldForm && !tracked_events.fourthFieldForm)
	{
	     //_gaq.push(['_trackEvent', 'Formulario', '4to campo form rellenado']);
 		tracked_events.fourthFieldForm = true;
	}
	else if (tracked_events.inicioForm && tracked_events.secondFieldForm && tracked_events.thirdFieldForm && tracked_events.fourthFieldForm && !tracked_events.fifthFieldForm)
	{
	     //_gaq.push(['_trackEvent', 'Formulario', '5to campo form rellenado']);
 		tracked_events.fifthFieldForm = true;
	}
	else if (tracked_events.inicioForm && tracked_events.secondFieldForm && tracked_events.thirdFieldForm && tracked_events.fourthFieldForm && tracked_events.fifthFieldForm && !tracked_events.sixthFieldForm)
	{
	     //_gaq.push(['_trackEvent', 'Formulario', '6to campo form rellenado']);
 		tracked_events.sixthFieldForm = true;
	}
	else if (tracked_events.inicioForm && tracked_events.secondFieldForm && tracked_events.thirdFieldForm && tracked_events.fourthFieldForm && tracked_events.fifthFieldForm && tracked_events.sixthFieldForm && !tracked_events.seventhFieldForm)
	{
	     //_gaq.push(['_trackEvent', 'Formulario', '7o campo form rellenado']);
 		tracked_events.seventhFieldForm = true;
	}
	else if (tracked_events.inicioForm && tracked_events.secondFieldForm && tracked_events.thirdFieldForm && tracked_events.fourthFieldForm && tracked_events.fifthFieldForm && tracked_events.sixthFieldForm && tracked_events.seventhFieldForm && !tracked_events.eighthFieldForm)
	{
	     //_gaq.push(['_trackEvent', 'Formulario', '8o campo form rellenado']);
 		tracked_events.eighthFieldForm = true;
	}
	else if (tracked_events.inicioForm && tracked_events.secondFieldForm && tracked_events.thirdFieldForm && tracked_events.fourthFieldForm && tracked_events.fifthFieldForm && tracked_events.sixthFieldForm && tracked_events.seventhFieldForm && tracked_events.eighthFieldForm && !tracked_events.ninthFieldForm)
	{
	     //_gaq.push(['_trackEvent', 'Formulario', '9o campo form rellenado']);
 		tracked_events.ninthFieldForm = true;
	}
	else if (tracked_events.inicioForm && tracked_events.secondFieldForm && tracked_events.thirdFieldForm && tracked_events.fourthFieldForm && tracked_events.fifthFieldForm && tracked_events.sixthFieldForm && tracked_events.seventhFieldForm && tracked_events.eighthFieldForm && tracked_events.ninthFieldForm && !tracked_events.tenthFieldForm)
	{
	     //_gaq.push(['_trackEvent', 'Formulario', '10o campo form rellenado']);
 		tracked_events.tenthFieldForm = true;
	}

 	


 	var fieldName = $(this).attr("name");
 	if (!tracked_events.fields[fieldName] )
 	{
 		//_gaq.push(['_trackEvent', 'Campos Formulario Cambiados', fieldName]);
 		tracked_events.fields[fieldName] = true;
 	}
 });

 $('#bot-columna').click(function () {
 	// Tracking en Analytics:
 	if (!tracked_events.inicioClick)
 	{
 		//_gaq.push(['_trackEvent', 'Formulario', 'Click en el Boton "Informate"']);
 		tracked_events.inicioClick = true;
 	}
	setTimeout(function () { $("form#cupon input[name=nombre]").focus(); }, 500);
});




});
