﻿var map;
var mapLoaded = false;
var timing;
var timResult;
var loadPopups = false;
var proccessMore = false;
var processPromotion = false;
var promotionList;
var totalResultTime;
var ShowPromotions;
var documentTitle = document.title;
var resultTotal = 0;

var isOrder = false;
var isFilter = false;
var oFilter;
var oOrder;
var inter = false;
var dist = false;
var pag = 1;
var type = false;
var filterError = false;
var jsonPoints = [];


var $ItemFilter;

function enableErrorMsg() {
    loadPopups = true;
}


function getTimming() {
    var res;
    var d = new Date();
    res = d.getTime() - timing;
    timing = d.getTime();
    return res;
}

//TODO:poner los datos correspondientes sin el Hardcode
var vPais = 1;
var iDiasAnticipo = 1;
var sDefaultValueOrigen;
var sDefaultTextOrigen;

//Establezco la cantidad de registros que se van a paginar
var hotelResults;
var hotelDrawing;
var currentPage;

var Categories = new Array();

function OcultarBuscadorPorHotel() {
    var estado = $("#buscarPorNombre").attr("checked");
    if (estado == true) {
        $("#nombreDelHotel").show();
    }
    else {
        $("#nombreDelHotel").hide();
        $("#nombreDelHotel").val("");
    }
}

function processMore(jsonHotels) {
    
    
    EnableFilters();

    if (jsonHotels != "" && jsonHotels != null) {
        
        jsonHotels = eval("(" + jsonHotels + ")");

        if (isFilter) {            
            $ItemFilter[0].obj.addOptions(oFilter); 
        }

        
        
        if (!$ItemFilter[0].obj.addJson(jsonHotels.Items, hotelDrawing.DrawingType, jsonHotels.ShowPromotions)) {
            
            if ($('#AlertNoResult').html()) 
            {
                ShowFilterError();
            } 
            else 
            {
                filterError = true;
            }
        }
    
    }

    if (jsonHotels.ShowPromotions == 1) {
         RequestPromotions();
    }
    
    
    showCount();
    GoToPage(pag);

    if (type) 
    {
        if (type == "Map") { selTab(2, 'solMapa'); }
        if (type == "Photo") { selTab(3, 'solFoto'); }
    }
    
    proccessMore = true;
    

    /* Omniture */
    if (typeof omnitureDataCollector != "undefined" && typeof json != "undefined") {
        minPrice = omniturePrecioMinimo(json);
        omnitureDataCollector.setPrecioMinimoHotel(minPrice);
    }
}


function doLogging() {
    if ((typeof Despegar).toString() == "object") {
        var reportData = new Despegar.HotelsReportLogData();
        var stage = new Despegar.FlowStage();
        var logger = new Despegar.Logger();
        reportData.ClientTime = CreateJSonDate(new Date());
        reportData.Stage = stage.HotelSearch;
        reportData.CheckIn = CreateJSonDate(getDateFromField($('#hdnCheckInDate').val()));
        reportData.CheckOut = CreateJSonDate(getDateFromField($('#hdnCheckOutDate').val()));
        reportData.Distribution = $('#lblDistributionList').text();
        reportData.Destination = $('#hdnDestination').val();
        reportData.ResultCount = resultTotal;
        reportData.ResultDelay = (totalResultTime);
        reportData.VariantTesting = "2.8";
        logger.LogReport(reportData);
    }
    
    if (typeof omnitureDataCollector != "undefined") {
        omnitureDataCollector.setCantidadDeResultados(resultTotal);
    }
}

function loadScript(name, path, callBack,charset) {
    var head = $("#Head1").get(0);
    var scriptTag;
    scriptTag = document.createElement("script");
    scriptTag.id = name;
    scriptTag.src = path;
    scriptTag.type = "text/javascript";
   // charset = 
    if (charset != undefined) {
        scriptTag.charset = charset;
    }
    if (callBack != undefined) {
        scriptTag.onload = scriptTag.onreadystatechange = callBack;
    }
    head.appendChild(scriptTag);
}

