var userInterc = 0;
//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) <= 9;
		flowRevancha['v'] = aleatorio(0, 9) <= 2;
		defaultValueOrigen = sDefaultValueOrigen;
		defaultTextOrigen = sDefaultTextOrigen;
		break;
	case 2:
	    	flowRevancha['h'] = aleatorio(0, 9) <= 9;
	    	defaultValueOrigen = "";
		defaultTextOrigen = "Escriba la ciudad de partida";
		break;
	case 5:
	    	flowRevancha['h'] = aleatorio(0, 9) <= 9;
	    	defaultValueOrigen = "MVD";
		defaultTextOrigen = "Montevideo (Carrasco), Uruguay";
		break;
	case 6:
		flowRevancha['h'] = aleatorio(0, 9) <= 9;
		flowRevancha['v'] = aleatorio(0, 9) < 9;
		defaultValueOrigen = "SCL";
		defaultTextOrigen = "Santiago de Chile, Chile";
		break;
	case 7:
	    flowRevancha['h'] = aleatorio(0, 9) <= 9;
	    defaultValueOrigen = "LIM";
		defaultTextOrigen = "Lima, Perú";
		break;
	case 8: //EC
	    flowRevancha['h'] = true;
	    flowRevancha['v'] = true;
	    defaultValueOrigen = "";
		defaultTextOrigen = "Escriba la ciudad de partida";
		break;
	case 9:
	    flowRevancha['h'] = aleatorio(0, 9) <= 9;
	    defaultValueOrigen = sDefaultValueOrigen;
        defaultTextOrigen = sDefaultTextOrigen;
		break;
	case 10:
		flowRevancha['h'] = aleatorio(0, 9) <= 9;	
		defaultValueOrigen = "SAO";
		defaultTextOrigen = "São Paulo";
		break;
	case 14: //CR
		flowRevancha['h'] = true;
		flowRevancha['v'] = true;
		defaultValueOrigen = sDefaultValueOrigen;
		defaultTextOrigen = sDefaultTextOrigen;
		break;
	case 59: //PA
		flowRevancha['h'] = true;
		flowRevancha['v'] = true;
		defaultValueOrigen = sDefaultValueOrigen;
		defaultTextOrigen = sDefaultTextOrigen;
		break;
	case 82:
        flowRevancha['h'] = aleatorio(0, 9) <= 9;	
		flowRevancha['v'] = aleatorio(0, 9) <= 9;
		defaultValueOrigen = "CCS";
		defaultTextOrigen = "Caracas, Venezuela";
		break;
	case 86:
	    flowRevancha['h'] = aleatorio(0, 9) <= 9;
		flowRevancha['v'] = aleatorio(0, 9) <= 2;
		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 = "adultsTraveling";
	var idCNN = "kidsTraveling";
	var idEdades = "kidAge";
	//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);
	}
}

function setTipoVuelo(value){
	sTripType = value;
	document.getElementById('parrafoFecha2').style.visibility = "visible";
	if(value == "i")
	document.getElementById('parrafoFecha2').style.visibility = "hidden";
}

