﻿/// <reference path="../jquery-1.3.2-vsdoc2.js" />
//Variaveis para controle de quantidade de pesquisas e tempo entre elas.
var numPerTryMaxInternational = 10;
var numPerTryMaxNational = 10;
var SecondTryForNoResults = true;
var numReloading = 0;
var timeHideWarningSelect = 5;
var isSecondTryFinished = true;
var WarningSelectActive = false;
var tmrSearchFlights = null;

var numPerTryMax = numPerTryMaxInternational;
var numTryTimeSecond = 4;

var AllFlights = null;
var Flights = null;
var FlightsFiltered = null
var Segments = null;
var Matrix = null;
var MatrixPage = null;
var MatrixPages = null;
var index = 0;
var numRows = 0;
var numPerPage = 10;
var numPerTry = 0;
var page = 1;
var template01 = null;
var journeyIndexJS = 0;

//Variaveis que guardam as journeys selecionadas.
var AirLineSelectedGo = '';
var AirLineSelectedBack = '';
var DepartureSelectedGo = '';
var ArrivalSelectedGo = '';
var DepartureSelectedBack = '';
var ArrivalSelectedBack = '';
var journeyIdSelectedGo = null;
var journeyIdSelectedBack = null;
var TrackCredentialIdSelectedGo = null;
var TrackCredentialIdSelectedBack = null;
var amountPriceMin = null;
var amountPriceMax = null;
var AmountPriceGo = null;
var AmountPriceBack = null;
var NumberOfPlots = null;
var DepartureGoTimeMin = null;
var DepartureGoTimeMax = null;
var DepartureBkTimeMin = null;
var DepartureBkTimeMax = null;

//Variavel para informar se todos os resultados já retornaram.
var IsFinished = false;

//Variável para informar se a busca está sendo executada ou não.
var IsActive = false;

//Variaveis que guardam a origem e destino que estao na tela, quantidade de pessoas, e se existe criancas na pesquisa
var Departure = '';
var Arrival = '';
var DepartureDayPeriod = '';
var ArrivalDayPeriod = '';
var DepartureDate = '';
var ArrivalDate = '';
var PaxQuantity = 0;
var ExistsKids = false;
var IsInternational = false;
var IsOnlyGo = false;
var isGoOrBackSlide = false;
var TextSelect = ''
var TextReserv = ''
var Order = "";
var OrderType = "";
//---------------------
var CompanyFilterIsActive = false;
var AmountPriceStopFilterIsActive = false;
var DayPeriodFilterIsActive = false;
var AmountPriceFilterIsActive = false;
var AirportFilterIsActive = false;
var AmountPriceFilterMin = 0;
var AmountPriceFilterMax = 0;
var Currency = "";
var index = 0;

//HOMOLOG
//var URL = "http://passagens-aereas.homolog.viajanet.com.br/webservices/WSFlight.asmx";
//PROD
//var URL = 'http://passagens-aereas.viajanet.com.br/webservices/WSFlight.asmx';
//DESENV
var URL;
$(document).ready(function() {
    URL = GetBaseUrlWS() + '/WSFlight.asmx';
});

var MatrixPageCount = null;

//Objetos dos filtros
var dayperiodfilterchecked = new DayPeriodFilterChecked(true, true, true, true);
var amountpricestopfilterchecked = new AmountPriceStopFilterChecked(true, true, true);

companyFilterChecked = new Array();
airportFilterChecked_0 = new Array();
airportFilterChecked_1 = new Array();


var BestPrice0Stop = 0;
var BestPrice1Stop = 0;
var BestPrice2Stop = 0;


//Prototypes ********************************************************************
//#region
var templateMatrix = null;
var templatePrincipalMatrix = null;
//Paginação matrix
var MatrixPage = null;
Array.prototype.contains = function(obj) { var i = this.length; while (i--) { if (this[i] === obj) { return true; } } return false; }
//#endregion

//Métodos de acesso ao WebService ***********************************************
//#region


//Prototypes ********************************************************************
//#region
Array.prototype.contains = function(obj) { var i = this.length; while (i--) { if (this[i] === obj) { return true; } } return false; }
//#endregion

var matrixstruct = function(currencyCode, directPrice, mainAirlineCode, mainAirlineName, oneStopPrice, sort, TwoormoreStopPrice, urlLogo) {
    this.CurrencyCode = currencyCode;
    this.DirectPrice = directPrice;
    this.MainAirlineCode = mainAirlineCode;
    this.MainAirlineName = mainAirlineName;
    this.OneStopPrice = oneStopPrice;
    this.Sort = sort;
    this.TwoOrMoreStopPrice = TwoormoreStopPrice;
    this.UrlLogo = urlLogo;
};

var matrixstruct_dados = function(currencyCode, mainAirlineCode, mainAirlineName, urlLogo, StopsGroupDirect, StopsGroupOne, TwoOrMoreStop, combopriceGroup) {
    this.currencyCode = currencyCode;
    this.ciaCode = mainAirlineCode;
    this.ciaName = mainAirlineName;
    this.UrlLogo = urlLogo;
    this.combopriceGroup = combopriceGroup;
    this.StopsGroupDirect = StopsGroupDirect;
    this.StopsGroupOne = StopsGroupOne;
    this.TwoOrMoreStop = TwoOrMoreStop;
};

function FilterIsFinished() {
    var fiterActive = false;

    if (CompanyFilterIsActive || AmountPriceStopFilterIsActive || DayPeriodFilterIsActive ||
            AmountPriceFilterIsActive || AirportFilterIsActive) {
        fiterActive = true;
    }
    return fiterActive;
}

function ShowLoading() {
    //Carregando
    if (IsFinished) {
        $("#divLoading").hide();
        $("#h6Loading").hide();
    }
}

function FlightFilter() {

    var resultsTmp = AllFlights;

    return resultsTmp;
}

function isOnTime(time, goBk) {
    if (goBk == 0) {
        if (DepartureGoTimeMin != null && DepartureGoTimeMax != null)
            return time >= DepartureGoTimeMin && time <= DepartureGoTimeMax;
        else if (DepartureGoTimeMin != null)
            return time >= DepartureGoTimeMin;
        else if (DepartureGoTimeMax != null)
            return time <= DepartureGoTimeMax;
        return false;
    }
    if (DepartureBkTimeMin != null && DepartureBkTimeMax != null)
        return time >= DepartureBkTimeMin && time <= DepartureBkTimeMax;
    else if (DepartureBkTimeMin != null)
        return time >= DepartureBkTimeMin;
    else if (DepartureBkTimeMax != null)
        return time <= DepartureBkTimeMax;

    return false;
}

