//BASE
//función para llamadas ajax. Agregada para búsqueda anticipada
//no me interese la función de call back porque es una llamada one way
function jah(url) {
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        req.onreadystatechange = function() { /*jahDone(url, target);*/ };
        req.open("GET", url, true);
        req.send(null);
        // IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = function() { /*jahDone(url, target);*/ };
            req.open("GET", url, true);
            req.send();
        }
    }
}
function registerNameSpace(ns)
{
   var nsParts = ns.split(".");
   var root = window;

   for(var i=0; i<nsParts.length; i++)
   {
      if(typeof root[nsParts[i]] == "undefined")
      root[nsParts[i]] = new Object();

      root = root[nsParts[i]];
   }
}


function despegarErrorHandler(message, url, line)
{
   var errMessage = '';
   var stack = '';

   var curError;
   while(window.globalStack.length > 0)
   {
      curError = window.globalStack.pop();
      stack =  curError.stackEntry() + '\n' + stack;
   }
   if(stack != '') stack = 'STACK:\n'+ stack;

   if(Despegar != undefined && Despegar.Exception != undefined && curError instanceof Despegar.Exception)
   {
      if(curError.stack) stack += '\n\nMOZILLA STACK:\n'+ curError.stack;
      errMessage = 'ERROR:\nMessage: ' + curError.message + '\nURL: ' + url + '\nLine: ' + line + '\n\n' + stack;
   }
   else
   {
      errMessage = 'ERROR:\nMessage: ' + message + '\nURL: ' + url + '\nLine: ' + line;
   }

   alert(errMessage);

   return false;
}

function aleatorio(inferior, superior) {

    numPosibilidades = superior - inferior

    aleat = Math.random() * numPosibilidades

    aleat = Math.round(aleat)

    return parseInt(inferior) + aleat

}

function devuelveRuta(oBuscador)
{
         return "/resultados/resultadoBusquedaVuelos.aspx";
}

//window.onerror = despegarErrorHandler;

window.globalStack = new Array();

//----------------------


//--RESOURCES-----------
registerNameSpace("Despegar");

Despegar.ResourceManager = function()
{
   this.resources = new Array();
   this.currentRegion = "es";


   this.add = function(key,value,region)
   {
      if(region == undefined) region = this.currentRegion;
      if (this.resources[region] != null)
      {
         this.resources[region][key]= value;
      }
      else
      {
         this.resources[region] = new Array();
         this.resources[region][key]= value;
      }
   }


   this.get = function (key,region)
   {
      if(region == undefined) region = this.currentRegion;
      if (this.resources[region] != null)
      {
         if (this.resources[region][key] != null)
         {
            return this.resources[region][key];
         }
         else
         {
            return null;
         }
      }
      else
      {
            return null;
      }
   }

   return this;
}

//- CREO EL RECURSO--
Despegar.ResourceManager = new Despegar.ResourceManager();

//----------------------

//----SEARCH BOX--------
registerNameSpace("Despegar.SearchBox");