function loadCss(path, callBack) {
    var scriptTag;
    var head = $("#Head1").get(0);
    scriptTag = document.createElement("link");
    scriptTag.rel = "stylesheet";
    scriptTag.href = path;
    scriptTag.type = "text/css";
    if (callBack != undefined) {
        scriptTag.onload = scriptTag.onreadystatechange = callBack;
    }
    head.appendChild(scriptTag);
}

function showPopUpEmail() {

    $("#popupemail").removeAttr("style");

}

function showDivEmail() {
    $("#emailPopup").show();
}


function showNewSearchLink() {
    $("#newFildLt").css("visibility", "");
}

function loadHtml(destDiv, sourceDiv, sourceFile, callBack) {
    if (callBack != undefined) {
        $("#" + destDiv).load(sourceFile + " #" + sourceDiv, null, callBack);
    } else {
        $("#" + destDiv).load(sourceFile + " #" + sourceDiv);
    }

}

function Initialize() {

    /* Inicializamos filtros de estrellas */
    
    hotelDrawing = new HotelDrawing();
    Categories[0] = new CategoryFilter();
    Categories[0].Name = $("#lblStar12").text(); 
    Categories[0].From = 0;
    Categories[0].To = 2;


    Categories[1] = new CategoryFilter();
    Categories[1].Name = $("#lblStar23").text(); 
    Categories[1].From = 2;
    Categories[1].To = 3;


    Categories[2] = new CategoryFilter();
    Categories[2].Name = $("#lblStar34").text();  
    Categories[2].From = 3;
    Categories[2].To = 4;


    Categories[3] = new CategoryFilter();
    Categories[3].Name = $("#lblStar45").text();  
    Categories[3].From = 4;
    Categories[3].To = 5;

    Categories[4] = new CategoryFilter();
    Categories[4].Name = $("#lblStar5x").text();  
    Categories[4].From = 5;
    Categories[4].To = 10;

    hotelDrawing.DrawStarsFilters(Categories);

    /* Fin de inicialización de filtro de estrellas */
    
    /* Ocultamos resultado de hoteles y motramos header y footers */
    $('#HotelResults').hide();
    $('#header').show();
    $('#footer').show();
    
    /*Deshabilita filtros */
    DisableAllFilters();
    
    /* Mostramos resultados de hoteles */
    $('#ResultadosHotelesBody').show();
    $("#HotelResults").show();
    
    var url = $('#hdnUrlTopRanking').attr('value');


    //controlo que no se muestren errores en los parametros
    if (checkErrors() == false)
        return;


    if ($('#LblCantHabitaciones').text() == "1") {
        $('#roomsLiteral').text($('#roomsDescSing').text());
    }

    if ($('#LblCantPasajeros').text() == "1") {
        $('#passengersLiteral').text($('#roomsPassSing').text());
    }


    $('#LblFechaCheckIn').text($('#LblFechaCheckIn').text().substr(0, 1).toUpperCase() + $('#LblFechaCheckIn').text().substr(1, $('#LblFechaCheckIn').text().length));
    $('#LblFechaCheckIn').show();
    $('#LblFechaCheckOut').text($('#LblFechaCheckOut').text().substr(0, 1).toUpperCase() + $('#LblFechaCheckOut').text().substr(1, $('#LblFechaCheckOut').text().length));
    $('#LblFechaCheckOut').show();
    $("#promoCheck").find("input").removeAttr("checked");
    
    var CSDPhoneNumber = trim($('#CSDPhoneNumber').html());

    if (CSDPhoneNumber != "") {
        $('.hotelPhoneNumber').html(CSDPhoneNumber);
    } else {
        $('.footerPhone').hide();
    }

    if (url != null) {
                    
        $.ajax({
            url: url,
            type: "GET",
            dataType: "text",
            cache: true,
            success: processResult,
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                try {

                    $("#HotelResults").show();
                    
                }
                catch (err) {
                    // TODO: Falta analizar que hacer cuando da un error la llamada
                }

            }
        });

    }

    SaveSearchedCity();
}

