﻿//Please edit in notepad++ , by using Collapse (Alt + 0) and Open ( Alt + Shift + 0) options

//CONSTANTS
var NUMBER_OF_AIRLINES = 5;
var GET_QUERY_ID_TIMEOUT = 15000;
var FLIGHT_QUERY_TIMEOUT = 160000;
var LOG_QUERY = true;
var LOG_QUERY_TIMEOUT = 20000;
var SHOW_BOOKING_COM_AD = true;
var BOOKING_COM_AD_TIMEOUT = 10000;
var CURRENT_LANG = "tr";
var trDayNames = ["Pzr", "Pzt", "Sal", "Çar", "Perş", "Cum", "Cts"];
var enDayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
var trResources = ["Devam eden sorgunuz var lütfen bitmesini bekleyiniz yada sayfayı yenileyiniz!",
                "Kalkış ve varış şehirleri aynı olamaz",
                "Lütfen gidiş tarihindeki eksiklik ve hataları düzeltiniz.",
                "Lütfen dönüş tarihindeki eksiklik ve hataları düzeltiniz.",
                "Dönüş tarihi gidiş tarihinden önce olamaz.",
                "uçuş bulundu",
                "Havayolu",
                "Uçuş no",
                "Tarih",
                "Kalkış",
                "Varış",
                "Ücret",
                "Sunucu bağlantısı başarısız, lütfen tekrar deneyiniz!",
                "Satınal"];
var enResources = ["Your search is running now, please wait until it finishes or refresh the page!",
                "Dept. and arrival cities cannot be same",
                "Please correct the dept. date",
                "Please correct the arrival date",
                "Arrival date must be later than dept. date",
                "flights found",
                "Airline",
                "Flight No",
                "Date",
                "Dept.",
                "Arrv.",
                "Price",
                "Your server connection is insuccessful, please try again!",
                "Buy"];
var currentResources = null;
//end of CONSTANTS

//SEARCH FIELDS
var isSearchRequested, isSearchInProgress;
var from, to;
var depDate, retDate;
var isRoundTrip;
var ajaxResponseCount;
var searchQueryId;
var depQueryId;
var retQueryId;
//end of SEARCH FIELDS

//DISPLAY OPTIONS
var isShowFullFlights;
var isHideTransitFlights;
var isIncludeTax;
//end of DISPLAY OPTIONS

//DEPARTURE FLIGHTS
var isOnlyDepRequested, isDepInProgress;
var depFlights;
var minDepFare, maxDepFare, minDepFareWithTax, maxDepFareWithTax;
var currentMaxDepFare = 0, currentMinDepHour = 0, currentMaxDepHour = 24;
var depVisibleFlightCount;
var depSortList = [[5, 0]];
//end of DEPARTURE FLIGHTS

//RETURN FLIGHTS
var isOnlyRetRequested, isRetInProgress;
var retFlights;
var minRetFare, maxRetFare, minRetFareWithTax, maxRetFareWithTax;
var currentMaxRetFare = 0, currentMaxRetHour = 24, currentMinRetHour = 0;
var retVisibleFlightCount;
var retSortList = [[5, 0]];
//end of RETURN FLIGHTS

//LOG DATA
var overallQueryStartTime, overallQueryEndTime, overallQueryDuration;
var queryStartTimes, queryEndTimes, clientQueryDurations, serverQueryDurations;
var successFlags, cacheFlags;
//end of LOG DATA

//AUXILIARY FUNCTIONS
function isDate(dateStr) {
    var datePat = /^(\d{1,2})(\/|.)(\d{1,2})(\/|.)(\d{4})$/;
    var matchArray = dateStr.match(datePat); // is the format ok?
    if (matchArray == null) {
        return false;
    }

    day = matchArray[1]; // p@rse date into variables
    month = matchArray[3];
    year = matchArray[5];

    if (month < 1 || month > 12) { // check month range
        return false;
    }

    if (day < 1 || day > 31) {
        return false;
    }

    if ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31) {
        return false;
    }

    if (month == 2) { // check for february 29th
        var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
        if (day > 29 || (day == 29 && !isleap)) {
            return false;
        }
    }
    return true; // date is valid
}
function convertToDate(dateStr) {
    var datePat = /^(\d{1,2})(\/|.)(\d{1,2})(\/|.)(\d{4})$/;
    var matchArray = dateStr.match(datePat); // is the format ok?
    if (matchArray == null) {
        return false;
    }

    day = matchArray[1]; // p@rse date into variables
    month = matchArray[3] - 1;
    year = matchArray[5];

    var resultDate = new Date(year, month, day);
    return resultDate;
}
function convertTime(hourAsInt, isForUI) {
    var convertedTime = "";
    if (hourAsInt < 10) {
        convertedTime = "0";
    }
    if (hourAsInt == 24 && isForUI) {
        convertedTime = "23:59";
    } else {
        convertedTime += hourAsInt.toString() + ":00";
    }
    return convertedTime;
}
function getShortDayStr(dayOfTheWeek) {
    var dayStr = "";
    var dayNamesArray = "";
    if (CURRENT_LANG == "tr") {
        dayNamesArray = trDayNames;
    }
    else {
        dayNamesArray = enDayNames;
    }
    dayStr = dayNamesArray[dayOfTheWeek];
    return dayStr;
}
function getDateStr(dateStr, dayOffset) {
    var convertedDate = convertToDate(dateStr);
    convertedDate.setDate(convertedDate.getDate() + dayOffset);

    var day = convertedDate.getDate();
    var month = convertedDate.getMonth() + 1;
    var year = convertedDate.getFullYear();

    if (day < 10) {
        day = "0" + day;
    }
    if (month < 10) {
        month = "0" + month;
    }

    dateStr = day + "." + month + "." + year + " " + getShortDayStr(convertedDate.getDay());
    return dateStr;
}
function hide(domId) {
    $('#' + domId).css('display', 'none');
}
function show(domId) {
    $('#' + domId).css('display', 'block');
}
//end of AUXILIARY FUNCTIONS

