﻿$(document).ready(function () {
    //Fixes a firefox menu issue when clicking the back button (clicked submenu remained open)
    $(window).unload(function () { $('.submenu').hide(); });

    //Set behaviour...
    $.ajaxSetup({ cache: false });
    adjustMenus();
    adjustSearchButtons();
    adjustWatermarks();
    initImagesLightBoxes();

    //date picker
    $('#txtDepartureDate').click(function () { $(this).blur(); });//Prevent departure date from focusing
    $('#txtDepartureDate').datepicker({ showButtonPanel: true,
        showOn: 'button',
        buttonImageOnly: true,
        buttonImage: '/Content/_img/nav/calendar.jpg',
        //beforeShow: function () { $('#ui-datepicker-div').maxZIndex(); },
        dateFormat: 'yy/mm/dd',
        minDate: '0D',
        maxDate: '+20D',
        showAnim: "scale"
    });

    if (DEFAULT_LANGUAGE == 'en')
        $.datepicker.setDefaults($.datepicker.regional['']);
    else
        $.getScript('/Scripts/jquery.ui.datepicker-' + DEFAULT_LANGUAGE + '.js')

    //make sure http links are targeting a new window (if no target specified)
    //Adjust internal pdf links to target new windows
    $('a').filter('[href*="/content/documents"]').attr("target", "_blank");
    $('a').filter('[href*="/contenu/documents"]').attr("target", "_blank");
    //Adjust all external links to target new windows
    $('a').filter('[href^="http"]').attr("target", "_blank");

    //CSS FIXES FOR BROWSERS
    navigator.browser = (function () {
        var N = navigator.appName, ua = navigator.userAgent, tem;
        var M = ua.match(/(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\.\d+)*)/i);
        if (M && (tem = ua.match(/version\/([\.\d]+)/i)) != null) M[2] = tem[1];
        M = M ? [M[1], M[2]] : [N, navigator.appVersion, '-?'];
        return M;
    })();

    if (navigator.browser[0] == "MSIE") {
        if (navigator.browser[1] < '8') {
            //$('div.details_footer').css("width", "100%");
            //$('#CircuitSearch').css("height", "192px");
            //$('#menucontainer').css("height", "21px");
            // $('table#content tr td#boxes div#schedule table tr#line_departure td img').css("padding-bottom", "5px;");            
            $('table#content tr td#boxes div#schedule table tr#line_departure td img').addClass("IE6AND7");
        }

        if (navigator.browser[1] < '7') {
            //$("#title").click(function () { window.top.location = "/about-us"; });
            //$("#title").html('');
            //$('#title').addClass("IE6");

        }
    }
    //    else if (navigator.browser[0] == "Firefox") {
    //        alert("!");
    //    }
    //    else
    //        $('iframe#frmContent').css('border', 'solid 1px blue');
    //END OF CSS FIXES FOR BROWSERS

    //JSON AUTOMATION FOR DYNAMIC DROPDOWN FILLING
    FillSearchCriterias($('#ddlDestinationsFrom'));
    //todo:uncomment if we want to update destinations onchange
    //$('#ddlDestinationsFrom').change(function () { FillSearchCriterias(this) });
    //$('#ddlDestinationsTo').change(function () { FillSearchCriterias(this) });    
    //END OF JSON
});