function GetAllFlightClient(indexParam, reloadMatrix) {
    index = indexParam;

    var resultsTmp = AllFlights;
    if ((AirLineSelectedGo != null && AirLineSelectedGo != '') && journeyIndexJS == 1) {
        resultsTmp = jLinq.from(resultsTmp)
        .equals("MainAirlineCode", AirLineSelectedGo)
            .select();
    }

    if ((AirLineSelectedBack != null && AirLineSelectedBack != '') && journeyIndexJS == 0) {
        resultsTmp = jLinq.from(resultsTmp)
        .equals("MainAirlineCode", AirLineSelectedBack)
            .select();
    }

    //    //Filtra no resultado os aeroportos escolhido na ida para as cias Webjet, OceanAir e Trip
    //    if ((DepartureSelectedGo != null && DepartureSelectedGo != '') && journeyIndexJS == 1 &&
    //			(AirLineSelectedGo == 'WH' ||
    //			AirLineSelectedGo == 'O6' || 
    //			AirLineSelectedGo == '8R' ||
    //			AirLineSelectedGo == 'AD' ||
    //			AirLineSelectedGo == 'G3')) 
    //	{
    //        resultsTmp = jLinq.from(resultsTmp)
    //            .equals("ArrivalAirport", DepartureSelectedGo)
    //            .andEquals("DepartureAirport", ArrivalSelectedGo)
    //            .select();
    //    }

    //    //Filtra no resultado os aeroportos escolhido na volta para as cias Webjet, OceanAir e Trip
    //    if ((DepartureSelectedBack != null && DepartureSelectedBack != '') && journeyIndexJS == 0 &&
    //			(AirLineSelectedBack == 'WH' ||
    //			AirLineSelectedBack == 'O6' || 
    //			AirLineSelectedGo == '8R' ||
    //			AirLineSelectedGo == 'AD' ||
    //			AirLineSelectedGo == 'G3'))  
    //			
    //	{
    //        resultsTmp = jLinq.from(resultsTmp)
    //            .equals("ArrivalAirport", DepartureSelectedBack)
    //            .andEquals("DepartureAirport", ArrivalSelectedBack)
    //            .select();
    //    }

    //Filtra resultado para a mesma trackcredentialid, para quando existir 2 credenciais para a mesma cia aerea escolha somente de 1 credencial.
    if (TrackCredentialIdSelectedGo != null && journeyIndexJS == 1) {
        resultsTmp = jLinq.from(resultsTmp)
            .equals("TrackCredentialId", TrackCredentialIdSelectedGo)
            .select();
    }

    //Filtra resultado para a mesma trackcredentialid, para quando existir 2 credenciais para a mesma cia aerea escolha somente de 1 credencial.
    if (TrackCredentialIdSelectedBack != null && journeyIndexJS == 0) {
        resultsTmp = jLinq.from(resultsTmp)
            .equals("TrackCredentialId", TrackCredentialIdSelectedBack)
            .select();
    }

    if (amountPriceMin != null && amountPriceMax != null) {
        resultsTmp = jLinq.from(resultsTmp)
        .where(function(rec, helper) {
            return (Math.round(Number(rec.AmountPrice.toString().replace(",", "."))) >= amountPriceMin && Math.round(Number(rec.AmountPrice.toString().replace(",", "."))) <= amountPriceMax);
        })
       .select();
    }

    if (DepartureGoTimeMin != null || DepartureGoTimeMax != null) {
        resultsTmp = jLinq.from(resultsTmp)
                     .where(function(rec) {
                         return isOnTime(rec.DepartureTime, 0);
                     })
                     .select();
    }

    if (DepartureBkTimeMin != null || DepartureBkTimeMax != null) {
        resultsTmp = jLinq.from(resultsTmp)
                     .where(function(rec) {
                         return isOnTime(rec.DepartureTimeBack, 1);
                     })
                     .select();
    }


    if (!amountpricestopfilterchecked.stop0) {
        resultsTmp = jLinq.from(resultsTmp)
	        .where(function(rec, helper) {
	            return (rec.Stops != 0);
	        })
            .select();

        /*if (IsInternational) {
        resultsTmp = jLinq.from(resultsTmp)
        .where(function(rec, helper) {
        return (rec.StopsBack != 0);
        })
        .select();
        }*/
    }

    if (!amountpricestopfilterchecked.stop1) {
        resultsTmp = jLinq.from(resultsTmp)
        .where(function(rec, helper) {
            return (rec.Stops != 1);
        })
            .select();

        /*if (IsInternational) {
        resultsTmp = jLinq.from(resultsTmp)
        .where(function(rec, helper) {
        return (rec.StopsBack != 1);
        })
        .select();
        }*/
    }

    if (!amountpricestopfilterchecked.stop2) {
        resultsTmp = jLinq.from(resultsTmp)
        .where(function(rec, helper) {
            return (rec.Stops < 2);
        })
            .select();

        /*if (IsInternational) {
        resultsTmp = jLinq.from(resultsTmp)
        .where(function(rec, helper) {
        return (rec.StopsBack != 2);
        })
        .select();
        }*/
    }

    $(companyFilterChecked).each(function(index) {
        if (!companyFilterChecked[index].value) {
            resultsTmp = jLinq.from(resultsTmp)
                .where(function(rec, helper) {
                    return (rec.MainAirlineName != companyFilterChecked[index].company);
                })
            .select();
        }
    });

    $(airportFilterChecked_0).each(function(index) {
        if (!airportFilterChecked_0[index].value) {
            resultsTmp = jLinq.from(resultsTmp)
                .where(function(rec, helper) {
                    return (rec.DepartureAirport != airportFilterChecked_0[index].airport);
                })
            .select();
        }
    });

    $(airportFilterChecked_1).each(function(index) {
        if (!airportFilterChecked_1[index].value) {
            resultsTmp = jLinq.from(resultsTmp)
                .where(function(rec, helper) {
                    return (rec.ArrivalAirport != airportFilterChecked_1[index].airport);
                })
            .select();
        }
    });

    asc = (OrderType == "asc" || OrderType == "");
    if (Order == "" || Order == "price") {
        if (asc) {
            resultsTmp = jLinq.from(resultsTmp)
		        .orderBy("AmountPrice")
		        .select();
        }
        else {
            resultsTmp = jLinq.from(resultsTmp)
		        .orderBy("-AmountPrice")
		        .select();
        }
    }

    if (Order == "departure") {
        if (asc) {
            resultsTmp = jLinq.from(resultsTmp)
		        .orderBy("DepartureDateTime")
		        .select();
        }
        else {
            resultsTmp = jLinq.from(resultsTmp)
		        .orderBy("-DepartureDateTime")
		        .select();
        }
    }

    if (Order == "arrival") {
        if (asc) {
            resultsTmp = jLinq.from(resultsTmp)
		        .orderBy("ArrivalDateTime")
		        .select();
        }
        else {
            resultsTmp = jLinq.from(resultsTmp)
		        .orderBy("-ArrivalDateTime")
		        .select();
        }
    }

    numRows = resultsTmp.length;

    if (reloadMatrix && (AirLineSelectedGo == null || AirLineSelectedGo == '') && (AirLineSelectedBack == null || AirLineSelectedBack == '')) {

        var matrix = [];
        var stopd = false;
        var stop1 = false;
        var stop2 = false;
        for (i = 0; i < resultsTmp.length; i++) {
            stopd = false;
            stop1 = false;
            stop2 = false;
            var matrixDados = new matrixstruct_dados();
            matrixDados.ciaName = resultsTmp[i].MainAirlineName;
            matrixDados.combopriceGroup = resultsTmp[i].AmountPrice;
            matrixDados.UrlLogo = resultsTmp[i].UrlLogo;
            matrixDados.ciaCode = resultsTmp[i].MainAirlineCode;
            matrixDados.currencyCode = resultsTmp[i].CurrencyCode;
            if (resultsTmp[i].Stops == 0 && stopd == false) {
                matrixDados.StopsGroupDirect = 0;
                stopd = true;
            }
            if (resultsTmp[i].Stops == 1 && stop1 == false) {
                matrixDados.StopsGroupOne = 1;
                stop1 = true;
            }
            if (resultsTmp[i].Stops > 1 && stop2 == false) {
                matrixDados.TwoOrMoreStop = 2;
                stop2 = true;
            }
            if (typeof matrixDados.StopsGroupDirect == 'undefined')
                matrixDados.StopsGroupDirect = -1;
            if (typeof matrixDados.StopsGroupOne == 'undefined')
                matrixDados.StopsGroupOne = -1;
            if (typeof matrixDados.TwoOrMoreStop == 'undefined')
                matrixDados.TwoOrMoreStop = -1;

            if (!findMatrix(matrix, matrixDados))
                matrix.push(matrixDados);
        }

        var amountPriceStop0 = jLinq.from(matrix)
                    .where(function(r) {
                        return r.StopsGroupDirect == 0;
                    })
                    .groupBy("ciaName")
                    .select(function(r) {
                        return {
                            ciaName: r.key,
                            stopsGroup: r.items[0].StopsGroupDirect,
                            combopriceGroup: jLinq.from(r.items).min("combopriceGroup"),
                            UrlLogo: r.items[0].UrlLogo,
                            ciaCode: r.items[0].ciaCode,
                            currencyCode: r.items[0].currencyCode
                        };
                    });

        var amountPriceStop1 = jLinq.from(matrix)
                    .where(function(r) {
                        return r.StopsGroupOne == 1;
                    })
                    .groupBy("ciaName")
                    .select(function(r) {
                        return {
                            ciaName: r.key,
                            stopsGroup: r.items[0].StopsGroupOne,
                            combopriceGroup: jLinq.from(r.items).min("combopriceGroup"),
                            UrlLogo: r.items[0].UrlLogo,
                            ciaCode: r.items[0].ciaCode,
                            currencyCode: r.items[0].currencyCode
                        };
                    });

        var amountPriceStop2 = jLinq.from(matrix)
                    .where(function(r) {
                        return r.TwoOrMoreStop > 1;
                    })
                    .groupBy("ciaName")
                    .select(function(r) {
                        return {
                            ciaName: r.key,
                            stopsGroup: r.items[0].TwoOrMoreStop,
                            combopriceGroup: jLinq.from(r.items).min("combopriceGroup"),
                            UrlLogo: r.items[0].UrlLogo,
                            ciaCode: r.items[0].ciaCode,
                            currencyCode: r.items[0].currencyCode
                        };
                    });

        matrix = jLinq.from(amountPriceStop0)
                    .union(amountPriceStop1)
                    .union(amountPriceStop2)
                    .orderBy("combopriceGroup", "ciaName", "stopsGroup")
                    .select();
        var company = jLinq.from(matrix)
                        .groupBy("ciaName")
                        .select(function(r) {
                            return {
                                ciaName: r.key,
                                stopsGroup: r.items[0].stopsGroup,
                                combopriceGroup: r.items[0].combopriceGroup,
                                UrlLogo: r.items[0].UrlLogo,
                                ciaCode: r.items[0].ciaCode,
                                currencyCode: r.items[0].currencyCode
                            };
                        });
        var matrixFinal = [];
        for (i = 0; i < company.length; i++) {
            var matrixDados = new matrixstruct();
            matrix2 = jLinq.from(matrix)
                    .where(function(rec) { return rec.ciaName == company[i].ciaName; })
                    .orderBy("stopsGroup")
                    .select();

            for (j = 0; j < matrix2.length; j++) {
                if (j == 0) {
                    matrixDados.CurrencyCode = matrix2[j].currencyCode;
                    matrixDados.UrlLogo = matrix2[j].UrlLogo;
                    matrixDados.MainAirlineCode = matrix2[j].ciaCode;

                    var ciaName = matrix2[j].ciaName.split("&nbsp;")[0];
                    if (ciaName == 'Air') {
                        matrix2[j].ciaName = matrix2[j].ciaName;
                    }
                    else {
                        matrix2[j].ciaName = matrix2[j].ciaName.split("&nbsp;")[0];
                    }
                    matrixDados.MainAirlineName = matrix2[j].ciaName;
                    matrixDados.Sort = 1;
                }
                if (matrix2[j].stopsGroup == 0)
                    matrixDados.DirectPrice = matrix2[j].combopriceGroup;
                else if (matrix2[j].stopsGroup == 1)
                    matrixDados.OneStopPrice = matrix2[j].combopriceGroup;
                else if (matrix2[j].stopsGroup > 1)
                    matrixDados.TwoOrMoreStopPrice = matrix2[j].combopriceGroup;
            }
            if (typeof (matrixDados.DirectPrice) == 'undefined')
                matrixDados.DirectPrice = '';
            if (typeof (matrixDados.OneStopPrice) == 'undefined')
                matrixDados.OneStopPrice = '';
            if (typeof (matrixDados.TwoOrMoreStopPrice) == 'undefined')
                matrixDados.TwoOrMoreStopPrice = '';

            matrixFinal[matrixFinal.length] = matrixDados;
        }
        result = jLinq.from(matrixFinal).ignoreCase().where(function(rec, helper) {
            return (rec.DirectPrice != 0 || rec.OneStopPrice != 0 || rec.TwoOrMoreStopPrice != 0);
        }).select();

        if (result.length > 0) {
            pagesize = 5;
//            Matrix = jLinq.from(result).take(5);
//            MatrixPage = jLinq.from(result).skipTake(5, result.length);

            matrixpagecount = Math.ceil(result.length / pagesize);
            MatrixPages = new Array();
            for (var i = 0; i <= matrixpagecount - 1; i++) {
                MatrixPages[i] = jLinq.from(result).skipTake((i * pagesize), pagesize);
            }

            //Inclui a coluna melhor preço na matrix.
            BestPrice0Stop = ((amountPriceStop0.length == 0) ? 0 : jLinq.from(amountPriceStop0).min("combopriceGroup"));
            BestPrice1Stop = ((amountPriceStop1.length == 0) ? 0 : jLinq.from(amountPriceStop1).min("combopriceGroup"));
            BestPrice2Stop = ((amountPriceStop2.length == 0) ? 0 : jLinq.from(amountPriceStop2).min("combopriceGroup"));

            for (var i = 0; i <= MatrixPages.length - 1; i++) {
                MatrixPages[i] = jLinq.from(
				{
				    MainAirlineCode: '',
				    MainAirlineName: '',
				    UrlLogo: ' ',
				    CurrencyCode: jLinq.from(result).select('CurrencyCode')[0].CurrencyCode,
				    DirectPrice: BestPrice0Stop,
				    OneStopPrice: BestPrice1Stop,
				    TwoOrMoreStopPrice: BestPrice2Stop,
				    Sort: 0
				}).union(MatrixPages[i])
				.orderBy('Sort', 'DirectPrice')
				.select();
            }

//            Matrix = jLinq.from(
//            {
//                MainAirlineCode: '',
//                MainAirlineName: '', //"Melhor Preço",
//                UrlLogo: ' ',
//                CurrencyCode: jLinq.from(result).select("CurrencyCode")[0].CurrencyCode,
//                DirectPrice: BestPrice0Stop,
//                OneStopPrice: BestPrice1Stop,
//                TwoOrMoreStopPrice: BestPrice2Stop,
//                Sort: 0
//            }).union(result)
//            .orderBy("Sort", "DirectPrice")
//            .select();

//            if (MatrixPage.length > 0) {
//                MatrixPage = jLinq.from(
//                {
//                    MainAirlineCode: '',
//                    MainAirlineName: '', //"Melhor Preço",
//                    UrlLogo: ' ',
//                    CurrencyCode: jLinq.from(result).select("CurrencyCode")[0].CurrencyCode,
//                    DirectPrice: BestPrice0Stop,
//                    OneStopPrice: BestPrice1Stop,
//                    TwoOrMoreStopPrice: BestPrice2Stop,
//                    Sort: 0
//                }).union(MatrixPage)
//                .orderBy("Sort", "DirectPrice")
//                .select();
//            }
            $(".resultado").removeClass("resultado resultado-vazio").addClass("resultado");
            $("#txtDynamic").removeClass("txtDynamic-noResult");
        }
        else {

            $(".resultado").addClass("resultado resultado-vazio");
            $("#txtDynamic").addClass("txtDynamic-noResult");
            MatrixPages = null;
            //Matrix = null;
            //            MatrixPage = null;
        }
    }
    else {
        MatrixPages = null;
        //Matrix = null;
        //MatrixPage = null;
    }
    Flights = resultsTmp; //jLinq.from(resultsTmp)
    //.skipTake(index, numPerPage);

    GenerateList();
    if (IsFinished) {
        //Se estiver finalizado, mas nao tiver trazido nenhum voo tenta mais uma vez.
        //        if (!isSecondTryFinished && (Flights == null || (Flights != null && Flights.length == 0))) {
        //            IsFinished = false;
        //            numPerTry -= 1;
        //            isSecondTryFinished = true;
        //        }
        //        else {
        $(document).stopTime('controlled');
        numPerTry = numPerTryMax + 1;
        ShowLoading();
        //}
    }

    if (numPerTry >= numPerTryMax && ((Flights != null && Flights.length == 0) || Flights == null) && isSecondTryFinished && !IsInSearchVerify()) {//cosulta sem resultados
        //$("#msgError").hide();
        $("#Geral").hide();
        $("#msgFilterEmpty").hide();
        $("#loadingFlight").hide();
        $("#loadingBlock").hide();
        $("#msgEmpty").show();
        analyticsLogNoResults();
        $("#semResultadoBusca").show();

        try {
            LoadingDataHide();
            $('#loadingData').height(0);
            $('.CarregandoPequeno').hide();
        }
        catch (ex) {
            $('#loadingData').height(0);
        }
        $("#flightResultSearch").hide();
    }
    else {
        if (numPerTry >= numPerTryMax && isSecondTryFinished && (Flights == null || Flights.length == 0)) {//sem resultado devido a filtros
            $("#msgEmpty").hide();
            $("#semResultadoBusca").hide();
            $("#loadingFlight").hide();
            $("#loadingBlock").hide();
            $("#msgEmpty").hide();
            $("#Geral").show();
            $("#msgFilterEmpty").show();
            try {
                LoadingDataHide();
                $('#loadingData').height(0);
                $('.CarregandoPequeno').hide();
            }
            catch (ex) {
                $('#loadingData').height(0);
                $('.CarregandoPequeno').hide();
            }
            $("#flightResultSearch").hide();
        }
    }

    try {
        LoadingDataHide();
        $('#loadingData').height(0);
        $('.CarregandoPequeno').hide();
    }
    catch (ex) {
        $('#loadingData').hide();
        $('.CarregandoPequeno').hide();
    }
}
var haveLowFare = false;
//Métodos de acesso ao WebService ***********************************************
//#region
function GetAllFlights(indexParam, reloadFilter) {

    ShowLoading();
    if (numPerTry > numPerTryMax && !IsFinished) {
        //Se nas primeiras X tentantivas não trouxer nenhum resultado, tenta mais x tentativas para procurar resultados.
        if (!SecondTryForNoResults && (Flights == null || (Flights != null || Flights.length == 0))) {
            numPerTry = 1;
            SecondTryForNoResults = true;
        }
        else {
            IsFinished = true;
            IsActive = false;

            /*if (!IsInSearchVerify()) {
            if (!FilterIsFinished()) {
            SetFilters();
            numPerTry = 1;
            }
            }*/
            ShowLoading();
            //return;
        }
    }

    IsActive = true;
    if (journeyIndexJS == 0) {
        $("#btnVolta").addClass("bt-volta-desabilitado").removeClass("bt-volta");
        $("#btnIda").addClass("bt-ida").removeClass("bt-ida-desabilitado");
    }
    else {
        $("#btnIda").addClass("bt-ida-desabilitado").removeClass("bt-ida");
        $("#btnVolta").addClass("bt-volta").removeClass("bt-volta-desabilitado");
        $("#principalMatrix").hide("slow");
    }

    index = indexParam;
    if (index == 0) { page = 1; }

    if (reloadFilter) {
        amountPriceMin = null;
        amountPriceMax = null;
    }

    // usa o identificador único de sessão para acessar o web methodo
       var guidSession = $('[id$=hSessionGuid]').val();
       
    try {
    	$.ajax({
    		type: "POST",
    		url: URL + "/GetFlights",
    		data: "{isFinished:" + IsFinished + ", guidSession:'" + guidSession + "'}",
    		contentType: "application/json; charset=utf-8",
    		dataType: "json",
    		success: function (response) {
    			//Se não retornou erro no WS, faz o carregamento normal da tela, caso contrário só incrementa o contador de tentativas
    			if (!response.d.Error) {

    				//Variaveis sao carregadas com retorno do metodo do webservice
    				AllFlightsTmp = (typeof response.d.Flight) == 'string' ? eval('(' + response.d.Flight + ')') : response.d.Flight;
    				Segments = (typeof response.d.Segment) == 'string' ? eval('(' + response.d.Segment + ')') : response.d.Segment;

    				numRows = response.d.Quantity;
    				if (numRows > 0)
    					haveLowFare = AllFlightsTmp[0].LowFareId != 0;
    				try {
    					$("#trackId").empty();
    					$("#trackId").html(response.d.TrackId);
    				}
    				catch (ex) { }

    				if (!IsFinished) {
    					IsFinished = response.d.Finished;
    					if (IsFinished)
    						clearInterval(tmrSearchFlights);
    				}
    				if (numRows > 0) {
    					$("#Geral").show();
    					$("#loadingFlight").hide();
    					$("#loadingBlock").hide();
    					LoadingDataShow();
    					$("#semResultadoBusca").hide();
    					$("#msgEmpty").hide();
    				}
    				else {
    					if (response.d.Finished) {
    						$("#loadingBlock").hide();
    						$("#loadingFlight").hide();
    						$("#semResultadoBusca").show();
    						//alert("else");
    					}
    				}

    				DepartureDate = response.d.DepartureDate;
    				ArrivalDate = response.d.ArrivalDate;

    				DepartureDayPeriod = response.d.DepartureDayPeriod;
    				ArrivalDayPeriod = response.d.ArrivalDayPeriod;

    				Departure = Segments[journeyIndexJS].DepartureAirportName;
    				Arrival = Segments[journeyIndexJS].ArrivalAirportName;
    				PaxQuantity = response.d.PaxQuantity;
    				ExistsKids = response.d.ExistsKids;
    				IsInternational = response.d.IsInternational;
    				IsOnlyGo = response.d.IsOnlyGo;

    				if (IsInternational) {
    					numPerTryMax = numPerTryMaxInternational;
    				}
    				else {
    					numPerTryMax = numPerTryMaxNational;
    				}

    				IsActive = false;

    				if (AllFlightsTmp != null) {
    					if (AllFlights == null || (AllFlightsTmp.length != AllFlights.length || (IsFinished && numRows == 0))) {
    						AllFlights = AllFlightsTmp;
    						GetAllFlightClient(indexParam, true);
    						GenerateMatrix();
    					}

    					if (AllFlights.length != 0) {
    						if (reloadFilter) {
    							if (!FilterIsFinished()) {
    								$("#tituloResultados").show("slow");
    								SetFilters();
    							}
    						}
    					}
    				}

    				try {
    					LoadingDataHide();
    				}
    				catch (ex) {
    					$('#loadingData').hide();
    					$('.CarregandoPequeno').hide();

    				}
    			}
    			else {

    				if (response.d.TrackId == -1) {
    					IsActive = false;
    					IsFinished = false;
    					clearInterval(tmrSearchFlights);
    					$("#msgEmpty").hide();
    					$("#msgEmptyFs").hide();
    					$("#msgFilterEmpty").hide();
    					$("#loadingFlight").hide();
    					$("#loadingBlock").hide();
    					$("#msgEmptyFs").show();
    					analyticsLogLimitSearch();
    					$("#Geral").hide();
    					$("#semResultadoBusca").show();
    					LoadingDataHide();
    				}
    				else {
    					IsActive = false;
    					IsFinished = false;
    					//IsFinished = true;
    					//clearInterval(tmrSearchFlights);
    					$("#loadingBlock").hide();
    					$("#loadingFlight").hide();
    					$("#semResultadoBusca").show();
    					$("#msgEmpty").show();
    					analyticsLogNoResults();
    				}
    			}
    		},
    		failure: function (msg) {
    			clearInterval(tmrSearchFlights);
    			$('#output').text(msg);
    			IsActive = false;
    			LoadingDataHide();
    		},
    		error: function (msg) {
    			clearInterval(tmrSearchFlights);
    			IsFinished = true;
    			IsActive = false;
    			numPerTry = numPerTryMax + 1;
    			$("#msgEmpty").hide();
    			$("#msgFilterEmpty").hide();
    			$("#loadingFlight").hide();
    			$("#loadingBlock").hide();
    			$("#msgEmpty").show();
    			analyticsLogNoResults();
    			$("#Geral").hide();
    			$("#semResultadoBusca").show();
    			LoadingDataHide();
    			IsActive = false;
    			$("#flightResultSearch").hide();
    			//$("#msgEmpty").find(".alertaErro").html(msg.responseText);
    			LoadingDataHide();
    			ShowLoading();
    		}
    	});
    }
    catch (ex) { clearInterval(tmrSearchFlights); }
}

