﻿var busquedavalida;

function validarHoteles() 
{
    
    $("#layerError").hide();
    $("#destinoAlert").hide();
    $("#fechaAlert").hide();
    $("#edadesAlert").hide();
    $("#condBusquedaAlert").hide();
	
	if(!hotel_poblacion_check()) {
	    $("#layerError").show();
	    $("#destinoAlert").show();
		return;
    }
    if(!hotel_combo_check()) {
        $("#layerError").show();
	    $("#fechaAlert").show();
		return;
    }
    if(!hotel_o_paquete_edad_check()) {
        $("#layerError").show();
	    $("#edadesAlert").show();
		return;
    }    
    if(!busquedavalida){
        $("#layerError").show();
	    $("#condBusquedaAlert").show();
	    return;
     }
        
    var msg='';
    var poblacion = quitarTilde(document.getElementById("inputString").value)
    var fTemporal;
    if (SID == "MA")
        fTemporal = $("#ctl00_cphPrincipal_Buscador_NewCalendar").val().split(".");
    else
        fTemporal = $("#ctl00_cphPrincipal_Buscador_NewCalendar").val().split("-");
	var fechahotel = fTemporal[2]+"-"+fTemporal[1]+"-"+fTemporal[0];
	
	var cNoches = $("#divComboNoches").children();
	var comboNoches = document.getElementById(cNoches[0].id);            
    var noches = comboNoches.options[comboNoches.selectedIndex].value;	
    
    var cCat = $("#divComboCategoria").children();
	var comboCat = document.getElementById(cCat[0].id);
	var categoria = comboCat.options[comboCat.selectedIndex].value;	
	
	var cReg = $("#divComboRegimen").children();
	var comboReg = document.getElementById(cReg[0].id);
	var regimen = comboReg.options[comboReg.selectedIndex].value;
	
	var cHab = $("#divComboHabitaciones").children();
	var comboHab = document.getElementById(cHab[0].id);
	var habitaciones = comboHab.options[comboHab.selectedIndex].value;
	
    var ocupacion='';
	var edades='';
	var edadTempAux = "";
	var nombresDias;
	var nombresMeses;

	for(var i=1;i<=habitaciones;i++) {
	
		//obtener ocupaciones y edades
		var hab = $("#divComboHabitacion_" + i).children();
		ocupacion += document.getElementById(hab[0].id).value + "/";
		var n = document.getElementById(hab[0].id).value.split("-")[1];
		n = (!n ? 0 : parseInt(n));
		var ed=(n == 0 ? "--" : "");
		for(var j=1;j<=n;j++) {
		edadTempAux =document.getElementById("edad"+i+"-"+j).value + "-";
			//Si peta al cogerlo por JQuery, lo intentamos coger por el metodo tradicional que nunca falla
			if(edadTempAux == "undefined-") {
				edadTempAux = document.getElementById("edad" + i + "-" + j)[document.getElementById("edad" + i + "-" + j).selectedIndex].text + "-";
			}
			ed += edadTempAux;
		}
		ed = ed.substring(0,ed.length-1);
		edades += ed + "/";
	}
	
	ocupacion = ocupacion.substring(0,ocupacion.length-1);
  
    poblacion=trimBuscador(poblacion);
    
    var url='/disponibilidad/resultados.aspx?pob=' + poblacion + '&cat=' + categoria + '&ocupa=' + ocupacion + '&edades=' + edades + '&numhab=' + habitaciones + '&fent=' + fechahotel + '&n=' + noches;
 	//Recuperamos la ruta del servidor del campo oculto en el control
	var rutaServidor = document.getElementById("rutaServidor").value;
    document.location.href= rutaServidor + url;
	return false;
   
    }
    
    function CheckCondBusqueda(){
        
        if(busquedavalida)
        {
            busquedavalida = false;
        }
        else
        {
            busquedavalida = true;
        }   
    
    }