//Reset search criterias values based on selected ones
function FillSearchCriterias(sender) {
    if ($(sender).length == 0)
        return;

    var sender_id = "All";
    if (sender != null) {
        if (sender[0].id == "")
            sender_id = sender.id;
         else
            sender_id = sender[0].id
    }

    $("#ddlDestinationsFrom").attr('disabled', 'disabled');
    $("#ddlDestinationsTo").attr('disabled', 'disabled');

    var from_destination = $("#ddlDestinationsFrom option:selected").text();
    var to_destination = $("#ddlDestinationsTo option:selected").text();

    var url = "/" + DEFAULT_LANGUAGE;
    url += "/Home/FillSearchCriterias"
    url += "/" + sender_id;    
    url += "/" + DEFAULT_TO_ID;
    url += "/" + from_destination;
    url += "/" + to_destination;

    $.getJSON(url, null,
        function (json) {
            //Validate async errors
            if (typeof (json) != 'object') {
                alert(json);
                $("#ddlDestinationsFrom").removeAttr('disabled');
                $("#ddlDestinationsTo").removeAttr('disabled');
            }
            else {
                FillDropDown("ddlDestinationsFrom", json[0]);
                FillDropDown("ddlDestinationsTo", json[1]);
            }
        });
    }

    function FillDropDown(ctl_id, data) {
        $("#" + ctl_id).removeAttr('disabled');
        if (data != null) {
            var selectedValue = $('#' + ctl_id).val(); //hold last selected value
            $("#" + ctl_id).fillSelect(data);
            if (selectedValue != null)
                $('#' + ctl_id).val(selectedValue); //reset selected value (if still exists)
        }
    }

    function CreateContentFrame(section_title, summary_text) {
        if ($('#print-header H1#section-title').length == 0)
            $('#print-header').append("<H1 id='section-title'></H1><div id='summary-text'></div>");

        $('#print-header H1#section-title').html(section_title);
        $('#print-header div#summary-text').html(summary_text);        

        if ($('iframe#frmContent').length == 1)
            return;

        if ($('#content #left #center-content').length > 0) {
            //flush content
            $('#content #left #center-content').remove();

            //adjust css
            $('#content #left').addClass("tracking-schedule");
        }
        
        //insert iframe
        $('#content #left').append("<iframe id='frmContent' frameborder='0' src='' />");

        //RESULTS FRAME EVENTS
        $('iframe#frmContent').load(function () {
            ShowProcess(false);
        });
        //END OF RESULTS FRAME EVENTS
    }

    function TrackSearch() {
        var awb_no_prefix = $('#txtAWBPrefix').val();
        var awb_no = $('#txtAWB').val();

        //Validate awb prefix number
        if (isNaN(awb_no_prefix) || awb_no_prefix.length > 3 || awb_no_prefix.length < 3) {
            $('#txtAWBPrefix').select();
            window.alert(MSG_AWB_PREFIX_INVALID_LENGTH);
            $('#txtAWBPrefix').focus();
            return false;
        }
        //Validate awb number
        if (isNaN(awb_no) || awb_no.length > 9 || awb_no.length < 8) {
            $('#txtAWB').select();
            window.alert(MSG_AWB_INVALID_LENGTH);            
            $('#txtAWB').focus();
            return false;
        }

        ShowProcess(true);
        CreateContentFrame(TRACKING_SECTION_TITLE, "");

        var awb = $('#txtAWBPrefix').val() + '-' + awb_no;
        $('iframe#frmContent').attr("src", TRACKING_URL + "?Carrier=" + CARRIER + "&Shipment_text=" + awb + "&Header=no&Width=695&Height=395");
    }

    function ScheduleSearch() {
        if (!ValidateScheduleSearchFields())
            return false;

        ShowProcess(true);
        CreateContentFrame(SCHEDULE_SECTION_TITLE, SCHEDULEBOX_SECTION_SUMMARY);
        
        var origin = $("#ddlDestinationsFrom option:selected").val();
        var destination = $("#ddlDestinationsTo option:selected").val();
        var date_format = 'ddMyy';
        var selected_date = new Date($('#txtDepartureDate').val());
        var departure_date = $.datepicker.formatDate(date_format, selected_date);
        var arrival_date = "";
        /*
        var arrival_date = departure_date;

        if ($('#cbxPlusMinus7Days').val() == "on") {
        arrival_date = $.datepicker.formatDate(date_format, new Date(selected_date.getYear(), selected_date.getMonth(), selected_date.getDate() + 7));
            
        var min_date = new Date(selected_date.getYear(), selected_date.getMonth(), selected_date.getDate() - 7);
        var today = new Date();
        if (min_date < today) //Make sure departure date is not in the past
        min_date = today;

        departure_date = $.datepicker.formatDate(date_format, min_date);
            
        }
        */

        $('iframe#frmContent').attr("src", SCHEDULE_URL + "?carrier=" + CARRIER + "&origin=" + origin + "&destination=" + destination + "&departure_date=" + departure_date + "&arrival_date=" + arrival_date);
    }

    function ShowProcess(show) {
        $('#print-header').show();        

        if (show) {
            if ($('iframe#frmContent').length > 0)
                $('iframe#frmContent').hide();
            
            $('#print-header img.print').hide();
            $('#processing').show();
        }
        else {
            $('#processing').hide();
            if ($('iframe#frmContent').length > 0) {
                $('iframe#frmContent').show();
                $('#print-header img.print').show();
            }
            
        }

    }

