//================================================================================
// Cookies
//================================================================================
// Toolbar
CookieManager.add({

    // Attach to the Google Analytics cookie since that's what we're asking about
    name: "ga",

    // Create HTML elements and set up click handlers for the buttons & links
    elements_created: false,
    create_elements: function() {
        // Only need to run this once
        if (this.elements_created) {
            return;
        }
        this.elements_created = true;

        // Create the HTML
        var html = '<div class="cookies-warning" style="display: none;"><div class="cookies-warning-inner"><span class="cookies-warning-text">';
        html += 'We use cookies to track website usage anonymously, so we can analyse trends &amp; improve our website. ';
        html += '<a href="#" class="cookies-warning-learn-more">Learn more/opt out &raquo;</a></span>';
        html += '<span class="cookies-warning-buttons"><a href="#" class="cookies-warning-opt-in"><span>Accept</span></a></span>';
        html += '<div class="clear"></div></div></div>';

        html += '<div class="cookies-info" style="display: none;"><div class="cookies-info-inner"><div class="cookies-info-text">';
        html += '<h2>What are cookies?</h2>';
        html += '<p>Cookies are small text files placed on your computer by this website, which we can access during your visit and when you visit our site in future. You can learn more about cookies at <a href="http://www.whatarecookies.com/">WhatAreCookies.com</a>.</p>';
        html += '<h2>What cookies do we use?</h2>';
        html += '<p>We use Google Analytics to analyse how visitors use the site in the aggregate, and Google Analytics uses cookies to identify unique visitors and record how you use the site. It does not collect any personally identifiable information, does not track your movements between different websites, and Google will not associate your IP address with any other data held by Google. You can read more detailed information in our <a href="/privacy-policy">Privacy policy</a>.</p>';
        html += '<h2>Opting out</h2>';
        html += '<p>If you click the "Opt out" button below we will delete the Google Analytics cookies and disable Google Analytics on all subsequent pages. To do this we will set another cookie called "CookieManager" that remembers your decision to opt out. You can change this setting at any time on our <a href="/privacy-policy">Privacy policy</a> page.</p>';
        html += '<p>Alternatively you can install the <a href="http://tools.google.com/dlpage/gaoptout" target="_blank">Google Analytics Opt-out Browser Add-on</a> to block Google Analytics on all websites, or configure your browser to block cookies.</p>';
        html += '<h2>Why are we telling you this?</h2>';
        html += '<p>In May 2011 a law came into effect that requires all websites to get consent from users before using cookies, and give clear information about cookies and how they are used. You can read more about it in our <a href="/news/2012/01/09/are-you-complying-with-the-new-cookies-law">news article</a>.</p>';
        html += '<p>If you want help complying with the cookie law on your own website, call us on 01865 794009 or <a href="/contact-us/email">email us</a> for more information.</p>';
        html += '</div><div class="cookies-info-buttons">';
        html += '<a href="#" class="cookies-warning-opt-in"><span>Accept cookies</span></a>';
        html += '<a href="#" class="cookies-warning-opt-out"><span>Opt out</span></a>';
        html += '<div class="clear"></div></div><div class="clear"></div></div></div>';

        html += '<div class="cookies-info-overlay" style="display: none;"></div>';

        var $cookies = $(html);
        $("#cookies-toolbar").replaceWith($cookies);

        // Set up event handlers
        var self = this;

        $cookies.find("a.cookies-warning-opt-in").click(function() {
            self.opt_in();
            return false;
        });

        $cookies.find("a.cookies-warning-opt-out").click(function() {
            self.opt_out();
            return false;
        });

        $cookies.find("a.cookies-warning-learn-more").click(function() {
            self.toggle_info();
            return false;
        });

        $cookies.find("div.cookies-info-text").bind("mousewheel", function(event, change) {
            // Prevent the wheel scrolling the whole document when at the
            // top/bottom of the text
            // http://stackoverflow.com/questions/5802467/prevent-scrolling-of-parent-element
            var $this = $(this);
            if (
                (change > 0 && this.scrollTop === 0) ||
                (change < 0 && this.scrollTop === (this.scrollHeight - $this.outerHeight()))
            ) {
              event.preventDefault();
            }
        });

        $("div.cookies-info-overlay, div.cookies-info").click(function() {
            self.slide_up_info();
        });

        $("div.cookies-info-inner").click(function(event) {
            event.stopPropagation();
        });

        $(window).resize(this.resize_info);
        $(window).resize(this.resize_overlay);
    },

    // Show the warning when the page loads (no animation)
    show: function() {
        this.create_elements();
        $("#wpadminbar").hide();
        $("div.cookies-warning").show();
    },

    // Show the warning with animation
    slide_down: function() {
        this.create_elements();
        var $warning = $("div.cookies-warning");
        if (!$warning.is(":visible")) {
            $("#wpadminbar").hide();
            $warning.show();
            $warning.css({top: -$warning.outerHeight()});
            $warning.animate({top: 0}, 300);
        }
    },

    // Hide the warning (and information) with animation
    slide_up: function() {
        this.slide_up_info();
        var $warning = $("div.cookies-warning");
        if ($warning.is(":visible")) {
            $warning.animate({top: -$warning.outerHeight()}, 300, null, function() {
                $warning.hide();
                $("#wpadminbar").show();
            });
        }
    },

    // Show the information with animation (the warning should be open already)
    slide_down_info: function()
    {
        var $info = $("div.cookies-info");
        if (!$info.is(":visible")) {
            // Make the info box visible and resize it to fit the window
            $info.show();
            this.resize_info();

            // Slide it onto the screen
            var $warning = $("div.cookies-warning");
            $info.css({top: -$info.outerHeight()});
            $info.animate({top: $warning.outerHeight()}, 300);

            // Fade in the overlay
            var $overlay = $("div.cookies-info-overlay");
            this.resize_overlay();
            $overlay.css({opacity: 0})
                    .fadeTo(200, 0.7);
        }
    },

    // Hide the information with animation
    slide_up_info: function()
    {
        var $info = $("div.cookies-info");
        if ($info.is(":visible")) {
            $info.animate({top: -$info.outerHeight()}, 300, null, function() {
                $info.hide();
            });

            // Fade out the overlay
            var $overlay = $("div.cookies-info-overlay");
            $overlay.fadeOut(200);
        }
    },

    // Toggle the information
    toggle_info: function()
    {
        var $info = $("div.cookies-info");
        if ($info.is(":visible")) {
            this.slide_up_info();
        } else {
            this.slide_down_info();
        }
    },

    // Resize the info box to fit the window
    resize_info: function()
    {
        var $info = $("div.cookies-info");
        if ($info.is(":visible")) {
            var $warning = $("div.cookies-warning");
            var $text = $info.find("div.cookies-info-text");

            // Set the maximum height of the text so it fits on screen
            var windowHeight = $(window).height();
            var warningHeight = $warning.outerHeight();
            var infoHeight = $info.outerHeight();
            var textHeight = $text.height();
            var padding = 15;

            var availableHeight = windowHeight - warningHeight - (infoHeight - textHeight) - padding;
            $text.css({maxHeight: availableHeight});
        }
    },

    // Resize the overlay to fit the window
    resize_overlay: function()
    {
        var $overlay = $("div.cookies-info-overlay");
        $overlay.css({height: $(document).height()});
    },

    // Event handlers
    at_ready_if_unknown:    "show",
    at_opt_in:              "slide_up",
    at_opt_out:             "slide_up",
    at_reset:               "slide_down"
});

