﻿/// <reference path="../jquery-1.3.2-vsdoc2.js" />

//Métodos de acesso ao WebService ***********************************************
function GetDayPeriodFilter() {

    DayPeriodFilterIsActive = true;

    var resultsTmp = FlightsFiltered;

    if (resultsTmp.length > 0) {
        var period = jLinq.from(resultsTmp).distinct("DepartureDayPeriod");

        Morning = period.contains(1);
        Afternoon = period.contains(2);
        Evening = period.contains(4);
        Night = period.contains(8);

        var strTitle = "<h3>" + $("#jsFlightFilterDeparturePrice").html().toString() + "</h3>";
        var strHtml = "";

        dayperiodfilterchecked.morning = true;
        dayperiodfilterchecked.afternoon = true;
        dayperiodfilterchecked.evening = true;
        dayperiodfilterchecked.night = true;

        if (Morning) {
            strHtml = "<label class='lbl-preco-manha' title='" + $('#jsFlightFilterMorning').html().toString() + "'>" +
                                "<input type='checkbox' name='cbxPrecoManha' checked='checked' onclick='javascript:LoadingDataShow();dayperiodfilterchecked.morning=this.checked;FilterData(0,false);' />" +
                                "<strong>" + $('#jsFlightFilterMorning').html().toString() + "</strong>" +
                                "<span>" + $('#jsFlightFilterTimeInterval6amTo12am').html().toString() + "</span> " +
                            "</label>";
        }

        if (Afternoon) {
            strHtml += "<label class='lbl-preco-tarde' title='" + $('#jsFlightFilterAfternoon').html().toString() + "'>" +
                                "<input type='checkbox' name='cbxPrecoTarde' checked='checked'  onclick='javascript:LoadingDataShow();dayperiodfilterchecked.afternoon=this.checked;FilterData(0,false);' />" +
                                "<strong>" + $('#jsFlightFilterAfternoon').html().toString() + "</strong>" +
                                "<span>" + $('#jsFlightFilterTimeInterval12amTo6pm').html().toString() + "</span> " +
                            "</label>";
        }

        if (Evening) {
            strHtml += "<label class='lbl-preco-noite' title='" + $('#jsFlightFilterNight').html().toString() + "'>" +
                                "<input type='checkbox' name='cbxPrecoNoite' checked='checked' onclick='javascript:LoadingDataShow();dayperiodfilterchecked.evening=this.checked;FilterData(0,false);' />" +
                                "<strong>" + $('#jsFlightFilterNight').html().toString() + "</strong>" +
                                "<span>" + $('#jsFlightFilterTimeInterval6pmTo12am').html().toString() + "</span> " +
                            "</label>";
        }
        if (Night) {
            strHtml += "<label class='lbl-preco-madrugada' title='" + $('#jsFlightFilterDawn').html().toString() + "'>" +
                                "<input type='checkbox' name='cbxPrecoMadrugada' checked='checked' onclick='javascript:LoadingDataShow();dayperiodfilterchecked.night=this.checked;FilterData(0,false);' />" +
                                "<strong>" + $('#jsFlightFilterDawn').html().toString() + "</strong>" +
                                "<span>" + $('#jsFlightFilterTimeInterval12pmTo6am').html().toString() + "</span> " +
                            "</label>";
        }

        if (strHtml != "") {
            $("#divDayPeriod").html(strTitle + strHtml);
            LoadingDataShow();
        }

        DayPeriodFilterIsActive = false;
        LoadingDataHide();
    }
}

