// * This file has been reorganized to reduce JS init execution time.
// * If you are not performing any direct actions on the body element then it is safe to execute the JS without waiting 
// for the full dom to be ready.
// ---------------------------------------------
// * To help keep this file organized, please add new functions to the FC object 
// 'namespace' and use the FC init code as demonstrated in this file.

FC.vars = {
    selectors: {
        LISTING_RESULTS: '#hotels-listing-results',
        FINDAHOTEL: '#find_a_hotel',
        BOOKINGFORM: '#booking_form',
        TOPDESTINATIONS: '#locations-selector',
        SEARCHSPECIALOFFERS: '#search-special-offers',
        CLUBLOGIN: '#club-login'
    }
};

// Find a hotel results : Google Map overlay
FC.hotelMapModal = function (elem) {

    var anchorClass = 'hotel-map';

    function clickHandler(e) {

        var target = e.target;

        // Check if the target is an anchor element and if the className matches
        if (target.nodeName !== 'A' || !new RegExp("\\b" + anchorClass + "\\b").test(target.className)) {
            return;
        }

        $.colorbox({
            href: target.href,
            iframe: true,
            initialWidth: 100,
            initialHeight: 100,
            width: 600,
            height: 425,
            faseIframe: false,
            scrolling: false
        });
        return false;
    }

    // Wait for DOM to be ready
    elem.live('click', clickHandler);
};

// Find a hotel widget: Fix for default value - "Enter Country, City or Hotel Name"
FC.findAHotelFix = function(elem) {

    var defDestValue = elem.find(".defaultDestination").val();

    elem
    .find(".destinationAcInput")
    .focus(function () {
        if (this.value == defDestValue) {
            this.value = ""
        }
    })
    .blur(function () {
        if (this.value == "") {
            this.value = defDestValue;
        }
    });
};

// Find a hotel booking form functionality.
FC.bookingForm = function(elem) {
    
    var _$bookingForm = elem;
    var _$hotelNightsContainer = _$bookingForm.find(".findAHotelNights")
    var _$hotelGuestsContainer = _$bookingForm.find(".findAHotelGuests")
    var _$arrivingTextInput = _$bookingForm.find(".arriving")
    var _$departingTextInput = _$bookingForm.find(".departing")
    var _$nightsSelectInput = _$bookingForm.find(".no-of-nights")
    var _$guestsSelectInput = _$hotelGuestsContainer.find(".guests")

    function showHideNightsAndGuests(show) {
        if (show) {
            _$hotelNightsContainer.show();
            _$hotelGuestsContainer.show();
            _$hotelNightsContainer.css({ "display": "block" });
            _$hotelGuestsContainer.css({ "display": "block" });

        } else {
            _$hotelNightsContainer.hide();
            _$hotelGuestsContainer.hide();
        }
    }

    if (_$arrivingTextInput.val() == "" || _$arrivingTextInput.val() == "dd/mm/yyyy" || _$arrivingTextInput.val() == "undefined") {
        _$arrivingTextInput.val("dd/mm/yyyy");
        if ($(FC.vars.selectors.FINDAHOTEL).length > 0) {
            showHideNightsAndGuests(false);
        }
        else {
            showHideNightsAndGuests(true);
        }
    } else {
        showHideNightsAndGuests(true);
    }

    // this change not working on datepicker change
    _$arrivingTextInput.bind('focus', function () {
        if ($(FC.vars.selectors.FINDAHOTEL).length > 0) {
            var show = $(this).val() != "" && $(this).val() != "dd/mm/yyyy";
            showHideNightsAndGuests(show);
        }
    });
    _$arrivingTextInput.bind('blur', function () {
        if ($(this).val() == "")
            $(this).val("dd/mm/yyyy");

        if ($(FC.vars.selectors.FINDAHOTEL).length == 0)
            return;

        var show = $(this).val() != "" && $(this).val() != "dd/mm/yyyy";
        showHideNightsAndGuests(show);
    });
    _$arrivingTextInput.bind('keyup', function () {
        if ($(FC.vars.selectors.FINDAHOTEL).length == 0)
            return;

        showHideNightsAndGuests($(this).val().length > 0);
    });

    _$arrivingTextInput.bind('click', function () {
        if (_$arrivingTextInput.val() == "dd/mm/yyyy")
            _$arrivingTextInput.val("")
    });  

    $(".submit-availability").bind("click", function (e) {
        if ($(".arriving").val() === 'dd/mm/yyyy' || $(".arriving").val() === '') {
            e.preventDefault();
            $(".error").remove();
            $(".button").before("<span class='error'>please enter a date to check availability</span>")
        }
    });

    $(".arriving").change(function () {
        $(".error").remove()
    })
};

FC.showLogin = function () {

    var checkbox = $('.club-member input');
    var clubLoginBox = $('.clubLogin');
    var checkAvailabilityButton = $('input.check-availability');

    // Pre-load images: DDK need to translate the images below, but need to move it to c#
    var imagePaths = [
		'/images/slh/button_sign-in-and-check-availability.gif'
	];
    for (var i = 0; i < imagePaths.length; i++) {
        var a = new Image();
        a.src = imagePaths[i];
    }
    // Images should be pre-loaded now

    var hideClubLoginBox = function () {
        //checkAvailabilityButton.attr('src', imagePaths[0]);
        clubLoginBox.hide();
    }

    var showClubLoginBox = function () {
        checkAvailabilityButton.attr('src', imagePaths[1]);
        clubLoginBox.show();
    }

    if (!checkbox.get(0).checked && $('.panel-club.club-login-reservation').length == 0) {
        hideClubLoginBox(); // Hide the Make Reservations login box, but only if the "I am a Club member" checkbox isn't checked, and the class indicating a log-in error isn't present
    }
    else {
        showClubLoginBox();
    }

    checkbox.bind("click", function () {
        //if it's selected, then show the div
        if (this.checked) {
            showClubLoginBox();
        } else {
            //hide the div
            hideClubLoginBox();
        }

    });
};

