﻿// ============================================================================================================
// Generic Variables
// ============================================================================================================
var mblnMediaGalleryMoved = false;
var mintDiveImageIndex = 0;
var mintDestImageIndex = 0;
var mintVideoIndex = 0;
var blnFadeInMediaPanel;
var blnFadeOutMediaPanel;
// ============================================================================================================
// Generic Functions
// ============================================================================================================
function SetUniqueRadioButton(nameregex, current) {

    var re = new RegExp(nameregex);

    for (i = 0; i < document.forms[0].elements.length; i++) {

        elm = document.forms[0].elements[i]
        if (elm.type == 'radio') {
            if (re.test(elm.name)) {
                elm.checked = false;
            }
        }
    }
    current.checked = true;

}
function ChangeMainImage(strMainImageControlID, strNewImageSrc, strNewImageAlt) {
    document.getElementById(strMainImageControlID).src = strNewImageSrc;
    document.getElementById(strMainImageControlID).alt = strNewImageAlt;
}
function ChangeMainImageDiv(strMainImageControlID, strNewImageSrc, strNewImageAlt) {
    document.getElementById(strMainImageControlID).src = strNewImageSrc;
    document.getElementById(strMainImageControlID).alt = strNewImageAlt;
}
function doClick(id) {
    document.getElementById(id).click();
    return false;
}
// ============================================================================================================
// Flow Player
// ============================================================================================================
function fnc_LoadFlowPlayer(strURL, strPrefix, strPlayerId, blnAutoPlay) {
    //var srcFlash = strPrefix + "/swf/flowplayer-3.1.0.swf";
    var srcFlash = "/Flash/flowplayer-3.1.0.swf";
    flowplayer(strPlayerId, { src: srcFlash, wmode: "transparent" }, {
        plugins: {
            pseudo: { url: '/Flash/flowplayer.pseudostreaming-3.1.2.swf' }
        },
        clip: {
            // no autostart
            autoPlay: blnAutoPlay,
            // make this clip use pseudostreaming plugin with "provider" property
            provider: 'pseudo',
            // scaling
            scaling: 'fit',
            // all videos under this baseUrl support pseudostreaming on the server side         
            url: strURL
        }
    });
}
function fnc_StopFlowPlayer() {
    flowplayer('ctl00_cphMainContent_player').stop();
}

function fnc_SelectPreference(strElementId) {
    // TODO ::
    // Populate the hidden field with the PRFID
    // Click the add preference button
    // Rebind the selected preferences list
    // Click the main content update panel button

    $get(strElementId).click();
}

function fnc_RemovePreference(strElementId) {
    // TODO ::
    // Populate the hidden field with the PRFID
    // Click the remove preference button
    // Rebind the selected preferences list
    // Click the main content update panel button

    $get(strElementId).click();
}


// AJAX Background Loading Methods

function OnSucceeded() {
    //alert('Loaded Successfully');
    //$get('ctl00_btnUpdateMain').click();
}

function OnFailed(error) {
    // Alert user to the error.
    alert(error.get_message());
}

/* Helper function for debugging
------------------- */
function js_debug_ouput(strMessage) {
    // uncomment to debug
    //$('#divJS_output').html($('#divJS_output').html() + strMessage + '<br />\n');
    //console.log(strMessage)
}

// ============================================================================================================
// Update panels and page life cycle
// ============================================================================================================

// Page loaded scripts
$(document).ready(function () {

    // Make the facebook and twitter buttons
    Facebook_and_Twitter();

    // Add the google analytics code
    Google_Analytics();

    // Add the dynamic telephone numbers code
    Dynamic_Telephone_Numbers();

    // Add the crazy egg code
    Crazy_Egg();

    // documentation for ajax lifecycle = http://msdn.microsoft.com/en-us/library/bb386417(v=vs.90).aspx
    // Ajax postback lifecycle event handlers
    Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(PageRequestManager_onPageLoading)
    Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(PageRequestManager_onPageLoaded)
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(PageRequestManager_onEndRequest)

    js_debug_ouput('document.ready');

    // Update the HST
    HST_Loader();
    if (gblnUD_iPAD_Fix) {
        // Stop load more button from being clicked twice
        fncAdd_DownloadMore_ButtonClick_Handlers()
    }
    else {
        // add scrolling code for none ipad browsers
        fncAdd_Tab_onScroll_DownloadMore_Handlers();
        fncAddEventHandlersToRecordScrollPosition();
    }

});

// Store the window scroll postion to allow scrolling around during partial post backs
var gintScrollTop = 0;

