/**
* Archivo      : validaciones.js
* Descripci�n  : funciones de validaci�n de datos en los forms
* Fecha        : 14/02/2008
* Cambios      :
* [xx/xx/xxxx] - xxxxx
*/

//Controlador de timer de js.
//Es global, pero es que no hay otra manera
var oTemporizador;

function  jsValidaciones__ValidarFormularioNieve(formID){

    var bRetorno=true; 
    var contador_servicios=0;
    $('#'+formID+ ' input:checkbox:checked')
        .each(function callback() {
            contador_servicios++;
            var aValores=$(this).attr('name').split('_');
            var codigo =aValores[1];
            if(!(bCampoVacio('fecha_servicio_'+codigo,"Se requiere obligatoriamente una fecha para el servicio de nieve.")))bRetorno=false;
            else {
                if(bComprobarFecha(document.getElementById('fecha_servicio_'+codigo))==false){alert("La fecha inicial no es v\xE1lida");bRetorno=false;}
                else {
                    var campo_ninos1        =document.getElementById('num_ninos1_'+codigo);
                    var campo_ninos2        =document.getElementById('num_ninos2_'+codigo);
                    var campo_adultos       =document.getElementById('num_adultos_'+codigo);
                    var campo_discapacitados=document.getElementById('num_discapacitados_'+codigo);
                    var campo_senior        =document.getElementById('num_senior_'+codigo);
                    var sum_personas_servicio=0;
                    if (campo_ninos1)sum_personas_servicio+=parseInt(campo_ninos1.value);
                    if (campo_ninos2)sum_personas_servicio+=parseInt(campo_ninos2.value);
                    if (campo_adultos)sum_personas_servicio+=parseInt(campo_adultos.value);
                    if (campo_discapacitados)sum_personas_servicio+=parseInt(campo_discapacitados.value);
                    if (campo_senior)sum_personas_servicio+=parseInt(campo_senior.value);
                    if (sum_personas_servicio<=0) {alert("El numero total de personas para un servicio ha de ser mayor que 0.");bRetorno=false;}
                }
            }
        });
        if (contador_servicios>0){
         //   alert ($('#'+formID+ ' .nombre_titular').val());
            if($('#'+formID+ ' input.nombre_titular').val()==""){
                alert("Se requiere obligatoriamente el nombre del titular de los servicios seleccionaods.");
                $('#'+formID+ ' input.nombre_titular').focus();
                bRetorno=false;
            }
            
            if($('#'+formID+ ' input.apellidos_titular').val()==""){
                alert("Se requiere obligatoriamente los apellidos del titular de los servicios seleccionaods.");
                $('#'+formID+ ' input.apellidos_titular').focus();
                bRetorno=false;
            }
        }

    return bRetorno;
}
function  call_actualizarSeguroNieve(id_resultado_busqueda){

    
    var aDatosSeguro=$('#comboSeguroNieve_'+id_resultado_busqueda).val().split('_');    
    var precio_total=parseFloat(aDatosSeguro[1].replace(/[,]/g,'.'));
    var codigo_seguro=parseInt(aDatosSeguro[0]);
    var cantidad_personas=0;
    cantidad_personas=parseInt($("#num_personas_seguro_"+id_resultado_busqueda).val());
    if (codigo_seguro!=2) precio_total=precio_total*(parseFloat(cantidad_personas));
    $("#div_precio_total_seguro_"+id_resultado_busqueda).html(precio_total+"&nbsp;&euro;");

    var descripcion_seguro=$('#comboSeguroNieve_'+id_resultado_busqueda+' option:selected').text();

    var nombres_personas="";
    var apellidos_personas="";
    for(var i=1;i<=cantidad_personas;i++){        
        nombres_personas+=$('#nombre_seguro_'+i+'_'+id_resultado_busqueda).val()+'|';
        apellidos_personas+=$('#apellidos_seguro_'+i+'_'+id_resultado_busqueda).val()+'|';
    }
    $.get("functions/func_primera_linea_nieve.php",
    {
        //cuando no exista el control el selector devuelve null y se pasa un 0....
        func: "func_primera_linea_nieve__actualizarSeguroNieve",
        param1: id_resultado_busqueda,
        param2: cantidad_personas,
        param3: nombres_personas,
        param4: apellidos_personas,
        param5: precio_total,
        param6: codigo_seguro,
        param7: descripcion_seguro
    },
    function(data){
    });
}

function call_actualizarServicioTitular(sIdTmpBusquedaDet)
{
    //call_llamadaAjaxTransparenciaInicioJquery("Recalculando precio total del servicio...", "", "", "", '200', '100', "./img/");
    $.get("functions/func_primera_linea_nieve.php",
    {
        //cuando no exista el control el selector devuelve null y se pasa un 0....
        func: "func_primera_linea_nieve__actualizarServicioTitular",
        param1: sIdTmpBusquedaDet,
        param2: $('#nombre_servicios_'+sIdTmpBusquedaDet).val(),
        param3: $('#apellidos_servicios_'+sIdTmpBusquedaDet).val()

    },
    function(data){
		id_form=$("#nombre_servicios_"+sIdTmpBusquedaDet).parents("form").eq(0).attr("id");
		if(jsValidaciones__ValidarFormularioNieve(id_form))
			$("#"+id_form).submit();
    });
}
function call_actualizarServicioPersonas(pkServicio)
{
    //call_llamadaAjaxTransparenciaInicioJquery("Recalculando precio total del servicio...", "", "", "", '200', '100', "./img/");
    $.get("functions/func_primera_linea_nieve.php",
    {
        //cuando no exista el control el selector devuelve null y se pasa un 0....
        func: "func_primera_linea_nieve__actualizarServicioPersonas",
        param1: $('#num_ninos1_'+pkServicio).val()||0,
        param2: $('#num_ninos2_'+pkServicio).val()||0,
        param3: $('#num_adultos_'+pkServicio).val()||0,
        param4: $('#num_senior_'+pkServicio).val()||0,
        param5: $('#num_discapacitados_'+pkServicio).val()||0,
        param6: pkServicio
    },
    function(data){
        var sHtmlPrecioServicio=data.replace(/[\n\r\t]/g,'');
        callback_actualizarServicioPersonas(sHtmlPrecioServicio,pkServicio);
        $.get("functions/func_primera_linea_nieve.php",
        {
            func: "func_primera_linea_nieve__calcularPrecioTotalServicios",
            param1: pkServicio
        },
        function(data){
            var sDatosPrecioTotal=data.replace(/[\n\r\t]/g,'');
            callback_actualizarServicioPrecioTotal(sDatosPrecioTotal);
        });
    });
}
function callback_actualizarServicioPersonas(sHtmlPrecioServicio,pkServicio){
    //call_llamadaAjaxTransparenciaFin();
    $("#td_precio_total_"+pkServicio).html(sHtmlPrecioServicio).addClass("lastcolumn");
}
function callback_actualizarServicioPrecioTotal(sDatosPrecioTotal){
    //call_llamadaAjaxTransparenciaFin();
    var aValores = sDatosPrecioTotal.split('|');
    $("#div_precio_total_servicios_"+aValores[0]).html(aValores[1]);
}
function call_actualizarServicioFecha(pkServicio)
{
    call_llamadaAjaxTransparenciaInicioJquery("Calculando precios por persona del servicio...", "", "", "", '200', '100', "./img/");
    $.get("functions/func_primera_linea_nieve.php",
    {
        func: "func_primera_linea_nieve__actualizarServicioFecha",
        param1: $('#fecha_servicio_'+pkServicio).val(),
        param2: pkServicio
    },
    function(data){
        var sDatosServicio=data.replace(/[\n\r\t]/g,'');
         callback_actualizarServicioFecha(sDatosServicio,pkServicio);
    });

}
function callback_actualizarServicioFecha(sDatosServicio,pkServicio){
    call_llamadaAjaxTransparenciaFin();
    sDatosServicio=sDatosServicio.replace(/[\n\r\t]/g,'');
    var aValores = sDatosServicio.split('|');
    var sHtmlDisponibilidad="";
    switch (aValores[1]) {
        case 'C':
            sHtmlDisponibilidad ='<img src="./img/info.jpg" title="Temporada '+aValores[0]+' - Reserva online disponible" />';
            break;
        case 'P':
            sHtmlDisponibilidad ='<img src="./img/info.jpg" title="Temporada '+aValores[0]+' - Reserva bajo petci&oacute;n" />';
            break;
        case 'N':
        default:
            sHtmlDisponibilidad='';
            break;
    }
	if(sHtmlDisponibilidad=='')
		$("#div_no_disponible_"+pkServicio).html("Servicio no disponible en esta fecha");
	else
		$("#div_no_disponible_"+pkServicio).html("");
    $("#info_"+pkServicio).html(sHtmlDisponibilidad);
    $("#div_precio_ninos1_"+pkServicio).html(aValores[2]);
    $("#div_precio_ninos2_"+pkServicio).html(aValores[3]);
    $("#div_precio_adultos_"+pkServicio).html(aValores[4]);
    $("#div_precio_senior_"+pkServicio).html(aValores[5]);
    $("#div_precio_discapacitados_"+pkServicio).html(aValores[6]);



    $("#num_ninos1_"+pkServicio).SpinButton({max: 10, min:0,onChange:function(e) { if (!e) var e = window.event;  call_actualizarServicioPersonas(pkServicio)}});
    $("#num_ninos2_"+pkServicio).SpinButton({max: 10, min:0,onChange:function(e) { if (!e) var e = window.event;  call_actualizarServicioPersonas(pkServicio)}});
    $("#num_adultos_"+pkServicio).SpinButton({max: 10, min:0,onChange:function(e) { if (!e) var e = window.event;  call_actualizarServicioPersonas(pkServicio)}});
    $("#num_senior_"+pkServicio).SpinButton({max: 10, min:0,onChange:function(e) { if (!e) var e = window.event;  call_actualizarServicioPersonas(pkServicio)}});
    $("#num_discapacitados_"+pkServicio).SpinButton({max: 10, min:0,onChange:function(e) { if (!e) var e = window.event;  call_actualizarServicioPersonas(pkServicio)}});

    $("#num_discapacitados_"+pkServicio).focus();
    $("#num_senior_"+pkServicio).focus();
    $("#num_adultos_"+pkServicio).focus();
    $("#num_ninos2_"+pkServicio).focus();
    $("#num_ninos1_"+pkServicio).focus();
}

function call_actualizarServicioEstado(pkServicio,id_resultado_busqueda,fecha_inicial,cantidad_dias)
{
    var aDatos=fecha_inicial.split('/');
    var fecha1=new Date(aDatos[2],aDatos[1] - 1,aDatos[0]);
    var fecha2=new Date(fecha1.getTime() + cantidad_dias*24*60*60*1000);
    $("#fecha_servicio_"+pkServicio).datepicker({showOn: 'button', buttonImage: 'img/calendar.jpg', buttonImageOnly: true,minDate:fecha1,maxDate:fecha2,constrainInput: true,firstDay: 1});
    call_llamadaAjaxTransparenciaInicioJquery("Recalculando precio total de servicios...", "", "", "", '200', '100', "./img/");
    $.get("functions/func_primera_linea_nieve.php",
    {
        func: "func_primera_linea_nieve__actualizarServicioEstado",
        param1: $('#servicio_'+pkServicio).is(':checked'),
        param2: pkServicio
    },
    function(data){
        var sHtmlPrecioServicios=data.replace(/[\n\r\t]/g,'');
         callback_actualizarServicioEstado(sHtmlPrecioServicios,id_resultado_busqueda,pkServicio);
    });

}
function callback_actualizarServicioEstado(sInnerHtmlPrecios,id_resultado_busqueda,pkServicio){
    call_llamadaAjaxTransparenciaFin();
    if ($('#servicio_'+pkServicio).is(':checked')){
        $("#fecha_servicio_"+pkServicio).datepicker('show');
    } else {
        $('#num_ninos1_'+pkServicio).val(0);
        $('#num_ninos2_'+pkServicio).val(0);
        $('#num_adultos_'+pkServicio).val(0);
        $('#num_senior_'+pkServicio).val(0);
        $('#num_discapacitados_'+pkServicio).val(0);
        call_actualizarServicioPersonas(pkServicio);
    }
}

function call_mostrarServiciosYSegurosNieve(sPais,desde,hasta,importe,id_room,id_resultado_busqueda)
{
    call_llamadaAjaxTransparenciaInicioJquery("Buscando informaci&oacute;n de servicios de nieve cercanos...", "", "", "", '200', '100', "./img/");
    $.get("functions/func_primera_linea_nieve.php",
    {
        func: "func_primera_linea_nieve__sSegurosNieve",
        param1: sPais,
        param2: desde,
        param3: hasta,
        param4: importe,
        param5: id_resultado_busqueda
    },
    function(data){
        var sHtmlSeguro=data.replace(/[\n\r\t]/g,'');
        $.get("functions/func_primera_linea_nieve.php",
        {
            func: "func_primera_linea_nieve__sServiciosNieve",
            param1: id_room,
            param2: id_resultado_busqueda
        },
        function(data){
            var sHtmlServicios=data.replace(/[\n\r\t]/g,'');
            var sHtmlSegurosYServicios=sHtmlSeguro+'<br />'+sHtmlServicios;
            callback_mostrarServiciosYSegurosNieve(sHtmlSegurosYServicios,id_resultado_busqueda);
        });
        
    });
}