function getDateFromField(dateString) {
    var sp = dateString.split("-");
    if (sp.length != 3)
        return new Date();
    else
        return new Date(sp[0], sp[1] - 1, sp[2]);
}
function ListToString(distributions) {
    
    var sepAux = "";
    var result = "";

    for (i = 0; i < distributions.length; i++) {
        var adults = distributions[i].Adults;
        var childrens = distributions[i].Children;

        result = result + sepAux + adults;
        sepAux = "!";

        for (j = 0; j < childrens.length; j++) {
            result = result + "-" + childrens[j];
        }
    }
    
    return result;
    
}
/*-------------------------------------------------------------------------------------------------*/

/* Genera la URL del Detalle de Hotel y almacena la cookie necesaria. 
 * Por URL se pasan IdHotel/FechaDesde/FechaHasta/Distribucion
 */
function hotelDetail(id, price) {
    var toUrl = "";
    var filterOptions = $ItemFilter[0].obj.getFilterOptions();
    var currentPage = $ItemFilter[0].obj.getCurrentPage();
    var type = hotelDrawing.DrawingType;
    if (filterOptions.stars && filterOptions.stars.length<5) toUrl += "#s=" + filterOptions.stars;
    if (filterOptions.name) toUrl += "#n=" + filterOptions.name;
    if (filterOptions.promo) toUrl += "#p=" + filterOptions.promo;
    var ratio = $('#moneyExchangeRatio').text();
    if (filterOptions.price1 && filterOptions.price2) toUrl += "#p1=" + ($ItemFilter[0].obj.isLocalCurrency() ? filterOptions.price1 : Math.round(filterOptions.price1 / ratio)) + "#p2=" + ($ItemFilter[0].obj.isLocalCurrency() ? filterOptions.price2 : Math.round(filterOptions.price2 / ratio));
    if (filterOptions.interest) { toUrl += "#i=" + $("#filtPoint option").index(filterOptions.interest); if (filterOptions.distance) toUrl += "#d=" + filterOptions.distance; }    
    var actualOrder = $ItemFilter[0].obj.getActualOrder();
    if (!(actualOrder.field == "Order" && actualOrder.order == "D")) toUrl += "#f=" + actualOrder.field + "#o=" + actualOrder.order;
    if (currentPage > 1) toUrl += "#pag=" + currentPage;
    if (type != "List") toUrl += "#t=" + type;
    if ($('#selMoneda').val() == "NonLocalCurrencyValue") { toUrl += "#nl=true"; } else {toUrl += "#nl=false"; };

    var actualLocation = window.location.href.split("#");

    window.location = actualLocation[0] + toUrl;


    /* Omniture */
    if (typeof omnitureDataCollector != "undefined") {
        var resultsByPage;
        var actualPage;
        var hotelSelected;
        if (parseInt(parseInt($("#CurrentHotelCount").text()) / parseInt($("#paginadoTop a:not(.paginatorArrow):last").text())) == (parseInt($("#CurrentHotelCount").text()) / parseInt($("#paginadoTop a:not(.paginatorArrow):last").text()))) {
            resultsByPage = (parseInt(parseInt($("#CurrentHotelCount").text()) / parseInt($("#paginadoTop a:not(.paginatorArrow):last").text())))
        } else {
            resultsByPage = (parseInt(parseInt($("#CurrentHotelCount").text()) / parseInt($("#paginadoTop a:not(.paginatorArrow):last").text())) + 1)
        }
        for (var i = 0; i < $(".neutral2").length; i++) {
            if ($(".neutral2:eq(" + i + ")").attr("href") != undefined) {
                actualPage = $(".neutral2:eq(" + i + ")").text();
                break;
            }
        }
        actualPage--;

        for (i = 0; i < $(".ListItem").length; i++) {
            if (parseInt($(".ListItem:eq(" + i + ")").attr("id")) == parseInt($(".buttonDisabled").parent().parent().parent().attr("id"))) {
                break;
            }
        }
        hotelSelected = parseInt(parseInt(resultsByPage) * parseInt(actualPage) + i + 1);
        omnitureDataCollector.setResultadoElegidoHotel(hotelSelected);

    }

    
    //ESTE CODIGO SE REPLICA EN DETAILSFUNCTIONS.JS DE LA PAGINA DE DETALLE (hotelDetailPage)
    
    $('#hdnProvider').val($('#HotelProvider' + id).html());
    $('#hdnHotelNameSelecion').val($('#filtName').val());
    
    if (price != undefined) {
        $('#hdnPrice').val(price);
    }
    
    var hdnCheckInDate = $('#hdnCheckInDate').val();
    var hdnCheckOutDate = $('#hdnCheckOutDate').val();
    var distribution = ListToString(JSON.parse($('#hdnDistributionList').val()));
    var destination = $('#hdnDestination').val();
    var hdnHotelNameSelecion = $('#hdnHotelNameSelecion').val();
    
	var provider = $('#hdnProvider').val();
    var jsonProvider = JSON.parse(provider);
    var strParametros = "CP=" + jsonProvider.Code + "&HP=" + encodeURIComponent(jsonProvider.HotelID) + "&SP=" + jsonProvider.SupplierType + "&P=" + $('#hdnPrice').val() + "&D=" + destination + "&HName=" + hdnHotelNameSelecion + "&HPosition=" + $ItemFilter[0].obj.getOriginalOrder(id) + "&FUrl=" + toUrl;

    var nombreCookie = id + hdnCheckInDate + hdnCheckOutDate + distribution;
	
	createCookie(nombreCookie, strParametros, 1);
}