// Scripts to run when ajax postback returned but not updated controls yet
function PageRequestManager_onPageLoading(sender, args) {
    js_debug_ouput('PageRequestManager_onPageLoading');
    // Store the top scroll offset
    gintScrollTop = $(window).scrollTop();
    // Store the telephone number
    saveDynamic_Telephone_Number();
}
// Scripts to run when ajax postback has returned and updated controls
function PageRequestManager_onPageLoaded(sender, args) {
    js_debug_ouput('PageRequestManager_onPageLoaded');
    // Restore the scroll to the position just before returned ajax caused layout to change
    $(window).scrollTop(gintScrollTop);
}
// Scripts to run when ajax postback has finished
function PageRequestManager_onEndRequest(sender, args) {
    js_debug_ouput('PageRequestManager_onEndRequest');

    // Check if the request failed (maybe the session is dead or internet connection is lost)
    if (args.get_error() != undefined) {
        // Display the error to the user
        var errorMessage = args.get_error().message;
        $('#ScriptManager_Error').text('An error has occurred please refresh your browser :: ' + errorMessage);
        // Mark the error as dealt with
        args.set_errorHandled(true);
        // Show the error text after a short delay to allow for links being clicked
        var t = setTimeout("fncShowClientErrorPanelAndNavigateRefresh()", 5000);
    }

    // Update the HST
    HST_Loader();
    if (gblnUD_iPAD_Fix) {
        // Stop load more button from being clicked twice
        fncAdd_DownloadMore_ButtonClick_Handlers()
    }
    else {
        // add scrolling code for none ipad browsers
        fncAdd_Tab_onScroll_DownloadMore_Handlers();
        fncAddEventHandlersToRecordScrollPosition();
    }
    // Make the facebook and twitter buttons
    // Facebook_and_Twitter();

    // Restore the telephone number
    restoreDynamic_Telephone_Number();
}

// If the browser is not connected when tying a post back make the whole page refresh
function fncShowClientErrorPanelAndNavigateRefresh() {
    // Make the error text visible
    $('#ScriptManager_Error').delay(500).show();
    // Navigate back this page
    window.location.href = window.location.href;
}

// ============================================================================================================
// FACEBOOK AND TWITTER SCRIPTS
// ============================================================================================================
function Facebook_and_Twitter() {
    // Facebook button
    (function (d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) return;
        js = d.createElement(s); js.id = id;
        js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1";
        fjs.parentNode.insertBefore(js, fjs);
    } (document, 'script', 'facebook-jssdk'));

    // Twitter button
    (!function (d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (!d.getElementById(id)) {
            js = d.createElement(s);
            js.id = id;
            js.src = "//platform.twitter.com/widgets.js";
            fjs.parentNode.insertBefore(js, fjs);
        }
    } (document, "script", "twitter-wjs"));
    // G+ Button
    (function () {
        var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
        po.src = 'https://apis.google.com/js/plusone.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
    })();
}

// ============================================================================================================
// Google analytics
// ============================================================================================================
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-2193576-2']);
_gaq.push(['_trackPageview']);

function Google_Analytics() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
}

function Crazy_Egg() {
    setTimeout(function () {
        var a = document.createElement("script");
        var b = document.getElementsByTagName('script')[0];
        a.src = document.location.protocol + "//dnn506yrbagrg.cloudfront.net/pages/scripts/0011/4565.js?" + Math.floor(new Date().getTime() / 3600000);
        a.async = true; a.type = "text/javascript";
        b.parentNode.insertBefore(a, b)
    }, 1);
}

// ============================================================================================================
// Dynamic telephone numbers
// ============================================================================================================
var adiInit = "1030";
var strDynamic_Telephone_Number = "";

function Dynamic_Telephone_Numbers() {
    var adiSrc = document.createElement("script"); adiSrc.type = "text/javascript";
    adiSrc.async = true;
    adiSrc.src = ("https:" == document.location.protocol ? "https://" : "http://") + "static.adinsight.com/static/scripts/adiTrack.min.js";
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(adiSrc, s);
}

/* Where telephone numbers are used in update panels need to store the value between postbacks
----------------- */
function saveDynamic_Telephone_Number() {
    if ($('span[class="adinsightNumber6852"]').length > 0) {
        strDynamic_Telephone_Number = $('span[class="adinsightNumber6852"]').first().text();
    }
}
function restoreDynamic_Telephone_Number() {
    if ($('span[class="adinsightNumber6852"]').length > 0) {
        $('span[class="adinsightNumber6852"]').each(function (index) {
            $(this).text(strDynamic_Telephone_Number);
        });
    }
}
// ============================================================================================================
// HST CONTROL PAGING SCRIPTS
// ============================================================================================================

// Sets a tab title to the value specified in its hidden field that sits within its update panel
function UpdateTabHeaderText(strTabName) {
    var hidTitle_TAB = $('input[type="hidden"][id$="hidTitle_' + strTabName + '"]');
    var spanTAB = $('span[id$="_tab' + strTabName + '"]');
    if (hidTitle_TAB.length > 0 && spanTAB.length > 0) {
        spanTAB.html(hidTitle_TAB.val());
    }
}

// Set the title of the favourites tab, this is a little more complicated 
// because it requires some HTML to get the start icon into it.
function UpdateTabHeaderText_Favourites() {
    //console.log("UpdateTabHeaderText_Favourites");
    var hidTitle_TAB = $('input[type="hidden"][id$="hidTitle_PanelFav"]');
    var spanTAB = $('span[id$="_tabPanelFav"]');
    if (hidTitle_TAB.length > 0 && spanTAB.length > 0) {
        if (hidTitle_TAB.val() == "0")
            spanTAB.html("<table cellpadding='0' cellspacing='0' ><tr><td style='vertical-align:middle' ><div class='tabfav'>&nbsp;</div></td><td style='vertical-align:middle' >Favourites</td></tr></table>");
        else
            spanTAB.html("<table cellpadding='0' cellspacing='0' ><tr><td style='vertical-align:middle' ><div class='tabfav'>&nbsp;</div></td><td style='vertical-align:middle' >Favourites (" + hidTitle_TAB.val() + ")</td></tr></table>");
    }
}


