﻿/// <reference path="../jquery-1.3.2-vsdoc2.js" />

var DefaultURL;
$(document).ready(function() {
    DefaultURL = GetBaseUrlWS() + '/WSFlight.asmx';
});
var MaxPageCurrent = 0;
var MaxPageView = 10;
var numGroups = 0;

//Métodos de Paginação ******************************************************************
//#region
function CalculatePages() {
    if (numRows == 0) {
        return;
    }
    if (IsInternational==false && IsOnlyGo)
        numPages = Math.ceil(defineNumberOfPages(Flights));
    else
        numPages = Math.ceil(numRows / numPerPage);
    SetPagerState();
    GenerateNumPage();
}

function DisplayPagCont() {

    $(document).ready(function() {

        $("#divPagCont").show("fast");

    });
}

function ChangePage(journeyIndex) {
    ClearFilter();
    amountPriceMin = null;
    amountPriceMax = null;
    page = 1;
    index = 0;
    Flights = null;
    MaxPageCurrent = 0;

    if (journeyIndexJS != journeyIndex) {
        LoadingDataShow();
        journeyIndexJS = journeyIndex;

        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");
        }
        GetAllFlightClient(0, true);
        GenerateMatrix();
        SetFilters();

        try {
            LoadingDataHide();
            $('#loadingData').height(0);
            $('.CarregandoPequeno').hide();
        }
        catch (ex) {
            $('#loadingData').height(0);
            $('.CarregandoPequeno').hide();
        }
    }
}

function GetNumPage() {
    //Semelhante ao método abaixo
    if (MaxPageCurrent != 0) {
        $('#liPager').append("<a href='javascript:Back(" + (MaxPageCurrent) + ");' title='" + (MaxPageCurrent) + "' rel='content'>...</a> ");
    }

    for (var i = (0 + MaxPageCurrent); i <= numPages - 1; i++) {
        if (i + 1 == page) {
            $('#liPager').append("<span class='pagina-atual'>" + (i + 1) + "</span> ");
        }
        else if (i == (MaxPageView + MaxPageCurrent)) {
            $('#liPager').append("<a href='javascript:Navigate(" + (i) + ",true);' title='" + (i + 1) + "' rel='content'>...</a> ");
            break;
        }
        else if ((i + 1 <= (MaxPageView + MaxPageCurrent))) {
            $('#liPager').append("<a href='javascript:Navigate(" + (i) + ");' title='" + (i + 1) + "' rel='content'>" + (i + 1) + "</a> ");
        }
    }
}


function GenerateNumPage() {
    $('#liPager').empty();
    if (MaxPageCurrent != 0) {
        $('#liPager').append("<a href='javascript:Back(" + (MaxPageCurrent) + ");' title='" + (MaxPageCurrent) + "' rel='content'>...</a> ");
    }
    for (var i = (0 + MaxPageCurrent); i <= numPages - 1; i++) {
        if (i + 1 == page) {
            $('#liPager').append("<span class='pagina-atual'>" + (i + 1) + "</span> ");
        }
        else if (i == (MaxPageView + MaxPageCurrent)) {
            $('#liPager').append("<a href='javascript:Navigate(" + (i) + ",true);' title='" + (i + 1) + "' rel='content'>...</a> ");
            break;
        }
        else if ((i + 1 <= (MaxPageView + MaxPageCurrent))) {
            $('#liPager').append("<a href='javascript:Navigate(" + (i) + ");' title='" + (i + 1) + "' rel='content'>" + (i + 1) + "</a> ");
        }
    }
}