// ----------- top destinations
FC.topDestinations = function(elem) {
    var locationSelector = elem;
    var monthList = locationSelector.find("#months a");
    var resultsPanel = locationSelector.find("#locations-selector-results");
    var monthListItem = locationSelector.find("#months li");

    monthList.bind("click", function () {
        $.ajax({
            url: this.href,
            success: function (html) {
                resultsPanel.empty().append(html);
                monthListItem.removeClass("selected");
                $(this).parent().addClass("selected");
            }
        })
        return false;
    });
};


// Special offers filter list dropdowns.
FC.searchSpecialOffers = function(container){
    
    var form = $('#aspnetForm'), request, ajaxLoader;

    function isFilterFormDropdown(target) {
        return (target[0].nodeName === 'SELECT' && target.parents('#search-special-offers').length);
    }

    function sendRequest(target) {
        
        var data = form.serialize();

        try {
            (request && request.abort) && request.abort();
        } catch(e){}

        container.find('select').each(function(){
            if (this !== target[0]) {
                $(this).empty().append('<option>Loading...</option>');
            }
        });
        
        request = $.ajax({
            url: form[0].action,
            type: 'POST',
            data: data,
            dataType: 'HTML',
            success: function(html) {

                html = $(html);
            
                // Find and replace the dropdowns in the filter form.
                html
                .find('#search-special-offers')
                .find('select')
                .each(function(){

                    // Don't replace the trigger dropdown.
                    if (this.id !== target[0].id) {

                        // Replace the dropdown.
                        $('#' + this.id).after(this).remove();
                    }
                });

                // Update the page view state.
                $('#__VIEWSTATE').val( html.find('#__VIEWSTATE').val() );
            },
            error: function() {
                alert('Sorry, an unexpected error occured. Please try again.');
            }
        });
    }

    if (container.length) {
        
        // The following function prevent the filter form from being submitted when hitting enter 
        // on any of the select dropdowns.
        (function(submit){

            $(document).keydown(function(e){

                submit = !( e.keyCode === 13 && isFilterFormDropdown( $(e.target) ) );
            });

            form.submit(function(){ return submit; });
        })(true);

        // The following code traps the .NET postback.
        // As we can't trap the onsubmit event (when it's exeucted by JS), we need to redefine the postback JS
        // See: http://stackoverflow.com/questions/645555/should-jquerys-form-submit-not-trigger-onsubmit-within-the-form-tag/645556#645556
        var postBack = window.__doPostBack;
        window.__doPostBack = function(eventTarget, eventArgument) {

            // Find the trigger target elem.
            var target = $('#' + eventTarget.replace(/\$/g, '_'));

            // Is the element a dropdown and is it part of the filter form?
            if (isFilterFormDropdown(target)) {
                sendRequest(target);
            } else {
                // Perform default postback.
                postBack.apply(this, arguments);
            }
        };
    }
};

// Club login placeholder values
FC.clubLogin = function(container) {

    function changeType(type, value) {
        // IE won't allow us to change the field type,
        // so we create a new input field
        var field = $('<input />')
        .attr({
            'type': type,
            'name': this.name,
            'value': value,
            'id': this.id,
            'tabIndex': this.tabIndex,
            'title': this.title,
            'style': this.style,
            'class': this.className
        })
        .data('password', (type === 'text'));

        $(this).after(field).remove();

        return field;
    }

    container
    .find('input:text, input:password')
    .live('focus.mask', function () {
        if (this.value === this.title) {
            this.value = '';
        }
        // If the text field was originally of type 'password',
        // then convert it back to a password field to mask the user input.
        if ($(this).data('password')) {
            var field = changeType.call(this, 'password');
            setTimeout(function () {
                field[0].focus();
            });
        }
    })
    .live('blur.mask', function (event) {
        if (!this.value.length && this.title) {
            // If it's a password field, then we need to convert it to 
            // type 'text' so can display the placeholder value.
            if (this.type === 'password') {
                changeType.call(this, 'text', this.title);
            }
            this.value = this.title;
        }
    })
    .trigger('blur.mask');
};

(function(){
    var __SEL = FC.vars.selectors;
    FC.init([
        { func: FC.clubLogin, test: __SEL.CLUBLOGIN },
        { func: FC.bookingForm, test: __SEL.BOOKINGFORM },
        { func: FC.hotelMapModal, test: __SEL.LISTING_RESULTS },
        { func: FC.findAHotelFix, test: __SEL.FINDAHOTEL },
        { func: FC.topDestinations, test: __SEL.TOPDESTINATIONS },
        { func: FC.searchSpecialOffers, test: __SEL.SEARCHSPECIALOFFERS }
    ]);
})();

// -- addLoadEvent function from http://simonwillison.net --//
function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function () {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}

//---- DROPDOWN LIST SYNC ----//
// The following code will filter a destination city select list by location
addLoadEvent(filterDestinations);
function hideOpt(opt, select) {
    //var opt = document.getEflementById(id);
    var sel = select;
    opt && sel && sel.appendChild(opt.cloneNode(true));
}