// This method is to bind events used by HST for paging and 
// to do layout after partial post backs (i.e. when an update panel refreshes)
// Also used on tier3 tab controls
function HST_Loader() {

    //console.log("HST_Loader(sender) has been called");
    //console.log("favourites = " + $('input[type="hidden"][id$="hidTitle_PanelFav"]').val());

    // Flag that we are not updating anymore
    if ($('input[type="hidden"][id$="hidHstPostBackInProgress"]').length > 0) {
        $('input[type="hidden"][id$="hidHstPostBackInProgress"]').val("FALSE");
    }


    /* Update the tab titles
    ------------------------------------------------- */
    if ($('input[type="hidden"][id$="hidTabTitlesNeedUpdating"]').length > 0) {
        if ($('input[type="hidden"][id$="hidTabTitlesNeedUpdating"]').val() == "TRUE") {
            $('input[type="hidden"][id$="hidTabTitlesNeedUpdating"]').val("FALSE");
            UpdateTabHeaderText('Destinations');
            UpdateTabHeaderText('Hotels');
            UpdateTabHeaderText('Liveaboards');
            UpdateTabHeaderText('Holidays');
            UpdateTabHeaderText_Favourites();
        }
    }


    /* HST load content into the hidden tabs
    ------------------------------------------------- */

    // Check if we need to background load the other tabs
    if ($('input[type="hidden"][id$="hidHstOtherTabsNeedLoading"]').length > 0) {
        if ($('input[type="hidden"][id$="hidHstOtherTabsNeedLoading"]').val() == "TRUE") {
            // Check that there is not already a postback in progress
            if ($('input[type="hidden"][id$="hidHstPostBackInProgress"]').length > 0) {
                if ($('input[type="hidden"][id$="hidHstPostBackInProgress"]').val() != "TRUE") {
                    // Flag that loading is busy
                    $('input[type="hidden"][id$="hidHstPostBackInProgress"]').val("TRUE");
                    $('input[type="hidden"][id$="hidHstOtherTabsNeedLoading"]').val("FALSE");

                    //console.log("load other tabs results in bg");

                    // Flag that we will need to update the titles once the tabs have been refreshed
                    if ($('input[type="hidden"][id$="hidTabTitlesNeedUpdating"]').length > 0) {
                        $('input[type="hidden"][id$="hidTabTitlesNeedUpdating"]').val("TRUE");
                    }

                    // Load more results
                    $('input[type="submit"][id$="btnLoadOtherTabs"]').click();
                }
            }
        }
    }

}

// This method adds event handlers to the hidden load more details buttons 
// so that they are disabled once they have been clicked
function fncAdd_DownloadMore_ButtonClick_Handlers() {
    js_debug_ouput('fncAdd_DownloadMore_ButtonClick_Handlers');


    // Hidden field used to check if we are already doing a postback
    if ($('input[type="hidden"][id$="hidHstPostBackInProgress"]').length == 0)
        return;


    /* HST Tabs download buttons
    ------------------------------------------------- */

    // Destinations - load more button click
    if ($('input[type="submit"][id$="btnLoadMoreResultsDestinations"]').length > 0) {
        $('input[type="submit"][id$="btnLoadMoreResultsDestinations"]').click(fncLoadMoreButton_onCLick);
    }


    // Hotels - Scroll detection function
    if ($('input[type="submit"][id$="btnLoadMoreResultsHotels"]').length > 0) {
        $('input[type="submit"][id$="btnLoadMoreResultsHotels"]').click(fncLoadMoreButton_onCLick);
    }

    // Liveaboards - Scroll detection function
    if ($('input[type="submit"][id$="btnLoadMoreResultsLiveaboards"]').length > 0) {
        $('input[type="submit"][id$="btnLoadMoreResultsLiveaboards"]').click(fncLoadMoreButton_onCLick);
    }

    // Holidays List - Scroll detection function
    if ($('input[type="submit"][id$="btnLoadMoreResultsHolidays"]').length > 0) {
        $('input[type="submit"][id$="btnLoadMoreResultsHolidays"]').click(fncLoadMoreButton_onCLick);
    }


    /* Tier 3 Hotels Scroll to download next page
    ------------------------------------------------- */


    // Tier3 Hotels Holidays List - Scroll detection function
    if ($('input[type="submit"][id$="btnLoadMoreResults_Tier3_Hotel_Holidays"]').length > 0) {
        $('input[type="submit"][id$="btnLoadMoreResults_Tier3_Hotel_Holidays"]').click(fncLoadMoreButton_onCLick);
    }

}
// This method adds event handlers to the scrolling DIVs so that they click 
// the hidden load more details buttons when the user scrolls near to the
// bottom of the list
function fncAdd_Tab_onScroll_DownloadMore_Handlers() {

    // Hidden field used to check if we are already doing a postback
    if ($('input[type="hidden"][id$="hidHstPostBackInProgress"]').length == 0)
        return;

    /* HST Tabs Scroll to download next page
    ------------------------------------------------- */

    // Destinations - Scroll detection function
    if ($('input[type="submit"][id$="btnLoadMoreResultsDestinations"]').length > 0
            && $('#divDestinations').length > 0) {
        $('#divDestinations').bind('scroll'
            , function () {
                // Record the scroll position for when tabs change
                int_divDestinations_scrollTop = $(this).scrollTop();
                // Trigger load more results if scroll down far enough
                fncOnScrollLoadNext(
                    $('input[type="submit"][id$="btnLoadMoreResultsDestinations"]')
                    , $(this)
                );
            });
    }

    // Hotels - Scroll detection function
    if ($('input[type="submit"][id$="btnLoadMoreResultsHotels"]').length > 0
            && $('#divHotels').length > 0) {
        $('#divHotels').bind('scroll'
            , function () {
                // Record the scroll position for when tabs change
                int_divHotels_scrollTop = $(this).scrollTop();
                // Trigger load more results if scroll down far enough
                fncOnScrollLoadNext(
                    $('input[type="submit"][id$="btnLoadMoreResultsHotels"]')
                    , $(this)
                );
            });
    }

    // Liveaboards - Scroll detection function
    if ($('input[type="submit"][id$="btnLoadMoreResultsLiveaboards"]').length > 0
            && $('#divLiveaboards').length > 0) {
        $('#divLiveaboards').bind('scroll'
            , function () {
                // Record the scroll position for when tabs change
                int_divLiveaboards_scrollTop = $(this).scrollTop();
                // Trigger load more results if scroll down far enough
                fncOnScrollLoadNext(
                    $('input[type="submit"][id$="btnLoadMoreResultsLiveaboards"]')
                    , $(this)
                );
            });
    }

    // Holidays List - Scroll detection function
    if ($('input[type="submit"][id$="btnLoadMoreResultsHolidays"]').length > 0
            && $('#divHolidaysList').length > 0) {
        $('#divHolidaysList').bind('scroll'
            , function () {
                // Record the scroll position for when tabs change
                int_divHolidaysList_scrollTop = $(this).scrollTop();
                // Trigger load more results if scroll down far enough
                fncOnScrollLoadNext(
                    $('input[type="submit"][id$="btnLoadMoreResultsHolidays"]')
                    , $(this)
                );
            });
    }


    /* Tier 3 Hotels Scroll to download next page
    ------------------------------------------------- */


    // Tier3 Hotels Holidays List - Scroll detection function
    if ($('input[type="submit"][id$="btnLoadMoreResults_Tier3_Hotel_Holidays"]').length > 0
            && $('#divProductHolidays').length > 0) {
        $('#divProductHolidays').bind('scroll'
            , function () {
                // Record the scroll position for when tabs change
                int_divProductHolidays_scrollTop = $(this).scrollTop();
                // Trigger load more results if scroll down far enough
                fncOnScrollLoadNext(
                    $('input[type="submit"][id$="btnLoadMoreResults_Tier3_Hotel_Holidays"]')
                    , $(this)
                );
            });
    }

}

