﻿var imagesLength = 0;
var slideShowXmlUrl = null;
var pageTracker;

$(document).ready(function() {

    if(pageTracker==undefined)
    {    
        // Stub pageTracker object so that the temporary PageTracker Google Analytics 
        // calls can be put back in place easily
        pageTracker = new Object();
        pageTracker._trackEvent = function(a, b, c) { return true; };
    }

    /* Set relevant body class based on time of day */
    /*if (IsMorning()) {
        $("body").attr("class", "morning");
    }
    else if (IsAfternoon()) {
        $("body").attr("class", "afternoon");
    }
    else {
        $("body").attr("class", "evening");
    }*/

    $("#showHide").attr("id", 'Template_showHide');
    $("#showText").attr("id", 'Template_showText');
    $("#showImages").attr("id", 'Template_showImages');
    $("#slidingContent").attr("id", 'Template_slidingContent');
    $("#slidingImage").attr("id", 'Template_slidingImage');

    $("a[href$='system_pages/nav_bars/header/gift_vouchers.aspx']").click(
        function() {
            urchinTracker('skchase-site');
        });

    $("a[href$='food__whisky/restaurant/reservations.aspx']").click(
        function() {
            urchinTracker('opentable-site')
        });

    $("form").submit(function() { __utmLinkPost(this); });
    
    SetupPopups();
    SetupContentSlide();
    SetupExpandingForms();
    FixSearchResultsForm();
    FixMultipleZIndexes();
    UseLabelInputs();

    if (!IsInImmediacyEditor()) {
        $("select").selectbox();
    }

    if (!IsInImmediacyEditor() && slideShowXmlUrl != null) {
        SetupImageGallery();
    }

    $("#gallery a").each(function() {
        var newHref = $(this).children("img").attr("src");
        if (newHref != undefined && newHref.indexOf("width=190") > -1 && newHref.indexOf("height=136") > -1) {
            newHref = newHref.replace("width=190", "width=800").replace("height=136", "height=500");
        }
        $(this).attr("href", newHref);
    });

    $(".removeByScript").addClass("remove");
    /* $(".showByScript").css("display", "block") - changed by Jamie Stewart this is due to an IE6 double margin bug when using floats and margins */
    $(".showByScript").removeClass("showByScript");

    $("#footerContent").addClass("jsEnabled");

    if (!IsInImmediacyEditor()) {
        if ($("#gallery a").length > 0) {
            $("#gallery a").lightBox({
                overlayBgColor: '#B2A276',
                overlayOpacity: 0.6
            });
        }

        var today = new Date();

        $("input.datePickerBox").datepicker({
            showOn: 'button',
            buttonImage: basePath + 'build_images/calendar.png',
            buttonImageOnly: true,
            dateFormat: 'd MM yy',
            buttonText: 'Click to open calendar pop-up',
            changeMonth: true,
            changeYear: true,
            yearRange: (new Date().getFullYear()) + ':' + (new Date().getFullYear() + 4)
        });

        $("input.datePickerBox").attr("readonly", true);
    }

});

function IsMorning()
{
    var currHour = new Date().getHours();
    return currHour>=5 && currHour < 12;
}

function IsAfternoon()
{
    var currHour = new Date().getHours();
    return currHour>=12 && currHour < 18;
}

function IsNight()
{
    return !IsMorning() && !IsAfternoon();
}

function SetupContentSlide() {
    $("#Template_showText a").click(
        function() {
            ToggleDisplay("Text", 1000);
            return false;
        });
//    $("#leftNavSwishyParentListItem a#leftNavSwishyParentListLink").click(
//        function() {
//            return false;
//        });    
//    $("#leftNavSwishyListItem a").click(
//        function() {
//            ToggleDisplay("Text", 1000);
//            return false;
//        }); 
}