function GetAmountPriceFilter() {

    AmountPriceFilterIsActive = true;

    var resultsTmp = FlightsFiltered;

    if (resultsTmp.length > 0) {
        //debugger;
        //resultsTmp = jLinq.from(resultsTmp).distinct("AmountPrice");
        var AmountPriceMin = jLinq.from(resultsTmp).min("AmountPrice");
        var AmountPriceMax = jLinq.from(resultsTmp).max("AmountPrice");
        Currency = jLinq.from(resultsTmp).select()[0].CurrencyCode;

        var strTitle = "<h3>" + configFlightClient.jsFlightFilterPrice + "</h3>";
        var strHtml = "";
        if (AmountPriceMin != null) {

            strHtml = "<div id='divFilterAmount'>" +
                                "<span id='divFilterAmountMin' />" +
                                "<span id='divFilterAmountText' />" +
                                "<span id='divFilterAmountMax' />" +
                            "</div>" +
                            "<div class='barra-preco'>" +
                                "<div id='slider' class='slider-range'></div>" +
                            "</div>";
        }

        if (strHtml != "") {
            $("#divAmountPrice").html(strTitle + strHtml);

            $(document).ready(function () {
                var AmountPriceFilterMin = Math.round(Number(AmountPriceMin.toString().replace(",", ".")));
                var AmountPriceFilterMax = Math.round(Number(AmountPriceMax.toString().replace(",", ".")));


                //if ((Number(AmountPriceMin.toString().substring((AmountPriceMin.toString().indexOf(',') + 1), AmountPriceMin.toString().lenght))) >= 50)
                AmountPriceFilterMin--;

                //if ((Number(AmountPriceMax.toString().substring((AmountPriceMax.toString().indexOf(',') + 1), AmountPriceMax.toString().lenght))) < 50)
                AmountPriceFilterMax++;


                $("#slider").slider({
                    range: true,
                    min: AmountPriceFilterMin,
                    max: AmountPriceFilterMax,
                    values: [AmountPriceFilterMin, AmountPriceFilterMax],
                    slide: function (event, ui) {
                        $("#divFilterAmountMin").html(Currency + " " + $("#slider").slider("values", 0).localeFormat("N"));
                        $("#divFilterAmountMax").html(Currency + " " + $("#slider").slider("values", 1).localeFormat("N"));
                        //FilterData(0, false);
                    },
                    stop: function (event, ui) {
                        LoadingDataShow();
                        amountPriceMin = $("#slider").slider("values", 0);
                        amountPriceMax = $("#slider").slider("values", 1);
                        FilterData(0, false);
                    }
                });
                $("#divFilterAmountMin").html(Currency + " " + $("#slider").slider("values", 0).localeFormat("N"));
                $("#divFilterAmountText").html(configFlightClient.jslblGenericUntil);
                $("#divFilterAmountMax").html(Currency + " " + $("#slider").slider("values", 1).localeFormat("N"));
                LoadingDataShow();
            });
        }

        AmountPriceFilterIsActive = false;
        LoadingDataHide();
    }
}

