﻿/*URLS BUSCADOR*/
/*----------------------------------------------------------------*/
var url_hoteles="http://www.muchoviaje.co/hoteles/";
var url_vacaciones="http://www.muchoviaje.co/vacaciones/";
var url_vuelos="http://www.muchoviaje.co/vuelos/";
var url_vuelomashotel="http://www.spanienstrandhotels.de/flugundhotel/";

var nombresDias;
var nombresMeses;

/*FUNCIONES GENERALES*/
/*----------------------------------------------------------------*/
function selecciona(elemento) {
    //ocultamos todas las categorias
    $('.hoteles').hide();
    $('.vacaciones').hide();
    $('.vuelos').hide();
    $('.th').hide();
    $('#Cruceros').hide();
    
    // capturamos el div categoría y el li del menú
    itemcat=$("#div_"+elemento);
    //itemli=$("#li_"+elemento);
    itemli=$("li[name=li_"+elemento+ "]");

    //Mostramos el div de la categoría seleccionada
    $(itemcat).show();
    
    //Marcamos el li del menú según la categoría seleccionada
    $('.selec').removeAttr("class");
    $(itemli).attr("class","selec");   
}

function setCombo(id, indice) {
    $("#"+id).val(indice);
}

function resetCombos(){
resetCombosHoteles();
resetCombosVacaciones();
resetCombosVuelos();
}

//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
//	d =["Domingo","Lunes","Martes","Miércoles","Jueves","Viernes","Sábado","Domingo"];
//	return d[new Date(m[5] + m[6] + "/" + m[3] + "/" + m[1]).getDay()];
//}

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 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;
}

function GetFechaUrl(fecha) {
    if(SID=='MA')
	    var iArr = fecha.split('.');
	else
	    var iArr = fecha.split('/');
	y = yLength(iArr[2]);
	m = mLength(iArr[1]);
	d = mLength(iArr[0]);
	fecha = y + '-' + m + '-' + d;
	return fecha;
}

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()];
}

/*----------------------------------------------------------------*/
/*FUNCIONES HOTELES*/
function BuscarHoteles() 
{
    if (ComprobarCampos())
    {
        $("#layerError").hide();
        var categoria='1';
        var regimen='OB';
	    var poblacion = quitarTilde($("#txtBusqueda").val());
        var fechahotel = GetFechaUrl($("#fechaEntrada").val());
        var noches = document.getElementById(numnoches).value;
	    var habitaciones = document.getElementById(numhab).value;
        var ocupacion='';
	    var edades='';
	    var edadTempAux = "";
    	
	    for(var i=1;i<=habitaciones;i++) {
	    //obtener ocupaciones y edades
	    ocupacion += document.getElementById(eval("habitacion_" + i)).value + "/";
    		
	    var n = document.getElementById(eval("habitacion_" + i)).value.split("-")[1]; //ninos
	    n = (!n ? 0 : parseInt(n));
		    var ed=(n == 0 ? "--" : "");
	    for(var j=1;j<=n;j++) {
			    edadTempAux =$("#edad"+i+"-"+j).val() + "-";
			    ed += edadTempAux;
		    }
		    ed = ed.substring(0,ed.length-1);
		    edades += ed + "/";
	    }
	    ocupacion = ocupacion.substring(0,ocupacion.length-1);
	    var url='Disponibilidad/Resultados.aspx?pob=' + poblacion + '&cat=' + categoria + '&ocupa=' + ocupacion + '&edades=' + edades + '&numhab=' + habitaciones + '&ureg=' + regimen + '&fent=' + fechahotel + '&n=' + noches;
        url = url_hoteles + url;
	    document.location.href=url;
	    return false;
	}
	else
    {
        $("#Error").show();
    }
}

function BuscarCruceros()
{
    var zona = $("#ddlZona").val();
    var company = $("#ddlCompannia").val();
    var fecha = $("#ddlFecha").val();
    var puerto = $("#ddlPuerto").val();
    var precio = $("#ddlPrecio").val();
    var tipo = $("#ddlTipo").val();
    
    //alert(zona + " / " + company + " / " + fecha + " / " + puerto + " / " + precio);
    
    url = "http://reservascruceros.muchoviaje.com/muchocruceros/buscador/Cruceros.aspx?zona=" + zona + "&naviera=" + company + "&mes=" + fecha + "&precio=" + precio + "&tipo=" + tipo + "&puerto=" + puerto
    document.location.href=url;
    return false;
    
    


}

function CompruebaDestino()
{
    if ($("#txtBusqueda").val() == "")
        return false;
    else
        return true;
}