Despegar.SearchBox.Box = function()
{
    this.vPais;
    this.domain = document.location.href.split(".")[0].replace("http://","");
    this.sOrigen;
    this.sDescripcionOrigen;
    this.sDestino;
    this.sDescripcionDestino;
    this.oFechas = new Array();
    this.sFlow;
    this.sTripType;
    this.sPaginaBuscador;
    this.aPaxGroup = new Array();
    //Privadas
    this.sADT = 0;
    this.sCNN = 0;
    this.sINF = 0;
    this.oForm;
    this.TipoDestinoPaq;
    this.MultipleDestinoPaq;
    this.comboDuracionPaq;
    this.restSearchFlow;
    this.aProducts= new Array();
    // ---------------- Array de nombre de Objetos de Productos ---------
    this.aProducts["v"]= "Despegar.SearchBox.Flights";
    this.aProducts["vh"]= "Despegar.SearchBox.FlightsHotels";
    this.aProducts["h"]= "Despegar.SearchBox.Hotels";
    this.aProducts["a"]= "Despegar.SearchBox.Cars";
    this.aProducts["p"]= "Despegar.SearchBox.Packages";
    // ---------------- Array de nombre de Objetos de Productos FIN -----
    this.objectSearch;
    this.sEdades = new Array();
    this.objectSearchInit = function()
   {
        //gp this.objectSearch = eval( "new " + this.aProducts[this.sFlow] + "(this)");
        this.objectSearch = eval( "new " + this.aProducts[this.sFlow] + "(this)");

        this.oForm = this.objectSearch.initForm();
    }
  this.buscar = function()
    {
        //Vieja Busqueda
        //if ((!this.restSearchFlow) || (this.sFlow != "h")) SP:Ojo que así está en PROD pero esto no anda para vuelos porque entra en el if
        if ((!this.restSearchFlow))
      {
                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!----------------------
                //GP  this.oForm.post();
          }
        else {
        //Flow de busqueda de REVANCHA
          if (this.sFlow == "v") {
                var hostUrl = "http://" + window.location.host + '/';

                if (this.sOrigen != "" && this.sDestino != "") {
                    var restParams = this.objectSearch.generateRestParams();
                    //Redirección
                    window.location = hostUrl + "search/flights/" + restParams;
                }
                else {
                    //Desambiguación
                    var myForm = new Despegar.Form(hostUrl + "search/Disambiguation/Disambiguation.aspx", "POST", "frmDisambiguation", "frmDisambiguation");

                    var departureDate = new Despegar.Date();
                    var returnDate = new Despegar.Date();

                    for (i = 0; i < this.aPaxGroup.length; i++) {
                        this.sADT += eval(this.aPaxGroup[i].adt);
                        this.sCNN += eval(this.aPaxGroup[i].cnn);
                        this.sINF += eval(this.aPaxGroup[i].inf);
                    }

                    departureDate.setddmmaaaa(this.oFechas[0], "/");

                    myForm.addInput("OriginLocation", "OriginLocation", this.sOrigen);
                    myForm.addInput("DestinationLocation", "DestinationLocation", this.sDestino);
                    myForm.addInput("DepartureDate", "DepartureDate", departureDate.getota());
                    myForm.addInput("ADTCount", "ADTCount", this.sADT);
                    myForm.addInput("CNNCount", "CNNCount", this.sCNN);
                    myForm.addInput("INFCount", "INFCount", this.sINF);
                    if (this.sTripType == "iv") {
                        returnDate.setddmmaaaa(this.oFechas[1], "/");
                        myForm.addInput("ReturnDate", "ReturnDate", returnDate.getota());
                        myForm.addInput("ItineraryType", "ItineraryType", "RoundTrip");
                    }
                    else {
                        myForm.addInput("ItineraryType", "ItineraryType", "OneWay");
                    }
                    myForm.addInput("OriginLocationName", "OriginLocationName", stripHTML(this.sDescripcionOrigen));
                    myForm.addInput("DestinationLocationName", "DestinationLocationName", stripHTML(this.sDescripcionDestino));

                    //GP myForm.post();
                }
            }
            else if (this.sFlow == "h") {
                  // TODO: Resolver el problema con las diferentes urls
                  // Se puso fija la url por diferencias de url.
                var hostUrl = "/";
                if(window.location.href.indexOf(".com.ar")>=0)
                {
                    hostUrl = "http://www.ar.despegar.com/";
                }
            if (window.location.href.indexOf(".com.mx") >= 0)
            {
               hostUrl = "http://www.mx.despegar.com/";
            }
                var oFields = this.objectSearch.buscar();
                var size = 0;
                var fields = "";
                var cantHabitaciones = "";
                var pasDistribution;
                for (var field in oFields) {
                    if (oFields[field] != null) {
                        fields += field + "-" + oFields[field] + "|";
                    }
                }
                cantHabitaciones = document.getElementById("Habitaciones").value;
                pasDistribution = setPasajerosNet(cantHabitaciones, fields);
                window.location = hostUrl + "search/Hotels/" + oFields["sCiudadDesdeHotel"] + "/" + getFormatedDate(oFields["FechaEntradaHotel"]) + '/' + getFormatedDate(oFields["FechaSalidaHotel"]) + "/" + pasDistribution + "/";
            }
        }
    }
    this.validar = function()
    {
        //Retorna un objeto del tipo Validation
        return this.objectSearch.validar();
    }

    this.addPaxGroup = function(_adt,_aEdades)
   {
        //verificar que la linea siguiente sea valida
        var oPaxGroup = new this.PaxGroup(_adt,_aEdades);
        this.aPaxGroup.push(oPaxGroup);
    }
    //Objeto para guardar informacion de grupos de pax (Pax x Habitacion)
    //Tener en cuenta que _aEdades, es un array de las edades de los niños
   this.PaxGroup = function(_adt,_aEdades)
   {
        this.adt = _adt;
        this.cnn = 0;
        this.inf = 0;
        this.edades = _aEdades;
        var MAX_INF = 1;//Edad Maxima para bebe
      for(var i=0;i<_aEdades.length;i++)
      {
         if(_aEdades[i]<= MAX_INF)
         {
                this.inf++;
            }
         else
         {
                this.cnn++;
            }
        }

      this.toString = function()
      {
            return 'adt:' + this.adt + ' ,cnn:' + this.cnn + ' ,inf:' + this.inf;
        }
    }
}
//----------------------
function createScriptRequest(path) {
    var head = document.getElementsByTagName('head')[0];
    var scriptTag;
    scriptTag = document.createElement("script");
    scriptTag.id = "request";
    scriptTag.src = path;
    scriptTag.type = "text/javascript";

    head.appendChild(scriptTag);

    return;
}