/* Variables to hold all the current scroll position of all tabs
------------------------------------------------- */
var int_divFactFile_scrollTop = 0;
var int_divRouteOptions_scrollTop = 0;
var int_divAvailability_scrollTop = 0;
var int_divExcursions_scrollTop = 0;
var int_divFavourites_scrollTop = 0;
var int_divRoomBoard_scrollTop = 0;
var int_divProductHolidays_scrollTop = 0;
var int_divDiveCentres_scrollTop = 0;
var int_divDestinations_scrollTop = 0;
var int_divHotels_scrollTop = 0;
var int_divLiveaboards_scrollTop = 0;
var int_divHolidaysList_scrollTop = 0;

/* Other Tabs record scroll position to restore when changing between tabs
------------------------------------------------- */
function fncAddEventHandlersToRecordScrollPosition() {
    if ($('#divFactFile').length > 0) {
        $('#divFactFile').bind('scroll'
            , function () {
                int_divFactFile_scrollTop = $(this).scrollTop();
            });
    }
    if ($('#divRouteOptions').length > 0) {
        $('#divRouteOptions').bind('scroll'
            , function () {
                int_divRouteOptions_scrollTop = $(this).scrollTop();
            });
    }
    if ($('#divAvailability').length > 0) {
        $('#divAvailability').bind('scroll'
            , function () {
                int_divAvailability_scrollTop = $(this).scrollTop();
            });
    }
    if ($('#divExcursions').length > 0) {
        $('#divExcursions').bind('scroll'
            , function () {
                int_divExcursions_scrollTop = $(this).scrollTop();
            });
    }
    if ($('#divFavourites').length > 0) {
        $('#divFavourites').bind('scroll'
            , function () {
                int_divFavourites_scrollTop = $(this).scrollTop();
            });
    }
    if ($('#divRoomBoard').length > 0) {
        $('#divRoomBoard').bind('scroll'
            , function () {
                int_divRoomBoard_scrollTop = $(this).scrollTop();
            });
    }
    if ($('#divDiveCentres').length > 0) {
        $('#divDiveCentres').bind('scroll'
            , function () {
                int_divDiveCentres_scrollTop = $(this).scrollTop();
            });
    }
}
/* Restore the scroll position of 
------------------------------------------------- */
function fncRestoreTabScrollPositions_OnTabChange() {
    if (!gblnUD_iPAD_Fix) {
        if ($('#divFactFile').length > 0)
            $('#divFactFile').scrollTop(int_divFactFile_scrollTop);
        if ($('#divRouteOptions').length > 0)
            $('#divRouteOptions').scrollTop(int_divRouteOptions_scrollTop);
        if ($('#divAvailability').length > 0)
            $('#divAvailability').scrollTop(int_divAvailability_scrollTop);
        if ($('#divExcursions').length > 0)
            $('#divExcursions').scrollTop(int_divExcursions_scrollTop);
        if ($('#divFavourites').length > 0)
            $('#divFavourites').scrollTop(int_divFavourites_scrollTop);
        if ($('#divRoomBoard').length > 0)
            $('#divRoomBoard').scrollTop(int_divRoomBoard_scrollTop);
        if ($('#divProductHolidays').length > 0)
            $('#divProductHolidays').scrollTop(int_divProductHolidays_scrollTop);
        if ($('#divDiveCentres').length > 0)
            $('#divDiveCentres').scrollTop(int_divDiveCentres_scrollTop);
        if ($('#divDestinations').length > 0)
            $('#divDestinations').scrollTop(int_divDestinations_scrollTop);
        if ($('#divHotels').length > 0)
            $('#divHotels').scrollTop(int_divHotels_scrollTop);
        if ($('#divLiveaboards').length > 0)
            $('#divLiveaboards').scrollTop(int_divLiveaboards_scrollTop);
        if ($('#divHolidaysList').length > 0)
            $('#divHolidaysList').scrollTop(int_divHolidaysList_scrollTop);
    }
}

