//AB Testing de VuelosRevancha y HotelesRevancha separados
var flowRevancha = new Array();
flowRevancha['h'] = false;
flowRevancha['v'] = false;
if(vPais != 10)
{
   var defaultValueOrigenCorto = "Escriba la Ciudad";
   var defaultValueOrigen;
   var defaultTextOrigen;
   var defaultValueDestino = "";
   var defaultTextDestino = "Escriba la ciudad de destino";
}
else
{
   var defaultValueOrigenCorto = "Digite a cidade";
   var defaultValueOrigen;
   var defaultTextOrigen;
   var defaultValueDestino = "";
   var defaultTextDestino = "Escreva a cidade de destino";
}
switch(vPais)
{
	case 1:
		flowRevancha['h'] = aleatorio(0, 9) <= 6;
		defaultValueOrigen = sDefaultValueOrigen;
		defaultTextOrigen = sDefaultTextOrigen;
		break;
	case 2:
	    flowRevancha['h'] = aleatorio(0, 9) <= 6;
	    defaultValueOrigen = "";
		defaultTextOrigen = "Escriba la ciudad de partida";
		break;
	case 5:
	    flowRevancha['h'] = aleatorio(0, 9) <= 6;
	    defaultValueOrigen = "MVD";
		defaultTextOrigen = "Montevideo (Carrasco), Uruguay";
		break;
	case 6:
		flowRevancha['h'] = aleatorio(0, 9) <= 9;
		flowRevancha['v'] = aleatorio(0, 9) < 3;
		defaultValueOrigen = "SCL";
		defaultTextOrigen = "Santiago de Chile, Chile";
		break;
	case 7:
	    flowRevancha['h'] = aleatorio(0, 9) <= 6;
	    defaultValueOrigen = "LIM";
		defaultTextOrigen = "Lima, Perú";
		break;
	case 9:
	    flowRevancha['h'] = aleatorio(0, 9) <= 6;
	    defaultValueOrigen = sDefaultValueOrigen;
        defaultTextOrigen = sDefaultTextOrigen;
		break;
	case 10:
		defaultValueOrigen = "SAO";
		defaultTextOrigen = "São Paulo";
		break;
case 82:
        flowRevancha['h'] = aleatorio(0, 9) <= 6;	
		defaultValueOrigen = "CCS";
		defaultTextOrigen = "Caracas, Venezuela";
		break;
case 86:
        flowRevancha['h'] = aleatorio(0, 9) <= 6;
		defaultValueOrigen = sDefaultValueOrigen;
		defaultTextOrigen = sDefaultTextOrigen;
		break;
	default:
		defaultValueOrigen = "Escriba la ciudad de partida";
		defaultTextOrigen = "Escriba la ciudad de partida";
		break;
}
function aleatorio(inferior, superior) {
    numPosibilidades = superior - inferior;
    aleat = Math.random() * numPosibilidades;
    aleat = Math.round(aleat);
    return parseInt(inferior) + aleat;
}
function setPasajeros(cantHabitaciones,oBuscador)
{
   //inicializo IDs
   var idADT = "txtBHVH";
   var idCNN = "txtBHVB";
   var idEdades = "txtBHVHY";
   //Auxiliares
   var adt;
   var cnnQuantity;
   var aEdades = new Array();
   for (i=1;i<=cantHabitaciones;i++)
   {
         adt = gValue(idADT + i);
         cnnQuantity = gValue(idCNN + i);
         aEdades = new Array();
         for (j=1;j<=cnnQuantity;j++)
         {
            aEdades[eval(j-1)] = gValue(idEdades + i + j);
         }
         oBuscador.addPaxGroup(adt,aEdades);
   }
}

//Abre los combos de edades segun la cantidad de niños seleccionado
function mostrarEdades(idCombo)
{
   var combo = gObject(idCombo);

   var Quantity  = combo.value;
      var numero = idCombo.substr(7,8);
      var target = "edadesNinios" + numero;
      var TargetDiv = gObject(target);
      TargetDiv.innerHTML = "";
      for (i=0;i<Quantity;i++)
      {
         if ((i==0) && (numero==1)){
         var title = document.createElement("span");
         if (vPais ==10)
         {
         title.innerHTML = "Idade";
         }
         else
         {title.innerHTML = "Edades";}

         var subTitle = document.createElement("span");
         subTitle.className = "message";
         if (vPais ==10)
         {
         subTitle.innerHTML = "(anos)";;
         }
         else
         {subTitle.innerHTML = "(años)";}


         var auxBR = document.createElement("br");
			var auxBR2 = document.createElement("br");
         TargetDiv.appendChild(title);
         TargetDiv.appendChild(auxBR);
         TargetDiv.appendChild(subTitle);
			TargetDiv.appendChild(auxBR2);
         }
         var select = document.createElement("select");
         select.id ="txtBHVHY" + numero + (i+1);
         for (j=0;j<12;j++)
         {
            var option = document.createElement("option");
            option.value = j;
            option.innerHTML = j;
            select.appendChild(option);
         }
         TargetDiv.appendChild(select);
      }
      TargetDiv.style.display = "block";

}