function hotel_poblacion_check() {

if ($("#inputString").val() == '') 
  	{
     return false;
    }
  	else
  	{
    return true;
  	}
   
   
}
function hotel_o_paquete_edad_check() {

    //segurar que los edades estan rellenados
    var allgood = true;
    for(var i=1;i<=$("#ctl00_cphPrincipal_Buscador_habitaciones").attr("value");i++) {
				n = $("#ctl00_cphPrincipal_Buscador_habitacion_" + i).attr("value").split("-")
			n= (n[1]? n[1] : 0);
				for(var j=1;j<=n;j++) {
					if(document.getElementById("edad" + i + "-" + j).selectedIndex == 0) { allgood = false; }
				}
            }
   return allgood;
}


function trimBuscador(cadena) {

    for(i=0; i<cadena.length; )
    {
    if(cadena.charAt(i)==String.fromCharCode(160))
        cadena=cadena.substring(i+1, cadena.length);
    else
    break;
    }

    for(i=cadena.length-1; i>=0; i=cadena.length-1)
    {
    if(cadena.charAt(i)== String.fromCharCode(160))
        cadena=cadena.substring(0,i);
    else
    break;
    }
   
    return cadena;
}


function LTrim(value) {
	var re = /\s*((\S+\s*)*)/;
    return value.replace(re, "$1");
}

function RTrim(value) {
   
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
}

function trim(value) {
    
	return LTrim(RTrim(value));
}

function SetDiasNombre(nombres)
{
	nombresDias = nombres.split(",");
}

function GetDiaNombre(fecha) {
	//fecha tiene que estar en formato dd/mm/yy o d/m/yy o yyyy
	m = fecha.match(/^(\d*)(\/?)(\d*)(\2)(\d\d)?(\d\d)$/);
	m[1] = mLength(m[1]); // 6 -> 06 dia
	m[3] = mLength(m[3]); // 6 -> 06 mes
	m[5] = yLength(m[5]); // 07 -> 2007 anio
	return nombresDias[new Date(m[5] + m[6] + "/" + m[3] + "/" + m[1]).getDay()];
}

function SetMesesNombre(nombres)
{
	nombresMeses = nombres.split(",");
}

function GetMesNombre(fecha) {
	//fecha tiene que estar en formato dd/mm/yy o d/m/yy o yyyy
	m = fecha.match(/^(\d*)(\/?)(\d*)(\2)(\d\d)?(\d\d)$/);
	m[1] = mLength(m[1]); // 6 -> 06 dia
	m[3] = mLength(m[3]); // 6 -> 06 mes
	m[5] = yLength(m[5]); // 07 -> 2007 anio
	return nombresMeses[new Date(m[5] + m[6] + "/" + m[3] + "/" + m[1]).getMonth()];
}

function yLength(y) {
	y = (parseInt(y) < 100 ? "20" + y : y);
	return y;
}
function mLength(m) {
	m = (m.length == 1 ? "0" + m : m);
	return m;
}

function cambiarFechaHotel(fecha) {
	var iArr = fecha.split('/');
	y = yLength(iArr[2]);
	m = mLength(iArr[1]);
	d = mLength(iArr[0]);
	fecha = y + '-' + m + '-' + d;
	return fecha;
}
function quitarTilde(str) {
	rep ={"á":"-aacute","é":"-eacute","í":"-iacute","ó":"-oacute","ú":"-uacute","Á":"-Aacute","É":"-Eacute","Í":"-Iacute","Ó":"-Oacute","Ú":"-Uacute","ñ":"-ntilde","Ñ":"-Ntilde"};
	for(var p in rep) {
		str=str.replace(p,rep[p]);
	}
	return str;
}