// CHeck the scroll position and perform click on hidden load more button if needed
function fncOnScrollLoadNext(btnButton, divScrollBox) {

    // Check where we are in the scroll
    if (divScrollBox.scrollTop() + divScrollBox.innerHeight() >= (divScrollBox[0].scrollHeight - 1250)) {
        // Perform click on hidden load more button
        fncClickTheLoadMoreButton(btnButton);
    }
}
// Perform click on hidden load more button
function fncClickTheLoadMoreButton(btnButton) {
    var hidPostBackFlag = $('input[type="hidden"][id$="hidHstPostBackInProgress"]');
    // Check that there is not already a postback in progress
    if (hidPostBackFlag.length > 0 && btnButton.length > 0) {
        if (hidPostBackFlag.val() != "TRUE") {

            // Flag that loading is busy
            hidPostBackFlag.val("TRUE");

            //console.log("Load more results");

            // Load more results
            btnButton.click();

            //console.log("after click !!!!!!!!!!!!!!!!!!!!!!!!!!");
        }
        //else {
        //console.log("already posting back");
        //}
    }
}


// Perform click on hidden load more button
function fncLoadMoreButton_onCLick(e) {
    js_debug_ouput('fncLoadMoreButton_onCLick');

    var hidPostBackFlag = $('input[type="hidden"][id$="hidHstPostBackInProgress"]');
    // Check that there is not already a postback in progress
    if (hidPostBackFlag.length > 0) {
        if (hidPostBackFlag.val() != "TRUE") {
            js_debug_ouput('YES');

            // Flag that loading is busy
            hidPostBackFlag.val("TRUE");
            return true;
        }
        else {
            js_debug_ouput('NO');
            e.preventDefault();
            e.stopPropagation();
            e.stopImmediatePropagation();
            return false;
        }
    }
    else {
        js_debug_ouput('NO');
        e.preventDefault();
        e.stopPropagation();
        e.stopImmediatePropagation();
        return false;
    }
}

function fncShowShare(strDivEnquire, strBtnClose, strBtnEnquire) {
    // hide all other enquire popouts
    $('#' + strDivEnquire).hide();

    // show the close button
    $get(strBtnClose).style.visibility = 'visible';
    $get(strBtnClose).style.display = 'block';
    // show the enquire button
    $get(strBtnEnquire).style.visibility = 'visible';
    $get(strBtnEnquire).style.display = 'block';
}
function fncHideShare(strDivEnquire, strBtnClose, strBtnEnquire) {
    // show the enquire div
    $get(strDivEnquire).style.visibility = 'visible';
    $get(strDivEnquire).style.display = 'block';
    // hide the close button
    $get(strBtnClose).style.visibility = 'hidden';
    $get(strBtnClose).style.display = 'none';
    // hide the enquire button
    $get(strBtnEnquire).style.visibility = 'hidden';
    $get(strBtnEnquire).style.display = 'none';
}

function fncShowPax(strDivEnquire, strBtnClose, strBtnEnquire, strDivPax, strArrow, strContainerDiv) {
    $(".holiday-result-container").css('z-index', '0');
    // hide all other enquire popouts
    $('input[id$="btnOpenPax"]').show();
    $('input[id$="btnCancel"]').hide();
    $('input[id$="btnEnquire"]').hide();
    $('div[id$="divPassengers"]').hide();
    $('div[id$="divEnquireArrow"]').hide();
    $('#' + strDivEnquire).hide();
    // hide the enquire div
    //$get(strDivEnquire).style.visibility = 'hidden';
    //$get(strDivEnquire).style.display = 'none';
    // show the close button
    $get(strBtnClose).style.visibility = 'visible';
    $get(strBtnClose).style.display = 'block';
    // show the enquire button
    $get(strBtnEnquire).style.visibility = 'visible';
    $get(strBtnEnquire).style.display = 'block';
    // show the pax div
    $get(strDivPax).style.visibility = 'visible';
    $get(strDivPax).style.display = 'block';
    // show the right arrow
    $get(strArrow).style.visibility = 'visible';
    $get(strArrow).style.display = 'block';

    $('#' + strContainerDiv).css('z-index', '1000');
}

function fncHidePax(strDivEnquire, strBtnClose, strBtnEnquire, strDivPax, strArrow, strContainerDiv) {
    // show the enquire div
    $get(strDivEnquire).style.visibility = 'visible';
    $get(strDivEnquire).style.display = 'block';
    // hide the close button
    $get(strBtnClose).style.visibility = 'hidden';
    $get(strBtnClose).style.display = 'none';
    // hide the enquire button
    $get(strBtnEnquire).style.visibility = 'hidden';
    $get(strBtnEnquire).style.display = 'none';
    // hide the pax div
    $get(strDivPax).style.visibility = 'hidden';
    $get(strDivPax).style.display = 'none';
    // hide the right arrow
    $get(strArrow).style.visibility = 'hidden';
    $get(strArrow).style.display = 'none';

    $(".holiday-result-container").css('z-index', '0');
}