function ToggleDisplay(displayType, duration) {

    if (displayType == "Text") {
        $("#prevNext").hide(); // Remove previous and next options for images
        
        //$("#leftNavSwishyListItem").addClass("selected");
        
        $("#Template_slidingImage").animate({ marginRight: "-510px" }, duration);
        $("#Template_showHide").animate({ left: "532px" }, duration, "", function() {

            $("#Template_slidingContent").css("display", "inline");
            $("#Template_showHide a").unbind();
            try {
                var colour = $("#content h1").css("color");

                if (colour.indexOf("rgb") > -1) {
                    colours = colour.replace("rgb(", "").replace(")","").split(",");
                    colour = rgbToHex(colours[0],colours[1],colours[2]);
                }
                sIFR.replace(gillsans, {
                    selector: '#content h1',
                    css: [
                            '.sIFR-root { text-transform:none;color: #00695B; background-color: #ffffff; }'
                         ]
                });
            }
            catch (exception) { }

            $("#Template_showImages a").click(
            function() {
                ToggleDisplay("Images", 1000);
                return false;
            });

//            $("#leftNavSwishyParentListItem a#leftNavSwishyParentListLink").unbind();
//            $("#leftNavSwishyParentListItem a#leftNavSwishyParentListLink").click(
//            function() {
//                ToggleDisplay("Images", 1000);
//                return false;
//            });

//            $("#leftNavSwishyListItem a").unbind();
//            $("#leftNavSwishyListItem a").click(
//            function() {
//                return false;
//            });
        });
        $("#Template_showText").hide();
        $("#Template_showImages").show();

        if (IsInImmediacyEditor()) {
            $("#mtaslideimagetext").height(430);
        }
    }
    else {
    
        //$("#leftNavSwishyListItem").removeClass("selected");
        //$("#leftNavSwishyParentListItem").addClass("selected");
        
        $("#Template_slidingContent").fadeOut("slow", function() {
            $("#Template_slidingImage").animate({ marginRight: "0" }, duration, function() { if (imagesLength > 0) { $("#prevNext").fadeIn(); } });
            $("#Template_showHide").animate({ left: "22px" }, duration);
            $("#Template_showText").show();
            $("#Template_showImages").hide();
        });

        $("#Template_showText a").click(
        function() {
            ToggleDisplay("Text", 1000);
            return false;
        });
        
//        $("#leftNavSwishyParentListItem a#leftNavSwishyParentListLink").unbind();
//        $("#leftNavSwishyParentListItem a#leftNavSwishyParentListLink").click(
//        function() {
//            return false;
//        }); 
//        
//        $("#leftNavSwishyListItem a").unbind();
//        $("#leftNavSwishyListItem a").click(
//        function() {
//            ToggleDisplay("Text", 1000);
//            return false;
//        });  
        
        
    }

}

/* Converts rgb to hex if required */
function rgbToHex(R, G, B) { return toHex(R) + toHex(G) + toHex(B) }
function toHex(N) {
    if (N == null) return "00";
    N = parseInt(N); if (N == 0 || isNaN(N)) return "00";
    N = Math.max(0, N); N = Math.min(N, 255); N = Math.round(N);
    return "0123456789ABCDEF".charAt((N - N % 16) / 16)
      + "0123456789ABCDEF".charAt(N % 16);
}

function SetupImageGallery() {

    $("#prevNext a").hover(function() {
        var source = $(this).children("img").attr("src");
        var newSource = source.replace(".png", "_hov.png");
        $(this).children("img").attr("src", newSource)
    },
    function() {
        var source = $(this).children("img").attr("src");
        var newSource = source.replace("_hov.png", ".png");
        $(this).children("img").attr("src", newSource)
    });

    $.ajax({
        type: "GET",
        url: slideShowXmlUrl,
        dataType: "xml",
        success: function(xml) {
            var imageElements = $(xml).find("img");
            imagesLength = imageElements.length;
            var imageGenPath = $(".galleryImages img.current").attr("src").toLowerCase();

            imageGenPath = imageGenPath.substring(0, imageGenPath.lastIndexOf("&image="));

            imageElements.each(function(i) {
                var image = $("<img/>");
                image.attr("src", imageGenPath + "&image=" + $(imageElements[i]).attr("src"));
                image.attr("alt", $(imageElements[i]).attr("alt"));
                image.attr("index", i);
                image.css("display", "none");
                $("#mainSlidingImage").append(image);
            });

            SetupPreviousNext(0);
        }
    })

}