function ChangeCombosValue(localMoney) {
    var moneyFrom = $('#moneyFrom').val();
    var moneyTo = $('#moneyTo').val();
    var ratio = $('#moneyExchangeRatio').text();

    if ((IsNumeric(moneyFrom) == true) && (moneyFrom!=""))
        moneyFrom = moneyFrom * 1;
    if ((IsNumeric(moneyTo) == true) && (moneyTo != ""))
        moneyTo = moneyTo * 1;
    if (localMoney == true)
    { 

    if ((IsNumeric(moneyFrom)==true) && (moneyFrom != ""))
    
        $('#moneyFrom').val(Math.round(moneyFrom / ratio));

    if ((IsNumeric(moneyTo) == true) && (moneyTo != ""))
        $('#moneyTo').val(Math.round( moneyTo / ratio));


    }
    else {

        if ((IsNumeric(moneyFrom) == true) && (moneyFrom != ""))
        $('#moneyFrom').val(Math.round(moneyFrom * ratio));

    if ((IsNumeric(moneyTo) == true) && (moneyTo != ""))
        $('#moneyTo').val(Math.round(moneyTo * ratio));
     }


}

function ChangeSelectedCurrency() {

    if ($('#selMoneda').val() == "NonLocalCurrencyValue") {
        $('#HotelResults').attr('class', 'ShowNonLocal');
		ChangeCombosValue(false);
		createCookie("selectedCurrency", "NonLocalCurrencyValue");
    }else{
        $('#HotelResults').attr('class', 'ShowLocal');
        ChangeCombosValue(true);
		createCookie("selectedCurrency", "LocalCurrencyValue");
    }
}

function SaveSearchedCity() {
    createCookie("searchedCity", $("#hdnDestination").val());
}

function isdefined(variable) {
    return (typeof (window[variable]) == "undefined") ? false : true;
}

var helper = null;

function processPointsOfInterest(json) {
    jsonComplete = JSON.parse(json)
    setAreas(jsonComplete.Areas);
    setPoints(jsonComplete.Points);
    if (isFilter && inter) {
        $("#RemovePointFilter").css("visibility","visible")
        var newFilter = { interest: $("#filtPoint").find("option:eq(" + inter + ")") };
        if (dist) { $("#filtDisctance").show().val(dist); newFilter.distance = dist; $("#filtDisctanceLabel").show(); }             
        $ItemFilter[0].obj.setInterest(newFilter);
        if(newFilter.interest.data("type") == "p"){
            $("#order4").show();
            $("#order4Label").show();
        }
        if (proccessMore) {
            filter(newFilter, hotelDrawing.DrawingType);
            GoToPage(pag);
        }        
        var filtPoint = document.getElementById("filtPoint");
        filtPoint.selectedIndex = inter;
    }
}

