jQuery(document).ready(function($) {

    var hero = $("#hero");
    var slides = $("#hero div.slide");

    if(slides.length >1) {

        $("#hero, #hero_left, #hero_right").supersleight({shim: 'http://www.sweet-apple.co.uk/wp-content/themes/sweetapple-v3/images/x.gif'});

        //Find the story panels
        var slides = $("#hero div.slide");
        var slideCount = slides.length;
        var slideWidth = $("#hero").width();
        var slidesTotalWidth = ( $(hero).width() * slides.length );
        var slidePosition = 1;
        var slideShowTimer;	// Timer for the slideshow
        var slidePaused = false;

        $(hero).css( { overflow: "hidden"} );
        //Create new container for the stories
        var slidesContainer = $("<div>").css( {position: "absolute", width: slidesTotalWidth + "px", height: "450px", top: 0, left: 0, overflow: "visible"} );
        $(slidesContainer).append(slides);
        $(hero).prepend(slidesContainer);

        //Animate the stories sideways every 5 secs
        var overlayLeft = $("<div id='hero_left'>");
        var overlayRight = $("<div id='hero_right'>");
        $(hero).append(overlayLeft).append(overlayRight);
        //$(overlay)

        //Creates a timer to update the slideShow
        var startSlideShowTimer = function (){
            clearTimeout(slideShowTimer);
            if( slidePaused == false) {
                slideShowTimer = setTimeout(function(){animateSlides()}, 8000);
            }

        }

        var stopSlideShowTimer = function(){
            $(slideContainer).clearQueue();
            clearTimeout(slideShowTimer);
        }

        var animateSlides = function (){
            $(slidesContainer).animate( { left : setNewPosition() }, 1000, 'easeOutQuint', function(){startSlideShowTimer()});
        }

        $(slidesContainer).hover(
            function(){
                slidePaused = true;
                stopSlideShowTimer();
            },
            function(){
                slidePaused = false;
                startSlideShowTimer();
            }
        );

        startSlideShowTimer();

    }

    function setSlidePosition(){
        slidePosition = (slidePosition >= slideCount) ? 1 : slidePosition + 1 ;
    }

    function setNewPosition(){
        var newPosition = (slidePosition >= slideCount) ? 0 : "-" + ( slideWidth * (slidePosition) );
        setSlidePosition();
        return newPosition;
    }

    //Add scrollpanes
    $('div.scrollpane').jScrollPane();


});


