/**
 * Set frames per second to something achievable for the average taregeted
 * browser
 */
var fps = 24;
jQuery.fx.interval = fps;

var the_carousel, fadeGallery;
var intSlideInSpeed = 600;
var intSlideOutSpeed = 300;

// Special animation duration settings for mobile clients
if (isMobile()) {
    intSlideInSpeed = 900;
    intSlideOutSpeed = 450;
}
var galleryLoad = function(idx, callback)
{
    var nextToLoad = galleryImages[idx];
	var gallery = $('#gallery');

    // Construct image URL
    var imageSrc = nextToLoad.image;
	
    // Preload image
    $.imgpreload(imageSrc, function() {
        // Construct <img> element and inject it into the <li>
        var img = $('<img />')
            .attr({
                src: nextToLoad.image,
                border: '0'
            })
            .css({
                display : idx == 0 ? 'block' : 'none'
            });
        
        var img_link = $('<a />')
            .addClass('slide')
            .attr('href', nextToLoad.url)
            .append(img);
		
        $(gallery).append(img_link);
        
        // remove loading class
        if (idx == 0) $(gallery).removeClass('loading');
        
		// Determine what to do next
		var next = idx + 1;
		
		// Check if there is a next
		if (next == galleryImages.length) {
			callback(); // start - ONLY when we have something.
		} else {
			galleryLoad(next, callback);
		}
    });
};

/* manage the active display of the secondary nav */
function mycarousel_loadCallback(carousel)
{
    var current = $('#mini-buttons a')[(carousel.first-1) % galleryImages.length];
	$('#mini-buttons a').removeClass('active');
    $('#mini-buttons #'+$(current).attr('id')).addClass('active');
}

/**
 * Preloads image data for the homepage gallery and instantiates the
 * (customised) fadeGallery jQuery plugin
 */
var loadFadeGallery = function()
{
    /*Removed to support correct URL on each banner image*/
	/*galleryLoad(0, function() {
        fadeGallery = $('#gallery').fadeGallery({
            slideElements: 'img',
            generatePagination: 'div#mini-buttons',
            paginationUlClass: '',*/
	galleryLoad(0, function() { 
		$('#gallery a.slide img').removeAttr('style');
		fadeGallery = $('#gallery').fadeGallery({ 
			slideElements: 'a.slide',
			generatePagination: 'div#mini-buttons',
			paginationUlClass: '',
            ie: false,
            autoRotation: true,
            switchTime: 3000,
            duration: 700,
            // Turn off pause on hover. We already have pause & play buttons, keep it simple by allowing control coming from the buttons only.
            pauseOnHover: false,
            pauseOnMouseEnter: false,
            btnDisable: '#buttons, #panel',
            //btnDisable: '#buttons, #panel, #gallery',
            //btnDisable: '#carousel-container',
            btnPlayPause: 'a#gallery-playpause-btn',
            pausedClass: 'gallery-paused',
            playClass: 'gallery-playing'
        });
    });

    HomepageCarousel.init();
}

/**
 * Preloads image data for the interior page gallery and instantiates the
 * (customised) fadeGallery jQuery plugin
 */
var loadInteriorFadeGallery = function()
{
    /*Removed to support correct URL on each banner image*/
	/*galleryLoad(0, function() {
        fadeGallery = $('#gallery').fadeGallery({
            slideElements: 'img',
            generatePagination: 'div#mini-buttons',
            paginationUlClass: '',*/
	galleryLoad(0, function() { 
		$('#gallery a.slide img').removeAttr('style');
		fadeGallery = $('#gallery').fadeGallery({ 
			slideElements: 'a.slide',
			generatePagination: 'div#mini-buttons',
			paginationUlClass: '',
            ie: false,
            autoRotation: true,
            switchTime: 3000,
            duration: 700,
            // Turn off pause on hover. We already have pause & play buttons, keep it simple by allowing control coming from the buttons only.
            pauseOnHover: false,
            pauseOnMouseEnter: false,
            btnDisable: '#buttons, #panel',
            btnPlayPause: 'a#gallery-playpause-btn',
            pausedClass: 'gallery-paused',
            playClass: 'gallery-playing'
        });
    });
}

var gaEventTrack = function(category, action, label, href)
{
    if (typeof _gaq == 'object') _gaq.push(['_trackEvent', category, action, label]);
    if (href.length > 0) window.location = href;
}

/**
 * Blurs image currently in view.
 * Called from the fadeGallery when the mouseenter event is triggered for one of
 * the buttons
 *
 * @param {HTMLObject} img Current image in view
 * @param {integer} idx Index of slide currently in view
 */