//Retorna segmentos da classe SegmentResults, para mostrar os detalhes do voo.
function getAllSegment(journeyId, type) {
    $.ajax({
        type: "POST",
        url: URL + "/GetAllSegment",
        data: "{journeyid:" + journeyId + ",guidSession:'" + $("[id$=hSessionGuid]").val() + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {
            Result = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
            GenerateListSegment(Result, type);
        },
        failure: function(msg) {
            $('#output').text(msg);
        }
    });
}


//#region
//function RemoveSelectedFlight(journeyIndexJSRemovida) {

//    if (journeyIdSelectedGo == null && journeyIdSelectedGo == null)
//        journeyIndexJS = 0;
//    else
//        journeyIndexJS = journeyIndexJSRemovida;

//    ClearFilter();
//    //Atualiza os filtros da nova pagina selecionada
//    FlightsFiltered = null;
//    SetFilters();

//    if (journeyIndexJSRemovida == 0) {

//        AirLineSelectedGo = '';
//        DepartureSelectedGo = '';
//        ArrivalSelectedGo = '';
//        journeyIdSelectedGo = null;
//        TrackCredentialIdSelectedGo = null;
//    }
//    else {
//        AirLineSelectedBack = '';
//        DepartureSelectedBack = '';
//        ArrivalSelectedBack = '';
//        journeyIdSelectedBack = null;
//        TrackCredentialIdSelectedBack = null;
//    }

