﻿// ######################################## //
// ############### Template ############### //

//show or hide the search watermark  
function textboxWatermark(action, textbox) {
    //get references to the search text box and the hidden field which has the "search flybmi.com" text from resource file   
    var textbox = document.getElementById(textbox);

    switch (action) {
        //adds the search flybmi.com watermark on the textbox if user clicks inside and no text has been entered 
        case 'add':
            //if the textbox is empty, add the search flybmi.com text
            if (textbox.value == '') { textbox.value = watermark; }
            break;
        //clear the search flybmi.com watermark on the textbox if user clicks inside 
        case 'remove':
            //if the textbox already has watermark text then clear it on click
            if (watermark == textbox.value) { textbox.value = ''; }
            break;
        //do nothing if not add or remove 
        default:
            break;
    }
}
// Change the CSS class of the given elements
function setCssClass() {
    var args = setCssClass.arguments;
    for (i = 0; i < (args.length - 1); i += 2)
        with (document) if (getElementById && ((obj = args[i]) != null)) {
            v = args[i + 1];
            if (obj.className != null) { obj.className = v; } 
        }
}

//find relative x position of any object
function findPosX(obj) {
    var curleft = 0;
    if (obj.offsetParent)
        while (1) {
            curleft += obj.offsetLeft;
            if (!obj.offsetParent)
                break;
            obj = obj.offsetParent;
        }
    else if (obj.x)
        curleft += obj.x;
    return curleft;
}
// Var to hold flyout open state
var languageFlyout = null;
var loginFlyout = null;
var accountFlyout = null;
// Shows/Hides the Flyout windows
function showHideFlyout(type, flyout, change, offset, login) {
    // ID of the relative position of a control where the animation starts from
    // this is needed since login/country language control are now in seperate controls
    var callingControlLinkID = null;

    switch (type) {
        // Show flyout
        case 'show':
            switch (flyout) {
                case 'chg':
                    languageFlyout = true;
                    // If login flyout is open, hide it
                    if (loginFlyout) { showHideFlyout('hide', 'log'); }
                    if (accountFlyout) { showHideFlyout('hide', 'acc_det'); }
                    callingControlLinkID = masterPageID;
                    break;
                case 'log':
                    loginFlyout = true;
                    // If language flyout is open, hide it
                    if (languageFlyout) { showHideFlyout('hide', 'chg'); }
                    //check that loginUniqueID exists (if there is no log in control included on the page then loginUniqueID is not found)
                    if (typeof loginUniqueID != "undefined") callingControlLinkID = loginUniqueID;
                    break;
                case 'acc_det':
                    accountFlyout = true;
                    if (languageFlyout) { showHideFlyout('hide', 'chg'); }
                    callingControlLinkID = 'acc_name';
                    // Change the arrow next to the name
                    toggleAccountArrow(true);
                    break;
            }
            // Get object "change" button link            
            var lnkChange = document.getElementById(callingControlLinkID + change);
            // If login flyout, modify logout link
            //check that loginUniqueID exists (if there is no log in control included on the page then loginUniqueID is not found)
            if (typeof loginUniqueID != "undefined" && login && lnkChange.innerHTML == document.getElementById(loginUniqueID + 'HiddenLogOutText').value) {

                document.getElementById(loginUniqueID + 'hiddenLogOutClicked').value = true;
                document.forms[0].submit();
                return false;
            }
            // Find relative x position of change link and take away offset (~popup length)
            var relativePosition = findPosX(lnkChange) - offset;
            // Set position of the popup to the relative position 
            document.getElementById(flyout).style.left = relativePosition + 'px';
            // Use blind down effect script to show the popup
            //Effect.BlindDown(flyout, {duration: 0.5});    
            $("#" + flyout).slideDown("slow");

            break;
        // Hide flyout 
        case 'hide':
            //use blind up effect to hide the popup
            //Effect.BlindUp(flyout, {duration: 0.5}); 
            $("#" + flyout).slideUp("slow");
            switch (flyout) {
                case 'chg':
                    // Update as language flyout closed
                    languageFlyout = null;
                    break;
                case 'log':
                    // Update as login flyout closed
                    loginFlyout = null;
                    break;
                case 'acc_det':
                    // Update as account flyout closed
                    accountFlyout = null;
                    // Change the arrow next to the logged in name
                    toggleAccountArrow(false);
                    break;
            }
            break;
        default:
            languageFlyout = null;
            loginFlyout = null;
            break;
    }
}