// Google Analytics
CookieManager.add({

    name: "ga",

    // Run the tracking code (once only)
    has_run: false,
    run: function()
    {
        if (!this.has_run) {
            window._gaq = window._gaq || [];
            _gaq.push(['_setAccount', 'UA-3719961-2']);
            _gaq.push(['_trackPageview']);

            // Don't actually log anything on the development server
            if (document.location.hostname.indexOf(".jericho.alberon.co.uk") == -1) {
                var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
                ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
                var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
            }

            this.has_run = true;
        }
    },

    // If the user opts out, delete all Google Analytics cookies
    delete_cookies: function()
    {
        var domain = document.location.hostname;
        domain = "." + domain.replace(/^www\./, "");
        CookieManager.delete_cookie("__utma", "/", domain);
        CookieManager.delete_cookie("__utmb", "/", domain);
        CookieManager.delete_cookie("__utmc", "/", domain);
        CookieManager.delete_cookie("__utmv", "/", domain);
        CookieManager.delete_cookie("__utmz", "/", domain);
    },

    // Event handlers
    if_opted_in: "run",
    if_unknown: "run",
    at_opt_in: "run",
    at_opt_out: "delete_cookies"
});

// Cookie status box on Privacy Policy page
$(function() {
    var $placeholder = $("div.cookie-status-placeholder");
    if ($placeholder.length > 0) {
        function updateStatus() {
            // Build HTML status box
            var html = '<div class="cookie-status">';
            html += '<div class="cookie-status-text">';
            switch (CookieManager.get_status("ga")) {
                case 'allow':
                    html += 'You are <strong>opted in</strong> to Google Analytics cookies.';
                    html += '</div><div class="cookie-status-buttons">';
                    html += '<a href="#" class="cookie-opt-out" data-cookie-name="ga"><span>Opt out</span></a> ';
                    //html += '<a href="#" class="cookie-reset" data-cookie-name="ga"><span>Reset</span></a>';
                    break;
                case 'block':
                    html += 'You are <strong>opted out</strong> from Google Analytics cookies.';
                    html += '</div><div class="cookie-status-buttons">';
                    html += '<a href="#" class="cookie-opt-in" data-cookie-name="ga"><span>Accept cookies</span></a> ';
                    html += '<a href="#" class="cookie-reset" data-cookie-name="ga"><span>Reset</span></a>';
                    break;
                default:
                    html += 'You have not set a preference for Google Analytics cookies.';
                    html += '</div><div class="cookie-status-buttons">';
                    html += '<a href="#" class="cookie-opt-in" data-cookie-name="ga"><span>Accept cookies</span></a> ';
                    html += '<a href="#" class="cookie-opt-out" data-cookie-name="ga"><span>Opt out</span></a>';
                    break;
            }
            html += '</div>';
            html += '<div class="clear"></div>';
            html += '</div>';

            // Replace placeholder(s)
            var $html = $(html);
            $placeholder.html($html);

            // Attach click events
            $html.find("a.cookie-opt-in").click(function() {
                CookieManager.opt_in($(this).data("cookie-name"));
                return false;
            });
            $html.find("a.cookie-opt-out").click(function() {
                if (confirm("Are you sure you want to opt out?")) {
                    CookieManager.opt_out($(this).data("cookie-name"));
                }
                return false;
            });
            $html.find("a.cookie-reset").click(function() {
                if (confirm("Are you sure you want to reset your settings?")) {
                    CookieManager.reset($(this).data("cookie-name"));
                }
                return false;
            });
        }
        CookieManager.subscribe("set_status", function(name, value) {
            if (name == "ga") updateStatus();
        });
        updateStatus();
    };
});