//    MoveToTop();

//    if ($("#btnslide_" + journeyIndexJSRemovida).text() == $('#maisFechar').text()) {
//        $("#btnslide_" + journeyIndexJSRemovida).html($('#maisInformacoes').text());
//        $("#boxResultPe_" + journeyIndexJSRemovida).removeClass("activeResultPe");
//        $("#boxResultPe_" + journeyIndexJSRemovida).toggleClass("activePe");
//        $("#btnslide_" + journeyIndexJSRemovida).removeClass("active");
//        $("#btnslide_" + journeyIndexJSRemovida).removeClass("active2");
//    }
//    $("#panel_" + journeyIndexJSRemovida).hide("slow");
//    $('#divFlightSelected_' + journeyIndexJSRemovida).hide("slow");

//    $("#panel_" + journeyIndexJSRemovida).empty();
//    $("#panel_" + journeyIndexJSRemovida).html('');

//    Departure = Segments[journeyIndexJS].DepartureAirportName;
//    Arrival = Segments[journeyIndexJS].ArrivalAirportName;

//    if (journeyIndexJS == 0) {
//        $("#btnVolta").addClass("bt-volta-desabilitado").removeClass("bt-volta");
//        $("#btnIda").addClass("bt-ida").removeClass("bt-ida-desabilitado");
//    }
//    else {
//        $("#btnIda").addClass("bt-ida-desabilitado").removeClass("bt-ida");
//        $("#btnVolta").addClass("bt-volta").removeClass("bt-volta-desabilitado");
//        $("#principalMatrix").hide("slow");
//    }