// Checnge the orientation of the arrow next to the logged in as name
function toggleAccountArrow(open) {
    if (open)
        document.getElementById('acc_det_img').src = '/images.net/v2/global/template/flybmi/v7/Arrows/small_arrow_down.gif';
    else
        document.getElementById('acc_det_img').src = '/images.net/v2/global/template/flybmi/v7/Arrows/small_arrow_right.gif';
}

var CountryInfo = null;
// Country option changed, get languages
function CountryChanged() {
    // Clear language list
    document.getElementById(changeLanguageID + 'drpLanguage').options.length = 0;
    document.getElementById(changeLanguageID + 'drpLanguage').options[0] = new Option('-', '-');
    if (CountryInfo == null) {
        Bmi.Src.Asmx.WebMethods.GetWebsiteCountries(CountryChangedComplete, ChangeError);
    }
    else {
        PopulateLanguage();
    }
}
// Country changed CallBack
function CountryChangedComplete(result, userContext, methodName) {
    CountryInfo = result;
    PopulateLanguage();
}
// Populate the language box
function PopulateLanguage() {
    var lang = document.getElementById(changeLanguageID + 'drpLanguage');
    var count = 0;
    if (CountryInfo != null) {
        for (i = 0; i < CountryInfo.length; i++) {
            if (document.getElementById(changeLanguageID + 'drpCountry').value == CountryInfo[i].CountryCode) {
                lang.options[count] = new Option(CountryInfo[i].Language, CountryInfo[i].CultureCode);
                count++;
            }
        }
    }
    UpdateLanguageButtons();
}
// Update the continue button text and country flag
function UpdateLanguageButtons() {
    var lang = document.getElementById(changeLanguageID + 'drpLanguage');
    var country = document.getElementById(changeLanguageID + 'drpCountry');
    var button = document.getElementById(changeLanguageID + 'btnContinue');
    var flag = document.getElementById(changeLanguageID + 'divSelectedFlag');
    var contentLanguage = 'en';

    if (flag) { flag.style.background = 'url(/images.net/v2/global/template/flybmi/v6/flags/' + country.value + '.gif) left no-repeat'; }

    if (CountryInfo != null) {
        for (i = 0; i < CountryInfo.length; i++) {
            if (CountryInfo[i].CultureCode == lang.value) { contentLanguage = CountryInfo[i].LanguageCode; }
        }
    }

    if (button) {
        switch (contentLanguage) {
            case 'fr':
                button.innerHTML = "Continuer";
                break;
            case 'nl':
                button.innerHTML = "Ga door";
                break;
            case 'es':
                button.innerHTML = "Continuar";
                break;
            default:
                button.innerHTML = "Continue";
                break;
        }
    }
}

function ChangeError(error, userContext, methodName) {
    //uncomment to view real error
    //alert(error.message);
}

function LanguageChanged() {
    UpdateLanguageButtons();
}

// ######################################## //
// ############### Homepage ############### //

// Animate homepage spotlights  
//$(function(){ 
//    
//    // Slide down effect on mouse enter    
//    $(".spotlightDrop").bind("mouseenter", function() {      
//        $(this).animate({
//            top: "80px"
//        }, 1000);
//    });     
//    
//    // Slide up effect on mouse leave
//    $(".spotlight").bind("mouseleave", function(){        
//        $(this).children().animate({
//            top: "0px"
//        }, 1000)      
//    });

//});

// Redirects to a given url;
function delayRedirect(url, delayTime) {
    // Check if a url has been provided
    if (url != '') {
        var redirect = "window.location = '" + url + "'";
        setTimeout(redirect, (delayTime * 1000));
    }
}