function activarSolapa(sFlow)
{
	//Apago todas las Solapas
	document.getElementById("sFlowVuelos").className = "tabExternal";
	document.getElementById("sFlowHoteles").className = "tabExternal";
	document.getElementById("sFlowVuelosHoteles").className = "solapaVHOff";
	document.getElementById("sFlowAutos").className = "tabExternal";
	document.getElementById("sFlowPaquetes").className = "tabExternal";

	document.getElementById('parrafoFecha2').style.visibility = "visible";
	switch(sFlow)
	{
		case "v":
			document.getElementById("sFlowVuelos").className = "tabExternal selected";
			if (sTripType == "i") {
				document.getElementById('parrafoFecha2').style.visibility = "hidden";
			}
			break;		
		case "h":
			document.getElementById("sFlowHoteles").className = "tabExternal selected";
			break;
		case "vh":
			document.getElementById("sFlowVuelosHoteles").className = "solapaVHOn";
			break;
		case "a":
			document.getElementById("sFlowAutos").className = "tabExternal selected";
			break;
		case "p":
			document.getElementById("sFlowPaquetes").className = "tabExternal selected";
			break;
	}
	if (sFlow =="v" && userInterc==0)
	{
		document.getElementById("adultsTraveling1").value = 1;
	}
	if ((sFlow =="h" || sFlow =="p" || sFlow =="vh") && userInterc==0)
	{
		document.getElementById("adultsTraveling1").value = 2;
	}
}
function setTipoProducto(value)
{
		switch(value)
		{
			case "v":
			{
				document.getElementById("solapaContainer").className = "tabVuelos";
				activarSolapa(value);
				document.getElementById("opcionesAvanzadas").href = "/search/flights/flightsearch.aspx";
				document.getElementById("origenDescripcion").value = sDefaultTextOrigen;
				document.getElementById("origen").value = sDefaultValueOrigen;
				
				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";
					document.getElementById("textoBuscar").innerHTML = "procurar vôos";
				}
				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("textoBuscar").innerHTML = "buscar vuelos";
				}
				
				if (document.getElementById("sTripTypeGo").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("adultsTraveling1").value < 2)
				{
					document.getElementById("adultsTraveling1").value = 2;
				}
				activarSolapa(value);
				if (vPais == 10)
				{
					document.getElementById("origenPaquetesLabel").innerHTML = "Cidade de origem";
					
					document.getElementById("titleDestinoDescripcion").innerHTML = "Cidade de destino";
					document.getElementById("titleFecha1").innerHTML = "Posso partir entre";
					document.getElementById("titleFecha2").innerHTML = "e";
					document.getElementById("textoBuscar").innerHTML = "procurar pacotes";
				}
				else
				{
					document.getElementById("origenPaquetesLabel").innerHTML = "Ciudad de origen";
					document.getElementById("titleDestinoDescripcion").innerHTML = "Ciudad de destino";
					document.getElementById("titleFecha1").innerHTML = "Puedo partir entre";
					document.getElementById("titleFecha2").innerHTML = "y el";
					document.getElementById("textoBuscar").innerHTML = "buscar paquetes";
				}
			}
			break;
			case "h":
			{
				document.getElementById("opcionesAvanzadas").href = "/search/hotels/home";
				document.getElementById("origenDescripcion").value = sDefaultTextOrigen;
				document.getElementById("origen").value = sDefaultValueOrigen;
				if (document.getElementById("adultsTraveling1").value < 2)
				{
					document.getElementById("adultsTraveling1").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)";
					document.getElementById("textoBuscar").innerHTML = "procurar hotéis";
				}
				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("textoBuscar").innerHTML = "buscar hoteles";
				}	
				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";
						document.getElementById("textoBuscar").innerHTML = "procurar carros";
				}
				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("textoBuscar").innerHTML = "buscar autos";
				}
				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 = sDefaultTextOrigen;
				document.getElementById("origen").value = sDefaultValueOrigen;							
				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 = "homePagev3Lite";
if(document.getElementById("sFlow").value == "h" || document.getElementById("sFlow").value == "vh")
{
	var cantHabitaciones = gValue('Habitaciones');
}
else
{
	var cantHabitaciones = 1;
}
	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("sTripTypeGo").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(oBuscador)
{
	checkFlow();
	var oBuscador = new Despegar.SearchBox.Box();
	initParametersReferences(oBuscador);
	oBuscador.objectSearchInit();
	oBuscador.sPaginaBuscador = "homev3Lite";
	oBuscador.restSearchFlow = flowRevancha[oBuscador.sFlow];
	var oValidator = oBuscador.validar();
	if (oValidator.isValid)
	{
		document.getElementById("botonBuscar").className="btnDisabled";
		if (!oBuscador.restSearchFlow) {
			document.getElementById("adultsTraveling1")[0].selected = true;
			document.getElementById("origen").value = sDefaultValueOrigen;
			document.getElementById("destino").value = defaultValueDestino;
			document.getElementById("origenDescripcion").value = sDefaultTextOrigen;
			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)));

	}
}

	

/**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 (/^\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.");
	}	
 	}
 } 
 /*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")
    );
}

		
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 = "http://www.despegar.com.ar/general/skype/popup_despegarskype.html";
      } else {
        var URLtoOpen = "http://www.despegar.com.ar/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")
    );
}

function skypeCheck() {
    if(CantDetect) {
        return true;
    } else if(!activex) {
        var skypeMime = navigator.mimeTypes["application/x-skype"];
        detected = true;
        if(typeof(skypeMime) == "object") {
            return true;
        } else {
            return oopsPopup();
        }
    } else {
        if(isSkypeInstalled()) {
            detected = true;
            return true;
        }
    }
    
    detected = true;
    return oopsPopup();
}

/* Funciones de Revancha */