//    ShowflightTotal('none');

//    MaxPageCurrent = 0;
//    index = 0;
//    page = 1;
//    GetAllFlightClient(0, true);
//    GenerateMatrix();
//}

function ShowflightTotal(display) {

    if (Flights.length != 0) {
        if (display == "none") {
            //$('#divTotalFlight')[0].style.display = display;
            $('#divTotalFlight').hide("slow");
        }
        else {
            $('#divTotalFlight').show("slow");
        }
        $('#AmountTotalFlight').empty();
        $('#AmountTotalFlight').append(Flights[0].CurrencyCode + ' ' + FormatarDecimal(AmountPriceGo + AmountPriceBack));

        $('#PlotsDescription').empty();
        if (NumberOfPlots > 0) {
            $('#PlotsDescription').append(NumberOfPlots + "x<b> " + Flights[0].CurrencyCode + " " + FormatarDecimal((AmountPriceGo + AmountPriceBack) / NumberOfPlots) + " </b> &nbsp");
        }
    }
}

function FormatarDecimal(valorCampo) {
    if (valorCampo != null) {
        valorCampo = valorCampo.toString();

        valorCampo = valorCampo.replace('.', ',');

        var inteiro = valorCampo.split(',')[0];

        var dec = '00'
        if (valorCampo.split(',').length > 1) {
            dec = valorCampo.split(',')[1];
        }

        if (dec.length > 0) {
            if (dec.length == 1) {
                dec = dec + '0'
            }
            else if (dec.length > 2) {
                dec = dec.substring(0, 2)
            }
        }
        return inteiro + ',' + dec;
    }
    else { return ""; }
}


function PublishGridLine(flight) {
    MountStruct(flight);
}

function GetAllBlightsByTimer(index) {
    if (!FilterIsFinished() && !IsActive && !IsFinished) {
        numPerTry++;
        GetAllFlights(index, true);
    }
}

function StartApp() {
    //$('#container-1').tabs();
    templateMatrix = $('#divMatrix').html();
    templatePagCont = $('#divPagCont').html();

    $('#loadingBlock').show();
    $('#loadingBlock').height(document.body.offsetHeight);
    $('#loadingBlock').width(document.body.offsetWidth);
    //Mostra botões de ida e volta e esconde o combinado
    $('#btnVolta').show();
    $('#btnIda').show();
    $('#divCombinate').hide();
    //Carregando
    $("#divLoading").addClass("loading-results-1");

    SetTemplateVoo();
    journeyIndexJS = 0;
    numPerTry = 1;
    GetAllFlights(index, true);
    tmrSearchFlights = setInterval(function() {
        GetAllBlightsByTimer(index);
    }, (numTryTimeSecond * 1000));
    //    $(document).everyTime(numTryTimeSecond * 1000, 'controlled', function() {
    //        GetAllBlightsByTimer(index);
    //    });
}

function SetTemplateVoo() {
    template01 = $('#output').html();
    $('#output').empty();
}

$(document).ready(function() {
    StartApp();
    //    $('#loadingBlock').height(document.body.offsetHeight);
    //    $('#loadingBlock').width(document.body.offsetWidth);
});

//Gera os registros dos segmentsResults para o mais informações
function GenerateListSegment(segment, type) {
    var journeyId = segment[0].JourneyId;

    // monta html com o conteúdo da modal
    var htmlModal = '<h2 title="Filtrar por" class="textoFlash2 tt-detalhesVoo">detalhes do voo</h2> <a href="#" class="close replace">Fechar</a>';
    htmlModal += '<ul id="listaDetalheVoo">';

    for (var i = 0; i <= segment.length - 1; i++) {
        // verifica se é o ultimo da listagem
        var classeLi = (i + 1 == segment.length) ? 'class="ultimo"' : '';

        htmlModal += '<li ' + classeLi + '><table class="tb-listaVoosDetalhe"><tr><td class="td-logo-cia-aerea">';
        htmlModal += '<div class="logoCiaAerea' + ((type == 0) ? ' ida' : ' volta') + '"><img src="' + segment[i].UrlLogo + '" /></div>';
        htmlModal += '<p><span class="classe">' + Flights[0].ClassType + '</span><br /><span class="aeronave"> ' + segment[i].Equipment + '</span><br />';
        htmlModal += '<span class="numeo-voo">' + $("#descrVoo").val() + " " + segment[i].FlightNumber + '</span></p></td><td class="td-ida">';
        htmlModal += '<p><span class="saida">' + $("#descrSaida").val() + ' - ' + segment[i].DepartureDateTime + '</span><br />';
        htmlModal += '<span class="aeroporto-modal">' + segment[i].DepartureAirportName + '</span>';
        htmlModal += '</p></td><td class="td-volta"><p><span class="saida">' + $("#descrChegada").val() + ' - ' + segment[i].ArrivalDateTime + '</span><br />';
        htmlModal += '<span class="aeroporto-modal">' + segment[i].ArrivalAirportName + '</span></p></td></tr></table>';
        htmlModal += '</li>';
    }

    htmlModal += '</ul>';

    // efetua a abertura da modal
    var idModal = "#modalDetalheVoo";
    var maskHeight = $(document).height();
    var maskWidth = $(window).width();

    $('#mask').css({ 'width': maskWidth, 'height': maskHeight });

    $('.pagina').css('position', 'static');

    $('#mask').fadeIn(100);
    $('#mask').fadeTo("fast", 0.7);

    // verifica as dimensões da área visível do browser
    var winH = $(window).height();
    var winW = $(window).width();

    // posição do scrolling
    var scrollTop = 0;
    if ($.browser.safari)
        scrollTop = $("body").scrollTop();
    else
        scrollTop = $("html").scrollTop();

    var scrollLeft = $("html").scrollLeft();

    // define posicionamento da modal conforme o scroll da tela
    var topCss = (winH / 2 - $(idModal).height() / 2) + scrollTop;
    var leftCss = (winW / 2 - $(idModal).width() / 2) + scrollLeft;

    $(idModal).css('top', topCss);
    $(idModal).css('left', leftCss);

    $(idModal).fadeIn(100);

    // preenche modal com o html gerado
    $(idModal).html(htmlModal);

    // adiciona captura de cliques apra fechar a modal
    $('.modalVoos .close').click(function(e) {
        e.preventDefault();

        $('#mask').hide();
        $('.modalVoos').hide();
        $('.pagina').css('position', 'relative');
    });

    $('#mask').click(function() {
        $(this).hide();
        $('.modalVoos').hide();
        $('.pagina').css('position', 'relative');
    });

    return false;
}

function PublishGrid() {
    $('#output').empty();
    //for (var i = 0; i <= Flights.length - 1; i++) {
    PublishGridLine(Flights);
    //}
    if (Flights.length > 0) {
        if ((numPerTry == 1) || (numPerTry > numPerTryMax)) {
            $("#flightResultSearch").hide();
        }
        $("#flightResultSearch").show();
    }
}

function ClickDetail(btn, type) {

    isGoOrBackSlide = false;

    var journeyId = btn.id.split('_')[1];
    if ((IsInternational || IsOnlyGo) && haveLowFare) {
        getAllSegmentByLowFareId(journeyId, type);
    }
    else {
    	getAllSegment(journeyId, type);
    }
    return false;
}

//Mostrar mensagem de seleção de ida ou volta
function ShowWarningSelect() {

    if ((!journeyIdSelectedGo && journeyIdSelectedBack) || (journeyIdSelectedGo && !journeyIdSelectedBack)) {
        var img = ''
        if (journeyIdSelectedGo) {
            img = 'voo-ida-selecionado.jpg';
        }
        else if (journeyIdSelectedBack) {
            img = 'voo-volta-selecionado.jpg';
        }
        if (!WarningSelectActive) {
            WarningSelectActive = true;
            try {
                $("#imgWarningSelectBack")[0].src = GetBaseUrlIMG() + img;
                $("#divWarningSelectBack").slideToggle("slow");

                $(document).everyTime(timeHideWarningSelect * 1000, 'timeHideWarningSelect', function() {
                    $("#divWarningSelectBack").hide("slow");
                    $(document).stopTime('timeHideWarningSelect');
                    WarningSelectActive = false;
                });
            }
            catch (ex) { }
        }
    }
}


function MoveToTop() {
    if (journeyIdSelectedGo && journeyIdSelectedBack) {
        $("html,body").animate({ scrollTop: $("#selectedresult").offset().top - 10 }, "slow");
    }
    else {
        $("html,body").animate({ scrollTop: 0 }, "slow", '', ShowWarningSelect);


    }
}

//Classes de Filtragem **********************************************************************

function DayPeriodFilterChecked(morning, afternoon, evening, night) {
    this.morning = morning;
    this.afternoon = afternoon;
    this.evening = evening;
    this.night = night;
}

