/**
customised javascript
**/

var mouseOverSlider = false;

$(document).ready(function() {


    Cufon.replace('.mainNav li a, .features .description h3, .subNav p.title, .homepage .featureContent .intro h3', { hover: true });

    //add css to include when js enabled
    if (!($.browser.opera)) {
        $("link[href$='dummy.css']").attr('href', '/templates/default/css/system/dynamic.css');
    } else {
        loadCSS('/templates/default/css/system/dynamic.css');
    }


    //auto fill search field
    autoFill($("fieldset.searchForm .Search, .exploreForm input.Search"), "Site search");

    //new window
    $('a.newWindow, a.fullscreen').click(function() {
        window.open($(this).attr('href'), this, 'width=700,height=500');
        return false;
    });

    //accordion menu
    initMenu();
    //tooltip
    tooltip();


    /* ---------------
    Calendar page
    ----------------- */
    if ($("body.calendar").length) {
        $(".exhibitions li").hide();

        $("li[id^='event']")
        .jqm({
            overlay: 0,
            trigger: false
        })
        .jqmAddClose(".exhibitions h3")
        .jqmAddClose("table.calendar td")
        .append('<span class="close" href="">Close</span>')
        .jqmAddClose(".calendar .close")
        .parents("ul").addClass("open");

        $("td.on a").click(function(e) {
            if ($(this).parent("p").hasClass("link")) {

                $("li[id^='event']")
                .jqm({
                    overlay: 0,
                    trigger: false
                })

                var y = e.pageY - this.offsetTop - 70;

                exhibition = $(this).attr("href");
                if (exhibition.indexOf("http://") != -1) {
                    exhibition = "#" + exhibition.split("#")[1];
                }
                $(exhibition).jqmShow();

                $("ul.exhibitions").css("top", y).css("left", "255px");
                $(".calendar .open li").hide();
                $("ul.exhibitions li." + exhibition + "").show();
                //alternative for ie 6 where offset does not work

                if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
                    var container = $(this).parent("tr").children("td");
                    var pos = $(container).index($(this)) * 36 + $(container).index($(this)) + 1;
                    var offset = $("ul.exhibitions").css("left", pos);
                }
                return false;
            }
        });

        //reactivate links in calendar
        $("td.on h3 a").click(function() {
            linki = $(this).attr("href");
            window.location.href = linki;
        });

        //make whole banner clickable
        clickThrough($("table.calendar tr.exhibitions td.on"), "h3 a");
        clickThrough($("table.calendar tr.collections td.on"), "h3 a");

        $(function() {
            $('.date-pick')
            .datePicker({
                createButton: false,
                selectWeek: true,
                closeOnSelect: true,
                startDate: '01/01/1996'

            })
            .bind(
                'click',
                function() {
                    var queryStringValue = document.location.search.substring(document.location.search.indexOf('=') + 1);
                    var chosenMonth = queryStringValue.substr(4, 2);
                    var chosenYear = queryStringValue.substr(0, 4);
                    if (queryStringValue == "") {
                        $(this).dpDisplay();
                    } else {
                        $(this).dpSetDisplayedMonth(chosenMonth - 1, chosenYear).dpDisplay();
                    }
                    this.blur();
                    return false;
                })
            .bind(
                'dateSelected',
                function(e, selectedDate, $td) {
                    Date.format = 'yyyymmdd';
                    var url = '?start=' + selectedDate.asString();
                    window.location.href = url;
                });
        });



        //additional styling
        $("tr.events:last td, tr.tours:last td, tr.exhibitions:last td").css("borderBottom", "2px solid #000");

    } //end calendar page


    /* ---------------
    home page
    ----------------- */

    if ($("body.homepage").length) {

        //add scrollbar to stop jumps in transitions
        $("html").addClass("scroll");

        /* accordion for homepage */
        $('#accordion h2 a').click(function() {
            var link = false;
            link = $(this).attr('href');


            if (!$(this).parent().hasClass('selected')) {

                //slideUp selected
                if ($(this).parent().prevAll('div.featureContent').is(":visible")) {
                    //alert("slideup");
                    lastActive = $("div.selected").slideUp(1000);

                    //slideDown selected
                } else {
                    //alert("slidedown");
                    lastActive = $("div.selected").slideUp(1000);
                }

                $(lastActive).prev("h2").removeClass("selected");
                $(lastActive).removeClass("selected");
                $(this).parent().next('div').slideDown(1000);
                $(this).parent().addClass("selected");
                setTimeout(function() {

                    $(this).parent().next("div").addClass("selected");

                }
                , 1000);


                setTimeout(function() {
                    $(".featureContent").fadeTo(0, 1000);
                }
                , 100);
                setTimeout(function() {
                    window.location.href = link;
                }, 1500);


            }
            else {
                window.location.href = link;
            }

            return false;

        }); //end accordion






        //target ie
        if ($.browser.msie) {
            $('.featureContent li').css("background", "#fff");
            $('.featureContent li').css("opacity", "0");
            $('.featureContent li').animate({
                opacity: 1
            }, 1000);

        } else {
            $('.featureContent').fadeTo(1, 0);
            $('.featureContent').fadeTo(1000, 1);
        }


        /* slide up */

        $(".box:not('.wide')").mouseenter(
            function() {
                $.overBox = true;
                $.thisBox = $(this).children("div");
                setTimeout(
                    function() {
                        if ($.overBox == true) {

                            $.thisBox.find("p").slideDown("slow");
                        }
                    }
                    , 500);
            });
        $(".box:not('.wide')").mouseleave(
            function() {
                $.overBox = false;
                $.thisBox.find("p").slideUp("slow");
                $.thisBox = "";

            });



        /* slideshow */
            $(".selected #mycarousel, .selected #mycarousel2, #accordion div.visitFeature ul").wrap('<div id="carousel"></div>');
            $(".selected #mycarousel, .selected #mycarousel2, #accordion div.visitFeature ul").wrap('<div id="carouselInner"></div>');
        $("#carouselInner").after('<span class="previous">Previous</span><span class="next">Next</span>');
        if ($('.homepage #carouselInner').size()) {
            $('.homepage .mainFeature #carouselInner').carousel('.previous', '.next', true);
            $('.homepage .visitFeature #carouselInner').carousel('.previous', '.next', false);
            $('.homepage .exploreFeature #carouselInner').carousel('.previous', '.next', false);
        }
      

        //The auto-scrolling function
        function slide() {
            $('.next').click();
        }
        //Launch the scroll every 2 seconds
        //var intervalId = window.setInterval(slide, 5000);
        //On user hover deactivate auto-scrolling
        $('.featureContent').mouseenter(function() {
            mouseOverSlider = true;
            //window.clearInterval(intervalId);
        }
        );
        $('.featureContent').mouseleave(function() {
            mouseOverSlider = false;
            //intervalId = setInterval(slide, 5000);
        });


    } //end homepage functions


    /* ---------------
    related links
    ----------------- */


    $(".commentForm h2.open, .relatedLinks h2.open, .calendar .category h3.open, .userComment h2.open, ul.sitemap li a.open span").live("click", function() {
        $(this).next("ul,div").slideUp();
        $(this).parent("a").next("ul").slideUp("slow");
        $(this).removeClass("open");
        $(this).parent("a").removeClass("open").addClass("close");
        $(this).addClass("close");
        // create reverse z-indexing for styles
        var container = $("ul.sitemap > li a");
        var pos = $(container).index($(this).parent("a"));
        $(this).parent("a").css("z-index", 10 - pos);
        return false;
    });


    $(".commentForm h2.close, .relatedLinks h2.close, .calendar .category h3.close, .userComment h2.close, ul.sitemap li a.close span").live("click", function() {
        $(this).next("ul,div").slideDown();
        $(this).parent("a").next("ul").slideDown("slow");
        $(this).addClass("open").removeClass("close");
        $(this).parent("a").addClass("open").removeClass("close");
        return false;
    });


    //make whole box clickable
    $(".mainFeature .featureImage img").click(function() {
        var linki = $(this).parent().find(".readMore a:first").attr('href');
        window.location.href = linki;
    });


    //style last in list
    $(".centreCol h2:last, ul.sitemap li a.section:last").addClass("last");

    /* slideshow */
    $(".relatedLinks .carousel").wrap('<div id="spotCarousel"></div>');
    $(".relatedLinks .carousel").wrap('<div id="spotCarouselInner"></div>');
    $("#spotCarouselInner").after('<div class="buttons"><span class="previous">Previous</span><span class="next">Next</span></div>');
    if ($('.relatedLinks #spotCarouselInner').size()) {
        $('.relatedLinks #spotCarouselInner').carousel('.relatedLinks .previous', '.relatedLinks .next');
    }

    //Launch the scroll every 2 seconds
    var intervalId = window.setInterval(function() { $('.relatedLinks .buttons .next').click(); }, 5000);
    //On user hover deactivate auto-scrolling
    $('.relatedLinks #spotCarousel').mouseenter(
        function() {
            mouseOverSlider = true;
            //window.clearInterval(intervalId);
        }
	);
    $('.relatedLinks #spotCarousel').mouseleave(
		function() {
		    mouseOverSlider = false;
		    //intervalId = setInterval(slide, 5000);
		}
	);
    /* ---------------
    explore page
    ----------------- */
    if ($("body.explore, .exploreHome").length) {

        //carousel
        if ($(".grid").length) {
            $("#mycarousel").wrap('<div id="exploreCarousel"></div>');
            $("#mycarousel").wrap('<div id="exploreCarouselInner"></div>');
            $('#exploreCarouselInner').carousel('.grid .previous', '.grid .next');
            $('.grid .previous, .grid .next').click(
                function() {
                    return false;
                }
            );
        }

        /* slide up */
        $(".box:not('.wide')").mouseenter(
            function() {
                $.overBox = true;
                $.thisBox = $(this).children("div");
                setTimeout(
                    function() {
                        if ($.overBox == true) {
                            $.thisBox.find("p").slideDown("slow");
                        }
                    }
                    , 500);
            });
        $(".box:not('.wide')").mouseleave(
            function() {
                $.overBox = false;
                $.thisBox.find("p").slideUp("slow");
                $.thisBox = "";

            });


        //make whole box clickable
        clickThrough($(".grid .box"), "a");


    }

    /* ---------------
    gallery page
    ----------------- */
    if ($(".galleryContainer, .galleryVideo,  .galleryInteractive").length) {

        /* slideshow */
        if ($(".galleryThumbnails .thumb").length > 7) {

            $(".slideshow").wrap('<div id="galleryCarousel"></div>');
            $(".slideshow").wrap('<div id="galleryCarouselInner"></div>');
            $("#galleryCarouselInner").after('<span class="previous">Previous</span><span class="next">Next</span>');
            $('.galleryThumbnails #galleryCarouselInner').carousel('.galleryThumbnails span.previous', '.galleryThumbnails span.next');
            $('span.previous, span.next').click(
                function() {
                    return false;
                }
            );

        }

        //thumbnails
        $(".galleryContainer .close,.galleryVideo .close").toggle(
            function() {
                $("div.caption").slideUp("slow");
                $(this).html("Show full description");
                $(this).removeClass("close");
                $.cookie("galleryDescDefault", "hide", { expires: 1 });
            },
            function() {
                $("div.caption").slideDown("slow");
                $(this).html("Hide full description");
                $(this).addClass("close");
                $.cookie("galleryDescDefault", "show", { expires: 1 });
            }
        );

        // this sets the default behaviour 
        // of the description panel
        setDescriptionDisplay();

        $(".galleryContainer").mouseenter(
            function() {
                $(".previous,.next").removeClass("js_hide");
            });
        $(".galleryContainer").mouseleave(
            function() {
                $(".previous,.next").addClass("js_hide");
            }
        );

    } //end gallery page/video page


    /* ---------------
    ie6 only functions
    ----------------- */
    if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
        $("#galleryCarousel .next, #galleryCarousel .previous").hover(
            function() {
                $(this).css("background-position", "0 -29px");
            },
            function() {
                $(this).css("background-position", "0 0");
            }
        );
        $(".next, .previous").not("#galleryCarousel .next, #galleryCarousel .previous").hover(
            function() {
                $(this).css("background-position", "0 -42px");
            },
            function() {
                $(this).css("background-position", "0 0");
            }
        );

        if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
            $(".gallery #slideshow .next, .gallery #slideshow .previous").hover(
                function() {
                    $(this).css("background-position", "0 -29px");
                },
                function() {
                    $(this).css("background-position", "0 0");
                }
             );
        }

        if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
            DD_belatedPNG.fix('.featureContent .readMore,span.booked, .explore .box div, .featureContent .box div, .galleryContainer .previous, .galleryContainer .next');
        }

        //add class on hover
        $("#header fieldset.searchForm input.button").hover(
            function() {
                $(this).addClass("buttonHover");
            },
            function() {
                $(this).removeClass("buttonHover");
            });

        $("div.pagination ul li:first-child").addClass("first");


    } //end ie6 functions


    //--------------------------------------------------
    // Search box functions
    //--------------------------------------------------
    $("fieldset.searchForm input").keyup(function(e) {
        if (e.keyCode == 13) {
            $("fieldset.searchForm input.button").click();
        }
    });

    //--------------------------------------------------
    // Explore search box functions
    //--------------------------------------------------
    $("fieldset.exploreForm input").keyup(function(e) {
        if (e.keyCode == 13) {
            $("fieldset.exploreForm input.button").click();
        }
    });

});                                    // end document ready