function processPromotions(json) {

    
    $('#promoFlash').addClass('Hide');
    $('#promoCheck').removeClass('Hide');
    
    if (json != "" && json != null) {
        json = eval("(" + json + ")");     
        $ItemFilter[0].obj.addPromotions(json, hotelDrawing.DrawingType);                
        showCount();
        GoToPage(pag);

        omniturePrecioMinimo(json);
    }
}

function processResult(json) {

    //console.log("Procesando Resultado");
    totalResultTime = getTimming();
    
    json = eval("(" + json + ")");
    
    var url = $('#hdnUrlMoreHotels').attr('value');
    
    ShowPromotions = json.ShowPromotions;
    resultTotal = json.ResultTotal;

    if (json != null) {
    
        //console.log("Mostrando Cantidad");
        showCount(json.ResultTotal);
        $("#filtQty").show();
    }

    if (json.ResultTotal > 0 || json.Items.length > 0) {
    
        //console.log("Hay Resultados ");
        var actualFilters = window.location.href.split("#");
        oFilter = {};
        oOrder = {};
        var field;
        var value;
        var isNonLocalValue;
        for (var i = 1; i < actualFilters.length; i++) {
            field = actualFilters[i].split("=")[0];
            value = actualFilters[i].split("=")[1];
            oFilter.interest = undefined;
            switch (field) {
                case "s":                    
                    oFilter.stars = value;
                    isFilter = true;
                    break;
                case "n":
                    oFilter.name = unescape(utf8_encode(value));
                    isFilter = true;
                    break;
                case "p":
                    oFilter.promo = value;
                    isFilter = true;
                    break;
                case "p1":
                    oFilter.price1 = parseInt(value);
                    isFilter = true;
                    break;
                case "p2":
                    oFilter.price2 = parseInt(value);
                    isFilter = true;
                    break;
                case "i":
                    inter = value;
                    isFilter = true;
                    break;
                case "d":
                    dist = value;
                    break;
                case "f":
                    oOrder.field = value;
                    isOrder = true;
                    break;
                case "o":
                    oOrder.order = value;
                    break;
                case "t":
                    type = value;
                    break;
                case "pag":
                    pag = parseInt(value);
                    break;
                case "nl":
                    isNonLocalValue = value;
                    if (isNonLocalValue == "true") {
                        $('#hdnLocalAsDefault').val("NonLocalCurrency");
                        $('#selMoneda').val("NonLocalCurrencyValue");
                    } else {
                        $('#hdnLocalAsDefault').val("LocalCurrency");
                        $('#selMoneda').val("LocalCurrencyValue");
                    }
                    break;
            }
        }
        if (!oFilter.stars) oFilter.stars = "12345";
        if (isNonLocalValue == "true") {
            var ratio = $('#moneyExchangeRatio').text();
            oFilter.price1 = Math.round(oFilter.price1 * ratio);
            oFilter.price2 = Math.round(oFilter.price2 * ratio);
        } 

        var CSDPhoneNumber = trim($('#CSDPhoneNumber').html());

        var cache = json.ShowPromotions;

        //console.log("Creando ItemFilter");
        
        $ItemFilter = $("#listaRowsList").ItemFilter({
            json: json.Items,
            page: 1,
            itemsPage: 15,
            tel: CSDPhoneNumber,
            nonLocalCurrency: $("#ltPriceFilterFromSignNonLocal").html(),
            localCurrency: $("#Label5").html(),
            hideMorePhotos: $("#hideMorePhotos").html(),
            hideLocation: $("#hideLocation").html(),
            hideDayPrice: $("#hideDayPrice").html(),
            hideFavoritoEliminar: $("#hideFavoritoEliminar").html(),
            hideFavorite: $("#hideFavorite").html(),
            hideMail: $("#hideMail").html(),
            hideImprimir: $("#hideImprimir").html(),
            hideSelect: $("#hideSelect").html(),
            type: "List",
            order: isOrder ? oOrder : null,
            ShowPromotions: json.ShowPromotions,
            StaticHost: staticHost,
            language: $("#lblCurrentLang").html(),
            nameMaxLength: 42
        });

        //console.log("Logueando");
		doLogging();

		if (json.ResultTotal > 20) {

		    //console.log("Pidiendo más resultados ");
		    
            if (url != null) {
                $.ajax({
                    url: url,
                    type: "GET",
                    cache: true,
                    dataType: "text",
                    success: processMore,
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        try {

                            $("#HotelResults").show();
                            if (isFilter) {
                                $ItemFilter[0].obj.addOptions(oFilter);
                                if (!$ItemFilter[0].obj.initialize(false, "List", cache, false)) {
                                    if ($('#AlertNoResult').html()) {
                                        ShowFilterError();
                                    } else {
                                        filterError = true;
                                    }
                                }
                            }

                            var errors = XMLHttpRequest.responseText;
                            //alert(errors);
                            //handleError(errors);
                        }
                        catch (err) {
                            //alert("AJAX Error:" + err);
                        }

                    }
                });
            }
        }
        else {
            if (json.ShowPromotions == 1) {
                RequestPromotions();
            }
            if (isFilter) {
                $ItemFilter[0].obj.addOptions(oFilter);
                if (!$ItemFilter[0].obj.initialize(false, "List", cache, false)) {
                    if ($('#AlertNoResult').html()) {
                        ShowFilterError();
                    } else {
                        filterError = true;
                    }
                }
            }
            showCount();
            GoToPage(pag);
            if (type) {
                if (type == "Map") { selTab(2, 'solMapa'); }
                if (type == "Photo") { selTab(3, 'solFoto'); }
            }
            //timResult += " createPaginationNumbers() - " + getTimming() + " - ";
            EnableFilters();
            //timResult += " EnableFilters() - " + getTimming() + " - ";
            proccessMore = true;
        }
    }

    var urlPointsAndAreasOfInterest = $('#hdnPointsAndAreasOfInterest').attr('value');
    if (urlPointsAndAreasOfInterest != null) {
        $.ajax({
        url: urlPointsAndAreasOfInterest,
            type: "GET",
            dataType: "text",
            timeout: 30000,
            success: processPointsOfInterest,
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                try {
                    //FRONT-END: que pasa cuando no se traen los puntos de interes
                }
                catch (err) {
                    //alert("AJAX Error:" + err);
                }

            }
        });
    }   

    if ($('#hdnLocalAsDefault').val() == "LocalCurrency") {
        $('#selMoneda').val("LocalCurrencyValue");
    } else {
        $('#selMoneda').val("NonLocalCurrencyValue");
    }
	ChangeSelectedCurrency();
	
    if ($('#hdnMoneyDropDownShow').val() == "false") {
        $('#showMoneyDropDown').hide();
    }

    if (json == null || json.Items.length == 0) {
        $("#Errors").hide();
        $("#Errors").text(JSON.stringify(new getJsError("", $("#lblErrNoResultTitle").text(), $("#lblErrNoResultDesc").text())));
        $("#HasErrors").text("1");
        checkErrors();
    } else {
        $('#HotelResults').show();
    }
    
    $("#footer").show();
    $("#header").show();

    if ($ItemFilter) { currentPage = $ItemFilter[0].obj.getCurrentPage(); }

    $(".Title").css("visibility", "");
    document.title = documentTitle;

    /* Omniture */
    if (typeof omnitureDataCollector != "undefined" && typeof json != "undefined") {

        minPrice = omniturePrecioMinimo(json);

        omnitureDataCollector.setPrecioMinimoHotel(minPrice);
        omnitureDataCollector.setCantidadResultadosHotel(resultTotal);
    }
}