//abre los combos de pasajeros segun la cantidad de habitaciones.
function mostrarCuartos(idCombo)
{
   var combo = gObject(idCombo);

   var Quantity  = combo.value;
   for(z=1;z<= Quantity;z++)
   {
   document.getElementById("PasajerosH" + z ).style.display = "block";
   }
   for (i=1;i<=Quantity;i++)
   {
      var Target = gObject("PasajerosH" + i + "Interno");

      if (Target.innerHTML == "")
      {
         var containerADT = document.createElement("div");
         containerADT.className = "comboAdultosContainer";
         containerADT.id = "comboAdultosContainer" + i;
         var containerParrafoADT = document.createElement("p");
         var selectADT = document.createElement("select");
         selectADT.id ="txtBHVH" + i;
         for(j=1;j<8;j++)
         {
            var option = document.createElement("option");
            option.value = j;
            option.innerHTML = j;
            selectADT.appendChild(option);
         }
         containerParrafoADT.appendChild(selectADT);
         containerADT.appendChild(containerParrafoADT);
         Target.appendChild(containerADT);
         var containerCNN = document.createElement("div");
         containerCNN.className = "comboNinosContainer";
         var containerParrafoCNN = document.createElement("p");
         var selectCNN = document.createElement("select");
         selectCNN.id ="txtBHVB" + i;
         for(j=0;j<8;j++)
         {
            var option = document.createElement("option");
            option.value = j;
            option.innerHTML = j;
            selectCNN.appendChild(option);
         }

         var DivEdades = document.createElement("div");
         DivEdades.id = "edadesNinios" + i;
         DivEdades.className ="edadesNinos";
         DivEdades.style.display = "none";
         selectCNN.onchange=function(){mostrarEdades(this.id)};
         containerParrafoCNN.appendChild(selectCNN);
         containerCNN.appendChild(containerParrafoCNN);
         Target.appendChild(containerCNN);
         var DivContainerEdades = document.createElement("div");
         DivContainerEdades.className = "contenedorEdades";
         DivContainerEdades.appendChild(DivEdades);
         Target.appendChild(DivContainerEdades);

      }

   }
   for(i=Quantity;i<7;i++)
   {
      j = i;
      j++;
      var Target = gObject("PasajerosH" + j );
      Target.style.display = "none";
   }

}
function setTipoVuelo(value)
{
      document.getElementById("sTripType").value = value;
		document.getElementById('parrafoFecha2').style.display = "block";
		if(value == "i")
		document.getElementById('parrafoFecha2').style.display = "none";
}





function showCiudadRetiro(value)
{
   if(value)
   {
         document.getElementById("titleDestinoDescripcion").style.display = 'inline';
         document.getElementById("destinoDescripcion").style.display = 'inline';

   }
   else
   {     
		document.getElementById("titleDestinoDescripcion").style.display = 'none';    
		document.getElementById("destinoDescripcion").style.display = 'none';
	}

}