function blurHeroImage(img, idx)
{
    var el, clonedImg;
    var parent = img.parent();
   
    // Use canvas if supported
    if (document.createElement('canvas').getContext) {

        // check if canvas already exists
        el = parent.find('canvas');
        if (el.length == 0) {
            // create canvas element
            clonedImg = img.clone();
            clonedImg
                .removeClass('active')
                .attr('id', 'hero-clone-' + idx)
                .addClass('hero-blur')
                .css({
                    display: 'none'
                })
                .appendTo( parent );

            el = $('<canvas />')
                .attr('id', 'hero-canvas-' + idx)
                .css({
                    position: 'absolute',
                    top: 0,
                    left: 0,
                    width: img.width(),
                    height: img.height()
                })
                .addClass('hero-blur')
                .appendTo( parent );
                
             // Initiate blur effect
             stackBlurImage( 'hero-clone-' + idx, 'hero-canvas-'+idx, 40, false );
        }

        parent.css('opacity', 0.5);
        el.show();

    } else {
        // IE CSS filters it is
        el = parent.find('div.filter');
        if (el.length == 0) {

            //clonedImg = img.clone();

            var filter = $('<div />')
                .css({
                    //filter: "progid:DXImageTransform.Microsoft.Blur(PixelRadius='10', MakeShadow='false', ShadowOpacity='0.35')",
                    width: 968,
                    height: 437,
                    position: 'absolute',
                    top: 0,
                    left: 0,
                    overflow: 'hidden'
                    //opacity: 0.5,
                })
                .addClass('hero-blur')
                .addClass('filter');

            filter.appendTo(parent);
        }
        //filter.css('opacity', 0.5);
        el.show();
    }
}

/**
 * Hides blurred image currently in view.
 * Called from the fadeGallery when the mouseleave event is triggered for one of
 * the buttons
 *
 * @param {HTMLObject} img Current image in view
 * @param {integer} idx Index of slide currently in view
 */
function unblurHeroImage(img)
{
    var parent = img.parent();
    var el;
    // Use canvas if supported
    if (document.createElement('canvas').getContext) {
        el = parent.find('canvas');
    } else {
        el = parent.find('div.filter');
    }
    parent.css('opacity', 1);
    el.remove();
    //el.hide();
}

/**
 * Returns true if user is using a mobile device
 * @return {boolean}
 */
function isMobile()
{
    try {
        document.createEvent("TouchEvent");
        return true;
    } catch (e) {
        return false;
    }
}