function GetAmountPriceStopFilter() {

    AmountPriceStopFilterIsActive = true;

    var resultsTmp = FlightsFiltered;

    if (resultsTmp.length > 0) {
        Currency = jLinq.from(resultsTmp).select()[0].CurrencyCode;

        var amountPriceAll = jLinq.from(resultsTmp)
            .groupBy("Stops")
            .select(function(r) {
                return {
                    Stops: r.key,
                    AmountPriceMin: jLinq.from(r.items).min("AmountPrice")
                };
            });

        var amountPrice0Stop = jLinq.from(amountPriceAll)
                .where(function(rec, helper) {
                    return (rec.Stops == 0);
                })
                .select("AmountPrice");
                
        //amountPrice0Stop = amountPrice0Stop.localeFormat("N");

        var amountPrice1Stop = jLinq.from(amountPriceAll)
                .where(function(rec, helper) {
                    return (rec.Stops == 1);
                })
                .select("AmountPrice");

        var amountPrice2Stop = jLinq.from(amountPriceAll)
                .where(function(rec, helper) {
                    return (rec.Stops > 1);
                })
                .select("AmountPrice");


        var strTitle = "<h3>" + $("#jsFlightFilterStops").html().toString() + "</h3>";
        var strHtml = "";

        if (amountPrice0Stop[0] != null) {
            strHtml += "<label>" +
                    "<input id='CheckBox0' " +
                        "type='checkbox' checked='checked' name='CheckBox0' " +
                         "onclick='javascript:LoadingDataShow();" +
									"amountpricestopfilterchecked.stop0=this.checked;" +
									"FilterData(0,false);' " +
                        " />" +
                    "<strong>" + $("#jsFlightFilterDirectFlight").html().toString() + "</strong> " +
            //"<span>" + Currency + " " + FormatarDecimal(amountPrice0Stop[0].AmountPriceMin) + " </span> " +
                    "<span>" + Currency + " " + amountPrice0Stop[0].AmountPriceMin.localeFormat("N") + " </span> " +
                "</label>";
        }
        if (amountPrice1Stop[0] != null) {
            strHtml += "<label>" +
                    "<input id='CheckBox1' " +
                        "type='checkbox' checked='checked' name='CheckBox1' " +
                         "onclick='javascript:LoadingDataShow();" +
									"amountpricestopfilterchecked.stop1=this.checked;" +
									"FilterData(0,false);' " +
                        " />" +
                    "<strong>" + $("#jsFlighFilterOneOrMoreStops").html().toString() + "</strong> " +
            //"<span>" + Currency + " " + FormatarDecimal(amountPrice1Stop[0].AmountPriceMin) + " </span> " +
                    "<span>" + Currency + " " + amountPrice1Stop[0].AmountPriceMin.localeFormat("N") + " </span> " +
                "</label>";
        }

        if (amountPrice2Stop[0] != null) {
            strHtml += "<label>" +
                    "<input id='CheckBox2' " +
                        "type='checkbox' checked='checked' name='CheckBox2' " +
                         "onclick='javascript:LoadingDataShow();" +
									"amountpricestopfilterchecked.stop2=this.checked;" +
									"FilterData(0,false);' " +
                        " />" +
                    "<strong>" + $("#jsFlightFilter2OrMoreStops").html().toString() + "</strong> " +
            //"<span>" + Currency + " " + FormatarDecimal(amountPrice2Stop[0].AmountPriceMin) + " </span> " +
                    "<span>" + Currency + " " + amountPrice2Stop[0].AmountPriceMin.localeFormat("N") + " </span> " +
                "</label>";
        }

        if (strHtml != "") {
            $("#divAmountPriceStop").html(strTitle + strHtml);
            LoadingDataShow();
        }
        AmountPriceStopFilterIsActive = false;
        LoadingDataHide();
    }
}

function GetCompanyFilter() {

    CompanyFilterIsActive = true;

    var resultsTmp = FlightsFiltered;
    if (resultsTmp.length > 0) {
        Currency = jLinq.from(resultsTmp).select()[0].CurrencyCode;

        var AirlineAmountPrice = jLinq.from(resultsTmp)
        .groupBy("MainAirlineName")
        .select(function(r) {
            return {
                MainAirlineName: r.key,
                AmountPriceMin: jLinq.from(r.items).min("AmountPrice"),
                UrlLogo: r.items[0].UrlLogo,
                MainAirlineCode: r.items[0].MainAirlineCode
            };
        });

        var strTitle = "<h3>" + $("#jsFlightFilterAirlines").html().toString() + "</h3>";
        var strHtml = "";

        companyFilterChecked = new Array();

        $(AirlineAmountPrice).each(function(index) {

            //var AmountPrice = FormatarDecimal(AirlineAmountPrice[index].AmountPriceMin);
            var AmountPrice = AirlineAmountPrice[index].AmountPriceMin.localeFormat("N");
            strHtml += "<div>" +
                                "<input id='CheckBoxAirline" + index + "' " +
                                    "type='checkbox' checked='checked' name='CheckBoxAirline" + index + "' " +
                                    "onclick='javascript:LoadingDataShow();" +
												"CompanyFilter(\"" + AirlineAmountPrice[index].MainAirlineCode + "\",this.checked);" +
												"FilterData(0,false);' " +
                                    "/>" +
                                "<img style='vertical-align:top' title='" + AirlineAmountPrice[index].MainAirlineName + "' alt='" + AirlineAmountPrice[index].MainAirlineName + "' align='middle' src='" + AirlineAmountPrice[index].UrlLogo + "' />" +
                                "<span>" + Currency + " " + AmountPrice + "</span>" +
                            "</div>";
            companyFilterChecked.push(new Company(AirlineAmountPrice[index].MainAirlineName, true, AirlineAmountPrice[index].MainAirlineCode));

        });

        if (strHtml != "") {
            $("#divCompanie").html(strTitle + strHtml);
            LoadingDataShow();
        }
        CompanyFilterIsActive = false;
        LoadingDataHide();
    }
}