function activarSolapa(sFlow)
{
   //Apago todas las Solapas
   document.getElementById("sFlowVuelos").className = "solapaVOff";
   document.getElementById("sFlowHoteles").className = "solapaHOff";
   document.getElementById("sFlowVuelosHoteles").className = "solapaVHOff";
   document.getElementById("sFlowAutos").className = "solapaAOff";
   document.getElementById("sFlowPaquetes").className = "solapaPOff";
   switch(sFlow)
   {
      case "v":
      {  document.getElementById("sFlowVuelos").className = "solapaVOn";}
      break;
      case "h":
      {  document.getElementById("sFlowHoteles").className = "solapaHOn";}
      break;
      case "vh":
      {document.getElementById("sFlowVuelosHoteles").className = "solapaVHOn";}
      break;
      case "a":
      {document.getElementById("sFlowAutos").className = "solapaAOn";}
      break;
      case "p":
      {  document.getElementById("sFlowPaquetes").className = "solapaPOn";}
      break;

   }
	
}
function setTipoProducto(value)
{
		switch(value)
		{
			case "v":
			{
				document.getElementById("solapaContainer").className = "tabVuelos";
				activarSolapa(value);
				document.getElementById("opcionesAvanzadas").href = "/busqueda/vuelos/busquedavuelos.aspx";
				document.getElementById("origenDescripcion").value = defaultTextOrigen;
				document.getElementById("origen").value = defaultValueOrigen;


            if (vPais == 10)
            {
               //TEXTO EN PORTUGUES
               document.getElementById("titleOrigenDescripcion").innerHTML = "Cidade de origem";
               document.getElementById("titleDestinoDescripcion").innerHTML = "Cidade de Destino";
               document.getElementById("titleFecha1").innerHTML = "Data de Ida";
               document.getElementById("titleFecha2").innerHTML = "Data de Volta";
            }
            else
            {


               document.getElementById("titleOrigenDescripcion").innerHTML = "Ciudad de origen";
               document.getElementById("titleDestinoDescripcion").innerHTML = "Ciudad de destino";
               document.getElementById("titleFecha1").innerHTML = "Fecha de Salida";
               document.getElementById("titleFecha2").innerHTML = "Fecha de Regreso";
            }

            if (document.getElementById("sTripTypeI").checked)
            {
               document.getElementById("sTripType").value = "iv";
            }
            else
            {
               document.getElementById("sTripType").value = "i";
            }
            globalac.flights.buscadorVuelosDescripcionDestinationLocation1.searchType = "vue";
         }
         break;
         case "p":
         {
            document.getElementById("solapaContainer").className = "tabPaquetes";
            if (document.getElementById("txtBHVH1").value < 2)
            {
               document.getElementById("txtBHVH1").value = 2;
            };
            activarSolapa(value);
            if (vPais == 10)
            {

               document.getElementById("titleOrigenDescripcion").innerHTML = "Cidade de origem";
               document.getElementById("titleDestinoDescripcion").innerHTML = "Cidade de destino";
               document.getElementById("titleFecha1").innerHTML = "Posso partir entre";
               document.getElementById("titleFecha2").innerHTML = "e";
            }
            else
            {


               document.getElementById("titleOrigenDescripcion").innerHTML = "Ciudad de origen";
               document.getElementById("titleDestinoDescripcion").innerHTML = "Ciudad de destino";
               document.getElementById("titleFecha1").innerHTML = "Puedo partir entre";
               document.getElementById("titleFecha2").innerHTML = "y el";
            }
         }
         break;













         case "h":
         {
            document.getElementById("opcionesAvanzadas").href = "/paginas/hoteles/busquedahoteles.asp?ep=a";
            document.getElementById("origenDescripcion").value = defaultTextOrigen;
            document.getElementById("origen").value = defaultValueOrigen;
            if (document.getElementById("txtBHVH1").value < 2)
            {
               document.getElementById("txtBHVH1").value = 2;
            };
            if (vPais == 10)
            {
               //Texto en Portugues
               document.getElementById("titleDestinoDescripcion").innerHTML = "Em que cidade deseja ficar?";
               document.getElementById("titleFecha1").innerHTML = "Data de entrada (check-in)";
               document.getElementById("titleFecha2").innerHTML = "Data de saída (check-out)";

            }
            else
            {
               document.getElementById("titleDestinoDescripcion").innerHTML = "¿En que ciudad desea alojarse?";
               document.getElementById("titleFecha1").innerHTML = "Fecha de entrada (check-in)";
               document.getElementById("titleFecha2").innerHTML = "Fecha de salida (check-out)";
            }
            document.getElementById("solapaContainer").className = "tabHoteles";
            activarSolapa(value);
            document.getElementById("sTripType").value = value;
            globalac.flights.buscadorVuelosDescripcionDestinationLocation1.searchType = "hot";
         }
         break;








         case "a":
         {
            document.getElementById("opcionesAvanzadas").href = "/paginas/autos/busquedaautos.asp?ep=a";
            document.getElementById("origenDescripcion").value = defaultTextDestino;
            document.getElementById("origen").value = defaultValueDestino;
            if (vPais == 10)
            {
                  //Texto en Portugues
                  document.getElementById("titleOrigenDescripcion").innerHTML = "Cidade onde retira o carro";
                  document.getElementById("titleDestinoDescripcion").innerHTML = "Cidade onde devolve o carro";
                  document.getElementById("titleFecha1").innerHTML = "Data de retirada";
                  document.getElementById("titleFecha2").innerHTML = "Data de devolução";

            }
            else
            {
                  document.getElementById("titleOrigenDescripcion").innerHTML = "Ciudad donde retira";
                  document.getElementById("titleDestinoDescripcion").innerHTML = "Ciudad donde entrega";
                  document.getElementById("titleFecha1").innerHTML = "Fecha de retiro";
                  document.getElementById("titleFecha2").innerHTML = "Fecha de devolucion";
            }
            document.getElementById("solapaContainer").className = "tabAutos";
            activarSolapa(value);
            document.getElementById("sTripType").value = "mismaderetiro";
         }

         break;









         case "vh":
         {

            document.getElementById("solapaContainer").className = "tabVuelosHoteles";
            activarSolapa(value);
            document.getElementById("origenDescripcion").value = defaultTextOrigen;
            document.getElementById("origen").value = defaultValueOrigen;
            if (vPais == 10)
            {
               //TEXTO EN PORTUGUES
               document.getElementById("titleOrigenDescripcion").innerHTML = "Cidade de origem";
               document.getElementById("titleDestinoDescripcion").innerHTML = "Cidade de destino";
               document.getElementById("titleFecha1").innerHTML = "Data de Ida";
               document.getElementById("titleFecha2").innerHTML = "Data de Volta";
            }
            else
            {
               document.getElementById("titleOrigenDescripcion").innerHTML = "Ciudad de origen";
               document.getElementById("titleDestinoDescripcion").innerHTML = "Ciudad de destino";
               document.getElementById("titleFecha1").innerHTML = "Fecha de Salida";
               document.getElementById("titleFecha2").innerHTML = "Fecha de Regreso";
            }
         }
      }
      document.getElementById("sFlow").value = value;
}
   function initParametersReferences(oBuscador)
   {

		oBuscador.vPais = vPais;
		if (document.getElementById("sFlow").value != "p")
		{
			oBuscador.sOrigen = gValue('origen');
			oBuscador.sDescripcionOrigen = gValue('origenDescripcion');
			oBuscador.sDestino = gValue('destino');
			oBuscador.sDescripcionDestino = gValue('destinoDescripcion');
		}
		else
		{
			var oOrigen = document.getElementById('origenPaquetes');
			oBuscador.sOrigen = oOrigen.options[oOrigen.selectedIndex].value;
		   oBuscador.sDescripcionOrigen= oOrigen.options[oOrigen.selectedIndex].text;
			oBuscador.sDestino = gValue('DestinationLocation2Hidden');
			oBuscador.sDescripcionDestino = gValue('descripcionDestinoPaquetes');
		}
		oBuscador.comboDuracionPaq = gValue('buscadorPaquetesEstadia');
		oBuscador.oFechas[0] = gValue('fecha1');
		oBuscador.oFechas[1] = gValue('fecha2');
		oBuscador.sTripType = gValue('sTripType');
		if (document.getElementById('searchHotelsCheckBox') != null)
		{
		oBuscador.sSearchHotels = document.getElementById('searchHotelsCheckBox').checked;
		}
		else 
		{
		oBuscador.sSearchHotels = false;
		}
		
		oBuscador.sFlow = gValue('sFlow');
		oBuscador.TipoDestinoPaq = gValue('TipoDestino');
		oBuscador.MultipleDestinoPaq = gValue('MultipleDestino');
		oBuscador.sPaginaBuscador = "homepagev3";
		var cantHabitaciones = (gValue('Habitaciones') == null) ? 1 : gValue('Habitaciones');
		setPasajeros(cantHabitaciones,oBuscador);
	}
	// devuelve un array con la cantidad de pasajeros y las edades de los niños
	function checkFlow()
	{
		switch(document.getElementById("solapaContainer").className)		
		{
		case "tabVuelos":
		{
			document.getElementById('sFlow').value = 'v';
			if (document.getElementById("sTripTypeI").checked)
				{
					document.getElementById("sTripType").value = "iv";
				}
				else
				{
					document.getElementById("sTripType").value = "i";
				}
		}
		break;
		case "tabVuelosHoteles":
		{
			document.getElementById('sFlow').value = 'vh';
			document.getElementById("sTripType").value = 'iv';
		}
		break;
		case "tabPaquetes":
		{
			document.getElementById('sFlow').value = 'p';
			document.getElementById("sTripType").value = 'p';				
		}
		break;
		case "tabHoteles":
		{
			document.getElementById('sFlow').value = 'h';
				document.getElementById("sTripType").value = 'h';
		}
		break;
		break;
		case "tabAutos":
		{
			document.getElementById('sFlow').value = 'a';
			document.getElementById("sTripType").value = 'mismaderetiro';
		}
		break;
		}
	}



	function Buscando()
	{
		//alert('Buscando.......');
		//document.getElementById("ff").innerHTML = "</form>";
		//document.getElementById("f").innerHTML = "<form method=post  id=formularioevento name=formularioevento action='inc/passthru.php?func=procesa'>";
		//formularioevento.submit();
		//alert(document.getElementById("origen").value); 
		//oBuscador = new Query.SearchBox.Box();
		//var myForm = new Despegar.Form("inc/passthru.php?func=procesa", "POST", "formularioevento", "formularioevento");
		//var myForm = new Despegar.Form("inc/temp.php", "POST", "formularioevento", "formularioevento");
		//alert('pasa 1');

                //var oFields = this.objectSearch.buscar();
                //var size = 0;
                //for (var field in oFields)
                //{
                 //     if (oFields[field] != null)
                 //     {
                 //           this.oForm.addInput(field,field,oFields[field]);
                 //     }
                //}
                //---------------------------POSTEO DEL FORMULARIO!----------------------
                //this.oForm.post(); // gepe



		//myForm.addInput("tipoalojamiento", "tipoalojamiento", document.getElementById("tipoalojamiento").value);
		//myForm.addInput("tipoalojamiento", "tipoalojamiento", document.getElementById("tipoalojamiento").value);
		//oBuscador.buscargp();
		//alert('pasa 2')
		//myForm.post();
		//var oValidator = oBuscador.validar();
		//alert(oValidator.isValid);
	}

	function Buscando__(oBuscador)
	{
		oBuscador = new Despegar.SearchBox.Box();
		initParametersReferences(oBuscador);
		oBuscador.objectSearchInit();
		oBuscador.restSearchFlow = flowRevancha[oBuscador.sFlow];
		var oValidator = oBuscador.validar();	
		if (oValidator.isValid)
      		{
       		mostrarBuscando();	
			document.getElementById("txtBHVB1")[0].selected = true;
             	document.getElementById("txtBHVH1")[0].selected = true;
			document.getElementById("origen").value = defaultValueOrigen;
			document.getElementById("destino").value = defaultValueDestino;
			document.getElementById("origenDescripcion").value = defaultTextOrigen;
			document.getElementById("destinoDescripcion").value = defaultTextDestino;
			oBuscador.buscar();
      		}
		else
      		{
	         	//_target: "alert" (despliega en un alert de los mensajes de validacion del formulario cargado por el usuario
      		   	//_target: "html" (despliega en un div especifico - Se especifica en el paremetro id
      	   		alert(oValidator.displayMessage("alert","",Despegar.ResourceManager,getRegion(oBuscador.vPais)));
		}
	}