HomepageCarousel = {

    /**
     * Reference to currently button that triggered the currently expanded
     * panel (if any)
     * @type {HTMLElement}
     */
    currentButton: null,

    /**
     * Reference to currently expanded panel (if any)
     * @type {HTMLElement}
     */
    currentPanel: null,

    /**
     * Container in which all panels are contained
     * @type {HTMLElement}
     */
    panelContainer: null,

    /**
     * 
     * @type (HTMLElement)
     */
    panel: null,

    block: false,

    init: function()
    {
        var $this = this;

        this.panelContainer = $('#panel');

        this.buildPanels();

        //this.panel = $('#panel');

        // Show/hide mini buttons
        $('#panel, #buttons').mouseenter(function() {
            $('#gallery').addClass('gallery-disabled');
        });
        $('#panel, #buttons').mouseleave(function() {
            $('#gallery').removeClass('gallery-disabled');
            //if (fadeAutoplay == true) $('a#gallery-playpause-btn').click();
            
        });
		
		$('#mini-buttons').mouseenter(function() { $('#gallery').removeClass('gallery-disabled'); });
		
		this.panelContainer.mouseleave(function() { $this.panelContainer.hide(); } );
				
        /*
		if (!$.browser.msie) {
            this.panelContainer.mouseleave(function() {
                $this.panelContainer.hide();
            });
        }
		*/

        // Return to default carousel state 
        $('#carousel-container').mouseleave(function() {
            //$('#gallery').removeClass('gallery-disabled');
            if ($this.currentButton !== null) {
                $this.animateOut($this.currentButton);
            }
        });
    },

    /**
     * Build DOM elements from dynamic data
     * @return {void}
     */
    buildPanels: function()
    {
        var $this = this;
        // The navigation on the right hand side
        // creates: <a href="#" class="nav" id="button1"></a>
        var navButtons = $('#buttons');

        for (i =0 ; i < 5; i ++) {
            var btn = $('<a />')
                .attr({
                    id: 'button' + (i+1),
                    text: '',
                    //href: '#',
                    //onClick: 'return false;',
                    'class': 'nav'
                })
                .css({
                    cursor: 'pointer'
                });
            if (isMobile()) {
                btn.click(function() {
                    $this.handleEvent($(this));
                });
            } else {
                btn.click(function() {
                    $this.handleEvent($(this));
                });
                btn.hoverIntent({
                    over: function() {
                        $this.handleEvent($(this));
                    },
                    out: function() {
                        $this.handleEvent($(this));
                    },
                    timeout: 200, // number = milliseconds delay before onMouseOut
                    sensitivity: 3, // number of pixels we allow people to move
                    interval: 250 // how long do we wait until we recognise hovering
                });
            }
            btn.appendTo(navButtons);
        }

        /**
         * load up the sliding panels - when hovering over a main nav button
         * used on panel with all html elements stored on array panelElements.
         * load up the sliding panels - when hovering over a main nav button
         */
        /*for (outerCount in panelElements) {*/
        for (outerCount=0; outerCount < panelElements.length; outerCount++) {
            panelID = outerCount * 1 + 1;
            var navPanel = $('<div id="panel' + panelID + '" class="panel" />').appendTo(this.panelContainer);

            // do it for each sub panel within the Main panel
            for (var innerCount =0 ; innerCount < panelElements[outerCount].length; innerCount ++) {
                var element = panelElements[outerCount][innerCount];
                // innerpanel-inner{html} inside innerpanel inside #panel
                var innerpanel = $('<div class="innerpanel-inner" />');
                // Insert Header
                $('<h1 />')
                    .attr( {'innerHTML': element.header} )
                    .appendTo(innerpanel);
                // Insert Content
                $('<div />')
                    .attr( {'innerHTML': element.content} )
                    .appendTo(innerpanel);
                // Insert Link
                var innerlink = '';
                if (element.link.length > 1){
                    for (var linkcount=0; linkcount < element.link.length; linkcount++ ){

                        innerlink = $('<a />');
                        innerlink.attr( {'href': element.link[linkcount].href,
                                         'innerHTML': element.link[linkcount].html} );

                        $('<p />').append(innerlink).appendTo(innerpanel);
                    }
                } else {
                    /*
					innerlink = $('<a />');
                    innerlink.attr( {'href': "#",
                                     'innerHTML': element.link.html,
                                     'onClick' : "gaEventTrack( '"+ gaEventTrackerButtons['button'+panelID].category +"', 'Click', '"+ element.header +"', '"+ element.link.href +"');"
                                    } );
					*/
					
					innerlink = $('<a />');
                    innerlink.attr( {'href': element.link.href,
                                     'innerHTML': element.link.html} );

                    $('<p />').append(innerlink).appendTo(innerpanel);
                }
                innerpanel.appendTo( $('<div class="innerpanel" />') .appendTo(navPanel) );
            }
        }
    },

    handleEvent: function(btn)
    {
        var state = btn.data('state');
        var animated = btn.data('animated');

        //if (isMobile() && fadeAutoplay == true) $('a#gallery-playpause-btn').click();
        //if (fadeAutoplay == true) $('a#gallery-playpause-btn').click();

        if (isMobile()) {
            if (animated == true) return false;
        } else {
            if (this.currentButton !== null && this.currentButton.index() == btn.index()) return false;
        }

        if (state == 'expanded') {
            this.animateOut(btn, true);
        } else {
            // Collapse
            if (animated !== true && state !== 'expanded') {

                var delay = 0;
                if (this.currentButton !== null) {
                    delay = intSlideOutSpeed;
                    this.animateOut(this.currentButton, false);
                }

                this.panelContainer.show();

                btn.data('animated', true);
                
                this.animateIn(btn, delay);
            }
        }

    },

    animateIn: function(btn, delay)
    {
        var $this = this;
        var idx = btn.index();
        // Find mathcing panel
        var panel = this.panelContainer.find('div.panel:eq('+ idx +')');

        this.block = true;

        // Disabled carousel controls on mobile manually
        if (isMobile()) $('#gallery').addClass('gallery-disabled');

        // .stop(true, false)
        panel.css('left', '-640px').show().delay(delay).animate({left: 20}, {
            duration: intSlideInSpeed,
            complete: function() {

                // Disabled carousel controls on mobile manually
                //if (isMobile()) $('#gallery').addClass('gallery-disabled');
                $this.block = false;
                
                // Un-mark panel connected to button as being animated & mark as
                // expanded
                btn.data('animated', false);
                btn.data('state', 'expanded');

                // Store reference to current elements
                $this.currentPanel = panel;
                $this.currentButton = btn;

                // fire up GA event tracker
                gaEventTrack(gaEventTrackerButtons['button'+(btn.index() + 1)].category, 'Mouse Over', '', '');
            }
        });

        /*Removed to reintroduce the blur effect*/
		/*var active = $('#gallery').find('img.active');*/
		var active = $('#gallery').find('a.active img:first');
		// If there is only one image, this makes sure we grab it
        if (active.length < 1)
		{
            active = $('#gallery').find('a.slide:first img');
		}

        // Add image blur effect
        blurHeroImage(active, active.parent().index());
    },

    animateOut: function(btn, enableAutoPlay)
    {
        var $this = this;
        /*Removed to reintroduce the blur effect*/
		/*var active = $('#gallery').find('img.active');*/
		var active = $('#gallery').find('a.active img:first');
        // If there is only one image, this makes sure we grab it
        if (active.length < 1)
		{
            active = $('#gallery').find('a.slide:first img');
		}


        // Remove image blur effect
        unblurHeroImage(active);

        this.currentPanel.animate({
            left: -640
        }, {
            duration: intSlideOutSpeed,
            complete: function()
            {
                // Check if we should manually turn autoplay back on
                if (isMobile() && !$this.block) {
                    $('#gallery').removeClass('gallery-disabled');
                    $this.panelContainer.hide();
                    //if (enableAutoPlay && fadeAutoplay == false) $('a#gallery-playpause-btn').click();
                }

                //$this.panelContainer.hide();

                // Mark carousel state
                $this.currentButton = null;
                $this.currentPanel.hide();
                
                btn.data('animated', false);
                btn.data('state', 'collapsed');
            }
        });
    }
}