function getFormatedDate(input) {
    var d = input.split(new RegExp('/', 'gi'));
    return d[2] + "-" + d[1] + "-" + d[0];
}

function getval(fields,field) {
    var sp;
    var sp2;
    var val= field + "-";
    sp=fields.split(val);
    if ((sp.length==1) | (sp.length==0))
    return null;
    if (sp==null)
    return null;
    sp2=sp[1].split("|");
   return sp2[0];
}

function setPasajerosNet(cantHabitaciones,fields) {
    //inicializo IDs
    var idADT = "txtBHH";
    var idCNN = "txtBHY";
    var idEdades = "txtBHY";
    //Auxiliares
    var adt;
    var cnnQuantity;
    var aEdades = new Array();
    var rooms = "";
    for (i = 1; i <= cantHabitaciones; i++) {
        if (i > 1)
            rooms = rooms + "!";
        adt = getval(fields,idADT + i) ;
        rooms = rooms + adt;
        for (j = 1; j <= getval(fields,"txtBHB" + i); j++) {
            if (getval(fields,idEdades + i + j)   == null)
            { age = "0"; }
            else {
                var age = getval(fields,idEdades + i + j) ;
                if (age == "?") {
                    age = "0";
                }
            }
            rooms = rooms + "-" + age;

        }

    }

    return rooms;
}

//------FLIGHTS---------

registerNameSpace("Despegar.SearchBox");