function AmountPriceStopFilterChecked(stop0, stop1, stop2) {
    this.stop0 = stop0;
    this.stop1 = stop1;
    this.stop2 = stop2;
}

function companyFilterChecked(company, value) {
    this.company = company;
    this.value = value;
}

//Retorna segmentos da classe SegmentResults, para mostrar os detalhes do voo.
function getAllSegmentByLowFareId(lowFareId, type) {
    var guidSession = $('[id$=hSessionGuid]').val();

    $.ajax({
        type: "POST",
        url: URL + "/GetAllSegmentByLowFareId",
        data: "{lowFareId:" + lowFareId + ", guidSession:'" + guidSession + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {
            Result = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
            GenerateListSegmentByLowFareId(Result, type);
        },
        failure: function(msg) {
            $('#output').text(msg);
        }
    });
}

function GenerateListSegmentByLowFareId(segment, type) {

    var lowFareId = segment[0].LowFareId;
    var journeyId = segment[0].JourneyId;
    var htmlwhite = ((type == 0) ? true : false);
    // monta html com o conteúdo da modal
    var htmlModal = '<h2 title="Filtrar por" class="textoFlash2 tt-detalhesVoo">' + configFlightClient.jsFresultsSolutionsComboTicketsTo + " " +'</h2> <a href="#" class="close replace">Fechar</a>';
    htmlModal += '<ul id="listaDetalheVoo">';

    for (var i = 0; i <= segment.length - 1; i++) {
        if (type == 0) {
            if (IsInternational == true && IsOnlyGo == false) {
                if (journeyId != segment[i].JourneyId) {
                    htmlwhite = false;
                    i = segment.length - 1;
                }
            }
        }
        else {
            if (IsInternational == true && IsOnlyGo == false) {
                if (journeyId != segment[i].JourneyId) {
                    htmlwhite = true;
                }
            }
        }
        if (htmlwhite == true) {
            // verifica se é o ultimo da listagem
            var classeLi = (i + 1 == segment.length) ? 'class="ultimo"' : '';

            htmlModal += '<li ' + classeLi + '><table class="tb-listaVoosDetalhe"><tr><td class="td-logo-cia-aerea">';
            htmlModal += '<div class="logoCiaAerea' + ((type == 0) ? ' ida' : ' volta') + '"><img src="' + segment[i].UrlLogo + '" /></div>';
            htmlModal += '<p><span class="classe">' + Flights[0].ClassType + '</span><br /><span class="aeronave"> ' + segment[i].Equipment + '</span><br />';
            htmlModal += '<span class="numeo-voo">' + $("#descrVoo").val() + " " + segment[i].FlightNumber + '</span></p></td><td class="td-ida">';
            htmlModal += '<p><span class="saida">' + $("#descrSaida").val() + ' - ' + segment[i].DepartureDateTime + '</span><br />';
            htmlModal += '<span class="aeroporto-modal">' + segment[i].DepartureAirportName + '</span>';
            htmlModal += '</p></td><td class="td-volta"><p><span class="saida">' + $("#descrChegada").val() + ' - ' + segment[i].ArrivalDateTime + '</span><br />';
            htmlModal += '<span class="aeroporto-modal">' + segment[i].ArrivalAirportName + '</span></p></td></tr></table>';
            htmlModal += '</li>';
        }
    }

    htmlModal += '</ul>';

    // efetua a abertura da modal
    var idModal = "#modalDetalheVoo";
    var maskHeight = $(document).height();
    var maskWidth = $(window).width();

    $('#mask').css({ 'width': maskWidth, 'height': maskHeight });

    $('.pagina').css('position', 'static');

    $('#mask').fadeIn(100);
    $('#mask').fadeTo("fast", 0.7);

    // verifica as dimensões da área visível do browser
    var winH = $(window).height();
    var winW = $(window).width();

    // posição do scrolling
    var scrollTop = 0;
    if ($.browser.safari)
        scrollTop = $("body").scrollTop();
    else
        scrollTop = $("html").scrollTop();

    var scrollLeft = $("html").scrollLeft();

    // define posicionamento da modal conforme o scroll da tela
    var topCss = (winH / 2 - $(idModal).height() / 2) + scrollTop;
    var leftCss = (winW / 2 - $(idModal).width() / 2) + scrollLeft;

    $(idModal).css('top', topCss);
    $(idModal).css('left', leftCss);

    $(idModal).fadeIn(100);

    // preenche modal com o html gerado
    $(idModal).html(htmlModal);

    // adiciona captura de cliques apra fechar a modal
    $('.modalVoos .close').click(function(e) {
        e.preventDefault();

        $('#mask').hide();
        $('.modalVoos').hide();
        $('.pagina').css('position', 'relative');
    });

    $('#mask').click(function() {
        $(this).hide();
        $('.modalVoos').hide();
        $('.pagina').css('position', 'relative');
    });

    return false;
    //    $("#panel_" + lowFareId).empty();
    //    for (var i = 0; i <= segment.length - 1; i++) {
    //        if (i != 0) {
    //            $("#panel_" + lowFareId).append("<div class='hrPanel'/>");
    //        }

    //        var arrivalCity = i == 0 ? "<h3 class='mais_info'>Passagem áerea para " + segment[0].ArrivalCity + "</h3>" : "";
    //        if (i != 0 && segment[i].ArrivalCity != segment[i - 1].ArrivalCity) {
    //            arrivalCity = "<h3 class='mais_info'>Passagem áerea para " + segment[i].ArrivalCity + "</h3>";
    //        }

    //        $("#panel_" + lowFareId).append(arrivalCity + "<ul><li class='empresa'><div class='img'><img src='" + segment[i].UrlLogo +
    //                                    "' alt='" + segment[i].MarketingAirLineName + "' title='" + segment[i].MarketingAirLineName +
    //                                    "' /></div>" + Flights[0].ClassType + " " + segment[i].Equipment + "<br>Voo " + segment[i].FlightNumber +
    //                                    " </li><li><span><strong>Saída - " + segment[i].DepartureDateTime + "</strong></span>" + segment[i].DepartureAirportName +
    //                                    " </li><li><span><strong>Chegada - " + segment[i].ArrivalDateTime + " </strong></span>" + segment[i].ArrivalAirportName + "</li></ul>");
    //    }

    //    $("#panel_" + lowFareId).slideToggle("slow");
    //    $("#boxResultPe_" + lowFareId).toggleClass("activeCombinadoPe");
    //    $("#btnslide_" + lowFareId).toggleClass("active");

    //    if ($("#btnslide_" + lowFareId).text() == $('#maisFechar').text()) {
    //        $("#btnslide_" + lowFareId).html($('#maisInformacoes').text());
    //    }
    //    else {
    //        $("#btnslide_" + lowFareId).html($('#maisFechar').text());
    //    }

    //    return false;

}

//**************27/09/2010 *************************

function FormatarDecimal(valorCampo) {
    if (valorCampo != null) {
        valorCampo = valorCampo.toString();

        valorCampo = valorCampo.replace('.', ',');

        var inteiro = valorCampo.split(',')[0];

        var dec = '00'
        if (valorCampo.split(',').length > 1) {
            dec = valorCampo.split(',')[1];
        }

        if (dec.length > 0) {
            if (dec.length == 1) {
                dec = dec + '0'
            }
            else if (dec.length > 2) {
                dec = dec.substring(0, 2)
            }
        }
        return inteiro + ',' + dec;
    }
    else { return ""; }
}

function selectFlightGroup(sender, iType, IndicePriceGroup) {

    $(".validacao-check-externa").removeClass("validacao-check-externa");
    if (iType == 0) {
        $(".grpFlight0:checked").each(function() {
            this.checked = false;
            $(".grpFlight1:checked").each(function() {
                if (this.attributes["indicepricegroup"].value != IndicePriceGroup) {
                    this.checked = false;
                    journeyIdSelectedBack = '';
                }
            });

        });

        AmountPriceGo = Flights[IndicePriceGroup].AmountPrice;

        journeyIdSelectedGo = sender.value; //JourneyId
        index = sender.attributes["indicepricegroup"].value;

        AirLineSelectedGo = Flights[IndicePriceGroup].MainAirlineCode;

        DepartureSelectedGo = Flights[IndicePriceGroup].DepartureAirport;
        ArrivalSelectedGo = Flights[IndicePriceGroup].ArrivalAirport;
        TrackCredentialIdSelectedGo = Flights[IndicePriceGroup].TrackCredentialId;

        //google analytics
        analyticsLogGo();

    }

    $(".alerta-validacao").each(function() {
        this.style.display = "none";
    });

    sender.checked = true;
    //        MoveToTop();

    if (PaxQuantity > 5) {
        PaxQuantity = 5;
    }
    NumberOfPlots = Flights[IndicePriceGroup].NumberPlots;
    if (journeyIdSelectedGo && journeyIdSelectedBack) {
        ShowflightTotal('', IndicePriceGroup);
    }
}