function SetupPreviousNext(currentIndex) {
    $("#prevNext .info .lowercase").text((currentIndex + 1) + " of " + imagesLength);
    $("#prevNext a").attr("currentIndex", currentIndex);
    // If no images or one image don't show the previous and next;
    if (imagesLength == 0 || imagesLength == 1) {
        $("#prevNext").hide();
    }
    else {
        $("#next a").click(function() {
            $("#prevNext a").unbind("click");
            var nextIndex = parseInt($(this).attr("currentIndex")) + 1;
            if (nextIndex > (imagesLength - 1)) { nextIndex = 0; } // if the next index takes us by the range start from 0
            IncrementImageGallery(nextIndex)
            SetupPreviousNext(nextIndex)
            return false;
        });
        $("#previous a").click(function() {
            $("#prevNext a").unbind("click");
            var prevIndex = parseInt($(this).attr("currentIndex")) - 1;
            if (prevIndex < 0) { prevIndex = (imagesLength - 1); } // if the next index takes us by the range start from 0
            IncrementImageGallery(prevIndex)
            SetupPreviousNext(prevIndex)
            return false;
        });

    }
    
    try{ BuildIEPager(); }
    catch(error){}
}

function IncrementImageGallery(index) {
    if (index <= imagesLength) {
        var bedroomImage = $(".galleryImages .current");
        bedroomImage.parent().css("height", bedroomImage.height() + "px");
        bedroomImage.fadeOut("fast", function() {
            bedroomImage.removeClass("current");
            var newImage = $(".galleryImages img[index='" + index + "']");
            newImage.addClass("current");
            newImage.fadeIn("fast");
        });
    }
}

function IsInImmediacyEditor() {
    return top.Support;
}

/* Required by the Immediacy Search Plugin */
function clearText(textBoxId, defaultText) {
    textbox = document.getElementById(textBoxId);

    if (textbox != null) {
        if (textbox.value == defaultText) {
            textbox.value = '';
        }
        else if (textbox.value == '') {
            textbox.value = defaultText;
        }
    }
}