function CompruebaEdades()
{
    var numeroHabitaciones = $("#ctl00_cphPrincipal_ctl00_habitaciones").val();
    for (var i = 0; i< numeroHabitaciones; i++)
    {
        var numHabsSplit = $("#ctl00_cphPrincipal_ctl00_habitacion_"+ (i+1) ).val().split("-");        
        var adultos = numHabsSplit[0];
        var ocupaNi =  numHabsSplit[1];        
        if (ocupaNi != "")
        {
            for (var x=0; x< ocupaNi; x++)
            {
                if ($("#edad"+(i+1)+"-"+(x+1)).val() == "")
                    return false;
            }
        }
        
    }
    return true;
}

function CompruebaCalendario()
{
    if ($("#NewCalendar").val() == "")
        return false;
    
    if (!ValidarFecha(new Date($("#NewCalendar").val().substring(6),($("#NewCalendar").val().substring(3,5)),$("#NewCalendar").val().substring(0,2))))
        return false;
    return true;
}

function ComprobarCampos()
{
    var noError = true;
    var mensajeError = "Se han producido los siguientes errores:<ul>";
    if (!CompruebaDestino())
    {
        noError = noError && false;
        mensajeError += "<li>Debe de introducir un destino</li>";
    }
    if (!CompruebaEdades())
    {
        noError = noError && false;
        mensajeError += "<li>Debe de introducir las edades de los niños</li>";
    }   
    if (!CompruebaCalendario())
    {
        noError = noError && false;
        mensajeError += "<li>Debe de introducir una fecha válida</li>";
    }
    mensajeError += "</ul>";
    if (!noError)
    {
        $("#Error").html(mensajeError);        
        return false;
    }
    else
        return true;
    
}

function ValidarFecha(fechaAnterior)
{                
    if (ComprobarMesDia($("#NewCalendar").val().substring(0,2), $("#NewCalendar").val().substring(3,5)))
    {                    
        var fechaActual = new Date();
        var temporal = new Date(fechaActual.getFullYear(), fechaActual.getMonth(), fechaActual.getDate());
        if (fechaAnterior < temporal)
            return false;
        else return true;
    }
    else
    {
        return false;
    }
}

function cambiarOcupacion(which, val, proyecto) 
{
	var n = val.split('-')[1]; //num niños
	
    n = (!n ? 0 : parseInt(n));
    if (n == 0) 
    {
		for(var i =1;i<4;i++) 
		{ 
		    $("#edad" + which + "-" + i + proyecto).hide();
    	}
	    $("#Habninos" + which + proyecto).hide();
    }
    else 
    {
	    $("#Habninos" + which + proyecto).show();
	    
		for(var i =1;i<4;i++) 
		{ 
		    $("#edad" + which + "-" + i + proyecto).hide();
		}
		for(i=1;i<=n;i++) 
		{ 
		    $("#edad" + which + "-" + i + proyecto).show();
		}
	} 
}


function CambiarNumHabitaciones(val,proyecto) 
{
	for(var i =1;i<5;i++) 
	{
	    $("#cajahab" + i + proyecto).hide();
  
  		for(var x =1;x<4;x++) 
		{ 
		    $("#edad" + i + "-" + x + proyecto).hide();
            $("#habitacion_" + i + proyecto).val(0);
        }
        $("#Habninos" + i + proyecto).hide();
        $("#hab" + i + proyecto).hide();
	    
	}
	for(i =1;i<=val;i++) 
	{
	    $("#hab" + i + proyecto).show();
        $("#habitacion_" + i + proyecto).show();
        $("#cajahab" + i + proyecto).show();
	}
}


function MostrarFechaVueltaHoteles() {
    fecha =$("#NewCalendar").val();
    //numnoches es una variable global
    n = parseInt(document.getElementById(numnoches).value);
    if(SID=='MA')
        var fArr = fecha.split(".");
    else
        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(fVuelta + ", "+ GetDiaNombre(fVuelta));
}