function showOpt(opt, select) {
    var dest = select; //document.getElementById('ctl00_FindHotel1_fDestinationselect');
    if (opt) {
        if (dest) {
            dest.appendChild(opt.cloneNode(true));
        }
    }
}
function moveSelectOption(select, selectcopy, start1, start2) {
    selectcopy.options.length = start2;
    for (i = start1; i < select.length; i++) {  //ignore the first please select
        hideOpt(select.options[i], selectcopy);
    }
    select.options.length = start1;
}
function findByValue(select, value) {
    var valueToSelect = value;
    var mySelect = select;
    for (var index = 0, roof = mySelect.options.length; index < roof; index++) {
        if (valueToSelect == mySelect.options[index].value) {
            return mySelect.options[index];
        }
    }
}
function filterDestinations() {
    if (typeof cIdTempSelectArrayId != 'undefined') {
        for (var index = 0, roof = cIdTempSelectArrayId.length; index < roof; index++) {
            subFilterDestinations(cIdTempSelectArrayId[index][0], cIdTempSelectArrayId[index][1], cIdTempSelectArrayId[index][2]);
        }
    }
}

function subFilterDestinations(tempId, mainSelect, subSelect) {
    var temp = document.getElementById(tempId);
    var country, dest, selectedValue, mainS, subS;

    if (temp) if (mainSelect) country = document.getElementById(mainSelect);
    if (temp) if (mainSelect) dest = document.getElementById(subSelect);

    if (temp && country && dest) {
        selectedValue = dest.options[dest.selectedIndex].value;
        if (temp.length == 0) moveSelectOption(dest, temp, 1, 0);
        dest.options.length = 1;
        if (country) {
            for (var currObj in CountrySlhDest) {
                if (CountrySlhDest[currObj][country.value]) { showOpt(findByValue(temp, CountrySlhDest[currObj][country.value]), dest); }
            }
            if (country.selectedIndex == 0) { moveSelectOption(temp, dest, 0, 1); }
            if (dest.options.length == 1 && (dest.options[0].text == 'Please Choose' || dest.options[0].text == '-- Not Applicable --')) dest.options[0].text = '-- Not Applicable --'; else if (dest.options[0].text == 'Please Choose' || dest.options[0].text == '-- Not Applicable --') dest.options[0].text = 'Please Choose';
        }
        var obj = findByValue(dest, selectedValue)
        if (obj) obj.setAttribute('selected', true);
    }
}

function setCookie(c_name, value, expiredays, path) {
    c_name = getCookieName(c_name);
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value) +
	((expiredays == null) ? "" : ";expires=" + exdate.toUTCString()) +
	(path ? ";path=" + path : "") +
	getDomainName();
}

function getCookieName(c_name) {
    return c_name + cookieSuffix;
}

function getDomainName() {
    var domain = window.location.hostname;
    var cookieDomain = "";

    if (domain.toLowerCase() == "www.slh.com" || domain.toLowerCase() == "slh.com") {
        cookieDomain = ".slh.com";
    }
    else {
        var firstDotPosition = domain.indexOf(".");
        if (firstDotPosition != -1) {
            cookieDomain = domain.substring(firstDotPosition);
        }
    }

    if (cookieDomain != "") {
        cookieDomain = ";domain=" + cookieDomain;
    }

    return cookieDomain;
}