//================================================================================
// Glossary tooltips
//================================================================================
if ($.fn.mopTip)
{
    $(function()
    {
        $(".tooltip, abbr, acronym").mopTip({
            w: 320,
            h: 140,
            style: "overOut",
            get: function(element)
            {
                var id = $(element).attr("href");
                if (id)
                {
                    // Link to an anchor (href="#id")
                    return "<h3>" + $(id).html() + "</h3>\n" + $(id + " + dd").html();
                }
                else
                {
                    // Other (e.g. <acronym>)
                    var text = $(element).data("title");
                    if (!text) {
                        text = $(element).attr("title");
                        $(element).data("title", text);
                        $(element).attr("title", "");
                    }
                    return "<h3>" + $(element).html() + "</h3>\n" + text;
                }
            }
        });
    });
}

//================================================================================
// Slideshows
//================================================================================
// Was based on jQuery Nivo Slider v2.1 but completely rewritten by Dave Miller
$(function()
{
    $(".slideshow").each(function()
    {
        // Config
        var delay       = 6000;   // ms
        var manualDelay = 60000;  // ms
        var speed       = 800;    // ms
        var gutter      = 9;      // px

        // Vars
        var $slideshow = $(this);
        var $viewport = $slideshow.find(".viewport");
        var $container = $viewport.children();
        var $images = $container.children();
        var $first = $images.eq(0);
        var $controls;
        var index = 0;
        var count = $images.length;
        var width = $first.width();
        var height = $first.height();
        var timer;

        //count = 1;
        if (count > 1) {

            // Fix the viewport & container sizes
            $viewport.css({overflow: "hidden", height: height, width: width});
            $container.css({position: "absolute", height: height, width: width * 2 + gutter});

            // Bring the first image to the top
            $images.eq(0).appendTo($container);

            // Fix the image position, and show all images so they load in the background
            $images.css({position: "absolute"}).show();

            // Function to slide between two images
            function slideTo(newIndex, direction, automatic)
            {
                if (newIndex == index) {
                    timer = setTimeout(nextAuto, (automatic ? delay : manualDelay));
                    return;
                }

                var startLeft = (direction > 0 ? 0 : width + gutter);
                var endLeft   = (direction < 0 ? 0 : width + gutter);

                var prev = index;
                index = newIndex;

                var $prev = $images.eq(prev);
                var $image = $images.eq(index);

                $controls.removeClass("active");
                $controls.eq(index).addClass("active");

                $container.stop().css({left: -startLeft});
                $prev.stop().appendTo($container).css({left: startLeft});
                $image.appendTo($container).css({left: endLeft});
                $container.animate(
                    {left: -endLeft},
                    speed,
                    // Pause for longer if the user clicked than if it was changed automatic
                    automatic ? setTimerAuto : setTimerManual
                );
            }

            // Function to set timer for the next image
            function setTimerAuto()
            {
                clearTimeout(timer);
                timer = setTimeout(nextAuto, delay);
            }

            function setTimerManual()
            {
                clearTimeout(timer);
                timer = setTimeout(nextAuto, manualDelay);
            }

            // Functions called by timer / click
            function nextAuto()
            {
                slideTo((index + 1) % count, 1, true);
            }

            function next()
            {
                clearTimeout(timer);
                slideTo((index + 1) % count, 1, false);
                this.blur();
                return false;
            }

            function prev()
            {
                clearTimeout(timer);
                slideTo((index - 1) % count, -1, false);
                this.blur();
                return false;
            }

            function slideClick()
            {
                clearTimeout(timer);
                var newIndex = $(this).data("slide");
                slideTo(newIndex, newIndex - index, false);
            }

            // Add next/prev controls
            var $directionNav = $slideshow.find(".slideshow-top")
                .addClass("nivo-directionNav")
                .mouseover(function() { $directionNav.addClass("nivo-directionNav-hover") })
                .mouseout(function() { $directionNav.removeClass("nivo-directionNav-hover") });
            $("<a class='nivo-prevNav' href='#'/>")
                .click(prev)
                .appendTo($directionNav);
            $("<a class='nivo-nextNav' href='#'/>")
                .click(next)
                .appendTo($directionNav);

            // Add controls to jump between slides and highlight the current slide
            var $controlNav = $("<div class='nivo-controlNav'/>").appendTo($slideshow);
            $controlNav = $("<div class='nivo-controlNav-inner'/>").appendTo($controlNav);
            $("<div class='clear'/>").appendTo($slideshow);

            for (var i = 0; i < count; i++) {
                var $control = $("<a class='nivo-control'/>")
                    .data("slide", i)
                    .click(slideClick)
                    .appendTo($controlNav);
                if (i == count - 1) {
                    $control.addClass("last");
                }
            }

            $controls = $controlNav.children();
            $controls.eq(0).addClass("active");

            // Set the timer to move to the second slide
            setTimerAuto();

        }
    });
});