function AdvSearch() {
   // se fija si el flow es revancha o no
   if (flowRevancha['v'])
   {
      var idCNN = "kidsTraveling";
      var idEdades = "kidAge";
      //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";
   }
}

var userInterc = 0;
var defaultValueDestino;
var defaultTextDestino;
var sTripType ="iv";

/**
 * Oculta las ofertas que no se mostrarán
 * @param {Integer} cantShownOferts Cantidad de ofertas que se mostrarán por cada tipo de oferta
 */
function customizeShownOferts(cantShownOferts){
	var passagesLis = document.getElementById("pasajes").getElementsByTagName("ul")[0].getElementsByTagName("li");
	for (var i = cantShownOferts;i<passagesLis.length-1;i++){
		passagesLis[i].style.display="none";
	}
	var packagesLis = document.getElementById("paquetes").getElementsByTagName("ul")[0].getElementsByTagName("li");
	for (var i = cantShownOferts;i<packagesLis.length-1;i++){
		packagesLis[i].style.display="none";
	}
	var hotelsLis = document.getElementById("hoteles").getElementsByTagName("ul")[0].getElementsByTagName("li");
		for (var i = cantShownOferts;i<hotelsLis.length-1;i++){
		hotelsLis[i].style.display="none";
	}
}

/**
 * Setea las clases y el atributo onclick de los divs correspondientes a cada tipo de oferta
 */
function setOfertsProperties(){
	document.getElementById("pasajes").className = "ofertContainer secondaryOferts";
	document.getElementById("paquetes").className = "ofertContainer secondaryOferts";
	document.getElementById("hoteles").className = "ofertContainer";
	document.getElementById("paquetes").getElementsByTagName("h1")[0].onclick = function(){showOferts('paquetes')};
	document.getElementById("hoteles").getElementsByTagName("h1")[0].onclick = function(){showOferts('hoteles')};
	document.getElementById("pasajes").getElementsByTagName("h1")[0].onclick = function(){showOferts('pasajes')};
}

function showOferts(ofertType){
	document.getElementById("pasajes").getElementsByTagName("ul")[0].style.display="none";
	document.getElementById("paquetes").getElementsByTagName("ul")[0].style.display="none";
	document.getElementById("hoteles").getElementsByTagName("ul")[0].style.display="none";
	document.getElementById(ofertType).getElementsByTagName("ul")[0].style.display="block";
}
/**
 * Toma un archivo HTML y lo devuelve su código en forma de string
 * @param {String} ofertPath
 * @return {String} El codigo HTML recuperado o un mensaje de error 
 */
function loadOferts(ofertPath)
{
	xmlhttp=null;
	if (window.XMLHttpRequest)
	{// code for IE7, Firefox, Opera, etc.
		xmlhttp=new XMLHttpRequest();
	}
	else if (window.ActiveXObject)
	{// code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	if (xmlhttp!=null)
	{
		xmlhttp.open("GET",ofertPath,false);

		xmlhttp.send(null);

		var ofertContent = xmlhttp.responseText;		
		
		if(xmlhttp.status != 200)
		{
			ofertContent = "//ERROR al cargar archivo '" + ofertPath + "' (" + xmlhttp.statusText + ")\n"
		}
	}
	else
	{
		ofertContent = "//ERROR al cargar archivo '" + ofertPath + "' (no se pudo instanciar XMLHttpRequest)\n"
	}
	return ofertContent;
}
function setPasajeros(cantHabitaciones,oBuscador)
{
	//inicializo IDs
	var idADT = "adultsTraveling";
	var idCNN = "kidsTraveling";
	var idEdades = "kidAge";
	//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);
	}
}

function gValue(id)
{
	var element = document.getElementById(id);
	if (element)
	{
		return element.value;
	}
	else
	{
		return null;
	}
}