//Función para comprobar que la fecha de búsqueda es correcta
function FechaCorrecta() {
	probarFecha = ($("#entradaD").val() + "/" + $("#entradaM").val() + "/" + $("#entradaY").val());
   
	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)) {
	f =  new Date($("#entradaM").val() + "/" + $("#entradaD").val() + "/" + $("#entradaY").val());
    var fArr = $("#fechaHoy").val().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 resetCombosHoteles() {	
    CambiarNumHabitaciones(1,'');
    CambiarNumHabitaciones(1,'VH');
    
    fecha =$("#fechaEntrada").val();
    var fArr = fecha.split("/");
    var d = fArr[0];
    var m = fArr[1];
    var fechaHoy = $("#fechaHoy").val().split("/");
	var hoy = new Date(fechaHoy[1] + "/" + fechaHoy[0] + "/" + fechaHoy[2]);
	var y = hoy.getFullYear();
	
    var vuelta=sumaDias(hoy,1);
    var dv = vuelta.getDate();
    var mv = vuelta.getMonth() + 1;
    var yv= vuelta.getFullYear();
    
    $("#dateEntradaHoteles").val(d + '/'+ m + '/'+ y);
}

/*----------------------------------------------------------------*/
/*FUNCIONES VACACIONES*/

function vacaciones_combo_check() {
if ($("#fechaDesdeVac").attr("value")!='' && $("#fechaDesdeVac").attr("value")!=undefined)
{
	probarFecha = ($("#entradaDVac").attr("value") + "/" + $("#entradaMVac").attr("value") + "/" + $("#entradaYVac").attr("value"));
	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($("#entradaMVac").attr("value") + "/" + $("#entradaDVac").attr("value") + "/" + $("#entradaYVac").attr("value"));
		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;
    } 
    }
    else
    {
    return true
    }
}

function resetCombosVacaciones() {

    fecha =$("#fechaEntrada").val();
    var fArr = fecha.split("/");
    var d = fArr[0];
    var m = fArr[1];
    var fechaHoy = $("#fechaHoy").val().split("/");
	var hoy = new Date(fechaHoy[1] + "/" + fechaHoy[0] + "/" + fechaHoy[2]);
	var y = hoy.getFullYear();
	
    var vuelta=sumaDias(hoy,1);
    var dv = "31";
    var mv = "12";
    var yv= vuelta.getFullYear() + 1;
    
    $("#dateEntradaVacaciones").val(d + '/'+ m + '/'+ y);
    $("#dateSalidaVacaciones").val(dv + '/'+ mv + '/'+ yv);
}

function fill(value,name,poblType) 
    {
        $("#inputString").val(name);
        $("#codigoDestino").val(value);
        $("#tipoDestino").val(poblType);
        $("#nombreDestino").val(name);
        $("#suggestions").hide();
   }
    
    
function lookup(e,inputString) 
{
    if(inputString.length == 0) 
    {     
        $("#codigoDestino").val("");
        $("#tipoDestino").val("");
    }
    var oEvent = window.event ? window.event : e;

    var keyCode = oEvent.keyCode;
  
    if ($("#sugestionContador").attr("value")==undefined || $("#sugestionContador").attr("value")=='')
    {
        $("#sugestionContador").val("0");
    }
    switch (keyCode) {
//        // Return/Enter
    case 13:
        if(inputString.length != 0) 
        {     
            if ($("#sugestionContador").attr("value")!=undefined && $("#sugestionContador").attr("value")!='')
            {
                document.getElementById("autoSuggestionsList" + $("#sugestionContador").attr("value")).onclick();
            }
            else
            {
                document.getElementById("autoSuggestionsList0").onclick();
            }
        }
        return true;
        break;

//        // Escape
    case 27:
        $("#inputString").val("");
        $("#codigoDestino").val("");
        $("#tipoDestino").val("");
        $("#sugestionContador").val("");
        $("#suggestions").hide();
        document.getElementById("layerError").style.visibility="hidden";
        document.getElementById("destinoAlert").style.visibility="hidden";
        document.getElementById("layerError").style.display="none";
        document.getElementById("destinoAlert").style.display="none";
        break;
    
//        // Up arrow
    case 38:
        var contador;
        if ($("#sugestionContador").attr("value")!=0)
        {
            if ($("#sugestionContador").attr("value")!=undefined && $("#sugestionContador").attr("value")!='')
            {
                contador=$("#sugestionContador").attr("value")
                document.getElementById("autoSuggestionsList" + (contador)).className='suggestionList';
            }
            else
            {
                contador=1;
            }
            contador=parseInt(contador)-1
            document.getElementById("autoSuggestionsList" + contador).className='suggestionSel';
            $("#sugestionContador").val(contador);
         }
            return true;
            break;

    case 40:
        var contador;
        var ultimoreg;
        ultimoreg=parseInt($("#sugestionContador").attr("value"))+1;
        
        if ($("#sugestionContador").attr("value")!=undefined && $("#sugestionContador").attr("value")!='')
        {
                contador=$("#sugestionContador").attr("value")
                contador=parseInt(contador)+1
                document.getElementById("autoSuggestionsList" + (contador-1)).className='suggestionList';
                if (!document.getElementById("autoSuggestionsList" + ultimoreg))
                {
                    $("#sugestionContador").val("0");
                    contador=0;
                }
        }
        else
        {
                contador=1;
        }
        
        document.getElementById("autoSuggestionsList" + contador).className='suggestionSel';
        $("#sugestionContador").val(contador);
        return true;
        break;
     
     default:
        $("#sugestionContador").val("");
        if(inputString.length == 0) 
        {
            document.getElementById("suggestions").style.visibility="hidden";
            document.getElementById("suggestions").style.display="none";
        } 
        else 
        { 
            $.post("http://www.muchoviaje.co/vacaciones/_engine/autocompleteservice.aspx", {queryString: "" + inputString  +""}, function(data){
                
                if(data.length > 0) {
                    document.getElementById("suggestions").style.visibility="visible";
                    document.getElementById("suggestions").style.display="";
                    document.getElementById("autoSuggestionsList").style.visibility="visible";
                      
                      $("#autoSuggestionsList").html(data);
                    }
              else {
              
                    document.getElementById("autoSuggestionsList").style.visibility="hidden";
                      document.getElementById("suggestions").style.visibility="hidden";
                    $("#autoSuggestionsList").html(data);
                    
               }
            });
        }
         return true;
         break;
    }

} 