function loadAutoComplete() {
   if (vPais == 10){globalac.language = "pt";}else{globalac.language = "es";}
   globalac.flights.buscadorVuelosDescripcionOriginLocation1 = new AutoComplete({ textInput: "origenDescripcion", valueInput: "origen", tabToInput: "arrPlace", callBackFunction: airportSelected, defaultText: defaultTextOrigen, defaultValue: defaultValueOrigen, searchType: "vue", popupFunc: completerPopupWrapAC, popdownFunc: completerPopdownWrapAC, popupid: "dapopupac", destTypeInput: "", destMultipleInput: "", origenSelect: "", urlType: "rest" }); //new DespegarAutCompCompleter("origenDescripcion", completerPopupWrapAC, completerPopdownWrapAC, "dapopupac", "arrPlace", airportSelected, "origen", defaultTextOrigen, defaultValueOrigen);
   globalac.flights.buscadorVuelosDescripcionDestinationLocation1 = new AutoComplete({ textInput: "destinoDescripcion", valueInput: "destino", tabToInput: "arrPlace", callBackFunction: airportSelected, defaultText: defaultTextDestino, defaultValue: defaultValueDestino, searchType: "vue", popupFunc: completerPopupWrapAC, popdownFunc: completerPopdownWrapAC, popupid: "dapopupac", destTypeInput: "", destMultipleInput: "", origenSelect: "", urlType: "rest" }); //new DespegarAutCompCompleter("destinoDescripcion", completerPopupWrapAC, completerPopdownWrapAC, "dapopupac", "arrPlace",airportSelected,"destino",defaultTextDestino,defaultValueDestino);
   createLocatorAC();

}
function initCalendarEvents() {
    initCalendarEventsWithParams('fecha1', 'fecha2', 'fecha1Image', 'fecha2Image');
}
function initCalendarEventsWithParams(sfecha1, sfecha2, sfecha1Image, sfecha2Image) {
    prepareInput(vPais, sfecha1, 0, 1, null, sfecha1, sfecha2, iDiasAnticipo);
    prepareInput(vPais, sfecha2, 0, 1, null, sfecha2, sfecha1, iDiasAnticipo);
    prepareButton(vPais, sfecha1Image, sfecha1, 0, 1, null, sfecha1, sfecha2, iDiasAnticipo);
    prepareButton(vPais, sfecha2Image, sfecha2, 0, 1, null, sfecha2, sfecha1, iDiasAnticipo);
}

