elfoco = false;     //Para saber que adulto - Nio fue seleccionado
var IdSeat_foco;        //Que id del Adulto - Nio fue seleccionado
var Avion_Select;       //Indica que Avion esta Revisando
//Ayuda de Paquetes  
var Tmpmoveobj;
var Tmpobj;             //objeto que se va a buscar la posicion..

//Determina Si Existe el elemento
function ExistsObj(obj) { 
	if (typeof obj=='string' && obj=='undefined') {
		return false;
	} else if (typeof obj!='undefined' && obj!=null) { 
		return true; 
	} else { return false; } 
}
//[elem] = Objeto a revisar -- [alert]= mensaje de carga
function YaCargo(elem,alert) {
	if (ExistsObj(elem)==true){
		if (!elem.disabled) {
			if (elem.tagName == "INPUT") {
				elem.value = '';
				elem.style.background= "url('/_Lib/Images/indicator.gif') no-repeat right";
			}
		} {elem.style.background= '';}
	}
}
function oWaitPage(){
	try {
		if (typeof busyBox!='undefined' && busyBox!=null){
			if (typeof busyBox.Show=='function') {
				busyBox.Show();
			}
		}
	}catch(ex){
	}
}

//funcion que obtiene el texto del id seleccionado a un origen
function ObtieneTextoSelect(inputori, inputdes, tipo) { //0 = Valor, 1= Texto de Combo
    if (tipo == 1) {
        inputdes.value = inputori.options[inputori.selectedIndex].text
    } else {
        inputdes.value = inputori.value;
    }
   
}

//Funcion que cambia atributos de un formulario
//[forma]    = Nombre del formulario
//[onsubmit] = Si valor  quiere  decir que reemplace el obsubmit que tenia el formulario 
//[action]   = Si valor, debe  cambiar la action del formulario/////

function SubmitForm(forma,onsubmit,url,remAttr) {
	
	/*if (param1 !='')
	  	eval(param1.replace(new RegExp("#","g"),"'"))*/
	var error = false; //No Hubo error
	//Ya tiene onsubmit el formulario? True  False	
	//Indica que quite el onsubmit
	if (remAttr!='') { 
		var rem = forma.removeAttribute(remAttr); 
		forma.onsubmit = null;		
	}	
	var existe = (ExistsObj(forma.onsubmit)==true) ? true :  false;	
	//si quieren cambiar el onsubmit o Agregar !!!
	if (onsubmit!="") { 
	   //forma.onsubmit = onsubmit; existe= true;  //cambio 	
	   // forma.setAttribute('onsubmit',onsubmit); existe= true; 
	   forma.onsubmit = function(){return eval(onsubmit.replace('return ',''));};existe= true;
	}		
	//Tiene ruta? Cambia la accion
	if(url!=""){ forma.action = url;}
	
	//Si tiene onsubmit el formulario ?
	if(existe==true)  { 
		//Ejecuto onsubmit:  False: Todo bien; True: Hubo Error	 
		if (!!forma.onsubmit()==true) {error = false;} else {error = true;}
	}	
	if (error == false){  //Si no hay error hago el submit del form..
		oWaitPage(); //muesra pagina de espera
		forma.submit(); return true;		
	}else { 
		return false;
	}
}
// Put Focus if Called
if (window.focus) {
	self.focus();
}
//funcion  que solo cambia la accion del formulario
function changeactionform(forma,url){
	forma.action = url;        
}
//Funcion que Cambia la Accion del Formulario de "PAGINAS DE DESTINOS"
function ChangeActionHotel(forma,cbodest,url,urlgral,arrDest,cboclasif,arrClasif){
	//Obtengo Clave de Combos	
	var _CboDest	=  (ExistsObj(cbodest)==true)? cbodest.value : '';
	var _CboClasif	=  (ExistsObj(cboclasif)==true)? cboclasif.value : '';
	//Obtengo Elemento Array y Carpeta del Destino Seleccionado
	var _ArrCboDest='';
	_ArrCboDest = (ExistsObj(typeof arrayDestinos)==true)? arrayDestinos : ''; 
	if (_ArrCboDest=='') { _ArrCboDest	=  (ExistsObj(arrDest)==true)? arrDest : ''; }
	if (typeof _ArrCboDest == 'object') { 
		if (! _ArrCboDest.length) { _ArrCboDest = _ArrCboDest.value;}
		else {
			_ArrCboDest = (_ArrCboDest.length && _CboDest!='')? _ArrCboDest[_CboDest] : '';
		}		
	}	
	//Obtengo Elemento Array y Carpeta del Destino Seleccionado
	var _ArrCboClasif = "";
	if (ExistsObj(arrClasif)==true) { _ArrCboClasif = (ExistsObj(arrClasif[_CboClasif])==true) ? arrClasif[_CboClasif] : ""; }
	if (_ArrCboDest!='') {		
		url = url.replace("<path>",(_ArrCboDest!="") ? _ArrCboDest : "");
		url = url.replace("<clasif>/",(_ArrCboClasif!="") ? _ArrCboClasif + "/" : "");
	}		
	//obtengo la carpeta del destino	
	if (_ArrCboDest != "" ) {
		forma.action = url;			//Ruta en el Destino + Clasificador de Hoteles o Tours
	}else {			
		forma.action = urlgral; 	//cambia action y manda a la Pagina General
	}	
	return true;
}
//funcion que cambia la accion del formulario segun el Operador de traslados
function ChangeActionShuttles(forma,ruta,airport){
    //debe tener formato  "Aiport" | "Clave Operador"
    if (typeof airport == 'string') {
        airport = airport;
        operador = '';
    } else if (airport.value != '')  {
		var result = airport.value.split("|");
		airport	 = (ExistsObj(result[0])==true)? result[0] : '';  //Obtengo Nombre Corto o Aeropuerto
		operador = (ExistsObj(result[1])==true)? result[1] : '';  //Obtengo clave del Operador
	} else {
		airport = ''; operador = '';
	}
	if (ruta == "") { 
		switch (f$("Idioma").value.toLowerCase()) {
			case "ing":
				ruta = "/Transfers/<air>/"; break;
			case "esp":
				ruta = "/Traslados/<air>/"; break;				
			case "por":
				ruta = "/Traslados/<air>/"; break;
			default:
		}					
	}
	ruta = ruta.replace('<air>',airport);		//pongo el aeropuerto		
	forma.action = ruta;						//cambio la accion del formulario
}
// abre la ventana de la galeria de imagenes
function openVideoOvnos(src, ancho, alto) {    
  //  if (typeof busyBox !='undefined' && busyBox !=null) { busyBox.Hide(); }
	popupWin = window.open(src,'gallery', 'top=25,left=25,width=' + ancho + ',height=' + alto + ',buttons=no,scrollbars=no,location=no,menubar=no,resizable=no,status=no,directories=no,toolbar=no');
}
// openWindow function for photo gallery
function openGallery(src, width, height) {
    var _width = (typeof width == 'undefined') ? 415 : width;
    var _height = (typeof width == 'undefined') ? 370 : height;
	popupWin = window.open(src,'gallery', 'top=25,left=25,width=415,height=370,buttons=no,scrollbars=no,location=no,menubar=no,resizable=no,status=no,directories=no,toolbar=no'); 
}
// openWindow function for photo gallery
function openMeetingMap(src) {
	popupWin = window.open(src,'gallery', 'top=25,left=25,width=400,height=300,buttons=no,scrollbars=no,location=no,menubar=no,resizable=no,status=no,directories=no,toolbar=no')
}
// openWindow function for calendar
function openCalendar(src,width,height) {	
	var _width  = (typeof width=='undefined')? 400: width;
	var _height = (typeof width=='undefined')? 380: height;
	popupWin = window.open(src,'calendar', 'top=35,left=35,width=' + _width + ',height=' + _height + ',buttons=no,scrollbars=no,location=no,menubar=no,resizable=no,status=no,directories=no,toolbar=no')
}
// openWindow function for room info
function openRoomInfo(src) {
	popupWin = window.open(src,'Rooms', 'top=25,left=25,width=415,height=300,buttons=no,scrollbars=yes,location=no,menubar=no,resizable=no,status=no,directories=no,toolbar=no')
}
// openWindow function for billing and cancelation policies
function openTerms(src, width, height) {
    var _width = (typeof width == 'undefined') ? 465 : width;
    var _height = (typeof width == 'undefined') ? 300 : height;
  //  var ie = document.all ? true : false;  if(ie==true) { busyBox.Hide(); }
    popupWin = window.open(src, 'Terms', 'top=25,left=25,width=' + _width + ',height=' + _height + ',buttons=no,scrollbars=yes,location=no,menubar=no,resizable=no,status=no,directories=no,toolbar=no')
}
// openWindow function for print rates
function openRates(src) {
 //   var ie = document.all ? true : false;  if(ie==true) { busyBox.Hide(); }
	popupWin = window.open(src,'Print', 'top=25,left=25,width=750,height=500,buttons=no,scrollbars=yes,location=no,menubar=no,resizable=no,status=no,directories=no,toolbar=no')
}
function openRatesHotelList_T1(destino) {
	var src
	src= 'http://www.e-travelsolution.com.mx/Reservations/Partners.aspx?asoc=T1MSNMX&Type=Hotels&View=List&Idioma=ESP&moneda=PE&destino=' + destino + '&dia_desde=' + document.forma.dia_desde.value +  '&mes_desde=' + document.forma.mes_desde.value + '&anio_desde=' + document.forma.anio_desde.value + '&dia_hasta=' + document.forma.dia_hasta.value +  '&mes_hasta=' + document.forma.mes_hasta.value + '&anio_hasta=' + document.forma.anio_hasta.value 
	popupWin = window.open(src,'Print', 'top=25,left=25,width=710,height=600,buttons=no,scrollbars=yes,location=no,menubar=no,resizable=no,status=no,directories=no,toolbar=no')
}         
function openRatesHotelList_Todito(destino) {
	var src
	src= 'http://www.e-travelsolution.com.mx/Reservations/Partners.aspx?asoc=todito&Type=Hotels&View=List&Idioma=ESP&moneda=PE&destino=' + destino + '&dia_desde=' + document.forma.dia_desde.value +  '&mes_desde=' + document.forma.mes_desde.value + '&anio_desde=' + document.forma.anio_desde.value + '&dia_hasta=' + document.forma.dia_hasta.value +  '&mes_hasta=' + document.forma.mes_hasta.value + '&anio_hasta=' + document.forma.anio_hasta.value 
	popupWin = window.open(src,'Print', 'top=25,left=25,width=710,height=600,buttons=no,scrollbars=yes,location=no,menubar=no,resizable=no,status=no,directories=no,toolbar=no')
}
function openRatesHotelList_T1_2(destino) {
	var src
	src= 'http://www.e-travelsolution.com.mx/Reservations/Partners.aspx?asoc=T1MSNMX&Type=Hotels&View=List&Idioma=ESP&moneda=PE&destino=' + destino + '&dia_desde=' + document.forma.dia_desde.value +  '&mes_desde=' + document.forma.mes_desde.value + '&anio_desde=' + document.forma.anio_desde.value + '&nights=' + document.forma.nights.value 
	popupWin = window.open(src,'Print', 'top=25,left=25,width=710,height=600,buttons=no,scrollbars=yes,location=no,menubar=no,resizable=no,status=no,directories=no,toolbar=no')
}
function openRatesTourList_T1(asoc,idioma,destino) {
	var src
	src= 'http://www.e-travelsolution.com.mx/Reservations/Partners.aspx?asoc=T1MSNMX&Type=Tours&View=List&Idioma=ESP&moneda=PE&destino=' + destino 
	popupWin = window.open(src,'Print', 'top=25,left=25,width=710,height=600,buttons=no,scrollbars=yes,location=no,menubar=no,resizable=no,status=no,directories=no,toolbar=no')
}
function openRatesTourList_Todito(destino) {
	var src
	src= 'http://www.e-travelsolution.com.mx/Reservations/Partners.aspx?asoc=todito&Type=Tours&View=List&Idioma=ESP&moneda=PE&destino=' + destino 
	popupWin = window.open(src,'Print', 'top=25,left=25,width=710,height=600,buttons=no,scrollbars=yes,location=no,menubar=no,resizable=no,status=no,directories=no,toolbar=no')
}
//http://www.e-travelsolution.com/reservations/partners.aspx?view=info&airport=cun&type=Transfers&Asoc=livcun
function openRatesTransferList_T1(destino) {
	var src
	src= 'http://www.e-travelsolution.com.mx/reservations/partners.aspx?view=info&airport=' + destino +  '&type=Transfers&Asoc=t1msnmx&Menu=yes' 
	popupWin = window.open(src,'Print', 'top=25,left=25,width=710,height=600,buttons=no,scrollbars=yes,location=no,menubar=no,resizable=no,status=no,directories=no,toolbar=no')		
}
function openRatesTransferList_Todito(destino) {
	var src
	src= 'http://www.e-travelsolution.com.mx/reservations/partners.aspx?view=info&airport=' + destino +  '&type=Transfers&Asoc=todito&Menu=yes' 
	popupWin = window.open(src,'Print', 'top=25,left=25,width=710,height=600,buttons=no,scrollbars=yes,location=no,menubar=no,resizable=no,status=no,directories=no,toolbar=no')
}
//funcion que abre un pagina Tipo pop-up
//[src]			=  Ruta Total o PreArmada en java	
//[paramobj]	=  Onjetos donde tomara los datos para armar el src... 'elem1,elem2,elem3,etc'
//[remplaza]	=  '<elem1>,<elem2>,<elem3>,etc' ahi pondra el valor segun la posicion de los elementos
function openInfoTour(src,objs,remplaza,_width,_height) {

    var ie = document.all ? true : false; 
	if (ExistsObj(remplaza)==true) {		
		if (objs!=''){		
			//Tipo de delimitador de datos 
			var delimitadorObj	  = (objs.indexOf(",") > -1) ?  "," : "|";
			var delimitadorValues = (remplaza.indexOf(",") > -1) ?  "," : "|";	 	
			objs = objs.split(delimitadorObj);  //Separo los Objetos con el delimitador
			remplaza = remplaza.split(delimitadorValues);  //Separo los valores con el delimitador	 	
			for(var i=0;i<objs.length;i++) { 	
				var _obj = objs[i];  //Nombre del Primer Objeto encontrado
				if (_obj.indexOf('document.')>-1) {
					_obj = eval(_obj); //Obtengo el Objeto
					if (ExistsObj(_obj)==true)
						if (ExistsObj(remplaza[i])==true) {						
							src = src.replace(remplaza[i],_obj.value) //Busca en el src  y remplaza por el valor					
						}
				}						
			}	
		}
	}	
	_width = (ExistsObj(_width) == true && _width > 0)? _width : 550; //Tomo el Ancho de la Ventana
	_height = (ExistsObj(_height) == true && _height > 0)? _height : 600;  //Tomo el Alto de la Ventana
	popupWin = window.open(src,'Tour', 'top=25,left=25,width=' + _width +  ',height=' + _height + ',buttons=no,scrollbars=yes,location=no,menubar=no,resizable=no,status=no,directories=no,toolbar=no')
	
}
function openPictureWindow_Fever(imageName,imageWidth,imageHeight,alt,posLeft,posTop) {
	newWindow = window.open('','newWindow',"width="+imageWidth+",height="+imageHeight+",left="+posLeft+",top="+posTop);
	newWindow.document.open();
	newWindow.document.write('<html><title>'+alt+'</title><body bgcolor="#FFFFFF" leftmargin="0" topmargin="0" marginheight="0" marginwidth="0" onBlur="self.close()">'); newWindow.document.write('<img src='+imageName+' width='+imageWidth+' height='+imageHeight+' alt='+alt+'>'); 
	newWindow.document.write('</body></html>');
	newWindow.document.close();
	newWindow.focus();
}
function openWindowMap(src,imageWidth,imageHeight) {
    var ie = document.all ? true : false; 
   // if(ie==true) { busyBox.Hide(); }
	popupWin = window.open(src,'Map', 'top=25,left=25,width='+imageWidth+',height='+imageHeight+',buttons=no,scrollbars=yes,location=no,menubar=no,resizable=no,status=no,directories=no,toolbar=no')
}
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
	var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
	var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
	if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