function AutoComplete_Key(e,inputString)
   {
       var oEvent = window.event ? window.event : e;
       var keyCode = oEvent.keyCode;
        if ($("#sugestionContador").attr("value")==undefined || $("#sugestionContador").attr("value")=='')
        {
            $("#sugestionContador").val("0");
        }
        switch (keyCode) {
        // Return/Enter
        case 13:
            if ($("suggestions"))
            {
                if(inputString.length != 0) 
                {     
                    document.getElementById("autoSuggestionsList" + $("#sugestionContador").attr("value")).onclick();
                }
            }
            
            if (e && e.preventDefault)
                e.preventDefault();
      
            e.returnValue=false;
  
            break;
    }
}

function CompletarDestinos()
{
   if (document.getElementById("ctl00_cphPrincipal_Buscador1_cboDestino")!=null)
   {
       var valor=document.getElementById("ctl00_cphPrincipal_Buscador1_cboDestino");
       fill(valor.value.substring(3),valor.options[valor.selectedIndex].text,valor.value.substring(0,2));      
   }

}

function GetResultsRwPathWithDates(mgdscode,name,destination_type,date_from,date_to,duration,from,mark)
{
    if (from!="")
    {
        if (mark!="")
        {
            return "viajes_ofertas.aspx?pob=" + mgdscode + "&tdest=" + destination_type.toLowerCase() + "&fechad=" + date_from + "&fechaa=" + date_to + "&n=" + duration + '&origen=' + from + '&marca=' + mark + "&name=" + name; 

            //return "" + destination_type.toLowerCase() + "-ofertas-vacaciones-en-" + GetPreparedString(name) + "__" + mgdscode + ".aspx?fechad=" + date_from + "&fechaa=" + date_to + "&n=" + duration + '&origen=' + from + '&marca=' + mark;
        }
        else
        {
            return "viajes_ofertas.aspx?pob=" + mgdscode + "&tdest=" + destination_type.toLowerCase() + "&fechad=" + date_from + "&fechaa=" + date_to + "&n=" + duration + '&origen=' + from + "&name=" + name; 
            //return "" + destination_type.toLowerCase() + "-ofertas-vacaciones-en-" + GetPreparedString(name) + "__" + mgdscode + ".aspx?fechad=" + date_from + "&fechaa=" + date_to + "&n=" + duration + '&origen=' + from;
        }
    }
    else
    {
        if (mark!="")
        {
            return "viajes_ofertas.aspx?pob=" + mgdscode + "&tdest=" + destination_type.toLowerCase() + "&fechad=" + date_from + "&fechaa=" + date_to + "&n=" + duration + '&marca=' + mark + "&name=" + name; 
            //return "" + destination_type.toLowerCase() + "-ofertas-vacaciones-en-" + GetPreparedString(name) + "__" + mgdscode + ".aspx?fechad=" + date_from + "&fechaa=" + date_to + "&n=" + duration + '&marca=' + mark;
        }
        else
        {
            return "viajes_ofertas.aspx?pob=" + mgdscode + "&tdest=" + destination_type.toLowerCase() + "&fechad=" + date_from + "&fechaa=" + date_to + "&n=" + duration + "&name=" + name; 
            //return "" + destination_type.toLowerCase() + "-ofertas-vacaciones-en-" + GetPreparedString(name) + "__" + mgdscode + ".aspx?fechad=" + date_from + "&fechaa=" + date_to + "&n=" + duration;
        }
    }
    
}