//CLEAR FUNCTIONS    				//--OK--\\
function clearFields() {
    $('#search_gidis_tarihi').val();
    $('#search_donus_tarihi').val();

    from = null;
    to = null;
    depDate = null;
    retDate = null;
    isRoundTrip = true;
}
function clearDisplayOptions() {
    isIncludeTax = false;
    isShowFullFlights = false;
    isHideTransitFlights = false;
}
function clearDepartureFlights() {
    hide('departureFlightsDiv');

    delete depFlights;

    isOnlyDepRequested = false;
    isDepInProgress = false;
    ajaxResponseCount = 0;
    depVisibleFlightCount = 0;
    depFlights = [];
    depQueryId = null;

    minDepFare = 0;
    minDepFareWithTax = 0;
    maxDepFare = 0;
    maxDepFareWithTax = 0;
    currentMinDepFare = 0;
}
function clearReturnFlights() {
    hide('returnFlightsDiv');

    delete retFlights;

    isOnlyRetRequested = false;
    isRetInProgress = false;
    ajaxResponseCount = 0;
    retQueryId = null;
    retVisibleFlightCount = 0;
    retFlights = [];

    minRetFare = 0;
    minRetFareWithTax = 0;
    maxRetFare = 0;
    maxRetFareWithTax = 0;
    currentMinRetFare = 0;
}
function clearLogData() {
    delete successFlags;
    delete clientQueryDurations;
    delete serverQueryDurations;
    delete queryStartTimes;
    delete queryEndTimes;
    delete cacheFlags;
    cacheFlags = [];
    successFlags = [];
    clientQueryDurations = [];
    serverQueryDurations = [];
    queryStartTimes = [];
    queryEndTimes = [];
    overallQueryStartTime = 0;
    overallQueryEndTime = 0;
    ovarallQueryDuration = 0;

    var counter = 0;
    for (counter = 0; counter < NUMBER_OF_AIRLINES; counter++) {
        successFlags[counter] = false;
        cacheFlags[counter] = false;
        serverQueryDurations[counter] = 0;
        clientQueryDurations[counter] = 0;
        queryStartTimes[counter] = 0;
        queryEndTimes[counter] = 0;
    }
}
function clearAll() {
    isSearchRequested = false;
    isSearchInProgress = false;
    searchQueryId = null;
    hide('depSliders');
    hide('retSliders');
    hide('depTopPanel');
    hide('retTopPanel');
    hide('hotelAdDiv');
    hide('depCaption');
    hide('retCaption');
    clearFields();
    clearDisplayOptions();
    clearDepartureFlights();
    clearReturnFlights();
    clearLogData();
}
//end of CLEAR FUNCTIONS

//PAGE INITIALIZATION FUNCS 		//--OK--\\
$(document).ready(initializePage);
function loadTableSorterWidget() {
    $.tablesorter.addWidget({
        id: "saveSortLists",
        format: function(table) {
            var sortList = table.config.sortList;
            var tableId = table.id;

            if (tableId == 'departureFlightsTable') {
                delete depSortList;
                depSortList = sortList;
            } else {
                delete retSortList;
                retSortList = sortList;
            }
        }
    });
}
function loadDateTimePicker() {
    $.datepicker.setDefaults($.datepicker.regional[CURRENT_LANG.toLowerCase()]);
    $('#search_donus_tarihi').datepicker({ changeMonth: true, changeYear: true, minDate: -0, constrainInput: true });
    $('#search_gidis_tarihi').datepicker({ changeMonth: true, changeYear: true, minDate: -0, constrainInput: true, onSelect:
            function(dateText, inst) {
                var selectedDate = inst.input.datepicker('getDate');
                var returnDatePicker = $('#search_donus_tarihi');
                returnDatePicker.datepicker('option', 'minDate', selectedDate);
                if (isRoundTrip) {
                    returnDatePicker.datepicker('setDate', selectedDate);
                }
            }
    });
}
function initializePage() {
    clearAll();
    loadDateTimePicker();
    loadTableSorterWidget();
}
//end of PAGE INITIALIZATION FUNCS

//EXTRAS
function showBookingComAD() {
    if (SHOW_BOOKING_COM_AD) {
        makeBookingComADServiceCall(to);
    }
}
//end of EXTRAS

