$(document).ready(function(){

    // put your custom jScript here - will execute on completion of DOM load

    // CONTACT FORM
    // Show hide contact form on click Toggle
    $('.contact-button a').click( function () {
        $('.globalContactForm').slideToggle('slow');
        return false;
    });

    //close button behaviour
    $('a.close').click( function () {
        $('.globalContactForm').slideToggle('medium');
        return false;
    });
    
    
    // AWESOME CARROUSEL
    // Hide current children but first
    if (!Array.prototype.indexOf)
    {
        Array.prototype.indexOf = function(elt /*, from*/)
        {
            var len = this.length >>> 0;

            var from = Number(arguments[1]) || 0;
            from = (from < 0)
            ? Math.ceil(from)
            : Math.floor(from);
            if (from < 0)
                from += len;

            for (; from < len; from++)
            {
                if (from in this &&
                    this[from] === elt)
                    return from;
            }
            return -1;
        };
    }
    
    var currentIndex = 1, 
    indexQueue = new Array(),
    movedOut = true,
    intervalId,
    maxPanels = $("#slider > .scroll .panel").length;
    $("#slider > .scroll .panel").hide().css('opacity', 0);
    $("#slider > .scroll .panel:nth-child(" + currentIndex + ")").show().css('opacity', 1);
    
    // Helper functions
    function fadeCycle() {
        if (indexQueue.length > 0) {
            fadeToChild(indexQueue[0]);
        } 
    }
    function fadeToChild(index) {
        $("#slider > .scroll .panel:nth-child(" + currentIndex + ")").animate({
            opacity: 0
        }, 300, 'linear', function(){
            currentIndex = index;
            
            $(this).hide();
            $("#slider > .scroll .panel:nth-child(" + currentIndex + ")").show();
            $("#slider > .scroll .panel:nth-child(" + currentIndex + ")").animate({
                opacity: 1
            }, 300, 'linear', function(){
                if(indexQueue.length > 0){
                    indexQueue.splice(0, 1); 
                }
                fadeCycle();
            });
        });
    }
    
    // 1. Hover over our thumbs, show corresponding images
    $('#slider > div.navigation > ol > li').mouseover(function(){
        movedOut = false;
        stopCycle();
        var emptyQueue = indexQueue.length === 0,
        nextIndex = $(this).index() + 1;
        if (currentIndex !== nextIndex && indexQueue.indexOf(nextIndex) === -1) {
            indexQueue.push(nextIndex);
        }
        if (emptyQueue) {
            fadeCycle();
        }
    });
    
    // 2. Move out of thumbs
    $('#slider > div.navigation > ol > li').mouseout(function(){
        movedOut = true;
        startCycle();
    });
    
    // 3. Cycle, auto-activate
    function startCycle() {
        if (movedOut) {
            intervalId = setInterval(cycle, 5000);
        }
    }
    startCycle();
    function stopCycle() {
        indexQueue = [];
        clearInterval(intervalId);
    }
    function cycle() {
        // Move to next index
        if(currentIndex === maxPanels) {
            indexQueue.push(1);
        } else {
            indexQueue.push(currentIndex + 1);
        }
        fadeCycle();
    }

    /*
    // HOMEPAGE CAROUSEL

    // 1. create scroll effect
    // 2. handle the selection of the navigation

    var $panels = $('#slider .panel');
    var $container = $('#slider .scrollContainer');
    var $scroll = $('#slider .scroll').css('overflow', 'hidden');

    $('#slider .navigation a').click(selectNav);

    function selectNav() {
        $(this)
        .parents('ol:first')
        .find('a')
        .removeClass('selected')
        .end()
        .end()
        .addClass('selected');
    }


    var scrollOptions =
    {
        target: $scroll,
        items: $panels,
        navigation: '.navigation a',
        axis: 'y',
        duration: 500,
        easing: 'swing'
    };



    // apply serialScroll to the slider - we chose this plugin because it
    // supports// the indexed next and previous scroll along with hooking
    // in to our navigation.
    $('#slider').serialScroll(scrollOptions);

    // now apply localScroll to hook any other arbitrary links to trigger
    // the effect
    // $.localScroll(scrollOptions);

    // finally, if the URL has a hash, move the slider in to position,
    // setting the duration to 1 because I don't want it to scroll in the
    // very first page load.  We don't always need this, but it ensures
    // the positioning is absolutely spot on when the pages loads.
    scrollOptions.duration = 1;
    $.localScroll.hash(scrollOptions);

    // autoscroll
    intervalIds = [];
    
    // select some trigger elements to stop the auto-cycle
    var $stopTriggers = $('#slider .navigation').find('a')
    .add('.scroll')
    .add('.stopscroll')             // links to the stop class div
    .add('.navigation')          // links to navigation id for tabs
    .add("a[href='#']");      // links to a tab


    // this is the function that will stop the auto-cycle
    function stopCycle() {
        console.log('stopped');
        
        // remove the no longer needed stop triggers
        for (i = 0, max = intervalIds.length; i < max; i++) {
            clearInterval(intervalIds[i]);
        }
        intervalIds = [];
        
        $(this) .parents('ol:first')
                .find('a')
                .removeClass('selected')
                .end()
                .end()
                .addClass('selected');
        
    //$buttons.show();                           // show the navigation buttons - SRJ, removed since crashes IE and not sure this is required
    //document.getElementById('stopscroll').style.display='none';    // hide the stop div
    //document.getElementById('startscroll').style.display='block';  // block the start div
    }
    
    function startCycle() {
        console.log('started');
        intervalIds.push(setInterval(function () {
            console.log('next up!');
            $scroll.trigger('next');
        }, 5000));  // how many milliseconds, change this to whatever you like
    }

    // start to automatically cycle the tabs
    startCycle();

    // bind stop cycle function to the click event using namespaces
    $('#slider .navigation a').bind('mouseover', stopCycle);
    $('#slider .navigation a').bind('mouseout', startCycle);
    
    
    
    */

    //Station template navigator. Remove Scroll
    $('.pane-wrapper').css('overflow', 'hidden');


    // function to populate a form-field with a default text as description
    function populateElement(selector, defvalue) {
        $(selector).each(function() {
            if($.trim(this.value) == "") {
                this.value = defvalue;
            }
        });

        $(selector).focus(function() {
            if(this.value == defvalue) {
                this.value = "";
            }
        });

        $(selector).blur(function() {
            if($.trim(this.value) == "") {
                this.value = defvalue;
            }
        });
    }

    // tell which element to populate with what text
    populateElement('.s', 'Site search...');
    populateElement('.near-you-input', 'Enter address or postcode...');
    
});


// AUTOLOAD CODE BLOCK (MAY BE CHANGED OR REMOVED)
if (!/android|iphone|ipod|series60|symbian|windows ce|blackberry/i.test(navigator.userAgent)) {
    jQuery(function($) {
        $("a[rel^='lightbox']").slimbox({/* Put custom options here */}, null, function(el) {
            return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
        });
    });
}