function mostrarBuscando()
{
   document.getElementById('buscandoDiv').style.display = 'block';
   document.getElementById('header').style.display = 'none';
   document.getElementById('MainContent').style.display = 'none';
   document.getElementById('bottomContent').style.display = 'none';
   document.getElementById('securityLogos').style.display = 'none';
   document.getElementById('footer').style.display = 'none';
   document.getElementById('PublicidadBottom').style.display = 'none';
   document.getElementById('rulesframe').style.display = 'none';

}

/**FUNCIONES DIAS DE ANTICIPACION***/
function esFeriado(dia)
{
   var esFeriado = false;
        if(feriados)
   {
      for (i=0;i< feriados.length;i++)
      {
         if (feriados[i].toString() == dia.toString())
         {
            esFeriado = true;
            break;
         }
      }
   }
   return esFeriado;
}
function esLaborable(dia,sabadoLaborable,domingoLaborable)
{

   if (!(esFeriado(dia)))
   {
      if (dia.getDay()== 6)
      {
         if (sabadoLaborable)
         {
            return true;
         }
         else
         {
            return false;
         }
      }
      else
      {
         if (dia.getDay()== 0)
         {
            if (domingoLaborable)
            {
               return true;
            }
            else
            {
               return false;
            }
         }
         else
         {
            return true;
         }
      }
   }
   else
   {
      return false;
   }
}
function getDiasAnticipo(Today,tipoCalendario,diasParaEmitir,sabadoLaborable,domingoLaborable)
{
   var diaToAnalize = Today;
   if (tipoCalendario=="AM")
   {
      iCounter = 0;

   }
   else
   {
      iCounter = 1;
      diaToAnalize.setDate(diaToAnalize.getDate() + 1);
   }

   var diasRestantes = diasParaEmitir;
   var esLaborableDia = false;
   while(!(diasRestantes < 0))
   {
      esLaborableDia = esLaborable(diaToAnalize,sabadoLaborable,domingoLaborable);
      if (esLaborableDia)
      {
         diasRestantes--;
         if (diasRestantes > 0)
         {
            diaToAnalize.setDate(diaToAnalize.getDate() + 1);
            iCounter++;
         }
      }
      else
      {
         while ((!esLaborableDia))
         {
            iCounter++;

            diaToAnalize.setDate(diaToAnalize.getDate() + 1);
            esLaborableDia = esLaborable(diaToAnalize,sabadoLaborable,domingoLaborable);

         }
      }

   }
   return iCounter;

}
/***************************************/
function buscarPreviaje()
{

   if (document.getElementById('destinopreviajeHidden').value != "")
   {
      location.href = 'http://www.previaje.com/destinos/home-' + document.getElementById('destinopreviajeHidden').value + ".html";
   }
   else{alert("- Ingrese una ciudad");}

}

