// Global variable to store the ID for the setInterval call used for
// the automated transitions 
var refreshId;

// Global variables used to set times for transitions etc.
var imageTransitionTime = 4000;
var pauseTime = 26000;
var totalSlideTime = imageTransitionTime + pauseTime;

// This function fades out the current slide image (if specified), fades in the
// next slide image and returns to the callback function if it exists.
function transitionImages($oldImage, $newImage) {
    if ($oldImage != null) {
        $oldImage.fadeOut(imageTransitionTime);
    }
    $newImage.fadeIn(imageTransitionTime);
}

// This method is used to rotate between slides.
function rotateSlides() {
    $slide = $('#main.home ul#slides li.current');
    $nextSlide = $slide.next();
    
    // Stop the automatic rotation if this is the last slide.
    if ($nextSlide.length < 1) {
        $nextSlide = $('#main.home ul#slides li:first');
    }
    
    transitionSlides($slide, $nextSlide);
}

// This function contains all actions to transition to the next slide.
function transitionSlides($slide, $nextSlide) {
	transitionImages($slide, $nextSlide);
    
    $slide.removeClass('current');
    $nextSlide.addClass('current');
}

// This function initialises the heroslot showing and hiding elements as
// required.
function initialise(f) {
    $('#main.home.slideshow ul#slides li').hide();
	$('#main.home.slideshow ul#slides li.first').show(0, function() {
        if (typeof f == "function") f();
    });
}

// When the document is ready it will initialise the heroslot, fade in
// the initial slide and then start the automatic transitions.
$(document).ready( function() {
    initialise(function() {
        transitionImages(null, $('#main.home.slideshow ul#slides li.current'));
    });
    
    // Start slide automatic rotation
    refreshId = setInterval(rotateSlides, totalSlideTime);
});