//WEB SERVICE CALLS			//--OK--\\
function checkIfFinished() {
    if (ajaxResponseCount == NUMBER_OF_AIRLINES) {
        if (isSearchInProgress || isDepInProgress || isRetInProgress) {
            overallQueryEndTime = new Date();
            overallQueryDuration = overallQueryEndTime - overallQueryStartTime;

            if (isSearchInProgress) {
                if (isRoundTrip) {
                    makeLogQueryServiceCall(searchQueryId, from, to, depDate, retDate, "1",
				                        cacheFlags, successFlags, clientQueryDurations,
				                        serverQueryDurations, overallQueryDuration);
                } else {
                    makeLogQueryServiceCall(searchQueryId, from, to, depDate, null, "0",
				                        cacheFlags, successFlags, clientQueryDurations,
				                        serverQueryDurations, overallQueryDuration);
                }
            } else if (isDepInProgress) {
                makeLogQueryServiceCall(depQueryId, from, to, depDate, null, "2",
				                            cacheFlags, successFlags, clientQueryDurations,
				                            serverQueryDurations, overallQueryDuration);

            } else if (isRetInProgress) {
                makeLogQueryServiceCall(retQueryId, to, from, retDate, null, "3",
				                        cacheFlags, successFlags, clientQueryDurations,
				                        serverQueryDurations, overallQueryDuration);
            }

            isSearchInProgress = false;
            isRetInProgress = false;
            isDepInProgress = false;
            updateFlightCounts();
            showFlightCounts();
        }
    }
}
function onFlightQuerySuccess(result) {
    ajaxResponseCount++;
    processFlightResults(result.d);
    checkIfFinished();
}
function onFlightQueryError(error) {
    //    debugger;
    ajaxResponseCount++;
    checkIfFinished();
}
function getWebServiceUrl() {
    var serviceUrl;
    if (window.location.toString().indexOf('www') > -1) {
        serviceUrl = 'http://www.bulucak.com/bulucakwebservice/bulucakwebservice.asmx/';
    } else {
        serviceUrl = 'http://bulucak.com/bulucakwebservice/bulucakwebservice.asmx/';
    }
    return serviceUrl;
}
function onGenericSuccess(result) {
}
function onGenericError(error) {
}
function makeServiceCall(serviceUrl, jsonParams, responseTimeout, onSuccess, onError) {
    var stringifiedParams = JSON.stringify(jsonParams);
    $.ajax({
        type: "POST",
        url: serviceUrl,
        data: stringifiedParams,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        timeout: responseTimeout,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("Content-type",
							 "application/json; charset=utf-8");
        },
        success: onSuccess,
        error: onError
    });
}
function queryAllAirlines(pQueryId, pDepCity, pArrCity, pDepDate, pRetDate) {
    overallQueryStartTime = new Date();
    loadTopPanels();
    showLoadingResults();
    var currentAirlineCode = 0;
    while (currentAirlineCode < NUMBER_OF_AIRLINES) {
        makeFlightQueryServiceCall(pQueryId, currentAirlineCode, pDepCity, pArrCity, pDepDate, pRetDate);
        currentAirlineCode++;
    }
}
function makeFlightQueryServiceCall(pQueryId, pAirlineCode, pDepCity, pArrCity, pDepDate, pRetDate) {
    var webMethod = getWebServiceUrl() + 'FindFlights';
    var params = { 'queryId': pQueryId, 'airline': pAirlineCode, 'from': pDepCity, 'to': pArrCity, 'departureDate': pDepDate, 'returnDate': pRetDate };
    queryStartTimes[pAirlineCode] = new Date();
    makeServiceCall(webMethod, params, FLIGHT_QUERY_TIMEOUT, onFlightQuerySuccess, onFlightQueryError);
}
function makeLogQueryServiceCall(pQueryId, pDepCity, pArrCity, pDepDate, pRetDate, pQueryType, pCacheFlags, pSuccessFlags, pClientQueryDurations, pServerQueryDurations,
								 pOverallQueryDuration) {
    if (LOG_QUERY) {
        var webMethod = getWebServiceUrl() + 'LogQuery';
        var params = { 'queryId': pQueryId,
            'depCity': pDepCity,
            'arrCity': pArrCity,
            'depDate': pDepDate,
            'retDate': pRetDate,
            'queryType': pQueryType,
            'cacheFlags': pCacheFlags,
            'successFlags': pSuccessFlags,
            'clientQueryDurations': pClientQueryDurations,
            'serverQueryDurations': pServerQueryDurations,
            'overallQueryDuration': pOverallQueryDuration
        };
        makeServiceCall(webMethod, params, LOG_QUERY_TIMEOUT, onGenericSuccess, onGenericError);
    }
}
function makeBookingComADServiceCall(pAirlineCode) {
    if (CURRENT_LANG == "tr") {
        var webMethod = getWebServiceUrl() + 'GetHotelAD';
        var params = { 'airlineCode': pAirlineCode };
        makeServiceCall(webMethod, params, BOOKING_COM_AD_TIMEOUT,
			    function(result) {
			        $('#hotelAdDiv').html(result.d);
			        show('hotelAdDiv');
			    },
			    function(error) {
			        hide('hotelAdDiv');
			    }
	    );
    }
}
function makeGetQueryIDServiceCall(pDepCity, pArrCity, pDepDate, pRetDate) {
    var pQueryType = 0;
    if (isSearchRequested && isRoundTrip) {
        pQueryType = 1;
    } else if (isOnlyDepRequested) {
        pQueryType = 2;
    } else if (isOnlyRetRequested) {
        pQueryType = 3;
    }

    var webMethod = getWebServiceUrl() + 'GetQueryID';
    var params = { 'queryType': pQueryType };
    makeServiceCall(webMethod, params, GET_QUERY_ID_TIMEOUT,
				function(result) {
				    if (isSearchRequested) {
				        searchQueryId = result.d;
				    } else if (isOnlyDepRequested) {
				        depQueryId = result.d;
				    } else if (isOnlyRetRequested) {
				        retQueryId = result.d;
				    }
				    queryAllAirlines(result.d, pDepCity, pArrCity, pDepDate, pRetDate);
				},
				function(error) {
				    clearAll();
				    alert(currentResources[12].toString());
				}
		);
}
//end of WEB SERVICE CALLS