/**
* function callback_mostrarTmpResultados()
*/
function callback_mostrarServiciosYSegurosNieve(sInnerHtml,id_resultado_busqueda)
{
    call_llamadaAjaxTransparenciaFin();
    $("#detalles_nieve_"+id_resultado_busqueda).html(sInnerHtml);

    //spin personas seguro nieve
    $("#num_personas_seguro_"+id_resultado_busqueda).SpinButton({max: 10, min:0,onChange:function(e) { if (!e) var e = window.event;  call_agregarPersonasSeguro(id_resultado_busqueda)}});


    //zebrificar tabla con los servicos
    $(".tabla_nieve > tbody > tr:not(.subtitlerow):nth-child(odd)").addClass("odd");
}

function call_agregarPersonasSeguro(id_resultado_busqueda){
    var iNumPersonas=$("#num_personas_seguro_"+id_resultado_busqueda).val();
    $("#div_personas_seguro_"+id_resultado_busqueda).html("");
    for(var i=1;i<=iNumPersonas;i++){
        $("#div_personas_seguro_"+id_resultado_busqueda).html($("#div_personas_seguro_"+id_resultado_busqueda).html()+'<label for="nombre_seguro_'+i+'_'+id_resultado_busqueda+'">Nombre:</label><input type="text" id="nombre_seguro_'+i+'_'+id_resultado_busqueda+'" name="nombre_seguro_'+i+'_'+id_resultado_busqueda+'" style="width:100px;" onblur="javascript:call_actualizarSeguroNieve(\''+id_resultado_busqueda+'\')"/>&nbsp;&nbsp;');
        $("#div_personas_seguro_"+id_resultado_busqueda).html($("#div_personas_seguro_"+id_resultado_busqueda).html()+'<label for="apellidos_seguro_'+i+'_'+id_resultado_busqueda+'">Apellidos:</label><input type="text" id="apellidos_seguro_'+i+'_'+id_resultado_busqueda+'" name="apellidos_seguro_'+i+'_'+id_resultado_busqueda+'" style="width:100px;" onblur="javascript:call_actualizarSeguroNieve(\''+id_resultado_busqueda+'\')"/><br />');
    }
    call_actualizarSeguroNieve(id_resultado_busqueda);
}

/**
* Archivo      : validaciones.js
* Descripci�n  : funciones de validaci�n de datos en los forms
* Fecha        : 14/02/2008
* Cambios      :
* [xx/xx/xxxx] - xxxxx
*/

/**
* function jsValidaciones__ActualizarLinkUltimaBusqueda()
*/
function jsValidaciones__ActualizarLinkUltimaBusqueda(){
    $.get("functions/func_busqueda_hoteles.php", {
        func: "func_busqueda_hoteles__GeneraLinkUltimaBusqueda"
    },
    function(data){
        data=data.replace(/[\n\r\t]/g,'');
        $("#link_ultima_busqueda").html(data);
    }
    );
}


/**
* function jsValidaciones__asignaSeguroNieve()
* asigna el seguro de nieve, lo guardamos en una 
* variable de sesi�n y recalculamos el precio.
*/
function jsValidaciones__asignaSeguroNieve()
{
    $.get("functions/func_reservas.php",
    {
        func: "func_reservas__sAsignaSeguroNieve",
        param1: document.getElementById('comboSeguroNieve').value
        },
    function(data){
        data=data.replace(/[\n\r\t]/g,'');
        aValores = data.split('|');
        // alert(str);
        document.getElementById('divSeguroNieve').innerHTML = aValores[1]+" &euro;";
        document.getElementById('divPrecioFinal').innerHTML = aValores[0]+" &euro;";
    }
    );
}

/**
* function jsValidaciones__bajaIpTours()
*/  
function jsValidaciones__bajaIpTours()
{
    var bConfirm = confirm("Seguro que quieres darte de baja.");
    if(bConfirm)
    {
        //window.open("./seccion-home.html", "_self")
        $.get("functions/func_usuarios.php",
        {
            func: "func_usuarios__bajaIptours"
        },
        function(data){
            window.location = "./seccion-home.html";
        }
        );
    }
}
	
/**
* function jsValidaciones__delNewsLetter()
* borra un registro de una tabla
* que tenga el mail y el codigo, como har� referencia a una suscripci�n de una lista, ya lo borrar� correctamente
*/
function jsValidaciones__delNewsLetter()
{
    with(document.frmDelFromNews)
    {
        action = './seccion-extra,modulo-newsletter,accion-execdelnews.html';
        submit();
        }
}
	
/**
* function jsValidaciones__publicad()
*/
function jsValidaciones__publicad(sDestino, sPais, sDesde, sHasta)
{    
    document.getElementById('txt_destino_hotel').value  = sDestino;
    document.getElementById('txt_fecha_inicial').value  = sDesde;
    document.getElementById('txt_fecha_final').value    = sHasta;
    document.getElementById('comboPaises').value        = sPais;
		
    call_vValidarEjecutarBusquedaHoteles();
}
	
/**
* function jsValidaciones__ipeuros()
* marca en el registro de la reserva
* en la tabla correspondiente que se usar�n los IPEUROS, deber� devolver 
* en caso de ser afirmativo el precio total de la reserva ya sea aplicando los ipeuros o no.
*/
function jsValidaciones__ipeuros(iLocalizadorInterno)
{    
    str="";
    aValores="";
    $.get("functions/func_reservas.php",
    {
        func: "func_reservas__asignarIpEuros",
        param1: iLocalizadorInterno
    },
    function(data){
        data=data.replace(/[\n\r\t]/g,'');
        aValores    = data.split('|');
        if (document.getElementById('divPrecioFinal')){
            document.getElementById('divPrecioFinal').innerHTML = '<strong>'+aValores[0]+'&nbsp;&euro;</strong>';
            $('divPrecioFinalOnLine').html('<strong>'+aValores[3]+'&nbsp;&euro;</strong>');
        }
        if (aValores[1] == '0,00')
        {
            if (document.getElementById('divPrecioIpEuros'))
                document.getElementById('divPrecioIpEuros').innerHTML = '<b>&nbsp;&nbsp;'+aValores[1]+'&nbsp;&euro;</b>';
        }
        else
        {
            if (document.getElementById('divPrecioIpEuros'))
                document.getElementById('divPrecioIpEuros').innerHTML = '<b>&nbsp;-&nbsp;'+aValores[1]+'&nbsp;&euro;</b>';
        }
        //aviso comision
        if (aValores[2] !== ''){
            if (document.getElementById('divPrecioPasarela'))
                    document.getElementById('divPrecioPasarela').innerHTML = '<strong>'+aValores[2]+'&nbsp;&euro;</strong>';
        }
    }
    );
}

/**
* function jsValidaciones__newsOfertas()
* guarda un email en la tabla de newsletter
* la de ofertas es la lista de mailing 1
*/
function jsValidaciones__newsOfertas()
{    
    var sEmail  = document.getElementById('txt_email').value;
		
    /* CORREO */
    if(!bEmailValido("txt_email","La direcci\u00F3n de email no parece valida."))
    {
        return;
    }
		
    aFunctions = new Array();
    aRuta = new Array();
    aRuta[0]   = 'functions/func_app.php';
    aFunctions[0]   = 'func_app__addToNewsLetter';
    aParams = new Array();
    aParams[0]      = 1+"##"+sEmail;
    aTipoReturn = new Array();
    aTipoReturn[0]  = 'print|yes|';
    init_call_process("Enviando direcci&oacute;n de correo...");
}
	
/**
* function call_mostrarTmpResultados(sDestino)
*/
function call_mostrarTmpResultados(sDestino)
{    
    $.get("functions/func_busqueda_hoteles.php",
    {
        func: "func_busqueda_hoteles__sGetInfoParcialBusqueda",
        param1: sDestino
    },
    function(data){
        data=data.replace(/[\n\r\t]/g,'');
        callback_mostrarTmpResultados(data);
        $.get("core/includes/common.inc.php", {
            func: "common__getSearchProcessIndicator",
            param1: "isSearching"
        },
        function(data){
            data=data.replace(/[\n\r\t]/g,'');
            var iProcess=data;
            iProcess = removeChar(iProcess);
            if(iProcess=="0")
                clearTimeout(oTemporizador);
        });
    });
}

/**
* function callback_mostrarTmpResultados()
*/
function callback_mostrarTmpResultados(str)
{    
    aValores    = str.split('|');
    aValores[0] = removeChar(aValores[0]);
    if( (aValores[0]==="true") ||(aValores[0]===true) )
    {
        $('#modal_dialog').dialog('option', 'title', aValores[1]);
    }
}

function call_vValidarEjecutarBusquedaHotelesExtern(sElements)
{
    //alert(JSON.parse(JSON.stringify(sElements)));
    //configuracion habitacion
    var sCfgHabitaciones    = "1-"+sElements.mostrar_adultos+'-'+sElements.mostrar_menores+'-';
    if (sElements.mostrar_menores==0)sCfgHabitaciones+='0';
    else{
        for(i=1; i<=sElements.mostrar_menores; i++){
            sCfgHabitaciones+='10-';
        }
        }
    sCfgHabitaciones +='|||||';    
    
    //destino fechafinal y fechainicial han de tener valor
    if(sElements.txtDestinoHoteles==='' ||  sElements.txt_fecha_inicial==='' || sElements.txt_fecha_final==='') {
        alert ("faltan datos para realizar una b\xFAsqueda.");
        return;
    }

    

    // Informacion de busqueda
    var sDestino            = sElements.txtDestinoHoteles;
    var sPais;
    if (sElements.pais==='')
    {
        var aPaises="";
        var sPaises="";
        $.get("functions/func_busqueda_hoteles.php", {
            func: "func_busqueda_hoteles__sObtenerPaisDe",
            param1: sDestino
        },function(data){
            aPaises= data.replace(/[\n\r\t]/g,'').split('|');
            if (aPaises.length>1){
                for(i=0; i<aPaises.length; i++){
                    var sTempElements=sElements;
                    sTempElements.pais= aPaises[i];
                    var sNombre = $.ajax({
                        url: "functions/func_busqueda_hoteles.php",
                        data: "func=func_busqueda_hoteles__sGetCidadPais&param1="+sElements.txtDestinoHoteles+"&param2="+sTempElements.pais,
                        async: false
                    }).responseText;
                    sPaises+="<a href='#null' onclick='javascript:call_vValidarEjecutarBusquedaHotelesExtern("+JSON.stringify(sTempElements)+");$(\"#modal_dialog_varios_destinos\").dialog(\"close\");'>"+sNombre+"</a><br />";
                }

                $('#modal_dialog_varios_destinos').html('Se encontraron varios paises con los criterios de b&uacute;squeda seleccionados para la ciudad seleccionada.<br />' + '<div class="buscando">'+sPaises+'</div>');
                $('#modal_dialog_varios_destinos').dialog('open');
                return;
            }
            else
            {
                var sTempElements=sElements;
                sTempElements.pais= aPaises[0];
                call_vValidarEjecutarBusquedaHotelesExtern(sTempElements);
                return;
            }
        });
        return;
    }else {
        sPais=sElements.pais;
    }
    var sMensajeCargando  = '<span><img src="img/logo_tarjeta.png" style="float:left;" /><ul"><li>Estamos buscando las mejores ofertas entre m&aacute;s de 125.000 hoteles.</li><li>iPtours te garantiza la mayor fiabilidad y seguridad al momento de realizar la reserva.</li><li>Contamos con los mejores precios del sector tur&iacute;stico.</li><li>Selecciona la reserva que mejor se adapte a tus necesidades.</li></ul><span>';
    $('#modal_dialog').dialog('option', 'title', 'Buscando hoteles...');
    call_llamadaAjaxTransparenciaInicioJquery(sMensajeCargando, "", "", "", '700', '200', "./img/");

    var dFechaInicial       = sElements.txt_fecha_inicial;
    var dFechaFinal         = sElements.txt_fecha_final;
    var iHabitaciones       = 1;
    var sRegimen            = sElements.slt_regimen;
    var iEsIptoursPromocion = 0;

    // Indicamos que la p�gina a mostrar es la 1
    $.get("core/includes/common.inc.php", {
        func: "common__session_manager__saveValue",
        param1: "iPagina",
        param2: 1
    } );
    // Indicamos que empieza el proceso de b�squeda
    $.get("core/includes/common.inc.php", {
        func: "common__inicializeSearchProcessIndicator",
        param1: "isSearching"
    } );
    $.get("functions/func_busqueda_hoteles.php", { 
        func: "func_busqueda_hoteles__inicializa"
    },
    function(data){
        data=data.replace(/[\n\r\t]/g,'');
        // Lanazamos el proceso de b�squeda
        $.get("functions/func_busqueda_hoteles.php", { 
            func: "func_busqueda_hoteles__GetWebservicesUsados"
        },
        function(data){
            data=data.replace(/[\n\r\t]/g,'');
            var aws_usados=data.split('|');
            if(aws_usados[0].split('=')[1])
                $.get("functions/func_busqueda_hoteles.php",
                {
                    func: "func_busqueda_hoteles__sSearchHotels_primera_linia",
                    param1: sDestino,
                    param2: sPais,
                    param3: dFechaInicial,
                    param4: dFechaFinal,
                    param5: iHabitaciones,
                    param6: sCfgHabitaciones,
                    param7: sRegimen,
                    param8: iEsIptoursPromocion
                },
                function(data){
                    data=data.replace(/[\n\r\t]/g,'');
                    callback_vValidarEjecutarBusquedaHoteles(data);
                });
            if(aws_usados[1].split('=')[1])
                $.get("functions/func_busqueda_hoteles.php",
                {
                    func: "func_busqueda_hoteles__sSearchHotels_transhotel",
                    param1: sDestino,
                    param2: sPais,
                    param3: dFechaInicial,
                    param4: dFechaFinal,
                    param5: iHabitaciones,
                    param6: sCfgHabitaciones,
                    param7: sRegimen,
                    param8: iEsIptoursPromocion
                },
                function(data){
                    data=data.replace(/[\n\r\t]/g,'');
                    callback_vValidarEjecutarBusquedaHoteles(data);
                });
            if(aws_usados[2].split('=')[1])
                $.get("functions/func_busqueda_hoteles.php",
                {
                    func: "func_busqueda_hoteles__sSearchHotels_gta",
                    param1: sDestino,
                    param2: sPais,
                    param3: dFechaInicial,
                    param4: dFechaFinal,
                    param5: iHabitaciones,
                    param6: sCfgHabitaciones,
                    param7: sRegimen,
                    param8: iEsIptoursPromocion
                },
                function(data){
                    data=data.replace(/[\n\r\t]/g,'');
                    callback_vValidarEjecutarBusquedaHoteles(data);
                });
            if(aws_usados[3].split('=')[1])
                $.get("functions/func_busqueda_hoteles.php",
                {
                    func: "func_busqueda_hoteles__sSearchHotels_aloja",
                    param1: sDestino,
                    param2: sPais,
                    param3: dFechaInicial,
                    param4: dFechaFinal,
                    param5: iHabitaciones,
                    param6: sCfgHabitaciones,
                    param7: sRegimen,
                    param8: iEsIptoursPromocion
                },
                function(data){
                    data=data.replace(/[\n\r\t]/g,'');
                    callback_vValidarEjecutarBusquedaHoteles(data);
                });
        });
    });
    // Lanzo el muestreo de resultados
    oTemporizador=setInterval("call_mostrarTmpResultados('"+sDestino+"');", 2000);
}


