$(document).ready(function() {
    $(".paging").show();
    $(".paging a:first").addClass("active");

    var imageWidth = $(".window").width();
    var imageSum = $(".image_reel img").size() + 1; // add one, since we are adding the first image to the end
    var imageReelWidth = imageWidth * imageSum;

    $(".image_reel").css({ 'width': imageReelWidth });

    // clone first image & text and add it to the end, include dummy paging
    $(".image_reel li:first").clone().appendTo($(".image_reel"));
    $(".botText a:first").clone().appendTo($(".botText"));
    $(".paging").append('<a href="#" rel="' + imageSum + '" style="width: 0px; height: 0px;"></a>'); // don't include the number in the link

    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

        $(".paging a").removeClass('active'); //Remove all active class
        $active.addClass('active'); //Add active class (the $active is declared in the rotateSwitch function)

        //Slider Animation
        $(".image_reel, .botText").animate({
            left: -image_reelPosition
        }, 750, function() {
            // callback function (called when animation is done)
            if (triggerID == imageSum - 1) {
                // if we're back to the first image, reset the window position
                $(".image_reel, .botText").css('left', 0);
            }
        });
    };

    //Rotation  and Timing Event
    rotateSwitch = function() {
        play = setInterval(function() { //Set timer - this will repeat itself every X seconds
            $active = $('.paging a.active').next(); //Move to the next paging
            if ($active.length === 0) { // If paging reaches the end...
                $active = $('.paging a:eq(1)'); // go back to second image (the first is now the last)
            }
            rotate(); //Trigger the paging and slider function
        }, 5500); //Timer speed in milliseconds (7 seconds)
    };

    rotateSwitch(); //Run function on launch

    //On Hover
    $(".image_reel a").hover(function() {
        clearInterval(play); //Stop the rotation
    }, function() {
        rotateSwitch(); //Resume rotation timer
    });

    //On Click
    $(".paging a").click(function() {
        $active = $(this); //Activate the clicked paging
        //Reset Timer
        clearInterval(play); //Stop the rotation
        rotate(); //Trigger rotation immediately
        rotateSwitch(); // Resume rotation timer
        return false; //Prevent browser jump to link anchor
    });

});