//SEARCH FUNCTIONS			//--OK--\\
function isAvailableForNewQuery() {
    if (isSearchInProgress || isDepInProgress || isRetInProgress) {
        alert(currentResources[0].toString());
        return false;
    } else {
        return true;
    }
}
function toggleReturnDate() {
    var isOpen = $('#rbRoundTrip').attr('checked');
    if (isOpen) {
        $('#search_donus_tarihi').removeAttr("disabled");
    } else {
        $('#search_donus_tarihi').val('');
        $('#search_donus_tarihi').attr("disabled", true);
    }
    isRoundTrip = isOpen;
}
function validateSearch() {
    $("#validationError").html('');

    var txtFrom = $("#search_nereden").val();
    var txtTo = $("#search_nereye").val();
    var msg = '';
    var tempResources = "";
    if (CURRENT_LANG == "tr") {
        tempResources = trResources;
    }
    else {
        tempResources = enResources;
    }

    if (txtFrom.length != 3) {
        msg += 'Kalkış şehrini seçmediniz!<br />';
    }

    if (txtTo.length != 3) {
        msg += 'Varış şehrini seçmediniz!<br />';
    }
    if ((txtTo == txtFrom) || (txtTo == 'IST' && txtFrom == 'SAW') || (txtTo == 'SAW' && txtFrom == 'IST')) {
        //        msg += 'Kalkış ve varış şehirleri aynı olamaz!<br />';
        msg += tempResources[1].toString() + '<br/>';
    }

    var strDepDate = String($("#search_gidis_tarihi").val());
    if (!isDate(strDepDate)) {
        msg += tempResources[2].toString() + '<br />';
    }

    if ($('#rbRoundTrip').attr('checked')) {
        var strRetDate = String($("#search_donus_tarihi").val());
        if (!isDate(strRetDate)) {
            msg += tempResources[3].toString() + '<br />';
        } else {
            var convertedRetDate = convertToDate(strRetDate);
            var convertedDepDate = convertToDate(strDepDate);
            if (convertedDepDate > convertedRetDate) {
                msg += tempResources[4].toString() + '<br />';
            }
        }
    }

    if (msg != '') {
        $("#validationError").html(msg);
        return false;
    }
    return true;
}
function setSearchFields() {
    isRoundTrip = $('#rbRoundTrip').attr('checked');
    from = $('#search_nereden').val();
    to = $('#search_nereye').val();
    depDate = $('#search_gidis_tarihi').val();

    if (isRoundTrip) {
        retDate = $('#search_donus_tarihi').val();
    } else {
        retDate = "";
    }
}
function setDisplayOptions() {
    isIncludeTax = $('#chkIncludeTax').attr('checked');
    isShowFullFlights = $('#chkShowFullFlights').attr('checked');
    isHideTransitFlights = $('#chkHideTransit').attr('checked');
}
function search() {
    if (isAvailableForNewQuery()) {
        clearAll();
        setSearchFields();
        if (validateSearch()) {
            isSearchRequested = true;
            isSearchInProgress = true;

            $('#btnSearch').attr("disabled", "disabled");
            hide('airlineLogos');
            show('searchFilter');

            show('depCaption');
            if (isRoundTrip) {
                show('retCaption');
            }

            showBookingComAD();

            //flight queries
            makeGetQueryIDServiceCall(from, to, depDate, retDate);
            $('#btnSearch').attr("disabled", "");
        }
    }
}
//end of SEARCH FUNCTIONS

//NEXT-PREV DAY FUNCTIONS 			//--OK--\\
function changeDepDay(dayStr) {
    if (isAvailableForNewQuery()) {
        clearDepartureFlights();
        clearLogData();
        depDate = dayStr.substr(0, dayStr.length - 4);
        isOnlyDepRequested = true;
        isDepInProgress = true;
        isSearchRequested = false;
        isOnlyRetRequested = false;
        makeGetQueryIDServiceCall(from, to, depDate, null);
    }
}
function changeRetDay(dayStr) {
    if (isAvailableForNewQuery()) {
        clearReturnFlights();
        clearLogData();
        retDate = dayStr.substr(0, dayStr.length - 4)
        isOnlyRetRequested = true;
        isRetInProgress = true;
        isSearchRequested = false;
        isOnlyDepRequested = false;
        makeGetQueryIDServiceCall(to, from, retDate, null);
    }
}
//end of NEXT-PREV FUNCTIONS

//DISPLAY OPTIONS
function includeTax() {
    setDisplayOptions();
    loadDepPriceSlider();
    loadRetPriceSlider();
    populateTables();
}
function showFullFlights() {
    setDisplayOptions();
    populateTables();
}
function hideTransitFlights() {
    setDisplayOptions();
    populateTables();
}
//end of DISPLAY OPTIONS