/* ---------- Functions -------- */
function autoFill(id, v) {
    $(id).attr({
        value: v
    }).focus(function() {
        if ($(this).val() == v) {
            $(this).val("").css({
                color: "#999"
            });
        }
    }).blur(function() {
        if ($(this).val() == "") {
            $(this).val(v);
        }
    });

}


//dynamically load css
var loadCSS = function(file) {
    var link = document.createElement('link');
    link.href = file;
    link.rel = 'stylesheet';
    link.type = 'text/css';
    document.getElementsByTagName('head')[0].appendChild(link);
};


/* Click through */
function clickThrough(el, hyperLink) {
    $(el).click(function() {
        var linki = $(this).find(hyperLink).attr('href');
        window.location.href = linki;
    });
}

/* Tooltip - written by Alen Grakalic (http://cssglobe.com)
* for more info visit http://cssglobe.com/post/1695/easiest-tooltip-and-image-preview-using-jquery
*/
this.tooltip = function() {
    /* CONFIG */

    // these 2 variable determine popup's distance from the cursor
    // you might want to adjust to get the right result
    /* END CONFIG */
    $("a.tooltip").hover(function(e) {


        this.t = $(this).attr("rel");
        this.rel = "";
        //alert(this.t);

        $(this).prepend("<p id='tooltip'>" + this.t + "</p>");
        $("#tooltip")
        .css("top", "10px")
        .css("left", "10px")
        .fadeIn("fast");
    },
    function() {
        this.rel = this.t;
        $("#tooltip").remove();
    });
    $("a.tooltip").mousemove(function(e) {
        $("#tooltip").remove();
    });
};