Despegar.SearchBox.Flights = function(oBuscador)
{

    // ----- Metodos ----- //
   this.initForm = function()
   {

         return new Despegar.Form("http://"+ oBuscador.domain +".viajo.com." + getCodePais(oBuscador.vPais) + devuelveRuta(oBuscador) ,"POST","frmVuelos","frmVuelos");

    }
    this.validar = function()
   {
        var region = getRegion(oBuscador.vPais);
        var oValidator = new Despegar.Validator();
        if ((!oBuscador.restSearchFlow && oBuscador.sOrigen.length == 0) || (oBuscador.restSearchFlow && oBuscador.sDescripcionOrigen.length == 0))
      {
            oValidator.isValid = false;
            oValidator.addMsgKey("_originNotValidMsg");
        }
        if ((!oBuscador.restSearchFlow && oBuscador.sDestino.length == 0 ||
                (oBuscador.restSearchFlow && (oBuscador.sDescripcionDestino.length == 0 ||  oBuscador.sDescripcionDestino == defaultTextDestino))))
      {
            oValidator.isValid = false;
            oValidator.addMsgKey("_destinationNotValidMsg");
        }
        if (oBuscador.sDestino == oBuscador.sOrigen && oBuscador.sOrigen.length != 0)
      {
            oValidator.isValid = false;
            oValidator.addMsgKey("_originDestinationEqualNotValidMsg");
        }
        this.validarFechas(oValidator);
        if (oValidator.isValid == false)
      {
            this.initResources(region);
        }
        return oValidator;
    }
   this.initResources = function(region)
   {
      if (region == "PT")
      {
      Despegar.ResourceManager.add("_startErrorMsg","",region);
      Despegar.ResourceManager.add("_originNotValidMsg"," - Digite a cidade de partida",region);
      Despegar.ResourceManager.add("_destinationNotValidMsg","- Digite a cidade de destino",region);
      Despegar.ResourceManager.add("_dateSalidaMayorNotValidMsg","- A data de partida deve ser anterior à data de regresso",region);
      Despegar.ResourceManager.add("_dateSalidaNotValidMsg","- Digite a data de partida",region);
      Despegar.ResourceManager.add("_dateRegresoNotValidMsg","- Digite a data de regreso",region);
      Despegar.ResourceManager.add("_originDestinationEqualNotValidMsg","- A origem e o destino não podem ser iguais",region);
      }
      else
      {
      Despegar.ResourceManager.add("_startErrorMsg","Señor Usuario, Revise los siguientes Mensajes:",region);
      Despegar.ResourceManager.add("_originNotValidMsg"," - Ingrese una ciudad de partida",region);
      Despegar.ResourceManager.add("_destinationNotValidMsg","- Ingrese una ciudad de destino",region);
      Despegar.ResourceManager.add("_dateSalidaMayorNotValidMsg","- La fecha de salida debe ser anterior a la fecha de llegada",region);
      Despegar.ResourceManager.add("_dateSalidaNotValidMsg","- La fecha de salida no es válida",region);
      Despegar.ResourceManager.add("_dateRegresoNotValidMsg","- La fecha de regreso no es válida",region);
      Despegar.ResourceManager.add("_originDestinationEqualNotValidMsg","- El origen y el destino no pueden ser iguales",region);
      }

   }
   this.validarFechas = function(oValidator)
   {
      var oFechaSalida;
      var oFechaRegreso;
      if (oBuscador.oFechas[0] == "dd/mm/aaaa" || oBuscador.oFechas[0] == "")
      {
         oValidator.isValid = false;
         oValidator.addMsgKey("_dateSalidaNotValidMsg");
      }
      else
      {
         oFechaSalida = new Despegar.Date();
         oFechaSalida.setddmmaaaa(oBuscador.oFechas[0],"/");
      }
      if (oBuscador.sTripType != "i")
      {
         if (oBuscador.oFechas[1] == "dd/mm/aaaa" ||  oBuscador.oFechas[1] == "")
         {
            oValidator.isValid = false;
            oValidator.addMsgKey("_dateRegresoNotValidMsg");
         }
         else
         {
            oFechaRegreso = new Despegar.Date();
            oFechaRegreso.setddmmaaaa(oBuscador.oFechas[1],"/");
         }
         if (oFechaSalida != null  && oFechaRegreso != null)
         {
            var comparacion;
            comparacion = oFechaSalida.compareTo(oFechaRegreso.getiso());
            if (comparacion == 1)
            {
               oValidator.isValid = false;
               oValidator.addMsgKey("_dateSalidaMayorNotValidMsg");
            }
         }
      }

   }
    //devuelve los parámetros de búsqueda en la forma <RoundTrip|OneWay>/CiudadDesde/CiudadHasta/FechaDesde/[FechaHasta]/adt/cnn/inf
    this.generateRestParams = function() {
        var departureDate = new Despegar.Date();
        var returnDate = new Despegar.Date();

        for (i = 0; i < oBuscador.aPaxGroup.length; i++) {
            oBuscador.sADT += eval(oBuscador.aPaxGroup[i].adt);
            oBuscador.sCNN += eval(oBuscador.aPaxGroup[i].cnn);
            oBuscador.sINF += eval(oBuscador.aPaxGroup[i].inf);
        }

        departureDate.setddmmaaaa(oBuscador.oFechas[0], "/");
        if (oBuscador.sTripType == "iv") {
            returnDate.setddmmaaaa(oBuscador.oFechas[1], "/");
            return "RoundTrip" + '/' + oBuscador.sOrigen + '/' + oBuscador.sDestino + '/' + departureDate.getota() + '/' + returnDate.getota() + '/' + oBuscador.sADT + '/' + oBuscador.sCNN + '/' + oBuscador.sINF;
        }
        else {
            return "OneWay" + '/' + oBuscador.sOrigen + '/' + oBuscador.sDestino + '/' + departureDate.getota() + '/' + oBuscador.sADT + '/' + oBuscador.sCNN + '/' + oBuscador.sINF;
        }
    }

    //devuelve los parámetros de búsqueda para la página de desambiguación
    this.generateDisambiguationParams = function() {
        var departureDate = new Despegar.Date();
        var returnDate = new Despegar.Date();

        for (i = 0; i < oBuscador.aPaxGroup.length; i++) {
            oBuscador.sADT += eval(oBuscador.aPaxGroup[i].adt);
            oBuscador.sCNN += eval(oBuscador.aPaxGroup[i].cnn);
            oBuscador.sINF += eval(oBuscador.aPaxGroup[i].inf);
        }

        departureDate.setddmmaaaa(oBuscador.oFechas[0], "/");
        if (oBuscador.sTripType == "iv") {
            returnDate.setddmmaaaa(oBuscador.oFechas[1], "/");
            return '?OriginLocation=' + oBuscador.sOrigen + '&DestinationLocation=' + oBuscador.sDestino + '&DepartureDate=' + departureDate.getota() + '&ReturnDate=' + returnDate.getota() + '&ADTCount=' + oBuscador.sADT + '&CNNCount=' + oBuscador.sCNN + '&INFCount=' + oBuscador.sINF + '&ItineraryType=RoundTrip&OriginLocationName=' + stripHTML(oBuscador.sDescripcionOrigen.replace("#", "%23")) + '&DestinationLocationName=' + stripHTML(oBuscador.sDescripcionDestino.replace("#", "%23"));
        }
        else {
            return '?OriginLocation=' + oBuscador.sOrigen + '&DestinationLocation=' + oBuscador.sDestino + '&DepartureDate=' + departureDate.getota() + '&ADTCount=' + oBuscador.sADT + '&CNNCount=' + oBuscador.sCNN + '&INFCount=' + oBuscador.sINF + '&ItineraryType=OneWay&OriginLocationName=' + stripHTML(oBuscador.sDescripcionOrigen.replace("#", "%23")) + '&DestinationLocationName=' + stripHTML(oBuscador.sDescripcionDestino.replace("#", "%23"));
        }
    }

this.buscar = function()
   {

      var oFields = new Array();
      //Cargo Primero los Fields Cargados Por el Usuario---
      oFields["sPaginaBuscador"] = oBuscador.sPaginaBuscador;
      oFields["OriginLocation1"] = oBuscador.sOrigen;
      oFields["DescripcionOriginLocation1"] = oBuscador.sDescripcionOrigen;
      oFields["DestinationLocation1"] = oBuscador.sDestino;
      oFields["DescripcionDestinationLocation1"] = oBuscador.sDescripcionDestino;
      oFields["sFlowType"] = "vp";
      oFields["sFlow"] = oBuscador.sFlow;
      oFields["vPais"] = oBuscador.vPais;
      oFields["FechaSalida"] = oBuscador.oFechas[0];
      oFields["FechaRegreso"] = oBuscador.oFechas[1];
      oFields["sTripType"] =  oBuscador.sTripType;
      //Preparo las fechas que necesita Resultado Busqueda de vuelos
      var auxFecha = new Despegar.Date();
      auxFecha.setddmmaaaa(oBuscador.oFechas[0],"/");
      //ESTAS FECHAS SE USABAN POR EL VIEJO CALENDARIO!
      oFields["DiaDesde"] = auxFecha.dia;
      oFields["MesDesde"] = auxFecha.mes;
      oFields["AnioDesde"] = auxFecha.anio;
	   oFields["HoraDesde"] = "";
	   oFields["HoraHasta"] = "";
		oFields["DepartureDate1"] = auxFecha.getota();
      auxFecha.setddmmaaaa(oBuscador.oFechas[1],"/");
      oFields["DepartureDate2"] = auxFecha.getota();
      //ESTAS FECHAS SE USABAN POR EL VIEJO CALENDARIO!
      oFields["DiaHasta"] = auxFecha.dia;
      oFields["AnioHasta"] = auxFecha.anio;
      oFields["MesHasta"] = auxFecha.mes;
      //----------- CARGO LA CANTIDAD DE PASAJEROS (aPaxGroup en el caso de vuelos siempre es 1 solo registro)
      for(i=0;i<oBuscador.aPaxGroup.length;i++)
      {
            oBuscador.sADT += eval(oBuscador.aPaxGroup[i].adt);
            oBuscador.sCNN +=  eval(oBuscador.aPaxGroup[i].cnn);
            oBuscador.sINF += eval(oBuscador.aPaxGroup[i].inf);
      }
      oFields["PassengerTypeQuantityADT"] = oBuscador.sADT;
      oFields["PassengerTypeQuantityCNN"] = oBuscador.sCNN;
      oFields["PassengerTypeQuantityINF"] = oBuscador.sINF;
      //---------------------------------------------------
      //---------------------------------------------------
      //-----------Genero los Fields Estaticos-------------
      oFields["urlBuscador"] = devuelveRuta(oBuscador.vPais);
      oFields["Amplitud"] = "D";
      oFields["TipoBuscador"] = "home";
		oFields["ClasePref"] = "";
      //-------------Parametros Fijos, Chequear si son necesarios!----------
      oFields["filtro_resultado"] = "A";
      oFields["sSearchCategory"] = "A";
      //oFields["rdoMismaCiudad"] = "N";
      oFields["solapa"] = "VE";
      //oFields["dHoraSalida"] = "1200";
      //oFields["dHoraLlegada"] = "1200";
      oFields["DepartureTime1"] = "";
      oFields["DepartureTime2"] = "";
		oFields["CabinPref1"] = "YC";
		oFields["RefundPenalty"] = "true";
		oFields["Set"] = "";
		oFields["MismaCiudad"] = "N";
      oFields["rdoMismaCiudad"] = "N";
      oFields["pdDias"] = "2";
		oFields["MaxStopsQuantity"] = "2";
		oFields["VendorPref1"] = "";
		oFields["VendorPref1Name"] = "";
      if (oBuscador.sSearchHotels)
      {
         searchHotelsForThisTrip(oFields);
      }

      return oFields;
   }
    // ----------------------- FIN FORMULARIO DE VUELOS!!! ---------------------

}


