//Declaracion de vars
Atrapalo.hoteles={};
Atrapalo.hoteles.MONEDA ='&euro;';
Atrapalo.hoteles.MONEDADELANTE ='';
Atrapalo.hoteles.MONEDARATIO ='1';
Atrapalo.hoteles.aplicacion="HOT";
Atrapalo.hoteles.id_package_hot="12";
Atrapalo.hoteles.dir="/hoteles/";

YAHOO.util.Event.onAvailable('destinos_trigger', function() {
    YAHOO.util.Event.removeListener('origenes_trigger', 'click');
    YAHOO.util.Event.removeListener('destinos_trigger', 'click');
    //YAHOO.util.Event.addListener('origenes_trigger', 'click', mostrar_origenes2);
    //YAHOO.util.Event.addListener('destinos_trigger', 'click', mostrar_destinos2);
  
  
});
var oPanel;
var ajax_hotel;
var ajax_vuelo;
var pestanaya_activa=0;
var hoteles_end=false;
var vuelos_end=false;
var vuelos_id='';
var hoteles_id='';
var d=new Date();
var t=d.getTime();
var params_hoteles={};
var params_vuelos={};
var query_hoteles=new Array();
var query_vuelos=new Array();
var titulos=new Array();
titulos[0]='';
var vmhAutoComp;
var vmhAutoComp2;
var is_search=false;
var no_cal='';
var num_max_hab=parseInt(5);
var ida_selected = -1;
var vuelta_selected = -1;

/*var ciudades_mas_frecuentes ='ciudades más frecuentes';
var destinos_mas_frecuentes ='destinos más frecuentes';*/
if(dir_hoteles==undefined)
{
    var dir_hoteles = '/hoteles/';
    var cod_idioma='es';
    var ciudades_mas_frecuentes ='ciudades más frecuentes';
    var destinos_mas_frecuentes ='destinos más frecuentes';
}
if (dir_vmh==undefined) var dir_vmh =     '/vuelo+hotel/';
if (dir_vuelos==undefined) var dir_vuelos='/vuelos/';
if(cod_idioma!=undefined && cod_idioma == 'it') {
    var months_long=["Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"];
    var day_short=["Do", "Lu", "Ma", "Me", "Gi", "Ve", "Sa"];
}else if(cod_idioma!=undefined && cod_idioma == 'fr') {
    var months_long = [ "Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre "];
    var day_short = [ "Di", "Lu", "Ma", "Me", "Je", "Ve", "Sa"];
}else {
    var months_long=["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"];
    var day_short=["Do", "Lu", "Ma", "Mi", "Ju", "Vi", "Sa"];
}

//YUI autocomplete
var myXHRDataSourceOrigen = new YAHOO.widget.DS_XHR_AUTO('<#t id="@VUEHomeBuscadorAjax" escape="js"#>VUE/home_buscador_ajax<#/t#>origen/',['ResultSet.Result','id', 'nombre','pais']);
var autoCompleteDataSource = new YAHOO.widget.DS_XHR_AUTO('<#t id="@HOTDoAjax" escape="js"#>HOT/do_ajax<#/t#>destinos_json/',["ResultSet.Result","id", "name","text"]);
var max_zoom = 12;
autoCompleteDataSource.responseType = YAHOO.widget.DS_XHR.TYPE_JSON;
autoCompleteDataSource.maxCacheEntries = 60;
autoCompleteDataSource.queryMatchSubset = true;
myXHRDataSourceOrigen.responseType = YAHOO.widget.DS_XHR.TYPE_JSON;
myXHRDataSourceOrigen.maxCacheEntries = 10;
myXHRDataSourceOrigen.queryMatchContains = true;



YAHOO.util.Event.onDOMReady(function(){ 
	
	initBuscador();
	setUpCalendar()
});

YAHOO.util.Event.onAvailable('id_home', function(){$('id_home').value = randomString();});
function changeFly(id_hotel)
{
    $('pg_action').value="vuelos";
    $('id_hotel').value=id_hotel;
    $('resultados_vmh').submit();
}
function changeHotel()
{
    $('pg_action').value="hoteles";
    $('resultados_vmh').submit();
}
function multiSearch()
{
    is_search=true;
    //mostrarSplash();
    hoteles_id=vuelos_id="";
    hoteles_end=vuelos_end=false;
    for ( key in params_hoteles ) query_hoteles.push(key+'='+params_hoteles[key]);
    for ( key in params_vuelos )
	{
		if ((key == 'pg') && (params_vuelos[key] == 'busqueda'))
			query_vuelos.push('pg=pre_busqueda');
		else
			query_vuelos.push(key+'='+params_vuelos[key]);

	}
    ajax_hotel=YAHOO.util.Connect.asyncRequest('POST', dir_hoteles+'index.php',{success:setHoteles},query_hoteles.join("&")+'&t='+d.getTime());
    setTimeout("ajax_vuelo=YAHOO.util.Connect.asyncRequest('GET',"+"'"+dir_vuelos+"index.php?mode=null&"+query_vuelos.join("&")+"&t="+d.getTime()+"',{success:setVuelos});",1);
    setTimeout("searchIsFinished()",1000);
}

// Esta variable define la funcion que se ejecuta en caso de qwue haya errores o mensajes a mostrar al usuario
var enviar_confirm_vmh = function (msg)
                    {
                        // Mostramos las advertencias al usuario
                        if (confirm(msg))
                        {
                            is_search=false;
						    hoteles_id=vuelos_id="";
						    hoteles_end=vuelos_end=false;
						    query_vuelos=new Array();
						    query_hoteles=new Array();
						    for ( key in params_hoteles ) query_hoteles.push(key+'='+params_hoteles[key]);
						    for ( key in params_vuelos )
							{
								query_vuelos.push(key+'='+params_vuelos[key]);
								// Si el vuelo es day_change es decir, el vuelo de ida llega un dia despues a la fecha en la q sale
								// ponemos el parametro para indicarlo al hotel y que reste una noche y cambia la fecha de entrada
								// al hotel.
								if (key.indexOf("alerta_vmh") != -1)
								query_hoteles.push("alerta_vmh="+params_vuelos[key]);

							}
						    ids_tmp = $('ids').value;
						    ajax_hotel=YAHOO.util.Connect.asyncRequest('GET', dir_vmh+'index.php?pg=resultados&pg_action=set&id_hotel&'+params_hoteles['id_hotel']+'&id_tarifa='+id_tarifa_vuelos+'&ids='+$('ids').value+'&t='+d.getTime(),
						    {
						        success:function(response){
						            ajax_hotel=YAHOO.util.Connect.asyncRequest('GET', dir_hoteles+'index.php?pg=check&es_vmh=1&'+query_hoteles.join("&")+'&t='+d.getTime()+'&ids='+ids_tmp,
						            {
						                success:function(response){
						                        setHoteles(response);
						                        if(response.responseText.indexOf("ERROR")<0 && response.responseText!='')
						                        {
						                            ajax_vuelo=YAHOO.util.Connect.asyncRequest('GET', dir_vuelos+'index.php?pg=disponibilidad&mode=null&es_vmh=1&'+query_vuelos.join("&")+'&ids='+ids_tmp+'&t='+d.getTime()+'&aplicar_desc='+id_prov_confirm,
						                            {
						                                success:setVuelos,
						                                failure:function(response){
						                                    vuelos_end=true;
						                                    vuelos_id='';
						                                    hoteles_end=true;
						                                    quitarHotel();
						                                    }
						                            });
						                        }
						                        },
						                failure:function(response){hoteles_end=true;hoteles_id='';vuelos_end=true;}
						            });
						        },
						        failure:function(response){hoteles_end=true;hoteles_id='';vuelos_end=true;}
						    });
						    mostrarSplash();
						    setTimeout("checkIsFinished()",1000);
                        }
                        else return (false); // No acepta
                    };