//TOP-PANEL LOADERS
function showLoadingResults() {
    if (isSearchRequested || isOnlyDepRequested) {
        hide('depFlightCount');
        show('depLoadingResults');
    }
    if ((isSearchRequested && isRoundTrip) || isOnlyRetRequested) {
        hide('retFlightCount');
        show('retLoadingResults');
    }
}
function showFlightCounts() {
    if (isSearchRequested || isOnlyDepRequested) {
        show('depFlightCount');
        hide('depLoadingResults');
    }
    if ((isSearchRequested && isRoundTrip) || isOnlyRetRequested) {
        show('retFlightCount');
        hide('retLoadingResults');
    }
}
function updateDepFlightCount() {
    var html = "";
    var color = "Green";


    if (depVisibleFlightCount == 0) {
        color = "Red";
    }
    html = '<font color="' + color + '"><b>' + depVisibleFlightCount + '</b></font> ' + currentResources[5].toString() + '';
    $('#depFlightCount').html(html);
}
function updateRetFlightCount() {
    var html = "";
    var color = "Green";
    var tempResources = "";

    if (retVisibleFlightCount == 0) {
        color = "Red";
    }
    html = '<font color="' + color + '"><b>' + retVisibleFlightCount + '</b></font> ' + currentResources[5].toString() + '';
    $('#retFlightCount').html(html);
}
function updateFlightCounts() {
    if (isSearchRequested) {
        updateDepFlightCount();
        updateRetFlightCount();
    }
    if (isOnlyDepRequested) {
        updateDepFlightCount();
    }
    if (isOnlyRetRequested) {
        updateRetFlightCount();
    }
}
function loadDepTopPanel() {
    var prevDayStr = getDateStr(depDate, -1);
    var prevHtml = '<a href="javascript:changeDepDay(\'' + prevDayStr + '\');">&lt;&lt; ' + prevDayStr + '</a>';
    var nextDayStr = getDateStr(depDate, 1);
    var nextHtml = '<a href="javascript:changeDepDay(\'' + nextDayStr + '\');">' + nextDayStr + ' &gt;&gt;</a>&nbsp;&nbsp;';

    var xPrevDayStr = prevDayStr.substr(0, prevDayStr.length - 4);
    var xPrevDay = convertToDate(xPrevDayStr);

    var xNextDayStr = nextDayStr.substr(0, nextDayStr.length - 4);
    var xNextDay = convertToDate(xNextDayStr);

    var today = new Date();
    today.setHours(0, 0, 0, 0);

    if (today > xNextDay) {
        nextHtml = '&nbsp;';
    }
    if (today > xPrevDay) {
        prevHtml = '&nbsp;';
    }

    $('#depPrevDay').html(prevHtml);
    $('#depNextDay').html(nextHtml);
    show('depTopPanel');
}
function loadRetTopPanel() {
    var prevDayStr = getDateStr(retDate, -1);
    var prevHtml = '<a href="javascript:changeRetDay(\'' + prevDayStr + '\');">&lt;&lt; ' + prevDayStr + '</a>';
    var nextDayStr = getDateStr(retDate, 1);
    var nextHtml = '<a href="javascript:changeRetDay(\'' + nextDayStr + '\');">' + nextDayStr + ' &gt;&gt;</a>&nbsp;&nbsp;';

    var xPrevDayStr = prevDayStr.substr(0, prevDayStr.length - 4);
    var xPrevDay = convertToDate(xPrevDayStr);

    var xNextDayStr = nextDayStr.substr(0, nextDayStr.length - 4);
    var xNextDay = convertToDate(xNextDayStr);

    var today = new Date();
    today.setHours(0, 0, 0, 0);

    if (today > xNextDay) {
        nextHtml = '&nbsp;';
    }
    if (today > xPrevDay) {
        prevHtml = '&nbsp;';
    }

    $('#retPrevDay').html(prevHtml);
    $('#retNextDay').html(nextHtml);
    show('retTopPanel');
}
function loadTopPanels() {
    if (isSearchRequested) {
        loadDepTopPanel();
        show('depTopPanel');
        if (isRoundTrip) {
            loadRetTopPanel();
            show('retTopPanel');
        }
    }
    if (isOnlyDepRequested) {
        loadDepTopPanel();
        show('depTopPanel');
    }
    if (isOnlyRetRequested) {
        loadRetTopPanel();
        show('retTopPanel');
    }
}
//end of TOP-PANEL LOADERS

