(function($){
  $.fn.wm_news = function(options){
  	if(options == undefined){
  		options = {};
  	}
		var defaults = {
			timeout: 10000,
			animate_time: 500
		};
		var opts = $.extend(defaults, options);
		return $(this).each(function(){var $elm = $(this);
			// position elements
			$elm.css({
				'margin-bottom':'10px',
				'position':'relative'
			});
			$elm.find('article p').hide();
			$elm.find('article').css({
				'width':'50%',
				'border':'1px solid #eee',
				'border-width':'0 1px 1px 1px',
				'margin':'0'
			});
			$elm.find('article h1').css({
				'margin':'0 10px',
				'padding':'10px 0',
				'font-weight':'normal'
			});
			var $preview_height = 0;
			
			$elm.find('article').each(function(){
				$preview_height += $(this).height()+1;
			});
			$preview_height--;
			$('<div class="preview"></div>').appendTo($elm).css({
				'width':'50%',
				'height':$preview_height+'px',
				'border':'1px solid #eee',
				'border-width':'0 1px 1px 0',
				'position':'absolute',
				'overflow':'hidden',
				'right':'0',
				'top': $elm.find('article h1:first').position().top
			});
			// vars			
			var $num_articles = $elm.find('article').size();
			var $news_counter = 0;
			var $preview = 	$elm.find('div.preview');
			// copy articles into preview
			$elm.find('article.news').each(function(){
				$preview.append('<div class="article">' + $(this).html() + '</div>');
			});
			$preview
				.find('p').show().css('margin','0 10px').end()
				.find('h1').css({
					'font-size':'16px'
				}).end()
				.find('article').css({
					'overflow':'hidden',
					'height':$preview_height+'px'
				});
				
			// function to update news
			var update_news = function($index){
				if($index != undefined){
					$news_counter = $index;
				}
				var $id_news = ($news_counter%$num_articles);		
				$news_counter = $news_counter+1;
				$preview.children('.article').hide();
				$($preview.children('.article')[$id_news]).fadeIn('slow');
				$elm.children('article').css('background','#fff');	
				$($elm.children('article')[$id_news]).css('background','#eee');	
			}
			update_news();
			var $timer = setInterval(function(){update_news()}, opts.timeout);
			var $timer_hover;
			$elm.hover(
				function(){
					clearInterval($timer);
				},
				function(){
					$timer = setInterval(
						function(){
							update_news();
						}, 
						opts.timeout
					);
				}
			);
			$elm.find('article.news').each(function($index){
				$(this).hover(
					function(){
						$(this).toggleClass("hover");
						clearTimeout($timer_hover);
						$timer_hover = setTimeout(
							function(){
								if( $elm.find('article.news:eq('+$index+')').hasClass('hover') ){
									update_news($index);
								}
							}, '400');
					},
					function(){
						$(this).toggleClass("hover");
					}
				);
			});
		});
  };
})(jQuery);