// openWindow function for tour info or hotel info asoc
function OpenPopAsoc(src, tipo) {
	popupWin = window.open(src,tipo, 'top=25,left=25,width=635,height=600,buttons=no,scrollbars=yes,location=no,menubar=no,resizable=no,status=no,directories=no,toolbar=no')
}
// <a href="#" onClick="javascript:openCalendar('/_lib/asp/popCalendarTour/?clav_tour=2&clav_servicio=1&clav_ciudad_origen=CUN&Month=9&Year=2005');"
// openWindow function for tour info or Hotel asoc in Pop Up
function OpenPopAsocRedirect(forma, src, tipo) {
    //forma.target=window.open(src,tipo, 'top=25,left=25,width=635,height=600,buttons=no,scrollbars=yes,location=no,menubar=no,resizable=no,status=no,directories=no,toolbar=no');
    //forma.target='_blank';
	//forma.action=src;
	//forma.submit();
	}

function FortyONE() {
	if (typeof fortyone != 'undefined' && fortyone != null) {  fortyone.collect('userPrefs'); }
	return true;
}
//funcion que valida Cupon
function validaCupon(params){
	var objCup = eval("document." + params.Forma + ".TengoCupon");
}
var disAddonsShuttleING = "Please Indicate the airline and flight number for your airport shuttle";
var disAddonsShuttleESP = "Por favor indique la aerolinea y vuelo para su traslado del aeropuerto";
function submitoptions(idioma,recalcular,action) {	
	var forma = document.forma; 
	//todo bien
	if (recalcular == "yes") {
		if (SubmitForm(forma,'','','')==false) {
			return false;
		}			
	} else if (recalcular == "no") {
		if (SubmitForm(forma,'',action,'')==false) {
			return false;
		}
	}	
	return true;	
}		
function submitoptions2(idioma,recalcular,action) {	
	if (typeof fortyone != "undefined" && fortyone !=null)
		fortyone.collect('userPrefs');
		
	error = false;
	if (document.forma.Check_transfer) {
		if (document.forma.Check_transfer.checked == true & (document.forma.AirlineReturn.value == " || document.forma.AirlineGo.value == " )) {			
			alert(fdic.trad(disIndiqueAerolineaTraslado,idioma));
			return false;		
		}		
	    if (recalcular == "yes") {
			document.forma.submit();
		    return true;
	    }
	    if (recalcular == "no") {
			document.forma.action = action;
	        document.forma.submit();
	    }
	    return true;	
	} else {
		if (recalcular == "yes") {
			document.forma.submit();
		    return true;
	    }
	    if (recalcular == "no") {
	        document.forma.action = action;	        
	    }
		document.forma.submit();
	}
	return true;
}
function ol(elURL) {  window.open(elURL) }
  
// **********************************************************************************************************
//                       FUNCIONES PARA PAQUETES DE AVION + HOTEL
// **********************************************************************************************************
// [sshow]  = 1 (Mostrar)  0 (Ocultar)  // [removertag]  = true (remover tag del html)  false (Mantener)
function showPage(sshow,removertag){
//debugger;
	var obj; var ObjClassName; var _remover=false;
	try {
        var objQuitar = document.getElementById('quitar'); if (objQuitar !=null) { objQuitar.style.display='none';}
		obj = document.getElementById('cajon');
        //ObjClassName = document.getElementsByClassName('WaitPage');
		_remover = (typeof removertag == 'undefined')? false:removertag;		
        if (obj != null) {				
		    if (sshow==1){obj.style.display='';}else{obj.style.display='none';} 						
	    }
	}catch(ex) {
		if (obj!=null){obj.style.display='none';}
	}finally{
		if (_remover==true){ }	
	}
 }
 //funcion que cambia el valor de un objeto dentro de un formulario
 //[forma] = string  Objeto 
 //[obj]   = string,  
 //[valor] = cualquiera,  
function changevalueObj(forma,obj,value) {  
	var _obj = eval("document." + forma + "." + obj);
	if (typeof _obj!= "undefined" && _obj!=null)
		_obj.value = value;
	
 }

//Funcion que pasa: a un Grupo de Objetos:  su valor respectivo
//[forma]		= Nombre del Formulario
//[objs]		= Nombre de los Objetos separados por delimitador. ej. 'NumPagina,Sort,Orden' 
//[tvalues]		= Valores para cada objeto, separados por delimitador. ej. '1,A,7' 
//[Delimitador] = Por el momento solo ","  "|"
//[overwrite]	= 1 - Sobrescribe los valores de los objetos objs, 0 - Obtiene los valores de los objetos objs
 //"Parametros:"  
 //      Forma: '',
 //      Objetos:'A,B,C',  ej. 'NumPagina,Sort,Orden' 
 //		 Separador:',',
 //      Valores:'1,2,3',  ej. '1,A,7'
 //		 Separador2:',',   
 //      Overwrite: 1  0
 
 function changevalueObjs(params) {  
	var valores = ""; var objts; var vals; var overwrite=1; var forma=''; var sep1=''; var sep2='';
	forma = params.Forma;     objs  = params.Objetos;    vals  = params.Valores;   overwrite = params.Overwrite;
	if (ExistsObj(params.Separador)==true){ sep1 = params.Separador; }
	if (ExistsObj(params.Separador2)==true){ sep2 = params.Separador2; }
	if (sep1=='') { sep1 = (objs.indexOf("|") > -1) ?  "|" : ","; }
	if (sep2=='') { sep2 = (vals.indexOf("|") > -1) ?  "|" : ","; }
	
	objs = objs.split(sep1);  //Separo los Objetos con el delimitador
 	vals = vals.split(sep2);  //Separo los valores con el delimitador 	  	
	for(var i=0;i<objs.length;i++) { 	
		var _obj = objs[i];  //Nombre del Primer Objeto encontrado
		if(typeof _obj == "string") { 
			_obj = eval("document." + forma + "." + _obj )
			if (ExistsObj(_obj)==true) {
				if (ExistsObj(vals[i])==true) {
					if(overwrite == 0) { valores += _obj.value + ","; } else { _obj.value = vals[i]; }
				}else { valores += ","; }
			}
		}
	}
	//if(overwrite == 1) return valores;
	return (overwrite == 1) ? valores : '';
}

//Funcion que Almacena Temporalmente los valores de los objetos que yo le diga, a "UN SOLO Elemento Hidden"
//[forma]		 = Nombre del formulario
//[objs]		 = Nombre de los Objetos separados por delimitador. ej. 'NumPagina,Sort,Orden'
//[setValHidden] = Nombre del Elemento hidden en donde almacanare todos los valores de los Objetos
//[Delimitador]  = Por el momento solo ","  "|"
 function setValuesHidden(forma,objs,setValHidden) {  
    
	//Si no existe el elemento donde voy a almacenar lo saco
	if (typeof setValHidden == 'undefined' || setValHidden == null)
		return false;
	//Si no tiene elementos por barrer lo saco ->Formato de Objetos:  'anio_desde,mes_desde,etc..'
	if (objs == '')
	  	return false;
	  	
  	var delimitadorObj	  = (objs.indexOf(",") > -1) ?  "," : "|"; //obtiene tipo de delimitador
  	//Formato de Objetos:  'anio_desde,mes_desde,etc..'
 	objs = objs.split(delimitadorObj);  //Separo los Objetos con el delimitador
 	setValHidden.value = '';  //Limpio antes de volver a armar
	for(var i=0;i<objs.length;i++) { 	
		var _obj = objs[i];  //Nombre del Primer Objeto encontrado
		if(typeof _obj == "string") {
			//Verifico si el formulario ya es objeto o String	
			_obj = (typeof forma == "string") ? eval("document." + forma + "." + _obj) : eval("document." + forma.name + "." + _obj); 			
			if (typeof _obj != "undefined" && _obj != null)                
				setValHidden.value += _obj.value + '|'; //Almacena el comportamiento del Usuario en hidden
		}		
	}
	return true;
}

//Funcion que permite tomar los valores ("Un Elemento Hidden" formato '2,3,4,5,6') y pasarlo a cada uno de los objetos
//[forma]		 = Nombre del formulario
//[objs]		 = Nombre de los Objetos separados por delimitador. ej. 'NumPagina,Sort,Orden'
//[getValHidden] = Nombre del Elemento Hidden donde tomara el valor de Cada Objeto
//[Delimitador]  = Por el momento solo ","  "|"
//Nota:  Muy Importante el Orden de cada objeto, para pasarle su valor
//Nota:  Inverza de la funcion:  "setValuesHidden"
 function getValuesHidden(forma,objs,getValHidden) {  
 
	//Si no existe el elemento donde voy a almacenar lo saco
	if (typeof getValHidden == 'undefined' || getValHidden == null)
		return false;
	
	//Si no tiene valores el hidden lo saco	
	if (getValHidden.value == '')
		return false;
		  	
  	//Formato de Objetos:  'anio_desde,mes_desde,etc..'
  	var delimitadorObj	  = (objs.indexOf(",") > -1) ?  "," : "|";
  	
  	//Formato de Datos:  '1,2,etc..'
 	var delimitadorValues = (getValHidden.value.indexOf(",") > -1) ?  "," : "|";
  	
 	objs = objs.split(delimitadorObj);  //Separo los Objetos con el delimitador 		
 	getValHidden = getValHidden.value.split(delimitadorValues);  //Separo los valores con el delimitador del elem hidden
 	
	for(var i=0;i<objs.length;i++) { 	
		var _obj = objs[i];  //Nombre del Primer Objeto encontrado
		if(typeof _obj == "string") {
			//Verifico si el formulario ya es objeto o String	
			_obj = (typeof forma == "string") ? eval("document." + forma + "." + _obj) : eval("document." + forma.name + "." + _obj);
			if (typeof _obj != "undefined" && _obj != null)
				_obj.value = getValHidden[i]; //Obtiene valor del elemento 
		}		
	}	
}

 
//Mas Vuelos de paquetes
function Next_Flights(maxGroups) {	
	var i = 0; var presiono = document.getElementById('cuenta').value;
	presiono++;
	document.getElementById('cuenta').value = presiono; //paso el valor nuevo al

	for (i=1; i<=maxGroups; i++) {
		//Si ya revaso el maximo ?
		if (presiono > maxGroups ) {
			Hide_Flights(maxGroups);  //Oculto los Objetos
			document.getElementById('cuenta').value = 1;  //Regreso al primer valor
			eval ("document.getElementById('flight_group_1').style.display=''"); 
		} else {
			if (i == presiono)
				eval ("document.getElementById('flight_group_" + i +"').style.display=''"); 
			else
				eval ("document.getElementById('flight_group_" + i +"').style.display='none'"); 
		}
	}   
}

//Menos Vuelos de paquetes
function Previus_Flights(maxGroups) { 
	var i = 0; var presiono = document.getElementById('cuenta').value;
	presiono--;
	document.getElementById('cuenta').value = presiono; //paso el valor nuevo al

	//Hide_Flights (maxGroups)
	for (i=1; i<=maxGroups; i++) {
		//Si ya revaso el maximo ?
		if (presiono < 1 ) {             
			Hide_Flights(maxGroups);  //Oculto los Objetos
			document.getElementById('cuenta').value = maxGroups;  //Regreso al primer valor
			eval ("document.getElementById('flight_group_" + maxGroups +  "').style.display=''"); 
		} else {
			if (i == presiono) 
				eval ("document.getElementById('flight_group_" + i +"').style.display=''"); 
			else
				eval ("document.getElementById('flight_group_" + i +"').style.display='none'"); 		
		}
	}
}
  
//Oculta Todos los Vuelos
function Hide_Flights (maxGroups) { 
	var i;
	for (i=1; i<=maxGroups; i++) {
		eval ("document.getElementById('flight_group_" + i +"').style.display='none'"); 
	}
}

//Oculta Todos Asientos de Adultos - Nios del Todos los Aviones
function Hide_Adults_Childs(max) { 
	var i;
	for (i=1; i<=max; i++){
		eval ("document.getElementById('Avion_SeatsAdNi_" + i +"').style.display='none'"); 
	}    
}
  
function Hide_Airplane(max) { 
	var i;
	for (i=1; i<=max; i++) {
		eval ("document.getElementById('avion_" + i +"').style.display='none'"); 
	}    
}

function Show_Airplane(avion,max) {        

    //elfoco  = false           //Bronca al poner el dato se queda con el enfoque anterior  del primer vuelo   
    Hide_Airplane(max);        //Oculto todos los Aviones 
    Hide_Adults_Childs(max);  //Oculto el Grupos de Asientos del Avion ( Adultos - Nios )
    
    //Muestro el Avion del Vuelo Seleccionado
    eval ("document.getElementById('avion_" + avion +"').style.display=''");   
    //Muestro el Grupo de Asientos del Vuelo Seleccionado  ( Adultos - Nios )
    eval ("document.getElementById('Avion_SeatsAdNi_" + avion +"').style.display=''");   
    //Busco el nombre del Vuelo seleccionado
    Name_Flight_Select(avion,max);
    //Cambio la Clase del Vuelos Seleccioando  
    change_class(avion,max);
    //Paso que Avion fue seleccionado    (Variable Global)      
    Avion_Select =  avion;          
}
  