function validarEmail(valor,campo,origen,form)
 {
   var target;

   target = document.getElementById(form).action;
   if (origen == 1){
      if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(valor))
         {
            window.open(target + "&eMail=" + valor + "&pais=" + vPais,"","height=300px,width=320px,directories=no,menubar=no,resizable=no,scroll=no");
         }
       else
         {
            alert("La dirección de Email es incorrecta.");
         }
      return false;
   }
   else 
   {
      if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(valor)) 
      {
         window.open(target + "&eMail=" + valor + "&pais=" + vPais,"","height=300px,width=320px,directories=no,menubar=no,resizable=no,scroll=no");
      }
      else 
	  {
           if (vPais==10) 
		   {
             alert("o endereço do e-mail está incorreto.");
           }
           else{
               alert("La dirección de Email es incorrecta.");
           }

      }
   }
}
function validarEmailBr(valor,campo,origen,form) 
{
   var target;
   target = document.getElementById(form).action;

   if (origen == 1){
      if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(valor)) 
	  {
         window.open(target + "&eMail=" + valor + "&pais=" + vPais,"","height=300px,width=320px,directories=no,menubar=no,resizable=no,scroll=no");
      }
      else 
      {
         alert("O endereço de e-mail é incorreto");
      }
      return false;
   }
   else 
   {
      if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(valor)) 
	  {
         window.open(target + "&eMail=" + valor + "&pais=" + vPais,"","height=300px,width=320px,directories=no,menubar=no,resizable=no,scroll=no");
      }
      else 
	  {
         alert("O endereço de e-mail é incorreto");
      }
   }
 }
 /*IFRAME GENERICO*/
var Top = 100
//var Left = document.body.clientWidth / 2;

function SetTopLeft(iTop, iLeft) 
{
   Top = iTop;
   Left = iLeft
}

function ResizeIFrame(oFrame) {
   if (oFrame.contentWindow != null &&
       oFrame.contentWindow.document != null &&
       oFrame.contentWindow.document.body != null &&
       oFrame.contentWindow.document.body.firstChild != null) {

         oFrame.style.display = 'block';
         oFrame.style.visibility = 'visible';
         if (oFrame.contentWindow.document.body.firstChild.nodeName == '#text')
            oFrame.height = oFrame.contentWindow.document.body.firstChild.nextSibling.offsetHeight;
         else
            oFrame.height = oFrame.contentWindow.document.body.firstChild.offsetHeight;
   }
}