function getCookie(c_name) {
    c_name = getCookieName(c_name);
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

//---- RESERVATION DROPDOWNS ----//  
function unSelect(dropdownId) {
    //selects the first element of a dropdown list
    if (document.getElementById(dropdownId)) { document.getElementById(dropdownId).selectedIndex = 0; }
}




/* GALLERY SHOW/HIDE */
var galleryPLImages = [];

var hotelGallery = function () {

    var __intro = $("#masthead-hotel");
    var __gallery = $("#masthead-gallery");
    var __galleryInner = $(".gallery-inner");
    var __open = $(".masthead-gallery-link");
    var __close = $("#masthead-gallery a.close");
    var __content = $("#content");

    // Preload images. This makes correctImageDimensions work more reliably
    var imageUrlsForPreloading = getURLs();
    for (var i = 0; i < imageUrlsForPreloading.length; i++) {
        var image = new Image();
        image.src = imageUrlsForPreloading[i];
        galleryPLImages.push(image);
    }

    var openGallery = function () {
        __intro.fadeOut(500, function () {

            __gallery.css({ display: "block" });
            __content.animate({ paddingTop: 483 }, 500);
            __gallery.animate({ height: 465 }, 500, function () {
                __galleryInner.fadeIn(500);
                correctImageDimensions();
            });

        });

        return false;
    }

    __open.bind("click", openGallery);


    __close.bind("click", function () {
        // stop the slideshow
        gallerySlideShowStop();
        __galleryInner.fadeOut(500, function () {

            __content.animate({ paddingTop: 254 }, 500);
            __gallery.animate({ height: 236 }, 500, function () {

                __gallery.css({ display: "none" });
                __intro.fadeIn(500);

            });

        });

        return false;

    });

    if ($('body.opengallery').length > 0) {
        openGallery();
    }

}

// GALLERY - Self contained 
var showImage = function () {
    $('.gallery-inner .thumb a').bind("click", function () {
        gallerySlideShowStop();
        var __imgPath = $(this).attr('href');
        gallerySlideShowMainImage.fadeOut(250, function () {
            gallerySlideShowMainImage.attr('src', __imgPath);
            correctImageDimensions();
            gallerySlideShowMainImage.fadeIn(250);
            //gallerySlideShowMainImage.attr('display','inline-block');	
        });
        return false;
    });
}

//Slideshow
var gallerySlideShowButton = $(".buttons .view");
var gallerySlideShowButtonImage = gallerySlideShowButton.find('img');
var gallerySlideShowMainImage = $('.main-image img');

var gallerySlideShow = function () {
    gallerySlideShowButton.bind("click", function () {
        if (window.slideshowRunning) {
            gallerySlideShowStop();
        }
        else {
            gallerySlideShowStart();
        }
        return false;
    });
    gallerySlideShowMainImage.bind("click", function () {
        if (window.slideshowRunning) {
            gallerySlideShowStop();
        }
        return false;
    })
}

var gallerySlideShowStart = function () {
    changeImage(0);
    window.slideshowInterval = setInterval("cycle()", 4000);
    window.slideshowRunning = true;
    gallerySlideShowButtonImage.attr('src', function () {
        return this.src.replace('-view-', '-stop-');
    });
}
var gallerySlideShowStop = function () {
    window.clearInterval(window.slideshowInterval);
    window.slideshowRunning = false;
    gallerySlideShowButtonImage.attr('src', function () {
        return this.src.replace('-stop-', '-view-');
    });
}

var cycle = function () {
    var $imageURLs = getURLs();
    __counter = getCurrentImage($imageURLs);
    __counter++;
    if (__counter == $imageURLs.length) { __counter = 0; }
    changeImage(__counter);
}



// CHANGE THE IMAGE 
var changeImage = function (__counter) {
    var $imageURLs = getURLs();

    gallerySlideShowMainImage.fadeOut(300, function () {
        gallerySlideShowMainImage.attr('src', $imageURLs[__counter]);
        gallerySlideShowMainImage.fadeIn(300);
        correctImageDimensions();
    });
}

var correctImageDimensions = function () {
    var MAXWIDTH = 473;
    var MAXHEIGHT = 338;

    var currentImageIndex = getCurrentImage(getURLs());
    gallerySlideShowMainImage.removeAttr('width');
    gallerySlideShowMainImage.removeAttr('height');

    var width = galleryPLImages[currentImageIndex].width;
    var height = galleryPLImages[currentImageIndex].height;

    if (width > MAXWIDTH || height > MAXHEIGHT) {
        var widthRatio = MAXWIDTH / width;
        var heightRatio = MAXHEIGHT / height;

        if (widthRatio < heightRatio) {
            var ratio = widthRatio;
        }
        else {
            var ratio = heightRatio;
        }

        var newWidth = Math.round(width * ratio);
        var newHeight = Math.round(height * ratio);

        //alert('Width: ' + width + '\nHeight: ' + height + '\n\nwidthRatio: ' + widthRatio + '\nheightRatio: ' + heightRatio + '\n\nnewWidth: ' + newWidth + '\nnewHeight: ' + newHeight);

        gallerySlideShowMainImage.attr('width', newWidth);
        gallerySlideShowMainImage.attr('height', newHeight);
    }
}



//Previous and Next buttons
var prevNext = function () {

    var $imageURLs = getURLs();

    $('.main-image .previous').bind("click", function () {
        gallerySlideShowStop();
        __counter = getCurrentImage($imageURLs);
        __counter--;

        if (__counter < 0) {
            __counter = ($imageURLs.length - 1);
        }
        changeImage(__counter);
        return false;

    });
    $('.main-image .next').bind("click", function () {
        gallerySlideShowStop();
        __counter = getCurrentImage($imageURLs);
        __counter++;
        // ensure it's not going past the length of the array
        if (__counter > ($imageURLs.length - 1)) {
            __counter = 0;
        }
        changeImage(__counter);
        return false;
    });
}

// get all the images into an array
var getURLs = function () {
    var $imageURLs = [];

    var __counter = 0;
    $(".gallery-inner .thumbCol li a").each(function () {
        $imageURLs[__counter] = $(this).attr('href');
        __counter++;
    });
    return $imageURLs;
}

// find the current image and made the array number match it - that way we can figure out which image to show next/previous
var getCurrentImage = function ($imageURLs) {
    var __arrayCounter = 0;
    for (var i = 0; i < $imageURLs.length; i++) {
        if (gallerySlideShowMainImage.attr('src') == ($imageURLs[i])) {
            __arrayCounter = i;
        }
    }
    return __arrayCounter;
}

// scroller function for IMAGE GALLERY */
var scroller = function () {
    $(".buttons .next").show();
    $(".buttons .previous").show();
    $(".thumbnailContainer").css('overflow-x', 'hidden');

    var __right = $(".buttons .next a");
    var __left = $(".buttons .previous a");
    var __container = $(".thumbnailContainer");
    var __scrollAmount = 1;
    var __current = 0;
    var __contentBoxes = $(".thumbnailContainer .thumbnailWrapper .thumbCol");
    var __max = Math.floor(__contentBoxes.length / __scrollAmount);
    __max = __max * __scrollAmount;

    //Activate both rollovers
    //rollover(__right,"FormatsRight",0);
    //rollover(__left,"FormatsLeft",0);

    //Make sure the scroller is at the start
    __container.scrollTo('.thumbCol:eq(' + 0 + ')', 500, { axis: 'x' });


    if (__max == __contentBoxes.length) {
        __max = __max - __scrollAmount;
    }


    //Left scroller button
    __left.bind("click", function () {

        if (__current > 0) {

            //rollover(__right,"FormatsRight",0);
            //__right.find("img").attr("src","../images/slh/country/colour5/buttons/products-right-off.gif");

            __current = __current - __scrollAmount;
            __container.scrollTo('.thumbCol:eq(' + __current + ')', 500, { axis: 'x' });
        }
        //if(__current==0){
        //	rollover(__left,"FormatsLeft",1);
        //	__left.find("img").attr("src","../images/slh/country/colour5/buttons/products-left-inactive.gif");
        //}
        return false;
    });

    //Right scroller button
    __right.bind("click", function () {

        if (__current < __max) {

            //if(__current==(__max-__scrollAmount)){
            //	rollover(__right,"FormatsRight",1);
            //	__right.find("img").attr("src","../images/slh/country/colour5/buttons/products-right-inactive.gif");
            //}

            //rollover(__left,"FormatsLeft",0);
            //__left.find("img").attr("src","../images/slh/country/colour5/buttons/products-left-off.gif");

            __current = __current + __scrollAmount;
            __container.scrollTo('.thumbCol:eq(' + __current + ')', 500, { axis: 'x' });
        }
        return false;
    });
}



var showRecommendedDestinations = function () {
    var heading = $('#panel-recommended-destinations h2');
    var spanToReceiveClickElement = $('#panel-recommended-destinations h2 .ie-js');
    var headingAndSIFR = $('#panel-recommended-destinations h2, #panel-recommended-destinations h2 object, #panel-recommended-destinations h2 embed');
    var content = $('#panel-recommended-destinations ul');

    //set default to collapsed
    heading.addClass('collapsed');
    content.hide();

    headingAndSIFR.toggle(
		function () {
		    content.show();
		    heading.removeClass('collapsed');
		    return false;
		},
		function () {
		    content.hide();
		    heading.addClass('collapsed');
		    return false;
		}
	);
    spanToReceiveClickElement.css({
        'cursor': 'pointer'
    });
}

var clubHomeLoggedIn = function () {

    $('div.logged-home li').click(

		function () {

		    if (!$(this).hasClass('selected') && $('#tab-offer-data').hasClass('hideThis')) {
		        $(this).addClass('selected');
		        $('#tab-hotel-nav').removeClass('selected');

		        $('#tab-hotel-data').addClass('hideThis');
		        $('#tab-hotel-data').removeClass('showThis');

		        $('#tab-offer-data').addClass('showThis');
		        $('#tab-offer-data').removeClass('hideThis');

		        return false;

		    }
		    else if (!$(this).hasClass('selected') && $('#tab-offer-data').hasClass('showThis')) {
		        $(this).addClass('selected');
		        $('#tab-offer-nav').removeClass('selected');

		        $('#tab-hotel-data').addClass('showThis');
		        $('#tab-hotel-data').removeClass('hideThis');

		        $('#tab-offer-data').addClass('hideThis');
		        $('#tab-offer-data').removeClass('showThis');

		        return false

		    }

		}

	);
}

var clubReasons = function () {
    $("ol.reasons li").find(".text").css("margin-top", "10px");
    $("ol.reasons li .text-collapse").each(function () {
        $(this).addClass("collapsed").hide().after($("<a></a>").addClass("collapse-link").addClass("large-link").attr("href", "#").text("Tell me more"));
        $(this).parents(".text").siblings(".image-collapse").css("height", "76px");
    });
    //alert($(".collapse-link").length);
    $(".collapse-link").bind("click", function () {
        if ($(this).siblings(".collapsed").length) {
            $(this).text("Close");
            $(this).siblings(".collapsed").removeClass("collapsed").addClass("expanded").slideDown(500);
            $(this).parents(".text").siblings(".image-collapse").animate({ height: 150 }, 500);
            $(this).parents(".text").animate({ marginTop: 0 }, 500);
            $(this).parents(".text").addClass("alt");
        } else {
            $(this).text("Tell me more");
            $(this).siblings(".expanded").removeClass("expanded").addClass("collapsed").slideUp(500);
            $(this).parents(".text").siblings(".image-collapse").animate({ height: 76 }, 500);
            $(this).parents(".text").animate({ marginTop: 10 }, 500);
            $(this).parents(".text").removeClass("alt");
        }
        return false;
    });
}

var tabs = function () {
    var tabsContainers = $(".tabs-bigger-js");
    var SELECTEDCLASS = 'selected';

    tabsContainers.each(function () {
        var tabContainer = $(this);
        var tabLinks = tabContainer.find('.tabs li a');

        tabLinks.bind('click', function () {
            var oldTab = tabContainer.find('.' + SELECTEDCLASS);
            var oldContent = $(oldTab.find('a').attr('href'));

            var newTab = $(this.parentNode);
            var newContent = $($(this).attr('href'));

            if (oldTab.get(0) !== newTab.get(0)) {
                oldTab.removeClass(SELECTEDCLASS);
                newTab.addClass(SELECTEDCLASS);

                tabContainer.get(0).className = tabContainer.get(0).className.replace('tabs-bigger_' + oldContent.attr('id'), 'tabs-bigger_' + newContent.attr('id')); // Set a class on the tab container indicating which tab content should be shown. You'll need to add a selector to the following rule in the stylesheet to actually make the content visible:

                // body.js .tabs-bigger_destination-map .tab-content#destination-map,
                // body.js .tabs-bigger_destination-list .tab-content#destination-list {
                //     position: static;
                //}

                // This was the only way I could find to make the transition smooth.
            }


            return false;
        });
    });
}

var logInSlideDown = function () {
    var logInLink = $('.login-link');
    var logInBox = $('#navigation .panel-club');
    logInBox.addClass('club-login-topmenu-closed');

    var logInBoxCloseLink = $('<a href="#" title="Close login window" class="login-close-link">x</a>');

    var openLogInBox = function () {
        logInBox.slideDown();
        logInBox.removeClass('club-login-topmenu-closed');
        logInBox.addClass('club-login-topmenu-open');
    }

    var closeLogInBox = function () {
        logInBox.slideUp();
        logInBox.removeClass('club-login-topmenu-open');
        logInBox.addClass('club-login-topmenu-closed');
    }

    $(logInBoxCloseLink).bind('click', function () {
        closeLogInBox();
        return false;
    });
    logInBox.append(logInBoxCloseLink);

    $(logInLink).bind("click", function () {
        if (logInBox.is('.club-login-topmenu-closed')) {
            openLogInBox();
        }
        else {
            closeLogInBox();
        }
        return false;
    });

    if ($('.panel-club.club-login-topmenu').length) {
        openLogInBox(); // Open the log-in box if the server says we should (i.e. because there's a sign-in error the user needs to see).
    }
}

var worldmap = function () {
    var worldmap = $('#worldmap');
    var areas = $(worldmap.attr('usemap') + ' area')

    //alert(areas.length);

    areas.each(function () {
        var i = new Image(); // Good old image pre-loading trick
        i.src = '/images/slh/map-' + this.id.replace('worldmap-', '') + '.jpg';
        //alert(i.src);
    });

    areas.each(function () {
        $(this).bind('mouseover', function () {
            worldmap.get(0).src = '/images/slh/map-' + this.id.replace('worldmap-', '') + '.jpg';
        });
        $(this).bind('focus', function () {
            worldmap.get(0).src = '/images/slh/map-' + this.id.replace('worldmap-', '') + '.jpg';
        });
        $(this).bind('mouseout', function () {
            worldmap.get(0).src = '/images/slh/map-placeholder.jpg';
        });
    });
}

function specialOfferDescription() {
    function init() {
        var specialOfferDetails = $(this);

        var description = specialOfferDetails.find('.special-offer-description');
        var image = specialOfferDetails.find('img');
        var additionalLinks = specialOfferDetails.find('.additional-links');
        var truncateTextAt = 200; // Rough guess as to how many characters the paragraph can hold at its maximum height. It's dependent on font size, but the font would have to get pretty big to stop this working.

        if (image.length) {
            var imageHeight = image.height();
        }
        else {
            var imageHeight = 119;
        }

        // Max description height is:
        // - height of image (currently 119px)
        // - minus height of .additional-links
        // - minus .onecol top and bottom padding (currently 5px + 5px)
        var maxDescriptionHeight = imageHeight - additionalLinks.height() - 10;

        // Remove stylesheet's min-height declaration from description
        description.css({
            'min-height': '0'
        });

        var fullText = description.text();
        var truncateAt = fullText.lastIndexOf(' ', truncateTextAt);

        description.fcSpecialOfferFullText = fullText;
        description.fcSpecialOfferTruncatedText = fullText.slice(0, truncateAt) + ' ... ';

        var collapse = function () {
            description.addClass('special-offer-description-collapsed');
            description.removeClass('special-offer-description-expanded');

            description.text(description.fcSpecialOfferTruncatedText);

            description.css({
                'height': maxDescriptionHeight
            });

            description.append(moreHideLink);
        }

        var expand = function () {
            description.addClass('special-offer-description-expanded');
            description.removeClass('special-offer-description-collapsed');

            description.text(description.fcSpecialOfferFullText);

            description.css({
                'height': 'auto'
            });

            description.append(moreHideLink);
        }

        var moreHideLink = $('<a href="#" class="more-hide-link">More &gt;</a>');
        moreHideLink.bind('click', function () {
            var self = $(this);
            if (description.attr('class').indexOf('special-offer-description-collapsed') > -1) {
                expand();
                self.text('Close >');
            }

            else {
                collapse();
                self.text('More >');
            }
            return false;
        });

        if (description.height() > maxDescriptionHeight) {
            collapse();
        }
    }

    $('.special-offer-summary-details').each(init);
}

$.submenu = function () { }

$.submenu.init = function (target) {

    //initialise jquery objects
    var __$menuLink = target.find("a");
    var __$pointer = target.find(".pointer");
    var __$selected = target.find(".selected a");
    var __$first = target.find(".first a");
    var __$startPoint = "";

    __$selected.length > 0 ? __$startPoint = __$selected : __$startPoint = __$first

    __$menuLink.bind("mouseenter", function () {
        $.submenu.animateBG(target, $(this))
        __$pointer.show()
    })

    __$menuLink.bind("mouseleave", function () {
        $.submenu.animateBG(target, __$startPoint)
        __$selected.length > 0 ? __$pointer.show() : __$pointer.hide()

    })

    $.submenu.animateBG = function (target, childElement) {
        var x = ((childElement.position().left - target.position().left) + childElement.innerWidth() / 2) + 13
        __$pointer.stop();
        __$pointer.animate({
            "left": x
        })
    }

    $.submenu.animateBG(target, __$startPoint)
    __$selected.length > 0 ? __$pointer.show() : __$pointer.hide()
}


jQuery.fn.initAccordion = function () {

    return this.each(function () {

        $('.accordionInner', this).hide();
        $('.accordionInner:first', this).show();
        $('.accordionItem:first', this).addClass('on');

        $('.accordionItem h3 a', this).click(function () {
            if ($(this).parent().parent().hasClass('on')) {
                $(this).parent().parent().removeClass('on');
                $(this).parent().parent().find(".accordionInner").slideUp('normal');
            } else {
                $(this).parent().parent().siblings().removeClass('on');
                $(this).parent().parent().addClass('on');

                var checkElement = $(this).parents(".accordionItem").find(".accordionInner");
                $(this).parents(".accordion").find(".accordionInner:visible").slideUp('normal');
                checkElement.slideDown('normal');
            }
            return false;
        });
    });
};


var lowestRateToolitp =
{
    toolTipWrapper: null,
    toolTipInitLink: null,
    toolTipWindow: null,
    toolTipClose: null,
    init: function (toolTipSelector) {
        this.toolTipWrapper = $(toolTipSelector);
        this.toolTipClose = lowestRateToolitp.toolTipWrapper.find(".lowest-rate-close");
        this.toolTipInitLink = lowestRateToolitp.toolTipWrapper.find(".lowest-rate-ribbon");
        this.toolTipWindow = lowestRateToolitp.toolTipWrapper.find(".lowest-rate-tip");
        lowestRateToolitp.toolTipInitLink.bind("click", function (event) { event.preventDefault(); })
        lowestRateToolitp.toolTipClose.bind("click", function (event) { event.preventDefault(); })
        lowestRateToolitp.toolTipInitLink.bind("click", function (event) { lowestRateToolitp.openTooltip(lowestRateToolitp.toolTipWindow) });
        lowestRateToolitp.toolTipClose.bind("click", function (event) { lowestRateToolitp.hideTooltip(lowestRateToolitp.toolTipWindow) });
    },
    openTooltip: function (toolTipWindow) {
        toolTipWindow.show();
    },
    hideTooltip: function (toolTipWindow) {
        toolTipWindow.hide();
    }
};

// Show/hide
// A custom slide toggle animation is used so we can calculate the
// outer height (including margins) to prevent the animation from 'jumping'.
// Show/hide
// A custom slide toggle animation is used so we can calculate the
// outer height (including margins) to prevent the animation from 'jumping'.
function showHide(wrapper) {
    $(wrapper)
	.find('.show-hide')
	.each(function () {

	    var 
			anchor = $(this),
            showText = $.trim(anchor.text()),
            hideText = anchor[0].getAttribute('data-hide'),
			showHide = anchor.parent().next();

	    if ($.trim(showHide.text())) {

	        var height = showHide.show().outerHeight();

	        showHide.hide().height(0);

	        anchor.click(function (event) {

	            var hide = !showHide.is(':hidden');

	            anchor.toggleClass('icon-minus');

	            if (hide) {
	                anchor.text(showText);
	            } else if (hideText) {
	                anchor.text(hideText);
	            }

	            showHide
				.show()
				.animate({ "height": hide ? 0 : height }, 1000, function () {
				    if (hide) {
				        showHide.hide();
				    }
				});

	            return false;
	        });

	        // If the show/hide container has no text content then hide the 'Full details' anchor
	    } else {
	        anchor.hide();
	        anchor.parent().hide();
	    }
	});
}


function inlinePopup(wrapperSelector, anchorSelector) {

    var 
		wrapper = $(wrapperSelector),
		anchor = $(anchorSelector),
		close = wrapper.find('.close');

    anchor.click(function () {
        wrapper.show();
        return false;
    });
    close.click(function () {
        wrapper.hide();
        return false;
    });
}


if ($("#lowest-rate-guaranteed").length > 0) {
    lowestRateToolitp.init("#lowest-rate-guaranteed");
}

$(".accordion").initAccordion();

if ($("#destinations_hero").length > 0) {
    var __lozenge = $("#destinations_hero .lozenge");

    __lozenge.bind("mouseenter", function (e) {
        $(this).addClass('iehov');
    });

    __lozenge.bind("mouseleave", function (e) {
        $(this).removeClass('iehov');
    });
}

$.car = function () { }

$.car.globals = {
    target: $("#carousel"),
    currentSlide: 1,
    timer: "",
    data: {}
}

$.car.init = function (target, data) {
    if (!target.length || !data.length) { return false; }

    this.globals.target = target;
    this.globals.data = data;

    this.buildHTML();

    //button events
    target.find("#carousel-control li").click(function () {
        $.car.showSlide(this.innerHTML);
        var allButtons = $(this).parent("#carousel-control").find("li");
        $(allButtons).removeClass("active-button"); // remove active position 

        var buttonClass = $(this).attr("class"); // taking a slide position from classname
        var slideNum = buttonClass.split("slide-pos");
        slideNum = parseInt(slideNum[1]); // make it a number
        $.car.globals.currentSlide = slideNum; // setting clicked pos as current in queue
        $(this).addClass("active-button"); // making clicked position active
    });

    //?what was this one for?
    //target.find("#carousel-control span").click(this.autoAdvance);

    //Slide events

    target.click(function (e) {
        if (e.target.className == "slide") {
            if (e.target.parentNode.parentNode.parentNode.id == "carousel-v2") {
                window.location = $.car.globals.data[$.car.globals.currentSlide - 1].viewMoreLink;
            }
            else
                window.location = $.car.globals.data[$.car.globals.currentSlide - 1].hotelLink;
        }
    });

    target.find("p").click(function (e) {
        if (e.target.parentNode.parentNode.className == "slide") {
            if (e.target.parentNode.parentNode.parentNode.parentNode.parentNode.id == "carousel-v2") {
                window.location = $.car.globals.data[$.car.globals.currentSlide - 1].viewMoreLink;
            }
            else
                window.location = $.car.globals.data[$.car.globals.currentSlide - 1].hotelLink;
        }
    });

    //target events
    target.mouseout(this.startTimer);
    target.mouseover(this.stopTimer);


    //Let's go!, hide all slide hard, show slide 1, remove backup img and start auto advance.

    if (!$.support.opacity) {
        $("#carousel-slides > div").hide();
    } else {
        $("#carousel-slides > div").css("opacity", 0);
    }


    this.showSlide(this.globals.currentSlide);
    this.globals.target.css("background", "#fff");
    this.startTimer();

}

$.car.buildHTML = function () {
    var slideHTML = "";
    var buttonHTML = "";
    for (var i in this.globals.data) {

        slideHTML += buildSlide(data[i], i);
        if (data.length > 1) {
            buttonHTML += buildButton(i);
        }
    }

    this.globals.target.html('<div id="carousel-slides">' + slideHTML + '</div><ul id="carousel-control">' + buttonHTML + '</ul>');



    function buildSlide(d, i) {

        var slideHTML = '<div class="slide" style="background-image:url(' + escape(d.img) + ');">';
        slideHTML += '<div class="slide-info">';

        if (d.hotelLink != "") {
            slideHTML += '<p class="title"><a href="' + d.hotelLink + '">' + d.hotelName + '</a></p>';
        } else {
            slideHTML += '<p class="title">' + d.hotelName + '</p>';
        }
        slideHTML += '<p>' + d.strapline + '</p>';

        /*if (d.viewMoreLink != ""){
        slideHTML += '<a href="'+ d.viewMoreLink +'" title="'+ d.viewMoreTitleText +'" class="view-more">'+ d.viewMoreLinkText +'</a>'; 
        }*/
        if (d.hotelLink != "") {
            slideHTML += '<a href="' + d.hotelLink + '" title="' + d.hotelTitleText + '" class="view-this-hotel">' + d.hotelLinkText + '</a>';
        }
        slideHTML += '</div></div>';
        return slideHTML;
    }

    function buildButton(i) {
        i++;
        return '<li class="slide-pos' + i + '">' + i + '</li>';
    }
}

$.car.startTimer = function () {
    $.car.globals.timer = window.setInterval($.car.autoAdvance, 5000)
};

$.car.stopTimer = function () {
    window.clearInterval($.car.globals.timer)
};

$.car.autoAdvance = function () {
    $.car.showSlide($.car.globals.currentSlide += 1)
};

$.car.showSlide = function showSlide(i) {
    if (i > this.globals.data.length) { i = 1 }

    $("#carousel-control li").removeClass("active-button");
    $("#carousel-control li.slide-pos" + i).addClass("active-button"); // setting active position highlighted

    if (!$.support.opacity) {
        $("#carousel-slides > div").hide();
        $("#carousel-slides > div:eq(" + (i - 1) + ")").show();

    } else {
        $("#carousel-slides > div").stop().animate({ "opacity": 0 }, "slow", function () {
            $(this).hide();
        });
        $("#carousel-slides > div:eq(" + (i - 1) + ")").stop().show().animate({ "opacity": 1 }, 1000);
    }

    this.globals.currentSlide = i;
};
/* Hero carousel */
var _$carousel = $("#carousel")
if (_$carousel.length > 0 && typeof data != "undefined") {
    $.car.init(_$carousel, data);
}

/* Hotel overview and review pages show/hide */
showHide('#content-inner');

/* Hotel review mystery tips inline popup */
inlinePopup('#mystery-popup-wrapper', '#mystery-tips-anchor');

//colorbox declarations - open modal window for booking system details
var callColorbox = function (target, colorboxHref) {

    target.colorbox({
        href: colorboxHref,
        iframe: true,
        height: 475,
        width: 650
    });
}
var $modalLink = $(".modalLink");
var $modalSubmit = $(".modalSubmit");
var $galleryItem = $(".colorboxGallery");


$modalLink.bind("click", function (e) {
    var colorboxHref;
    if (this.tagName === 'A') {
        colorboxHref = this.href;
        callColorbox($(this), colorboxHref)
    }
    if (this.tagName === 'IMG') {
        colorboxHref = this.parentNode.href;
        callColorbox($(this), colorboxHref)
    }
    e.preventDefault();
});

$modalSubmit.bind("click", function (e) {

    var target = $(e.target);
    var colorboxHref = target.attr('rel');
    target.colorbox({
        href: colorboxHref, iframe: true, height: 475, width: 650
    });
    e.preventDefault(); //do I need to prevent the submission of the form?
});

// controls gallery lightbox for club - logged in landing page
$galleryItem.bind("click", function (e) {
    var target = $(e.target);
    var colorboxHref = target.attr('href');
    var colorboxTitle = target.attr('title');
    target.colorbox({
        href: colorboxHref, title: colorboxTitle
    });
    e.preventDefault();
});

    
if ($("#masthead-gallery").length > 0) { hotelGallery(); window.setTimeout(function () { correctImageDimensions() }, 500); }
if ($("ol.reasons").length) { clubReasons(); };
if ($('.gallery-inner .thumb a').length) {
    showImage();
    scroller();
    prevNext();
    gallerySlideShow();
    //var $imageURLs = getURLs();	
};
if ($('.club-member').length) {
    FC.showLogin();
} else {
    if ($(FC.vars.selectors.FINDAHOTEL).length || $(FC.vars.selectors.BOOKINGFORM).length) {
        $(".bottom-border").hide();
        $("#sub-navigation").css("height", "236px")
    }
};
if ($('#panel-recommended-destinations').length) { showRecommendedDestinations(); }
if ($('.tabs-bigger-js').length) { tabs(); }
if ($('.login-link').length) { logInSlideDown(); }
if ($('#worldmap').length) { worldmap(); }
if ($('div.logged-home li.selected').length) { clubHomeLoggedIn(); }
if ($('.special-offer-summary-details').length) { specialOfferDescription() };
if ($("#sm").length) { $.submenu.init($("#sm")); }
if ($("#destinations_hero").length) {
    $.destSwitcher.initialize($("#destinations_hero"));
    $("#destinations_hero").css("background", "#000");
    $("#destinations_hero .back").click(function (e) {
        $.destSwitcher.showSlide("dest_world");
    })
}