//Busco y paso el nombre del Vuelo seleccionado
function Name_Flight_Select(vuelo,max) { 
	var i; var myName="";
	for (i=1; i<=max; i++) {
		//Tomo el nombre del Vuelo Seleccionado 
		if (vuelo == i) {            
			myName = eval ("document.getElementById('Name_flight" + i +"').value");  //busco el nombre de vuelo selccionado           
			document.getElementById('Name_Selectflight').value = myName;   //paso el valor a un oculto           
		}
	}    
}
  
function change_class(avion,max) { 
	var i; 
	//Hago  el barrido de todos los Vuelos
	for (i=1; i<=max; i++) {        
		//Cambio la clase del Vuelo Seleccionado
		if (avion == i)        
			eval ("document.getElementById('myclass_" + i +"').className='FlightSelect'"); //cambio la clase a SELECCIONADO
		else        
			eval ("document.getElementById('myclass_" + i +"').className='FlightNonSelect'"); //cambio la clase a NO SELECCIONADO    
	}    
}
  
// **********************************************************************************************************
//                        VENTANA  EMERGENTE QUE INDICA EN QUE ASIENTO DEL AVION ESTOY UBICADO
// **********************************************************************************************************
/*var agt=navigator.userAgent.toLowerCase();
var appVer = navigator.appVersion.toLowerCase();
var is_opera = (agt.indexOf("opera") != -1);
var is_ie =  (appVer.indexOf('msie') != -1) && (!is_opera);*/

function getScrollXY() {
	var scrOfX = 35, scrOfY = 0;
	if( typeof( window.pageYOffset ) == 'number')  {
		//Netscape compliant
		scrOfY = window.pageYOffset;
		scrOfX = window.pageXOffset;		
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		//DOM compliant
		scrOfY = document.body.scrollTop;
		scrOfX = document.body.scrollLeft;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) )  {
		//IE6 standards compliant mode
		scrOfY = document.documentElement.scrollTop;
		scrOfX = document.documentElement.scrollLeft;
	}
	return [ scrOfX, scrOfY ];
}

function getWindowSize() {
	var myWidth = 0, myHeight = 0;
	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;
	}
	return [myWidth, myHeight];
}
//Regresa Objeto(s)
function f$() {    
	var _IdArray=new Array();	
	for(var i=0;i<arguments.length;i++) { 	
		var _Id=arguments[i];
		if(typeof _Id == "string") { 
			_Id = document.getElementById(_Id); //objeto por Id
		}
		if(arguments.length==1) {
			return _Id;
		}
		_IdArray.push(_Id);
	}
	

	return _IdArray;
}
//Regresa elementos por Tag Name(s)
function $TagName() {
	var _tagNameArray=new Array();	
	for(var i=0;i<arguments.length;i++) { 	
		var _tagName = arguments[i];
		if(typeof _tagName == "string") { 
			_tagName = document.getElementsByTagName(_tagName); //Tag Name
		}
		if(arguments.length==1) {
			return _tagName;
		}
		_tagNameArray.push(_tagName);
	}
	return _tagNameArray;
	
}

function showPopupWithContent(content,obj,idhtml,posPopUp)  {  

    var mleft; var mTop; var popupDiv = f$('hdPopupDiv');  
	var popupContentDiv = f$('hdPopupContent');	
	var popupWidthContainer = parseInt(popupWidth);
	var popupHtml = content;
	
	popupContentDiv.innerHTML = popupHtml;   //"<div>"+ popupHtml+"</div>";
	popupDiv.style.display = "block";
	
	var windowSize = getWindowSize();	
	//var scrollXY = getScrollXY();
	popupDiv.style.width = popupWidthContainer;
	popupDiv.style.position = "absolute";

	popupDiv.style.background = "#FFFFFF";
	//popupDiv.style.border = "1px solid #000000";	
	var posElementXY = getPositionElement(obj);
	
	//idhtml = vacio entonces arma el html en java
	if (idhtml == "") {    
	
	    // Left: I=izquierda, C=centrado, D=derecha
		switch (posPopUp) {
			case "I": mleft = (posElementXY[0] - popupWidthContainer + 20);  break;
			case "C": mleft = (posElementXY[0] - popupWidthContainer/2 + 10); break;
			case "D": mleft = (posElementXY[0] + 20);break;
			default: mleft = (posElementXY[0] + 20);
		}
		mTop+= f$(obj).offsetHeight;
		mTop = (posElementXY[1] + 20);	 //Top
	} else 	{   
		//Cuando envio el Html ( Tomo de la Pagina )
	    mleft = (posElementXY[0] - ((posElementXY[0]<1000)?10:220));  //Left
        mTop = (posElementXY[1] + 50);	 //Top
    }
	
	popupDiv.style.left = (mleft - (parseInt(popupDiv.style.width)/2)) + 'px'; //left del Objeto  //((windowSize[0] - popupWidth ) / 2) + scrollXY[0];
	popupDiv.style.top = mTop + 'px';  //Top del Objeto  //((windowSize[1] - popupHeight) / 2) + scrollXY[1];
	popupDiv.style.zIndex = 100;
	
	displayLayer('hdPopupDiv',true);
}
function displayLayerAsObj(divObj, popup) 
{
    if(popup == true) {
		divObj.style.zIndex = 100;
	}
	divObj.style.visibility = "visible";
	divObj.style.display = "inline";
}
//Me da la Posicion Izquierda del elemento
function getPositionElement(elem) {   
	//default left    //default top 
	var curleft=0;   var curtop=0;         
	var obj = f$(elem);   //tomo el nombre del elemento y convierto en objeto
	//Si tenemos al objeto
	if (obj!= null) {       
		if (obj.offsetParent) {
			curleft = obj.offsetLeft;  //tomo la posicion left del objeto
			curtop = obj.offsetTop;  //tomo el tope del objeto
			while (obj.offsetParent) {
				curleft += obj.offsetLeft;
				curtop += obj.offsetTop;
				obj = obj.offsetParent;
            }
		}
		curleft=parseInt(curleft);
		curtop=parseInt(curtop); 
	}   
	return [curleft, curtop];
} 
function displayLayer(layerName, popup) {
	var currentLayer = f$(layerName);
	displayLayerAsObj(currentLayer, popup);
}
function hideLayer(layerName)  {   
	DisplayObj(layerName,0);    
}
function hidePopup(layerName) {    
	var Version =navigator.appVersion.substring(22,25);
	Version = parseInt(Version);	
	if (navigator.appName=="Microsoft Internet Explorer")
		if (Version < 7)	    
			Mostrar_Elementos();
	hideLayer(layerName); 
}
function Ocultar_Elementos() {
	var x=document.getElementsByTagName("SELECT");  
	for (i=0;i<x.length;i++) {
		x[i].style.visibility= "hidden";
	}  
}     
function Mostrar_Elementos() {
	var x=document.getElementsByTagName("SELECT");  
	for (i=0;i<x.length;i++) {
		x[i].style.visibility= "visible";
	}	    
}
function displayMesagge(event,ColBde_Tit,titseat,tittext,width,height,obj,idhtml) {
 
    var imagen = f$(obj); 
    //Verifico que si exista el elemento Ruta de Imagen del Sitio
    imagen = (typeof imagen != "undefined" && imagen != null) ? imagen.src : "";
       
    var content =""; var htmlTemp="";        
	popupWidth = width;  popupHeight = height;
		
	//Si no tiene valor  color le pongo Blanco
	if (ColBde_Tit=="") 
		ColBde_Tit = "#FFFFFF";  //Blanco
		
	//Significa que no trae Html debo pintar el que Armo en el Java
	if (idhtml =="") {
	
		//Nombre del Vuelo Seleccionado
	    popupTitle = document.getElementById('Name_Selectflight');  	    
	    popupTitle = (typeof popupTitle != "undefined" && popupTitle !=null) ? popupTitle.value : "";
	    var num_seat = getSeat(obj);  //tomo el numero del asiento
        //Armo el Html de la Ventana Emergente de las Cabinas de Avion		
	    content += '<div style="height:100%; width:' + (popupWidth-5) + '; font-family: Trebuchet MS, Verdana;">'; 		
        content += '<table width=' + width + ' border="0" cellspacing="0" cellpadding="1" style="font-size:14px;">';
        /*content += '  <tr>';
        content += '    <td align="center" colspan="2" bgcolor="' + ColBde_Tit + '"><strong>' +  popupTitle +  '</strong></td>';
        content += '    <td bgcolor="'+  ColBde_Tit + '"><img src="' + ruta_imagen +    '/infoA.gif" width="19" height="19" border="0" align="right"></td>';
        content += '  </tr>';*/
        content += '  <tr>';
        content += '    <td valign="middle">';
        //'Segun el sitio pongo Ruta de Iamgen del Asiento
        content += '<img src="' + imagen + '" border="0" vspace="2" hspace="2" align="right" />';
        content += '</td>';
        //Available Space
        content += '    <td style="font-size:12px">&nbsp;' +  tittext + '&nbsp;<strong>' + num_seat + '</strong></td>';
        content += '    <td>&nbsp;</td>';
        content += '  </tr>';
        /*content += '  <tr>';
        content += '    <td >&nbsp;</td>';       
        //Titulo Seat   y Numero de Asiento
        content += '    <td style="font-size:12px"><strong>' +  titseat  +  ':</strong>&nbsp;' + num_seat + '</td>';
        content += '    <td>&nbsp;</td>';
        content += '  </tr>';
        content += '  <tr>';
        content += '    <td align="center"><img src="' + ruta_imagen +    '/avionI.gif" width="26" height="22" border="0" align="left" /></td>';
        content += '    <td>&nbsp;</td>';
        content += '    <td>&nbsp;</td>';
        content += '  </tr>';*/
        content += '</table>';
        content += '</div>';
        
    } else  {	    
		//Regreso el Html que le paso	    
	    htmlTemp = arrWindows_html[idhtml];
	    content += '<div style="height:100%; width:' + (popupWidth-5) + '; font-family: Trebuchet MS, Verdana;">'; 
	    content += htmlTemp;  //el Html que quiero mostrar
	    content += '</div>';	    
	}	
	showPopupWithContent(content,obj,idhtml,'D');	  //Escupo el Html que le pase o que Armo en Html   
}
//Funcion que Regresa el Nombre del Asiento que recibe el enfoque  
function getSeat(obj) {	
    var objseat = f$(obj);   //Obtengo el Objeto asiento       
    var val = objseat.alt;    //tomo su valor del alt        
    return val;  //Regreso el valor del asiento "ALT"   
}

//Pone el asiento selecionado al los Adultos - Nios
function setSeatAdNi(obj,maxAd,maxNi) {       

    //Nota:   obj = ( Nombre del Objeto 'V1_Seat1_1')
    var objseat = f$(obj);           //Convierto en objeto el asiento
    var myseat = getSeat(obj);      //Obtengo el nombre del asiento           
    var maxObj = maxAd + maxNi;     //Sumo el total de Adultos + Nios
    var armaObj;                    //Armo el nombre del objeto asiento
    var tmparmaObj;                 //Armo el nombre para cuando busco si el asiento fue asignado
    var arrayBusca;                  //Regreso true  false de encontardo y indice del  encontrado
    var obj_tomoval;                //Nombre del Objeto asiento de donde tomo el valor
    var armaObjPos;                 //Objeto donde esta ubicado el foco
    
    arrayBusca = Busca_Valor(myseat,maxObj);    //Busco si ya esta asignado el asiento asignado       
    armaObjPos = f$('V' + Avion_Select + '_ubicado');   //elemento seleccionado ( Asiento )
    
    //Ya estaba ubicado anteriormente ? 
    if (armaObjPos.value=="") {
		elfoco = false;  //Obligo que sea automatico por lo tanto pondra al primer elemento vacio el asiento      
    } else {
		elfoco = true;  //Obligo que sea por seleccion     
		IdSeat_foco = armaObjPos.value;   //Obtengo la Posicion donde se quedo  Valor Hidden   
    }
                 
    //Elemento con FOCO ( Cuando se selecciono directamente el adulto - nio )
    if  (elfoco == true) {
    
        armaObj = f$('V' + Avion_Select + '_Seat_' + IdSeat_foco);           //asiento con el foco
        obj_tomoval = f$('V' + Avion_Select + '_obj_click_' + IdSeat_foco);   //de que objeto asiento se tomo el valor
        tmparmaObj = f$('V' + Avion_Select + '_Seat_' + arrayBusca[1]);      //Objeto en donde se encontro el valor
        
        //encontro el numero de asiento (ya se asigno anteriormente)
        if (arrayBusca[0] == true) {         
            //Si son iguales los valores  limpio al adulto - Nio          
            if (armaObj.value ==  tmparmaObj.value) {                           
              My_Seat(objseat,'AS_Disp.gif');   //Cambio su estado a disponible
              armaObj.value = "";               //limpio Numero de asiento Aduulto - Nio                                                        
              obj_tomoval.value = "";           //Limpio el nombre del objeto de donde tomo el valor
            }               
        } else {                      
			//si tiene dato ? SI ==  Tiene el objeto de donde tomo el valor
            if (obj_tomoval.value != "") { 
                  var obj_ant = f$(obj_tomoval.value);  //Objeto anterior de donde se tomo el valor del asiento                        
                  My_Seat(obj_ant,'AS_Disp.gif');      //Cambio su estado a disponible                  
            }                
            My_Seat(objseat,'AS_Asign.gif');         //My asiento    
            armaObj.value =  myseat;                 //asigno el asiento al adulto - nio  
            obj_tomoval.value = obj;                 //paso el nombre del objeto                                   
            //elfoco = false;                  //Llena de manera automatica 
        }       
       
    } else  { //Elemento sin FOCO
        //Recorro el Total de Objetos Adultos - Nios
        for (var i=1; i<=maxObj; i++ ) {           
        
            armaObj = f$('V' + Avion_Select + '_Seat_' + i);                       //Obtengo el Objeto asiento
            obj_tomoval = f$('V' + Avion_Select + '_obj_click_' + i);              //de que objeto asiento se tomo el valor           
            tmparmaObj = f$('V' + Avion_Select + '_Seat_' + arrayBusca[1]);        //Objeto donde encontro el asiento
            
             //  ya fue asignado ? True = Asignado,     false = "NO Asignado"
             if (arrayBusca[0] == true) {                              
				if (armaObj.value ==  tmparmaObj.value)                   
					break;  //no hago nada                
					
             } else {
                  //el Valor del Objeto esta Vacio ?  Si = Pongo valor del Asiento  
                  if (armaObj.value == "")  {                         
                      My_Seat(objseat,'AS_Asign.gif');        //My asiento 
                      armaObj.value =  myseat;                //Pongo numero de asiento al Objeto asiento
                      obj_tomoval.value = obj;                //paso el nombre del objeto 
                      ImgApunta_AdultNinio(i,maxObj,'A');     //Apuntador (Imagen) -- Se si el Objeto tiene el Foco                      
                      break;
                  } 
             }           
        }
    }       
}