function searchHotelsForThisTrip(oFields)
{

   var popupsOK = true;
   for (var j=0; j<1; j++) {
      popupsOK = (popupsOK && singlewindow(j, "Despegar", 1,oFields));
   }
   window.focus();
   return popupsOK;
}

function singlewindow(num, code, total,oFields)
 {
    var windowname = code;
    try {
                var hostUrl = "/";
                 if(window.location.href.indexOf(".com.ar")>=0)
                 {
                       hostUrl = "http://www.ar.despegar.com/";
                 }
                var fields = "";
                var cantHabitaciones = "";
                var pasDistribution;
                for (var field in oFields) {
                    if (oFields[field] != null) {
                        fields += field + "-" + oFields[field] + "|";
                    }
                }
                cantHabitaciones = document.getElementById("Habitaciones").value;
                pasDistribution = oFields["PassengerTypeQuantityADT"] + oFields["PassengerTypeQuantityCNN"] + oFields["PassengerTypeQuantityINF"];
                if (pasDistribution > 4)
                  {
                     pasDistribution = 2;
                  }
                var args = "height=800,width=800,menubar=1,location=1,resizable=1,scrollbars=1,toolbar=1";
                var url = hostUrl + "search/Hotels/" + oFields["DestinationLocation1"] + "/" + getFormatedDate(oFields["FechaSalida"]) + '/' + getFormatedDate(oFields["FechaRegreso"]) + "/" + pasDistribution + "/"
                var mywin = window.open(url, windowname, args);
                mywin.focus();
          }
          catch (ignored) {
               return false;
         }
    return true;
}