//funciones para probar si el formulario puede submit o no
function hotel_combo_check() {

    var newFecha = $("#ctl00_cphPrincipal_Buscador_NewCalendar").val();

    var arrFecha;
    if (SID == "MA")
        arrFecha = newFecha.split(".");
    else
        arrFecha = newFecha.split("-");
    var ndia = arrFecha[0];
    var mes = arrFecha[1];
    var anho = arrFecha[2];

    probarFecha = (ndia + "/" + mes + "/" + anho);
    
	var reg = /^((((0?[1-9]|[12]\d|3[01])[\.\-\/](0?[13578]|1[02])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|[12]\d|30)[\.\-\/](0?[13456789]|1[012])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|1\d|2[0-8])[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|(29[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00)))|(((0[1-9]|[12]\d|3[01])(0[13578]|1[02])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|[12]\d|30)(0[13456789]|1[012])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|1\d|2[0-8])02((1[6-9]|[2-9]\d)?\d{2}))|(2902((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00))))$/;
    if (probarFecha.match(reg)) {
		//probar fecha es mas que ayer y menos que hoy+334
		f =  new Date(mes + "/" + ndia + "/" + anho);
		var fArr = $("#fechaHoy").attr("value").split("/");
		hoy = new Date(fArr[1] + "/" + fArr[0] + "/" + fArr[2]);
		diferenciaDias = Math.round((f - hoy)/(24*60*60*1000));
		if(diferenciaDias < -1 ) {
			return false;
		} else {
			return true
        }
    } else {
        return false;
    } 

}

function pop(pg,t,w,h) {
	window.open(pg,t,'scrollbars=yes,toolbar=no,status=no,resizable=no,width=' + w + ',height=' + h);
}
//manejar popups ej calendarios 
function ninosybebes(callback) {
	if(callback){
		hidepop();
	} else {
		//combo('none');
		load('includes/ninosybebes.aspx', 'formspop');//METER EN EL PROYECTOP ESTA PÁGINA
	}
}
function combo(disp) {
    //apagar o mostrar combos (en ie no puedes flotar elementos encima de un combo)
    for (var f = 0; f < document.forms.length; f++){
        for (var e = 0; e < document.forms[f].length; e++) {
			if(disp =="none") {
				if (document.forms[f].elements[e].options) document.forms[f].elements[e].style.visibility = "hidden";
			} else {
				if (document.forms[f].elements[e].options) document.forms[f].elements[e].style.visibility = "visible";
			}
        }
    }
}
function submitshowhide(val) {
    if(val) {
            $("#buscarDis").hide();
            $("#buscar").show();
    } else {
            $("#buscar").hide();
            $("#buscarDis").show();
    }
}
//funciones generals para manejar fechas etc
function select(id, indice) {	
	document.getElementById(id).selectedIndex=indice;
	
}
function prepDest(cual) {
    v = cual.value
    if (v == "Origen" || v=="Población" || v=="Destino") {
		cual.value="";
		submitshowhide(false);
    }
}

function resetCombos() {
	fecha = $("#fechaEntrada").val();
    var fArr = fecha.split("/");
    var d = fArr[0]-1;
    var m = fArr[1];
    
    var fechaHoy = document.getElementById("fechaHoy").value.split("/");
	var hoy = new Date(fechaHoy[1] + "/" + fechaHoy[0] + "/" + fechaHoy[2]);
    var y = hoy.getFullYear();
    
    var comboMes = $("#divComboMes").children();
    var comboDia = $("#divComboDia").children();
    
    CargarComboDias(comboDia[0].id, m, y)
    
    select(comboDia[0].id, d)
    
    var fechaParaSeleccionar = m + "-" + y;
    comboMes.val(fechaParaSeleccionar);
}
//funciones para probar si el formulario puede submit o no

function fechaCombo()
{    
    if (ComprobarMesDia($("#ctl00_cphPrincipal_Buscador_NewCalendar").val().substring(0,2), $("#ctl00_cphPrincipal_Buscador_NewCalendar").val().substring(3,5)))
    {        
        var fechaDate = new Date($("#ctl00_cphPrincipal_Buscador_NewCalendar").val().substring(6), $("#ctl00_cphPrincipal_Buscador_NewCalendar").val().substring(3,5) - 1, $("#ctl00_cphPrincipal_Buscador_NewCalendar").val().substring(0,2));
        if (SID == "MA")
            $("#fechaEntradaMos").html(" " +ChangeDay(fechaDate.getDay())+", "+fechaDate.getDate()+"."+ArrayMonth[fechaDate.getMonth()]+"."+fechaDate.getFullYear());
        else
            $("#fechaEntradaMos").html(" " + ChangeDay(fechaDate.getDay()) +", " + fechaDate.getDate() + " " + ArrayMonth[fechaDate.getMonth()]+" "+fechaDate.getFullYear());
        fechaDate.setDate(fechaDate.getDate()+parseInt($("#ctl00_cphPrincipal_Buscador_noches").val()));
        
        if (SID == "MA")
            $("#fechaVuelta").html(" " +ChangeDay(fechaDate.getDay())+ ", " + fechaDate.getDate()+"."+ArrayMonth[fechaDate.getMonth()]+"."+fechaDate.getFullYear());
        else
            $("#fechaVuelta").html(" " + ChangeDay(fechaDate.getDay()) +", " + fechaDate.getDate() + " " + ArrayMonth[fechaDate.getMonth()]+" "+fechaDate.getFullYear());
    }
}