//Apunta la posicion del asiento con una imagen
function ImgApunta_AdultNinio(ind,max,tipo) {  //ImgApunta_Asiento

   //elfoco = false;  //por default no tiene el enfoque el asiento

    var ruta_img = (typeof document.getElementById('Ruta_Imagen') != 'undefined' && document.getElementById('Ruta_Imagen')!=null) ? document.getElementById('Ruta_Imagen').value : '/_lib/images/bestday';   //Obtengo la Ruta de imagen segun el sitio
    var img_Select =  ruta_img + '/arrowsmall.gif';  //Img Adulto seleccionado
    var img_NoSelect =  ruta_img + '/spacer.gif';   //Img Adulto No seleccionado        
    var armaObj;
    var armaObjPos;  //Indica cual es el Objeto que esta actualmente posicionado vuelo X Vuelo
       
    //Recorro el Total de Objetos Adultos - Nios
    for (var i=1; i<=max; i++ ) {     
      //Significa que es por asignacion por seleccion
      if (tipo ==  "") {              
		armaObjPos = f$('V' + Avion_Select + '_ubicado');      
        armaObjPos.value = ind;  //Paso el Objeto en donde esta posicionado      
        armaObj = f$('V' + Avion_Select + '_apunta_' + i);  //Objeto apuntado (  Imagen Bullet azul )
        armaObj.src =  img_Select;   //imagen arrow (seleccionado)
        
        //es el elemento Seleccionado ?  
        if (ind == i) {
            IdSeat_foco = ind;                            //Asiento que tiene el foco
            elfoco = true;                                //Tiene el enfoque el objeto
        } else {
			armaObj.src = img_NoSelect;       //imagen spacer (No seleccionado)  
        }      
      } else  {  //Asignacion Automatica
        //elfoco = false;   //cambio a Manual        
        armaObj = f$('V' + Avion_Select + '_apunta_' + i);  //apuntador Imagen Bullet Azul                 
        var j = ind + 1;   //siguiente elemento        
        armaObj.src = img_NoSelect;  //apuntado Imagen no seleccionado
        
        if (j<=max) { //Si es menor del Maximo? 
          armaObj = f$('V' + Avion_Select + '_apunta_' + j);  //apunto siguiente elemento "Imagen seleccionado"          
          armaObj.src =  img_Select;                        //Cambio la Imagen asiento a ( My Asiento )
        }   
      }      
    }              
}
//Busca en los Adultos el numero de asiento  y valida si ya fue asignado anteriormente
function Busca_Valor(val,maxObj) {
    //var qVuelo =  Avion_Select; //Variable Global con Vuelo Seleccionado  
    var encontro = false;  var encontroInd =0;
    var armaObj;  //Objeto Asiento seleccionado     
    for (var i=1; i<=maxObj; i++ ) {   
		armaObj = f$('V' + Avion_Select + '_Seat_' + i);  //Armo el Objeto Asiento         
        //Valor que paso, es Igual al valor del elemento seleccionado ?
        if (val == armaObj.value) {        
			return [true,i];  //Fue encontrado y Regreso su indice 
            break;
        }               
    }           
    return [encontro,encontroInd];
}
//Busca Si los elementos estan llenos
function Cuenta_Vacios(maxObj,avion) {       
	//Contador de elementos vacios | Objeto Asiento seleccionado
    var contador=0; var armaObj;     
    for (var i=1; i<=maxObj; i++ ) {   
        armaObj = f$('V' + avion + '_Seat_' + i);          
        if (armaObj.value == "") { contador += 1; }               
    }           
    return [contador];  //Regresa el numero de elemtos vacios ( Asientos )
}
//Cambia la Imagen del asiento que ya se asigno al pasajero
function My_Seat(objseat,imagen) {
    var ruta_imagen = (typeof document.getElementById('Ruta_Imagen') != 'undefined' && document.getElementById('Ruta_Imagen')!=null) ? document.getElementById('Ruta_Imagen').value : '/_lib/images/bestday';  //Ruta de Imagen segun el sitio
  objseat.src =  ruta_imagen + '/'  +  imagen;                     //Cambio la imagen del asiento asignado
}
//Valida que se haya capturado los datos obligatorios de los Pasajeros
function ValidatePassengers(maxAd,maxni) {
 
  var mensaje;  
  var armaObj;     //Objetos de Datos de Pasajeros  
  var max = maxAd + maxni;
  var error = false;
  var varDicc = 'disMandatoryField';  //variable de datos obligatorios
    
  //Recorro todos los elementos Obligatorios de Datos Personales de Pasajeros
  for (var i=1; i<=max; i++ ) {   
		//Valida (First Name )
		armaObj = f$('first_name_' + i);
		if  (armaObj.value == "") { error= true; varDicc = 'disAlertName'; break; }        
		//Valida (Last Name)
		armaObj = f$('last_name_' + i);
		if (armaObj.value == "") { error = true; varDicc = 'disAlertLastName'; break; }  
		//Valida (Issue country)
		//armaObj = f$('issue_country_' + i);
		//if (armaObj.value == "") { error = true; varDicc = ''; break; }
		//Valida (Fecha de Nacimiento)
		armaObj = f$('day_birthday_' + i);   //Dia de Nacimiento
		if (armaObj.value == "") { error = true; varDicc = 'disDayBirthday'; break; }
		armaObj = f$('month_birthday_' + i); //Mes de Nacimiento
		if (armaObj.value == "") { error = true; varDicc = 'disMonthBirthday'; break; }
		armaObj = f$('year_birthday_' + i);  //Año de Nacimiento
		if (armaObj.value == "") { error = true; varDicc = 'disYearBirthday'; break; }				
		//Valida (Sexo)
		armaObj = f$('gender_' + i);
		if (armaObj.value == "") { error = true; varDicc = 'disGender'; break; }
        
		//Datos Adicionales de Adultos ( contact name - contact phone )
		if (i==1 & maxAd > 0 ) { 
			//Valida ( Contact Name )       
			armaObj = f$('contact_name_' + i);
			if (armaObj.value == "") { error = true; varDicc = 'disEmergencyContactName'; break; }  
			//Valida ( Contact Phone )       
			armaObj = f$('contact_phone_' + i);
			if (armaObj.value == "") { error = true; varDicc = 'disEmergencyContactPhone'; break; }            
			if (!validaPhone(armaObj.value)) {
				error=true;
				Apunta_Pasajeros("si",i,max);
				//Valido el Idioma para mandar el mensaje 
				mensaje = fdic.trad(disTelPasajero,fdic.lang(null));
				alert(mensaje);
				armaObj.focus();
      			return false;      
				break;
			}           
		}
		//Valida las Edades de los Nios
		if (i>maxAd & maxni > 0) {
			//Valida ( Contact Name )       
			armaObj = f$('EdadNino_' + i);
			 //Sibolo "?"  No se capturo nada aun
			if  (armaObj.value == -1) { error= true; varDicc = 'disAlertRates'; break; }
		}        
  }
     
  //Convierte a imagenes sin apuntar
  if (error ==false) { 
	Apunta_Pasajeros("no",1,max);
  } else {      
  
      //Al final mando mensaje de datos faltantes
      Apunta_Pasajeros("si",i,max);
      SendMsgError(varDicc);
      armaObj.focus();
      return false;      
  }
  return true;
}

function SendMsgError(keydicc) {
    var mensaje = '';
    keydicc = (typeof keydicc != 'undefined' && keydicc != null) ? keydicc : '';
    mensaje = fdic.trad(eval(keydicc), fdic.lang(null));
    alert(mensaje);
}

function validaPhone(value) {
  var str =value; // email string
  //var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; // not valid
  //var reg1 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/;  
  var reg1 = /((\(\d{3,4}\)|\d{3,4}-)\d{4,9}(-\d{1,5}|\d{0}))|(\d{7,12})/;
  
  if (!reg1.test(str)) { // if syntax is valid  
    return false;
  }    
  return true;
}

//Apunta a los pasajeros en donde le hace falta algun dato obligatorio
function Apunta_Pasajeros(valida,ind,max) {
    var Ruta_Imagen = (typeof document.getElementById('Ruta_Imagen') != 'undefined' && document.getElementById('Ruta_Imagen')!=null) ? document.getElementById('Ruta_Imagen').value : '/_lib/images/bestday';
  var armaObj;  
  //1=  Cambia de imagen apuntando o No apuntando //0=  No importa y muestra todos sin apuntar  
  //Recorro todos los elementos
  for (var i=1; i<=max; i++ ) {
	armaObj = f$('foco_' + i); 
    if (valida == "si")
		//es el indice que estoy revisando (Indice es Igual= Pongo Imagen Flechita y diferente  = spacer)
        armaObj.src = (ind == i) ? Ruta_Imagen + "/arrowsmall.gif" : Ruta_Imagen + "/spacer.gif";    	        
     else  
		//Vuelo a cambiar a imagen sin apuntar
         armaObj.src = Ruta_Imagen + "/spacer.gif";          
  }
}

//funcion que Pasa el Pais a todos los demas pasajeros que no tenga pais especificado
function LlenaPaisPasajeros(maxpas,ind) {
    var armaObj; var armaObjVal = f$('issue_country' + ind);  //tomo su valor de este objeto
     //Si tiene dato pongo a los demas 
     if (armaObjVal.value != "") {
		for (var i=1; i<=maxpas; i++ ) {
            //Tomo su valor y propago a los demas que no tengan  
            armaObj = f$('issue_country_' + i);
            //Solo a los que no tengan valor 
            if (armaObj.value == "")            
				armaObj.value = armaObjVal.value;  //Le paso su valor a los demas                          
        }
     }    
}
//Pasa la Clave iata del Aeropuerto cuando es Cancun, cabos y vallarta
function pasaCiudad(params) { 
	var objCdad;   var objClvCdad; ////objeto donde tomo su clave | objeto donde paso la clave
	objCdad = eval("document." + params.Forma + "." + params.getValue);   
	objClvCdad = eval("document." + params.Forma + "." + params.setValue); 
	objClvCdad.value = objCdad.value; 	
}

//Pasa el nombre de la ciudad desde combo con Clave nombre
function pasaCodeAirport() {   
    var armaObjLeavingfrom;  //objeto donde tomo su clave
    var armaObjCodeAirport; //objeto donde paso la clave    
    armaObjLeavingfrom = f$('Leavingfrom');               //objeto clav_ciudad (destino)    
    armaObjCodeAirport = f$('CodeAirport');               //objeto ciudades (origen)       
    armaObjCodeAirport.value = armaObjLeavingfrom.value;    //Si es Combo Leaving from tomo  value = Clave  Text = Nombre del aeropuerto
}

//obj.-  Objeto que recibe el foco
//descripcion:  Descripcion de Inicio  "City Name..."   dif
//mandatory:  
//			True :  (Ajax toma el primer elemento de la lista)
//			False:  (Tomo la descripcion de Inicio y limpio clave hidden )

var descripcionGral = ''; var mandatory = true;
function ClearField(Obj,descripcion,pmandatory,limpiar) { 
	if (limpiar == true) {
		Obj.value = descripcion; 
	} else {
		descripcionGral = descripcion;  //Descripcion de Inicio 	
		mandatory = (pmandatory != null && typeof pmandatory == "boolean" ) ? pmandatory: true;  //Por default es obligatorio
		var descObj = Obj.value;
		///if ((Cadena == "City Name or Airport Code") || (Cadena == "Teclee el nombre de la ciudad  codigo del Aeropuerto")) {     
		if (descObj == descripcion) {
			Obj.value="";         
		} else {
			Obj.focus(); Obj.select();
		}
     }
}

//Mueve a la posicion el elemento que le pacen..
//objMove: Objeto que se mueve
//objPos : Objeto donde quiero que se posicione "objMove"
//alignType: 
//		[elem]	 .- Posicion en base al objeto
//		[screen] .- Posicion en base a la pantalla
//align:  Alineado Izquierda, Derecha, Arriba, Abajo, centro
//addLeft:  Valor que agrega posicion Izquerda
//addTop :  Valor que agrega al Tope de la posicion 
function setPositionElement(objPos,objMove,alignType,align,addLeft,addTop) {  
   
    objPos = (typeof Tmpobj     != null && typeof Tmpobj     != "undefined") ? Tmpobj : objPos;         //Tomo del Global
    objMove= (typeof Tmpmoveobj != null && typeof Tmpmoveobj != "undefined") ? Tmpmoveobj : objMove; //Toma de los Globales
    
    objPos  = f$(objPos);  //tomo id 
    objMove = f$(objMove);  //tomo id o elemento a mover
    alignType = (alignType != null) ? alignType : "";
    
    //Obtengo valores adicionales
    addLeft = (typeof addLeft =="number") ?  parseInt(addLeft) : 0;
    addTop  = (typeof addTop  =="number") ?  parseInt(addTop)  : 0;
    
    //Que exista el elemento que se movera
    if (typeof objMove != "undefined") {
	   	var posElementXY; var mLeft = 0; var mTop  = 0;        
        switch (alignType.toLowerCase())
        {
			case "elem":  //X y Y del elemento
				posElementXY = getPositionElement(objPos);  
				mLeft = posElementXY[0]; mTop  = posElementXY[1]; break; 
			case "elem2":  //X y Y del elemento
				posElementXY = getPositionElement(objPos);  var h = 0;
				if (objPos.offsetHeight > 0) {h = objPos.offsetHeight; } else { h = objPos.scrollHeight; }				
				mLeft = posElementXY[0];	mTop  = (posElementXY[1] + h);	
				objMove.style.position = "absolute";  //para que permita moverlo
				break; 	
			case "add":  //X y Y del elemento + adicional
				posElementXY = getPositionElement(objPos);  
				mLeft = (posElementXY[0] + addLeft);	//Posicion Izq + Valor Adicional Izq
				mTop  = (posElementXY[1] + addTop );	//Posicion Top + Valor Adicional Top
				break; 
			case "screen":  //W y H de Pantalla
				posElementXY = getWindowSize();
				var scrollXY = getScrollXY();		 				
				mLeft = ((posElementXY[0] - objMove.clientWidth)  /2) + scrollXY[0];//Left (Mitad de Pantalla)
				mTop  = ((posElementXY[1] - objMove.clientHeight) /2) + scrollXY[1];//Top  (Alto de Pantalla)
				break;
			case "value":  //Tomo los valores que me pasen
				mLeft = addLeft; mTop = addTop;
			default:
				posElementXY = getPositionElement(objPos);  //X y Y Posicion elemento
				mLeft = (posElementXY[0] + objPos.clientWidth ); //Posicion Izq + Valor Ancho Ele
				mTop  = (posElementXY[1] + objPos.clientHeight); //Posicion Izq + Valor Alto Ele
				break;
        }
                        
        //objMove.style.width = objPos.clientWidth;        
	    objMove.style.left = mLeft + "px"; //left del Objeto  
	    objMove.style.top = mTop  + "px";	//Top del Objeto  
	    objMove.style.zIndex = 70;    	
	} 
}