//----------------------

//-----VALIDATOR---------

registerNameSpace("Despegar");

Despegar.Validator = function()
{
    this.isValid = true;
    this.aMsgKey = new Array();
   this.displayMessage = function(target,id,oResources,region)
   {
        var stringMsg ="";
      if (region == "PT")
      {

         if (target=="alert")
         {
                stringMsg += Despegar.ResourceManager.get("_startErrorMsg","PT");
                stringMsg += "\n";
            for (var i in this.aMsgKey)
            {
                        stringMsg += Despegar.ResourceManager.get(this.aMsgKey[i],"PT");
                        stringMsg += "\n";
                    }
                }
            }
      else
      {
         if (target=="alert")
         {
                stringMsg += Despegar.ResourceManager.get("_startErrorMsg","ES");
                stringMsg += "\n";
            for (var i in this.aMsgKey)
            {
                        stringMsg += Despegar.ResourceManager.get(this.aMsgKey[i],"ES");
                        stringMsg += "\n";
                    }
                }
            }
        return stringMsg;
    }
   this.addMsgKey = function(key)
   {
        this.aMsgKey.push(key);
    }
}

//----------------------

//-----DATES---------

registerNameSpace("Despegar");

//Objeto FechasDespegar
Despegar.Date = function()
{
   this.day;
   this.month;
   this.year;
   this.monthText;
   this.dayOfWeek;
   //funcion setddmmaaaa
   //descripcion: carga el objeto a partir de un string
   //fechastring: string con el valor de fecha
   //separador:string con el char separador entre dia, mes y año
   this.setddmmaaaa = function(fechastring,separador)
   {
      var aFecha = fechastring.split(separador);
      this.day  = aFecha[0];
      this.month = aFecha[1];
      this.year = aFecha[2];
   }
   this.getddmm = function()
   {
      var auxDia;
      var auxMes;
      if (this.day.length == 1)
      {
         auxDia = "0" + this.day.toString();
      }
      else
      {
         auxDia =  this.day.toString();
      }
      if (this.month.length == 1)
      {
         auxMes = "0" + this.month.toString();
      }
      else
      {
         auxMes =  this.month.toString();
      }

      return  auxDia.toString() + "/" + auxMes.toString();

   }
   this.getiso = function()
   {
      var auxDia;
      var auxMes;
      if (this.day.length == 1)
      {
         auxDia = "0" + this.day.toString();
      }
      else
      {
         auxDia =  this.day.toString();
      }
      if (this.month.length == 1)
      {
         auxMes = "0" + this.month.toString();
      }
      else
      {
         auxMes =  this.month.toString();
      }
      return this.year.toString()  + auxMes.toString() + auxDia.toString();
   }
   this.compareTo= function(sFechaIso) //recibe una fecha tipo ISO y dice si la actual es menor a la
   {
         var fechaIso = this.getiso()
         if (fechaIso < sFechaIso)
         {return -1;}
         else
         {
         if (fechaIso == sFechaIso)
            {
               return 0;
            }
            else
            {
               return 1;
            }
         }
   }
   this.getota = function()
   {
      var auxDia;
      var auxMes;
      if (this.day.length == 1)
      {
         auxDia = "0" + this.day.toString();
      }
      else
      {
         auxDia =  this.day.toString();
      }
      if (this.month.length == 1)
      {
         auxMes = "0" + this.month.toString();
      }
      else
      {
         auxMes =  this.month.toString();
      }
      return this.year.toString()  + "-" + auxMes + "-" + auxDia;
   }
}
//Objeto FechasDespegar FIN