//SLIDER LOADERS			//--OK--\\
function enableSlider(sliderId) {
    $('#' + sliderId).slider('enable');
}
function disableSlider(sliderId) {
    $('#' + sliderId).slider('disable');
}
function loadDepPriceSlider() {
    if (depFlights.length > 0) {
        var maxFare = 0;
        var minFare = 0;
        if (isIncludeTax) {
            maxFare = maxDepFareWithTax;
            minFare = minDepFareWithTax;
        } else {
            maxFare = maxDepFare;
            minFare = minDepFare;
        }

        var actualCurrentMaxDepFare = currentMaxDepFare;
        if (currentMaxDepFare > maxFare) {
            actualCurrentMaxDepFare = maxFare;
        } else if (currentMaxDepFare < minFare) {
            actualCurrentMaxDepFare = minFare;
        }

        $('#sliderDepPrice').slider('destroy');
        $('#sliderDepPrice').slider({
            animate: true,
            range: 'min',
            max: maxFare,
            min: minFare,
            step: 1,
            value: currentMaxDepFare,
            slide: function(event, ui) {
                if (CURRENT_LANG == "tr") {

                    $('#sliderDepPriceInfo').html("<b><font color=\"red\">" + ui.value.toString() + " TL </font></b>' den ucuz uçuşları göster");
                }

                else {
                    $('#sliderDepPriceInfo').html("Show flights cheaper than : <b><font color=\"red\">" + ui.value.toString() + " TL </font></b>");
                }

            },
            stop: function(event, ui) {
                var newMaxFare = ui.value;
                if (newMaxFare != currentMaxDepFare) {
                    currentMaxDepFare = newMaxFare;
                    populateDepTable();
                }
            }
        });
        if (CURRENT_LANG == "tr") {
            $('#sliderDepPriceInfo').html("<b><font color=\"red\">" + actualCurrentMaxDepFare + " TL </font></b>' den ucuz uçuşları göster");
        }
        else {
            $('#sliderDepPriceInfo').html("Show flights cheaper than : <b><font color=\"red\">" + actualCurrentMaxDepFare + " TL </font></b>");
        }
        currentMaxDepFare = actualCurrentMaxDepFare;
    }
}
function loadRetPriceSlider() {
    if (retFlights.length > 0) {
        var maxFare = 0;
        var minFare = 0;

        if (isIncludeTax) {
            maxFare = maxRetFareWithTax;
            minFare = minRetFareWithTax;
        } else {
            maxFare = maxRetFare;
            minFare = minRetFare;
        }


        var actualCurrentMaxRetFare = currentMaxRetFare;
        if (currentMaxRetFare > maxFare) {
            actualCurrentMaxRetFare = maxFare;
        } else if (currentMaxRetFare < minFare) {
            actualCurrentMaxRetFare = minFare;
        }

        $('#sliderRetPrice').slider('destroy');
        $('#sliderRetPrice').slider({
            animate: true,
            range: 'min',
            max: maxFare,
            min: minFare,
            step: 1,
            value: currentMaxRetFare,
            slide: function(event, ui) {
                if (CURRENT_LANG == "tr") {
                    $('#sliderRetPriceInfo').html("<b><font color=\"red\">" + ui.value.toString() + " TL </font></b>' den ucuz uçuşları göster");
                }

                else {
                    $('#sliderRetPriceInfo').html("Show flights cheaper than : <b><font color=\"red\">" + ui.value.toString() + " TL </font></b>");
                }

            },
            stop: function(event, ui) {
                var newMaxFare = ui.value;
                if (newMaxFare != currentMaxRetFare) {
                    currentMaxRetFare = newMaxFare;
                    populateRetTable();
                }
            }
        });
        if (CURRENT_LANG == "tr") {
            $('#sliderRetPriceInfo').html("<b><font color=\"red\">" + actualCurrentMaxRetFare + " TL </font></b>' den ucuz uçuşları göster");
        }
        else {
            $('#sliderRetPriceInfo').html("Show flights cheaper than : <b><font color=\"red\">" + actualCurrentMaxRetFare + " TL </font></b>");
        }

        currentMaxRetFare = actualCurrentMaxRetFare;
    }
}
function loadDepHourSlider() {
    if (depFlights.length > 0) {
        $('#sliderDepHour').slider('destroy');
        $('#sliderDepHour').slider({
            animate: true,
            range: true,
            max: 24,
            min: 0,
            step: 1,
            values: [currentMinDepHour, currentMaxDepHour],
            slide: function(event, ui) {
                if (CURRENT_LANG == "tr") {
                    $('#sliderDepHourInfo').html("<b><font color=\"red\"> " + convertTime(ui.values[0].toString(), true) + "</font></b> - <b><font color=\"red\">" + convertTime(ui.values[1].toString(), true) + "</font></b> arası uçuşları göster");
                }

                else {
                    $('#sliderDepHourInfo').html("Show flights btw. hours : <b><font color=\"red\"> " + convertTime(ui.values[0].toString(), true) + "</font></b> - <b><font color=\"red\">" + convertTime(ui.values[1].toString(), true) + "</font></b>");
                }
            },
            stop: function(event, ui) {
                var newMinHour = ui.values[0];
                var newMaxHour = ui.values[1];

                if (newMinHour != currentMinDepHour || newMaxHour != currentMaxDepHour) {
                    currentMinDepHour = newMinHour;
                    currentMaxDepHour = newMaxHour;
                    populateDepTable();
                }
            }
        });
        if (CURRENT_LANG == "tr") {
            $('#sliderDepHourInfo').html("<b><font color=\"red\"> " + convertTime(currentMinDepHour, true) + "</font></b> - <b><font color=\"red\">" + convertTime(currentMaxDepHour, true) + "</font></b> arası uçuşları göster");
        }
        else {
            $('#sliderDepHourInfo').html("Show flights btw. hours : <b><font color=\"red\"> " + convertTime(currentMinDepHour, true) + "</font></b> - <b><font color=\"red\">" + convertTime(currentMaxDepHour, true) + "</font></b>");
        }
    }
}
function loadRetHourSlider() {
    if (retFlights.length > 0) {
        $('#sliderRetHour').slider('destroy');
        $('#sliderRetHour').slider({
            animate: true,
            range: true,
            max: 24,
            min: 0,
            step: 1,
            values: [currentMinRetHour, currentMaxRetHour],
            slide: function(event, ui) {
                if (CURRENT_LANG == "tr") {
                    $('#sliderRetHourInfo').html("<b><font color=\"red\"> " + convertTime(ui.values[0].toString(), true) + "</font></b> - <b><font color=\"red\">" + convertTime(ui.values[1].toString(), true) + "</font></b> arası uçuşları göster");
                }

                else {
                    $('#sliderRetHourInfo').html("Show flights btw. hours : <b><font color=\"red\"> " + convertTime(ui.values[0].toString(), true) + "</font></b> - <b><font color=\"red\">" + convertTime(ui.values[1].toString(), true) + "</font></b>");
                }
            },
            stop: function(event, ui) {
                var newMinHour = ui.values[0];
                var newMaxHour = ui.values[1];

                if (newMinHour != currentMinRetHour || newMaxHour != currentMaxRetHour) {
                    currentMinRetHour = newMinHour;
                    currentMaxRetHour = newMaxHour;
                    populateRetTable();
                }
            }
        });
        if (CURRENT_LANG == "tr") {
            $('#sliderRetHourInfo').html("<b><font color=\"red\"> " + convertTime(currentMinRetHour, true) + "</font></b> - <b><font color=\"red\">" + convertTime(currentMaxRetHour, true) + "</font></b> arası uçuşları göster");
        }
        else {
            $('#sliderRetHourInfo').html("Show flights btw. hours : <b><font color=\"red\"> " + convertTime(currentMinRetHour, true) + "</font></b> - <b><font color=\"red\">" + convertTime(currentMaxRetHour, true) + "</font></b>");
        }
    }
}
function loadSliders() {
    if (depFlights.length > 0) {
        loadDepPriceSlider();
        loadDepHourSlider();
        show('depSliders');
    }
    if (retFlights.length > 0) {
        loadRetPriceSlider();
        loadRetHourSlider();
        show('retSliders');
    }
}
//end of SLIDER LOADERS