//    function ShowPopup(url, width, height) {
//        window.showModalDialog(url, "toolbar:no;menubar:no;dialogWidth:" + width + ";dialogHeight:" + height);
//    }

//    function switchCulture() {
//        var days = 15;
//        var date = new Date();
//        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
//        var expires = "; expires=" + date.toGMTString();

//        var current_culture = Get_Cookie("airtransatcargo_culture");
//        var new_culture = (current_culture.toLowerCase() == "en-ca") ? "fr-ca" : "en-ca";
//        document.cookie = "airtransat_culture=" + new_culture + ";expires=" + date.toGMTString() + ";path=/"

//        var url = "";
//        if (window.top.location.href.indexOf("/" + current_culture.substring(0, 2)) == -1)
//            url = "http://" + window.top.location.host + "/" + new_culture.substring(0, 2);
//        else
//            url = window.top.location.href.replace("/" + current_culture.substring(0, 2), "/" + new_culture.substring(0, 2));

//        window.top.location = url;
//    }

//    // this function gets the cookie, if it exists
//    // don't use this, it's weak and does not handle some cases
//    // correctly, this is just to maintain legacy information
//    function Get_Cookie(name) {

//        var start = document.cookie.indexOf(name + "=");
//        var len = start + name.length + 1;
//        if ((!start) && (name != document.cookie.substring(0, name.length))) {
//            return null;
//        }
//        if (start == -1) return null;
//        var end = document.cookie.indexOf(";", len);
//        if (end == -1) end = document.cookie.length;
//        return unescape(document.cookie.substring(len, end));
//    }
    //			

    function printIframe(id) {            
            var styleStr;
            styleStr = 'toolbar=no,location=no,directories=no,status=no,menubar=no';
            styleStr += 'dependent=no,scrollbars=no,resizable=no,copyhistory=no';
            styleStr += 'width=' + $('#frmContent').width  + ',height=200'

            var url = HTTP_HOST + '/PrintProxy.aspx?u=' + escape($('#frmContent').attr('src'));
            window.open(url, 'printWindow', styleStr);
        }

    function showSection(sender) {        
        var elem = $(sender).parent().find('div.content')[0];
        if (elem.style.display != 'block')
            $(elem).show();
        else {
            $(elem).hide();
        }
        
        var oimage = $(sender);
        var image_url = oimage.attr("src");

        if(image_url.indexOf("expand.jpg") > -1)
            $(oimage).attr("src", image_url.replace("expand","contract"));
        else
            $(oimage).attr("src", image_url.replace("contract","expand"));

    }

    function showImg(url, name, features) {
        if (features == null)
            features = 'width=850,height=550,scrollbars=1,resizable=1';

        var pimg = window.open(url, 'zeIMG', features);

        try { pimg.focus(); } catch (e) { }
    }

    function initImagesLightBoxes() {
        if ($('img.linkedImage').length > 0 && $('img.linkedImage').parent('a').length == 0) {
            //Adjust image so that it can be handled as a fancybox
            $('img.linkedImage').each(function () {
                //replace img tag coming from gammes into an anchored image useable by fancybox plugin.
                var url = this.src;
                var onclick_url = this.attributes["local_url"].value;
                $(this).replaceWith('<a href=\"' + onclick_url + '\" alt=\"\"><img src=\"' + url + '\" class=\"linkedImage\"></a>');                
            });
        }

        //Set clickable images to be shown within a fancyBox 
        $('img.linkedImage').parent().fancybox({
            'transitionIn': 'elastic',
            'transitionOut': 'elastic',
            'speedIn': 600,
            'speedOut': 200,
            'overlayShow': false
        });
    }

    function adjustMenus() {
        $('#menucontainer').addClass(DEFAULT_LANGUAGE);

        //WHEN HOVERING TOP-MENU ELEMENTS
        $("#menucontainer table td.top_menu_element div.menu_item").hover(
         function (event) {/*mouseover*/
             var submenu = $(this).find('.submenu')

             if ($(submenu).find('a').length == 0)
                 return;

             var x = $(this).position().top + $(this).height();
             var y = ($(this).position().left + ($(this).width() / 2)) - ($(this).width() / 2);
             submenu.css('top', x).css('left', y).toggle();
         },
         function (event) { /*mouseout*/
             //Hide menu's associated submenu
             var submenu = $(this).children('span.submenu');
             if ($(submenu).children('a').length == 0)
                 return;

             submenu.toggle();
         });

        //WHEN HOVERING MENU ELEMENTS
         $("#menucontainer table tr.menu_element td").hover(
         function (event) {/*mouseover*/
             var submenu = $(this).find('.submenu')

             if ($(submenu).find('a').length == 0)
                 return;

             var x = $("#menucontainer").offset().top + $("#menucontainer").height() - 4;
             var y = $(this).position().left;

             //Make sure submenu does not go outside of the screen
             var offset = ($('tr.menu_element td:last-child').has(submenu).length == 1) ? 20 : 19;
             var max_y = (submenu.parent().width() + submenu.parent().offset().left);
             if (submenu.parent().offset().left + submenu.width() > max_y)
                 y = (submenu.parents('td').position().left + submenu.parents('td').width()) - submenu.width() - offset;
             
             submenu.css('top', x).css('left', y).toggle();
         },
         function (event) { /*mouseout*/
             //Hide menu's associated submenu
             var submenu = $(this).children('span.submenu');
             if ($(submenu).children('a').length == 0)
                 return;

             submenu.toggle();
         });
     }

     function adjustSearchButtons() {
         //INITIALIZE SEARCH BUTTONS EVENTS
         $("#btnTrackSearch").click(function () { TrackSearch(); });
         $("#btnTrackSearch").hover(
                function () {
                    $(this).toggleClass('hovered');
                }
                , function () {
                    $(this).toggleClass('hovered');
                }
             );

         //Initialize btnScheduleSearch onclick method
         $("#btnScheduleSearch").click(function () { ScheduleSearch(); });
         $("#btnScheduleSearch").hover(
                function () {
                    $(this).toggleClass('hovered');
                }
                , function () {
                    $(this).toggleClass('hovered');
                }
             );
     }

     function adjustWatermarks() {
         //WATERMARKS
         $(function () {
             $(".watermark").each(function () {
                 $tb = $(this);
                 if ($tb.val() != this.title) {
                     $tb.removeClass("watermark");
                 }
             });

             $(".watermark").focus(function () {
                 $tb = $(this);
                 if ($tb.val() == this.title) {
                     $tb.val("");
                     $tb.removeClass("watermark");
                 }
             });

             $(".watermark").blur(function () {
                 $tb = $(this);
                 if ($.trim($tb.val()) == "") {
                     $tb.val(this.title);
                     $tb.addClass("watermark");
                 }
             });
         });
     }

     function ValidateScheduleSearchFields() {
         var is_valid = false;

         if ($("#ddlDestinationsFrom option:selected").val() == DESTINATION_SELECT) {
             window.alert(MSG_DESTINATION_MISSING);
             $("#ddlDestinationsFrom").focus();
         }
         else if ($("#ddlDestinationsTo option:selected").val() == DESTINATION_SELECT) {
             window.alert(MSG_DESTINATION_MISSING);
             $("#ddlDestinationsTo").focus();
         }
         else if ($("#txtDepartureDate").val().length == 0) {
             window.alert(MSG_DEPARTURE_DATE_MISSING);
             $('#txtDepartureDate').datepicker("show");
         }
         else
             is_valid = true;

         return is_valid;
     }