// Logic used for the country language selector
function CountryChange(dropdown) {
    var oSelectedCountryLanguages = eval(dropdown[dropdown.selectedIndex].value)[0].split(',');
    var drpLanguage = document.getElementById(drpLanguageUniqueID + 'drpLanguage');
    // Remove all options from list
    drpLanguage.length = 0;
    // Repopulate with valid options
    for (var i = 0; i < oSelectedCountryLanguages.length; i++) {
        drpLanguage.options[i] = new Option(oSelectedCountryLanguages[i].split('#')[1], oSelectedCountryLanguages[i].split('#')[0]);
        try {
            // Select the right languge
            if (drpLanguage.options[i].value == window.location.href.split('/')[4].split('-')[0]) { drpLanguage.options[i].selected = true; }
        }
        catch (err) {// we have been unabble to 
        }
    }
    // Make space for the Country flag and change it
    document.getElementById('chg_cty').style.paddingLeft = "30px";
    document.getElementById('chg_cty').style.background = "url(/images.net/v2/global/template/flybmi/v6/flags/" + dropdown[dropdown.selectedIndex].value + ".gif) no-repeat 0 23px";
    return false;
}

// Accepts the language selection change
function SelectLanguage() {
    var drpCountries = document.getElementById(drpLanguageUniqueID + 'drpCountry');
    var drpLanguage = document.getElementById(drpLanguageUniqueID + 'drpLanguage');
    // Redirect to required site
    window.location.href = '/bmi/' + drpLanguage[drpLanguage.selectedIndex].value + '-' + drpCountries[drpCountries.selectedIndex].value + '/index.aspx';
}

// webapi3 linkbutton - adding click funcationality
function addClickFunction(id) {
    var b = document.getElementById(id);
    if (b && typeof (b.click) == 'undefined') b.click =
    function () {
        var result = true;
        if (b.onclick) result = b.onclick();
        if (typeof (result) == 'undefined' || result) {
            eval(b.getAttribute('href'));
        }

    };
}




// Sets links that need to open in a new window to do so
function SetExternalTargets() {
    // Find a tags with rel=nofollow
    $("a[rel*=nofollow]").click(function () {
        window.open(this.href); return false;
    });
    // Find a tags with rel=external
    $("a[rel*=external]").click(function () {
        window.open(this.href); return false;
    });
}

function OCKIValidateDepartureAirport(sender, args) {
    args.IsValid = (args.Value != "0");
}