/**
* function call_vValidarEjecutarBusquedaHoteles()
* funcion que valida si se puede ejecutar la b�squeda de hoteles
*/ 
function call_vValidarEjecutarBusquedaHoteles()
{        

    var sCfgHabitaciones    = "";   // Configuraci�n de habitaciones
    var sHabitacion         = "";
    var aParametros         = "";
    var iNumAdultos         = 0;
    var iNumNinos           = 0;
        
    for(i=1; i<=5; i++)
    {
        if(document.getElementById('div_habita'+i).style.visibility == "visible")
        {
            // Tratamos las habitaciones.
            sHabitacion    = document.getElementById('slt_habitacion_'+i).value;
            aParametros    = sHabitacion.split('-');  // Convierte string en array
            iNumAdultos    = aParametros[1];
            iNumNinos      = aParametros[2];
            sCfgHabitaciones += i+'-'+iNumAdultos+'-'+iNumNinos;
												
            // Edades de los ni�os
            for(j=1; j<=iNumNinos; j++)
            {
                if (document.getElementById('slt_edades_'+i+'_'+j).value != '--')
                {
                    sCfgHabitaciones += '-'+document.getElementById('slt_edades_'+i+'_'+j).value;
                }
                else
                {
                    alert('Se requieren todas las edades de los menores.');
                    return;
                }
            }
        }
        sCfgHabitaciones += '|';
    }
				
    if(!(bCampoVacio("txtDestinoHoteles","Se requiere obligatoriamente un destino.")))
    {
        return;
    }
    if(!(bComprobarFechas("txt_fecha_inicial", "txt_fecha_final")))
    {
        return;
    }

        
    sMensajeCargando = "";
    sMensajeCargando += "<div style='width:580px; height:345px; text-align:center; background:#ffffff url(./img/swf/anim_busqueda.jpg) no-repeat top center'>";
    sMensajeCargando += "   <div style='padding-top:315px'>";
    sMensajeCargando += "       <img src='./img/swf/cargando.gif' border='0'>";
    sMensajeCargando += "   </div>";
    sMensajeCargando += "   <div style='clear:both'></div>";
    sMensajeCargando += "</div>&nbsp;";
        
    $('#modal_dialog').dialog('option', 'title', 'Buscando hoteles...');
    call_llamadaAjaxTransparenciaInicioJquery(sMensajeCargando, "", "", "", '625', '410', "./img/");

    // Informaci�n de b�squeda
    var sDestino            = document.getElementById('txtDestinoHoteles').value;
    var sPais               = document.getElementById('comboPaises').value;
    var dFechaInicial       = document.getElementById('txt_fecha_inicial').value;
    var dFechaFinal         = document.getElementById('txt_fecha_final').value;
    var iHabitaciones       = document.getElementById('slt_habitaciones').value;
    var sRegimen            = document.getElementById('slt_regimen').value;
    var iEsIptoursPromocion = 0;
        
    // Indicamos que la p�gina a mostrar es la 1
    $.get("core/includes/common.inc.php", {
        func: "common__session_manager__saveValue",
        param1: "iPagina",
        param2: 1
    } );
    // Indicamos que empieza el proceso de b�squeda
    $.get("core/includes/common.inc.php", {
        func: "common__inicializeSearchProcessIndicator",
        param1: "isSearching"
    } );
    
    $.get("functions/func_busqueda_hoteles.php", {
        func: "func_busqueda_hoteles__inicializa"
    },
    function(data){
        data=data.replace(/[\n\r\t]/g,'');
        // Lanazamos el proceso de b�squeda
        $.get("functions/func_busqueda_hoteles.php", { 
            func: "func_busqueda_hoteles__GetWebservicesUsados"
        },
        function(data){
            data=data.replace(/[\n\r\t]/g,'');
            var aws_usados=data.split('|');
            if(aws_usados[0].split('=')[1])
                $.get("functions/func_busqueda_hoteles.php",
                {
                    func: "func_busqueda_hoteles__sSearchHotels_primera_linia",
                    param1: sDestino,
                    param2: sPais,
                    param3: dFechaInicial,
                    param4: dFechaFinal,
                    param5: iHabitaciones,
                    param6: sCfgHabitaciones,
                    param7: sRegimen,
                    param8: iEsIptoursPromocion
                },
                function(data){
                    data=data.replace(/[\n\r\t]/g,'');
                    callback_vValidarEjecutarBusquedaHoteles(data);
                });
            if(aws_usados[1].split('=')[1])
                $.get("functions/func_busqueda_hoteles.php",
                {
                    func: "func_busqueda_hoteles__sSearchHotels_transhotel",
                    param1: sDestino,
                    param2: sPais,
                    param3: dFechaInicial,
                    param4: dFechaFinal,
                    param5: iHabitaciones,
                    param6: sCfgHabitaciones,
                    param7: sRegimen,
                    param8: iEsIptoursPromocion
                },
                function(data){
                    data=data.replace(/[\n\r\t]/g,'');
                    callback_vValidarEjecutarBusquedaHoteles(data);
                });
            if(aws_usados[2].split('=')[1])
                $.get("functions/func_busqueda_hoteles.php",
                {
                    func: "func_busqueda_hoteles__sSearchHotels_gta",
                    param1: sDestino,
                    param2: sPais,
                    param3: dFechaInicial,
                    param4: dFechaFinal,
                    param5: iHabitaciones,
                    param6: sCfgHabitaciones,
                    param7: sRegimen,
                    param8: iEsIptoursPromocion
                },
                function(data){
                    data=data.replace(/[\n\r\t]/g,'');
                    callback_vValidarEjecutarBusquedaHoteles(data);
                });
            if(aws_usados[3].split('=')[1])
                $.get("functions/func_busqueda_hoteles.php",
                {
                    func: "func_busqueda_hoteles__sSearchHotels_aloja",
                    param1: sDestino,
                    param2: sPais,
                    param3: dFechaInicial,
                    param4: dFechaFinal,
                    param5: iHabitaciones,
                    param6: sCfgHabitaciones,
                    param7: sRegimen,
                    param8: iEsIptoursPromocion
                },
                function(data){
                    data=data.replace(/[\n\r\t]/g,'');
                    callback_vValidarEjecutarBusquedaHoteles(data);
                });
        });
    });
/// Lanzo el muestreo de resultados
//oTemporizador=setInterval("call_mostrarTmpResultados('"+sDestino+"');", 2000);
}

function callback_vValidarEjecutarBusquedaHoteles(str)
{
    if ( typeof callback_vValidarEjecutarBusquedaHoteles.llamadas == 'undefined' ) {
        callback_vValidarEjecutarBusquedaHoteles.llamadas = 0;
        }

    var contador_usados=0;
    $.get("functions/func_busqueda_hoteles.php", { 
        func: "func_busqueda_hoteles__GetWebservicesUsados"
    },
    function(data){
        data=data.replace(/[\n\r\t]/g,'');
        var aws_usados=data.split('|');
        for(var i=0;i<aws_usados.length;i++)
            if(aws_usados[i].split('=')[1]) contador_usados++;
            
            if (callback_vValidarEjecutarBusquedaHoteles.llamadas< (contador_usados-1)) {//numero de webservices en uso menos uno
                callback_vValidarEjecutarBusquedaHoteles.llamadas++;
            }
            else {
                callback_vValidarEjecutarBusquedaHoteles.llamadas=0;
                // Recuperamos los resultados:
                $.get("functions/func_busqueda_hoteles.php", {
                    func: "func_busqueda_hoteles__filtrarRepetidos"
                },
                function(data){
                    data=data.replace(/[\n\r\t]/g,'');
                    /*$.get("core/includes/common.inc.php", {
                func: "common__getSearchProcessIndicator",
                param1: "isSearching"});*/
                    $.get("functions/func_busqueda_hoteles.php", {
                        func: "func_busqueda_hoteles__sMostrarResultadosBusqueda"
                    },function(data){
                        data=data.replace(/[\n\r\t]/g,'');
                        var aValores_resultados    = data.split('|');
                        aValores_resultados[0] = removeChar(aValores_resultados[0]);

                        if (aValores_resultados[0]==='true')
                    {
                            ocultarDiv('est__divCuerpoBuscador');
                            ocultarDiv('est__divResumenBusqueda');
                            ocultarDiv('est__divFiltroBusquedas');
                            mostrarDiv('est_divCuerpoLinkNuevaBusqueda');
                            $("#est__divCuerpoCentro").html(aValores_resultados[1]);
                            $.get("functions/func_busqueda_hoteles.php", {
                                func: "func_busqueda_hoteles__ObtenerDetalleGTA"
                            },function(data){
                                data=data.replace(/[\n\r\t]/g,'');
                                callback_ObtenerDetalleGTA(data);
                            });
                        }
                        else if (aValores_resultados[0]==='false')
                    {
                            $('#modal_dialog_destinos_alternativos').html('No se han encontrado resultados, ha habido alg&uacute;n error.');
                            //$('#modal_dialog_destinos_alternativos').html('<center><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>No se han encontrado resultados, ha habido alg�n error.</center><br /><span>');
                            $('#modal_dialog_destinos_alternativos').dialog('open');
                    }
                        else if (aValores_resultados[0]==='zerohotelsfound')
                        {
                            $.get("functions/func_busqueda_hoteles.php", {
                                func: "func_busqueda_hoteles__sDestinosParecidos"
                            },function(data){
                                data=data.replace(/[\n\r\t]/g,'');
                                $('#modal_dialog_destinos_alternativos').html('No se encontraron hoteles con los criterios de b&uacute;squeda seleccionados.<br /><span>Sugerencias:</span><br />' + '<div class="buscando">'+data+'</div>');
                                $('#modal_dialog_destinos_alternativos').dialog('open');
                            });
                        //$('#modal_dialog').html('<span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>No se encontraron hoteles con los criterios de b&uacute;squeda seleccionados.<br /><span>Sugerencias:</span><br />'+aValores[1]);
                        }

                        // Indicamos que el proceso de b�squeda ha finalizado con o sin error
                        $.get("core/includes/common.inc.php",{
                            func: "common__finalizeSearchProcessIndicator",
                            param1: "isSearching"
                        });
                        $('#modal_dialog').dialog('close');
                    });
                });
            }
    });
}