window.onload = function(){
	for (var i = 1; i <= 7; i++) {
		createSelectOptionsRange("adultsTraveling" +i, 1, 7);
	}
	for (var j = 1; j <= 7; j++) {
		createSelectOptionsRange("kidsTraveling" +j, 0, 7);
	}
	createSelectOptionsRange("Habitaciones", 1, 7);
	for (var k = 1;  k<= 7; k++) {
		for (var l = 1; l <= 7; l++){
			createSelectOptionsRange("kidAge" +k +l, 0, 11);
		}
	}

	if (!(vPais == 8 || vPais == 14 || vPais == 59)) {
	    
	    addTextToOffersLink("pasajes", "Lite");
		addTextToOffersLink("paquetes", "Lite");
	}
	switch (vPais){
		case 1:
			modifyOffersLinkAffiliate("hoteles", "sIdLinkAfiliadoDescripcion", 987223);
			break;
		case 2:
			modifyOffersLinkAffiliate("hoteles", "sIdLinkAfiliadoDescripcion", 987231);
			break;
		case 5:
			modifyOffersLinkAffiliate("hoteles", "sIdLinkAfiliadoDescripcion", 987230);
			break;
		case 6:
			modifyOffersLinkAffiliate("hoteles", "sIdLinkAfiliadoDescripcion", 987228);
			break;
		case 7:
			modifyOffersLinkAffiliate("hoteles", "sIdLinkAfiliadoDescripcion", 987229);
			break;
		case 9:
			modifyOffersLinkAffiliate("hoteles", "sIdLinkAfiliadoDescripcion", 987227);
			break;
		case 10:
			modifyOffersLinkAffiliate("hoteles", "sIdLinkAfiliadoDescripcion", 987225);
			break;
		case 82:
			modifyOffersLinkAffiliate("hoteles", "sIdLinkAfiliadoDescripcion", 987226);
			break;
		case 86:
			modifyOffersLinkAffiliate("hoteles", "sIdLinkAfiliadoDescripcion", 987224);
			break;
	}
	
}
		
/**
 * Crea options con valores consecutivos en un rango especifico en un select especificado
 * @param {String} selectID ID del select al que se le agregaran los options
 * @param {Integer} initialValue Valor incial de la enumeración de los selects
 * @param {Integer} finalValue Valor final de la enumeración de los selects
 */
createSelectOptionsRange = function(selectID,initialValue,finalValue)
{
	var selectCombo = document.getElementById(selectID);
	for (i = initialValue; i <= finalValue; i++) {
		var option = document.createElement("option");
		option.value = i;
		option.innerHTML = i;
		selectCombo.appendChild(option);
	}
}

/**
 * Muestra los selects para seleccionar las edades de la cantidad de niños seleccionados, si es cero oculta tambien el titulo
 * @param {Integer} cantKids Cantidad de chicos que viajan (valor del select)
 * @param {String} kidsAgesTitleId ID del p o div que contiene los textos de las edades (un label y un span)
 * @param {String} kidsAgesId ID del div que contendrá a todos los selects (de las edades)
 * @param {String} selectsId Parte del ID que tienen en común todos los selects de las edades (en la funcion se agrega el ultimo número que los enumera)
 */
openKidsAges = function(cantKids, kidsAgesTitleId, kidsAgesId, selectsId)
{
	if (cantKids == 0) {
    	document.getElementById(kidsAgesTitleId).style.display = "none";
    	document.getElementById(kidsAgesId).style.display = "none";
    }
	else
	{
    	document.getElementById(kidsAgesTitleId).style.display = "block";
    	document.getElementById(kidsAgesId).style.display = "block";
    	for (i = 1; i <= cantKids; i++) {
        	document.getElementById(selectsId + i).style.display = "block";
        }
	    for (i = 7; i > cantKids; i--) {
    	    document.getElementById(selectsId + i).style.display = "none";
        }
	}
}
	
/**
 * Muestra los selects para seleccionar loss pasajeros de la cantidad de habitaciones seleccionadas
 * @param {String} roomsId La id del select con la cantidad de habitaciones
 * @param {String} passangersContainerId Parte en comun que tienen todos los divs que contienen los selects con los pasajeros
 */
function showHotelsRoomsPassangers(cantRooms,passangersContainerId){
	for (i = 2; i <= cantRooms; i++) {
		document.getElementById(passangersContainerId + i).classes="";
    	document.getElementById(passangersContainerId + i).style.display = "block";
    }
    for (i = 7; i > cantRooms; i--) {
		document.getElementById(passangersContainerId + i).classes="";
	    document.getElementById(passangersContainerId + i).style.display = "none";
    }
}