function fncShowMediaPanelContent(strId, oElement) {

    // reset the button styles
    if ($get('ctl00_InnerFooter_ctrlMediaPanel_divDivImageButton'))
        $get('ctl00_InnerFooter_ctrlMediaPanel_divDivImageButton').className = 'MediaPanel-Button';
    if ($get('ctl00_InnerFooter_ctrlMediaPanel_divDestImageButton'))
        $get('ctl00_InnerFooter_ctrlMediaPanel_divDestImageButton').className = 'MediaPanel-Button';
    if ($get('ctl00_InnerFooter_ctrlMediaPanel_divVideos'))
        $get('ctl00_InnerFooter_ctrlMediaPanel_divVideos').className = 'MediaPanel-Button';
    if ($get('ctl00_InnerFooter_ctrlMediaPanel_divDestMapButton'))
        $get('ctl00_InnerFooter_ctrlMediaPanel_divDestMapButton').className = 'MediaPanel-Button';

    oElement.className = 'MediaPanel-Button MediaPanel-Button-Selected';

    // hide all
    $get('ctl00_InnerFooter_ctrlMediaPanel_divDiveImages').style.display = 'none';
    $get('ctl00_InnerFooter_ctrlMediaPanel_divDiveImages').style.visibility = 'hidden';
    $get('ctl00_InnerFooter_ctrlMediaPanel_divDestImages').style.display = 'none';
    $get('ctl00_InnerFooter_ctrlMediaPanel_divDestImages').style.visibility = 'hidden';
    $get('divDestVideos').style.display = 'none';
    $get('divDestVideos').style.visibility = 'hidden';
    //$get('divDestMap').style.display = 'none';
    //$get('divDestMap').style.visibility = 'hidden';

    //alert(strId);
    // show the one we want to show
    $get(strId).style.display = 'block';
    $get(strId).style.visibility = 'visible';
}

function fncMoveMediaPanel(blnUp, strListId, intMaxResults) {

    // Set our constants
    var intInitialIncrement = 35;
    var intIncrement = 35;
    var intExtraIncrement = 91;
    var intMarginTopWithPX = 0;
    var intBase = 28;
    var strFinalMarginTop = '';
    var intMaxMarginTop = ((intMaxResults / 4) * 240);
    var blnAllowIncrement = true;

    // If there is no marginTop set, default to our base value
    if ($get(strListId).style.marginTop == '')
        $get(strListId).style.marginTop = intBase + 'px';

    // Store the string value of the marginTop css attribute
    var strMarginTop = $get(strListId).style.marginTop;

    // Store the integer value of the margin
    var intMarginTopWithPX = parseInt(strMarginTop.replace('-', '').replace('px'));

    // Check if we have already moved up once
    if (intMarginTopWithPX >= intIncrement)
        intIncrement = intExtraIncrement;

    if (!blnUp && intMarginTopWithPX + intIncrement > intMaxMarginTop) {
        //alert('wtf');
        blnAllowIncrement = false;
    }

    if (blnAllowIncrement) {

        // Decide which way to calculate the new marginTop
        if (blnUp == true)
            intMarginTopWithPX = intMarginTopWithPX - intIncrement;
        else
            intMarginTopWithPX = intMarginTopWithPX + intIncrement;

        if (intMarginTopWithPX < intIncrement) {
            intMarginTopWithPX = intBase;
            strFinalMarginTop = intMarginTopWithPX + 'px';
        }
        else
            strFinalMarginTop = '-' + intMarginTopWithPX + 'px';


        $("#" + strListId).animate({
            marginTop: strFinalMarginTop
        }, 200);

        // Apply the marginTop css attribute
        //$get(strListId).style.marginTop = strFinalMarginTop;
    }

}


function fncMoveDiveImagePanelToImage(strListId, intImageIndex) {

    // Update the dive image index
    mintDiveImageIndex = intImageIndex;
    // Store the amount of images in total
    var intTotalImages = $('input[type="hidden"][id$="hidCountDiveImages"]').val();
    fncMoveImagePanelToImage(strListId, intImageIndex, intTotalImages);
}
function fncMoveDestImagePanelToImage(strListId, intImageIndex) {

    // Update the dest image index
    mintDestImageIndex = intImageIndex;
    // Store the amount of images in total
    var intTotalImages = $('input[type="hidden"][id$="hidCountDestImages"]').val();
    fncMoveImagePanelToImage(strListId, intImageIndex, intTotalImages);
}
function fncMoveVideoPanelToImage(strListId, intImageIndex) {

    // Update the dest image index
    mintVideoIndex = intImageIndex;
    // Store the amount of images in total
    var intTotalImages = $('input[type="hidden"][id$="hidCountVideos"]').val();
    fncMoveImagePanelToImage(strListId, intImageIndex, intTotalImages);
}