/* slider */
function slider(el, slides, slideWidth, numToDisplay, automatic, controls) {
    //set variables
    var controls = controls;
    var currentPosition = 0;
    var slideWidth = slideWidth; // image plus margin
    var slides = slides; // name wrapping slides
    var numberOfSlides = slides.length;
    var numToDisplay = numToDisplay;
    var automatic = automatic;
    var animate = automatic;
    var currentSelection = $("div.thumb a").index($("div.thumb a.on")) + 1;
    var directionAnimate = "";
    var animating = false;


    // if scrolling required
    if (numberOfSlides > numToDisplay) {
        // Wrap all .slides with #slideInner div
        $(el).wrap('<div id="slideshow"><div id="slideInner"></div></div>');
        $(el).css("width", (slideWidth * numberOfSlides));

        // Insert left and right arrow controls in the DOM
        if (controls == 1) {
            $("#slideshow").append('<span class="previous">Previous</span><span class="next">Next</span>');
        }
    }

    // Set #slideInner width equal to total width of all slides
    $('#slideInner').css('width', slideWidth * numToDisplay);


    /*
    * following code is for highlighting current selection
    */
    if ($(el).hasClass("galleryThumbnails")) {
        if (currentSelection > numToDisplay) {
            //add neg margin equal to that slide's position multiplied by slides width
            currentPosition = (currentSelection - numToDisplay);
            var setMargin = currentPosition * slideWidth * -1 + "px";
            $(el).css("marginLeft", setMargin);
        }
    }

    // Hide left arrow control on first load
    //manageControls(currentPosition);

    function animateBanner() {

        // Determine new position
        if (directionAnimate == "next") {
            currentPosition = currentPosition + 1;
            // if last slide go to beginning
            if (currentPosition == numberOfSlides - (numToDisplay - 1)) {
                currentPosition = 0;
            }

        } else {
            currentPosition = currentPosition - 1;
            // if first slide go to end
            if (currentPosition == -1) {
                currentPosition = (numberOfSlides - (numToDisplay));
            }
        }


        /*
        * hide/show controls
        */

        //pause animation on hover
        $('.mainFeature #slideshow').mouseover(function() {
            animate = 0;
        })
        .mouseleave(function() {
            animate = 1;
        });

        /*
        * move slider
        */
        if (animate == 1 && !animating) {
            animating = true;
            $(el).animate({
                //indicate action in process
                'marginLeft': slideWidth * (-currentPosition)
            });

        }

        //end action
        animating = false;

    } // end animation


    /*
    * automatic scrolling
    */
    if (automatic == 1) {
        setTimeout(
            function() {
                setInterval(animateBanner, 5000);
            }, 5000);
    }

    /*
    * Create event listeners for .controls clicks
    */
    /*
    $('#slideshow .previous, #slideshow .next')
    .bind('click', function(event) {
        event.preventDefault();
        animate = true;
        directionAnimate = $(this).attr("class");
        if (!animating) {
            animateBanner();
        }
    });
    */
}

