$(document).ready(function(){

	//Link campus
	$("#link_campus").click(function(evt){
		window.open( evt.target.href );
		return false;
	})

	// Estara

	if( $("#estaraA").length > 0 ){
		$.getJSON( 'http://callcenter.ulisesinteractive.com/estara/activo-106a6c241b8797f52e1e77317b96a201.html?callback=?',
				function( jObj ){
					if( jObj.active ){
						$( ".click2call_container" ).show();
						$( ".estara_hide" ).hide();
					}
					else
					{
						$( ".click2call_container" ).hide();
						$( ".estara_hide" ).show();
					}
		});
	}

	if( $("#estaraT").length > 0 ){
		$.getJSON( 'http://callcenter.ulisesinteractive.com/estara/activo-1009ae9aa1aa14092f4aaf3e0fdc4f00.html?callback=?',
				function( jObj ){
					if( jObj.active ){
						$( ".click2call_container" ).show();
						$( ".estara_hide" ).hide();
					}
					else
					{
						$( ".click2call_container" ).hide();
						$( ".estara_hide" ).show();
					}
		});
	}

	// MODAL WINDOW

	$('.modal').click(function() {
		var capaId = $(this).attr('rel');

		$(capaId).dialog({
			resizable: false,
			closeText: 'Cerrar',
			width: 785
		});
		$('#aceptar').click(function(){
			$(capaId).dialog('close');
		});
		return false;
	});

	var inputs = $('#formulario input[type=text], #formulario textarea, #formulario select');

	// mostrar/ocultar label al hacer click
	inputs.focus(function(event){
		$('label.error').css('display', 'none');
		if($(this).hasClass('error')){
			var thisID = $(this).attr('id');
			var label = $('label[for='+ thisID +'].error');
			label.css('display', 'block');
		}
	});


// class required a inputs
	$('#formulario label:contains("*")').each(function(){
		var thisFor = $(this).attr('for');
		var thisId= $('#formulario [id='+ thisFor +']');
		if( thisId.css( "display" ) != "none" )
		{
			thisId.addClass('required');
		}
	});


// mostrar y requerir CP/Provincia segun Pais elegido
	$('#nacionalidad').change(function(){

		var selPais = $(this).attr('value');
		if (selPais != '67') {
			$('.dniNie').css('display','block');
		}
		else
		{
			$('#dniNie').removeClass( 'required' );
			$('.dniNie').css('display','none');
		}
	});

/*
	$("#cp").blur(function(){
	 	$.getScript("http://services.ulisesmedia.es/getlocationdatafrompostalcode/JS/?cp="+$(this).val(),function(){
	 			$("#provincia").val(location_provincia);
	 			$("#poblacion").val(location_poblacion);
 		});
	});
*/
	//Avisos legales
	$("#legal input[type=checkbox]").click(function(){
		var elem_chk = $('#' + $(this).attr('rel') );
		var chk_val = $(this).is(':checked');
		elem_chk.val(chk_val?0:1);
	});
	$('#aceptar').click(function(){
		$("#avisoLegal").attr('checked','checked');
	});
	// COMO NOS CONOCIO
	$("#idmeet").change(function(){
		e = $(this);
		var tipo= $("option:selected", this).attr("rel");
		$.post("/ajax/meet/","idmeet="+e.val(),function(data){
			if(data){
				$("#idmeettype").parent().css('display','block');
				$("#meettype").html(tipo);
				$("#idmeettype").html(data);
			}else{
				$("#idmeettype").parent().css('display','none');
			}

		});
	});

	//Mostrar Paso 2
	if( $("#language_level").length )
	{
		//$('#landing-form').prev().css('display','block');
		$('#landing-form').css('display','block');
		var topscroll = $( "#landing-form" ).offset().top;
	    $( 'html, body' ).animate( { scrollTop: topscroll }, 'slow' );
	    $( "#landing-form input[type=text]" ).first().focus();
	}

// __________________________________________________________________________________ //
// ____________________________ VALLIDATION _________________________________________ //
// __________________________________________________________________________________ //


	//------------------------------------------------------------------------
	// Custom Method ---------------------------------------------------------

	$.validator.addMethod("telefono", function(value, element) {
		var r = false;
		if( this.optional(element) || /^(6|8|9)[0-9]{8}$/.test(value)){
			r = true;
		}
		if(  /0{6,}|1{6,}|2{6,}|3{6,}|4{6,}|5{6,}|6{6,}|7{6,}|8{6,}|9{6,}/.test(value) ){
			r = false;
		}
		return r;
	});
	$.validator.addMethod("nacimiento", function() {

    	var r = false;
		if(($('#anyo').val() == '') || ($('#mes').val() == '') || ($('#dia').val() == ''))
		{			r = false;
		}else{
			var nacimiento=$('#anyo').val() + "/" + $('#mes').val() + "/" + $('#dia').val();
			r=true;
			var edad=isDate(nacimiento);
			if(edad<18){
				r = false;
			}
		}
		return r;

	});
	$.validator.addMethod("dni", function(value, element) {
		if( $("#nacionalidad").val() != '67' )
			return !isDNI(value);
		else
			return true;
	});

	// End Custom Method -----------------------------------------------------
	//------------------------------------------------------------------------


	$.validator.setDefaults({
		debug: false,
	    errorElement: "label",
	    errorLabelContainer: $('#errorCont'),
	    wrapper: 'li'

	});

	$('#formulario').validate ({
		groups: {
	    	nacimiento: "dia mes anyo"
	  	},
	  	rules: {
	  		'email': { required: true, email: true },
	        'telefono': { required: true, telefono: true },
	        'dia': { required :  true },
	        'mes': { required :  true },
	        'anyo': { required :  true },
	        'dniNie': {
	        	required:   function(elm) {
	              var cnd1 = $("#nacionalidad").val() != '67' ;
	              return cnd1 ? true : false;
            	},
            	rangelength: [0, 9],
            	dni: true
            },
	        'cp': {
	        	required: true,
	            digits: true,
	            rangelength: [5, 5]
	        },
	        'num': {
	        	required: true,
	            digits: true
	        }

	    },
	    messages: {
	        'nombre': "Debe indicar su Nombre.",
	        'apellidos': "Debe indicar sus Apellidos.",
	        'pais': "Debe indicar su pa&iacute;s de residencia.",
	        'cp': "Debe indicar tu c&oacute;digo postal.",
	        'num':"Debe indicar el número.",
	        'how_met':"Debe especificar como conocio esta actividad.",
	        'dia': "Debe indicar su fecha de nacimiento correctamente.",
	        'mes': "Debe indicar su fecha de nacimiento correctamente.",
	        'anyo': "Debe indicar su fecha de nacimiento correctamente.",
	        'nacimiento': "Debes ser mayor de edad.",
	        'telefono': {
	            required: "Debe indicar su tel&eacute;fono.",
	            digits: "Introduzca solo n&uacute;meros.",
	            telefono: "Debe indicar su tel&eacute;fono"
	        },
	        'email': {
	            required: "Debe indicar su E-mail.",
	            email: "Debe indicar un E-mail v&aacute;lido."
	        },
	        'avisoLegal':"Debe aceptar el aviso legal.",
	        'nacionalidad': "Debe seleccionar su nacionalidad.",
	        'direccion': "Debe indicar su Domicilio.",
	        'dniNie': "Debe indicar su NIE/NIF."
	    },
	    submitHandler: function(form){
	    	$( '#solicitar' ).attr( 'disabled', 'disabled' );
	    	form.submit();
	    }
	});

	// Move SI
	$( ".link_si" ).click( function(){
		var topscroll = $( ".si_form" ).offset().top;
		$( 'html, body' ).animate( { scrollTop: topscroll }, 'slow' );
		//$( ".si_form input" ).first().focus();
		return false;
	});

	$('.si_form input[type=text]').focus(function(){
		$(this).prev('label').addClass('detras');
	});

	$('.si_form input[type=text]').blur(function(){
		if ( $(this).val() == '' )
		{
			$(this).prev('label.detras').removeClass('detras');
		}
		ocultarLabels();
	});

	$('.boton').click( showForm );

 });