function MountStruct(voos) {
    $('#output').html('');
    var nPage = 1;
    var tabela = ''
    var numbergroup = 0
    if (index != 0) {
        if (voos.length == 10)
            numbergroup = page * voos.length - 10;
        else
            numbergroup = (page - 1) * 10 + voos.length - voos.length;
    }
    else {
        page = 1;
        numbergroup = 0;
    }
    var indexGroup = 0;
    var AmountPriceAux = 0;
    var MainAirlineCodeAux = '';
    var DepartureAirportAux = '';
    var ArrivalAirportAux = '';
    var i = 0;
    if (voos.length > 0) {
        if (IsInternational == false && IsOnlyGo == true) {
            while (indexGroup < 10 && i < voos.length) {
                for (i = 0; i < voos.length; i++) {

                	
                	if ($('#isInternationalDeparture').text() == 'true') {
                		voos[i - numbergroup].NumberPlots = 0;
                	}
                    if (AmountPriceAux != voos[i].AmountPrice || MainAirlineCodeAux != voos[i].MainAirlineCode || voos[i].DepartureAirport != DepartureAirportAux || voos[i].ArrivalAirport != ArrivalAirportAux) {
                        if (page == nPage) {
                            if (i > 0 && indexGroup > 0) {
                                tabela += '</div></div></div>';
                                tabela += appendLineCombo(voos[i - 1], voos[i - 1], indexGroup - 1);
                                tabela += '</div>'
                            }
                            tabela += '<div class="Group">';
                            tabela += appendLineGroup(voos[i], indexGroup);
                            tabela += '<div class="conj-resultados-linha-primeira"><span style="width:52px" class="ida-titulo">' + $('#descrIda').val() + '</span><span style="width:80px">' + DepartureDate + '</span>';
                            var textoAirportGo = ((voos[i].DepartureAirportName.length >= 22) ? voos[i].DepartureAirportName.substring(0, 22) + '...' : voos[i].DepartureAirportName);
                            var textoAirportBack = ((voos[i].ArrivalAirportName.length >= 22) ? voos[i].ArrivalAirportName.substring(0, 22) + '...' : voos[i].ArrivalAirportName);
                            tabela += '<span><a href="javascript:FilterAirport(\'' + voos[i].DepartureAirport + '\',0);">' + textoAirportGo + '(<strong>' + voos[i].DepartureAirport + '</strong>)</a> /<a href="javascript:FilterAirport(\'' + voos[i].ArrivalAirport + '\',1);">' + textoAirportBack + '(<strong>' + voos[i].ArrivalAirport + '</strong>)</a></span></div><div id=Ida_' + indexGroup + '><div class="validacao-check-interna">'
                        }
                        indexGroup = indexGroup + 1;
                    }

                    //Monta Ida

                    if (page == nPage) {
                        tabela += appendLine(voos[i], 'Ida', indexGroup - 1, i);
                    }
                    if (i <= voos.length - 1 && i + 1 <= voos.length - 1) {
                        if (voos.length == 1 || (indexGroup == 10 && (voos[i].AmountPrice != voos[i + 1].AmountPrice || voos[i].MainAirlineCode != voos[i + 1].MainAirlineCode || voos[i].DepartureAirport != voos[i + 1].DepartureAirport || voos[i].ArrivalAirport != voos[i + 1].ArrivalAirport))) {
                            if (page == nPage) {
                                tabela += '</div></div></div>';
                                tabela += appendLineCombo(voos[i], voos[i], indexGroup - 1);
                                tabela += '</div>'
                                i = voos.length;
                            }
                            else {
                                indexGroup = 0;
                                AmountPriceAux = 0;
                                MainAirlineCodeAux = '';
                                DepartureAirportAux = '';
                                ArrivalAirportAux = '';
                            }
                            nPage++;
                        }
                        else if (i == voos.length - 1) {
                            tabela += '</div></div></div>';
                            tabela += appendLineCombo(voos[i], voos[i], indexGroup - 1);
                            tabela += '</div>'
                        }
                    }
                    else {
                        if (page == nPage) {
                            tabela += '</div></div></div>';
                            tabela += appendLineCombo(voos[i], voos[i], indexGroup - 1);
                            tabela += '</div>'
                            i = voos.length;
                        }
                    }
                    if (i < voos.length - 1) {
                        AmountPriceAux = voos[i].AmountPrice;
                        MainAirlineCodeAux = voos[i].MainAirlineCode;
                        DepartureAirportAux = voos[i].DepartureAirport;
                        ArrivalAirportAux = voos[i].ArrivalAirport;
                    }
                }
            }
        }
        else {
            //            voos = jLinq.from(voos)
            //                .skipTake(index, numPerPage);
            while (indexGroup < 10 && i < voos.length) {
                for (i = 0; i < voos.length; i++) {

                    //                    if (AmountPriceAux != voos[i].AmountPrice || MainAirlineCodeAux != voos[i].MainAirlineCode) {
                    //                        if (page == nPage) {
                    //                            if (i > 0 && indexGroup > 0) {
                    //                                tabela += '</div></div></div>';
                    //                                tabela += appendLineCombo(voos[i], voos[i], indexGroup);
                    //                                tabela += '</div>'
                    //                            }
                    if (page == nPage) {
                        tabela += '<div class="Group">';
                        tabela += appendLineGroup(voos[i], [i]);
                        tabela += '<div class="conj-resultados-linha-primeira"><span style="width:52px" class="ida-titulo">' + $('#descrIda').val() + '</span><span style="width:80px">' + DepartureDate + '</span>';
                        var textoAirportGo = ((voos[i].DepartureAirportName.length >= 22) ? voos[i].DepartureAirportName.substring(0, 22) + '...' : voos[i].DepartureAirportName);
                        var textoAirportBack = ((voos[i].ArrivalAirportName.length >= 22) ? voos[i].ArrivalAirportName.substring(0, 22) + '...' : voos[i].ArrivalAirportName);
                        tabela += '<span><a href="javascript:FilterAirport(\'' + voos[i].DepartureAirport + '\',0);">' + textoAirportGo + '(<strong>' + voos[i].DepartureAirport + '</strong>)</a> /' + textoAirportBack + '(<strong>' + voos[i].ArrivalAirport + '</strong>)</span></div><div id=Ida_' + [i] + '><div class="validacao-check-interna">'
                    }
                    indexGroup = indexGroup + 1;
                    //                    }

                    //Monta Ida

                    if (page == nPage) {
                        tabela += appendLine(voos[i], 'Ida', indexGroup - 1, i);
                    }
                    //                    if (AmountPriceAux != voos[i].AmountPrice || MainAirlineCodeAux != voos[i].MainAirlineCode) {
                    if (page == nPage) {
                        tabela += '</div></div><div class="conj-resultados-linha-primeira-volta"><span style="width:52px" class="volta-titulo">' + $('#descrVolta').val() + '</span>';
                        var textoAirportGo = ((voos[i].DepartureAirportBackName.length >= 22) ? voos[i].DepartureAirportBackName.substring(0, 22) + '...' : voos[i].DepartureAirportBackName);
                        var textoAirportBack = ((voos[i].ArrivalAirportBackName.length >= 22) ? voos[i].ArrivalAirportBackName.substring(0, 22) + '...' : voos[i].ArrivalAirportBackName);
                        tabela += '<span style="width:80px">' + ArrivalDate + '</span><span><a href="javascript:FilterAirport(\'' + voos[i].DepartureAirportBack + '\',1);">' + textoAirportGo + ' (<strong>' + voos[i].DepartureAirportBack + '</strong>)</a>';
                        tabela += ' / <span class="underline">' + textoAirportBack + ' (<strong>' + voos[i].ArrivalAirportBack + '</strong>)</span></span></div><div id=Volta_' + [i] + ' ><div class="validacao-check-interna">';
                    }
                    //                    }

                    if (page == nPage) {
                        tabela += appendLine(voos[i], 'Volta', indexGroup - 1, i);
                    }

                    //                    AmountPriceAux = voos[i].AmountPrice;
                    //                    MainAirlineCodeAux = voos[i].MainAirlineCode;
                    if (voos.length == 1 || indexGroup == 10) {
                        if (page == nPage) {
                            tabela += '</div></div></div>';
                            tabela += appendLineCombo(voos[i], voos[i], indexGroup - 1);
                            tabela += '</div>'
                            i = voos.length;
                        }
                        else {
                            indexGroup = 0;
                            //                            AmountPriceAux = 0;
                            //                            MainAirlineCodeAux = '';
                        }
                        nPage++;
                    }
                    else if (i == voos.length - 1) {
                        if (page == nPage) {
                            tabela += '</div></div></div>';
                            tabela += appendLineCombo(voos[i], voos[i], indexGroup - 1);
                            tabela += '</div>'
                        }
                    }
                    else {
                        if (page == nPage) {
                            tabela += '</div></div></div>';
                            tabela += appendLineCombo(voos[i], voos[i], indexGroup - 1);
                            tabela += '</div>'
                        }
                    }
                }
            }

        }

    }
    $('#output').html(tabela);
    $('#output').attr('style', '');
}

