// Slideswitch function for top banners
function slideSwitch() {
    var $active = $('#slide img.active');
    if ( $active.length == 0 ) $active = $('#slide img:last');
    var $next = $active.next().length ? $active.next()
        : $('#slide img:first');
    $active.addClass('last-active');
    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 600, function() {
            $active.removeClass('active last-active');
        });
};
$(document).ready(function(){
    setInterval( "slideSwitch()", 5000 );
    
    // Newsreel settings
    var newsWidth = $("#news_window").width();
    var newsSum = $("#news_reel a").size();
    var newsReelWidth = newsWidth * newsSum;

    //Adjust the image reel to its new size
    $("#news_reel").css({'width' : newsReelWidth});
  
    // Add the paging links and activate the first one
  
    for(var i = 1; i <= newsSum; i++) {
        $("#news_paging").append('<li><a href="#" rel="'+i+'">'+i+'</a></li>');
    }
    $("#news_paging a:first").addClass("active");
    
    // Paging  and Slider Function
    rotate = function(){
        var triggerID = $active.attr("rel") - 1; //Get number of times to slide
        var news_reelPosition = triggerID * newsWidth; //Determines the distance the news reel needs to slide

        $("#news_paging a").removeClass('active'); //Remove all active class
        $active.addClass('active'); //Add active class (the $active is declared in the rotateSwitch function)

        //Slider Animation
        $("#news_reel").animate({
            left: -news_reelPosition
        }, 500 );

    };

    //Rotation  and Timing Event
    rotateSwitch = function(){
        play = setInterval(function(){ //Set timer - this will repeat itself every 7 seconds
            $active = $($('#news_paging a.active').parent()).next().find('a'); //Move to the next paging
            if ( $active.length === 0) { //If paging reaches the end...
                $active = $('#news_paging a:first'); //go back to first
            }
            rotate(); //Trigger the paging and slider function
        }, 9000); //Timer speed in milliseconds (7 seconds)
    };

    rotateSwitch(); //Run function on launch
    
    //On Hover
    $("#news_reel a").hover(function() {
        clearInterval(play); //Stop the rotation
    }, function() {
        rotateSwitch(); //Resume rotation timer
    });    

    //On Click
    $("#news_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
    });
});