//Return lowest price
var globalMinPrice;
function omniturePrecioMinimo(json) {
    var minPrice;
    if (json.Items) {json = json.Items; }
    for (var j in json) {
        if (minPrice) {
            if (json[j].AvgDiscountPrice < minPrice) {
                minPrice = json[j].AvgDiscountPrice;
            }
        }
        else {
            minPrice = json[j].AvgDiscountPrice;
        }
    }
    if (minPrice < globalMinPrice || !globalMinPrice) {
        globalMinPrice = minPrice;
        return minPrice;
    }
}

function ShowFilterError() {
    openMyModal($('#AlertNoResult').html());
    $('#closeNoResultButton').focus();
    ResetFiltersHmtl();
}

function RequestPromotions() {

    $('#promoCheck').addClass('Hide');
    $('#promoFlash').removeClass('Hide');
    var urlPromotion = $('#hdnUrlHotelsPromotions').attr('value');
    if (urlPromotion != null) {
        $.ajax({
            url: urlPromotion,
            type: "GET",
            dataType: "text",
            timeout: 30000,
            cache: true,
            success: processPromotions,
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                try {
                    $('#promoFlash').addClass('Hide');
                    $('#promoCheck').removeClass('Hide');
                    $ItemFilter[0].obj.errorPromotion(hotelDrawing.DrawingType);
                }
                catch (err) {
                    //alert("AJAX Error:" + err);
                }
            }
        });
    }
}