function MostrarIFrame(tipo, nombreFrame , altura, sTitulo, sTexto, url, idPais)
{
   var sInfo;

   var oFrame;
   var sOnLoad;
   var aux;

   /*
       El iframe puede estar en el documento actual o en el padre. Se considera esta segunda posibilidad
       para el buscador SEO. Antes estaba dentro del mismo frame del buscador pero se veía por la mitad,
       ahora está en la página que lo contiene (modeloPaginasInternas[br].html).
   */
   if(document.getElementById(nombreFrame))
       oFrame = document.getElementById(nombreFrame);
   else {
       oFrame = parent.document.getElementById(nombreFrame);
       Left = parent.document.body.clientWidth / 2;
   }

   //document.all[nombreFrame].display='none';

   if (url != '')
   {
      oFrame.style.top = Top;
      oFrame.style.left = Left;
      oFrame.height = altura;
      oFrame.style.backgroundColor = '#ffffff';
      oFrame.style.borderStyle = 'none';
      aux = " " + oFrame.onload;
      sOnLoad = aux.toUpperCase();
      if(oFrame.onload == null ||  sOnLoad.indexOf("IFRAMERESIZE") <= 0 )  // Esto es porque el evento onload del iframe puede manejar el auto-resize y para evitar el flicker
         oFrame.style.display = 'block';
      if (url.indexOf('?') > 0)
         oFrame.src = url+'&tipo='+tipo+'&nombreFrame='+nombreFrame+'&idPais='+idPais;
      else
         oFrame.src = url+'?tipo='+tipo+'&nombreFrame='+nombreFrame+'&idPais='+idPais;
      if (oFrame.onload == null || sOnLoad.indexOf("IFRAMERESIZE") <= 0) // Esto es porque el evento onload del iframe puede manejar el auto-resize y para evitar el flicker
         oFrame.style.visibility = 'visible';
   }
   else
   {
      //document.all[nombreFrame].src = '/galeria/images/trans.gif';
      oFrame.style.top = Top;
      oFrame.style.left = Left;
      oFrame.height = altura;
      oFrame.style.visibility = 'visible';
      oFrame.style.display = 'block';
      sInfo = '';

      sInfo += '<html><head>'
      sInfo += '<title>'+ sTitulo +'</title>';
         sInfo = '<script language="JavaScript">';
      sInfo += 'function HideRegla()';
      sInfo += '{';
//       sInfo += 'parent.document.getElementById("'+nombreFrame+'").style.display="none"';
      sInfo += 'var oIFrame;';
      sInfo += 'oIFrame = parent.document.getElementById("'+nombreFrame+'");';
      sInfo += 'oIFrame.style.visibility = "hidden";';
       sInfo += 'oIFrame.src= "/galeria/images/trans.gif";';
         sInfo += '}';
      sInfo += '</script>';
      sInfo += '<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">';
      sInfo += '<link rel="stylesheet" href="/paginas/css/homedespegar.css">';
      sInfo += '<link rel="stylesheet" href="/paginas/css/vuelos.css">';
      sInfo += '</head>';
      sInfo += '<body bottommargin="0" leftmargin="0" marginheight="0" marginwidth="0" rightmargin="0" topmargin="0">';
       sInfo += '<table border="1" bgcolor="#ffffff" bordercolor="#000000" cellpadding="5" cellspacing="5"><tr><td bordercolor="#ffffff">'
      sInfo += '<table width="400" border="0" cellpadding="0" cellspacing="0" align="left" height="200" bgcolor="#ffffff">';
      sInfo += '<tr><td width="26" class="verdeoscuro" height="22">&nbsp;</td>';
       sInfo += '<td width="243" class="verdeoscuro" height="22">&nbsp;</td>';
       sInfo += '<td width="21" valign="bottom" height="22"><img src="/img/common/miselan/ico_curvaverdebus.gif" width="21" height="22"></td><td colspan="2" height="22">';
      if (idPais != '10')
          sInfo += '<img src="/img/common/btn/bot_cerrarrojo.gif" width="70" height="17" style="cursor:pointer;cursor:hand" onclick="javascript:HideRegla();" align="right">';
      else
         sInfo += '<img src="/img/common/btn/bot_cerrarrojo_br.gif" width="70" height="17" style="cursor:pointer;cursor:hand" onclick="javascript:HideRegla();" align="right">';
       sInfo += '</td></tr><tr valign="top"><td colspan="5" class="verdeoscuro" align="center"><br>';
       sInfo += '<table width="95%" border="0" align="center" cellpadding="1" cellspacing="0" class="tablanegravuelos">';
       sInfo += '<tr><td colspan="3" align="left"><p class="mdazul"><strong>' + sTitulo + '</strong></p>';
       sInfo += '</td></tr><tr><td colspan="3" align="left"><span class="textos">';
       sInfo += sTexto + '</span></td></tr><tr><td colspan="3"><p>&nbsp;</p></td></tr></table></td></tr><tr>';
       sInfo += '<td height="10" class="verdeoscuro"><img src="/img/common/trans.gif"></td><td height="10" colspan="2" class="verdeoscuro">&nbsp;';
       sInfo += '</td><td width="20" class="verdeoscuro">&nbsp;</td><td width="90" class="verdeoscuro">&nbsp;</td></tr></table>';
       sInfo += '</tr></td></table>';

       if(oFrame.contentDocument)
            oFrame.contentDocument.write(sInfo);
       else
            document.frames[nombreFrame].document.write(sInfo);
   }
}

