(function($){
	$.fn.newsFade = function() {
		return this.each(function() {
			var play = true;
			var articles = $(this).find('.newsfadearticles');
			var thumbnails = $(this).find('.newsfadethumbnails');
			$(articles).children().each(function(i) {
				$(this).css('position', 'absolute');
				$(this).css('z-index', i);
				if(i == 0) {
					$(this).addClass('active');
				}
				else {
					$(this).hide();
				}
			});
			articles.moveBy = function(direction) {
				var activeIndex = articles.children().index(articles.children('.active').get(0));
				articles.moveTo((activeIndex + direction) % articles.children().length);
			}
			articles.moveTo = function(index) {
				var activeIndex = articles.children().index(articles.children('.active').get(0));
				var nextIndex = index % articles.children().length;
				var activeArticle = $(articles).children().get(activeIndex);
				var nextArticle = $(articles).children().get(nextIndex);
				$(activeArticle).fadeOut(function() {
					$(this).removeClass('active');
				});
				$(nextArticle).fadeIn(function() {
					$(this).addClass('active');
				});
				var activeThumbnail = $(thumbnails).children().get(activeIndex);
				var nextThumbnail = $(thumbnails).children().get(nextIndex);
				$(activeThumbnail).animate({ opacity: 0.5 }, 500, 'swing');
				$(nextThumbnail).animate({ opacity: 1.0 }, 500, 'swing');
			}
			$(thumbnails).children().each(function(i) {
				if(i > 0) {
					$(this).css('opacity', '0.5');
				}
				$(this).click(function() {
					play = false;
					articles.moveTo(thumbnails.children().index(this));
				});
			});
			$(this).bind('next-article', function() {
				articles.moveBy(1);
			});
			$(this).bind('previous-article', function() {
				articles.moveBy(-1);
			});
			setInterval(function() {
				if(play) {
					articles.moveBy(1);
				}
			}, 8000);
		});
	};
})(jQuery);