function SetPagerState() {
    var FlightName = configFlightClient.jsFlightSolutionsCombinations;
    if (numPages == 0) {
        $('#pager').hide();

        $("#BackButton").addClass("bt-prev-desabilitado").removeClass("bt-prev");
        $("#NextButton").addClass("bt-next-desabilitado").removeClass("bt-next");
    }
    else {
        if (numPages == 1) {
            $('#pager').hide();
            $("#BackButton").addClass("bt-prev-desabilitado").removeClass("bt-prev");
            $("#NextButton").addClass("bt-next-desabilitado").removeClass("bt-next");

            $('#divPagCont').empty();
            var values = null;

            if (IsInternational == false && IsOnlyGo) {
                values = {
                    Result1: numGroups + " " + configFlightClient.jsFlightPageFlightsOf + " ",
                    totalResults1: numGroups + " " + FlightName
                };
            }
            else {
                values = {
                    Result1: (numRows % numPerPage) + " " + configFlightClient.jsFlightPageFlightsOf + " ",
                    totalResults1: numRows + " " + FlightName
                };
            }
            $("#divPagCont").append($.tmpl(templatePagCont, values));
            DisplayPagCont();

        }
        else {
            $('#pager').show();
        }
        if (index == 0 || page == 1) {
            $("#BackButton").addClass("bt-prev-desabilitado").removeClass("bt-prev");
        }
        else {
            $("#BackButton").addClass("bt-prev").removeClass("bt-prev-desabilitado");

        }

        if (page == numPages || page > numPages) {

            $("#NextButton").addClass("bt-next-desabilitado").removeClass("bt-next");

            if (numPages != 1) {
                $('#divPagCont').empty();
                var values = null;
                if (IsInternational == false && IsOnlyGo) {
                    values = {
                        Result1: (numGroups % numPerPage) + " " + configFlightClient.jsFlightPageFlightsOf + " ",
                        totalResults1: numGroups + " " + FlightName 
                    };
                }
                else {
                    values = {
                        Result1: (numRows % numPerPage) + " " + configFlightClient.jsFlightPageFlightsOf + " ",
                        totalResults1: numRows + " " + FlightName 
                    };
                }

                    $("#divPagCont").append($.tmpl(templatePagCont, values));
                DisplayPagCont();
            }
        }
        else {

            $("#NextButton").addClass("bt-next").removeClass("bt-next-desabilitado");

            $('#divPagCont').empty();
            var values1 = null;
            if (IsInternational == false && IsOnlyGo) {
                values1 = {
                    Result1: " " + configFlightClient.jsFlightPageFlights10Of + " ",
                    totalResults1: numGroups + " " + FlightName 
                };
            }
            else {
                values1 = {
                    Result1: " " + configFlightClient.jsFlightPageFlights10Of + " ",
                    totalResults1: numRows + " " + FlightName
                };
            }
            
            $("#divPagCont").append($.tmpl(templatePagCont, values1));
            DisplayPagCont();
        }
    }
}

function Next() {
    if (page == numPages) { return; }

    index = index + numPerPage;
    page = page + 1;
    MoveToTop();
    GetAllFlightClient(index, true);
    if ((page - 1) % MaxPageView == 0) {
        MaxPageCurrent += 10;
        GenerateNumPage();
    }
}

function Navigate(selectedPage, regenerate) {
    index = selectedPage * numPerPage;
    page = selectedPage + 1;
    MoveToTop();
    GetAllFlightClient(index, true);
    //Verifica se tem que atualizar a paginação para as próximas 10
    if (regenerate) {
        if (selectedPage != 0 && (selectedPage % MaxPageView == 0)) {
            MaxPageCurrent += 10;
            GenerateNumPage();
        }
    }
}

function Back(selectedPage) {
    if (page == 1) { return; }
    index = index - numPerPage;
    page = page - 1;
    MoveToTop();
    GetAllFlightClient(index, true);
    if ((selectedPage % MaxPageView == 0) || (!selectedPage && page % MaxPageView == 0)) {
        MaxPageCurrent -= 10;
        GenerateNumPage();
    }
}

function GenerateList() {
    if (Flights != null) {
        $('#Departure').empty();
        $('#Departure').append(Departure);
        $('#Arrival').empty();
        $('#Arrival').append(Arrival);

        $('#divDateGo').empty();
        $('#divDateBack').empty();

        if (journeyIndexJS == 0) {
            $('#divDateGo').append(DepartureDate);
        }
        else {
            $('#divDateBack').append(ArrivalDate);
        }

        $('#divDateCombinate').empty();
        $('#divDateCombinate').append(DepartureDate + " - " + ArrivalDate);

        if (IsInternational) {
            $('#btnVolta').hide();
            $('#btnIda').hide();
            $('#divCombinate').show();
            //$('#divBordaTopAba').removeClass("borda-top-abas");
            $('.opcoesIdaVolta').hide();
        } else if (IsOnlyGo) {
            $('#btnVolta').hide();
            $('#btnIda').show();
            $('#divCombinate').hide();
            //$('#divBordaTopAba').addClass("borda-top-abas");
            $('.opcoesIdaVolta').show();
        }

        //$('#FlightQuantity').empty();
        //$('#FlightQuantity').append(numRows);
        CalculatePages();
        PublishGrid();
    }
}