//funcion que mueve html de un contenedor a otro que lo llame
function MoveElemAddOns(forma,objPos,objMove,clasAct,classNew,objs,getValHidden,idimg,imgopen,imgclose) {  
    objPosInsert = f$('B' + objPos);  //Elemento contendero Hijo del que llama para incrustar el html
    objMoveContent = f$(objMove + 'Content');  //HTML que se mueve
    objPapa = objMoveContent.parentNode; //Obtengo el Papa Contenedor del HTML que se mueve
    
    //Obtengo la Ruta de Imagenes
    var rutaImagen = f$('Ruta_Imagen');
    rutaImagen = (typeof rutaImagen != 'undefined' && rutaImagen != null) ? rutaImagen.value : "";
    
    //Obtengo las Imagenes
    imgopen  = (typeof imgopen != 'undefined' && imgopen != null) ? imgopen : "spacer.gif";
    imgclose = (typeof imgclose != 'undefined' && imgclose != null) ? imgclose : "spacer.gif";
        
    //Si es el mismo que lo llamo no hago nada
    if (('b' + objPos.toLowerCase()) == objMoveContent.parentNode.id.toLowerCase())	{		
		return false;
    }
    if (typeof objPosInsert == 'undefined' || objPosInsert == null)	return false;  //saco sin hacer nada		
	if (typeof objMoveContent == 'undefined' || objMoveContent == null) return false;  //saco sin hacer nada			
	var content = '';
	//Si existe el elemento que voy a mover  Saco el HTML de contenedor y muevo a otro contenedor que lo llamo
	if (typeof objPapa != 'undefined' &&  objPapa != null) 
		content = objPapa.innerHTML;    
		
   	//Si tiene contenido lo muevo 
   	if (content != '') { 
   		if (typeof idimg != 'undefined'){
   			var idxAnt = 0;  var idxAct = 0
   			idxAnt = (typeof objPapa.idx !='undefined' && objPapa.idx != null) ? objPapa.idx : 0  //tomo posicion del contenedor
   			idxAct = (typeof objPosInsert.idx !='undefined' && objPosInsert.idx != null) ? objPosInsert.idx : 0  //tomo posicion del contenedor
   			   			
   			if (idxAnt > 0 &&  idxAct > 0) {
   				var _imgAnt =  idimg.replace((idxAct+''),(idxAnt+''));   				
   				DisplayObj(objPapa.id,0);VerMas(objPapa.id,_imgAnt,rutaImagen,imgopen,imgopen); //Posicion de imagen anterior
   			}
			DisplayObj(objPosInsert.id,0); VerMas(objPosInsert.id,idimg,rutaImagen,imgopen,imgclose);
		}
   		objPapa.innerHTML = '';  objPosInsert.innerHTML = content;  //Inserto el html al que llama
   	}
	
	//Tomo el ao actual
	var anioActual = new Date();  anioActual = anioActual.getFullYear();
	
	//Ejecuto Nuevamente el script de Fechas de Calendario
	FechaGet(forma.fechaFrom_pickup,forma.anio_pickup,forma.mes_pickup,forma.dia_pickup);
	FechaGet(forma.fechaTo_dropoff,forma.anio_dropoff,forma.mes_dropoff,forma.dia_dropoff);
	fillMonthsSelect(forma.anio_pickup.value,forma.mes_pickup,forma.dia_pickup, false);
    fillMonthsSelect(forma.anio_dropoff.value,forma.mes_dropoff,forma.dia_dropoff, false);
	CalendarLoad(forma.fechaFrom_pickup,'CalFrom_pickup',''+ anioActual,''+ (anioActual + 1));
	CalendarLoad(forma.fechaTo_dropoff,'CalTo_dropoff',''+ anioActual,''+ (anioActual + 1));

	//Funcion que extrae el valor actual seleccionado de los elementos
	getValuesHidden(forma,objs,getValHidden);
	

	
	
}


//Funcion que revisa que elemento de radios button fue seleccionado
function selectCheck(elem,pos) {	
	//elem.type == "checkbox"
	for (var i=0; i<=elem.length - 1; i++) {
		if (i==pos)
			elem[i].checked = true;  //Selecciona
		else
			elem[i].checked = false; //Deseleccona
	}		
			
}
function selectCheckBox (elem,activo) {
	//puede estar el elemento como hidden   checkbox
	if (elem.type == "checkbox") {
		if (activo)
			elem.checked = true;	
		else
			elem.checked = false;	
	}	
}
function Ocultar_Flash() {    
	var x = document.getElementsByTagName("Object"); 	
	for (i=0;i<x.length;i++) {	    
		x[i].style.visibility= "hidden";
	}
}
function Mostrar_Flash() {
	var x=document.getElementsByTagName("Object");
	for (i=0;i<x.length;i++) {
		x[i].style.visibility= "visible";
	}
}
//funcion que muestra la descripcion de la Categoria seleccionada (Lista de Hoteles)
function ttCategory(_id,clvCat,nombCat,colorBor,evento,RutaImagenes) {
	if (clvCat == '') return;	var idiomaCategoria = 'ING'; var txtCategoria = '';
	if(typeof RutaImagenes=='undefined'){ 		
		RutaImagenes= f$('Ruta_Imagen'); RutaImagenes = (RutaImagenes!=null)? RutaImagenes.value:'';
	}	
	idiomaCategoria = fdic.lang(null);
	//Existe el Array 
	if (typeof(descCateg) != "undefined") txtCategoria = descCateg[clvCat];  //Tomo el valor del arreglo	
	var content = '<div style="font-family:Trebuchet MS, Arial, Helvetica, sans-serif;text-align: left; font-weight: bold; border-bottom: 1px solid ' + colorBor + '; margin: 2px 5px 2px 5px; padding-bottom: 2px; font-size:13px;">';
		content += '<img src="' + RutaImagenes + '/Cat_' + clvCat + '_' + idiomaCategoria + '.gif" border="0" align="absbottom"/>&nbsp;' + nombCat + '</div>';
		content += '<div style="font-family:Trebuchet MS, Arial, Helvetica, sans-serif;text-align: justify; padding: 5px; font-size:10px;">' + txtCategoria + '</div>';		
	tooltip.show(_id,content,0,true,evento,200);
}

var disHide_esp = "Ocultar";  var disHide_ing = "Hide"; var disShow_esp = "Mostrar";  var disShow_ing = "Show"; 
//Si Visible:		Oculto Obj --> con title de Mostrar		
//Si NO Visible:	Muestro Obj --> con title de Ocultar
function VerMas(Iddiv,Idimg,RutaImg,imgShow,imgHide) { 

	var imgObj = f$(Idimg);	//Idimg		-->  Nombre del Id de la Imagen click (Cambia su Title)
	var divObj = f$(Iddiv);	//Iddiv		-->  Nombre del Id del Div Oculta / Muestra
							//imgShow	-->  Nombre de Imagen con Extension Cuando el Objeto esta Visible
							//imgHide	-->  Nombre de Imagen con Extension Cuando el Objeto NO esta Visible
	var title;	var pIdioma	= fdic.lang(null);		
	//Obtengo el Idioma del Sitio	
	if (divObj.style.display == "") {
		//Titulo Imagen Mostrar o Ocultar
		title = (pIdioma.toLowerCase() == "ing") ? disShow_ing : disShow_esp;
		divObj.style.display = "none";			//Oculta el div
		imgObj.title = title;					//Nuevo titulo de la Imagen  
		imgObj.src = RutaImg + '/' + imgShow;	//Imagen Mostrar		
	} else {	
		//Titulo Imagen.- es el Opuesto a la Accion de hizo
		title = (pIdioma.toLowerCase() == "ing") ? disHide_ing : disHide_esp;			
		divObj.style.display = '';		//Muestra el Div
		imgObj.title = title;					//Nuevo titulo de la Imagen  
		imgObj.src = RutaImg + '/' + imgHide;	//Imagen de Ocultar
	}
}
function VerMasSin(Iddiv) { 
	var divObj = f$(Iddiv);	//Iddiv		-->  Nombre del Id del Div Oculta / Muestra
	if (divObj.style.display == "") divObj.style.display = "none";	//Oculta el div  	
	else divObj.style.display = '';									//Muestra el Div
}

var tooltip=function(){	
	var id = 'help'; var top = 5; var left = 5;
	var maxwidth = 300; //Ancho  Maximo del ToolTip
	var minwidth = 150; //Ancho Minimo del ToolTip
	var tt,t,c,b,h;
	var ie = document.all ? true : false; 
	var widthObj = 0;var cad='';
	return{		
		show:function(_id,_textHTML,_width,_hide,evento,_minwidth,_maxwidth){
			//Si NO recibe Texto 
			if (typeof _textHTML =='undefined' || _textHTML ==null || _textHTML == '') return;
			//Trae Nombre ?  Tomo su nombre si No la de dafault
			id = (typeof _id !='undefined' &&  _id !=null) ? _id : id;
			//Valida que ya exista el elemento con ese ID
			if(document.getElementById(id) != null) {
				//Es el mismo Objeto ? Si Borra el documento
				if(tt.id.toLowerCase() != id.toLowerCase()) {
					tt = null;
					document.body.removeChild(document.getElementById(id));
				}
			} else {
				tt = null;
			}
					
			//Valida que la variable tt sea null para crear el elemento
			if(tt == null){
				if(typeof _minwidth != 'undefined') minwidth = _minwidth;
				if(typeof _maxwidth != 'undefined') maxwidth = _maxwidth;
				widthObj = _width;
				tt = document.createElement('div');
				tt.setAttribute('id',id);
				t = document.createElement('div');
				t.setAttribute('id',id + 'top');
				c = document.createElement('div');
				c.setAttribute('id',id + 'cont');
				b = document.createElement('div');
				b.setAttribute('id',id + 'bot');
				tt.appendChild(t); tt.appendChild(c); tt.appendChild(b);
				document.body.appendChild(tt);
			}  
			//tt.style.opacity = 97;
			//tt.style.filter = 'alpha(opacity=97)';
			c.innerHTML = _textHTML;
			tt.style.display = 'block';
			tt.style.width = _width ? _width + 'px' : 'auto';			//Si no hay _width de default toma width=auto
			tt.style.left = (ie ? event.clientX : evento.pageX) + 'px'; //Posicion del evento
			if(tt.offsetWidth > maxwidth){ tt.style.width = maxwidth + 'px'	}
			//Si es caja que se mueve con el mouse
			_hide = (_hide != null  && typeof _hide  == "boolean") ? _hide :  true;
			
			if (_hide) { 
				document.onmousemove = this.pos; 
			} 
			else {
				document.onmousemove = ""; //por click
				tt.style.position = "absolute";
				tooltip.pos(evento);
			}
			//Valida que el objeto este visible, que sea IE y que sea version menor a 7
			if (tt.style.display != "none" && ie && navigator.appVersion.substring(22,25) < 7) Ocultar_Elementos();

		},
		pos:function(e){
			//debugger;
			//scrollTop y scrollLeft: para Doctype HTML usa document.body y para XHTML se usa document.documentElement
			//offsetWidth y offsetHeight: se usa document.documentElement para todo tipo de Doctype
			var u = ie ?  event.clientY + document.body.scrollTop + document.documentElement.scrollTop : e.pageY;
			var l = ie ?  event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft : e.pageX;
			var difHeight = (ie ? (document.body.scrollTop + document.documentElement.scrollTop) : 0) + document.documentElement.offsetHeight - u; 
			//Hay espacio abajo antes de que termina la pagina para que muestre el objeto?			
			if(difHeight < tt.offsetHeight) { 
				//alert('top[u]:' + u + '-deoffsetH:' + document.documentElement.offsetHeight + '- dif:' + difHeight + '-htt:' + tt.offsetHeight + '-top' + top );
				if (u <= tt.offsetHeight) {					
					tt.style.top = ((tt.offsetHeight + (u - tt.offsetHeight)) + top) + 'px'; //Mueve el Objeto hacia Abajo del Posicion del Mouse					
				} else {					
					tt.style.top = (u - tt.offsetHeight - top) + 'px'; //Mueve el Objeto hacia Abajo del Posicion del Mouse
				}
			 }else {
			   tt.style.top = (u + top) + 'px';  //Mueve el Objeto hacia Arriba del Posicion del Mouse
			 }  
			//tt.style.top = (u + top) + 'px'; 					//Mueve el Objeto hacia Abajo de la Posicion del Mouse
			var difWidth = (widthObj != 0 ) ? widthObj : minwidth //Existe ancho minimo?
			if((document.documentElement.offsetWidth - l)  < difWidth) {  	//(Ancho pagina - posicion evento) < ancho del objeto
				tt.style.width = difWidth;
				tt.style.left = ((ie ? event.clientX : e.pageX)) - difWidth - left + 'px';
			}
			else tt.style.left = (l + left) + 'px';
			if(tt.offsetWidth > maxwidth){ tt.style.width = maxwidth + 'px'	} // Tamao maximo del objeto
		},
		hide:function(id){
		   // if(ie==true && typeof busyBox !='undefined') { busyBox.Hide(); }
			var e = f$(id); 
			if(e != null) {	
				// Valida que sea IE y que sea version menor a 7
				if(ie && navigator.appVersion.substring(22,25) < 7) Mostrar_Elementos();
				document.onmousemove = "";
				eval("e.style.display = 'none'");				
			}
		}
	};
}();