function onSelectOpen()
{
	if (document.getElementById('optionsCountry').style.display == 'block')
	{
		document.getElementById('optionsCountry').style.display = 'none';
	}
	else
	{
		document.getElementById('optionsCountry').style.display = 'block';
	}
	return false;
}

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 validateEmailCorporate(formName, mailBoxName,destinationAdress)
{
	var form = document.getElementById(formName);
	var destination = destinationAdress + "?";
	destination = destination + "pais=" +vPais;
	var separator ="&";
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(document.getElementById(mailBoxName).value))
	{
		for(var i = 0; i < form.length; i++)
		{
			destination = destination + separator + form[i].name + "=" + form[i].value.replace(/\n/g, '<br>');
		}
		window.open(destination,"","height=300px,width=320px,directories=no,menubar=no,resizable=no,scroll=no");
	}
	else
	{
		if(vPais=10)
		{
			alert("O endereço de e-mail é incorreto");
		}
		else
		{
			alert("La dirección de mail es incorrecta");
		}
	}
	return false;
}

function addTextToOffersLink(productContainerId, textToAdd){
	var productContainer = document.getElementById(productContainerId);
	var lis = null;
	var liIndex = null;
	var a = null;
	lis = productContainer.getElementsByTagName("li");
	for(liIndex = 0; liIndex < lis.length; liIndex++){
		a = lis[liIndex].getElementsByTagName("a")[0];
		a.setAttribute("href", a.getAttribute("href") + textToAdd);
	}
}

function modifyOffersLinkAffiliate(productContainerId, affiliateParameterName, affiliateCod){
	var productContainer = document.getElementById(productContainerId);
	affiliateParameterName = "&" + affiliateParameterName + "=";
	var lis = null;
	var liIndex = null;
	var a = null;
	var affiliateOldCod = null;
	var link = null;
	var asd ="asd";
	lis = productContainer.getElementsByTagName("li");
	for(liIndex = 0; liIndex < lis.length; liIndex++){
		a = lis[liIndex].getElementsByTagName("a")[0];
		link = a.getAttribute("href");
		if(link.indexOf(affiliateParameterName) != -1){
			affiliateOldCod = link.substr(link.indexOf(affiliateParameterName) + affiliateParameterName.length);
			if(affiliateOldCod.indexOf("&") != -1){
				affiliateOldCod = affiliateOldCod.substr(0,affiliateOldCod.indexOf("&"));
			}
			link = link.substr(0,link.indexOf(affiliateOldCod)) + affiliateCod  + link.substr(link.indexOf(affiliateOldCod) + affiliateOldCod.length)
			a.setAttribute("href", link);
		}
	}
}

function multiplesDestinos()
{
    if(!flowRevancha['v'])
    {
        switch (vPais){
        case 1: {
               location.href="http://www.ar.despegar.com/busqueda/vuelos/busquedamultiplesdestinos.aspx";       
        }
        break;
        case 86: {
               location.href="http://www.mx.despegar.com/busqueda/vuelos/busquedamultiplesdestinos.aspx";       
        }
        break;
        default: {
               location.href="/busqueda/vuelos/busquedamultiplesdestinos.aspx";       
        }
        break;
        }
    }
    else{
        multiplesDestinosRevancha();
    }
}

function multiplesDestinosRevancha()
{
    var myForm = new Despegar.Form(location.href="/search/flights/flightsearch.aspx", "POST", "frmMultidestinations", "frmMultidestinations");

    var multidestinationsData = new Object();
    multidestinationsData.originsLocations = [];
    multidestinationsData.destinationsLocations = [];
    multidestinationsData.departureDates = [];
    multidestinationsData.originsLocationsDescriptions = [];
    multidestinationsData.destinationsLocationsDescriptions = [];

    var departureDate = new Despegar.Date();
    departureDate.setddmmaaaa(document.getElementById("fecha1").value, "/");

    multidestinationsData.originsLocations.push(document.getElementById("origen").value);
    multidestinationsData.destinationsLocations.push(document.getElementById("destino").value);
    multidestinationsData.departureDates.push(departureDate.getota());
    multidestinationsData.originsLocationsDescriptions.push(document.getElementById("origenDescripcion").value);
    multidestinationsData.destinationsLocationsDescriptions.push(document.getElementById("destinoDescripcion").value);
    multidestinationsData.typeSearch = "MultipleDestinations";

    /* Workaround debido a un bug de Stringify en IE8 */
    var replacer = function(k,v) { return (v == null || v==="") ? "" : v};
    var jsonAsStr = JSON.stringify(multidestinationsData, replacer);

    myForm.addInput("MultidestinationsData", "MultidestinationsData", jsonAsStr);
    myForm.post();
}
