/*
 * As simple as a newsticker that works.
 * Depends on Prototype and Scriptaculous.
 *
 * Sample HTML:
 *
 * <div id='newsContainment'>
 *  <a href="/news/1">News Story One</a>
 *  <a href="/news/2">News Story Two</a>
 * </div>
 * <script>
 *   var news = RED5.Newsticker({ container: 'newsContainment' });
 *   news.start();
 *   ... or shorter ...
 *   RED5.Newsticker({ container: 'newsContainment' }).start();
 * </script>
 *
 */
var RED5 = RED5 || {};
RED5.Newsticker = function(options) {

    var self = {};
    var container = $(options.container || 'newsticker');
    var interval = options.interval || 5; /* seconds */
    var newsItems = [];
    var newsItemCount = 0;
    var breakingNews = 0;
    var oldNews = null;
    var timer = null;


    self.start = function() {
	newsItems = container.childElements();
	newsItemCount = newsItems.length
	self.hideAllNews();
	self.showNewsItem();
	timer = setInterval(self.showNewsItem.bind(self), interval * 1000 + 1000);
    };

    self.hideAllNews = function() {
	newsItems.each(function(newsItem) {
	  $(newsItem).hide();
	});
    };

    self.showNewsItem = function() {
	Effect.Appear(newsItems[breakingNews]);
	setTimeout(self.fadeNewsItem.bind(self), interval * 1000);

	if(breakingNews < newsItemCount - 1) {
	    oldNews = breakingNews;
	    breakingNews = breakingNews + 1;
	} else {
	    breakingNews = 0;
	    oldNews = newsItemCount - 1
	}
    };

    self.fadeNewsItem = function() {
	Effect.Fade(newsItems[oldNews]);
    };

    return self;
};