function showForm(){
	//$('#landing-form').prev().css('display','block');
	$('#landing-form-container').slideDown();
	var topscroll = $( "#landing-form-container" ).offset().top;
    $( 'html, body' ).animate( { scrollTop: topscroll }, 'slow' );
    $( "#landing-form input[type=text]" ).first().focus();
}

function ocultarLabels()
{
	// ocultar labels si hay contenido al refrescar pagina
	$('.si_form input[type=text]').each(function(){
		if ( $(this).val() != '' )
		{
			$(this).prev('label').addClass('detras');
		}
	});
}

//---------------------------------------------------------------- //
//                       Funciones extra                           //
//---------------------------------------------------------------- //

//valida el campo del DNI
function isDNI(dni) {
	var first = dni.substring(0, 1);
	if (first == 'X' || first == 'Y' || first == 'Z') {
		var number = dni.substring(1, 9);
		if (first == 'X') {
			dni = '0' + number
		}
		if (first == 'Y') {
			dni = '1' + number
		}
		if (first == 'Z') {
			dni = '2' + number
		}
	}
	numero = dni.substr(0,dni.length-1);
	let = dni.substr(8,1);
	numero = numero % 23;
	letra='TRWAGMYFPDXBNJZSQVHLCKET';
	letra=letra.substring(numero,numero+1);

	if (letra!=let.toUpperCase()) {
		return true;
	}else{
		return false;
	}
}

function isDate(dtStr){
	// Date must be in the format yyyy/mm/dd
  //calculo la fecha de hoy
  hoy=new Date()
  //alert(hoy)

  //calculo la fecha que recibo
  //La descompongo en un array
  var array_fecha = dtStr.split("/")
  //si el array no tiene tres partes, la fecha es incorrecta
  if (array_fecha.length!=3)
     return false

  //compruebo que los ano, mes, dia son correctos
  var ano
  ano = parseInt(array_fecha[0]);
  if (isNaN(ano))
     return false

  var mes
  mes = parseInt(array_fecha[1]);
  if (isNaN(mes))
     return false

  var dia
  dia = parseInt(array_fecha[2]);
  if (isNaN(dia))
     return false


  //si el año de la fecha que recibo solo tiene 2 cifras hay que cambiarlo a 4
  if (ano<=99)
     ano +=1900

  //resto los años de las dos fechas
  edad=hoy.getFullYear()- ano - 1; //-1 porque no se si ha cumplido años ya este año
//alert(hoy.getMonth()+"+ 1 -"+mes);
//alert(edad);
  //si resto los meses y me da menor que 0 entonces no ha cumplido años. Si da mayor si ha cumplido
  if (hoy.getMonth() + 1 - mes < 0) //+ 1 porque los meses empiezan en 0
     return edad
  if (hoy.getMonth() + 1 - mes > 0)
    return (edad+1)

  //entonces es que eran iguales. miro los dias
  //si resto los dias y me da menor que 0 entonces no ha cumplido años. Si da mayor o igual si ha cumplido
  if (hoy.getUTCDate() - dia >= 0)
     return edad + 1


  return edad
}