/* ------------------------------------------------- */
/* Inicia: Funciones de FILTROS AVANZADOS DE HOTELES */
function uncompressHotels(){
    var _indices_match = new Array();
    if (typeof a_hotels != 'undefined') { 
        for(var i=0;i<a_hotels.length;i++){
		    _indices_match[i] = i;
	    }
    }	
	return _indices_match;
}

//Recibe el arreglo de indeces (indices_match), la posicion del filtro a buscar (posArray) y el id del elemento a buscar
function matchGeneral(indices_match,posArray,tipo,idElemento1,idElemento2) {
	
	var _indices_match = new Array();
	var _array_interno = new Array();
	var _valor1 = new String; _valor1 = "";
	var _valor2 = new String; _valor2 = "";
	var _coincide = new Boolean; _coincide = false;
	var _Obj1 =f$(idElemento1); var _Obj2 =f$(idElemento2);
	
	if (ExistsObj(_Obj1)==true) { _valor1 = _Obj1.value; }
	if (ExistsObj(_Obj2)==true) { _valor2 = _Obj2.value; }		
	
	
	if(tipo == "Entre") { 
		_valor1 = _valor1.split("|")[0];	//Primer valor del split del arreglo grande
		_valor2 = _valor2.split("|")[0];	//		Ej.: 5 de "5|S3"		
	}
	if(tipo == "Entre" && _valor1 == "" && _valor2 != "") _valor1 = "0";			//Ej.: Categorias: Todas hasta _valor2
	if(tipo == "Entre" && _valor2 == "" && _valor1 != "") _valor2 = "9999999999";	//Ej.: Categorias: Desde _valor1 hasta todas
	if(_valor1 != "") { //Tiene valor el primer elemento?
		for(var i=0;i<indices_match.length;i++){ //Recorre el arreglo de indices que cumplen con los filtros anteriores
			_array_interno = a_hotels[indices_match[i]].split("|");
			_coincide = false;
			
			switch (tipo) {
				case "Simple": 	if(_array_interno[posArray].toLowerCase() == _valor1.toLowerCase()) _coincide = true; break;
				case "Comas": 	if(_array_interno[posArray].indexOf(_valor1) >= 0) _coincide = true; break; 
				case "Entre": 	if(parseFloat(_array_interno[posArray]) >= parseFloat(_valor1) && parseFloat(_array_interno[posArray]) <= parseFloat(_valor2)) _coincide = true; break;
			}
			
			if(_coincide == true)
				_indices_match[_indices_match.length] = indices_match[i];	//Agrego al nuevo arreglo de indices
		}
	}	
	else _indices_match = indices_match;
	return _indices_match;
}

function matchCheckBox (indices_match,posArray,idElemento) {
	var _indices_match=new Array();
	var _listCheckBox = f$(idElemento);
	//No existe el elemento lo saco
	if (ExistsObj(_listCheckBox) == false){ return indices_match; }
	var _bits = new String;
	var _listCheckBox= _listCheckBox.getElementsByTagName("input"); //Todos los input dentro del ID recibido
	var _listChecked=new Array();
	var _coincide = new Boolean; _coincide = false;
	var _hiddenValor = "" //Cadena de valores CheckBox seleccionados
	//debugger;
	for(var i=0;i<_listCheckBox.length;i++){ //Obtiene todos los CheckBox dentro del ID recibido
		if(_listCheckBox[i].checked){
			_listChecked[_listChecked.length]=_listCheckBox[i].getAttribute("filter"); //Atributo con el bit que representa
			_hiddenValor += _listCheckBox[i].value + ','; 
		}
	}
	f$(idElemento + 'Buscar').value = _hiddenValor;	//Elemento Hidden
	if(_listChecked.length==0){ //Existen seleccionados?
		return indices_match;
	}
	for(var i=0;i<indices_match.length;i++){ //Recorre el arreglo de indices que cumplen con los filtros anteriores
		_array_interno = a_hotels[indices_match[i]].split("|"); 
		_bits=parseInt(_array_interno[posArray],32).toString(2); //Convierte a bits (base 2) el valor de la BD en base 32
		
		for(var j=0;j<_listChecked.length;j++){ //Recorre la lista con CheckBox seleccionado
			if(_bits.charAt(_bits.length-1-_listChecked[j])=="1") _coincide=true; 	//Tiene 1 en el bit que indica el CheckBox?
			else { _coincide=false;j=_listChecked.length; }							//No coinciden
		}
		if(_coincide)
			_indices_match[_indices_match.length] = indices_match[i];	//Agrego al nuevo arreglo de indices
	}
	return _indices_match;
}


//funcion para mostrar la caja de filtros avanzados de la lista de hoteles desde la carga inicial de la pagina
function inicioFiltros(Iddiv,Idimg,RutaImg,imgShow,imgHide) {
	revisaFiltros();
	VerMas(Iddiv,Idimg,RutaImg,imgShow,imgHide);
}

function revisaFiltros(Filtro_CLKH) {
	//indices_match: arreglo con los indices de a_hotels que cumplen con los filtros
	var indices_match = uncompressHotels();
	indices_match = (indices_match.length > 0) ? matchGeneral(indices_match,1,"Simple","fLocation") : "";			//Ubicacion
	indices_match = (indices_match.length > 0) ? matchGeneral(indices_match,2,"Simple","fCiudad") : "";				//Ciudad
	indices_match = (indices_match.length > 0) ? matchGeneral(indices_match,3,"Simple","fCadena") : "";				//Cadena
	indices_match = (indices_match.length > 0) ? matchGeneral(indices_match,4,"Comas","fPlan") : "";					//Planes
	if(Filtro_CLKH == 1)
	{
        indices_match = (indices_match.length > 0) ? matchGeneral(indices_match,5,"Entre","CatDesde","CatHasta") : "";	//Categoria
		indices_match = (indices_match.length > 0) ? matchGeneral(indices_match,6,"Entre","preciode","preciohasta") : "";	//Tarifa
		indices_match = (indices_match.length > 0) ? matchGeneral(indices_match,8,"Entre","ratede","ratehasta") : "";	//Calificacion
		
		/* indices_match = (indices_match.length > 0) ? matchGeneral(indices_match,8,"Entre","ratede","ratehasta") : ""; */	//Tarifa
	}else{
        indices_match = (indices_match.length > 0) ? matchGeneral(indices_match,5,"Entre","fCatDesde","fCatHasta") : "";	//Categoria
		indices_match = (indices_match.length > 0) ? matchGeneral(indices_match,6,"Entre","fPrecioDe","fPrecioHasta") : "";	//Tarifa   
	}
	
	indices_match = (indices_match.length > 0) ? matchCheckBox(indices_match,7,"fTemas") : "";				//Temas en base 32

	
	/*Corregir en los nuevos filtros*/
	var element  = 	document.forms['frmFilters'].getElementsByTagName("input");
	for (var i=0;  i<element.length; i++) {
		if (element[i].name.toLowerCase() =='submit') {		
			if (indices_match.length <=0)
				element[i].style.display = 'none';	 //desactiva		
			else
				element[i].style.display = ''; //activa
		}
	}
	var _Obj = f$("TotalFiltros"); 
	if (ExistsObj(_Obj)==true) { _Obj.innerHTML = indices_match.length; }
}
/* Fin: Funciones de FILTROS AVANZADOS DE HOTELES */
/* ---------------------------------------------- */


function ExtraeValores (tour,cboservicio,cbociudad,cbohorario,arrCiudades,arrHorarios,defciudad,defhora,pos) { 
	var arra = arrCiudades; LimpiaCombo(cbociudad); var j= 0;
	
	if (typeof arrCiudades == "undefined" && arrCiudades == null) 
		arrCiudades = '';
	
	if (typeof arrHorarios == "undefined" && arrHorarios == null) 
		arrHorarios = '';	
	
	var primera = true;
	for (var i=0;  i<arra.length; i++) {	
		var arraVal = new Array(); arraVal = arra[i].split("|"); var obj;	
		if (arraVal != null){
	   		if (typeof arraVal[0] != "undefined" && arraVal[0] != null) //Clave de Tour
				if (typeof arraVal[1] != "undefined" &&  arraVal[1] != null) //Clave de Servicio
					if (typeof arraVal[2] != "undefined" && arraVal[2] != null) //Clave Ciudad
						if (typeof arraVal[3] != "undefined" && arraVal[3] != null) { //nombre de ciudad
							//Es el mismo Tour y Servicio
							if (parseInt(arraVal[0]) == parseInt(tour) && parseInt(arraVal[1]) == parseInt(cboservicio) && (arraVal[3]+'')!= '') 
							{
								if (defciudad == arraVal[2]) {
									cbociudad.options[j] = new Option(arraVal[3], arraVal[2],true,true); //seleccionado	
								}else{
									//Si viene vacio por default selecciono el primero
									if (primera && defciudad =='') {
										cbociudad.options[j] = new Option(arraVal[3], arraVal[2],true,true);	//seleccionado
										primera = false;
									} else {
										cbociudad.options[j] = new Option(arraVal[3], arraVal[2],false,false);	//No seleccionado
									}
								}
								//Oculto Combo de Ciudade y titulo				
								if (cbociudad.value == "NOCIUDAD") {						
									eval("document.getElementById('SaliendoDe" + pos + "').style.display='none'");
									eval("document.getElementById('SaliendoDeTxt" + pos + "').style.display='none'");
								}else{
									eval("document.getElementById('SaliendoDe" + pos + "').style.display=''");
									eval("document.getElementById('SaliendoDeTxt" + pos +"').style.display=''");
								}
								j+=1; //Incremento de Opciones Reales										
							}	
						}	   
		}
				
	}
	//Cargo Horarios	
	var arraH = arrHorarios; LimpiaCombo(cbohorario); primera = true; j=0;
	//Barro los Valores
	for (var i=0;  i<arraH.length; i++) {
		var arraValH = new Array();		
		arraValH = arraH[i].split("|");		
		
		if (arraValH != null) {
		   //tomo la Clave del tour
		   if (typeof arraValH[0] != "undefined" && arraValH[0] != null) //Clave de Tour
	         if (typeof arraValH[1] != "undefined" && arraValH[1] !=null) //Clave de Servicio
				if (typeof arraValH[2] != "undefined" && arraValH[2] != null) { //Hora

					//Es el mismo Tour y Servicio y no viene vacio o cero							
					if (parseInt(arraValH[0]) == parseInt(tour) && parseInt(arraValH[1]) == parseInt(cboservicio) && (arraValH[2]+'') != '0') 
					{										
					
						//Es la misma hora seleccionada
						if (defhora == arraValH[2]) {						
							cbohorario.options[j] = new Option(arraValH[2], arraValH[2],true,true); //seleccionado						
						}else{										
							if (primera && defhora == ""){							
								cbohorario.options[j] = new Option(arraValH[2], arraValH[2],true,true); //seleccionado
								primera = false;							
							}else {							
								cbohorario.options[j] = new Option(arraValH[2], arraValH[2],false,false); //No seleccionado							
							}
						}
						j+=1; //Incremento de Opciones Reales
					}
					//Para esconderlo si no trae Valores	
					if (cbohorario.value == "0" || cbohorario.value == "") {
						eval("document.getElementById('elHorario" + pos + "').style.display='none'");
						eval("document.getElementById('elHorarioTxt" + pos + "').style.display='none'");										
					} else {
						eval("document.getElementById('elHorario" + pos + "').style.display=''");
						eval("document.getElementById('elHorarioTxt" + pos + "').style.display=''");
        
					}
					
				}
		}
			
	}
}
//funcion  que limpia los Combos
function LimpiaCombo(combo)	{
	while (combo.options.length > 0) { combo.options[0] = null; }															
}   
//Actualiza Combo de Fecha 
function Fecha_Actual(maxanio,cboanio,cbomes,cbodia) {	
	var myDate = new Date();
	var _CurrentMonth = myDate.getMonth(); var _CurrentYear  = myDate.getFullYear(); var _CurrentDay   = myDate.getDate();
	LimpiaCombo(cboanio);
	//Lleno los aos del combo
	for(var i=0; i<maxanio; i++){
		if (_CurrentYear == _CurrentYear + i)
			cboanio.options[i] = new Option(_CurrentYear + i, _CurrentYear + i ,true,true); //seleccionado	
		else	
			cboanio.options[i] = new Option(_CurrentYear + i, _CurrentYear + i ,false,false); //No seleccionado	
	}
}    

//funcion que valida que no se pongan ciertos caracteres
function validacaracteres(e){
	var idioma =  fdic.lang(null); var mensaje='';
	tecla = (document.all) ? e.keyCode : e.which;	
	if (tecla==8) return true; //espacio	
	//Valor Hexadecimal "7C"  -->  "u00" + "7C"
	//            |          &     ~     ^          %     {          }                                                               
	patron =/[\u007C\u00AC\u0026\u007E\u005E\u00B0\u0025\u007B\u00A8\u007D\u00F1\u00D1\u00E1\u00E9\u00ED\u00F3\u00FA\u00C1\u00C9\u00CD\u00D3\u00DA]/;
	te = String.fromCharCode(tecla);
	if (patron.test(te)){	
		mensaje = fdic.trad(disAlertCaracteresInvalidos,idioma);
		mensaje +="\n";
		mensaje +="\t" + "\u007C, \u00AC, \u0026, \u007E, \u005E, \u00B0, \u0025, \u007B, \u00A8, \u007D, \u00F1, \u00D1, \u00E1, \u00E9, \u00ED, \u00F3, \u00FA, \u00C1, \u00C9, \u00CD, \u00D3, \u00DA ";
		alert(mensaje);
	}
	return !patron.test(te);
} 

//funcion k valida que se pongan numeros
function validanumeros(e){
	tecla = (document.all) ? e.keyCode : e.which; // 2
	if (tecla==8) return true;
	patron =/[0123456789]/;	
	te = String.fromCharCode(tecla);
	return patron.test(te);
}     

//funcion que valida si puse algo para buscar (BUSCADOR DEL SITIO)
function validaSearchSite(elem,idioma) {	
	if (elem.value == '') { 
		alert(fdic.trad(disSearchSite,idioma)); 
		return false;
	}
	return true;	
}
//Cambia el contenido tomandolo de un array. a un elemento (id)
function CambiaContenidoElem(html,idpapa) {
	//Verifico que si se le haya enviado contenido
	if (html == '')
		return false;
	//valido que si exista el elemento			
	var div = f$(idpapa);
	if (typeof div != 'undefined' && div !=null)
		div.innerHTML = html;	
}