/* accordion menu */
function initMenu() {
    $('.subNav ul li.expand ul').hide();
    $('.subNav ul li.expanded ul').show();
    $('.subNav ul > li.expand > a').click(

        function() {
            var checkElement = $(this).next();
            if ((checkElement.is('ul')) && (checkElement.is(':visible'))) {
                $('.subNav ul ul:visible').slideUp('normal');
                $(".subNav ul li.on").removeClass("on");
            }
            if ((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
                $('.subNav ul ul:visible').slideUp('normal');
                checkElement.slideDown('normal');
                $(".subNav ul li.on").removeClass("on");
                $(this).parent("li").addClass("on");


            }

            return false;
        }
        );
}

/* set default display mode of gallery description */
function setDescriptionDisplay() {
    if ($.cookie("galleryDescDefault") != undefined) {
        var mode = $.cookie("galleryDescDefault");
        if (mode == "hide") {
            $("div.caption").hide();
            $("#imageDesc, #videoDesc, #audioDesc, #interactiveDesc").html("Show full description");
            $("#imageDesc, #videoDesc, #audioDesc, #interactiveDesc").removeClass("close");
        }
        else if (mode == "show") {
            $("div.caption").show();
            $("#imageDesc, #videoDesc, #audioDesc, #interactiveDesc").html("Hide full description");
            $("#imageDesc, #videoDesc, #audioDesc, #interactiveDesc").addClass("close");
        }
        else {
            /* do nothing */
        }
    }
}