function ChangeDay(day)
{
    var dia="";
    dia = ArrayWeek[day];            
    return dia;
}

function ComprobarMesDia(dia, mes)
{
    if ((mes == 1 || mes == 3 || mes == 5 || mes == 7 || mes == 8 || mes == 10 || mes == 12) && dia <=31)
            return true;
    else
    {
        if (mes == "02" && dia <=29)
            return true;
        else
            if (mes != "02" && dia <= 30)
                return true;
            else
                return false;
    }
}
function cambiarOcupacion(which, val) 
{
	var n = val.split('-')[1]; //cuantos niños
    n = (n ?  parseInt(n):0 );
    if (n == 0) 
    {
	    document.getElementById("edades" + which).className='Dnone';
   		for(var i =1;i<4;i++) 
		{ 
		    document.getElementById("edad" + which + "-" + i).className='Vhidden';
		}
    }
    else 
    {
	    document.getElementById("edades" + which ).className='Dblock';
	    
		for(var i =1;i<4;i++) 
		{ 
		    document.getElementById("edad" + which + "-" + i).className='Vhidden';
		}
		for(i=1;i<=n;i++) 
		{ 
	    document.getElementById("edad" + which + "-" + i).className='Vvisible';
		}
	} 
}
function cambiarHabitaciones(val) 
{
	for(var i =1;i<5;i++) 
	{
	    document.getElementById("hab" + i).className='Dnone';
	    document.getElementById("edades" + i).className='Dnone';
	    document.getElementById("edad" + i + "-" + 1).className='Vhidden';
	    document.getElementById("edad" + i + "-" + 2).className='Vhidden';
	    document.getElementById("edad" + i + "-" + 3).className='Vhidden';
	}
	for(i =1;i<=val;i++)
	{
	    document.getElementById("hab" + i).className='Dblock';
	    var hab = $("#divComboHabitacion_" + i).children();
	    document.getElementById(hab[0].id).selectedIndex=4;
	}
}
function fechaHotelCB(fecha) {
    if(fecha){
        $("#fechaEntrada").val(fecha);
        resetCombos();
        $("#fechaEntradaMos").val(fecha + ", "+ GetDiaNombre(fecha));
        fechaHotelVuelta();
    };
    hidepop();
}
function fechaHotelVuelta() {

    var cNoches = $("#divComboNoches").children();
    fecha = $("#fechaEntrada").val();
    n = parseInt($("#" + cNoches[0].id).val());
    var fArr = fecha.split("/");
    var d = fArr[0];
    var m = fArr[1]-1;
    var y = fArr[2];
    var fVuelta=new Date();
    fVuelta.setFullYear(y,m,d);
    fVuelta.setDate(fVuelta.getDate()+n);
    fVuelta = fVuelta.getDate() + "/" + (fVuelta.getMonth()+1) + "/" + fVuelta.getFullYear();
    $("#fechaVuelta").html((GetDiaNombre(fVuelta) + ", " + fVuelta.split('/')[0] + " " + GetMesNombre(fVuelta) + " " + fVuelta.split('/')[2]));
}




function load(src, dest) {
       window.open(src,"xcvb",'scrollbars=yes,toolbar=no,status=no,resizable=no,width=300,height=300');
}
function hidepop() {
        combo('');
        $("#formspop").hide();
}

 