//TABLE POPULATERS		//--OK--\\
function getFlightRowHtml(flight, isDeparture) {
    var currentQueryId = searchQueryId;
    if (isDeparture && depQueryId != null) {
        currentQueryId = depQueryId;
    } else if (!isDeparture && retQueryId != null) {
        currentQueryId = retQueryId;
    }

    var currentFlightFare = Math.round(flight.Fare * 100) / 100;
    if (isIncludeTax) {
        currentFlightFare = Math.round(flight.FareWithTax * 100) / 100;
    }

    var date = eval(flight.FlightDate.replace(/\/Date\((\d+)\)\//gi, "new Date($1)"));

    var rowHtml = '<tr><td><img src="images/' + flight.AirlineCode.toString().replace(' ', '') + '.gif" alt="' + flight.AirlineCode + '"/> </td><td>' + flight.FlightCode + '</td><td>' + date.format("dd/mm/yy") + '</td><td style="width: 30px">'
                  + flight.DepTime + '</td><td style="width: 30px">' + flight.ArrTime + '</td><td  style="width: 60px">' + currentFlightFare + '</td><td>';
    if (flight.AirlineInfo != null) {
        var aInfo = flight.AirlineInfo;
        if (CURRENT_LANG == "en") {
            aInfo = aInfo.replace(/Kalk../g, 'Departure from');
            aInfo = aInfo.replace(/Var../g, 'Arrival to');
            aInfo = aInfo.replace(/Havaliman./g, 'Airport');
        }
        rowHtml += '<img src="images/ico_info.png" alt="' + aInfo + '" title="' + aInfo + '" />';
    }
    if (flight.TransitInfo != null) {
        var tInfo = flight.TransitInfo;
        if (CURRENT_LANG == "en") {
            tInfo = tInfo.replace(/.zerinden transit u.u.tur/g, '');
            tInfo = 'Transit flight over ' + tInfo;
        }
        rowHtml += '<img src="images/transit.png" alt="' + tInfo + '" title="' + tInfo + '" />';
    }

    var airlineCode = flight.AirlineCode;

    if (airlineCode == 'AJT') {
        airlineCode = 'THY';
    }

    rowHtml += '</td><td><a target="_blank" href="QueryToLink.aspx?&FlightID=' + flight.FlightLogID + '&Airline=' + airlineCode + '&DepCode=' + flight.DepCode + '&ArrCode=' + flight.ArrCode + '&FlightDate=' + date.format("dd/mm/yy") + '"><img src="images/ico_arrow.gif" alt=' + currentResources[13].toString() + '> </a></td> </tr>';

    return rowHtml;
}
function getFlightRowsHtml(flights, tableId) {
    var overallRowsHtml = '';
    var convertedMinDepHour = convertTime(currentMinDepHour, false);
    var convertedMinRetHour = convertTime(currentMinRetHour, false);
    var convertedMaxDepHour = convertTime(currentMaxDepHour, false);
    var convertedMaxRetHour = convertTime(currentMaxRetHour, false);

    for (var i in flights) {
        if (isShowFullFlights || flights[i].SeatExists == 'E') {
            if (!isHideTransitFlights || flights[i].TransitInfo == null) {
                var currentFare = flights[i].Fare;
                if (isIncludeTax) {
                    currentFare = flights[i].FareWithTax;
                }
                if (tableId == 'departureFlightsTable') {
                    if (currentFare <= currentMaxDepFare &&
					   flights[i].DepTime >= convertedMinDepHour &&
					   flights[i].DepTime <= convertedMaxDepHour) {
                        overallRowsHtml += getFlightRowHtml(flights[i], true);
                        depVisibleFlightCount++;
                    }
                } else {
                    if (currentFare <= currentMaxRetFare &&
					   flights[i].DepTime >= convertedMinRetHour &&
					   flights[i].DepTime <= convertedMaxRetHour) {
                        overallRowsHtml += getFlightRowHtml(flights[i], false);
                        retVisibleFlightCount++;
                    }
                }
            }
        }
    }
    return overallRowsHtml;
}
function getFlightsTableHtml(tableId, flights) {
    var rowsHtml = getFlightRowsHtml(flights, tableId);
    var tableHtml = '<table id="' + tableId + '" class="tablesorter">' +
                  '<thead><tr><th>' + currentResources[6].toString() + '</th><th>' + currentResources[7].toString() + '</th><th>' + currentResources[8].toString() + '</th><th>' + currentResources[9].toString() + '</th><th>' + currentResources[10].toString() + '</th><th>' + currentResources[11].toString() + '</th><th></th><th></th></tr></thead>' +
                  '<tbody>' + rowsHtml + '</tbody></table>';
    return tableHtml;
}
function populateDepTable() {
    depVisibleFlightCount = 0;
    if (depFlights.length > 0) {
        var departureFlightsDiv = $('#departureFlightsDiv');
        departureFlightsDiv.html(getFlightsTableHtml('departureFlightsTable', depFlights));

        if (depVisibleFlightCount > 0) {
            var departuresFlightsTable = $('#departureFlightsTable');
            departuresFlightsTable.tablesorter({ widgets: ['saveSortLists'], sortList: depSortList, headers: { 6: { sorter: false }, 7: { sorter: false}} });
            departureFlightsDiv.show();
        }
    }
    updateDepFlightCount();
}
function populateRetTable() {
    retVisibleFlightCount = 0;
    if (retFlights.length > 0) {
        var returnFlightsDiv = $('#returnFlightsDiv');
        returnFlightsDiv.html(getFlightsTableHtml('returnFlightsTable', retFlights));

        if (retVisibleFlightCount > 0) {
            var returnFlightsTable = $('#returnFlightsTable');
            returnFlightsTable.tablesorter({ widgets: ['saveSortLists'], sortList: retSortList, headers: { 6: { sorter: false }, 7: { sorter: false}} });
            returnFlightsDiv.show();
        }
    }
    updateRetFlightCount();
}
function populateTables() {
    setDisplayOptions();
    populateDepTable();
    populateRetTable();

    if (!isSearchInProgress && !isDepInProgress && !isRetInProgress) {
        showFlightCounts();
    }
}
//end of TABLE POPULATERS

//MIN MAX FINDERS		//--OK--\\
function findDepMinMaxPrice() {
    if (depFlights.length > 0) {
        minDepFare = 9999;
        minDepFareWithTax = 9999;

        var oldMaxDepFare = maxDepFare;

        for (var i in depFlights) {
            var currentFlight = depFlights[i];
            if (currentFlight.Fare < minDepFare && currentFlight.Fare > 0 && currentFlight.SeatExists == 'E') {
                minDepFare = currentFlight.Fare;
            }
            if (currentFlight.FareWithTax < minDepFareWithTax && currentFlight.FareWithTax > 0 && currentFlight.SeatExists == 'E') {
                minDepFareWithTax = currentFlight.FareWithTax;
            }
            if (currentFlight.Fare > maxDepFare) {
                maxDepFare = currentFlight.Fare;
            }
            if (currentFlight.FareWithTax > maxDepFareWithTax) {
                maxDepFareWithTax = currentFlight.FareWithTax;
            }
        }

        if (currentMaxDepFare == oldMaxDepFare) {
            currentMaxDepFare = maxDepFare;
        }

        if (minDepFare == 9999 || minDepFareWithTax == 9999) {
            minDepFare = 0;
            minDepFareWithTax = 0;
        }
    }
}
function findRetMinMaxPrice() {
    if (retFlights.length > 0) {
        if (minRetFare == 0 || minRetFareWithTax == 0) {
            minRetFare = 9999;
            minRetFareWithTax = 9999;
        }

        var oldMaxRetFare = maxRetFare;

        for (var i in retFlights) {
            var currentFlight = retFlights[i];
            if (currentFlight.Fare < minRetFare && currentFlight.Fare > 0 && currentFlight.SeatExists == 'E') {
                minRetFare = currentFlight.Fare;
            }
            if (currentFlight.FareWithTax < minRetFareWithTax && currentFlight.FareWithTax > 0 && currentFlight.SeatExists == 'E') {
                minRetFareWithTax = currentFlight.FareWithTax;
            }
            if (currentFlight.Fare > maxRetFare) {
                maxRetFare = currentFlight.Fare;
            }
            if (currentFlight.FareWithTax > maxRetFareWithTax) {
                maxRetFareWithTax = currentFlight.FareWithTax;
            }
        }

        if (currentMaxRetFare == oldMaxRetFare) {
            currentMaxRetFare = maxRetFare;
        }

        if (minRetFare == 9999 || minRetFareWithTax == 9999) {
            minRetFare = 0;
            minRetFareWithTax = 0;
        }
    }
}
function findMinMaxPrice() {
    if (isOnlyDepRequested) {
        findDepMinMaxPrice();
    } else if (isOnlyRetRequested) {
        findRetMinMaxPrice();
    } else if (isSearchRequested) {
        findDepMinMaxPrice();
        findRetMinMaxPrice();
    }
    if (currentMaxDepFare == 0) {
        currentMaxDepFare = maxDepFare;
    }
    if (currentMaxRetFare == 0) {
        currentMaxRetFare = maxRetFare;
    }
}
//end of MIN MAX FINDERS

//RESULT PROCESSORS			//--OK--\\
function addToFlights(flights) {
    for (var index in flights) {
        if (index > 0) {
            var currentFlight = flights[index];
            if (currentFlight.DepCode == from || (from == "ALL" && (currentFlight.DepCode == "IST" || currentFlight.DepCode == "SAW"))) {
                depFlights.push(currentFlight);
            } else if (currentFlight.DepCode == to || (to == "ALL" && (currentFlight.DepCode == "IST" || currentFlight.DepCode == "SAW"))) {
                retFlights.push(currentFlight);
            }
        }
    }
    delete flights;
}
function processFlightResponseInfo(results) {
    var isValid = true;

    try {
        var flightResponseInfo = results[0];
        var airlineCode = flightResponseInfo.AirlineCode;
        successFlags[airlineCode] = flightResponseInfo.IsSuccessful;
        cacheFlags[airlineCode] = flightResponseInfo.IsFromCache;
        serverQueryDurations[airlineCode] = flightResponseInfo.ServerQueryDuration;
        queryEndTimes[airlineCode] = new Date();
        clientQueryDurations[airlineCode] = queryEndTimes[airlineCode] - queryStartTimes[airlineCode];
    } catch (err) {
        //        debugger;
        isValid = false;
    }

    return isValid;
}
function processFlightResults(results) {
    if (processFlightResponseInfo(results)) {
        addToFlights(results);
        findMinMaxPrice();
        loadSliders();
        populateTables();
    } else {
        //        debugger;
    }
}
//end of RESULT PROCESSORS