function appendLine(f, grp, g, indexVoo) {
    var type = (grp == 'Ida') ? 0 : 1;
    var linha = '';

    if (IsInternational == false && IsOnlyGo)
        linha = '<div class="conj-resultados-linha"><span style="width:60px; padding-left:10px;"><input class="grpFlight' + type + '" onclick="javascript:selectFlightGroup(this,' + type + ',' + g + ');" type="radio" indicepricegroup="' + g + '" value=#Id /></span>';
    else
        linha = '<div class="conj-resultados-linha"><span style="width:60px; padding-left:10px;"></span>';

    linha += '<span style="width:80px;">' + $('#descrSaida').val() + ' <strong>#HoraSaída</strong></span><span style="width:100px;">' + $('#descrChegada').val() + ' <strong>#HoraChega</strong></span>';
    linha += '<span style="width:120px;">' + configFlightClient.jsFlightSolutionComboElapseTime + ' <strong>#Duration</strong></span><span style="width:95px;">' + ((f.StopsDescription == "Direto") ? $('#descrVoo').val() : $('#descrParadas').val()) + ' <strong>#stopDesc</strong></span>';
    linha += '<span><a id="minfo_' + f.JourneyId + '" onclick="return ClickDetail(this,' + type + ');" class="conj-resultados-linha-mais">&nbsp;</a></span></div>';
    if (type == 0) {
        linha = linha.replace('#Id', f.JourneyId);
        linha = linha.replace('#HoraSaída', f.DepartureTime);
        linha = linha.replace('#HoraChega', f.ArrivalTime);
        linha = linha.replace('#Duration', f.JourneyDuration);
        linha = linha.replace('#stopDesc', f.StopsDescription);
    }
    else {
        linha = linha.replace('#Id', f.JourneyIdBack);
        linha = linha.replace('#HoraSaída', f.DepartureTimeBack);
        linha = linha.replace('#HoraChega', f.ArrivalTimeBack);
        linha = linha.replace('#Duration', f.JourneyDurationBack);
        linha = linha.replace('#stopDesc', f.StopsDescriptionBack);
    }

    return linha;
}

function appendLineGroup(f, index) {
    var linha = '<div class="conj-resultados-top"><span style="width:70px"><img src="#urlImage" alt="Cia aerea" /></span>'
    linha += '<span style="width:80px">#Empresa</span><span>' + configFlightClient.jsFlightSolutionComboFlightTicket + ' <span class="orange-title">de</span> <strong>#Origem</strong> <span class="orange-title">para</span> <strong>#Destino</strong></span></div>'
    linha += '<div class="conj-resultados-middle"><span id=Alert_' + index + ' style="display:none;" class="alerta-validacao"><div id=msg_' + index + '></div></span><div class="ida-volta-info-go">'


    linha = linha.replace('#urlImage', f.UrlLogo);

    var ciaName = f.MainAirlineName.split("&nbsp;")[0];
    if (ciaName == "Air") {
        linha = linha.replace('#Empresa', f.MainAirlineName);  
    } else {
        linha = linha.replace('#Empresa', ciaName);
    }
    linha = linha.replace('#Origem', Departure);
    linha = linha.replace('#Destino', Arrival);

    return linha;
}

function appendLineCombo(f, g, index) {
    var linha = '';
    if (IsOnlyGo) {
        linha = '<div class="box-preco"><span class="parte-0"> ' + $('#descrPriceGo').val() + '<br/>' + $('#descrPriceGo2').val() + '</span>';        
    }
    else
        linha = '<div class="box-preco"><span class="parte-0"> ' + $('#descrPriceGoBack').val() + '<br/>' + $('#descrPriceGoBack2').val()  + '</span>';

    linha += '<div class="box-preco-miolo"><h3 class="parte-1">#currencycode #amountpricecombo</h3>';
    if ((f.AmountPrice != null && f.AmountPrice != 0) && (f.NumberPlots != null && f.NumberPlots != 0))
        linha += '<span class="parte-2">' + $('#descrAvistaou').val() + '</span><span class="parte-3"><span>#NumberPlots x</span> #currencycode #AmountPlot</span>';
    else
        linha += '<span class="parte-2">' + $('#descrAvista').val() + '</span>';

    if (IsInternational == false)
        linha += '<span class="parte-4">' + configFlightClient.jsFlightSolutionsFromADT + '</span><a id=Reserve_' + index + ' href="javascript: validateMasterReserve(' + index + ');" value="' + index + '" class="reserve-ja replace-bt">' + $('#descrReservationNow').val() + '</a>';
    else
        linha += '<span class="parte-4">' + configFlightClient.jsFlightSolutionsFromADT + '</span><a id=Reserve_' + index + ' href="javascript: validateMasterReserve(' + f.JourneyId + ',' + index + ');" value="' + index + '" class="reserve-ja replace-bt">' + $('#descrReservationNow').val() + '</a>';

    linha += '</div></div></div><div class="conj-resultados-rodape" >';
    linha += '<div class="col-esq"><a id="dialog_link" onclick="javascript:ShowModal(' + index + ');" class="mail-ico">' + configFlightClient.jsFlightSolutionComboSendByEmail + '</a><a href="#" class="imprimir print-ico">' + configFlightClient.jsFlightSolutionComboPrint + '</a></div>';
    linha += '<div class="col-dir" style="Display:none"><span>Redes sociais:</span><a href="#">Enviar pelo Twitter</a><a href="#">Adicionar no Delicious</a>'
    linha += '<a href="#">Adicionar no Digg</a></div></div>'

    linha = linha.replace(/\#currencycode/gi, f.CurrencyCode);
    linha = linha.replace('#amountpricecombo', f.AmountPrice.localeFormat("N"));
    linha = linha.replace('#NumberPlots', f.NumberPlots);
    linha = linha.replace('#AmountPlot', f.AmountPlot.localeFormat("N"));
    return linha;
}

function OpenMatrix() {
    $("#principalMatrixSub").show("slow");
    $('#OpenResult')[0].style.display = "none";

}

function CloseMatrix() {
    $("#principalMatrixSub").hide("slow");
    $('#OpenResult')[0].style.display = "inline-block";
}
function validaReserve(index) {
	return true;
//    var SelectGo = null;
//    var SelectBack = null;
//    $(".grpFlight0:checked").each(function() {
//        this.checked = false;
//        if (this.attributes["indicepricegroup"].value == index) {
//            SelectGo = true;
//            this.checked = true;
//        }
//    });


//    if (SelectGo != null) {
//        return true;
//    }
//    else {
//        if (SelectGo == "" || SelectGo == null) {
//            journeyIdSelectedGo = null;
//            $(".validacao-check-externa").removeClass("validacao-check-externa");
//            $("#Ida_" + index).addClass("validacao-check-externa");
//            $("#msg_" + index).html($('#descrFlightComboGoAlert').val());
//        }

//        $(".alerta-validacao").each(function() {
//            this.style.display = "none";
//        });

//        $("#Alert_" + index)[0].style.display = "";
//        return false;
//    }
}
function validateMasterReserve(journey, group) {
    if (IsInternational == false) {
    	if (validaReserve(index)) {
    		loadingReserve();
    		analyticsLogNationalReserve();
    		if (haveLowFare)
    			SendToValuationLowFare(journeyIdSelectedGo);
    		else {
    			if (journeyIdSelectedBack == null) journeyIdSelectedBack = 0;
    			SendToValuation();
    		}
    	}
    }
    else {
        loadingReserve();
        analyticsLogNationalReserve();
        if (journey != null)
            journeyIdSelectedGo = journey;

        SendToValuationLowFare(journeyIdSelectedGo);
    }
}
function findMatrix(matrix, matrixDados) {
    for (var i = 0; i < matrix.length; i++) {
        if (matrix[i].ciaCode == matrixDados.ciaCode) {
            if (matrixDados.StopsGroupDirect != -1 && matrix[i].StopsGroupDirect != matrixDados.StopsGroupDirect)
                return false;
            else if (matrixDados.StopsGroupOne != -1 && matrix[i].StopsGroupOne != matrixDados.StopsGroupOne)
                return false;
            else if (matrixDados.TwoOrMoreStop != -1 && matrix[i].TwoOrMoreStop != matrixDados.TwoOrMoreStop)
                return false;

            return true;
        }
    }
    return false;
}