function validarBusquedaPaquetes() 
{
	var poblacion = $("#codigoDestino").val();
	var typedest = $("#tipoDestino").val();
	var name = $("#nombreDestino").val();
	var fechaDesde = GetFechaUrl($("#fechaDesde").val());
	var fechaHasta = GetFechaUrl($("#fechaHastaVac").val());
	var noches = $("#nochesVac").val();
	var origen='';
	var marca='';

    var url = GetResultsRwPathWithDates(poblacion, name, typedest, fechaDesde, fechaHasta, noches,origen,marca);   
    var navegador = navigator.appName
 
    document.getElementById("codigoDestino").value='';
    url = url_vacaciones + url;
    document.location.href=url;

	return false;
}


function BuscarVacaciones() 
    {
       CompletarDestinos();
       if (($("#codigoDestino").val()=='')&&((document.getElementById("suggestions").style.visibility == 'hidden' || document.getElementById("suggestions").style.visibility == ''))) 
        { 
//            document.getElementById("layerError").style.visibility="visible";
// 	        document.getElementById("destinoAlert").style.visibility="visible";
// 	        document.getElementById("layerError").style.display="";
// 	        document.getElementById("destinoAlert").style.display="";    
 	    }
        else {
        if (document.getElementById("suggestions").style.visibility == 'visible')  {
            if (($("#sugestionContador").attr("value")!=undefined)&&($("#sugestionContador").attr("value")!=''))
                {
                document.getElementById("autoSuggestionsList" + $("#sugestionContador").attr("value")).onclick();
                }
            else 
                {
                document.getElementById("autoSuggestionsList0").onclick();
                }
            
        }
       validarBusquedaPaquetes();
        
    }
    }
    
/*----------------------------------------------------------------*/
/*FUNCIONES VUELO MAS HOTEL*/   
function BuscarVH () {
    var departure=$('#departureVH').val();
    var arrival=$('#arrivalVH').val();
    var air=$('#airVH').val();
    var rail=$('#railVH').val();
    var bus=$('#busVH').val();
    if(SID=='MA')
    {
        var dateGo=$('#formDepartureDateVH').val();
        var dateReturn=$('#formReturnDateVH').val();
    }
    else
    {
        var dateGo=$('#formDepartureDateVH').val();
        var dateReturn=$('#formReturnDateVH').val();
    }
    
    if(SID=='MA')
        document.getElementById("esperaBusqueda2").style.display = "inline";
    
    var rooms=$("#ctl00_cphPrincipal_ctl00_habitacionesVH").val();
    var room1Ocupation=$("#ctl00_cphPrincipal_ctl00_habitacion_1VH").val();var room2Ocupation=$("#ctl00_cphPrincipal_ctl00_habitacion_2VH").val();var room3Ocupation=$("#ctl00_cphPrincipal_ctl00_habitacion_3VH").val();var room4Ocupation=$("#ctl00_cphPrincipal_ctl00_habitacion_4VH").val();
    var room1ChildAge1=$("#edad1-1VH").val();var room1ChildAge2=$("#edad1-2VH").val();var room1ChildAge3=$("#edad1-3VH").val();
    var room2ChildAge1=$("#edad2-1VH").val();var room2ChildAge2=$("#edad2-2VH").val();var room2ChildAge3=$("#edad2-3VH").val();
    var room3ChildAge1=$("#edad3-1VH").val();var room3ChildAge2=$("#edad3-2VH").val();var room3ChildAge3=$("#edad3-3VH").val();
    var room4ChildAge1=$("#edad4-1VH").val();var room4ChildAge2=$("#edad4-2VH").val();var room4ChildAge3=$("#edad4-3VH").val();
    
    var url='engine/search.ashx?departure=' + departure + '&arrival=' + arrival + '&air=' + air + '&rail=' + rail + '&bus=' + bus + '&dateGo=' + dateGo + '&dateReturn=' + dateReturn + '&rooms=' + rooms 
    + '&room1Ocupation=' + room1Ocupation + '&room1ChildAge1=' + room1ChildAge1 + '&room1ChildAge2=' + room1ChildAge2 + '&room1ChildAge3=' + room1ChildAge3
    + '&room2Ocupation=' + room2Ocupation + '&room2ChildAge1=' + room2ChildAge1 + '&room2ChildAge2=' + room2ChildAge2 + '&room2ChildAge3=' + room2ChildAge3
    + '&room3Ocupation=' + room3Ocupation + '&room3ChildAge1=' + room3ChildAge1 + '&room3ChildAge2=' + room3ChildAge2 + '&room3ChildAge3=' + room3ChildAge3
    
//    alert(url_vuelomashotel + url);
//    return false;
    
    url = url_vuelomashotel + url;

    document.location.href=url;
	return false;

}//validateSearch