function SetupPopups() {

    var popupClone = $("div.popup").clone();
    $("div.popup").remove();
    $('<div id="popupOverlay"/>').appendTo($("body"));
    popupClone.appendTo($("body"));

    for (var ii = 0; ii < popupClone.length; ii++) {
        var clone = $(popupClone[ii]);
        if (clone.attr("class").indexOf("contentPopup") > -1) {
            clone.wrap('<div id="popupContainer" class="contentPopup"/>');
        }
        else {
            clone.wrap('<div id="popupContainer"/>');
        }
    }


    $("a.popup").click(function() {

    $("#subNav h3.sIFR-replaced,#Template_slidingContent h1").css("visibility", "hidden");
        // Setup the overlay
        var height = $(document).height();
        var width = $(document).width();
        $('#popupOverlay').css({
            backgroundColor: "#B2A276",
            opacity: 0.6,
            height: height,
            width: width,
            display: "block"

        })

        var popupId = $(this).attr("href");

        var popup = $(popupId).show(); // The main container
        var height = $(popupId + " .popupContent").height(); // The contents width (Set through CSS)
        var width = $(popupId + " .popupContent").width() + 10; // The contents width (Set through CSS) + 10 is there to generate space for the shadow
                    
        if (IsInImmediacyEditor()) {
            popup.animate({ width: width, height: height }, "fast", function() {
                $(popupId + " .popupContent").fadeIn("fast", function() {
                    $("#mtapreviewa").height(420);
                    $("#mtapreviewb").height(210);
                    $("#mtapreviewc").height(370);
                    $("#mtapreviewd").height(300);
                });
            });
        }
        else {
            // Animate the container to be the width first then height of the content inside
            popup.animate({ width: width, height: height }, 1200, function() {
                $(popupId + " .popupContent").fadeIn("fast", function() {
                           
                    if($("#mainImage img")!=undefined)
                    {
                        $(".col_345").show();
                        $(".col_446fl").show();
                        $("#mainImage img").attr("src", basePath+"build_images/white.gif");
                        $("#mainImage").hide();
                    }
                                 
                    // Now show the bottom shadow, trying to show it at all times made it look messy
                    $(popupId + " .shadowBottom").removeClass("remove");
                    $(popupId + " .close").removeClass("remove");
                    // We only want it solid when animating this reduces the requirement for more divs
                    $(this).parent().css("background-color", "transparent");
                    // Now add the right shadow, for the same reason as the bottom shadow
                    $(this).parent().addClass("shadowRight");
                    
                    // Specify sIFR again because it has to be done when text is visible (Birds eye view)
                    sIFR.replace(bodoni,
                        { selector: '#homePopup h2',
                            css: ['.sIFR-root { text-transform:none;color: #00695B; }'],
                            wmode: 'transparent'
                        });

                    // Specify sIFR again because it has to be done when text is visible (content popup)
                    sIFR.replace(bodoni,
                    { selector: '.contentPopup h3',
                        css: ['.sIFR-root { color: #ffffff; }'],
                        wmode: 'transparent'
                    });

                    // Specify sIFR again because it has to be done when text is visible (content popup)
                    sIFR.replace(bodoni,
                    { selector: '.popup h1,.popup h2,.popup h3',
                        css: ['.sIFR-root { color: #00695B;text-transform:none; }'],
                        wmode: 'transparent'
                    });
                });
            });
            return false;
        }
    });
    
    SetupPopupClose();

    if ($(".popupContent a[class!='close']").length > 0) {
        SetupDetailsLinks();
    }
}

function SetupPopupClose() {
    $(".close").click(function() {
    $("#subNav h3.sIFR-replaced,#Template_slidingContent h1").css("visibility", "visible");
    $("div.popup .shadowBottom").addClass("remove");
    $("div.popup").removeClass("shadowRight");
    var contentBg = $(".popupContent").css("background-color");
    $("div.popup").css("background-color", contentBg);
    $("#popupOverlay").hide();

    if($("#mainImage img")!=undefined)
    {
        $(".col_345").show();
        $(".col_446fl").show();
        $("#mainImage img").attr("src", basePath+"build_images/white.gif");
        $("#mainImage").hide();
    }
    
    $("div.popupContent").fadeOut("slow", function() { 
        $("div.popup").animate({ height: 0, width: 0 }, 1200); });        
        return false;
    });
}

function SetupDetailsLinks() {
    var detailLinks = $(".popupContent a[class!='close'][href][href!='#']");
    var imageSrcs;

    for (var ii = 0; ii < detailLinks.length; ii++) {
        if (!$(detailLinks[ii]).children("img").length > 0) {
            var imageId = $(detailLinks[ii]).attr("href");
            var hashIndex = imageId.indexOf("#");
            imageId = imageId.substring(hashIndex, imageId.length);
            if (imageId.length > 1) {
                var src = $(imageId.toString()).attr("src");
                if(src!=undefined)
                {
                    if (src.indexOf("&") > -1) {
                        src = src.substring(0, src.indexOf("&")) + "&width=920&height=510&constraint=true&pad=true";
                 
                    }
                    if (src && ii + 1 != detailLinks.length) {
                        imageSrcs += src + ",";
                    }
                    else if (src) {
                        imageSrcs += src;
                    }
                }
            }
        }
    }
    
    $.preloadImages(imageSrcs);

    detailLinks.click(function() {
        var imageId = $(this).attr("href");
        var hashIndex = imageId.indexOf("#");
        if (hashIndex > -1) {
            imageId = imageId.substring(hashIndex, imageId.length);
            var src = $("img" + imageId).attr("src");
            var imageTitle = $(this).attr("rel");

            if (src!=undefined && src.indexOf("&") > -1) {
                src = src.substring(0, src.indexOf("&")) + "&width=920&height=510&constraint=true&pad=true";
            }
            $("#mainImage img").attr("src", src);
            $("#mainImage img").ready(function() {
                $("#mainImage p[id!='backToGallery']").text(imageTitle);
                $(".col_345").hide();
                $(".col_446fl").hide();
                $("#mainImage").show();
            });

            return false;
        }
    });
    
    $("#backToGallery a").unbind("click");
    $("#backToGallery a").click(function() {
        $(".col_345").show();
        $(".col_446fl").show();
        $("#mainImage img").attr("src", basePath+"build_images/white.gif");
        $("#mainImage").hide();
        return false;
    });
}

