(function($){ 
 	$.fn.newsScroller = function(options){
		var options = $.extend({ 
      				scrollInterval: 30,
      				scrollStepSize: 1
    			}, options);
		
		return $(this).each(function(){
			
      		var scroller = $(this),
				scrollerHeight = scroller.height(),
				scrollContainer = $('.scroll-container', scroller),
				totalItemsHeight = 0,
				scrollY = 0,
				scrollPaused = false,
				slideIn = false,
				scrollerInt = null,
				el = null;
				
			var defaultHtml = scrollContainer.html();
				
				
			var doScroll = function(){
				if(scrollPaused || !scroller.is(':visible')) return;
				
				scrollY -= options.scrollStepSize;
				
				var el = $('*:eq(0)', scrollContainer);
				el.css({marginTop: scrollY + 'px'});
				
				if(Math.abs(scrollY) > elRealHeight(el)){
					el.css({marginTop: 0});
					scrollContainer.append(el);
					scrollY = 0;
					
					if(slideIn)	el.css({marginTop: '150px'}).animate({marginTop: 0}, 1500);
				}
			}
			
			var startScroll = function(){
				scrollerInt = setInterval(function(){ doScroll(); }, options.scrollInterval);
			}
			
			var restartScroll = function(){
				clearInterval(scrollerInt);
				scrollContainer.html(defaultHtml);
				scrollPaused = false;
				scrollY = 0;
				startScroll();
			}
			
			var elRealHeight = function(obj){
				var elHeight = obj.height();
				elHeight += isNaN(parseInt(obj.css('padding-top'))) ? 0 : parseInt(obj.css('padding-top'));
				elHeight += isNaN(parseInt(obj.css('padding-bottom'))) ? 0 : parseInt(obj.css('padding-bottom'));
				elHeight += isNaN(parseInt(obj.css('margin-bottom'))) ? 0 : parseInt(obj.css('margin-bottom'));
				return elHeight;
			}
		
			scrollContainer.children().each(function(){
				totalItemsHeight += elRealHeight($(this));
			});
			
			if(totalItemsHeight > scrollerHeight - 20){
				scrollContainer.css({height: (scrollerHeight /*- 20*/) + 'px'});
				
				if(totalItemsHeight < scrollerHeight + 20) slideIn = true;
				
				scroller.bind('mouseover', function(){
					scrollPaused = true;	
				}).bind('mouseleave', function(){ 
					scrollPaused = false;
				}).bind('pauseScroll', function(){ 
					scrollPaused = true; 
				}).bind('resumeScroll', function(){ 
					scrollPaused = false; 
				}).bind('restartScroller', function(){ 
					restartScroll(); 
				});
				
				$(window).bind('blur', function(){ 
					scrollPaused = true;	
				}).bind('focus', function(){ 
					scrollPaused = false; 
				});
				
				startScroll();
				
			}
				
    	});
		
	}; 
})( jQuery );