function GetAirportFilter() {

    AirportFilterIsActive = true;
    var GoBackIndex = -1;
    airportFilterChecked = new Array();

    var resultsTmp = FlightsFiltered;
    if (resultsTmp.length > 0) {
        Currency = jLinq.from(resultsTmp).select()[0].CurrencyCode;

        var airportDepartureFilter = jLinq.from(resultsTmp)
            .groupBy("DepartureAirport")
            .select(function(r) {
                return {
                    AirportName: jLinq.from(r.items).min("DepartureAirportName"),
                    Airport: r.key,
                    AmountPrice: jLinq.from(r.items).min("AmountPrice"),
                    GoBackIndex: 0
                };
            });
            //debugger;
        var airportArrivalFilter = jLinq.from(resultsTmp)
            .groupBy("ArrivalAirport")
            .select(function(r) {
                return {
                    AirportName: jLinq.from(r.items).min("ArrivalAirportName"), //r.key, //jLinq.from(r.items)[0].ArrivalAirportName,
                    Airport: r.key,
                    AmountPrice: jLinq.from(r.items).min("AmountPrice"),
                    GoBackIndex: 1
                };
            });

        AirportList = jLinq.from(airportDepartureFilter).union(airportArrivalFilter).orderBy("GoBackIndex", "AirportName").select();

        var strHtml = "";

        airportFilterChecked_0 = new Array();
        airportFilterChecked_1 = new Array();


        $(AirportList).each(function(index) {

            if (GoBackIndex != AirportList[index].GoBackIndex) {
                if (AirportList[index].GoBackIndex == 0) {
                    strHtml += "<h3>" + $("#jsFlightFilterDepartureAirport").html().toString() + "</h3>";

                }
                else {
                    $("#divAirportGo").html(strHtml);
                    strHtml = "";
                    strHtml += "<h3>" + $("#jsFlightFilterArrivalAirport").html().toString() + "</h3>";
                }
                GoBackIndex = AirportList[index].GoBackIndex;
            }
            strHtml += "<lab" + "el>" +
                                "<span class='check'><input id='CheckBoxAirport" + index + "' " +
                                    "type='checkbox' checked='checked' name='CheckBoxAirport" + index + "' " +
                                    " GoBackIndex='" + AirportList[index].GoBackIndex + "' " +
                                    "onclick='javascript:LoadingDataShow();" +
											 "AirportFilter_" + GoBackIndex + "(\"" + AirportList[index].Airport + "\",this.checked);" +
											 "FilterData(0,false);' " +
                                    "/></span>" +
            //"<span class='precoAero'>" + Currency + " " + FormatarDecimal(AirportList[index].AmountPrice) + "</span>" +
                                "<span class='precoAero'>" + Currency + " " + AirportList[index].AmountPrice.localeFormat("N") + "</span>" +
                                "<span class='iataAero'>" + AirportList[index].Airport + "</span>" +
                                "<span class='nomeAero'>" + AirportList[index].AirportName + "</span>" +
                            "</lab" + "el>";
            if (GoBackIndex == 0) {
                airportFilterChecked_0.push(new Airport(AirportList[index].Airport, true));
            }
            else {
                airportFilterChecked_1.push(new Airport(AirportList[index].Airport, true));
            }

        });

        if (strHtml != "") {
            $("#divAirportBack").html(strHtml);
            LoadingDataShow();
        }
        AirportFilterIsActive = false;
        LoadingDataHide();
    }
}
//Métodos para ordenação **************************************************
function SetOrder() {
    LoadingDataShow()
    Order = $("#ddlOrderType").val();
    /*Order = $("input[name='radOrder']:checked").val();*/
    OrderType = 'asc';
    FilterData(0, false);
}