jQuery.preloadImages = function() {
    arguments = arguments[0].split(",");
    for (var i = 0; i < arguments.length; i++) {
        jQuery("<img>").attr("src", arguments[i]);
    }
}

function SetupExpandingForms() {

    $("#reservationForm fieldset#details").show();
    $("#reservationForm fieldset#availability").show();
    $("#reservationForm fieldset#restaurant").hide();
    $("#reservationForm fieldset#spa").hide();
    $(".spa fieldset#spa").show(); // This is required for the Spa reservation
    $("#reservationForm fieldset#concierge").hide();
    $("#reservationForm fieldset#additional").hide();

    // Iterate through all cookies, finding ones that are form region persistance details
    // then extract the relevant regionName from the cookie and set its CSS display from the cookie's value
    $.each(document.cookie.split(';'), function(i, cookie) {
        var cookieNameValuePair = $.trim(cookie).split('=');
        if (cookieNameValuePair[0].indexOf('bespokeReservationForm_') == 0) {
            var regionName = cookieNameValuePair[0].substring(23); // extract XYZ from bespokeReservationForm_XYZ
            $("#reservationForm fieldset#" + regionName).css("display", cookieNameValuePair[1]);
        }
    });

    $("#reservationForm h2 a.collapsible").click(function() {
        var idSelect = $(this).attr("href");
        $(idSelect).slideToggle("slow", function() {
            var displayValue = $(idSelect).css("display");
            $.cookie("bespokeReservationForm" + idSelect.replace('#', '_'), displayValue);
        });

        /* This is required because the initial call to .selectbox() can't get to the select's width in a collapsed state
        so we have to reset that width here */
        $(idSelect + " .selectbox-wrapper").each(function() {
            var selectWidth = parseInt($(this).parent().width()) + 2 ; // Required to compensate for borders
            $(this).css("width", selectWidth + "px");
        });
        return false;
    });

    $("#reservationForm h2 a.nocollapse").click(function() {
        return false;
    });
}

function FixSearchResultsForm() {
    $(".results tr td[colspan='2']").addClass("fixIndex");
}

function UseLabelInputs() {
    var labels = $(".useLabel");
    labels.hide();

    labels.each(function(i) {
        var inputId = $(labels[i]).attr("for");
        var input = $("#" + inputId);
        input.val($(labels[i]).text());
        input
        .click(function() { $(this).val(""); })
        .focus(function() { $(this).val(""); })
        .blur(function() {
            var labelFor = $(this).attr("id");
            var labelText = $("label[for='" + labelFor + "']").text();
            $(this).val(labelText);

        });
    });
}

function FixMultipleZIndexes() {
    var fixZindexElements = $("div.formRow.fixZIndex");
    for (var ii = 0; ii <= fixZindexElements.length; ii++) {
        zIndexElement = $(fixZindexElements[ii]);
        zIndexElement.removeClass("fixZIndex");
        zIndexElement.addClass("fixZIndex"+(ii+1));
    }
    
}