//----------------------

//-----Form---------


registerNameSpace("Despegar");
//Objeto Formulario
Despegar.Form = function(_action,_method,_id,_name)
{
   this.action = _action;
   this.method = _method;
   this.id = _id;
   this.name = _name;
   this.oForm = document.createElement("form"); // Propiedad donde se guarda el form generado
   this.oForm.name = _name;
   this.oForm.action = _action;
//GP    this.oForm.method = _method;//"post";//con _Method da error en IE;
   this.oElements = new Array();

   this.addInput = function(name,id,value)
   {
      var inputHidden = document.createElement("input");
      inputHidden.id = id;
      inputHidden.name = name;
      inputHidden.value = value;
      inputHidden.type = "hidden";
      this.oForm.appendChild(inputHidden);
   }
//GP    this.post = function()
   {
      document.body.appendChild(this.oForm);
      //GP this.oForm.submit();
   }
}





//Funciones Genericas
function getRegion(vPais)
{
   if (vPais==10)
      return "PT";
   else
      return "ES";

}
function getCodePais(vPais)
{
   switch(vPais)
   {
      case 1:return "AR";
      break;
      case 2:return "US";
      break;
      case 5:return "UY";
      break;
      case 6:return "CL";
      break;
      case 7:return "PE";
      break;
      case 9:return "CO";
      break;
      case 10:return "BR";
      break;
      case 82:return "VE";
      break;
      case 86:return "MX";
      break;
      default:return "MX";
      break
   }
}

function gValue(id)
{
   var element = document.getElementById(id);
   if (element)
   {
      return element.value;
   }
   else
   {
      return null;
   }
}

function gObject(id)
{
   return document.getElementById(id);
}

function stripHTML(strHTML) {

    //Replace all HTML tag matches with the empty string
    var strOutput = strHTML.replace(RegExp("<(.|\n)+?>", "ig"), "");

    //Replace all < and > with &lt; and &gt;
    strOutput = strOutput.replace(RegExp("<", "ig"), "&lt;");
    strOutput = strOutput.replace(RegExp(">", "ig"), "&gt;");

    return strOutput;
}

