var currentArticle = -1;
var newsArticles = [];
var ARTICLE_SPEED = 5000;
var manuallySelected = false;

function hideCurrentArticle() {
  newsArticles[currentArticle].fadeOut('slow');
  $('a[homeImage=' + currentArticle + ']').removeClass('current');
}

function showCurrentArticle() {
  newsArticles[currentArticle].fadeIn('slow');
  $('a[homeImage=' + currentArticle + ']').addClass('current');
}

function animateNextArticle() {
  // as soon as a user selects an article, stop animating
  if(manuallySelected)
    return;
  
  // fade the old article out
  if(currentArticle != -1)
    hideCurrentArticle();

  // show the next one
  currentArticle = (currentArticle + 1) % newsArticles.length;
  showCurrentArticle();
  
  // trigger the next animation
  if(newsArticles.length > 1)
    setTimeout('animateNextArticle()', ARTICLE_SPEED);
}

$(document).ready(function() {
  // get each news image
  $('.home_image').each(function() {
    newsArticles.push($(this));
  });
  
  // get each news snippet on other pages
  $('.news_snippet').each(function() {
    newsArticles.push($(this));
  });
  
  // if there are no articles on this page ignore
  if(newsArticles.length == 0)
    return;
  
  // show the first article
  animateNextArticle();
  
  // watch for clicks on the news snippet links
  $('.home_image_link').click(function(event) {
    // prevent the event from bubbling and the animation from occurring again
    event.preventDefault();
    manuallySelected = true;
    
    // show the selected article
    var selectedArticle = parseInt($(this).attr('homeImage'), 10);
    if(selectedArticle != currentArticle) {
      hideCurrentArticle();
      currentArticle = selectedArticle;
      showCurrentArticle();
    }
  });
});

