jQuery(document).ready(function() {
    jQuery(".paging").show();

    var imageWidth = jQuery(".carouselWindow").width();
    var imageNum = jQuery(".paging a").size();
    var imageReelWidth = imageWidth * imageNum;

    // Adjust the image reel to its new size
    jQuery(".imageReel").css({'width' : imageReelWidth});

    // Sets "next" slide as active, also set button images correctly
    activateNext = function(page){
        jQuery(".paging a").html("<img src='assets/images/carousel/dots-off.png'/>").removeClass('active');

        ( $next.attr('id') == 'overflow' ?
            jQuery('.paging a:first') : $next ).html("<img src='assets/images/carousel/dots-on.png'/>").addClass('active');
        // Set the $next page button to active, unless the overflow slide is being activated, in which case set the first page button
    };

    randomize = function(){
        var rand = Math.floor(Math.random() * (imageNum - 1)); // Make sure the overflow image will never be selected
        $next = jQuery(".paging a").eq(rand);

        activateNext();

        jQuery(".imageReel").animate({ // Move image reel to randomly selected image{
            left: -(($next.attr("rel") - 1) * imageWidth)
        }, 0);
    };

    rotate = function(){
        var triggerID = $next.attr("rel") - 1; //Get number of times to slide
        var imageReelPosition = triggerID * imageWidth; //Determines the distance the image reel needs to slide

        activateNext();

        jQuery(".imageReel").animate({
            left: -imageReelPosition
        }, 1000);

        if ( $next.attr('id') == 'overflow' ) { // If paging reaches the end...
            jQuery(".imageReel").animate({ // go back to first.
                left: 0
            }, 0);
            $next = jQuery('.paging a:first').next();
        };

    };

    rotateSwitch = function(){
        play = setInterval(function(){ //Set timer - this will repeat itself every 7 seconds
            $next = jQuery('.paging a.active').next(); //Move to the next paging
            rotate();
        }, 6000);
    };

    randomize();
    rotateSwitch();

    jQuery(".imageReel a").hover(function() {
        clearInterval(play); //Stop the rotation
    }, function() {
        rotateSwitch(); //Resume rotation timer
    });

    jQuery(".paging a").click(function() {
        $next = jQuery(this);
        //Reset Timer
        clearInterval(play); //Stop the rotation
        rotate(); //Trigger rotation immediately
        rotateSwitch(); // Resume rotation timer
        return false; //Prevent browser jump to link anchor
    });
});