function DisableAllFilters() {

   for (var i = 0; i < 5; i++) {
       $("#FilterByStars" + i + "Name").attr("disabled", "disabled");
    }

    $("#filtName").attr("disabled", "disabled");
    $("#moneyFrom").attr("disabled", "disabled");
    $("#moneyTo").attr("disabled", "disabled");
    $("#promoCheck").find("input").attr("disabled", "disabled");
    filterVisibility();
    $("#filtQty").hide();


}

function EnableFilters() {
    for (var i = 0; i < 5; i++) {
        $("#FilterByStars" + i + "Name").removeAttr("disabled");
    } 

    /*  order1
    order2
    order1*/
    $("#filtName").removeAttr("disabled");
    $("#moneyFrom").removeAttr("disabled");
    $("#moneyTo").removeAttr("disabled");
    $("#promoCheck").find("input").removeAttr("disabled");
    filterVisibility();

    if (isFilter) { $("#removefilterstitle").text($("#deletedfilters1").text()); $("#removefilters").css("visibility", "visible"); $("#filtShowAll").show(); }
    if (isFilter && oFilter.stars) {        
        for (var i = 0; i < oFilter.stars.length; i++) {
            $("#FilterByStars" + (parseInt(oFilter.stars.substr(i, 1)) - 1) + "Name").attr("checked", true);
        }
        if (oFilter.stars.length == 1) { $("#filtStars").find("input:checked").attr("disabled", "true"); }
    } else {
        for (var i = 0; i < 5; i++) {
            $("#FilterByStars" + i + "Name").attr("checked", true);
        }
    }    
    if (isFilter && oFilter.promo) {
        $("#promoCheck").find("input").attr("checked", true);
    }
    if (isFilter && oFilter.price1 && oFilter.price2) {
        $("#moneyFrom").val(oFilter.price1);
        $("#moneyTo").val(oFilter.price2);
        $("#RemovePriceFilter").css("visibility", "visible");
    }
    if (isFilter && oFilter.name) {
        $("#filtName").val(oFilter.name);
        $("#RemoveNameFilter").css("visibility", "visible");
    }    
    if (isOrder) {
        $(".lstResults #HotelResultsContainer .Header .Title .topFilter:checked").removeAttr("checked");
        switch (oOrder.field) {
            case 'Order':
                $("#order1").attr("checked", true);
                break;
            case 'CurrentPrice':
                $("#order2").attr("checked", true);
                break;
            case 'Category':
                $("#order3").attr("checked", true);
                break;
            case 'distance':
                $("#order4").attr("checked", true).show();
                $("#order4Label").show();
                break;
        }
    }
}


function validateNumeic(OField) {
    if (IsNumeric(OField.value) == false) {
        OField.value = "";
    }
    filterVisibility();
}