/*----------------------------------------------------------------*/
/*FUNCIONES VUELOS*/   
function sumaDias(fecha, diasSumar)
{ var milisecSumar= parseInt(diasSumar *24*60*60*1000); 
fecha.setTime(fecha.getTime()+milisecSumar); return fecha; 
}

function resetCombosVuelos() {	
	fecha =$("#fechaEntrada").val();
    var fArr = fecha.split("/");
    var d = fArr[0];
    var m = fArr[1];
    var fechaHoy = $("#fechaHoy").val().split("/");
	var hoy = new Date(fechaHoy[1] + "/" + fechaHoy[0] + "/" + fechaHoy[2]);
	var y = hoy.getFullYear();
	
    var vuelta=sumaDias(hoy,1);
    var dv = vuelta.getDate();
    var mv = vuelta.getMonth() + 1;
    var yv= vuelta.getFullYear();
    
    $("#formDepartureDate").val(d + '/'+ m + '/'+ y);
    $("#formDepartureDateVH").val(d + '/'+ m + '/'+ y);
    $("#formReturnDate").val(dv + '/'+ mv + '/'+ yv);
    $("#formReturnDateVH").val(dv + '/'+ mv + '/'+ yv);
}

//=====================================================================================//
//------------------------------------- FECHAS ----------------------------------------//
//=====================================================================================//

function dateParse(datestr) {
    var match = new RegExp("(\\d{2})/(\\d{2})/(\\d{4})", "g").exec(datestr);
    var date = new Date(match[3], (match[2]-1), match[1], 0, 0, 0);
    return date;
}//dateParse

function dateToString(datestr) {
    var match = new RegExp("(\\d{2})/(\\d{2})/(\\d{4})", "g").exec(datestr);
    
    if(match == null) {
		matchISO = new RegExp("(\\d{4})(/|-)(\\d{2})(/|-)(\\d{2})", "g").exec(datestr);
		if(matchISO == null) {
			return datestr;
		} else {
			match = {3: matchISO[1], 2: matchISO[3], 1: matchISO[5]};
		}
    }
    
    var date = new Date(match[3], (match[2]-1), match[1], 0, 0, 0);
    return formatDates.replace("_DAYWEEK_", dayNames[date.getDay()]).replace("_DAY_", match[1]).replace("_MONTH_", monthNames[match[2]-1]).replace("_YEAR_", match[3])
}//dateToString

//=====================================================================================//
//----------------------------------- FIN FECHAS --------------------------------------//
//=====================================================================================//


//=====================================================================================//
//------------------------------------- ARRAYS ----------------------------------------//
//=====================================================================================//

/**
 * Utilidad para comprobar si una clave se encuentra dentro de un array
 * @param array array Array desde el que se comprobara si existe una clave dentro de el
 * @param string key Clave a comprobar dentro del array
 * @return bool true cuando se encuentre la clave, false cuando no
 */
function inArray(array, key) {
	for(var i in array) {
		if(i == key) {
			return true;
		}
	}
	return false;
}//inArray

//=====================================================================================//
//----------------------------------- FIN ARRAYS --------------------------------------//
//=====================================================================================//


//=====================================================================================//
//-------------------------------------- AJAX -----------------------------------------//
//=====================================================================================//

/**
 * La ya clasica funcion de MrProper, para utilizar ajax al mas bajo nivel para operaciones rapidas
 * sin la necesidad de usar frameworks que ralentizan el proceso.
 */
function DonLimpioMrProper() {
	try {
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (E) {
			xmlhttp = false;
		}
	}

	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
		xmlhttp = new XMLHttpRequest();
	}

	return xmlhttp;
}

//=====================================================================================//
//------------------------------------ END AJAX ---------------------------------------//
//=====================================================================================//


//=====================================================================================//
//--------------------------------- AUTOCOMPLETADO ------------------------------------//
//=====================================================================================//

/**
 * Carga los aeropuertos en el autocompleta en base al texto introducido en el input con id pasado por parametro
 * @param string name Id del elemento, generalmente input, desde el que se va a activar el suggest o autocompleta.
 */
