// Funcion que asigna el id_destino a los campos correspondientes
function setid_destino(id)
{
    $('id_destino').value=id;
    $('nombre_destino1').value='';
}
// Funcion que asigna el id_destino de una metadestino a los campos correspondientes
function setid_costa2(id)
{
    $('id_destino').value=id;
    $('id_costa').value=id;
    $('nombre_destino1').value='';
}
// Funcion que comprubea los datos del formulario y si todo esta correcto lo envia
function comprobar()
{
    var error='';
    if (($('id_destino').value == '' && $('nombre_destino').value == ''  && (pestanaya_activa!='1' && pestanaya_activa!='2')) || ($('id_costa').value == '' && (pestanaya_activa=='1' || pestanaya_activa=='2') ) )
    {
        errores.push(new Error('12','000','000',"Por favor, introduzca una ciudad/zona de destino en el buscador","setErrorBackColor($('nombre_destino1'))"));
    }
    else if ($('fecha_entrada').value=='' || $('fecha_salida').value=='' || $('fecha_salida').value==$('fecha_entrada').value)
    {
        errores.push(new Error('12','000','000',"Debe introducir una fecha valida","setErrorBackColor($('fecha_entrada'));"));
    }
    else
    {
        var today = new Date();
        var thisYear = today.getFullYear();
        var thisMonth = today.getMonth();
        var thisDay = today.getDate();

        var fechaEntrada = $('fecha_entrada').value.split('/');
        var anoEntrada = fechaEntrada[2];
        var mesEntrada = fechaEntrada[1];
        var diaEntrada = fechaEntrada[0];

        var fechaSalida = $('fecha_salida').value.split('/');
        var anoSalida = fechaSalida[2];
        var mesSalida = fechaSalida[1];
        var diaSalida = fechaSalida[0];

        fecha_ini=new Date(parseInt(anoEntrada, 10),parseInt(mesEntrada, 10)-1,parseInt(diaEntrada, 10));
        fecha_fin=new Date(parseInt(anoSalida, 10),parseInt(mesSalida, 10)-1,parseInt(diaSalida, 10));
        fecha_control=new Date(thisYear,thisMonth-1,thisDay);
        if (fecha_ini.valueOf()<fecha_control.valueOf())
        errores.push(new Error('12','000','000',"La fecha de entrada no puede ser anterior a "+thisDay+"/"+thisMonth+"/"+thisYear+"\n","setErrorBackColor($('fecha_entrada'));"));
        else if (today.getUTCHours()>=20 && fecha_ini.valueOf()==fecha_control.valueOf())
        errores.push(new Error('12','000','000',"Es demasiado tarde para hacer una reserva para hoy\n"));

        if($('id_hotel2')) $('id_hotel').value=$('id_hotel2').value;
        $('num_noches').value=Math.round((fecha_fin.getTime()-fecha_ini.getTime())/(1000*3600*24));
        if($('num_noches').value>30)
        {
            errores.push(new Error('12','000','000',"Lo lamentamos, no es posible hacer reservas de más de 30 días.\n","setErrorBackColor($('fecha_salida'));"));
        }
        var i = 1;
        while (error.length==0 && i<=$('num_habitaciones')[$('num_habitaciones').selectedIndex].value)
        {
            var j = 1;
            var f = i;
            var n = $('num_ninos_'+f);
            if(n[n.selectedIndex])
            {
                while (error.length==0 && j<=n[n.selectedIndex].value)
                {
                    if ($('edad_'+f+'_'+j).selectedIndex==0)  errores.push(new Error('12','000','000',"Debe especificar la edad del niño "+j+" de la habitacion "+f,"setErrorBackColor($('edad_"+f+"_"+j+"'));"));
                    j++;
                }
            }
            i++;
        }
        if (errores.cuantos()>0)
        {
            errores.show();
            return;
        }else{
        	 loadBanner($('id_destino').value);
             mostrar_splash();
             setTimeout("document.busqueda.submit()",500);

           // mostrar_splash();
           // document.busqueda.submit();
        }
    }
    errores.show();
}
// Funcion que reasigna los valores de id_destino y nombre_destino desde la combo de destinos con hoteles con filtro
function updateId2(obj)
{
    $('id_destino').value=obj.value;
    $('nombre_destino').value=$('nombre_destino1').value=obj[obj.selectedIndex].innerHTML.replace(/... /g,'');
    if(obj.id!='nombre_destino2') $('nombre_destino2').value=obj[obj.selectedIndex].innerHTML.replace(/... /g,'');
    reloadHoteles('id_hotel2');
}
// Funcion que muestra la busqueda avanzada
function simple2advance()
{
    changedisp('id_categorias','block','');
    changedisp('id_regimen_menu','block','');
    changedisp('avanzada1','block','');
    changedisp('avanzada2','block','');
    $('simple').innerHTML='';
}
// Funcion que muestra la caja del buscador adecuada a la marca seleccionada
function showSearchBox()
{
    if(!$('search_1')) return;
    $('search_1').style.display='none';
    if($('search_2')) $('search_2').style.display='none';
    if($('search_3')) $('search_3').style.display='none';
    skicos=false;
    if ( pestanaya_activa=='1' || pestanaya_activa=='2' )
    {
        skicos=true;
        for(i=$('id_costa2').options.length;i>0;i--) $('id_costa2').options[i]=null;
        $('id_costa2').options[0]=new Option(str_cualquiera, '');
        $('search_2').style.display='inline';
        if ( pestanaya_activa=='1') {$('id_costab').style.display='inline';$('id_costaa').style.display='none';}
        else {$('id_costaa').style.display='inline';$('id_costab').style.display='none';}
    }
    else if ( pestanaya_activa=='3' || pestanaya_activa=='4' || pestanaya_activa=='5' || pestanaya_activa=='6' || pestanaya_activa=='7'  || pestanaya_activa=='8' )
    {
        $('search_3').style.display='inline';
        reloadDestinos2('nombre_destino2');
        if($('id_destino').value!='') reloadHoteles('id_hotel2')
    }
    else $('search_1').style.display='inline';
}
// Recarga aquellas partes de la home que se modifican segun el segmento seleccionado
function loadNewData(pestanya)
{
    pestanaya_activa=pestanya;
    $('id_destino').value = '';
    $('id_costa2').value = '';
    $('id_costaa').value = '';
    $('id_costab').value = '';
    $('nombre_destino').value = '';
    $('nombre_destino1').value = '';
    $('nombre_destino2').value = '';
    if(is_ie)
    {
        setCookie('buscador_HOT','');
        switch(pestanya)
        {
            case 0:document.location.href="/hoteles/";break;
            case 1:document.location.href="/hoteles/de/playa/";break;
            case 2:document.location.href="/hoteles/de/montana/";break;
            case 3:document.location.href="/hoteles/con/ninos/";break;
            case 4:document.location.href="/hoteles/de/relax/";break;
            case 5:document.location.href="/hoteles/con/encanto/";break;
            case 7:document.location.href="/hoteles/de/lujo/";break;
            case 8:document.location.href="/hoteles/de/negocios/";break;
        }
        return;
    }
    $('titulo_home').innerHTML=titulos[pestanaya_activa];
    if(pestanaya_activa==0) $('dtitulo_home').style.display='none';
    else $('dtitulo_home').style.display='block';
    $('id_marca').value=pestanya;
    $('overlay_so').style.display='block';
    $('titulo_home').innerHTML=titulos[pestanaya_activa];
    document.title='Hoteles Atrapalo: Ofertas de '+titulos[pestanaya_activa]+'. Atrapalo.com';
    for(i=1;i<=so_box;i++)
    {
        $('so_image_'+i).src='http://www.atrapalo.com/images_new/hoteles/hotel_vacio_new.gif';
        $('so_'+i).style.display='none';
    }
    $('od_overlay').style.display='block';
    $('od_table').style.display='none';
    $('DABox').innerHTML='<div class="overlay_reco_der" id="overlay_reco_der"><div id="loading"><img src="/images_new/hoteles/gifanimado.gif"  alt="Cargando..." width="90%" /><'+'/div><'+'/div>';
    $('DBBox').innerHTML='<div class="overlay_reco_der" id="overlay_reco_der"><div id="loading"><img src="/images_new/hoteles/gifanimado.gif"  alt="Cargando..." width="90%" /><'+'/div><'+'/div>';
    if($('que_tal_fue')) $('que_tal_fue').style.display='none';
    dd=new Date()
    t=dd.getDate()+'-'+dd.getMonth()+' '+dd.getHours()+':'+dd.getMinutes();

    //Funciones de Ajax de script.aculo.us
    new Ajax.Request(dir_hoteles+'index.php', {method:'get',parameters:'pg=do_ajax&pg_action=superofertas_centro&id_marca='+pestanya+'&t='+t, onSuccess:cargaSuperOfertas});
    new Ajax.Request(dir_hoteles+'index.php', {method:'get',parameters:'pg=do_ajax&pg_action=ofertas_destacadas_centro&id_marca='+pestanya+'&t='+t, onSuccess:cargaOfertasDestacadas});
    new Ajax.Request(dir_hoteles+'index.php',{method:'get',parameters:'pg=do_ajax&pg_action=dabox&id_marca='+pestanya+'&t='+t,onSuccess:setDABox});
    new Ajax.Request(dir_hoteles+'index.php', {method:'get',parameters:'pg=do_ajax&pg_action=dbbox&id_marca='+pestanya+'&t='+t, onSuccess:setDBBox});
    if($('que_tal_fue')) new Ajax.Request(dir_hoteles+'index.php', {method:'get',parameters:'pg=do_ajax&pg_action=quetalfue&id_marca='+pestanya+'&t='+t, onSuccess:cargarOpinion});
    showSearchBox();
}
// Recarga aquellas partes de la home que se modifican segun el segmento seleccionado (Version no home)
function loadNewDataMini(pestanya)
{
    pestanaya_activa=pestanya;
    $('id_marca').value=pestanya;
    if(!$('search_1')) return;
    $('id_destino').value = '';
    $('id_costa2').value = '';
    $('id_costaa').value = '';
    $('id_costab').value = '';
    $('nombre_destino').value = '';
    $('nombre_destino1').value = '';
    $('nombre_destino2').value = '';
    showSearchBox();
}
// Recarga los destinos cuando selecionamos un metadestino
function reloadDestinos(select,fieldId)
{
    for(i=$(fieldId).options.length;i>0;i--) $(fieldId).options[i]=null;
    $(fieldId).options[0]=new Option(str_cargando, '');
    new Ajax.Request(dir_hoteles+'index.php', {
        method:'get',
        parameters:'pg=do_ajax&pg_action=destinos_en_metadestino&id_costa='+select[select.selectedIndex].value,
        onSuccess: function (response)
        {
            nodes = response.responseXML.documentElement.getElementsByTagName('destino');
            $(fieldId).options[0]=new Option(str_cualquiera, '');
            for(i=0;i<nodes.length;i++)
            {
                $(fieldId).options[(i+1)]=new Option(nodes[i].getAttribute("nombre"), nodes[i].getAttribute("id_destino"));
            }
        }
    });
}
// Recarga los destinos cuando una segmentacion
function reloadDestinos2(fieldId)
{
    for(i=$(fieldId).options.length;i>0;i--) $(fieldId).options[i]=null;
    $(fieldId).options[0]=new Option(str_cargando, '');
    new Ajax.Request(dir_hoteles+'index.php', {
        method:'get',
        parameters:'pg=do_ajax&pg_action=destinos_con_marca&id_marca='+pestanaya_activa,
        onSuccess: function (response)
        {
            nodes = response.responseXML.documentElement.getElementsByTagName('destinogrp');
            $(fieldId).options[0]=new Option(str_selecciona, '');
            z=0;
            for(i=0;i<nodes.length;i++)
            {
                z++;
                $(fieldId).options[z]=new Option(nodes[i].getAttribute("nombre"), nodes[i].getAttribute("id_destino"));
                subnodes=nodes[i].getElementsByTagName('destino');
                for(y=0;y<subnodes.length;y++)
                {
                    z++;
                    if(is_ie) $(fieldId).options[z]=new Option('... '+subnodes[y].getAttribute("nombre"), subnodes[y].getAttribute("id_destino"));
                    else{
                        $(fieldId).options[z]=new Option(subnodes[y].getAttribute("nombre"), subnodes[y].getAttribute("id_destino"));
                        $(fieldId).options[z].style.marginLeft='10px';
                    }

                }
            }
        }
    });
}
// Recarga el combo de hoteles cuando selecionamos un destino
function reloadHoteles(fieldId)
{
    for(i=$(fieldId).options.length;i>0;i--) $(fieldId).options[i]=null;
    $(fieldId).options[0]=new Option(str_cargando, '');
    new Ajax.Request(dir_hoteles+'index.php', {
        method:'get',
        parameters:'pg=do_ajax&pg_action=hoteles_en_destino&id_destino='+$('id_destino').value+'&id_marca='+pestanaya_activa,
        onSuccess: function (response)
        {
            xmldata=response.responseXML.documentElement;
            nodes = xmldata.getElementsByTagName('data')[0].getElementsByTagName('hotel');
            $(fieldId).options[0]=new Option(str_cualquiera, '');
            for(i=0;i<nodes.length;i++)
            {
                $(fieldId).options[(i+1)]=new Option(nodes[i].getAttribute("nombre"), nodes[i].getAttribute("id_hotel"));
            }
        }
    });
}
//
function changedisp(whatdiv,whatdisp,whatcover)
{
    if (whatcover=='') {$(whatdiv).style.display=whatdisp}
    else
    {
        if (whatdisp=='block') {
            $(whatdiv).style.display='block'
            $(whatcover).style.top=$(whatdiv).style.top
            $(whatcover).style.left=$(whatdiv).style.left
            $(whatcover).style.width=$(whatdiv).offsetWidth
            $(whatcover).style.height=$(whatdiv).offsetHeight
            $(whatcover).style.display='block'
        }else{
            $(whatcover).style.display='none'
            $(whatdiv).style.display='none'
        }
    }
}
function recuperarDatos()
{
    mostrarFilasHabitaciones($F('num_habitaciones'))
    for(k=1;k<=$F('num_habitaciones');k++)
    {
        actualizaNinos(k);
        mostrarInputsEdades($('num_ninos_'+k)[$('num_ninos_'+k).selectedIndex].value,k);
    }
}
// Metodo que inicializa el buscador a los datos por defecto, par aque no haya problema de cahes
function initBuscador()
{
    $('id_destino').value = '';
    $('id_costa2').value = '';
    $('id_costaa').value = '';
    $('id_costab').value = '';
    $('fecha_entrada').value = '';
    $('fecha_salida').value = '';
    $('nombre_destino').value = '';
    $('nombre_destino1').value = '';
    $('nombre_destino2').value = '';
    $('num_habitaciones').selectedIndex = '0';
    $('id_regimen_menu').selectedIndex = '0';
    $('id_categorias').selectedIndex = '0';
    for(k=1;k<=num_max_hab;k++)
    {
        $('num_adultos_'+k).selectedIndex = '1';
        $('num_ninos_'+k).selectedIndex = '0';
        for(y=1;y<=3;y++)
        {
            $('edad_'+k+'_'+y).selectedIndex = '0';
        }
    }
    recuperarDatos();
}

function recalcularPaxHab() {
    num_hab=$('num_habitaciones').value;
    num_max_hab=5;
    for(i=1;i<=num_hab;i++) {
        $('num_adultos_'+i).value=$('num_adultos_1').value;
    }
    for(y=i;y<=num_max_hab;y++) {
        $('num_adultos_'+y).value=0;
    }
}
