/**
 * North American Truckers Guild Javascript
 * @author Guillaume VanderEst <gvanderest@netshiftmedia.com>
 */

var news_delay = 5000;
var news_interval = 0;
var news_index = 0;
var news_selector = '#home-news';

$(document).ready(function(){

    // start the news rotator
    news_start();

    // sponsor rotator
    $('.sponsor-list').cycle();

});

/**
 * News start
 */
function news_start()
{
    // if there is a news rotator on this page, start the timer
    var $news = $(news_selector);
    if ($news.length > 0)
    {
        $stories = $news.find('.stories li');
        
        // hide all news stories except the first
        $stories.hide();
        $stories.eq(news_index).show();

        // activate the first slide
        $slides = $news.find('.slides li');
        $slides.removeClass('active');
        $slides.eq(news_index).addClass('active');

        // start the timer
        news_play();

        // also make the list of story options clickable
        $slides.click(function(e){
            e.preventDefault();
            news_set_slide($(this).index());
            news_pause();
        });
    }
}

/**
 * Go to next news slide
 */
function news_next_slide()
{   
    news_index++;
    $news = $(news_selector);
    $stories = $news.find('.stories li');
    if (news_index >= $stories.length) { news_index = 0; }

    news_set_slide(news_index);
}

/**
 * Go to a specific news slide
 * @param int index
 */
function news_set_slide(index)
{
    if (news_index == index)
    {
        return;
    }
    news_index = index;

    $news = $(news_selector);
    $stories = $news.find('.stories li');
    $stories.stop(true, true);

    // if there are no visible slides, fade the requested index in
    if ($stories.filter(':visible').length == 0)
    {
        $stories.eq(index).fadeIn();

    // otherwise, fade all visible slides out.. then callback to fade slide in
    } else {

        $visibles = $stories.filter(':visible');
        $visibles.eq(0).fadeOut(function(){
            $stories.eq(index).fadeIn();
        });
    }
    
    // flag slide list with active
    $slides = $news.find('.slides li');
    $slides.removeClass('active');
    $slides.eq(index).addClass('active');
}

/**
 * Stop the news rotator
 */
function news_pause()
{
    clearTimeout(news_interval);
    news_interval = 0;
}

/**
 * Start the news rotator
 */
function news_play()
{
    if (news_interval != 0)
    {
        news_pause();
    }
    news_interval = setInterval('news_next_slide()', news_delay);
}

