$(document).ready(function() {
    //in miliseconds
    var slideSpeed = 2000;
    var slideBuffer = 8000;
    var captionSlideSpeed = 1000;

    $(".paging").show();
    $(".paging a:first").addClass("active");
    $(".contentTextContainer div:first").addClass("active");

    var imageWidth = $(".contentImageContainer").width();
    var imageSum = $(".image_reel img").size();
    var imageReelWidth = imageWidth * imageSum;

    $(".image_reel").css({ 'width': imageReelWidth });

    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');
        $active.addClass('active');

        //logic goes here!

        $(".image_reel").animate({ left: -image_reelPosition }, slideSpeed);

        displaySideInfo();
        showCaption();
    };

//    rotateSwitch = function() {
//        $active = $('.paging a.active').next();
//    
//        if ($active.length === 0) {
//            $active = $('.paging a:first');
//        }

//        rotate();
//        
//        play = setTimeout("rotateSwitch()", slideBuffer);
//    };

    rotateSwitch = function() {
        play = setInterval(function() {
            $active = $('.paging a.active').next();
            if ($active.length === 0) {
                $active = $('.paging a:first');
            }
            rotate();
        }, slideBuffer);
    };

    displaySideInfo = function() {
        var infoID = "#contentText_" + $active.attr("rel");
        $(".contentTextContainer div").stop(true, true).removeClass('active').css('display', 'none');
        $(infoID).slideDown(captionSlideSpeed).addClass('active');
    };

    showCaption = function() {
        $("#captionContainer").hide();
        $("#captionContainer div").removeClass('active');

        var nextCaptionID = "#caption_" + $active.attr("rel");
        $(nextCaptionID).addClass('active');

        $("#captionContainer").slideDown(captionSlideSpeed);
    };

    $(".image_reel img").hover(function() {
        clearInterval(play); //Stop the rotation
    }, function() {
        rotateSwitch(); //Resume rotation timer
    });

    $(".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
    });

    rotateSwitch();
});