//Métodos para setagem dos filtros **************************************************

function SetFilters() {
    if (FlightsFiltered == null)
        FlightsFiltered = FlightFilter();

    GetDayPeriodFilter();
    GetAmountPriceFilter();
    GetAmountPriceStopFilter();
    GetCompanyFilter();
    GetAirportFilter();

}



//Métodos para o "loading" dos dados **************************************************
var loadingFlightFirstFinish = true;
function LoadingDataShow() {
    $("#msgEmpty").hide();
    $("#msgFilterEmpty").hide();

    if ($('#loadingFlight').css('display') == "block" || $('#divLoading').css('display') == "block") {
        loadingFlightFirstFinish = false;
    }
    if (loadingFlightFirstFinish) {
        $('#loadingData').height(document.body.offsetHeight);
        $('#loadingData').width(document.body.offsetWidth);

        $('#loadingData').show();
        $('.CarregandoPequeno').show();

    }
}

function LoadingDataHide() {
    if (!FilterIsFinished() && !IsActive && IsFinished) {
        loadingFlightFirstFinish = true
        $('#loadingData').hide();
        $('.CarregandoPequeno').hide();

        ShowLoading();
    }
}

//Métodos de Filtragem **********************************************************************
function IsInSearchVerify() {
    var bool = false;
    if ((!dayperiodfilterchecked.morning) ||
            (!dayperiodfilterchecked.afternoon) ||
            (!dayperiodfilterchecked.evening) ||
            (!dayperiodfilterchecked.night)) {
        bool = true;
    }

    if ((!amountpricestopfilterchecked.stop0) ||
            (!amountpricestopfilterchecked.stop1) ||
            (!amountpricestopfilterchecked.stop2)) {
        bool = true;
    }

    $(companyFilterChecked).each(function(index) {
        if (!companyFilterChecked[index].value) {
            bool = true;
        }
    });

    $(airportFilterChecked_0).each(function(index) {
        if (!airportFilterChecked_0[index].value) {
            bool = true;
        }
    });

    $(airportFilterChecked_1).each(function(index) {
        if (!airportFilterChecked_1[index].value) {
            bool = true;
        }
    });

    if (AmountPriceFilterMin != amountPriceMin && amountPriceMin != null) {
        bool = true;
    }
    else {
        amountPriceMin = null;
    }

    if (AmountPriceFilterMax != amountPriceMax && amountPriceMax != null) {
        bool = true;
    }
    else {
        amountPriceMax = null;
    }

    return bool;
}

function FilterData(index, reloadFilter) {
    GetAllFlightClient(index, true);
    GenerateMatrix();
}

function AirportFilter_0(airport, value) {
    $(airportFilterChecked_0).each(function(index) {
        if (airportFilterChecked_0[index].airport == airport) {
            airportFilterChecked_0[index].value = value;
        }
    });
}

function AirportFilter_1(airport, value) {
    $(airportFilterChecked_1).each(function(index) {
        if (airportFilterChecked_1[index].airport == airport) {
            airportFilterChecked_1[index].value = value;
        }
    });
}

function CompanyFilter(mainairlinename, value) {
    $(companyFilterChecked).each(function(index) {
        if (companyFilterChecked[index].code == mainairlinename) {
            companyFilterChecked[index].value = value;
        }
    });
}

function Company(company, value, code) {
    this.company = company;
    this.value = value;
    this.code = code;
}

function Airport(airport, value) {
    this.airport = airport;
    this.value = value;
}