// Runs with window.onload
$(document).ready(function () {
    SetExternalTargets();

    /*Check-in Online departure airport dropdown list*/
    // Bind change event to identification methods
    $("select.ddlCheckinUsing", this.control).bind("change");

    // Create blank options
    var blankOption = "<option value=\"0\">-------------------------------</option>";
    // Get LHR text from dropdown
    var lhrOption = $("select.DeptAirport option[value='LHR']", this.control).text();
    // Add to dropdown after the first option
    $("select.DeptAirport option[value='0'], select.EtktDeptAirport option[value='0'], select.FfpDeptAirport option[value='0'] ").after($(blankOption + "<option value=\"LHR\">" + lhrOption + "</option>" + blankOption));
    /* end of Check-in Online departure lists*/


    jQuery.each(jQuery.browser, function (i) {
        //Underline text on hover for input of class button 
        $("input.button").hover(
           function () {
               $(this).css("text-decoration", "underline")
               //Fix for Mozilla
               if ($.browser.mozilla) $(this).css("display", "table-cell");
           },
           function () {
               $(this).css("text-decoration", "none");
           }
        );
    });

    $.ajaxSetup({ cache: true });
    // HP Scrollable banners
    $.getScript("/bmi/src/js/jQuery/jquery.tools.min.js", function () {
        // custom easing called "custom" 
        $.easing.custom = function (x, t, b, c, d) {
            var s = 1.70158;
            if ((t /= d / 2) < 1) return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b;
            return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;
        }

        $("div.scrollable").scrollable({
            onSeek: function () {
                if ($("a.NextButton").hasClass("notactive")) {
                    $("a.NextButton img").attr("src", "/images.net/v2/bmi/v7/Homepage/Navigation/next0.jpg");
                }
                else {
                    $("a.NextButton img").attr("src", "/images.net/v2/bmi/v7/Homepage/Navigation/next1.jpg");
                }

                if ($("a.PreviousButton").hasClass("notactive")) {
                    $("a.PreviousButton img").attr("src", "/images.net/v2/bmi/v7/Homepage/Navigation/previous0.jpg");
                }
                else {
                    $("a.PreviousButton img").attr("src", "/images.net/v2/bmi/v7/Homepage/Navigation/previous1.jpg");
                }
            },
            easing: 'custom',
            speed: 1500,
            prev: '#prvButton_',
            next: '#nxtButton_',
            prevPage: '#Previous',
            nextPage: '#Next',
            disabledClass: 'notactive',
            activeClass: 'active',
            size: 3,
            clickable: false,
            keyboard: false
        });

        // Add custom link Ominture tracking to the next and previous buttons
        $("a.PreviousButton").click(function () {
            var omPreviousButton = s_gi(s_account);
            omPreviousButton.tl($(this), 'o', 'Homepage promo previous button');
        });

        $("a.NextButton").click(function () {
            var omNextButton = s_gi(s_account);
            omNextButton.tl($(this), 'o', 'Homepage promo next button');
        });

        $(".bmifriday").closest(".AccordionHeader").click(function () {
            if ($("#bmifriday").closest(".AccordionContent").css("overflow") == "hidden") {
                //Track 
                var omPreviousButton = s_gi(s_account);
                omPreviousButton.tl($(this), 'o', 'BmiFriday Accordian');
            }

        })

    });

    // Make last menu display right to left
    //$("#ht_top_nav_con ul li:last").closest("ul").css("right", "0%");


    // Set links to be ids for the tabs
    $("a.tabLink", "#accordionTabs").each(function (i) {
        var classname = $(this)[0].className.split(" ");
        $(this).attr("href", "#" + classname[1]);
    });

    // Tabify
    $("#accordionTabs").tabs({
        select: function (event, ui) {
            $(ui.panel).css("display", "block");
            // If its not the flights tab, then redirect
            if (ui.index != 0) {
                // Find the redirect link
                var url = $(ui.panel).find(".redirectLink").val();
                // If we find it, redirect
                if (url != null) delayRedirect(url, 3);
            }
        }
    });

 

    // Homepage accordion
    $("#accordion").accordion({
        autoHeight: false,
        animated: 'easeInOutQuart',
        changestart:
        function (event, ui) {
            if ($.browser.mozilla) {
                $(".FromCountryList option").hide() // Firefox bugfix
            }
        },
        change:
        function (event, ui) {
            if ($.browser.mozilla) {
                $(".FromCountryList option").show(); // Firefox bugfix
            }
        }
    });

    if (document.location.href.toString().split('ockimsg=')[1] != null) {
        //a redirect from ocki has taken place display the message 
        //open the accordian in the right place
        $('div.OckiErrorMessage').show();
        $('#accordion').accordion('activate', 1)
    }
});


function ToggleBackground() {
    //make request and hide the panel
    ExecuteJsonRequest(null, "json=true&command=BackgroungToggle", this, BackgroundImageCallback, null);
    return false;
}

function BackgroundImageCallback (res) {

    var flckrContainer = $("#flk_inf");

    var defaultBg = '#BAD9EE'
    var bgImg = $("#hdBgImg");
    var bgCol = $("#hdBgCol");
    var mainBg = $('#background');
    var linkbtn = $('.flckrbtn:first');


    if (flckrContainer.hasClass('flckrinfo')) {
        //currently visible will now hide it
        flckrContainer.removeClass('flckrinfo');
        flckrContainer.addClass('flckrinfohidden');
        mainBg.css("background-image", "");
        mainBg.css("background-color", defaultBg);
        linkbtn.text('on');        
    } else {
        //currently hidden will now show
        flckrContainer.removeClass('flckrinfohidden');
        flckrContainer.addClass('flckrinfo');
        var bgString = ('#' + bgCol.val() + ' ' + bgImg.val());
        mainBg.css("background", bgString);
        linkbtn.text('off');
    }
}