function filterVisibility() {
    var mFrom = $("#moneyFrom").val();
    var mTo = $("#moneyTo").val();
    var fname = $("#filtName").val();
    if ((trim(mFrom) == "") & (trim(mTo) == "")) {
        $("#filtBtn1").attr("disabled", "disabled");
        $("#filtBtn1").removeClass("btnSmallBlue");
        $("#filtBtn1").addClass("btnSmallDisabled");

    } else {

        $("#filtBtn1").removeAttr("disabled");
        $("#filtBtn1").removeClass("btnSmallDisabled");
        $("#filtBtn1").addClass("btnSmallBlue");

    }
    if (trim($("#filtName").val()) == "") {

        $("#filtBtn2").attr("disabled", "disabled");
        $("#filtBtn2").removeClass("btnSmallBlue");
        $("#filtBtn2").addClass("btnSmallDisabled");
    } else {

        $("#filtBtn2").removeAttr("disabled");
        $("#filtBtn2").removeClass("btnSmallDisabled");
        $("#filtBtn2").addClass("btnSmallBlue");

    }
}

function IsNumeric(sText) {
    var ValidChars = "0123456789.";
    var IsNumber = true;
    var Char;


    for (i = 0; i < sText.length && IsNumber == true; i++) {
        Char = sText.charAt(i);
        if (ValidChars.indexOf(Char) == -1) {
            IsNumber = false;
        }
    }
    return IsNumber;

}

var _regionHtml = "";

function newFind() {        
    var spDesde;
    var spHasta;
    var sp;
    var i;
    var j;

    spDesde = $('#hdnCheckInDate').val().split(/-/ig);
    spHasta = $('#hdnCheckOutDate').val().split(/-/ig);    
    
    if (_regionHtml == "") {
        _regionHtml = $('#divNuevaBusqueda').html();

        $('#divNuevaBusqueda').html("");
    }
    
    openMyModal(_regionHtml);

    $('.searchBoxHotels').searchBoxHotels({
        'language': ($("#lblCurrentLang").text()),
        'maxroomsquantity': 4,
        'maxcnnroom': 3,
        'maxpaxroom': 4,
        'searchflow': 'Revancha',
        'showYearOld': true,
        'showBestPrice': true,
        'btnClass': 'btnBlue',
        'searchByName': true,
        'defaultdestination': ($('#hdnDestination').val()),
        'defaultdestinationdesc': ($('#LblNombreDestino').text()),
        'departureDate': ((spDesde[2] * 1) + "/" + (spDesde[1] * 1) + "/" + spDesde[0]),
        'returnDate': ((spHasta[2] * 1) + "/" + (spHasta[1] * 1) + "/" + spHasta[0]),
        'distribution': $('#lblDistributionList').text(),
        'abTesting': false
    });

    $('.modal-window').css("position", "absolute");
    $('#NuevaBusqueda').show();
}

function newFindErr() {
    var spDesde;
    var spHasta;
    var sp;
    var i;
    var j;

    spDesde = $('#hdnCheckInDate').val().split(/-/ig);
    spHasta = $('#hdnCheckOutDate').val().split(/-/ig);

    if (_regionHtml == "") {
        _regionHtml = $('#divNuevaBusqueda').html();

        $('#divNuevaBusqueda').html("");
    }

    openMyModal(_regionHtml);

    $('.searchBoxHotels').searchBoxHotels({
        'language': ($("#lblCurrentLang").text()),
        'maxroomsquantity': 4,
        'maxcnnroom': 3,
        'maxpaxroom': 4,
        'searchflow': 'Revancha',
        'showYearOld': true,
        'showBestPrice': true,
        'btnClass': 'btnBlue',
        'searchByName': true,
        'defaultdestination': ($('#hdnDestination').val()),
        'defaultdestinationdesc': ($('#LblNombreDestino').text()),
        'departureDate': ((spDesde[2] * 1) + "/" + (spDesde[1] * 1) + "/" + spDesde[0]),
        'returnDate': ((spHasta[2] * 1) + "/" + (spHasta[1] * 1) + "/" + spHasta[0]),
        'distribution': $('#lblDistributionList').text(),
        'abTesting': false
    });

    $('.modal-window').css("position", "absolute");
    $('#NuevaBusqueda').show();
}