var activex = ((navigator.userAgent.indexOf('Win')  != -1) && (navigator.userAgent.indexOf('MSIE') != -1) && (parseInt(navigator.appVersion) >= 4 ));
var CantDetect = ((navigator.userAgent.indexOf('Safari')  != -1) || (navigator.userAgent.indexOf('Opera')  != -1));

function oopsPopup() {
   if(document.getElementById('ventana') != null){
      if(document.getElementById('ventana').value == 1){
         alert('Para poder llamar a Despegar usando skype, necesita tener instalado el programa de skype.\nDescargue e instale el programa.\nLuego, intente nuevamente');
         return false;
      }
   }else{
      if((navigator.language && navigator.language.indexOf("ja") != -1) || (navigator.systemLanguage && navigator.systemLanguage.indexOf("ja") != -1) || (navigator.userLanguage && navigator.userLanguage.indexOf("ja") != -1)) {
        var URLtoOpen = "/general/skype/popup_despegarskype.html";
      } else {
        var URLtoOpen = "/general/skype/popup_despegarskype.html";
      }
      var windowName = "oops";
      var popW = 434, popH = 600;
      var scrollB = 'yes';
      w = screen.availWidth;
      h = screen.availHeight;
      var leftPos = (w-popW)/2, topPos = (h-popH)/2;
      oopswindow = window.open(URLtoOpen, windowName,'width=' + popW + ',height=' + popH + ',scrollbars=' + scrollB + ',screenx=' +leftPos +',screeny=' +topPos +',top=' +topPos +',left=' +leftPos +',resizable=yes');
      return false;
   }
}

if(typeof(detected) == "undefined" && activex) {
    document.write(
        ['<script language="VBscript">',
        'Function isSkypeInstalled()',
        'on error resume next',
        'Set oSkype = CreateObject("Skype.Detection")',
        'isSkypeInstalled = IsObject(oSkype)',
        'Set oSkype = nothing',
        'End Function',
        '</script>'].join("\n")
    );
}


/* Funciones de Revancha */

function AdvSearch() {
   // se fija si el flow es revancha o no
   if (flowRevancha['v'])
   {
      var idCNN = "txtBHVB";
      var idEdades = "txtBHVHY";
      //Auxiliares
      var cnnQuantity;
      var CNN = 0;
      var INF = 0;

      cnnQuantity = document.getElementById(idCNN + "1").value;

      for (j=1;j<=cnnQuantity;j++)
      {
         if (document.getElementById(idEdades + "1" + j).value > 1)
         {
            CNN++;
         }
         else
         {
            INF++;
         }
      }

      var DepartureParams = "?";
      if (document.getElementById("origenDescripcion").value != defaultTextOrigen)
      {
         DepartureParams = DepartureParams + "DepLocDesc=" + stripHTML(document.getElementById("origenDescripcion").value) +
                         "&DepLocCode=" + document.getElementById("origen").value + "&";
      }

      if (document.getElementById("destinoDescripcion").value != defaultTextDestino)
      {
         DepartureParams = DepartureParams + "DestLocDesc=" + stripHTML(document.getElementById("destinoDescripcion").value) +
                   "&DestLocCode=" + document.getElementById("destino").value + "&";
      }

      var Parameters = DepartureParams + "&Roundtrip=" + (document.getElementById("sTripTypeI").checked ? "1" : "0")
                  + "&DepDate=" + document.getElementById("fecha1").value;

      if (document.getElementById("sTripTypeI").checked)
          Parameters += "&RetDate=" + document.getElementById("fecha2").value;

      Parameters += "&ADT=" + document.getElementById("txtBHVH1").value +
                   "&CNN=" + CNN +
                   "&INF=" + INF;

      location.href="http://" + window.location.host + "/search/Flights/FlightSearch.aspx" + Parameters;
   }
   else
   {
      location.href="http://" + window.location.host + "/busqueda/vuelos/busquedavuelos.aspx";
   }
}

