//----COMPROBAR FORMS
//Filtros
var filters = {
    required: function(el) {return ($(el).val() != '' && $(el).val() != -1);},
    number: function(el) {return ($(el).val()=='' || !isNaN($(el).val()))},
	
	email: function(el) {return /^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/.test($(el).val());},
    telefono: function(el){return /^[0-9]*$/.test($(el).val());},
	isChecked: function(el) {
			result=false; 
			$("form").find("input").each(function(y,radio) {
				if (radio.name==el.name) {if (radio.checked) result=true;}
			});
			return result;
	},
	nomultiples: function (el) {return (/[;.\/,]/.test($(el).val())?false:true);},
	coincideClave: function(el) {return $(el).val()==$("#CLAVE").val();},
	isImage: function(el) {valor=$(el).val(); return (valor != '' && (valor.indexOf('jpg')>0 || valor.indexOf('jpeg')>0 || valor.indexOf('gif')>0));}
};	
// Extensiones
$.extend({
	stop: function(e){
        if (e.preventDefault) e.preventDefault();
        if (e.stopPropagation) e.stopPropagation();
    }
});
// Código
$(document).ready(function(){
	$("form").bind("submit", function(e){
		//Limpiamos las clases de error anteriores si las hay
		$(this).find(".error").removeClass("error");
		$(this).find(".errorSpan").removeClass("errorSpan");
		
		if (typeof filters == 'undefined') return;
	    $(this).find("input, textarea, select").each(function(x,el){
	        if ($(el).attr("className") != 'undefined') {
	        $.each(new String($(el).attr("className")).split(" "), function(x, klass){
	            if ($.isFunction(filters[klass]))
	                if (!filters[klass](el))  {
						//Definimos las clases de error
						$(el).addClass("error");
						$(el.parentNode).addClass("errorSpan");
					}
			});
	        }
	    });
		if ($(this).find(".error").size() > 0) {
			$.stop(e || window.event);
			$(this).find(".error:first").focus();
			
			//Movemos scroll hasta el error
			var targetOffset = $(this).find(".error:first").offset().top;
			targetOffset-=30;
			$('html, body').animate({scrollTop: targetOffset}, 1000);	
			//Fin movimiento scroll hasta el error
			
			return false;
		}
	    return true;
	});
});
//---- FIN COMPROBAR FORMS


//Funciones de inicio
$(document).ready(function () {
    //Convertimos los enlaces que tengan clase external a blank
	$("a.external").attr('target', '_blank');
});


//Funciones para el cálculo de las inscripciones
var importe=hotel1=hotel2=curso=noches=0;

function number_format( number, decimals, dec_point, thousands_sep ) {
    var i, j, kw, kd, km;
    if( isNaN(decimals = Math.abs(decimals)) ) decimals = 2;
    if( dec_point == undefined ) dec_point = ",";
    if( thousands_sep == undefined ) thousands_sep = ".";
    i = parseInt(number = (+number || 0).toFixed(decimals)) + "";
    if( (j = i.length) > 3 ){
        j = j % 3;
    } else{
        j = 0;
    }
    km = (j ? i.substr(0, j) + thousands_sep : "");
    kw = i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands_sep);
    kd = (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).slice(2) : "");
    return km + kw + kd;
}

function sumarCurso(valor) {
	curso=valor;
	recalcular();
}
function sumarHotel(valor1,valor2) {
	hotel1=valor1;
	hotel2=valor2;
	recalcular();
}
function numNoches() {
	if ($("#f_llegada").val()!='' && $("#f_salida").val()!='') {
		var fecha1 = new fecha( $("#f_llegada").val() );     
	   	var fecha2 = new fecha( $("#f_salida").val() );
		var miFecha1 = new Date( fecha1.anio, fecha1.mes, fecha1.dia );  
		var miFecha2 = new Date( fecha2.anio, fecha2.mes, fecha2.dia ); 
		var diferencia = miFecha2.getTime() - miFecha1.getTime();  
		var dias = Math.floor(diferencia / (1000 * 60 * 60 * 24)); 
		if (dias>0) {
			noches=dias;
			$("#f_llegada").removeClass("error");
			$("#f_salida").removeClass("error");
			recalcular();
		} else {
			noches=0;
			recalcular();
			$("#f_llegada").addClass("error");
			$("#f_salida").addClass("error");
		}
	}
}
function recalcular() {
	hotel=($("#tipo_habitacion").val()=='individual')?hotel1:hotel2;
	//noches=parseInt($("#nr_noches").val());
	importe=(hotel*noches)+(curso*1);
	$("p.importe strong").html(number_format(importe,2,',','.')+' €');
	$("#nrNoches").val(noches);
	$("#importe").val(hotel*noches);
}

function fecha( cadena ) {  
   var separador = "/";
   if ( cadena.indexOf( separador ) != -1 ) {  
        var posi1 = 0;  
        var posi2 = cadena.indexOf( separador, posi1 + 1 );  
        var posi3 = cadena.indexOf( separador, posi2 + 1 );  
        this.dia = cadena.substring( posi1, posi2 );  
        this.mes = cadena.substring( posi2 + 1, posi3 );  
        this.anio = cadena.substring( posi3 + 1, cadena.length );  
   } else {  
        this.dia = 0;  
        this.mes = 0;  
        this.anio = 0;     
   }  
}  
function isDate(dateStr) {
//Se introducen fechas con el formato dd/mm/yyyy o dd-mm-yyyy
    var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
    var matchArray = dateStr.match(datePat); // is the format ok?
	var respuesta = "";
    if (matchArray == null) {
        respuesta+="Por favor, introduzca la fecha con formato dd/mm/yyyy. \n";
		return respuesta;
    }
    month = matchArray[3]; // parse date into variables
    day = matchArray[1];
    year = matchArray[5];

    if (month < 1 || month > 12) { // check month range
        respuesta+="El mes debe tener un valor entre 1 y 12. \n";
		return respuesta;
    }

    if (day < 1 || day > 31) {
        respuesta+="Día debe tener un valor entre 1 y 31. \n";
		return respuesta;
    }

    if ((month==4 || month==6 || month==9 || month==11) && day==31) {
        respuesta+="El mes "+month+" no tiene 31 días! \n";
		return respuesta;
    }

    if (month == 2) { // check for february 29th
        var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
        if (day > 29 || (day==29 && !isleap)) {
            respuesta+="Febrero " + year + " no tiene " + day + " días! \n";
			return respuesta;
        }
    }
	return respuesta;
}