//---- splash.js
function mostrarSplash()
{

	// Asinamos los valores a la pagina de espera. VMH
	if ($('sp_origen') && $('nombre_origen1')) 
		$('sp_origen').innerHTML = $('nombre_origen1').value;
	if ($('sp_destino') && $('nombre_destino1'))
	{
		$('sp_destino').innerHTML = $('nombre_destino1').value; 
	    $('sp_destino2').innerHTML = $('nombre_destino1').value;
	}
	if ($('sp_salida') && $('fecha_entrada')) 
		$('sp_salida').innerHTML = $('fecha_entrada').value;
	if ($('sp_llegada') && $('fecha_salida')) 
		$('sp_llegada').innerHTML = $('fecha_salida').value;
	if ($('sp_adultos') && $('num_adultos_1')) 
		$('sp_adultos').innerHTML = $('num_adultos_1').value;
	if ($('sp_ninos') && $('num_ninos_1'))
		$('sp_ninos').innerHTML = $('num_ninos_1').value;
	if ($('sp_nh') && $('num_habitaciones'))
		$('sp_nh').innerHTML = $('num_habitaciones').value;
	                    	    	
	mostrar_splash();
}
                    
                    
                    
function mostrar_splash()
{
    //paramos el cambio de oferton
    if($('container')) $('container').style.display="none";
    $('splash').style.display="block";
    if( typeof( window.innerWidth ) == 'number' ) {
        //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }
    if($('table_splash')) $('table_splash').style.height=myHeight;
    $('splash').style.height=myHeight;
}

// Para pasar el proveedor en el caso de mostrar un confirm.
var id_prov_confirm;

function multiCheck(id_proveedor)
{
	id_prov_confirm = id_proveedor;

	// Comprobamos si el vuelo de ida es day_change (+1) y si la diferencia entre la fecha de ida y vuelta
	// es de un dia, le mostramos al usuario un error comentandole que debe escojer otro vuelo.
	if ((document.getElementById(id_tarifa_vuelos+'_alervmh_i_'+document.getElementsByName('vida'+id_tarifa_vuelos)[ida_selected].value).value.indexOf("1-") != -1) && (document.getElementById('num_noches').value ==1))
	{
		errores.push(new Error('17','100','002'));
		errores.show();
		return false;

	}
	// Comprobamos si hay un dia de diferencia entre el vuelo de ida y el de vuelta, si el de vuelta sale
	// de madrugada, no le dejamos que haga la reserva ya que no pasaría ni una noche en el hotel.
	if ((document.getElementById(id_tarifa_vuelos+'_alervmh_v_'+document.getElementsByName('vvuelta'+id_tarifa_vuelos)[vuelta_selected].value).value.indexOf("2-") != -1) && (document.getElementById('num_noches').value ==1))
	{
		errores.push(new Error('17','100','004'));
		errores.show();
		return false;
	}
	// Si se quieren pasar dos noches y el vuelo de ida llega al dia siguiente y el de regreso sale de madrugada
	// se restarian dos noches, con lo q no se reservaria hotel.
	if (
		(document.getElementById('num_noches').value == 2)
		&& (document.getElementById(id_tarifa_vuelos+'_alervmh_i_'+document.getElementsByName('vida'+id_tarifa_vuelos)[ida_selected].value).value.indexOf("1-") != -1)
		&& (document.getElementById(id_tarifa_vuelos+'_alervmh_v_'+document.getElementsByName('vvuelta'+id_tarifa_vuelos)[vuelta_selected].value).value.indexOf("2-") != -1)
		)
	{
		errores.push(new Error('17','100','005'));
		errores.show();
		return false;
	}
	// Si el vuelo sale y llega el mismo dia, pero llega antes de las tres se le indica al usuario q debe cojer una noche mas
	// ya que sino cuando llegue al hotel deberá esperar a las 12:00 am para entrar.
	if ((document.getElementById(id_tarifa_vuelos+'_alervmh_i_'+document.getElementsByName('vida'+id_tarifa_vuelos)[ida_selected].value).value.indexOf("3-") != -1)
		|| 	(document.getElementById(id_tarifa_vuelos+'_alervmh_v_'+document.getElementsByName('vvuelta'+id_tarifa_vuelos)[vuelta_selected].value).value.indexOf("3-") != -1))
	{
		errores.push(new Error('17','100','006'));
		//errores.show();
	}

	// Comprobamos si hay una ciudad secundaria para avisar al usuario, caso ida y vuelta
	al_aer_ida = '';
	al_aer_vuelta = '';
	aer_o_ida = '';
	aer_d_ida = '';
	aer_o_vuelta = '';
	aer_d_vuelta = '';
	
	if (ida_selected != -1)
	{
		al_aer_ida = document.getElementById(id_tarifa_vuelos+'_alerta_i_'+document.getElementsByName('vida'+id_tarifa_vuelos)[ida_selected].value).value;
		aer_o_ida = document.getElementById(id_tarifa_vuelos+'_o_i_'+document.getElementsByName('vida'+id_tarifa_vuelos)[ida_selected].value).value;
		aer_d_ida =	document.getElementById(id_tarifa_vuelos+'_d_i_'+document.getElementsByName('vida'+id_tarifa_vuelos)[ida_selected].value).value;
	}
	if (vuelta_selected != -1)
	{
		al_aer_vuelta = document.getElementById(id_tarifa_vuelos+'_alerta_v_'+document.getElementsByName('vvuelta'+id_tarifa_vuelos)[vuelta_selected].value).value;
		aer_o_vuelta = document.getElementById(id_tarifa_vuelos+'_o_v_'+document.getElementsByName('vvuelta'+id_tarifa_vuelos)[vuelta_selected].value).value;
		aer_d_vuelta = document.getElementById(id_tarifa_vuelos+'_d_v_'+document.getElementsByName('vvuelta'+id_tarifa_vuelos)[vuelta_selected].value).value;
	}
    // Comprobamos si hay una ciudad secundaria para avisar al usuario, caso ida y vuelta
    if ((al_aer_ida.indexOf("6-") != -1) || (al_aer_ida.indexOf("8-") != -1) || (al_aer_vuelta.indexOf("6-") != -1) || (al_aer_vuelta.indexOf("8-") != -1))
    {
        //texto = errores['error_2820'];
        errores.push(new Error('11','150','001'));
    }
    //document.forms['form'+id_tarifa].id_res.value = randomString();
    if ((aer_o_vuelta != '') &&
    	((aer_o_ida != aer_d_vuelta) || (aer_d_ida != aer_o_vuelta))) 
    	errores.push(new Error('11','150','002'));
    
    //document.forms['form'+id_tarifa].id_res.value = randomString();
    if ((al_aer_ida.indexOf("1-") != -1) || ((al_aer_vuelta.indexOf("1-") != -1)))
    {
        errores.push(new Error('11','150','025'));
    }
    // Comprobamos si el vuelo es de iberia 6xxx, para informar al usuario q es un vuelo
    // internacional
    if ((al_aer_ida.indexOf("4-") != -1) || (al_aer_vuelta.indexOf("4-") != -1))
        errores.push(new Error('11','150','021'));

	/*
    if ((document.getElementById(id_tarifa_vuelos+'_alerta_aer').value.indexOf("2-") != -1) || (document.getElementById(id_tarifa_vuelos+'_alerta_aer').value.indexOf("8-") != -1))
    {
        errores.push(new Error('11','150','001'));
    }
	*/
	// Mostramos el mensaje al usuario informandole que el aeropuerto de salida o llegada es diferente
	// de la que ha puesto.
	if (errores.cuantos() > 0)
    {
        errores.push(new Error('11','150','003'));
		errores.eval(enviar_confirm_vmh);
        //if (!errores.eval(enviar_confirm_vmh))
        return true;
    }

	is_search=false;

    hoteles_id=vuelos_id="";
    hoteles_end=vuelos_end=false;
    query_vuelos=new Array();
    query_hoteles=new Array();
    for ( key in params_hoteles ) query_hoteles.push(key+'='+params_hoteles[key]);
    for ( key in params_vuelos )
	{
		query_vuelos.push(key+'='+params_vuelos[key]);
		// Si el vuelo es day_change es decir, el vuelo de ida llega un dia despues a la fecha en la q sale
		// ponemos el parametro para indicarlo al hotel y que reste una noche y cambia la fecha de entrada
		// al hotel.

		if (key.indexOf("alerta_vmh") != -1)
			query_hoteles.push("alerta_vmh="+params_vuelos[key]);

	}
 
    ids_tmp = $('ids').value;
    ajax_hotel=YAHOO.util.Connect.asyncRequest('GET', dir_vmh+'index.php?pg=resultados&pg_action=set&id_hotel='+params_hoteles['id_hotel']+'&id_tarifa='+id_tarifa_vuelos+'&ids='+$('ids').value+'&t='+d.getTime(),
    {
        success:function(response){
            ajax_hotel2=YAHOO.util.Connect.asyncRequest('GET', dir_hoteles+'index.php?pg=check&es_vmh=1&'+query_hoteles.join("&")+'&t='+d.getTime()+'&ids='+ids_tmp,
            {
                success:function(response){
                        setHoteles(response);
                        if(response.responseText.indexOf("ERROR")<0 && response.responseText!='')
                        {
                            ajax_vuelo=YAHOO.util.Connect.asyncRequest('GET', dir_vuelos+'index.php?pg=disponibilidad&mode=null&es_vmh=1&'+query_vuelos.join("&")+'&ids='+ids_tmp+'&t='+d.getTime()+'&aplicar_desc='+id_proveedor,
                            {
                                success:setVuelos,
                                failure:function(response){
                                    vuelos_end=true;
                                    vuelos_id='';
                                    hoteles_end=true;
                                    quitarHotel();
                                    }
                            });
                        }
                        },
                failure:function(response){hoteles_end=true;hoteles_id='ERROR';vuelos_end=true;}
            });
        },
        failure:function(response){hoteles_end=true;hoteles_id='ERROR';vuelos_end=true;}
    });
    mostrarSplash();
    setTimeout("checkIsFinished()",1000);

}
function quitarHotel()
{
    if(hoteles_id!='')
       YAHOO.util.Connect.asyncRequest('GET',dir_hoteles+'index.php?pg=do_ajax&pg_action=delete_pedido&id_pedido='+hoteles_id);
}
function setHoteles(response)
{
    hoteles_end=true;
    hoteles_id=response.responseText;
    if(hoteles_id.indexOf("ERROR")>=0 || hoteles_id=='' || hoteles_id.length>40)
    {
		if (ajax_vuelo)
        	YAHOO.util.Connect.abort(ajax_vuelo);
        vuelos_id='';
        vuelos_end=true;
        if(is_search) document.location.href=dir_vuelos;
    }
}
function setVuelos(response)
{
    vuelos_end=true;
    vuelos_id=response.responseText;
    if(vuelos_id.indexOf("ERROR")>=0 || vuelos_id=='' || vuelos_id.length>50)
    {
        YAHOO.util.Connect.abort(ajax_hotel);
        if(hoteles_id) quitarHotel();
        hoteles_id='';
        hoteles_end=true;
        if(is_search) document.location.href=dir_vuelos;
    }

}
function searchIsFinished()
{
    if(hoteles_end && vuelos_end)
    {
        if(hoteles_id.indexOf("ERROR")>=0 || vuelos_id.indexOf("ERROR")>=0 || hoteles_id=='' || vuelos_id=='' )
        {
            $('splash').style.display="none";
            $('container').style.display="block";
            errores.cargarErroresCookie();
            errores.show();
        }else{
            document.location.href=dir_vmh+'index.php?pg=resultados&ids='+hoteles_id+'|'+vuelos_id;
        }
    }else setTimeout("searchIsFinished()",500);
}
function checkIsFinished()
{
    if(hoteles_end && vuelos_end)
    {
        if(hoteles_id.indexOf("ERROR")>=0 || vuelos_id.indexOf("ERROR")>=0
            || hoteles_id=='' || vuelos_id==''
            || hoteles_id.length>32 || vuelos_id.length>20
          )
        {
            if ($('splash')){ $('splash').style.display="none";
            $('container').style.display="block";}
            errores.cargarErroresCookie();
            errores.show();
        }else{
            paquetes=getCookie('hay_vmh');
            value_cookie=(paquetes!=null)?paquetes+":":"";
            value_cookie+=hoteles_id+'|'+vuelos_id;
            /*
            if(location.href=(location.href.indexOf('atrapalo.com')>=0)) {
                setCookie('hay_vmh',value_cookie,null,'/','atrapalo.com');
                location.href = 'https://secure.atrapalo.com/carrito/';
                //location.href = 'https://jomartinez.atrapalo.com/carrito/';
                //location.href = 'https://wwwagent.atrapalo.com/carrito/';
            }else {
            */
                domain=location.hostname.split(".");
                domain=domain[1]+"."+domain[2];
                setCookie('hay_vmh',value_cookie,null,'/',domain);
                location.href = 'https://'+location.hostname+'/carrito/';
            //}
        }
    }else setTimeout("checkIsFinished()",500);
}
function recargar() { $('resultados_vmh').submit(); }
function paginar(offset) { $('offset').value = offset; recargar(); }
function mostrar_destinos_vmh(caja)
{
    input_m_vmh=caja;
    mostrar_destinos('hoteles');
    return false;
}
function informar(text,code)
{
    if(input_m_vmh=="origen")
    {
        $('nombre_origen').value = text;
        $('nombre_origen1').value = text;
    }else{
        $('nombre_destino').value = text;
        $('nombre_destino1').value = text;
    }
    oPanel.hide()
}
function informar2(text,code)
{
    if(input_m_vmh=="origen")
    {
        $('id_origen').value = '';
        $('nombre_origen').value = text;
        $('nombre_origen1').value = text;
        $('id_costa_o').value = code;
    }else{
        $('id_destino').value = '';
        $('nombre_destino').value = text;
        $('nombre_destino1').value = text;
        $('id_costa_d').value = code;
    }
    oPanel.hide()
}
function simple2advance()
{
    $('avanzada3').style.display='block';
    $('avanzada4').style.display='block';
    $('clase').style.display='block';
    $('linea_aerea').style.display='block';
    $('solo_vue_directos_lbl').style.display='block';
    $('sin_ciudades_secundarias_lbl').style.display='block';
    $('simple').innerHTML='';
}
function updateAutocompletIdVmh (a,b,c)
{
        id=c[0].split("_");
        name=c[1];
        var containerId = null;
        if ($('id_costa_d')) $('id_costa_d').value='';
        if ($('id_costa_o')) $('id_costa_o').value='';
        if(YAHOO.VERSION == '2.2.2') { containerId = a._oContainer.id; }
        else { containerId = a._elContainer.id; }

        if(id[0]=='cid')
        {
            if(containerId == "div_auto_complete_o") $('id_costa_o').value=id[1];
            else $('id_costa_d').value=id[1];
        }else{
            if(containerId == "div_auto_complete_o") $('id_origen').value=id[1];
            else $('id_destino').value=id[1];
        }
        if(containerId == "div_auto_complete_o") $('nombre_origen').value=$('nombre_origen1').value=name;
        else $('nombre_destino').value=$('nombre_destino1').value=name;
};

function updateAutocompletId (a,b,c)
{
        id=c[0].split("_");
        name=c[1];
        if ($('id_costa_d')) $('id_costa_d').value='';
        if ($('id_costa_o')) $('id_costa_o').value='';
        if(id[0]=='cid')
        {
            if(a._elContainer.id=="div_auto_complete_o") $('id_costa_o').value=id[1];
            else $('id_costa_d').value=id[1];
        }else{
            if(a._elContainer.id=="div_auto_complete_o") $('id_origen').value=id[1];
            else $('id_destino').value=id[1];
        }
        if(a._elContainer.id=="div_auto_complete_o") $('nombre_origen').value=$('nombre_origen1').value=name;
        else $('nombre_destino').value=$('nombre_destino1').value=name;
};
// Metodo que inicializa el buscador a los datos por defecto, par aque no haya problema de cahes
function initBuscador()
{
	if($('tipo_buscador') && ($('tipo_buscador').value!=2)) { $('num_habitaciones').selectedIndex = '0'; }
	if($('nombre_destino1'))
    {
    	YAHOO.util.Event.removeListener('nombre_destino1');
        vmhAutoComp = new YAHOO.widget.AutoComplete("nombre_destino1","div_auto_complete_d", autoCompleteDataSource);
        vmhAutoComp.minQueryLength = 1;
        vmhAutoComp.queryDelay = 0;
        vmhAutoComp.forceSelection = false;
        vmhAutoComp.typeAhead = false;
        vmhAutoComp.maxResultsDisplayed = 7;
        vmhAutoComp.higlightClassName = "yui-ac-highlight";
        vmhAutoComp.formatResult = formatAutoComplete;
        vmhAutoComp.itemSelectEvent.fire=updateAutocompletIdVmh;
        vmhAutoComp.dataRequestEvent.fireold=vmhAutoComp.dataRequestEvent.fire;
        if(is_ie) vmhAutoComp.useIFrame = true;
        vmhAutoComp.animVert = false;
        vmhAutoComp.animHoriz = false;
        vmhAutoComp.animSpeed = 0;
        vmhAutoComp.dataRequestEvent.fire=function ( oSelf , sQuery )
        {
            $('indicator2').style.display='inline';
            $('div_auto_complete_d').style.width="470px";
            vmhAutoComp.dataRequestEvent.fireold ( oSelf , sQuery );
        }
        vmhAutoComp.dataReturnEvent.fireold=vmhAutoComp.dataReturnEvent.fire;
        vmhAutoComp.dataReturnEvent.fire=function ( oSelf , sQuery , aResults )
        {
            $('indicator2').style.display='none';
            vmhAutoComp.dataReturnEvent.fireold ( oSelf , sQuery, aResults );
        }
        if($('tipo_buscador').value!=2)
        {
            $('id_destino').value = '';
            $('nombre_destino').value = '';
            vmhAutoComp.forceSelection = true;
        }
    }
    if($('nombre_origen1'))
    {
    	YAHOO.util.Event.removeListener('nombre_origen1');
        vmhAutoComp2 = new YAHOO.widget.AutoComplete("nombre_origen1","div_auto_complete_o",myXHRDataSourceOrigen);
        vmhAutoComp2.minQueryLength = 1;
        vmhAutoComp2.queryDelay = 0;
        vmhAutoComp2.maxResultsDisplayed = 7;
        vmhAutoComp2.forceSelection = false;
        vmhAutoComp2.typeAhead = false;
        vmhAutoComp2.higlightClassName = "yui-ac-highlight";
        vmhAutoComp2.formatResult = formatDivAutocompleteVmh;
        vmhAutoComp2.itemSelectEvent.fire=updateAutocompletIdOrigenVmh;
        vmhAutoComp2.dataRequestEvent.fireold=vmhAutoComp2.dataRequestEvent.fire;
        if(is_ie) vmhAutoComp2.useIFrame = true;
        vmhAutoComp2.animVert = false;
        vmhAutoComp2.animHoriz = false;
        vmhAutoComp2.animSpeed = 0;
        vmhAutoComp2.dataRequestEvent.fire=function ( oSelf , sQuery )
        {
            $('indicator1').style.display='inline';
            $('div_auto_complete_o').style.width="300px";
            vmhAutoComp2.dataRequestEvent.fireold ( oSelf , sQuery );
        }
        vmhAutoComp2.dataReturnEvent.fireold=vmhAutoComp2.dataReturnEvent.fire;
        vmhAutoComp2.dataReturnEvent.fire=function ( oSelf , sQuery , aResults )
        {
            $('indicator1').style.display='none';
            vmhAutoComp2.dataReturnEvent.fireold ( oSelf , sQuery, aResults );
        }
        if($('tipo_buscador').value!=2)
        {
            $('id_origen').value = '';
            $('nombre_origen').value = '';
            vmhAutoComp.forceSelection = true;
        }
    }
    if($('tipo_buscador').value!=2)
    {
        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 formatDivAutocompleteVmh(aResultItem, sQuery)
{
    var aMarkup = ["<div id='",unescape(aResultItem[0]),"'>",unescape(aResultItem[1]) +', '+unescape(aResultItem[2]) +', ('+unescape(aResultItem[0])+')', "<"+"/"+"div>"];
    return (aMarkup.join(""));
};
function updateAutocompletIdOrigenVmh(a,b,c)
{
     $('nombre_origen1').value=$('nombre_origen').value=c[1].replace('&nbsp;&nbsp;&nbsp;','') +', '+c[2]+', ('+ c[0] +')';
     $('id_origen').value=c[0];
}
function checkVuelos(id_tarifa, marcar)
{
	var continuar = true;
	
	// Miramos q esten marcados los vuelos
	if (marcar)
	{
		// Marcamos la ida
		if(!document.getElementsByName('vida'+id_tarifa)[0].checked)
			document.getElementsByName('vida'+id_tarifa)[0].checked = true;
		ida_selected = 0;
			
		// Marcamos la vuelta
		if(!document.getElementsByName('vvuelta'+id_tarifa)[0].checked)
			document.getElementsByName('vvuelta'+id_tarifa)[0].checked = true;
		vuelta_selected = 0;
	}
	// Comprobamos si es ida y vuelta q se haya escojido un vuelo de ida y uno de vuelta.
	for(i=0;i<document.getElementsByName('vida'+id_tarifa).length;i++)
	{
		if (document.getElementsByName('vida'+id_tarifa)[i].checked)
		{
			ida_selected = i;
			break;
		}
	}

	if (document.getElementsByName('vvuelta'+id_tarifa)[0]) // Mas de una vuelta
	{
		for(i=0;i<document.getElementsByName('vvuelta'+id_tarifa).length;i++)
		{
			if (document.getElementsByName('vvuelta'+id_tarifa)[i].checked)
			{
				vuelta_selected = i;
				break;
			}
		}
	}
	
	if ((ida_selected == -1) 
		|| ((document.getElementById('vvuelta'+id_tarifa) && (vuelta_selected == -1)))
		)
	{	
		$('err'+id_tarifa).style.display='';
		continuar = false;
	}
	else
	{
		// Asiganamos los trayectos.
		document.getElementById('trayecto['+id_tarifa+'-0]').value = document.getElementById('itr_'+id_tarifa+'_'+document.getElementsByName('vida'+id_tarifa)[ida_selected].value).value;
		if (document.getElementsByName('vvuelta'+id_tarifa)[0])
		{
			document.getElementById('trayecto['+id_tarifa+'-1]').value = document.getElementById('vtr_'+id_tarifa+'_'+document.getElementsByName('vvuelta'+id_tarifa)[vuelta_selected].value).value;
		}
		
		// Asignamos la tarifa (solo si se ha cambiado el vuelo)
		it_ida = (document.getElementById(id_tarifa+'_it_vue_'+document.getElementsByName('vida'+id_tarifa)[ida_selected].value).value).split('/');
		it_vuelta = document.getElementById(id_tarifa+'_it_vue_'+document.getElementsByName('vvuelta'+id_tarifa)[vuelta_selected].value).value;
		document.getElementById('it_vue['+id_tarifa+']').value = it_ida[0]+'/'+it_vuelta+'/'+it_ida[1]+'/'+it_ida[2];
			
	}
	
	return continuar;

}
function generarParamsVuelos(id_tarifa)
{
	params_vuelos = {};
    var x=$("form"+id_tarifa);
    for (var i=0;i<x.length;i++) params_vuelos[x.elements[i].name]=escape(x.elements[i].value);
    id_tarifa_vuelos=id_tarifa;
}
function generarParamsHoteles(hci,id_hotel,tarifa,sist_reserva)
{
    params_hoteles={'hci':hci,'id_hotel':id_hotel,'tarifa':tarifa,'sist_reserva':sist_reserva};
}
function generarParamsHotelesOferta(hci,id_hotel,tarifa,sist_reserva,vkvmhmo,special)
{
    params_hoteles={'hci':hci,'id_hotel':id_hotel,'tarifa':tarifa,'sist_reserva':sist_reserva,'vkvmhmo':vkvmhmo,'special':special};
}
function getIdFromIds(qual)
{
    if($('ids'))
    {
        ids=$('ids').value.split('|');
        switch(qual)
        {
            case "hci": return ids[0]; break;
            case "id_home": return ids[1]; break;
        }
    }else{
        return '';
    }
}
//Este metodo comprueba los datos de la home de la busqueda de vuelo+hotel
function comprobar()
{
    var error='';

    if ((($('id_origen').value != '') || ($('id_costa_o').value != '')) && $('nombre_origen1').value=='')
    {
        errores.push(new Error('12','999','008',"","setErrorBackColor($('nombre_origen1'))"));
    }

    if (($('id_origen').value == '') && ($('id_costa_o').value == '') && $('nombre_origen1').value=='')
    {
        errores.push(new Error('12','999','008',"","setErrorBackColor($('nombre_origen1'))"));
    }

    if ((($('id_destino').value != '') || ($('id_costa_d').value != '')) && $('nombre_destino1').value=='')
    {
        errores.push(new Error('12','999','008',"","setErrorBackColor($('nombre_destino1'))"));
    }

    if (($('id_destino').value == '') && ($('id_costa_d').value == '') && $('nombre_destino1').value=='' )
    {
        errores.push(new Error('12','999','003',"","setErrorBackColor($('nombre_destino1'))"));
    }
    else if ($('fecha_entrada').value=='' || $('fecha_salida').value=='' || $('fecha_salida').value==$('fecha_entrada').value)
    {
        errores.push(new Error('12','999','004',"","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','999','005',"","setErrorBackColor($('fecha_entrada'));"));
        else if (today.getUTCHours()>=20 && fecha_ini.valueOf()==fecha_control.valueOf())
        errores.push(new Error('12','999','006',""));

        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','999','007',"","setErrorBackColor($('fecha_salida'));"));
        }
        var i = 1;
        num_nin=0;
        num_adl=0;
        num_beb=0;
        num_inf=0;
        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&ntilde;o "+j+" de la habitacion "+f,"setErrorBackColor($('edad_"+f+"_"+j+"'));"));
                    if ($('edad_'+f+'_'+j).selectedIndex>0 && $('edad_'+f+'_'+j).value>=2) num_nin=num_nin+1;
                	if ($('edad_'+f+'_'+j).selectedIndex>0 && $('edad_'+f+'_'+j).value<2) num_beb=num_beb+1;
                	if ($('edad_'+f+'_'+j).selectedIndex>0 && $('edad_'+f+'_'+j).value<5) num_inf=num_inf+1;
                    j++;
                }
            }
            if ($('num_adultos_'+i))
            	num_adl=num_adl+parseInt($('num_adultos_'+i).value);
            i++;
        }
        if (num_adl+num_nin>9) errores.push(new Error('12','000','000',"No es posible solicitar más de 9 viajeros, modifique su selección"));
        if ((num_adl+1)<num_inf) errores.push(new Error('12','000','000',"No es posible solicitar más plazas de niños que de adultos, modifique su selección"));
        else if (num_adl<num_beb) errores.push(new Error('12','000','000',"No es posible solicitar más plazas de bebés que de adultos, modifique su selección"));
		if (fecha_fin.valueOf() < fecha_ini.valueOf()) errores.push(new Error('11','150','015',''));
        if (errores.cuantos()==0)
        {
        	//mostrarSplash();
        	$('busqueda_vmh').submit();
        }
    }
    errores.show();
    return false;
}
function mostrarInputsEdades(cantidad,enFila)
{

    for(i=1;i<=3;i++)
    {
         $('edad_'+enFila+'_'+i).style.display = (cantidad>=i ? '' : 'none');
    }
    if($('div_edades_'+enFila)) $('div_edades_'+enFila).style.display = (cantidad>0)?(!is_ie)? 'table-row' : 'block' : 'none';
    if($('label_edad_'+enFila)) $('label_edad_'+enFila).style.display = (cantidad>0)?(!is_ie)? 'table-row' : 'block' : 'none';
}

function mostrarFilasHabitaciones(cantidad)
{
    if(cantidad=='+')
    {
        document.location.href=dir_hoteles+"?pg=grupos";
        return;
    }
    if(cantidad>1 && $('hab1')) $('hab1').style.display='block';
    else if($('hab1')) $('hab1').style.display='none';
    for(i=1;i<(num_max_hab+1);i++)
    {
        if (i<=cantidad)
        {
            if($('fila_hab_'+i+'_a'))
            {
            $('fila_hab_'+i+'_a').style.display = (is_ie ? 'block' : 'table-row');
            $('fila_hab_'+i+'_b').style.display = (is_ie ? 'block' : 'table-row');
            $('fila_hab_'+i+'_c').style.display = (is_ie ? 'block' : 'table-row');
            if (!$('num_ninos_'+i).options[0].selected) $('label_edad_'+i).style.display = (is_ie ? 'block' : 'table-row');
            }
        }else{
            if($('fila_hab_'+i+'_a')) $('fila_hab_'+i+'_a').style.display = 'none';
            if($('fila_hab_'+i+'_b')) $('fila_hab_'+i+'_b').style.display = 'none';
            if($('fila_hab_'+i+'_c')) $('fila_hab_'+i+'_c').style.display = 'none';
            $('label_edad_'+i).style.display    = 'none';
        }
    }
}
function actualizaNinos(fila)
{
    var lim = 0;
    var i=0;
    var a = $('num_adultos_'+fila);
    var n = $('num_ninos_'+fila);
    var nAd = parseInt(a[a.selectedIndex].value);
    var nNi = parseInt(n[n.selectedIndex].value);
    n.options.length = 0;
    lim = (nAd > 0) ? nAd + 1 : nAd;
    if(nAd<4) lim++;
    while ((i<lim) && ((nAd+i) <= 6))
    {
        n.options[i] = new Option(i,i);
        if (i == (nNi-0)) n.options[i].selected = true;
        i++;
    }
}
function actualizaAdultos(fila)
{
    var a = $('num_adultos_'+fila);
    var n = $('num_ninos_'+fila);
    nNi = parseInt(n[n.selectedIndex].value);
    nAd = parseInt(a[a.selectedIndex].value);
    if (nNi > 3)
    {
        errores.push(new Error('12','999','001'));
        errores.show();
        n.selectedIndex = 0;
        return false;
    }else{
        a.options.length=0;
        if (nNi == 0) i = 1;
        else i = nNi - 1;
        j=0;
        while ((i+nNi) <= 6)
        {
            a.options[j] = new Option(i,i);
            if (i == nAd) a.options[j].selected = true;
            j++; i++;
        }
    }
}
//Muestra el layer con varios destinos
function mostrar_destinos(app)
{
    oPanel = new YAHOO.widget.Panel("panel",{ width:"300px", constraintoviewport: true, underlay:"none", close:true, draggable:true, fixedcenter:false, zIndex:1000, context:["origenes_trigger_vmh","tl","bl"], iframe: true});
    oPanel.setHeader(destinos_mas_frecuentes.toUpperCase());
    YAHOO.util.Connect.asyncRequest('GET', dir_vuelos+'index.php?pg=destinos_frecuentes&mode=null',{success:function(response){html=response.responseText;oPanel.setBody(html); oPanel.render($('principal')); oPanel.show(); }});

}
function formatAutoComplete (aResultItem, sQuery) {
    var aMarkup = ["<div class='zindex300' id='",unescape(aResultItem[1]),"'>",unescape(aResultItem[2]), "<"+"/"+"div>"];
    return (aMarkup.join(""));
};
function recuperarDatos()
{
    if($('id_regimen_menu'))
    {
        mostrarFilasHabitaciones($F('num_habitaciones'))
        for(k=1;k<=$F('num_habitaciones');k++)
        {
            actualizaNinos(k);
            mostrarInputsEdades($('num_ninos_'+k)[$('num_ninos_'+k).selectedIndex].value,k);
        }
    }
};
//Calendarios
/*
if(cod_idioma && cod_idioma == 'it') {
    var months_long=["Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"];
    var day_short=["Do", "Lu", "Ma", "Me", "Gi", "Ve", "Sa"];
}else {
    var months_long=["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"];
    var day_short=["Do", "Lu", "Ma", "Mi", "Ju", "Vi", "Sa"];
}
*/
function setUpCalendar()
{
    if(!$('fecha_salida')){ setTimeout('setUpCalendar();',200);return;}
    if(no_cal!='') return;
    var calOptions ={iframe:true,PAGES:2,close:true,pagedate: (d.getMonth()+1)+"/"+d.getFullYear(),  mindate: (d.getMonth()+1)+"/"+d.getDate()+"/"+d.getFullYear(),  maxdate: (d.getMonth()+1)+"/"+d.getDate()+"/"+(d.getFullYear()+1)};
    var calOptions2={iframe:true,PAGES:2,close:true,pagedate: (d.getMonth()+1)+"/"+d.getFullYear(),  mindate: (d.getMonth()+1)+"/"+(d.getDate()+1)+"/"+d.getFullYear(),  maxdate: (d.getMonth()+1)+"/"+d.getDate()+"/"+(d.getFullYear()+1)};
    cal1 = new YAHOO.widget.CalendarGroup("cal1","cal1Container",calOptions);
    cal2 = new YAHOO.widget.CalendarGroup("cal2","cal2Container",calOptions2);
    YAHOO.util.Event.removeListener("entrada-trigger");
    YAHOO.util.Event.addListener("entrada-trigger", "click", showCal, cal1, true);
    YAHOO.util.Event.removeListener("fecha_entrada");
    YAHOO.util.Event.addListener("fecha_entrada", "click", showCal, cal1, true);
    YAHOO.util.Event.removeListener("salida-trigger");
    YAHOO.util.Event.addListener("salida-trigger", "click", showCal, cal2, true);
    YAHOO.util.Event.removeListener("fecha_salida");
    YAHOO.util.Event.addListener("fecha_salida", "click", showCal, cal2, true);
    
    if($('fecha_salida')) $('fecha_salida').setAttribute('autocomplete', 'off');
    if($('fecha_entrada'))  $('fecha_entrada').setAttribute('autocomplete', 'off');
    
    cal1.selectEvent.subscribe(calSelectDate, cal1, true);
    cal2.selectEvent.subscribe(calSelectDate, cal2, true);
    cal1.cfg.setProperty("MONTHS_LONG",months_long);
    cal1.cfg.setProperty("WEEKDAYS_SHORT",day_short);
    cal1.cfg.setProperty("START_WEEKDAY",1);
    cal1.cfg.setProperty("NAV_ARROW_LEFT","/images_new/flecha_iz.gif");
    cal1.cfg.setProperty("NAV_ARROW_RIGHT","/images_new/flecha_de.gif");
    cal2.cfg.setProperty("MONTHS_LONG",months_long);
    cal2.cfg.setProperty("WEEKDAYS_SHORT",day_short);
    cal2.cfg.setProperty("START_WEEKDAY",1);
    cal2.cfg.setProperty("NAV_ARROW_LEFT","/images_new/flecha_iz.gif");
    cal2.cfg.setProperty("NAV_ARROW_RIGHT","/images_new/flecha_de.gif");
    if($('fecha_entrada').value!='')
    {
        tmp=$('fecha_entrada').value.split("/");
        cal1.cfg.setProperty("selected",tmp[1]+'/'+tmp[0]+'/'+tmp[2],false);
        cal1.cfg.setProperty("pagedate",tmp[1]+'/'+tmp[2],false);
    }
    if($('fecha_salida').value!='')
    {
    	if (tmp!='') cal2.cfg.setProperty("mindate",tmp[1]+'/'+tmp[0]+'/'+tmp[2],false);
        tmp2=$('fecha_salida').value.split("/");
        //cal2.cfg.setProperty("selected",tmp[1]+'/'+tmp[0]+'/'+tmp[2],false);
        cal2.cfg.setProperty("pagedate",tmp2[1]+'/'+tmp2[2],false);
        cal2.select(tmp2[1]+'/'+tmp2[0]+'/'+tmp2[2]);
    }
    cal1.render();
    cal2.render();
}
function calSelectDate(type,args,obj)
{
    var dates = args[0][0];
    var year = dates[0], month = dates[1], day = dates[2];
    if(obj.id=="cal1")
    {
        var fechaSalida = ($('fecha_salida').value)?$('fecha_salida').value.split('/'):null;
        if(fechaSalida!=null)
        {
            var fechaEntrada=$('fecha_entrada').value.split('/');
            if(!$('fecha_entrada').value) fechaEntrada=[dates[2],dates[1], dates[0]];
            var fecha_ini=new Date(parseInt(fechaEntrada[2], 10),parseInt(fechaEntrada[1], 10)-1,parseInt(fechaEntrada[0], 10));
            var fecha_fin=new Date(parseInt(fechaSalida[2], 10),parseInt(fechaSalida[1], 10)-1,parseInt(fechaSalida[0], 10));
            $('num_noches').value=Math.round((fecha_fin.getTime()-fecha_ini.getTime())/(1000*3600*24));
            var nn = parseInt($('num_noches').value);
		    var fecha_ini_nueva=new Date(year,month-1,day);
        	if (fecha_ini_nueva>=fecha_fin)
        	{
        		nn=1;
	            var next_day=new Date(year, month-1, day+nn);
	            var nday=next_day.getDate();
	            var nmonth=next_day.getMonth()+1;
	            var nyear=next_day.getFullYear();
	            if(parseInt(nday)<10) nday="0"+nday;
	            if(parseInt(nmonth)<10) nmonth="0"+nmonth;
		        $('fecha_salida').value = nday + "/" + nmonth + "/" + nyear;
		        cal2.select(nmonth+"/"+nday+"/"+nyear);
		        cal2.cfg.setProperty("pagedate",nmonth+"/"+nyear,false);
		        cal2.setMonth(nmonth-1);
		        cal2.setYear(nyear);
        	}
        }else{
            $('num_noches').value=1;
            var nn = parseInt($('num_noches').value);
	        var next_day=new Date(year, month-1, day+nn);
	        var nday=next_day.getDate();
	        var nmonth=next_day.getMonth()+1;
	        var nyear=next_day.getFullYear();

	        if(parseInt(nday)<10) nday="0"+nday;
	        if(parseInt(nmonth)<10) nmonth="0"+nmonth;

	        $('fecha_salida').value = nday + "/" + nmonth + "/" + nyear;
	        cal2.select(nmonth+"/"+nday+"/"+nyear);
	        cal2.cfg.setProperty("pagedate",nmonth+"/"+nyear,false);
	        cal2.setMonth(nmonth-1);
	        cal2.setYear(nyear);
        }
        if(parseInt(day)<10) day="0"+day;
        if(parseInt(month)<10) month="0"+month;
        $('fecha_entrada').value = day + "/" + month + "/" + year;
        cal2.cfg.setProperty("mindate",month+"/"+day+"/"+year,false);
		cal2.render();
    }else if(obj.id=="cal2")
    {
        if($('fecha_entrada').value)
        {
            fechaSalida=[dates[2],dates[1], dates[0]];
            var fechaEntrada=$('fecha_entrada').value.split('/');
            var fecha_ini=new Date(parseInt(fechaEntrada[2], 10),parseInt(fechaEntrada[1], 10)-1,parseInt(fechaEntrada[0], 10));
            var fecha_fin=new Date(parseInt(fechaSalida[2], 10),parseInt(fechaSalida[1], 10)-1,parseInt(fechaSalida[0], 10));
            if(fecha_ini.getTime()>=fecha_fin.getTime())
            {
                errores.push(new error_o('12','999','002'));
                errores.show();
                return;
            }else{
                if(parseInt(day)<10) day="0"+day;
                if(parseInt(month)<10) month="0"+month;
                $('fecha_salida').value = day + "/" + month + "/" + year;
            }
        }else{
            var pday=d.getDate();
            var pmonth=d.getMonth()+1;
            var pyear=d.getFullYear();
            if(parseInt(pday)<10) pday="0"+pday;
            if(parseInt(pmonth)<10) pmonth="0"+pmonth;
            if(parseInt(day)<10) day="0"+day;
            if(parseInt(month)<10) month="0"+month;
            $('fecha_entrada').value = pday + "/" + pmonth + "/" + pyear;
            $('fecha_salida').value = day + "/" + month + "/" + year;
        }
    }
    eval(obj.id+".hide()");
}
function showCal(even,obj)
{
    if(obj.oDomContainer.style.display=='none' || obj.oDomContainer.style.display=='')
    {
        if(obj.id=='cal1'){ cal1.show(); cal2.hide();}
        else {cal1.hide(); cal2.show();}
    }else eval(obj.id+".hide()");
}
function mostrar_origenes2()
{
    if(oPanel) oPanel.destroy();
    input_m_vmh="origen";
    oPanel = new YAHOO.widget.Panel("panel_origenes",
        { width:'300px', underlay:"none", close:true, draggable:false, fixedcenter:false, zIndex:1000, context:["origenes_trigger","tl","bl"], iframe: true }
    );
    load_url = dir_vuelos+'origenes_frecuentes/mode.null'
    YAHOO.util.Connect.asyncRequest("get",load_url, {
          timeout: 10000,
          success: function(o) {
             oPanel.setHeader(ciudades_mas_frecuentes.toUpperCase());
             oPanel.setBody(o.responseText);
             oPanel.render(document.body);
          },
          failure: function() {
             return false;
          }
        });
}

function mostrar_destinos2()
{

    if(oPanel) oPanel.destroy();

    input_m_vmh="destino";
    oPanel = new YAHOO.widget.Panel("panel_destinos",
        { width:'300px', underlay:"none", close:true, draggable:false, fixedcenter:false, zIndex:1000, context:["destinos_trigger","tr","bl"], iframe: true }
    );
    load_url = dir_vuelos+'destinos_frecuentes/mode.null'
    YAHOO.util.Connect.asyncRequest("get",load_url, {
          timeout: 10000,
          success: function(o) {
             oPanel.setHeader(ciudades_mas_frecuentes.toUpperCase());
             oPanel.setBody(o.responseText);
             oPanel.render(document.body);
          },
          failure: function() {
             return false;
          }
        });
        $('id_destino').value = "";
        $('nombre_destino').value = "";
}
function propagarHuespedes()
{
    n_h=$('num_habitaciones').value;
    for(i=2;i<=5;i++)
    {
        $('num_adultos_'+i).value=0;
        $('num_ninos_'+i).value=0;
    }
    for(i=1;i<=n_h;i++)
    {
        $('num_adultos_'+i).value=$('num_adultos_1').value;
        $('num_ninos_'+i).value=$('num_ninos_1').value;
    }
}
function sendFormHome()
{
    try{
        $('origen').value=$('nombre_origen1').value;
        document.forms.busqueda.destino.value = document.forms.busqueda.nombre_destino1.value;
        $('fecha_regreso').value=$('fecha_salida').value;
        $('fecha_salida').value=$('fecha_entrada').value;
        if(valid_form()) enviar_form_vmh(true);
        else{
        $('fecha_entrada').value=$('fecha_salida').value;
        $('fecha_salida').value=$('fecha_regreso').value;
        }
    }catch(e){
        $('fecha_entrada').value=$('fecha_salida').value;
        $('fecha_salida').value=$('fecha_regreso').value;
    }
    return false;
}

function mostrar(destino){

    $('Principales').style.display="none";
    $('Spain').style.display="none";
    $('Europa').style.display="none";
    $('Resto').style.display="none";
    $('imgPrincipales').src="/images_new/css/bullet.gif";
    $('imgSpain').src="/images_new/css/bullet.gif";
    $('imgEuropa').src="/images_new/css/bullet.gif";
    $('imgResto').src="/images_new/css/bullet.gif";

    switch (destino){
        case "Principales":
            $('Principales').style.display="block";
            $('imgPrincipales').src="/images_new/css/bullet_down.gif";
            break;
        case "Spain":
            $('Spain').style.display="block";
            $('imgSpain').src="/images_new/css/bullet_down.gif";
            break;
        case "Europa":
            $('Europa').style.display="block";
            $('imgEuropa').src="/images_new/css/bullet_down.gif";
            break;
        case "Resto":
            $('Resto').style.display="block";
            $('imgResto').src="/images_new/css/bullet_down.gif";
            break;
    }
}
function cargaPaises(letra, zona)
{
    switch (zona){
        case 'Europa':
            destino='EuropaList';
            break;
        case 'Resto':
            destino='RestoList';
            break;
        default:
            break;
    }
    load_url = dir_vuelos+'index.php?pg=origenes_frecuentes_pais&zona='+zona+'&letra='+letra;
    YAHOO.util.Connect.asyncRequest("get",load_url, {
          timeout: 10000,
          success: function(o) {
              $(destino).innerHTML=o.responseText;
          },
          failure: function() {
             return false;
          }
        });
}

function cargaCiudades(pais, zona)
{
    switch (zona){
        case 'Europa':
            destino='EuropaList';
            break;
        case 'Resto':
            destino='RestoList';
            break;
        default:
            break;
    }
    pais = escape(pais);
    load_url = dir_vuelos+'index.php?pg=origenes_frecuentes_ciudad&zona='+zona+'&pais='+pais;
    YAHOO.util.Connect.asyncRequest("get",load_url, {
          timeout: 10000,
          success: function(o) {
              $(destino).innerHTML=o.responseText;
          },
          failure: function() {
             return false;
          }
        });
}

function ActivaSelects(objeto,valor)
{
    for (var i=0;i<objeto.length;i++)
    {
        if (objeto.options[i].value==valor) objeto.options[i].selected=true;
    }
}