function ControlImagenes(Idimg,RutaImg,imgOn,NoImag) { 

	var imgObj = f$(Idimg);	//Idimg		-->  Nombre del Id de la Imagen click (Cambia su Title)
	var Cont=0;
	for(Cont=1;Cont<=NoImag;Cont++) {
		f$( "CtrImagen"+Cont ).src=RutaImg + '/icon_products' + Cont + ".png";
	}
    imgObj.src = RutaImg + '/' + imgOn;
}
function start_Int(NameFuncion,Tiempo) { 
	IntId=window.setInterval(NameFuncion,Tiempo);
}        
function stop_Int(){ 
	window.clearInterval(IntId);
} 
// Dos bloques que tienen en comn un link que los muestra u oculta
function VerMasTexto (bloque1, texto1, bloque2, texto2, idTexto) {
	// Bloque1 
	if(f$(idTexto).innerHTML==texto1) {
		f$(idTexto).innerHTML = texto2; DisplayObj(bloque1,0); DisplayObj(bloque2,1);
	} else {
		f$(idTexto).innerHTML = texto1; DisplayObj(bloque2,0); DisplayObj(bloque1,1);
	}
}
// Cambia de estado de un tab a seleccionado
function SelectTab(MyId) {
	   	var li;
		for(var i=1;i<=6;i++){
		 	//li= f$('Tab' + i);  
			f$('Tab' + i).className = "";
		}		 
		li= f$(MyId);
		if (typeof li != 'undefined' && li !=null)
			li.className = "seleccionado";	
}

// Mandar cookies de un dominio a otro para Google Analytics
// [tipo] = L (Link) o F (Formulario)
// Si es "L" [valor] = Ruta   ----    Si es "F" [valor] = EL formulario (this)
function pageTrackerGoogle(tipo, valor) {    
    if (tipo == null || typeof tipo == 'undefined') { tipo = 'F' }   
    if (tipo.toUpperCase() == "L") {
        if (typeof _gaq != 'undefined') _gaq.push(['_link', valor]);
        return false;
    } else {
        if (typeof _gaq != 'undefined') _gaq.push(['_linkByPost', valor]);
        return true;
    }    	
}

// Funcion que manda eventos a Google Analytics
//  [Brinca] = poner href
//	[Category], [Action] = Son obligatorios
//	[Label] = no es obligatorio
//	[Value]	= Numerico
function GoogleAnalyticsEventos(Brinca, Category, Action, Label, Value) {

    if (typeof _gaq != 'undefined') {
        theCategory = "'" + Category;
        theAction = "', '" + Action + "'";
        theLabel = (Label == null || Label == "") ? "" : ", '" + Label + "'";
        theValue = (Value == null || Value == "") ? "" : ", " + Value;
        eval("_gaq.push(['_trackEvent', " + theCategory + theAction + theLabel + theValue + "])");
    }	
	if(Brinca != "") location.href = Brinca;
}

// Obtiene valores de un formulario y manda un evento a Google Analytics
// 	[]
//objs =  
function GoogleAnalytics(numpagina,sorts,orden,pos,url) {
	GoogleAnalyticsEventos("", "Lista Hoteles", "Pag " + numpagina + ", Orden " + orden + ", Sort " + sorts, url, pos);
}
//funcion regresa datos del navegador
function getNavigator(tipoNav){
	var nav = navigator;
	
	var _browser = [{subString: "MSIE",		identity: "Explorer"},	{subString: "Firefox",	identity: "Firefox"},
					{subString: "Chrome",	identity: "Chrome"},	{subString: "Apple",	identity: "Safari"}
				   ];
	
	var numVersion=0;
	var jsEnabled= nav.javaEnabled();	
	return {CodeName:nav.appCodeName,Name:nav.appName,Version:nav.appVersion,NVersion:numVersion,UserAgent:nav.userAgent,Lang:nav.userLanguage,JavaEnabled:jsEnabled};
}
function ConvertHTMLCode(cad,cambiar){
	var cadHtml='';
	try {
		var valASCCode=0;	
		//var _chr[10,10]=new Array({225,'&aacute;'},{233,'&eacute;'},{237,'&iacute;'},{243,'&oacute;'},{250,'&uacute;'});
		var _chr = new Array();
		if (cambiar){
			_chr[225]='a'; _chr[233]='e'; _chr[237]='i'; _chr[243]='o';	_chr[250]='u';			
		}else {
			_chr[225]='&aacute;'; _chr[233]='&eacute;'; _chr[237]='&iacute;'; _chr[243]='&oacute;';	_chr[250]='&uacute;';
		}		
		for(var x=0;x<cad.length;x++){
			valASCCode = cad.charCodeAt(x);	
			if (typeof _chr[valASCCode]!='undefined'){ 
				cadHtml +=  _chr[valASCCode];
			} else {
				cadHtml += String.fromCharCode(valASCCode);
			}		
		}
	}
	catch(ex){
		cadHtml = cad;
	}	
	return [cad,cadHtml];
}
//Funcion para obtener parametros de la URL del Navegador
function ObtieneParametros(name)
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if(results == null) return "";
  else return results[1];
}  

// Funcion para crear un anuncio RichMedia de AdManager
function AnuncioRichMedia(TipoArchivo,NombreArchivo,Width,Height,Url,FlashVars,SlotName,anio_desde,mes_desde,dia_desde,anio_hasta,mes_hasta,dia_hasta)
{
	if(ObtieneParametros('asoc')!='' && Url!='' ) {
			//Url=Url+ ((Url.indexOf('?')<0)? '?asoc='+ObtieneParametros('asoc'):'&asoc='+ObtieneParametros('asoc'));
             Url=Url+ ((Url.slice(Url.indexOf('?') + 1).indexOf('?')<0)? '?asoc='+ObtieneParametros('asoc'):'&asoc='+ObtieneParametros('asoc'));
			 
	}
	
	Url=Url.replace('mysite',document.location.hostname)

 	if(TipoArchivo=='imagen')
	{	if(Url!='')
		{
			if(anio_desde=='' || anio_desde==undefined)
			  { document.write('<a id="AdImage-'+SlotName+'" href="'+Url+'"><img src="'+NombreArchivo+'"  style="border-width: 0px;"></a>');
			  }
			else{  
			  document.write('<a  id="AdImage-'+SlotName+'" onclick="javascript:SubmitForm(document.forma'+SlotName+', \'\',\'\',\'\');"><img class="cur" src="'+NombreArchivo+'"  style="border-width: 0px;"></a>'+
							'<form style="margin: 0px;" action="'+Url+'" method="post" name="forma'+SlotName+'">'+
							'<input type="Hidden" value="'+anio_desde+'" name="anio_desde">'+
							'<input type="Hidden" value="'+mes_desde+'"  name="mes_desde">'+
							'<input type="Hidden" value="'+dia_desde+'"  name="dia_desde">'+
							'<input type="Hidden" value="'+anio_hasta+'" name="anio_hasta">'+
							'<input type="Hidden" value="'+mes_hasta+'"  name="mes_hasta">'+
							'<input type="Hidden" value="'+dia_hasta+'"  name="dia_hasta">'+
							'</form>');		
			}
		}
		else
		{document.write('<img src="'+NombreArchivo+'">');}
		
	}else{// si se ha detectado una versin aceptable
			 if (DetectFlashVer(8) == true)
			 {
				 AC_FL_RunContent(                                       
				 'codebase', 'https://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0',             
				 'width', Width,                     
				 'height', Height,                    
				 'src', NombreArchivo.replace('.swf',''),                  
				 'quality', 'high',                  
				 'pluginspage', 'https://www.macromedia.com/go/getflashplayer',      
				 'align', 'middle',                  
				 'play', 'true',                     
				 'loop', 'true',                     
				 'scale', 'noscale',                 
				 'devicefont', 'false',              
				 'id', SlotName,                      
				 'bgcolor', '#e5effa',               
				 'name', SlotName,                    
				 'FlashVars', FlashVars,                    
				 'menu', 'false',
				 'wmode', 'transparent',
				 'allowScriptAccess','sameDomain',   
				 'movie', NombreArchivo.replace('.swf',''),                  
				 'salign', ''                        
				 );                                  
			 }else  //No tiene Flash Player y se le invita a descargarlo del sitio de Adobe
			 {  document.write('<a href=""http://www.macromedia.com/go/getflash/"" target=""_blank"" rel=""nofollow""><img src=""" & miParametro.Sitio_Imagenes & "/Flash_" & miParametro.Sitio_Idioma & ".gif"" border=""0""></a>');                        
			 }
		
		}
}

/* QUITAR AL ACTUAIZAR PIXEL */ 

/* MENU TELEFONOS */

