var stopSwitch = function(){};
var rotateSwitch = function(){};

$(document).ready(function() {
    if(!$("#container_image .paging"))
        return false;
        
    //Show the paging and activate its first link
    $("#container_image .paging").show();
    $("#container_image .paging a:first").addClass("active");
    
    //Get size of the image, how many images there are, then determin the size of the image reel.
    var imageWidth = $("#container_image .window").width();
    var imageSum = $("#container_image .window .image_reel img").size();
    var imageReelWidth = imageWidth * imageSum;
    
    //Adjust the image reel to its new size
    $("#container_image .window .image_reel").css({'width' : imageReelWidth});
    
    //Paging  and Slider Function
    rotate = function(){
        var triggerID = $active.attr("rel") - 1; //Get number of times to slide
        var image_reelPosition = triggerID * imageWidth; //Determines the distance the image reel needs to slide
    
        $("#container_image .paging a").removeClass('active'); //Remove all active class
        $active.addClass('active'); //Add active class (the $active is declared in the rotateSwitch function)
    
        //Slider Animation
        $("#container_image .window .image_reel").animate({
            left: -image_reelPosition
        }, 500 );
    
    }; 
    
    //Rotation  and Timing Event
    var play;
    rotateSwitch = function(){
        clearInterval(play);
        play = setInterval(function(){ //Set timer - this will repeat itself every 7 seconds
            $active = $('#container_image .paging a.active').next(); //Move to the next paging
            if ( $active.length === 0) { //If paging reaches the end...
                $active = $('#container_image .paging a:first'); //go back to first
            }
            rotate(); //Trigger the paging and slider function                            
        }, 7000); //Timer speed in milliseconds (7 seconds)
    };
    stopSwitch = function() {
        clearInterval(play);
    };
    
    rotateSwitch(); //Run function on launch    
    
    //On Hover
    $("#container_image .window .image_reel a").hover(function() {
        stopSwitch(); //Stop the rotation
    }, function() {
        rotateSwitch(); //Resume rotation timer
    }); 
    $("#container_image .paging a").hover(function() {
        stopSwitch(); //Stop the rotation
    }, function() {
        rotateSwitch(); //Resume rotation timer
    });     
    
    //On Click
    $("#container_image .paging a").click(function() {
        $active = $(this); //Activate the clicked paging
        //Reset Timer
        stopSwitch(); //Stop the rotation
        rotate(); //Trigger rotation immediately
        //rotateSwitch(); // Resume rotation timer
        return false; //Prevent browser jump to link anchor
    });    
});