function ClearFilter(regenerateFilter) {

    $("#ClearFilterMatrix").hide();
    amountPriceMin = amountPriceMax = null;

    dayperiodfilterchecked.morning = true;
    dayperiodfilterchecked.afternoon = true;
    dayperiodfilterchecked.evening = true;
    dayperiodfilterchecked.night = true;

    amountpricestopfilterchecked.stop0 = true;
    amountpricestopfilterchecked.stop1 = true;
    amountpricestopfilterchecked.stop2 = true;

    if (regenerateFilter) {
        SetFilters();
        FilterData(0, false);
    }
    else {
        $(companyFilterChecked).each(function(index) {
            companyFilterChecked[index].value = true;
        });

        $(airportFilterChecked_0).each(function(index) {
            airportFilterChecked_0[index].value = true;
        });

        $(airportFilterChecked_1).each(function(index) {
            airportFilterChecked_1[index].value = true;
        });

        //Regera slider, porque não tem como limpar o filtro já feito.
        GetAmountPriceFilter();
    }

    try {
        LoadingDataHide();
        $('#loadingData').height(0);
        $('.CarregandoPequeno').hide();
    }
    catch (ex) {
        $('#loadingData').hide();
        $('.CarregandoPequeno').hide();
    }

    return false;
}

function FilterMatrix(stops, airline, price) {
    //alert(airline);
    $("#ClearFilterMatrix").show();

    //Atualiza cias aéreas
    if (airline != '') {
        $(companyFilterChecked).each(function(index) {
            $("#CheckBoxAirline" + index).attr('checked', false);
            if (companyFilterChecked[index].code == airline) {
                companyFilterChecked[index].value = true;
                $("#CheckBoxAirline" + index).attr('checked', 'checked')
            }
            else
                companyFilterChecked[index].value = false;
        });
    }
    else {
        var resultsTmp = FlightsFiltered;
        var tmp;
        if (stops == 0)
            tmp = jLinq.from(resultsTmp)
            .where(function(rec, helper) {
                return (Math.round(Number(rec.AmountPrice.toString().replace(",", "."))) == price);
            }).andLess('Stops', 1).select("MainAirlineCode");
        else
            tmp = jLinq.from(resultsTmp)
            .where(function(rec, helper) {
                return (Math.round(Number(rec.AmountPrice.toString().replace(",", "."))) == price);
            }).andEquals('Stops', stops).select("MainAirlineCode");

        $(companyFilterChecked).each(function(index) {
            $("#CheckBoxAirline" + index).attr('checked', false);
            if (jLinq.from(tmp).equals("MainAirlineCode", companyFilterChecked[index].code).select()[0] != null) {
                companyFilterChecked[index].value = true;
                $("#CheckBoxAirline" + index).attr('checked', 'checked')
            }
            else
                companyFilterChecked[index].value = false;
        });

    }

    amountpricestopfilterchecked.stop0 = false;
    amountpricestopfilterchecked.stop1 = false;
    amountpricestopfilterchecked.stop2 = false;

    //Atualiza paradas
    $("#CheckBox0").attr('checked', false)
    $("#CheckBox1").attr('checked', false)
    $("#CheckBox2").attr('checked', false)
    if (stops == 0) {
        amountpricestopfilterchecked.stop0 = true;
        $("#CheckBox0").attr('checked', 'checked')
    }
    else if (stops == 1) {
        amountpricestopfilterchecked.stop1 = true;
        $("#CheckBox1").attr('checked', 'checked')
    }
    else {
        amountpricestopfilterchecked.stop2 = true;
        $("#CheckBox2").attr('checked', 'checked')
    }

    //Atualiza slider
    $('#slider').slider('values', 0, price);
    $('#slider').slider('values', 1, price + 1);
    $("#divFilterAmountMin").html(Currency + " " + price + ',00');
    $("#divFilterAmountMax").html(Currency + " " + price + ',00');
    amountPriceMin = price;
    amountPriceMax = price;

    FilterData(0, false);
}