function callback_ObtenerDetalleGTA(bDeboActualizar){
    if (bDeboActualizar==='true')
    {
        $.get("functions/func_busqueda_hoteles.php",{
            func: "func_busqueda_hoteles__sMostrarResultadosBusqueda"
        },
        function(data){
            data=data.replace(/[\n\r\t]/g,'');
            var aValores_resultados    = data.split('|');
            aValores_resultados[0] = removeChar(aValores_resultados[0]);
            if (aValores_resultados[0]==='true')
            {
                ocultarDiv('est__divCuerpoBuscador');
                mostrarDiv('est_divCuerpoLinkNuevaBusqueda');
                $("#est__divCuerpoCentro").html(aValores_resultados[1]);
            }
        });
    }
}
/**
* function call_vValidarEjecutarBusquedaHotelesIpOfertas()
* funcion que valida si se puede ejecutar la b�squeda de hoteles
*/ 
function call_vValidarEjecutarBusquedaHotelesIpOfertas(cOrigen, sIdExternoHotel,sDestino, sPais, dFechaInicial, dFechaFinal, iHabitaciones, sCfgHabitaciones, sRegimen)
{
    sMensajeCargando = "";
    sMensajeCargando += "<div style='width:580px; height:345px; text-align:center; background:#ffffff url(./img/swf/anim_busqueda.jpg) no-repeat top center'>";
    sMensajeCargando += "   <div style='padding-top:315px'>";
    sMensajeCargando += "       <img src='./img/swf/cargando.gif' border='0'>";
    sMensajeCargando += "   </div>";
    sMensajeCargando += "   <div style='clear:both'></div>";
    sMensajeCargando += "</div>&nbsp;";

    $('#modal_dialog').dialog('option', 'title', 'Buscando hoteles...');
    call_llamadaAjaxTransparenciaInicioJquery(sMensajeCargando, "", "", "", '625', '410', "./img/");
    
    // Indicamos que empieza el proceso de b�squeda
    $.get("core/includes/common.inc.php", {
        func: "common__inicializeSearchProcessIndicator",
        param1: "isSearching"
    } );
    $.get("functions/func_busqueda_hoteles.php", {
        func: "func_busqueda_hoteles__inicializa"
    },
    function(data){
        data=data.replace(/[\n\r\t]/g,'');
        // Lanazamos el proceso de b�squeda
        $.get("functions/func_busqueda_hoteles.php",
        {
            func: "func_busqueda_hoteles__sSearchHotelById",
            param1: cOrigen,
            param2: sIdExternoHotel,
            param3: sDestino,
            param4: sPais,
            param5: dFechaInicial,
            param6: dFechaFinal,
            param7: iHabitaciones,
            param8: sCfgHabitaciones,
            param9: sRegimen
        },
        function(data){            
            data=data.replace(/[\n\r\t]/g,'');
            callback_vValidarEjecutarBusquedaHotelesIpOfertas(data);
        });
    });    
}

function callback_vValidarEjecutarBusquedaHotelesIpOfertas(str)
{
    // Recuperamos los resultados:
    $.get("functions/func_busqueda_hoteles.php", {
        func: "func_busqueda_hoteles__filtrarRepetidos"
    },
    function(data){
        data=data.replace(/[\n\r\t]/g,'');
        $.get("functions/func_busqueda_hoteles.php", {
            func: "func_busqueda_hoteles__sMostrarResultadosBusqueda"
        },function(data){
            data=data.replace(/[\n\r\t]/g,'');
            var aValores_resultados    = data.split('|');
            aValores_resultados[0] = removeChar(aValores_resultados[0]);
            if (aValores_resultados[0]==='true')
            {
                ocultarDiv('est__divCuerpoBuscador');
                ocultarDiv('est__divResumenBusqueda');
                ocultarDiv('est__divFiltroBusquedas');
                mostrarDiv('est_divCuerpoLinkNuevaBusqueda');
                $("#est__divCuerpoCentro").html(aValores_resultados[1]);
                $.get("functions/func_busqueda_hoteles.php", {
                    func: "func_busqueda_hoteles__ObtenerDetalleGTA"
                },function(data){
                    data=data.replace(/[\n\r\t]/g,'');
                    callback_ObtenerDetalleGTA(data);
                });
            }             
            // Indicamos que el proceso de busqueda ha finalizado con o sin error
            $.get("core/includes/common.inc.php",{
                func: "common__finalizeSearchProcessIndicator",
                param1: "isSearching"
            });
            $('#modal_dialog').dialog('close');
        });
    });
}
/**
* Ha clicado en un destino alternativo
*/
function seleccionaDestinoAlternativo(sDestino)
{
    //el replace solo aplica la sustitucion una vez si el parametro inicial es una cadena, ha de ser una regexp con la g!!!
    document.getElementById('txtDestinoHoteles').value = sDestino.replace(/_/g, " ");
    mostrarDiv('est__divCuerpoBuscador');
    $('#modal_dialog_destinos_alternativos').dialog('close');
}