function fncMoveImagePanelToImage(strListId, intImageIndex, intTotalImages) {

    // Don't move the panel if at the end of the list
    if (intImageIndex < intTotalImages - 3) {
        var intIncrement = 91;
        var intInitialIncrement = 63;
        var blnMovePanel = false;
        var strFinalMarginTop;
        var intBase = 28;

        if (intImageIndex > 1) {
            intIncrement = intInitialIncrement + (intIncrement * (intImageIndex - 1));
            //alert(intIncrement);
            strFinalMarginTop = '-' + intIncrement + 'px';
            blnMovePanel = true;
        }
        else if (intImageIndex == 1) {
            strFinalMarginTop = '-' + intInitialIncrement + 'px';
            blnMovePanel = true;
        }
        else if (intImageIndex == 0) {
            strFinalMarginTop = intBase + 'px';
            blnMovePanel = true;
        }

        if (blnMovePanel)
            $("#" + strListId).animate({ marginTop: strFinalMarginTop }, 200);
    }
}
function fncNextDiveImage(strListId, blnRight) {

    if (blnRight)
        mintDiveImageIndex = mintDiveImageIndex + 1;
    else
        mintDiveImageIndex = mintDiveImageIndex - 1;

    var strIndex = '';
    if (mintDiveImageIndex < 10)
        strIndex = '0' + mintDiveImageIndex;
    else
        strIndex = mintDiveImageIndex;

    var imgImage = $('img[id$="rptImageList_ctl' + strIndex + '_imgImage"]');
    if (imgImage.length > 0) {
        imgImage.click();
    }
    else {
        if (blnRight)
            mintDiveImageIndex = mintDiveImageIndex - 1;
        else
            mintDiveImageIndex = mintDiveImageIndex + 1;
        // Move the panel
        fncMoveDiveImagePanelToImage(strListId, mintDiveImageIndex);
    }
}
function fncNextDestImage(strListId, blnRight) {

    if (blnRight)
        mintDestImageIndex = mintDestImageIndex + 1;
    else
        mintDestImageIndex = mintDestImageIndex - 1;

    var strIndex = '';
    if (mintDestImageIndex < 10)
        strIndex = '0' + mintDestImageIndex;
    else
        strIndex = mintDestImageIndex;

    var imgImage = $('img[id$="rptDestImageList_ctl' + strIndex + '_imgImage"]');
    if (imgImage.length > 0) {
        imgImage.click();
    }
    else {
        if (blnRight)
            mintDestImageIndex = mintDestImageIndex - 1;
        else
            mintDestImageIndex = mintDestImageIndex + 1;
        // Move the panel
        fncMoveDestImagePanelToImage(strListId, mintDestImageIndex);
    }
}

function fncNextVideo(strListId, blnRight) {
    if (blnRight)
        mintVideoIndex = mintVideoIndex + 1;
    else
        mintVideoIndex = mintVideoIndex - 1;

    var strIndex = '';
    if (mintVideoIndex < 10)
        strIndex = '0' + mintVideoIndex;
    else
        strIndex = mintVideoIndex;

    var imgImage = $('img[id$="rptVideos_ctl' + strIndex + '_imgImage"]');
    if (imgImage.length > 0) {
        imgImage.click();
    }
    else {
        if (blnRight)
            mintVideoIndex = mintVideoIndex - 1;
        else
            mintVideoIndex = mintVideoIndex + 1;
        // Move the panel
        fncMoveVideoPanelToImage(strListId, mintVideoIndex);
    }
}


function fncMoveRecommendedPanel(blnUp, strListId) {

    var intIncrement = 122;
    var intTimesBy = 0;

    if ($('input[type="hidden"][id$="hidMaxResults"]').length > 0) {
        intTimesBy = (parseInt($('input[type="hidden"][id$="hidMaxResults"]').val()) / 3) - 1;
    }

    if ($get(strListId).style.marginTop == '')
        $get(strListId).style.marginTop = '0px';

    var strMarginTop = $get(strListId).style.marginTop;

    var intMarginTopWithPX = 0;

    if (blnUp == true)
        intMarginTopWithPX = parseInt(strMarginTop.replace('-', '').replace('px')) - intIncrement;
    else
        intMarginTopWithPX = parseInt(strMarginTop.replace('-', '').replace('px')) + intIncrement;

    // Cater for 3 pages of items
    if (intMarginTopWithPX <= (122 * intTimesBy))
        $get(strListId).style.marginTop = '-' + intMarginTopWithPX + 'px';

}

function fncFadeInMediaPanelArrows() {
    if (!blnFadeInMediaPanel) {

        blnFadeInMediaPanel = true;
        blnFadeOutMediaPanel = false;
        $(".MediaPanel-Content-DivingImagesListLeft").animate({
            opacity: 0.70
        }, 70);
        $(".MediaPanel-Content-DivingImagesListRight").animate({
            opacity: 0.70
        }, 70);
    }
}
function fncFadeOutMediaPanelArrows() {

    if (!blnFadeOutMediaPanel) {

        blnFadeInMediaPanel = false;
        blnFadeOutMediaPanel = true;
        $(".MediaPanel-Content-DivingImagesListLeft").animate({
            opacity: 0
        }, 70);
        $(".MediaPanel-Content-DivingImagesListRight").animate({
            opacity: 0
        }, 70);
    }
}


function fncSetActiveTabIndex(strTabContainer, intActiveTabIndex) {
    $find(strTabContainer).set_activeTabIndex(intActiveTabIndex);
}