if(typeof $$ == "function"){

/* Validar si existe jQuery */

    $$(document).ready(function() {
       

        var rgn = $$('.tdTitulo');
        var dest_cur = $$('a.cur', rgn).attr('id');
        dest_cur = $$('.contenido[id=' + dest_cur + ']');
        dest_cur.show();

        $$('a', rgn).not('.tdViewAll').click(function() {

            $$('a', rgn).removeClass('cur');
            $$(this).addClass('cur');

            if ($$(this).attr('id') != 'none') {
                dest_cur.hide();
                $$('.contenido[id=' + $$(this).attr('id') + ']').show();
                dest_cur = $$('div[id=' + $$(this).attr('id') + ']');

                /** Eventos Analytics **/
                if (typeof _gaq != 'undefined') {
                    _gaq.push(['_trackEvent', rgn.parent().attr('id'), 'view', $$(this).attr('id')]);
                }
                /**/
            }

            return false;
        });

        /**NUEVO MENU DE DESTINOS POPULARES EN LA PESTAÑA HOTELES**/

        $$('.menu_principal .drop').mouseenter(function() {
			
			var _posicionMenu, _fixOffset, _fixActivo;

           // if ($$('.menu_hoteles').attr('style') == '') {
                var _posicionMenu = $$(this).offset();
                var _fixOffset = $$('.Header').offset();
                var _fixActivo = $$(this).is('.activo') ? 1 : 0;
				
                $$(this).css({
                    position: 'relative'
                });
				
                $$('.menu_principal .menu_hoteles').css({
                    marginLeft: (_posicionMenu.left - _fixOffset.left) - 4 - _fixActivo
                });
           // }

            $$('.menu_principal .menu_hoteles').show();
			if(!jQuery.support.boxModel && $$('.jmap').length > 0){
				$$('.jmap').css('position','fixed');
			}
			

        });

       $$('.link_menu_principal:not(.drop), #logo_bd_mx, .menu_telefonos, .menu_paises, .Navega, #Right, #Left, #ContentAll').mouseover(function() {
            $$('.menu_principal .menu_hoteles').hide();
       });

        var posMenuPaises = function() {
            /** Eventos Analytics **/
            if ($$('.opciones_paises').is(':visible')) {
                if (typeof _gaq != 'undefined') {
                    _gaq.push(['_trackEvent', 'botonSitiosIdioma', 'view']);
                }
            }
            /**/
            if ($$('.menu_paises').length > 0) {
                var _posicionMenu = $$('.menu_paises').offset();
                var _topInfo = $$('.opciones_paises').offset();
                $$('li:odd', $$('.opciones_paises')).css('background', '#FFF');
                $$('.opciones_paises').css({
                    top: _posicionMenu.top + 26,
                    left: _posicionMenu.left - ((parseInt($$('.menu_paises').width()) - parseInt($$('.opciones_paises').width())) * -1) + 50
                    //width: parseInt($$('.menu_paises').width())+50
                });
                $$('.opciones_paises').toggle();
                $$('.menu_paises').toggleClass('desplegado_2');
            }
        }
        if ($$('.menu_paises').length > 0) {
            $$('.menu_paises').click(function() {
                posMenuPaises();
            });
        }
        var posMenuTelefonos = function() {
            /** Eventos Analytics **/
            if ($$('.info_telefonos').is(':visible')) {
                if (typeof _gaq != 'undefined') {
                    _gaq.push(['_trackEvent', 'botonTelefonos', 'view']);
                }
            }
            /**/
            if ($$('.menu_telefonos').length > 0) {
                var _posicionMenu = $$('.menu_telefonos').offset();
                var _topInfo = $$('.info_telefonos').offset();

                $$('.info_telefonos').css({
                    top: _posicionMenu.top + 29,
                    left: _posicionMenu.left - ((parseInt($$('.menu_telefonos').width()) - parseInt($$('.info_telefonos').width())) * -1) + 30
                });

                $$('.info_telefonos').toggle();
                $$('.menu_telefonos').toggleClass('desplegado');

            }
        }
        if ($$('.menu_telefonos').length > 0) {
            $$('.menu_telefonos').click(function() {
                posMenuTelefonos();
            });
        }

        /* AJAX MENSUALIDADES */

        var mensualidades = function() {

            if ($$('.modal_mensualidades').length < 1) {

                /** Eventos Analytics **/
                if (typeof _gaq != 'undefined') {
                    _gaq.push(['_trackEvent', 'botonOpcionesPagos', 'view']);
                }

                /**/

                $$('body').append('<div class="modal_mensualidades"></div><img class="cerrar_modal" src="/_lib/images/bestday/cerrar_overlay.gif"/>');

                $$('.cerrar_modal').css({
                    position: 'absolute',
                    zIndex: '2497',
                    top: ((parseInt($$(window).height())) / 2) + $$(window).scrollTop() - 245,
                    left: (parseInt($$(window).width()) / 2) + (255)
                }).click(function() {
                    $$('.modal_mensualidades').remove();
                    $$(this).remove();
                });

                var hrefSplit = $$('.mensualidades_wide').attr('href').split('/');

                htmlhref = hrefSplit[hrefSplit.length - 1];

                $$('.modal_mensualidades').css({
                    display: 'none',
                    position: 'absolute',
                    top: ((parseInt($$(window).height())) / 2) + $$(window).scrollTop(),
                    left: '50%',
                    width: 600,
                    marginLeft: -300,
                    marginTop: -260,
                    /*backgroundColor: '#f3f7f9',
                    overflow: 'hidden',
                    fontFamily: 'Arial, Helvetica',
                    textAlign: 'left',*/
                    zIndex: '2496'
                }).load('/' + htmlhref, function() {
                    $$(this).fadeIn('fast');
                    $$('.overlay_mensualidades').fadeIn('fast');
                });

            }
            return false;
        }

        if ($$('.modal_mensualidades').length < 1) {
            $$('.mensualidades_wide').click(function() {

                mensualidades();
                return false;
            });
        }

        $$('.mensualidades_wide').live('click', function() {
            mensualidades();
            return false;
        });

        if ($$('.toggle', '.calificacion_usuarios').length > 0) {
            $$('.toggle', '.calificacion_usuarios').click(function() {
                $$(this).parent().next('.detalles-toggle').slideToggle();
                $$(this).parent().parent().parent().next('.detalles-toggle').slideToggle();
                return false;
            });
        }

        /** DESTINOS OFERTAS **/


        $$('textarea[maxlength]').live('keyup change', function() {
            var str = $$(this).val()
            var mx = parseInt($$(this).attr('maxlength'))
            if (str.length > mx) {
                $$(this).val(str.substr(0, mx))
                $$(this).scrollTop(1000);

                return false;
            }
        });

        /**/

        $$('h3:last', $$('.destinosDeals')).css({ 'border': 'none' });

        $$('ul', $$('.destinosDeals')).each(function() {
            $$(this).data('hgt', $$(this).height());
        });

        var firstTimeFlag = true;

        $$('#BoxDer', $$('.destinosDeals')).click(function() {

            /** Eventos Analytics **/

            switch ($$(this).index()) {
                case 0:
                    if (typeof _gaq != 'undefined') {
                        _gaq.push(['_trackEvent', 'menuOfertasDestacadas', 'click', 'playas']);
                    }
                    break;
                case 2:
                    if (typeof _gaq != 'undefined') {
                        _gaq.push(['_trackEvent', 'menuOfertasDestacadas', 'click', 'ciudades']);
                    }
                    break;
                case 3:
                    if (typeof _gaq != 'undefined') {
                        _gaq.push(['_trackEvent', 'menuOfertasDestacadas', 'click', 'masdestinos']);
                    }
                    break;
            }

            /**/

            _nextUl = $$(this).next('ul');

            if (!!firstTimeFlag) {

                firstTimeFlag = false;

                _nextUl.css({
                    height: _nextUl.data('hgt')
                }).slideDown();

            } else {

                if (_nextUl.is(':hidden')) {


                    $$('ul:visible', $$('.destinosDeals')).animate({
                        height: 1
                    }, function() {
                        $$(this).hide();
                        _nextUl.css({
                            height: _nextUl.data('hgt')
                        }).slideDown();

                    });


                } else {
                    _nextUl.animate({
                        height: 1
                    }, function() {
                        $$(this).hide();
                        firstTimeFlag = true;
                    })
                }
            }

        });


        $$('.toggleDet').click(function() {
            $$(this).parents('.descHab').children('.detallesHab').toggle(500);
            return false;
        });

        /**  PROMO HABITACION **/

        $$('.promoCompleta').each(function() {
            if (parseInt($$(this).height()) == 20) {
                $$(this).children('.vPromoCompleta').remove();
            }
        });

        $$('.promoCompleta').each(function(i) {
            $$(this).data('myHgt', $$(this).height()).css('height', '20px');
            $$(this).css({ 'color': '#FF4E00' });
        });

        $$('.vPromoCompleta').click(function() {

            if (parseInt($$(this).parent('.promoCompleta').height()) < $$(this).parent('.promoCompleta').data('myHgt')) {
                $$(this).parent('.promoCompleta').animate({
                    height: $$(this).parent('.promoCompleta').data('myHgt')
                }, 300);
            } else {
                $$(this).parent('.promoCompleta').animate({
                    height: 20
                }, 300);
            }

            return false;

        });


        var tooltip_modal = '<div class="promoModal"></div>';

        $$('.promoTip').click(function(e) {

            _idSpl = this.id.split('_');
            _tip = $$('#promo_' + _idSpl[1]);

            _tipOff = $$(this).offset();
            if ($$('.promoModal').length > 0) {
                $$('.promoModal').remove();
            }

            $$('body').append(tooltip_modal);
            $$('.promoModal').text(_tip.text()).prepend('<div class="cerrar"><img src="/_lib/images/bestday/cerrar_promo.gif"/></div>');

            var tLnegth = _tip.text().length;

            var topFix = 100;

            if (tLnegth < 120) {
                topFix = 50;
            }

            $$('.promoModal').css({
                top: _tipOff.top - topFix,
                left: _tipOff.left - 100
            });


            if ($$('.promoModal').length > 0) {
                if (e.stopPropagation) {
                    e.stopPropagation();
                } else if (window.event) {
                    window.event.cancelBubble = true;
                }
                $$(':not(.promoTip)').live('click', function() {
                    $$('.promoModal').remove();
                    $$(this).die('click');
                });
            }

        });

        /* POLITICAS DE CANCELACION HABITACIONES NUEVAS */

        var getRoomInfo = function(tip, idioma) {
            $$('body').append(tooltip_modal);
            //$$('div',$$('.tooltip')).html('<img src="/_lib/java/jquery/ligthbox-images/lightbox-ico-loading-ESP.gif" />');
            tipOff = tip.offset();
            $$('.promoModal').css({
                left: tipOff.left - 180,
                top: tipOff.top - 300,
                height: 270,
                overflow: 'auto'
            });
            $$('.promoModal').show();
            var toGet = tip.attr('rel'); //Habitación

            if ($$('input[name=IAN_' + toGet + '_cancellationPolicy]').length < 1) { return false; }

            var targetContent = $$('input[name=IAN_' + toGet + '_cancellationPolicy]').val();

            if (targetContent != '') {
                $$('.promoModal').html(targetContent).prepend('<div class="cerrar"><img src="/_lib/images/bestday/cerrar_promo.gif"/></div>'); ;
            }

            $$('.promoModal').live('click', function() {
                $$(this).remove();
            });

            if ($$('.promoModal').length > 0) {
                $$(':not(.promoModal)').live('click', function() {
                    $$('.promoModal').remove();
                    $$(this).die('click');
                });
            }

        }

        if (!!$$('.Info').length) {
            $$('.Info').click(function() {
                getRoomInfo($$(this));
                return false;
            });
        }


        /* Imagenes con zoom */
        var imgDisplay = '<div class="img_display"></div>';
        var galeria_display = function() {
            $$('a[ref=zoom]').live('mouseover',function() {
                if ($$('.img_display').length < 1) {
                    var me = $$(this).offset();
                    $$('body').append(imgDisplay);

                    /* HACER LA CORRECCION PARA CLICKHOTELES:

                    	if ( me.left <= $$('body').width() / 2) {

                    */

                    if (me.left <= $$('body').width()) {
                        $$('.img_display').html('<img src="' + $$(this).attr('rel') + '" />').css({
                            left: me.left + parseInt($$('img', $$(this)).width()) + 5,
                            top: me.top - (parseInt($$('img', $$(this)).height()))
                        });
                    } else {
                        $$('.img_display').html('<img src="' + $$(this).attr('rel') + '" />').css({
                            left: me.left - parseInt($$('.img_display').width()) - 5,
                            top: me.top - (parseInt($$('img', $$(this)).height()))
                        });
                    }
                }
            });
            $$('a[ref=zoom]').live('mouseout',function() {
                $$('.img_display').remove();
            });
            $$('a[ref=zoom]').live('click',function() {
                if (/\#/.test($$(this).attr('href'))) {
                    return false;
                }
            });
        } ();

        (function($$) {
            $$.fn.galeriaPop = function(options) {

                var s = {
                    _debug: false,
                    _thumbs: $$('.thumbs'),
                    _controles: $$('.controles'),
                    _cThumbs: $$('.contenedor_thumbs'),
                    _slider: $$('.thumb_slider'),
                    _moveRate: 1
                };
                if (options) {
                    $$.extend(s, options);
                }
                var _launcher = $$(this);
                var _me = s._gallery;
                var antiSpeed = true;
                var _firstLaunch = true;
                var _error = false;
                var _imgIndex = 0;
                var _firstThumb = $$('a:first', s._cThumbs);
                var _nThumbs = $$('a', s._cThumbs).length;
                var _imgArray = [];

                _me.parent().css({
                    overflow: 'visible'
                });

                $$.fn.galeriaPop.loadImage = function(path) {

                    if (antiSpeed) {

                        antiSpeed = false;
                        if (_firstLaunch) {
                            _animSpeed = 50;
                        } else {
                            _animSpeed = 300;
                        }
                        $$('.pic').animate({
                            opacity: 0
                        }, _animSpeed, function() {

                            var _img = new Image();
                            _img.onload = function() {

                                _fixWidth = ($$.support.cssFloat) ? 0 : 25;
                                _me.animate({
                                    width: _img.width + _fixWidth,
                                    marginLeft: (_img.width / 2) * -1,
                                    marginTop: ((_img.height / 2) + parseInt($$('.pic').parent().css('margin-bottom'))) * -1,
                                    top: '50%',
                                    left: '50%'
                                }, _animSpeed);
                                $$('.pic').animate({
                                    width: _img.width,
                                    height: _img.height
                                }, _animSpeed, function() {
                                    $$(this).attr('src', path);
                                    $$(this).animate({
                                        opacity: 1
                                    }, _animSpeed, function() {
                                        if (s._thumbs.is(':hidden')) {
                                            s._thumbs.fadeIn();
                                            s._controles.fadeIn('fast');
                                        }
                                        if (_me.is(':hidden')) {
                                            _me.fadeIn();
                                        }
                                        antiSpeed = true;
                                        _firstLaunch = false;
                                    });
                                });
                            };
                            $$.ajax({
                                url: path,
                                success: function(data) {
                                    if (data != "" || _img.width == 0) {
                                        _img.src = path;
                                    }
                                },
                                error: function(error) {
                                    _img.src = path;
                                }
                            });
                            $$('.numero').text((_imgIndex + 1) + '/' + _nThumbs);
                            var _caption = $$('a:eq(' + (_imgIndex + 1) + ')').attr('ref');
                            $$('.texto').text(_caption);
                        });
                    }
                }
                return this.each(function() {
                    $$('.cerrar', _me).click(function() {
                        _me.fadeOut();
                    });
                    var _wThumb = parseInt(_firstThumb.width()) + parseInt(_firstThumb.css('margin-right')) + parseInt(_firstThumb.css('border-left-width')) + parseInt(_firstThumb.css('border-right-width'));
                    var _sldWidth = 0;
                    $$('a', s._cThumbs).each(function(i) {
                        _imgArray[i] = $$(this).attr('href');
                        _sldWidth += _wThumb;
                    });
                    s._slider.width(_sldWidth);



                    $$('.control:first', s._controles).click(function() {
                        if (!!_imgIndex) {
                            $$.fn.galeriaPop.loadImage(_imgArray[_imgIndex - 1]);
                            _imgIndex--;
                        }
                    });
                    $$('.control:last', s._controles).click(function() {

                        if (_imgIndex != _nThumbs - 1) {
                            _imgIndex++;
                            $$.fn.galeriaPop.loadImage(_imgArray[_imgIndex]);
                        }

                    });
                    $$('.controlIzq').css({
                        display: function() {
                            if (_imgArray.length < 3) {
                                return 'none'
                            }
                        }
                    }).click(function() {
                        if (s._slider.css('margin-left') == 'auto') {
                            s._slider.css('margin-left', 0);
                        }
                        if (parseInt(s._slider.css('margin-left')) != 0 && antiSpeed) {
                            antiSpeed = false;
                            s._slider.animate({
                                marginLeft: parseInt(s._slider.css('margin-left')) + (_wThumb * s._moveRate)
                            }, 300, function() {
                                antiSpeed = true;
                            });
                        }
                    });
                    $$('.controlDer').css({
                        display: function() {
                            if (_imgArray.length < 3) {
                                return 'none'
                            }
                        }
                    }).click(function() {
                        if (s._slider.css('margin-left') == 'auto') {
                            s._slider.css('margin-left', 0);
                        }
                        if ((parseInt(s._cThumbs.width()) - parseInt(s._slider.width())) < parseInt(s._slider.css('margin-left')) && antiSpeed) {
                            antiSpeed = false;
                            s._slider.animate({
                                marginLeft: parseInt(s._slider.css('margin-left')) - (_wThumb * s._moveRate)
                            }, 300, function() {
                                antiSpeed = true;
                            });
                        }
                    });
                    $$('.thumb', s._slider).click(function(e) {
                        e.preventDefault();
                        _imgIndex = $$(this).index();
                        var _imgPath = $$(this).attr('href');
                        $$.fn.galeriaPop.loadImage(_imgPath);
                    });
                    _launcher.click(function() {
                        if (s._gallery.is(':hidden')) {
                            $$.fn.galeriaPop.loadImage(_firstThumb.attr('href'));
                        }
                        return false;
                    });
                });
            }
        })(jQuery);

        $$(document).ready(function() {
            $$('.launch').galeriaPop({
                _gallery: $$('.galeriaPlug'),
                _debug: false,
                _moveRate: 1
            });
        });

        $$('.toggleShutDet').click(function() {
            $$(this).next('.tarifasShuttleMoreInfo').toggle('slow');
            return false;
        });
        $$('.toggleFullInfo').click(function() {
            $$('.shuttleIntroTxt').next('.shuttleTxt').toggle('slow');
            return false;
        });

        /** NUEVOS DESTINOS HOME **/

        $$('.link_pais').show().not('.mas_destinos').click(function() {
            var _me = $$(this);
            var _bloques_destinos_top = _me.attr('href');

            $$('.bloques_destinos_top').hide();
            $$('div' + _bloques_destinos_top, $$('.top_destinos')).show();

            $$('.link_pais').removeClass('pais_activo');

            _me.addClass('pais_activo');
            $$('.v', $$('.top_destinos')).appendTo(_me);
            return false;
        });

        $$('.bloques_destinos_top:first').show();

        $$('.top_destinos .v').css({ display: 'block' });

        var _fixPaises = jQuery.support.boxModel ? '5px' : '7px';

        $$('.link_pais:first').css({
            marginLeft: _fixPaises,
            borderLeft: '1px solid #E5E5E5'
        });
        $$('.link_pais:last').css({
            borderRight: '1px solid #E5E5E5'
        });


    });
	
	
		/*function addvaluesForm(form,valoresJSON)
		{
	
		    var parentForm = $$('form[name="'+form+'"]');
	
			  $$.each(valoresJSON, function(key, val) {
					$$('input[name="'+key+'"]',parentForm).attr("value",val);
			  });
			  
		}*/
		
		
		function addvaluesForm(form,parametros,valores)
		{
			var params=parametros.split(",");
			var values=valores.split(",");
			
			if (params.length==values.length)
			{
				var parentForm = $$('form[name="'+form+'"]');
				for(var i=0; i<=params.length;i++){
						$$('input[name="'+params[i]+'"]',parentForm).attr("value",values[i]);
				}
			}
		}
		
		
		
}