//================================================================================
// Side nav popups
//================================================================================
$(function()
{
    var timer;
    var sticky = false;
    $items = $("div.side-nav div.popup-nav ul li");
    $items
        /*
        .mouseover(function()
        {
            if (!sticky) {

                var $item = $(this);

                // Stop existing timer
                clearTimeout(timer);

                // Function to open the menu
                var openFn = function()
                {
                    $items.removeClass("popup-open");
                    $item.addClass("popup-open");
                };

                // If this menu is not already open...
                if (!$item.is(".popup-open")) {
                    if ($items.filter(".popup-open").not($item).length) {
                        // If there's another one open, wait 500ms before switching
                        timer = setTimeout(openFn, 500);
                    } else {
                        // Otherwise open it immediately
                        openFn();
                    }
                }

            }
        })
        .mouseout(function()
        {
            if (!sticky) {

                var $item = $(this);

                // Stop existing timer
                clearTimeout(timer);

                // Set a timer to close the menus if no mouseover occurs in 500ms
                timer = setTimeout(function()
                {
                    $items.removeClass("popup-open");
                }, 500);

            }
        })
        */
        .children("a")
            .click(function(event)
            {
                var $item = $(this).parent();

                // Stop existing timer
                clearTimeout(timer);

                // Disable mouseover/out events
                sticky = true;

                // Open/close the menu immediately
                if ($item.is(".popup-open")) {
                    $items.removeClass("popup-open");
                } else {
                    $items.removeClass("popup-open");
                    $item.addClass("popup-open");
                }

                // Don't follow the link
                event.preventDefault();

                // Don't trigger the document click handler
                event.stopPropagation();
            });
    $(document).click(function()
    {
        // Close the menus
        $items.removeClass("popup-open");

        // Enable mouseover/out events
        sticky = true;
    });
});