function LoadAirports(name) {
	data = document.getElementById(name).value;

	if (data.length > 2) {
	
		DonLimpio = DonLimpioMrProper();
		path = "_engine/aeropuertosAutocompleta.aspx?name=" + data;
		DonLimpio.open("GET", path, true);
		 
		DonLimpio.onreadystatechange = function() {
			if (DonLimpio.readyState == 1){}
			else if(DonLimpio.readyState == 4) {
				if(DonLimpio.status == 200){
					 if(!inArray(__AutoComplete, name)) {
						AutoComplete_Create(name, eval(DonLimpio.responseText), {"keypress":"LoadAirports(\"" + name + "\");", "layerName":"layerAutocomplete_" + name, "layerWidth":"230"});
						
					} else {
						__AutoComplete[name]["data"] = eval(DonLimpio.responseText);
					}
				}
			}
		}
		DonLimpio.send(null);
	}
}




function LoadAutocompleteItems(name) {
	data = document.getElementById(name).value;

	if (data.length > 2) {
	
		DonLimpio = DonLimpioMrProper();
		path = "/vuelos/engine/service.aspx?type=autocomplete&name=" + data;
		DonLimpio.open("GET", path, true);
		 
		DonLimpio.onreadystatechange = function() {
			if (DonLimpio.readyState == 1){}
			else if(DonLimpio.readyState == 4) {
				if(DonLimpio.status == 200){
					 if(!inArray(__AutoComplete, name)) {
						AutoComplete_Create(name, eval(DonLimpio.responseText), {"keypress":"LoadAutocompleteItems(\"" + name + "\");", "layerName":"layerAutocomplete_" + name, "layerWidth":"230"});
					} else {
						__AutoComplete[name]["data"] = eval(DonLimpio.responseText);
					}
				}
			}
		}
		DonLimpio.send(null);
	}
}
//=====================================================================================//
//------------------------------- FIN AUTOCOMPLETADO ----------------------------------//
//=====================================================================================//



//=====================================================================================//
//----------------------------------- BUSCADORES --------------------------------------//
//=====================================================================================//

/**
 * Muestra u oculta los combos de edades de los niños en base al numero de niños seleccionado en el
 * combo de niños
 */
function drawChildAgesCombos() {

	var i;
	var trace;
	var childs = document.getElementById("formChilds").value;

	for(i = 1; i <= childs; i++) {
		document.getElementById("formChildAge" + i).style.display = "block";
		//document.getElementById("formChildAge" + i).style.visibility = "visible";
	}
	
	for(i = parseInt(childs) + 1; i <= 9; i++) {
		document.getElementById("formChildAge" + i).style.display = "none";
		//document.getElementById("formChildAge" + i).style.visibility = "hidden";
	}
	
	if(childs == 0) {
		document.getElementById("labelChildsAge").style.display = "none";
		//document.getElementById("labelChildsAge").style.visibility = "hidden";
	} else {
		document.getElementById("labelChildsAge").style.display = "block";
		//document.getElementById("labelChildsAge").style.visibility = "visible";
	}
}//drawChildAgesCombos


function showFrecuentAirports(airport) {
	LayerAirportsName = airport;
	elementOrigin = document.getElementById(airport);
	
    var position = $('#departure').position();
	var left = position.left;
	var tope = position.top;

	var layer = document.getElementById('layerCities');
	layer.style.top = tope + "px";
	layer.style.left = left + "px";
	layer.style.display = "block";
}//showFrecuentAirports

function loadAirportsList(type, code) {
	switch (type) {
		case "PS": //Listar aeropuertos del pais
			params = "country=" + code;
		break;
		case "CT": //Listar paises del continente
			params = "continent=" + code;
		break;
		case "WL": //Listar continentes del mundo
			params = "";
		break;
		case "CL": //Cerramos la capa
			document.getElementById("layerListAirports").style.display = "none";
			return;
		break;
		case "AP":
			document.getElementById(LayerAirportsName).value = code;
			loadAirportsList("CL", "");
			return;
		break;
		default:
			alert("No implementado");
			return;
	}


	url = "/vuelos/controles/aeropuertosAjax.aspx?" + params;
	objetivo = "layerListAirportsData"
	
	DonLimpio = DonLimpioMrProper();
	DonLimpio.open("GET", url, true);
		 
	DonLimpio.onreadystatechange = function() {
		if (DonLimpio.readyState == 1){}
		else if(DonLimpio.readyState == 4) {
			if(DonLimpio.status == 200){
				document.getElementById(objetivo).innerHTML = DonLimpio.responseText;
				
                var position = $('#departure').position();
	            var left = position.left;
	            var tope = position.top;
				

				var layer = document.getElementById('layerListAirports');
				layer.style.top = tope + "px";
				layer.style.left = left + "px";
				layer.style.display = "block";
				
				//document.getElementById("layerListAirports").style.display = "block"
				document.getElementById("layerCities").style.display = "none"
			}
		}
	}
	DonLimpio.send(null);
}