function fncChangeDiveImage(strURL, strAlt, strTitle) {
    //console.log('fncChangeDiveImage(' + strURL + ',' + strAlt + ')');
    var imgMainDestImage = $('img[id$="imgMainImage"]');
    if (imgMainDestImage.length > 0) {
        //console.log('found imgMainImage');
        imgMainDestImage.attr("src", strURL);
        imgMainDestImage.attr("alt", strAlt);
        $get('divDiveImageText').innerHTML = strTitle;
    }
}

function fncChangeDestImage(strURL, strAlt, strTitle) {
    //console.log('fncChangeDestImage(' + strURL + ',' + strAlt + ')');
    var imgMainDestImage = $('img[id$="imgMainDestImage"]');
    if (imgMainDestImage.length > 0) {
        //console.log('found imgMainDestImage');
        imgMainDestImage.attr("src", strURL);
        imgMainDestImage.attr("alt", strAlt);
        $get('divDestImageText').innerHTML = strTitle;
    }
}



// ============================================================================================================
// Home page
// Cut and paste by MRB 2012-01-10
// ============================================================================================================

var strCurrentlySelected = 'ud1';

function fnc_ChangeImage(oElement) {
    // Turn all of the buttons off
    document.getElementById('ud1').src = document.getElementById('ud1').src.replace('on', 'off');
    document.getElementById('ud2').src = document.getElementById('ud2').src.replace('on', 'off');
    document.getElementById('ud3').src = document.getElementById('ud3').src.replace('on', 'off');
    document.getElementById('ud4').src = document.getElementById('ud4').src.replace('on', 'off');
    document.getElementById('ud5').src = document.getElementById('ud5').src.replace('on', 'off');

    // Turn the clicked element on
    oElement.src = oElement.src.replace('off', 'on');

    // Update our global variable so we know what element is currently selected
    strCurrentlySelected = oElement.id;

}

function fnc_RollOverImage(oElement, strFlag) {

    // Check that the currently rolled over icon is NOT the one currently selected

    var strOppositeFlag = ''

    if (strFlag == 'on')
        strOppositeFlag = 'off';
    else
        strOppositeFlag = 'on';

    // Change the image of the element
    oElement.src = oElement.src.replace(strOppositeFlag, strFlag);

}

function moveToImageAtPx(intLeftMarginPx) {
    $(".widearea").animate({
        marginLeft: '-' + intLeftMarginPx + 'px'
    }, 500);
    fncChangeIndicatorImage(intLeftMarginPx);
}


function moveToNextImage() {

    var strMarginLeft = $get('divwidearea').style.marginLeft;
    var intMarginLeftWithPX = parseInt(strMarginLeft.replace('-', '').replace('px'))

    // Flick back to the start with no animation
    if (intMarginLeftWithPX > 3840) {
        $(".widearea").css({
            marginLeft: '0px'
        });
        intMarginLeftWithPX = 0;
    }

    // Offset so that it will scroll by image width
    intMarginLeftWithPX = intMarginLeftWithPX + 960;

    $(".widearea").animate({
        marginLeft: '-' + intMarginLeftWithPX + 'px'
    }, 500);

    fncChangeIndicatorImage(intMarginLeftWithPX);
    var t = setTimeout("moveToNextImage()", 5000);

}

function fncChangeIndicatorImage(intMarginLeftWithPX) {
    var strSliderOn = '/Images/slider-on.png';
    var strSliderOff = '/Images/slider-off.png';
    if (intMarginLeftWithPX == 960) {
        document.getElementById('slider1').src = strSliderOff;
        document.getElementById('slider2').src = strSliderOn;
        document.getElementById('slider3').src = strSliderOff;
        document.getElementById('slider4').src = strSliderOff;
        document.getElementById('slider5').src = strSliderOff;
    }
    else if (intMarginLeftWithPX == 1920) {
        document.getElementById('slider1').src = strSliderOff;
        document.getElementById('slider2').src = strSliderOff;
        document.getElementById('slider3').src = strSliderOn;
        document.getElementById('slider4').src = strSliderOff;
        document.getElementById('slider5').src = strSliderOff;
    }
    else if (intMarginLeftWithPX == 2880) {
        document.getElementById('slider1').src = strSliderOff;
        document.getElementById('slider2').src = strSliderOff;
        document.getElementById('slider3').src = strSliderOff;
        document.getElementById('slider4').src = strSliderOn;
        document.getElementById('slider5').src = strSliderOff;
    }
    else if (intMarginLeftWithPX == 3840) {
        document.getElementById('slider1').src = strSliderOff;
        document.getElementById('slider2').src = strSliderOff;
        document.getElementById('slider3').src = strSliderOff;
        document.getElementById('slider4').src = strSliderOff;
        document.getElementById('slider5').src = strSliderOn;
    }
    else {
        document.getElementById('slider1').src = strSliderOn;
        document.getElementById('slider2').src = strSliderOff;
        document.getElementById('slider3').src = strSliderOff;
        document.getElementById('slider4').src = strSliderOff;
        document.getElementById('slider5').src = strSliderOff;
    }
}

function fncOpenReadMore() {
    $('#divHomepageSocial').hide();
    $('#divHomepageReadMore').removeClass("homepage-getintouch").addClass("homepage-getintouch-open");
}
function fncCloseReadMore() {
    $('#divHomepageSocial').show();
    $('#divHomepageReadMore').removeClass("homepage-getintouch-open").addClass("homepage-getintouch");
}

function fncNavigate(strURL) {
    window.location.href = strURL;
}
function fncOpenForgottenPassword() {
    $('#divOpenForgottenPassword').show();
}

