var newsbox_counter = 0;
var newsbox_loopcount = 0;
var newsbox_loopmax = 1;
var newsbox_links;
var newsbox_images;

$.fn.delay = function(time, callback){
  jQuery.fx.step.delay = function(){};
  return this.animate({delay:1}, time, callback);
}

$(document).ready(function() {
  newsbox_links = $('#top_stories li a');
  newsbox_images = $('#top_stories img');

  // position the image_spans so they can fade properly
  newsbox_images.addClass('fader');

  // and hide all but the first one
  newsbox_images.not(':first').fadeOut(0);

  // add mouseover actions for story titles
  newsbox_links.bind('mouseover', function(event, simulated) {
    // if not from the autoplay then kill the autoplay
    if ( simulated === undefined ) {
      newsbox_loopcount = -1;
    }
    // figure out index of selected anchor
    var index = $('#top_stories li').index($(this).parent());

    // swap selected text states
    $('#top_stories li a.selected').removeClass('selected');
    $(this).addClass('selected');

    // animate indicator arrow
    $('#newsbox #indicator').stop(true,false).animate({
      top: ( $(this).position().top + 8 ) + 'px'
    }, {
      duration: 500,
      complete: function() {
        // after the indicator animation fade image_spans
        var selected_img = newsbox_images.eq(index);
        newsbox_images.stop(true,true);
        selected_img.fadeIn(500);
        newsbox_images.not(selected_img).fadeOut(500);
      }
    });
  });
  
  // kickoff autoplay
  NewsboxAutoPlay();
});

function NewsboxAutoPlay() {
  if ( newsbox_loopcount < newsbox_loopmax && newsbox_loopcount != -1 ) {
    // if we haven't gone over the max number of loops
    // trigger the mouseover action passing true to show simulated event
    newsbox_links.eq(newsbox_counter).trigger('mouseover', [true]).delay(1500, function() {
      if ( newsbox_counter >= newsbox_links.length-1 ) {
        // wrap around at end
        newsbox_counter = 0;
        newsbox_loopcount++;
      } else {
        newsbox_counter++;
      }
      // and do it all over again
      NewsboxAutoPlay();
    });
  } else if ( newsbox_loopcount != -1 ){
    // loop is over
    // end on the first element
    newsbox_links.eq(0).trigger('mouseover', [true]);
  }
}