//=====================================================================================//
//--------------------------------- FIN BUSCADORES ------------------------------------//
//=====================================================================================//



//=====================================================================================//
//------------------------------------- ESPERA ----------------------------------------//
//=====================================================================================//

function showWaiter (name) {
	$('#content').hide();
	
    var widthTotal=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth); 
    var heightTotal=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight); 
    document.getElementById(name).style.width = widthTotal + "px";
    document.getElementById(name).style.height = heightTotal + "px";
    
    //Ocultamos la publicidad
    $('#topBanner').hide();
    $('.bloquePubli').hide();
    $('.PubliBottom').hide();
    
    
    
    //document.getElementById("loading").style.top = ($(window).height() - $('#loading').outerHeight())/2 + "px";
    //document.getElementById("loading").style.top = "150px";
    
    changeDisplayDiv(name);
}//showWaiter

//=====================================================================================//
//----------------------------------- FIN ESPERA --------------------------------------//
//=====================================================================================//



//=====================================================================================//
//----------------------------------- GENERALES ---------------------------------------//
//=====================================================================================//

function openObj (obj) {
    if (!obj.is(':visible')) {
        obj.slideDown(500);
    }
}//openObj

function closeObj (obj) {
    if (obj.is(':visible')) {
        obj.slideUp(500);
    }
}//openObj

function changeDisplayByObj (obj) {
    if (!obj.is(':visible')) {
        obj.slideDown(500);
    } else {
        obj.slideUp(500);
    }
}//changeDisplayDiv

function changeDisplayDiv (name) {
    if (!$('#' + name).is(':visible')) {
        $('#' + name).slideDown(500);
    } else {
        $('#' + name).slideUp(500);
    }
}//changeDisplayDiv

function changeTextInput (name, text1, text2) {
    if (!$('#' + name).value == text1) {
        $('#' + name).value = text2;
    } else {
        $('#' + name).value = text1;
    }
}//changeTextInput

function changeTextInner (name, text1, text2) {
    if ($('#' + name).html() == text1) {
        $('#' + name).html(text2);
    } else {
        $('#' + name).html(text1);
    }
}//changeTextInner

function findPos(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        do {
	        curleft += obj.offsetLeft;
	        curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
        return [curleft,curtop];
    }
}//findPos
//=====================================================================================//
//--------------------------------- FIN GENERALES -------------------------------------//
//=====================================================================================//


//=====================================================================================//
//--------------------------- VALIDACIÓN DE FORMULARIOS -------------------------------//
//=====================================================================================//

function validate () {
    if (document.getElementById("departure")) return validateSearch();
}//validate

function validateSearch () {

    var tripType = $("input[name='tripType']:checked").val();
    var departure=$('#departure').val();
    var arrival=$('#arrival').val();
    var air=$('#air').val();
    var rail=$('#rail').val();
    var bus=$('#bus').val();
    var dateGo=$('#formDepartureDate').val();
    var dateReturn=$('#formReturnDate').val();
    var adults=$('#formAdults').val();
    var childs=$('#formChilds').val();
    var childAge1=0;var childAge2=0;var childAge3=0;var childAge4=0;var childAge5=0;var childAge6=0
    var childAge7=0;var childAge8=0;var childAge9=0;
    
    var url='disponibilidad/buscador.aspx?tripType=' + tripType + '&departure=' + departure + '&arrival=' + arrival + '&air=' + air + '&rail=' + rail + '&bus=' + bus + '&adults=' + adults + '&childs=' + childs + '&dateGo=' + dateGo + '&dateReturn=' + dateReturn + '&childAge1=' + childAge1 + '&childAge2=' + childAge2 + '&childAge3=' + childAge3 + '&childAge4=' + childAge4 + '&childAge5=' + childAge5 + '&childAge6=' + childAge6 + '&childAge7=' + childAge7 + '&childAge8=' + childAge8 + '&childAge9=' + childAge9
    url = url_vuelos + url;
	document.location.href=url;
	return false;

}//validateSearch

//=====================================================================================//
//------------------------- FIN VALIDACIÓN DE FORMULARIOS -----------------------------//
//=====================================================================================//