/** call_vValidarEjecutarBusquedaVuelosExtern(sElements)
 *valida la busqueda, y la realiza
* @param sElements objeto en formato json con los datos necesarios para realizar la busqueda
*/
function call_vValidarEjecutarBusquedaVuelosExtern(sElements)
{
    if(sElements.txtOrigenVuelos==='' || sElements.txtDestinoVuelos==='' || sElements.fsalida==='' )
    {
        alert("faltan datos para realizar la b\xFAsqueda de vuelos.");
        return(false);
    }
    if (sElements.tipo_vuelo==='ida_vuelta' && sElements.fregreso==='' )
    {
        alert("faltan datos para realizar la b\xFAsqueda de vuelos.");
        return(false);
    }
    var fecha_regreso='';
    if (sElements.tipo_vuelo==='solo_ida' )fecha_regreso=''; else fecha_regreso=sElements.fregreso;
        
    //chapuza rellenar el formulario para que al navegar por la paginacion no se queje de que le faltan datos aaaaaaaaarrjjjjj
    $('#txtOrigenVuelos').val(sElements.txtOrigenVuelos);
    $('#txtDestinoVuelos').val(sElements.txtDestinoVuelos);
    $('#origen').val(sElements.origen);
    $('#destino').val(sElements.destino);
    $('#fsalida').val(sElements.fsalida);
    $('#fregreso').val(fecha_regreso);
    $('#adultos').val(sElements.adultos);
    $('#mostrar_menores').val(sElements.mostrar_menores);
    $('#mostrar_bebes').val(sElements.mostrar_bebes);
    $('#cabina').val(sElements.cabina);
    $('#residente').val(sElements.residente);
    $('#diasflexibles').attr('checked', true);
    $('#mezclador').attr('checked', true);
    for(i=1; i<=parseInt(sElements.mostrar_menores); i++){
        $("#menor_0"+i).val("11");
    }
    for(i=1; i<=parseInt(sElements.mostrar_bebes); i++){
        
        $("#bebe_0"+i).val("11");
    }
    if (sElements.low_xml==='si') $('#low_xml').attr('checked', true); else $('#low_xml').attr('checked', false);
    if (sElements.escalas==='si') $('#escalas').attr('checked', true); else $('#escalas').attr('checked', false);
        
    //codigos iata de aeropuertos de origen y destino
    if (sElements.origen==='')
    {
        //si hay mas de un resultado me vienen en el formato XXX|YYY.......
        //dnd XXX y YYY son codigos iata de aeropuertos de 3 caracteres
        $.get("functions/func_vuelos.php",{
            func: "func_vuelos__sGetAeropuertoDeCiudad",
            param1: sElements.txtOrigenVuelos
            },
        function(data){
            var iata_origen=data.replace(/[\n\r\t]/g,'');
            if (iata_origen.length>3)
            {
                var aIataOrigenes = iata_origen.split('|');
                var sIataOrigenes="";
                for(i=0; i<aIataOrigenes.length; i++){
                    var sTempElements=sElements;
                    sTempElements.origen= aIataOrigenes[i];
                    var sNombre = $.ajax({
                        url: "functions/func_vuelos.php",
                        data: "func=func_vuelos__sGetDatosAeropuertoIata&param1="+sTempElements.origen,
                        async: false
                    }).responseText;
                    sIataOrigenes+="<a href='#null' onclick='javascript:call_vValidarEjecutarBusquedaVuelosExtern("+JSON.stringify(sTempElements)+");$(\"#modal_dialog_varios_origenes\").dialog(\"close\");'>"+sNombre+"</a><br />";
                }
                $('#modal_dialog_varios_origenes').html('Se encontraron varios aeropuertos con los criterios de b&uacute;squeda seleccionados para el origen.<br />' + '<div class="buscando">'+sIataOrigenes+'</div>');
                $('#modal_dialog_varios_origenes').dialog('open');;
            } else if (iata_origen.length==3){
                sElements.origen=iata_origen;
                call_vValidarEjecutarBusquedaVuelosExtern(sElements);
            }
        });
        return (false);
    }
    if (sElements.destino==='')
    {
        //si hay mas de un resultado me vienen en el formato |XXX|YYY.......
        //dnd XXX y YYY son codigos iata de aeropuertos de 3 caracteres
        $.get("functions/func_vuelos.php",{
            func: "func_vuelos__sGetAeropuertoDeCiudad",
            param1: sElements.txtDestinoVuelos
            },
        function(data){
            var iata_destino=data.replace(/[\n\r\t]/g,'');
            if (iata_destino.length>3)
            {
                var aIataDestinos = iata_destino.split('|');
                var sIataDestinos="";
                for(i=0; i<aIataDestinos.length; i++){
                    var sTempElements=sElements;
                    sTempElements.destino= aIataDestinos[i];
                    var sNombre = $.ajax({
                        url: "functions/func_vuelos.php",
                        data: "func=func_vuelos__sGetDatosAeropuertoIata&param1="+sTempElements.destino,
                        async: false
                    }).responseText;
                    sIataDestinos+="<a href='#null' onclick='javascript:call_vValidarEjecutarBusquedaVuelosExtern("+JSON.stringify(sTempElements)+");$(\"#modal_dialog_varios_destinos\").dialog(\"close\");'>"+sNombre+"</a><br />";
                }
                $('#modal_dialog_varios_destinos').html('Se encontraron varios aeropuertos con los criterios de b&uacute;squeda seleccionados para el destino.<br />' + '<div class="buscando">'+sIataDestinos+'</div>');
                $('#modal_dialog_varios_destinos').dialog('open');
            } else if (iata_destino.length==3){
                sElements.destino=iata_destino;
                call_vValidarEjecutarBusquedaVuelosExtern(sElements);
            }
        });
        return (false);
    }

    //contenido dialogo modal
    sMensajeCargando = "";
    sMensajeCargando += "<div style='width:580px; height:345px; text-align:center; background:#ffffff url(./img/swf/anim_vuelos.jpg) no-repeat top center'>";
    sMensajeCargando += "   <div style='padding-top:225px'>";
    sMensajeCargando += "       <img src='./img/swf/cargando.gif' border='0'>";
    sMensajeCargando += "   </div>";
    sMensajeCargando += "   <div style='clear:both'></div>";
    sMensajeCargando += "</div>&nbsp;";
    $('#modal_dialog').dialog('option', 'title', 'Se est&aacute;n buscando vuelos...');
    call_llamadaAjaxTransparenciaInicioJquery(sMensajeCargando, "", "", "", '608', '410', "./img/");

    //construir datos busqueda

    var sElementos='origen='+sElements.origen+'|destino='+sElements.destino+'|fsalida='+sElements.fsalida+'|fregreso='+sElements.fregreso+'|hsalida=28'+'|hregreso=28'+'|adultos='+sElements.adultos+'|cabina='+sElements.cabina+'|residente='+sElements.residente+'|escalas='+sElements.escalas+'|lowcost='+sElements.lowcost+'|mezclador='+sElements.mezclador;
    for(i=1; i<=sElements.mostrar_menores; i++) sElementos+='|menor_0'+i+'='+11;
    for(i=1; i<=sElements.mostrar_bebes; i++) sElementos+='|bebe_0'+i+'='+11;
    if (sElements.low_xml==='si')sElementos+='|low_xml=si';else sElementos+='|low_xml=no';//si el usuario desmarca el checkbox no me viene el valor de low_xml, lo fuerzo a no ya que reglowmixer usa si por defecto
    if (sElements.diasflexibles==='si')sElementos+='|prevDate=1|postDate=1|prevReturnDate=1|postReturnDate=1';

    $.get("functions/func_vuelos.php",{
        func: "func_vuelos__guardarBusquedaEnHistorial",
        param1: sElementos
    });
    $.get("functions/func_vuelos.php",{
        func: "func_vuelos__busqueda_v2",
        param1: sElementos
    },
    function(data){
        data=data.replace(/[\n\r\t]/g,'');
        if (data.indexOf("error") == -1)
        {
            $.get("functions/func_vuelos.php",{
                func: "func_vuelos__sInfoBusquedaVuelos"
            },
            function(data){
                data=data.replace(/[\n\r\t]/g,'');
                $("#est__divResumenBusqueda").html(data);
            });
            $.get("functions/func_vuelos.php",{
                func: "func_vuelos__MostrarFormularioFiltro"
            },
            function(data){
                $("#est__divFiltroBusquedas").html(data);
            });
            var sFiltroInicial="";
            if (sElementos.match("diasflexibles"))
            {
                //filtrar solo por fecha de ida
                var sFechaSalidaFormatoReglow ="";
                var sFechaSalida=$('#fsalida').val().replace(/\//g, "");
                sFechaSalidaFormatoReglow =sFechaSalida.slice(0,-4)+sFechaSalida.slice(-2,sFechaSalida.length);
                sFiltroInicial= "TRAYECTO[1]/VUELO[1]/ORIGEN/@FECHA="+sFechaSalidaFormatoReglow;
                if ($('#fregreso').val()!=="")
                {
                    // y filtrar por fecha de vuelta
                    var sFechaRegresoFormatoReglow ="";
                    var sFechaRegreso=$('#fregreso').val().replace(/\//g, "");
                    sFechaRegresoFormatoReglow =sFechaRegreso.slice(0,-4)+sFechaRegreso.slice(-2,sFechaRegreso.length);
                    sFiltroInicial += " and TRAYECTO[2]/VUELO[1]/ORIGEN/@FECHA="+sFechaRegresoFormatoReglow;
                }
            }
            else
            {
                sFiltroInicial="TRAYECTO/VUELO/@CIA = TRAYECTO/VUELO/@CIA ";
            }
            call_MostrarResultadosBusquedaVuelos(sFiltroInicial,"0","20");
        }
        else
        {
            //Tiene error
            $('#modal_dialog').dialog('option', 'title', 'Se ha producido un error...');
            call_llamadaAjaxTransparenciaInicioJquery("<center><br><br><table height='125'><tr><td>&nbsp;&nbsp;<img src='./img/error.gif'>&nbsp;&nbsp;</td><td><br>"+data.substr(6,data.length)+"</td></tr></table><br></center>", "", "","", 608, 205, "./img/");
            $('#est__divCuerpoBuscador').css('visibility','visible').css('display','block');
        }
    }
    );
}

/**
* function call_vValidarEjecutarBusquedaVuelos()
* funcion que valida si se puede ejecutar la b�squeda de vuelos
*/ 
function call_vValidarEjecutarBusquedaVuelos(sPagina, bEsNuevaBusqueda)
{        		
    if(!bCampoVacio("txtOrigenVuelos","Debe introducir una ciudad de origen"))
    {
        return(false);
    }
    if(!bCampoVacio("txtDestinoVuelos","Debe introducir una ciudad de destino"))
    {
        return(false);
    }
		
    var iMenores = document.getElementById('mostrar_menores').value;
    for(i=1; i<=iMenores; i++)
    {
        if(document.getElementById('menor_0'+i).value=="")
        {
            alert("Se requieren todas las edades");
            return(false);
        }
    }
		
    var iBebes = document.getElementById('mostrar_bebes').value;
    for(i=1; i<=iBebes; i++)
    {
        if(document.getElementById('bebe_0'+i).value=="")
        {
            alert("Se requieren todas las edades");
            return(false);
        }
    }
		
    if (sPagina == '-1')
    {
        sMensajeCargando = "";
        sMensajeCargando += "<div style='width:580px; height:345px; text-align:center; background:#ffffff url(./img/swf/anim_vuelos.jpg) no-repeat top center'>";
        sMensajeCargando += "   <div style='padding-top:225px'>";
        sMensajeCargando += "       <img src='./img/swf/cargando.gif' border='0'>";
        sMensajeCargando += "   </div>";
        sMensajeCargando += "   <div style='clear:both'></div>";
        sMensajeCargando += "</div>&nbsp;";
										    
        $('#modal_dialog').dialog('option', 'title', 'Se est&aacute;n buscando vuelos...');
        call_llamadaAjaxTransparenciaInicioJquery(sMensajeCargando, "", "","", '608', '410', "./img/");

        sPagina = 1;
    }
    else
    {
        call_llamadaProcesoInicio("Recuperando la p&aacute;gina "+sPagina);
    }
        
    var sElementos = formData2QueryString(document.forms["FormBuscarVuelos"]);
    if (!sElementos.match("low_xml"))sElementos+='|low_xml=no';//si el usuario desmarca el checkbox no me viene el valor de low_xml, lo fuerzo a no ya que reglowmixer usa si por defecto
    if (sElementos.match("diasflexibles"))sElementos+='|prevDate=1|postDate=1|prevReturnDate=1|postReturnDate=1';


    $.get("functions/func_vuelos.php",{
        func: "func_vuelos__guardarBusquedaEnHistorial",
        param1: sElementos
    });
    $.get("functions/func_vuelos.php",{
        func: "func_vuelos__busqueda_v2",
        param1: sElementos
    },
    function(data){
        data=data.replace(/[\n\r\t]/g,'');
        if (data.indexOf("error") == -1)
        {
            $.get("functions/func_vuelos.php",{
                func: "func_vuelos__sInfoBusquedaVuelos"
            },
            function(data){
                data=data.replace(/[\n\r\t]/g,'');
                $("#est__divResumenBusqueda").html(data);
            });
            $.get("functions/func_vuelos.php",{
                func: "func_vuelos__MostrarFormularioFiltro"
            },
            function(data){
                $("#est__divFiltroBusquedas").html(data);
            });
            var sFiltroInicial="";
            if (sElementos.match("diasflexibles"))
            {
                //filtrar solo por fecha de ida
                var sFechaSalidaFormatoReglow ="";
                var sFechaSalida=$('#fsalida').val().replace(/\//g, "");
                sFechaSalidaFormatoReglow =sFechaSalida.slice(0,-4)+sFechaSalida.slice(-2,sFechaSalida.length);
                sFiltroInicial= "TRAYECTO[1]/VUELO[1]/ORIGEN/@FECHA="+sFechaSalidaFormatoReglow;
                if ($('#fregreso').val()!=="")
                {
                    // y filtrar por fecha de vuelta
                    var sFechaRegresoFormatoReglow ="";
                    var sFechaRegreso=$('#fregreso').val().replace(/\//g, "");
                    sFechaRegresoFormatoReglow =sFechaRegreso.slice(0,-4)+sFechaRegreso.slice(-2,sFechaRegreso.length);
                    sFiltroInicial += " and TRAYECTO[2]/VUELO[1]/ORIGEN/@FECHA="+sFechaRegresoFormatoReglow;
                }
            }
            else
            {
                sFiltroInicial="TRAYECTO/VUELO/@CIA = TRAYECTO/VUELO/@CIA ";
            }
            call_MostrarResultadosBusquedaVuelos(sFiltroInicial,"0","20");
        }
        else
        {
            //Tiene error
            $('#modal_dialog').dialog('option', 'title', 'Se ha producido un error...');
            call_llamadaAjaxTransparenciaInicioJquery("<center><br><br><table height='125'><tr><td>&nbsp;&nbsp;<img src='./img/error.gif'>&nbsp;&nbsp;</td><td><br>"+data.substr(6,data.length)+"</td></tr></table><br></center>", "", "","", 608, 205, "./img/");
            $('#est__divCuerpoBuscador').css('visibility','visible').css('display','block');
        }
    }
    );

}
function call_MostrarResultadosBusquedaVuelos(filtro,pagina,resultados_por_pagina)
{
    $.get("functions/func_vuelos.php",{
        func: "func_vuelos__ActualizarVistaResultados",
        param1: filtro,
        param2: pagina,
        param3: resultados_por_pagina
    },
    function(data){
        data=data.replace(/[\n\r\t]/g,'');
        callback_vValidarEjecutarBusquedaVuelos(data);
    });
}


function callback_vValidarEjecutarBusquedaVuelos(str)
{

    $('#modal_dialog').html(" ");
    call_llamadaAjaxTransparenciaFin();
    $('#modal_dialog').dialog('close');

    if( str==='false')
    {
        alert('No se recibieron datos o se produjo un error');
    }
    else
    {
        // Ocultamos los motores
        ocultarDiv('est__divCuerpoBuscador');
        mostrarDiv('est__divResumenBusqueda');
        mostrarDiv('est__divFiltroBusquedas');
        mostrarDiv('est_divCuerpoLinkNuevaBusqueda');
        $("#est__divCuerpoCentro").html(str);
        $("#labelFiltroActualizado").effect("pulsate", {
            times:3
        }, 800,function(){
            $('#labelFiltroActualizado').hide()
            });
    }
}        

/**
* function call_vuelosReservasPaso02(sNombreFormulario)
*/
function call_vuelosReservasPaso02(sNombreFormulario)
{        
    if(!iGetRadioButtonSelectedValue(document.forms[sNombreFormulario].rbt_seguro))
    {
        alert("Debes seleccionar una opci\xF3n para el seguro.");
        return false;
    }
    with(document.forms[sNombreFormulario])
    {
        submit();
        }
}

/**
* function call_vuelosReservasPaso03()  
* funci�n que ejecuta la llamada al ws para
* realizar la reserva
*/
function call_vuelosReservasPaso03(sNombreFormulario)  
{
    // Compruebo que esten seleccionadas las checkbox
    if(!bCheckBoxSeleccionada("chk_acepto0", "Para continuar con la reserva debe aceptar las condiciones generales y de privacidad."))
    {
        return(false);
    }
    if(!bCampoVacio("tlfp","Debe introducir como m\xEDnimo un tel\xE9fono."))
    {
        return(false);
    }
    if(!bCampoVacio("direnvio","Debe introducir una direcci\xF3n de env\xEDo."))
    {
        return(false);
    }
    if(!bCampoVacio("codigopostal","Debe introducir un codigo postal."))
    {
        return(false);
    }
    if(!bCampoVacio("ciudad","Debe introducir una ciudad de env\xEDo."))
    {
        return(false);
    }
    if(!bCampoVacio("emailenvio","Debe introducir un email de env\xEDo."))
    {
        return(false);
    }

        

		
    // Comprobamos si se han introducido
    var iNumAdultos = removeChar($.ajax({
        url: "core/includes/common.inc.php",
        data: "func=common__session_manager__getValue&param1=NUM_ADULTOS",
        async: false
    }).responseText);
    var iNumMenores = removeChar($.ajax({
        url: "core/includes/common.inc.php",
        data: "func=common__session_manager__getValue&param1=NUM_MENORES",
        async: false
    }).responseText);
    var iNumBebes = removeChar($.ajax({
        url: "core/includes/common.inc.php",
        data: "func=common__session_manager__getValue&param1=NUM_BEBES",
        async: false
    }).responseText);

    // alert(iNumAdultos+' '+iNumMenores+' '+iNumBebes);
		
    // Revisamos que esten las textboxs llenas
    if(iNumAdultos>0)
    {
        for(i=1; i<=iNumAdultos; i++)
        {
            if(!bCampoVacio("nombrea"+i,"Debe introducir todos los Nombres"))
            {
                return(false);
            }
            if(!bCampoVacio("apellidoa"+i,"Debe introducir todos los Apellidos"))
            {
                return(false);
            }
            if(!bCampoVacio("dnia"+i,"Debe introducir todos los Documentos de Identificaci\xF3n"))
            {
                return(false);
            }       
        }
    }
    if(iNumMenores>0)
    {
        for(i=1; i<=iNumMenores; i++)
        {
            if(!bCampoVacio("nombrem"+i,"Debe introducir todos los Nombres"))
            {
                return(false);
            }
            if(!bCampoVacio("apellidom"+i,"Debe introducir todos los Apellidos"))
            {
                return(false);
            }
            if(!bCampoVacio("dnim"+i,"Debe introducir todos los Documentos de Identificaci\xF3n"))
            {
                return(false);
            }
        }
    }
    if(iNumBebes>0)
    {
        for(i=1; i<=iNumBebes; i++)
        {
            if(!bCampoVacio("nombreb"+i,"Debe introducir todos los Nombres"))
            {
                return(false);
            }
            if(!bCampoVacio("apellidob"+i,"Debe introducir todos los Apellidos"))
            {
                return(false);
            }
            if(!bCampoVacio("dnib"+i,"Debe introducir todos los Documentos de Identifiaci\xF3n"))
            {
                return(false);
            }
        }
    }
		
    var sElementos  = formData2QueryString(document.forms[sNombreFormulario]);
		
    $.get("functions/func_vuelos.php", {
        func: "func_vuelos__comprobarUsuario",
        param1: sElementos
    },
    function(data){
        data=data.replace(/[\n\r\t]/g,'');

        aValores        = data.split('|');
        aValores[0]     = removeChar(aValores[0]);
        if( (aValores[0]==='false') || (aValores[0]===false) )
        {
            alert(aValores[1]);
        }
        else
        {
            // Lanazamos el proceso de b�squeda
            with(document.forms[sNombreFormulario])
            {
                submit();
                }
        }
    });
}

/**
* function vValidarSeguroSeleccionado()
* funci�n que comprueba si se ha seleccionado o no el seguro
*/
function vValidarSeguroSeleccionado()
{
    with(document.frm_reserva_paso1)
    {
        if( (rbt_seguro[0].checked==false) && (rbt_seguro[1].checked==false) )
        {
            alert("Seleccione si desea o no contratar el seguro de la Reserva");
            rbt_seguro.focus();
            rbt_seguro.style.background="#FFF0F0";
            return;
        }
        else
        {
            action = "index.php";
            submit();
        }
        }
}
 
/**
* function validar_usuario
* valida los datos al dar de alta un usuario
*/
function validaciones__altaUsuarioExec() //se puede mandar como parametro el modulo
{    
    with(document.frmAltaUsuario)
    {
        /* LOGIN */
        if(!bCampoVacio("USUARIO","El Nombre de usuario no puede estar en blanco."))
        {
            return;
        }
        /* CLAVE */
        if(!bCampoVacio("PASSWORD","La clave no puede estar en blanco."))
        {
            return;
        }
        /* LONGITUD CLAVE */
        if(!bLongitudMinima("PASSWORD","La clave debe tener como m\xEDnimo 6 digitos.", 6))
        {
            return;
        }
        /* REPETIR CLAVE */
        if(!bCampoVacio("REPASSWORD","La validaci\xF3n de la clave no puede estar en blanco."))
        {
            return;
        }
        /* REPETIR CLAVE LONGITUD */
        if(!bLongitudMinima("REPASSWORD", "La validaci\u00F3n de la clave debe tener como m\u00EDnimo 6 d\u00EDgitos.", 6))
        {
            return;
        }
        /* CLAVE = REPETIR CLAVE */
        if(!bSonIguales("PASSWORD","REPASSWORD", "La clave y la validaci\u00F3n No son iguales."))
        {
            return;
        }
        /* CORREO */
        if(!bEmailValido("EMAIL","La direcci\u00F3n de email no puede estar en blanco."))
        {
            return;
        }
        //comprobar que existe en la base de datos (caso contrario error)
        if ($('#EMAIL_RECOMENDADO_POR').val()!=""){
            $.get("functions/func_usuarios.php",
            {
                func: "func_usuarios__bEsMailRecomendacionValido",
                param1: $('#EMAIL_RECOMENDADO_POR').val()
            },
            function(data){
                var pk_usuario=data.replace(/[\n\r\t]/g,'');
                if (pk_usuario!='false')
                    param1: $('#ID_RECOMENDADO_POR').val(pk_usuario);
                else {
                    alert("El Email de la recomendaci\u00F3n no existe en nuestra base de datos.  ");
                    $('#EMAIL_RECOMENDADO_POR').focus();
                    return;
                }

            });
        }


        // Premios Fitur 2009:
        if (document.getElementById('FITUR_PREMIO')) {
            /* CLAVE FITUR */
            if (document.getElementById('FITUR_PREMIO').value != '0')
            {
                if(!bCampoVacio("FITUR_CODIGO_SEG","La clave FITUR no puede estar en blanco."))
                {
                    return;
                }
            }
        }

        /* NOMBRE */
        /*
		if(!bCampoVacio("NOMBRE","El Nombre no puede estar en blanco."))
		{
			return;
		}
        */
        /* APELLIDOS */
        /*
		if(!bCampoVacio("APELLIDO1","El Apellido no puede estar en blanco."))
		{
			return;
		}
        */
        /* SEXO */
        /*
		if(!(iGetRadioButtonSelectedValue(SEXO)))
		{
			alert('Seleccione su sexo');
			return;
		}		
        */
        if(!chk_acepto0.checked)
        {
            chk_acepto0.focus();
            alert("Para darse de alta como usuario registrado debe marcar la casilla aceptando las Condiciones de privacidad y de uso.");
            return;
        }
        submit();
        }
}

/**
* function vValidarContactar()
* valida los datos del formulario de contacto
*/ 
function vValidarContactar()
{
    with(document.frm_contactar)
    {
        /* Nombre */
        if(!bCampoVacio("Nombre","Por favor, escriba su nombre."))
        {
            return;
        }

        /* CORREO */
        if(!bEmailValido("Email","La direcci\xF3n de email no puede estar en blanco."))
        {
            return;
        }

        /* Asunto */
        if(!bCampoVacio("Asunto","Por favor, escriba su direcci\xF3n de email."))
        {
            return;
        }

        /* mensaje */
        if(!bCampoVacio("Mensaje","Por favor, escriba su mensaje."))
        {
            return;
        }
				
        var sElementos = formData2QueryString(document.forms["frm_contactar"]);
        //var str = agent.call('','func_app__sEnviarFormularioContacto','',sElementos);
        $.get("functions/func_app.php", {
            func: "func_app__sEnviarFormularioContacto",
            param1: sElementos
        });
        aRespuesta      =  str.split('|');
        aRespuesta[0]   = removeChar(aRespuesta[0]);
        // Si fue correcto cerramos las capas.
        if( (aRespuesta[0]==="true") || (aRespuesta[0]===true))
        {
            alert(aRespuesta[1]);
            call_llamadaAjaxTransparenciaFin();
        }
        }
}

/**
* function vValidarUsuarioLogin()
* Funci�n que permite verificar si el usuario y la clave esta vacia
*/
function vValidarUsuarioLogin()
{
    with(document.frm_usuario_login)
    {
        if(!bCampoVacio("txt_usuario","Debes introducir tu nombre de usuario."))
        {
            return;
        }
        if(!bCampoVacio("txt_clave","La clave no puede estar en blanco."))
        {
            return;
        }
        action="./validacion.php";
        submit();
        }
}

/**
* function validar_usuario_logoff() 
* funcion para realizar validaciones antes de logoff() del usuario
*/
function vValidarUsuarioLogoff()
{
    with(document.frm_usuario_logoff)
    {
        action="./validacion.php";
        submit();
        }
}

/**
* function validar_recordar_clave()
* validaciones y mostrar el formulario de recordar password
*/
function validaciones__recordarPasswordExec()
{
    // Comprobamos que el email sea v�lido
    if(!bEmailValido("txt_email", "El campo email no puede estar en blanco."))
    {
        return;
    }
		
    sEmail = document.getElementById('txt_email').value;
		
    aFunctions = new Array();
    aRuta = new Array();
    aRuta[0]   = 'functions/func_usuarios.php';
    aFunctions[0]   = 'func_usuarios__recordarPasswordExec';
    aParams = new Array();
    aParams[0]      = sEmail+'##';
    aTipoReturn = new Array();
    aTipoReturn[0]  = 'print|yes|';
    init_call_process("Enviando datos...");
}

/**
* function validarReservasUsarMismosDatos()
* asigna a unas textboxes los mismos datos
*/
function vValidarReservasUsarMismosDatos()
{
    vIgualarCampos("txt_huesped_nombre"     , "NOMBRE");
    sApellido1 = document.getElementById('APELLIDO1').value;
    sApellido2 = document.getElementById('APELLIDO2').value;
    document.getElementById('txt_huesped_apellidos').value = sApellido1+" "+sApellido2;
    vIgualarCampos("txt_huesped_email"      , "EMAIL");
    if (document.getElementById('MOVIL').value !="")
        vIgualarCampos("txt_huesped_fono_movil" , "MOVIL");
    else if (document.getElementById('TELEFONO').value !="")
        vIgualarCampos("txt_huesped_fono_movil" , "TELEFONO");
    else document.getElementById('txt_huesped_fono_movil').value ="";
	 
}

/**
* function validarReservasUsarMismosDatosVuelos()
* asigna a unas textboxes los mismos datos
*/
function vValidarReservasUsarMismosDatosVuelos()
{
        
    //vIgualarCampos("nombrea1", "NOMBRE");
    //vIgualarCampos("dnia1"   , "VALOR_NIF_PASAPORTE");
    vIgualarCampos("tlfp"    , "TELEFONO");
    vIgualarCampos("tlfo"    , "MOVIL");
    vIgualarCampos("emailenvio"   , "EMAIL");
		
    // Combo de País
    document.getElementById('pais').selectedIndex = document.getElementById('FK_PAIS').selectedIndex

    // Combo de documento
    document.getElementById('doc_typea1').selectedIndex = document.getElementById('TIPO_NIF_PASAPORTE').selectedIndex;
		
    // Nombre
    document.getElementById('nombrea1').value = document.getElementById('NOMBRE').value;

    // Apellidos
    document.getElementById('apellidoa1').value = document.getElementById('APELLIDO1').value+' '+document.getElementById('APELLIDO2').value;

    // Combo de Nif/pasaporte
    document.getElementById('doc_typea1').selectedIndex = document.getElementById('TIPO_NIF_PASAPORTE').selectedIndex

    // Nif/pasaporte
    document.getElementById('dnia1').value = document.getElementById('VALOR_NIF_PASAPORTE').value;

		
    // Obtenemos algunos datos que faltan como la direcci�n de envio cp y ciudad
    //var str         = agent.call('', 'func_vuelos__obtenerMasDatosUsuarios', '', document.getElementById('hPkUsuario').value );
    $.get("functions/func_vuelos.php", {
        func: "func_vuelos__obtenerMasDatosUsuarios",
        param1: document.getElementById('hPkUsuario').value
        },
    function(data){
        data=data.replace(/[\n\r\t]/g,'');
        var aValores    = data.split('|');
        aValores[0]     = removeChar(aValores[0]);
        if( (aValores[0]===true) || (aValores[0]==='true') )
        {
            document.getElementById('direnvio').value = aValores[1];
            document.getElementById('codigopostal').value = aValores[2];
            document.getElementById('ciudad').value = aValores[3];
        }
        else
        {
            alert("Error al obtener datos del usuario");
        }
    }
    );
}

function jsValidaciones__asignaPais()
{
    //alert(document.getElementById('comboPaises').value);
    $("#txtDestinoHoteles").flushCache();
    $.get("core/includes/common.inc.php", {
        func: "common__session_manager__saveValue",
        param1: "pk_pais",
        param2: document.getElementById('comboPaises').value
        } );
}

function jsValidaciones__asignaPaisNieve()
{
    //alert(document.getElementById('comboPaises').value);
    $("#txtDestinoHoteles").flushCache();
    $.get("core/includes/common.inc.php", {
        func: "common__session_manager__saveValue",
        param1: "pk_paisNieve",
        param2: document.getElementById('comboPaisesNieve').value
        } );
}

/**
* function jsValidacionesUsarDatosEnHuespedes()
*/
function jsValidacionesUsarDatosEnHuespedes()
{
    document.getElementById('hgta_1').value = document.getElementById('NOMBRE').value+', '+document.getElementById('APELLIDO1').value + ' ' + document.getElementById('APELLIDO2').value;    
}

//////////////////////////////////
////// FUNCIONES DE LA RSO ///////
//////////////////////////////////

/**
*
*/
function jsValidaciones__seleccionaAvatar(sFile)
{        
    // Proceso de llamadas as�ncronas
    aFunctions = new Array();
    aRuta = new Array();
    aRuta[0]   = 'functions/func_usuarios.php';
    aFunctions[0] = 'func_usuarios__seleccionaAvatar';
    aRuta[1]   = 'functions/func_usuarios.php';
    aFunctions[1] = 'func_usuarios__visualizarPerfil';
    aParams = new Array();
    aParams[0] = sFile+'##';
    aParams[1] = '##';
    aTipoReturn = new Array();
    aTipoReturn[0] = 'noprint|yes';
    aTipoReturn[1] = 'print|no|var__DivComunidadDer';
    init_call_process("Asignando Avatar....");
}

/**
* function validaciones__vValidarInformacionViajero()
*/
function validaciones__vValidarInformacionViajero()
{            
    var sElementos  = formData2QueryString(document.forms["frm_informacion_viajero"]);
    // Proceso de llamadas as�ncronas
    aFunctions = new Array();
    aRuta = new Array();
    aRuta[0]   = 'functions/func_app_rso.php';
    aFunctions[0] = 'func_app_rso__sActualizaInformacionViajero';
    aParams = new Array();
    aParams[0] = sElementos+'##';
    aTipoReturn = new Array();
    aTipoReturn[0] = 'print|yes';
    init_call_process("Actualizando datos....");
}

/**
* function validaciones__vValidarInteresesAficionesViajero()
*/
function validaciones__vValidarInteresesAficionesViajero()
{    
    var sElementos  = formData2QueryString(document.forms["frm_interesesyaficiones"]);
    // Proceso de llamadas as�ncronas
    aFunctions = new Array();
    aRuta = new Array();
    aRuta[0]   = 'functions/func_app_rso.php';
    aFunctions[0] = 'func_app_rso__sActualizaInteresesAficionesViajero';
    aParams = new Array();
    aParams[0] = sElementos+'##';
    aTipoReturn = new Array();
    aTipoReturn[0] = 'print|yes';
    init_call_process("Actualizando datos....");
}

/**
* function validaciones__vValidarDatosPersonales()
*/
function validaciones__vValidarDatosPersonales()
{           
    var sElementos  = formData2QueryString(document.forms["frm_DatosPersonales"])+'|POBLACION_OTROS=';
    // Proceso de llamadas as�ncronas
    aFunctions = new Array();
    aRuta = new Array();
    aRuta[0]   = 'functions/func_app_rso.php';
    aFunctions[0] = 'func_app_rso__sActualizarDatosPersonales';
    aRuta[1]   = 'functions/func_usuarios.php';
    aFunctions[1] = 'func_usuarios__datosPersonales';
    aParams = new Array();
    aParams[0] = sElementos+'##';
    aParams[1] = '##';
    aTipoReturn = new Array();
    aTipoReturn[0] = 'noprint|yes';
    aTipoReturn[1] = 'print|no|var__DivComunidadDer';
    init_call_process("Actualizando datos....");
}

/**
* function agregar_favoritos()
*/
function agregar_favoritos()
{ 
    var url     = "http://www.iptours.com" ;
    var titulo  = "iPtours.com, Hoteles - Vuelos";
    if (window.sidebar&&window.sidebar.addPanel)
    {
        window.sidebar.addPanel(titulo,url,"");
    }
    else
    {
        window.external.AddFavorite(url,titulo);
    }
} 

/**
* function validaciones__ColocarCursorUsuario()
*/ 

function validaciones__ColocarCursorUsuario()
{
    document.getElementById('txt_usuario').value='';
}

function validaciones__ColocarCursorOfertasCorreo()
{

    document.getElementById('txt_email').value='';
}

/**
* function validaciones__ColocarCursorClave()
*/

function validaciones__ColocarCursorClave()
{
    document.getElementById('txt_clave').value='';
}

/**
* function validaciones__UsuarioClave(form)
*/
function validaciones__UsuarioClave(form)
{

    if (form.txt_usuario.value == "")
    {
        alert("El nombre de usuario no puede estar vac\xEDo");
        form.txt_usuario.focus();
        form.txt_usuario.style.background="#FFF0F0";
        return false;
    }

    if (form.txt_usuario.value == "Nombre de usuario")
    {
        alert("Debe cambiar el nombre del usuario que escribi\xF3 el sistema");
        form.txt_usuario.value='';
        form.txt_usuario.focus();
        form.txt_usuario.style.background="#FFF0F0";
        return false;
    }
		
    if (form.txt_clave.value == "")
    {
        alert("Ingrese su clave");
        form.txt_clave.focus();
        form.txt_clave.style.background="#FFF0F0";
        return false;
    }

		
    if (form.txt_clave.value == "*************")
    {
        alert("Debe cambiar la clave que escribi\xF3 el sistema");
        form.txt_clave.value='';
        form.txt_clave.focus();
        form.txt_clave.style.background="#FFF0F0";
        return false;
    }
    // alert(form.txt_usuario.value);
    // alert(form.txt_clave.value);

    form.action="./validacion.php";
    form.submit();

}

/**
* function validaciones__ocultarMostrarDiv()
*/
function validaciones__ocultarMostrarDiv(capaOcultar, capaIcono)
{
 
    var xOcultar = document.getElementById(capaOcultar);
    var xIcono = document.getElementById(capaIcono);
		
    if (xOcultar.style.visibility == 'hidden')
    {
        xIcono.innerHTML            = '<a href="#" onclick=validaciones__ocultarMostrarDiv("'+capaOcultar+'","'+capaIcono+'")><img src="img/flecha_arriba.jpg" border="0" title="Ocultar informaci�n" /></a>';
        xOcultar.style.display      = 'block';
        xOcultar.style.visibility   = 'visible';
    }
    else
    {
        xIcono.innerHTML            = '<a href="#" onclick=validaciones__ocultarMostrarDiv("'+capaOcultar+'","'+capaIcono+'")><img src="img/flecha_abajo.jpg" border="0" title="Mostrar informaci�n" /></a>';
        xOcultar.style.display      = 'none';
        xOcultar.style.visibility = 'hidden';
    }
}


/**
* function call_vValidarEjecutarPreReserva()
* funcion que valida si se puede ejecutar la b�squeda de hoteles
*/ 
function call_vValidarPulsarPagar(sNombreFormulario)
{           
    var sElementos = formData2QueryString(document.forms[sNombreFormulario]);
						
    // Lanazamos el proceso de b�squeda
    //agent.call('', 'func_vuelos__haPulsadoPagar', '', sElementos);
    $.get("functions/func_vuelos.php", {
        func: "func_vuelos__haPulsadoPagar",
        param1: sElementos
    });
    document.frmProcesoPago.submit();
}

/**
* function jsSeleccionDestinoAeropuerto()
*/
function jsSeleccionDestinoAeropuerto()
{        
    document.getElementById('destino').value = document.getElementById('destino_visible').value;
}

/**
* function jsSeleccionOrigenAeropuerto()
*/
function jsSeleccionOrigenAeropuerto()
{
    document.getElementById('origen').value = document.getElementById('origen_visible').value;
}

function addZero(vNumber){
    return ((vNumber < 10) ? "0" : "") + vNumber
}
/**
* function formatDate(vDate, vFormat)
* da formato a una fecha
* @param sDate
* fecha a formatear en formato string
* @param vFormat
* dd for Date of the month
* MM for month
* yyyy for Year
* @return devuelve un string con la fecha con el formato dado
*/
function formatDate(sDate, vFormat){
    var dayfield    = sDate.split("/")[0];
    var monthfield  = sDate.split("/")[1];
    var yearfield   = sDate.split("/")[2];
    var vDate = new Date(yearfield, monthfield-1, dayfield);
    var vDay              = addZero(vDate.getDate());
    var vMonth            = addZero(vDate.getMonth()+1);
    var vYearLong         = addZero(vDate.getFullYear());    
    return vFormat.replace(/dd/g, vDay).replace(/MM/g, vMonth).replace(/yyyy/g, vYearLong);
}

function call_iTurismo__BuscarRegiones(){
    if( $('#txt_buscar_regiones').val()!=""){
        $('#txt_buscar_regiones').css({backgroundColor: '#f9d49d'});
        //mostrar dialogo de buscando
        call_llamadaProcesoInicio("Buscando regiones... ");
        $.get(
            "functions/func_iTurismo.php",
            {
                // Lanazamos el proceso de busqueda
                func: "func_iTurismo__buscarPorRegion",
                param1: $('#txt_buscar_regiones').val()
            },
            function(data){
                data=data.replace(/[\n\r\t]/g,'');
                callback_iTurismo__BuscarRegiones(data);
            });
    } else {
        alert ("Debes introducir alguna regi\xF3n.");
        $('#txt_buscar_regiones').css({backgroundColor: '#f9d49d'});
    }
    
}

function callback_iTurismo__BuscarRegiones(str)
{
    call_llamadaProcesoFin();
    $("#container_inferior").html(str);
}



function call_vValidarEjecutarBusquedaHotelesNieve()
{

    var sCfgHabitaciones    = "";
    var sHabitacion         = "";
    var aParametros         = "";
    var iNumAdultos         = 0;
    var iNumNinos           = 0;

    for(i=1; i<=5; i++)
    {
        if(document.getElementById('div_habita_nieve'+i).style.visibility == "visible")
        {
            // Tratamos las habitaciones.
            sHabitacion    = document.getElementById('slt_habitacion_nieve_'+i).value;
            aParametros    = sHabitacion.split('-');  // Convierte string en array
            iNumAdultos    = aParametros[1];
            iNumNinos      = aParametros[2];
            sCfgHabitaciones += i+'-'+iNumAdultos+'-'+iNumNinos;

            // Edades de los ni�os
            for(j=1; j<=iNumNinos; j++)
            {
                if (document.getElementById('slt_edades_nieve_'+i+'_'+j).value != '--')
                {
                    sCfgHabitaciones += '-'+document.getElementById('slt_edades_nieve_'+i+'_'+j).value;
                }
                else
                {
                    alert('Se requieren todas las edades de los menores.');
                    return;
                }
            }
        }
        sCfgHabitaciones += '|';
    }

    if(!(bCampoVacio("txtDestinoHotelesNieve","Se requiere obligatoriamente un destino.")))
    {
        return;
    }
    if(!(bComprobarFechas("txt_fecha_inicial_nieve", "txt_fecha_final_nieve")))
    {
        return;
    }


    var sMensajeCargando = "";
    sMensajeCargando += "<div style='width:580px; height:345px; text-align:center; background:#ffffff url(./img/swf/anim_busqueda.jpg) no-repeat top center'>";
    sMensajeCargando += "   <div style='padding-top:315px'>";
    sMensajeCargando += "       <img src='./img/swf/cargando.gif' border='0'>";
    sMensajeCargando += "   </div>";
    sMensajeCargando += "   <div style='clear:both'></div>";
    sMensajeCargando += "</div>&nbsp;";

    // Informaci�n de b�squeda
    var sDestino            = document.getElementById('txtDestinoHotelesNieve').value;
    var sPais               = document.getElementById('comboPaisesNieve').value;
    var dFechaInicial       = document.getElementById('txt_fecha_inicial_nieve').value;
    var dFechaFinal         = document.getElementById('txt_fecha_final_nieve').value;
    var iHabitaciones       = document.getElementById('slt_habitaciones').value;
    var sRegimen            = document.getElementById('slt_regimen').value;
    var iEsIptoursPromocion = 0;

    

    $.get("functions/func_busqueda_hoteles.php", {
        func: "func_busqueda_hoteles__inicializa"
    },

        function(data){
        data=data.replace(/[\n\r\t]/g,'');
        // Lanazamos el proceso de b�squeda

        $.get("functions/func_busqueda_hoteles.php", {
            func: "func_busqueda_hoteles__GetWebservicesUsados"
        },
        function(data){
            data=data.replace(/[\n\r\t]/g,'');
            var aws_usados=data.split('|');
            if(aws_usados[0].split('=')[1]){
                $('#modal_dialog').dialog('option', 'title', 'Buscando hoteles de nieve...');
                call_llamadaAjaxTransparenciaInicioJquery(sMensajeCargando, "", "", "", '625', '410', "./img/");

                // Indicamos que la p�gina a mostrar es la 1
                $.get("core/includes/common.inc.php", {
                    func: "common__session_manager__saveValue",
                    param1: "iPagina",
                    param2: 1
                } );
                // Indicamos que empieza el proceso de b�squeda
                $.get("core/includes/common.inc.php", {
                    func: "common__inicializeSearchProcessIndicator",
                    param1: "isSearching"
                } );

                $.get("functions/func_busqueda_hoteles.php",
                {
                    func: "func_busqueda_hoteles__sSearchHotels_primera_linia_nieve",
                    param1: sDestino,
                    param2: sPais,
                    param3: dFechaInicial,
                    param4: dFechaFinal,
                    param5: iHabitaciones,
                    param6: sCfgHabitaciones,
                    param7: sRegimen,
                    param8: iEsIptoursPromocion
                },
                function(data){
                    data=data.replace(/[\n\r\t]/g,'');
                    callback_vValidarEjecutarBusquedaHotelesNieve(data);
                });
            } else {
                call_llamadaAjaxTransparenciaInicioJquery("Servicio temporalmente no disponible", "", "", "", '300', '200', "./img/");
            }

        });


        

    });
/// Lanzo el muestreo de resultados
//oTemporizador=setInterval("call_mostrarTmpResultados('"+sDestino+"');", 2000);
}

function callback_vValidarEjecutarBusquedaHotelesNieve(str)
{
    // Recuperamos los resultados:
    $.get("functions/func_busqueda_hoteles.php", {
        func: "func_busqueda_hoteles__sMostrarResultadosBusqueda"
    },function(data){
        data=data.replace(/[\n\r\t]/g,'');
        var aValores_resultados    = data.split('|');
        aValores_resultados[0] = removeChar(aValores_resultados[0]);

        if (aValores_resultados[0]==='true')
        {
            ocultarDiv('est__divCuerpoBuscador');
            ocultarDiv('est__divResumenBusqueda');
            ocultarDiv('est__divFiltroBusquedas');
            mostrarDiv('est_divCuerpoLinkNuevaBusqueda');
            $("#est__divCuerpoCentro").html(aValores_resultados[1]);
        }
        else if (aValores_resultados[0]==='false')
        {
            $('#modal_dialog_destinos_alternativos').html('No se han encontrado resultados, ha habido alg&uacute;n error.');
            $('#modal_dialog_destinos_alternativos').dialog('open');
        }
        else if (aValores_resultados[0]==='zerohotelsfound')
        {
            $.get("functions/func_busqueda_hoteles.php", {
                func: "func_busqueda_hoteles__sDestinosCercanosNieve"
            },function(data){
                data=data.replace(/[\n\r\t]/g,'');
                $('#modal_dialog_destinos_alternativos').html('No se encontraron hoteles con los criterios de b&uacute;squeda seleccionados.<br /><span>Sugerencias:</span><br />' + '<div class="buscando">'+data+'</div>');
                $("#accordion_destinos_alternativos_nieve").accordion({ animated: 'bounceslide',autoHeight: false,clearStyle: true,collapsible: true,active:false });
                $('#modal_dialog_destinos_alternativos').css('top','20px');
                $('#modal_dialog_destinos_alternativos').dialog('open');
                

            });
        }
        // Indicamos que el proceso de b�squeda ha finalizado con o sin error
        $.get("core/includes/common.inc.php",{
            func: "common__finalizeSearchProcessIndicator",
            param1: "isSearching"
        });
        $('#modal_dialog').dialog('close');
    });
}
function seleccionaDestinoAlternativoNieve(sDestino)
{
    //el replace solo aplica la sustitucion una vez si el parametro inicial es una cadena, ha de ser una regexp con la g!!!
    document.getElementById('txtDestinoHotelesNieve').value = sDestino.replace(/_/g, " ");
    mostrarDiv('est__divCuerpoBuscador');
    $('#modal_dialog_destinos_alternativos').dialog('close');
}

function PosRegional__MostrarOcultarMapa(id){
    if(document.getElementById(id).style.display=='none')
        document.getElementById(id).style.display='block';
    else
        document.getElementById(id).style.display='none';
    cargar_mapa();
}

function PosRegional__PrepararBuscarPorHotel(id_hotel,nombre_hotel,url)
{
    $("#txtIdHotel").val(id_hotel);
    $("#txtHotel").html("<label>Hotel:</label><br>"+nombre_hotel);
    $("#txt_fecha_inicial").datepicker('show');
    document.frm_hoteles.action= url;
}

function PosRegional__BuscarPorHotel()
{
    var sCfgHabitaciones    = "";
    var sHabitacion         = "";
    var aParametros         = "";
    var iNumAdultos         = 0;
    var iNumNinos           = 0;

    if($("#txtIdHotel").val()=='')
        {
        alert("Debe seleccionar un hotel");
        return;
        }
    if($("#txt_fecha_inicial").val()=='' || $("#txt_fecha_final").val()=='')
        {
        alert("Debe seleccionar fecha de entrada y salida");
        return;
        }
    for(i=1; i<=5; i++)
    {
        if(document.getElementById('div_habita'+i).style.visibility == "visible")
        {
            // Tratamos las habitaciones.
            sHabitacion    = document.getElementById('slt_habitacion_'+i).value;
            aParametros    = sHabitacion.split('-');  // Convierte string en array
            iNumAdultos    = aParametros[1];
            iNumNinos      = aParametros[2];
            sCfgHabitaciones += i+'-'+iNumAdultos+'-'+iNumNinos;

            // Edades de los ni�os
            for(j=1; j<=iNumNinos; j++)
            {
                if (document.getElementById('slt_edades_'+i+'_'+j).value != '--')
                {
                    sCfgHabitaciones += '-'+document.getElementById('slt_edades_'+i+'_'+j).value;
                }
                else
                {
                    alert('Se requieren todas las edades de los menores.');
                    return;
                }
            }
        }
        sCfgHabitaciones += '|';
    }
    //Guardamos configuración habitaciones
    $("#sCfgHabitaciones").val(sCfgHabitaciones);

    document.frm_hoteles.submit();
}

function PosRegional__BuscarHoteles()
{
    var sCfgHabitaciones    = "";
    var sHabitacion         = "";
    var aParametros         = "";
    var iNumAdultos         = 0;
    var iNumNinos           = 0;

    if($("#txtDestinoHoteles").val()=='')
    {
		alert("Se requiere obligatoriamente un destino.");
        return;
    }
    if($("#txt_fecha_inicial").val()=='' || $("#txt_fecha_final").val()=='')
        {
        alert("Debe seleccionar fecha de entrada y salida");
        return;
        }
    for(i=1; i<=5; i++)
    {
        if(document.getElementById('div_habita'+i).style.visibility == "visible")
        {
            // Tratamos las habitaciones.
            sHabitacion    = document.getElementById('slt_habitacion_'+i).value;
            aParametros    = sHabitacion.split('-');  // Convierte string en array
            iNumAdultos    = aParametros[1];
            iNumNinos      = aParametros[2];
            sCfgHabitaciones += i+'-'+iNumAdultos+'-'+iNumNinos;

            // Edades de los ni�os
            for(j=1; j<=iNumNinos; j++)
            {
                if (document.getElementById('slt_edades_'+i+'_'+j).value != '--')
                {
                    sCfgHabitaciones += '-'+document.getElementById('slt_edades_'+i+'_'+j).value;
                }
                else
                {
                    alert('Se requieren todas las edades de los menores.');
                    return;
                }
            }
        }
        sCfgHabitaciones += '|';
    }
    //Guardamos configuración habitaciones
    $("#sCfgHabitaciones").val(sCfgHabitaciones);
	$("#DestinoHoteles").val($("#txtDestinoHoteles").val());
    document.frm_hoteles.submit();	
}

function PosRegional__BuscarEnHotel()
{
    var sCfgHabitaciones    = "";
    var sHabitacion         = "";
    var aParametros         = "";
    var iNumAdultos         = 0;
    var iNumNinos           = 0;

    if($("#txt_fecha_inicial").val()=='' || $("#txt_fecha_final").val()=='')
        {
        alert("Debe seleccionar fecha de entrada y salida");
        return;
        }

    for(i=1; i<=5; i++)
    {
        if(document.getElementById('div_habita'+i).style.visibility == "visible")
        {
            // Tratamos las habitaciones.
            sHabitacion    = document.getElementById('slt_habitacion_'+i).value;
            aParametros    = sHabitacion.split('-');  // Convierte string en array
            iNumAdultos    = aParametros[1];
            iNumNinos      = aParametros[2];
            sCfgHabitaciones += i+'-'+iNumAdultos+'-'+iNumNinos;

            // Edades de los ni�os
            for(j=1; j<=iNumNinos; j++)
            {
                if (document.getElementById('slt_edades_'+i+'_'+j).value != '--')
                {
                    sCfgHabitaciones += '-'+document.getElementById('slt_edades_'+i+'_'+j).value;
                }
                else
                {
                    alert('Se requieren todas las edades de los menores.');
                    return;
                }
            }
        }
        sCfgHabitaciones += '|';
    }
    //Guardamos configuración habitaciones
    $("#sCfgHabitaciones").val(sCfgHabitaciones);

    document.frm_hoteles.submit();
}

function PosRegional__CambiarTab(tab)
{
    switch (tab){
            case 'descripcion':
                $('#link_descripcion_territorios').addClass('link_sel_territorios');
                $('#link_ubicacion_territorios').removeClass('link_sel_territorios');
                document.getElementById('tab_contenedor_ubicacion_territorios').style.display = 'none';
                document.getElementById('tab_contenedor_descripcion_territorios').style.display = 'block';
            break;
            case 'ubicacion':
                $('#link_ubicacion_territorios').addClass('link_sel_territorios');
                $('#link_descripcion_territorios').removeClass('link_sel_territorios')
                    .addClass('link_territorios');
                document.getElementById('tab_contenedor_descripcion_territorios').style.display = 'none';
                document.getElementById('tab_contenedor_ubicacion_territorios').style.display = 'block';
                cargar_mapa();
            break;
            case 'resultados':
                $('#link_resultados_territorios').addClass('link_sel_territorios');
                $('#link_informacion_territorios').removeClass('link_sel_territorios');
                $('#link_situacion_territorios').removeClass('link_sel_territorios');				
                document.getElementById('tab_contenedor_informacion_territorios').style.display = 'none';
                document.getElementById('tab_contenedor_situacion_territorios').style.display = 'none';				
                document.getElementById('tab_contenedor_resultados_territorios').style.display = 'block';
            break;	
            case 'informacion':
                $('#link_informacion_territorios').addClass('link_sel_territorios');
                $('#link_resultados_territorios').removeClass('link_sel_territorios');
                $('#link_situacion_territorios').removeClass('link_sel_territorios');				
                document.getElementById('tab_contenedor_resultados_territorios').style.display = 'none';
                document.getElementById('tab_contenedor_situacion_territorios').style.display = 'none';				
                document.getElementById('tab_contenedor_informacion_territorios').style.display = 'block';
            break;	
            case 'situacion':
                $('#link_situacion_territorios').addClass('link_sel_territorios');
                $('#link_resultados_territorios').removeClass('link_sel_territorios');
                $('#link_informacion_territorios').removeClass('link_sel_territorios');				
                document.getElementById('tab_contenedor_resultados_territorios').style.display = 'none';
                document.getElementById('tab_contenedor_informacion_territorios').style.display = 'none';				
                document.getElementById('tab_contenedor_situacion_territorios').style.display = 'block';
                cargar_mapa();				
            break;				
        }
}

function PosRegional__mostrarPrecioBusqueda()
{
    if(document.getElementById('tab_contenedor_busqueda_territorios').style.display=='block' || document.getElementById('tab_contenedor_busqueda_territorios').style.display=='')
        {
            document.getElementById('tab_contenedor_busqueda_territorios').style.display='none';
            document.getElementById('tab_contenedor_precios_territorios').style.display='block';
            document.getElementById('div_cambiar_busqueda').style.display='block';
            document.getElementById('div_mostrar_resultados').style.display='none';
        }
    else
        {
            document.getElementById('tab_contenedor_busqueda_territorios').style.display='block';
            document.getElementById('tab_contenedor_precios_territorios').style.display='none';
            document.getElementById('div_cambiar_busqueda').style.display='none';
            document.getElementById('div_mostrar_resultados').style.display='block';
        }
}

function PosRegional__pagina_ciudad(valor)
{
    $("#iPagina").val(valor);
    document.frm_pagina_hoteles.submit();
}

function PosRegional__carga_ciudad(id,valor)
{
    if(id=='FiltroEstrellas')
    {
        if(valor==-1)
            $("#"+id).val(valor);
        else
        {
            valor='';
            for(cont=1;cont<6;cont++)
                if($("#estrella"+cont).attr("checked")==true)
                    valor=valor+"1|";
                else 
                    valor=valor+"0|";
            valor=valor.substring(0,valor.length-1);
            $("#"+id).val(valor);
        }
        document.frm_estrellas_hoteles.submit();
    }
}

function PosRegional__vValidarEjecutarBusquedaHoteles(str)
{
    if ( typeof PosRegional__vValidarEjecutarBusquedaHoteles.llamadas == 'undefined' ) {
        PosRegional__vValidarEjecutarBusquedaHoteles.llamadas = 0;
        }

    var contador_usados=0;
    $.get("functions/func_busqueda_hoteles.php", { 
        func: "func_busqueda_hoteles__GetWebservicesUsados"
    },
    function(data){
        data=data.replace(/[\n\r\t]/g,'');
        var aws_usados=data.split('|');
        for(var i=0;i<aws_usados.length;i++)
            if(aws_usados[i].split('=')[1]) contador_usados++;
            if (PosRegional__vValidarEjecutarBusquedaHoteles.llamadas< (contador_usados-1)) {//numero de webservices en uso menos uno
                PosRegional__vValidarEjecutarBusquedaHoteles.llamadas++;
            }
            else {
                PosRegional__vValidarEjecutarBusquedaHoteles.llamadas=0;
                // Recuperamos los resultados:
                $.get("functions/func_busqueda_hoteles.php", {
                    func: "func_busqueda_hoteles__filtrarRepetidos"
                },function(data){window.location = "http://www.iptours.com/resultados_hoteles.php"
});
            }
    });
}