function SendToValuation() {
    var guidSession = $('[id$=hSessionGuid]').val();
    $.ajax({
        type: "POST",
        url: DefaultURL + "/SendToValuation",
        data: "{" + "journeyIdSelectedGo:" + journeyIdSelectedGo + ",journeyIdSelectedBack:" + journeyIdSelectedBack +
                    ",groupIdSelected:0, guidSession:'" + guidSession + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {
            RedirectToValuation(response.d)
        },
        failure: function(msg) {

        }
    });
}

function SendToValuationLowFare(lowFareId) {
    var guidSession = $('[id$=hSessionGuid]').val();
    $.ajax({
        type: "POST",
        url: DefaultURL + "/SendToValuationLowFare",
        data: "{lowFareId:" + lowFareId + ", guidSession:'" + guidSession + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {
            RedirectToValuation(response.d)
        },
        failure: function(msg) {

        }
    });
}

function RedirectToValuation(Url) {

    document.location = Url;
}
var journeySelectedEmail = 0;
function ShowModal(index) {
    if (validateReserve(index)) {
        $('#modal').dialog('open');
    }
    return false;
}

function validateReserve(index) {
    var SelectGo = journeyIdSelectedGo;
    

    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 CloseModal() {

    $(".nameFrom").val('');
    $(".emailFrom").val('');
    $(".nameTo").val('');
    $(".emailTo").val('');
    $(".subject").val('');
    $(".message").val('');
    $(".nameFrom").removeClass("FieldErro");
    $(".emailFrom").removeClass("FieldErro");
    $(".nameTo").removeClass("FieldErro");
    $(".emailTo").removeClass("FieldErro");
    $(".subject").removeClass("FieldErro");
    $(".message").removeClass("FieldErro");

    $('#modal').dialog('close');
    return false;
}

function SendMail() {

    if (typeof (Page_ClientValidate) == 'function') {
        if (Page_ClientValidate('SendEmail') == false) {
            return false;
        }
    }

    var nameFrom = $(".nameFrom").val();
    var emailFrom = $(".emailFrom").val();
    var nameTo = $(".nameTo").val();
    var emailTo = $(".emailTo").val();
    var subject = $(".subject").val();
    var message = $(".message").val();
    
    var guidSession = $('[id$=hSessionGuid]').val();

    $.ajax({
        type: "POST",
        url: DefaultURL + "/SendEmail",
        data: "{" + "'nameFrom':'" + nameFrom + "','nameTo':'" + nameTo + "','emailFrom':'" + emailFrom + "','emailTo':'" + emailTo + "','subject':'" + nameFrom + configFlightClient.jsFlightSolutionsIndicatedaFlight + "','message':'" + message + "','journeyId':" + journeyIdSelectedGo + ",'trackId':" + Number($("#trackId").html()) + ",'isInternational':" + IsInternational + ",'Url':'" + window.location.href + "', 'guidSession':'" + guidSession + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {
            //window.location.href;
            $(".nameFrom").val('');
            $(".emailFrom").val('');
            $(".nameTo").val('');
            $(".emailTo").val('');
            $(".subject").val('');
            $(".message").val('');
        },
        failure: function(msg) {
//            alert(msg.responseText);

        },
        error: function(msg) {
//            alert(msg.responseText);
        }
    });
    $('#modal').dialog('close');
    return false;
}


$(function() {
    $('#modal').dialog({
        autoOpen: false,
        //closeText: 'fechar',
        width: 600
    });
    $("#modal").dialog().parents(".ui-dialog").find(".ui-dialog-titlebar").remove();
});

function defineNumberOfPages(result) {
    var nPage = ((result.length == 0) ? 0 : 1);
    var i = 0;
    var AmountPriceAux = 0;
    var MainAirlineCodeAux = '';
    var nGroup = 0;
    numGroups = 0;

    for (i = 0; i < result.length; i++) {
        if (AmountPriceAux != result[i].AmountPrice || MainAirlineCodeAux != result[i].MainAirlineCode) {
            nGroup++;
            numGroups++;
            AmountPriceAux = result[i].AmountPrice;
            MainAirlineCodeAux = result[i].MainAirlineCode;
        }
        if (nGroup > 9) {
            nGroup = 0;
            nPage++;
        }
    }
        
    return nPage
}
