/**
* 
* @package     rpa.jquery
* @author      Adrian Hall, RPA Code Ltd
* @copyright   Copyright (c) 2010, RPA Code Ltd
* @url         http://www.rpacode.co.uk
*/

jQuery.fn.ticker = function(options) {
	  
		
	
		var defaults = { 
				align: 'vertical',
				width: 300, 
				height: 300, 
				speed: 2000, 
				delay: 100, 
				easing: 'linear'
			  };
		
		
		//DEFAULT SETTINGS AND OVERRIDE
		settings = jQuery.extend(defaults, options);
  	
		if(settings.align != 'vertical')
			settings.align = 'horizontal'; 
		
		return this.each(function(){
			   
			 var target = $(this); 
			 
			 
			 target.height((settings.align=='vertical' ? settings.height : target.height()))
		  			.width((settings.align!='vertical' ? settings.width : target.width()))
		  			.addClass('ticker_wrapper');
		  	
		  		//foreach div within the wrapper, we need to stack them up, up, up. 
			 	target.children().wrapAll('<div class="ticker_items"></div>').wrap('<div class="ticker_item '+settings.align+'"></div>'); 
			 	
			 	
			 	var items = target.children('.ticker_items'); 
			 	
			 	
			 	if(items.children().length >1 && items.height() > settings.height)
			 	{
				 	//now start them spinning. 
				 	/*
				 	 * to do this, we'll move the div up until the SECOND item has an offset of 0, then we'll reset the position and move the top item to the bottom. 
				 	 */
			 		
			 		items.bind('mouseenter', function(evt)
				 			{
				 				//pause the animation
								//topitem.remove().hide().appendTo(items).fadeIn(100); 
								//items.css('top', 0);
			 					//TODO: what it first item more than halfway shown? Would be nice to animate up to that level, remove, append and set top to 0. 
				 				items.stop(true);
				 				items.animate({top:0}, 100); 
				 			})
				 			.bind('mouseleave', function(evt)
				 			{
				 				//resume the animation
				 				tickerrotate(items, settings);
				 			}); 
				 	setTimeout(function(){tickerrotate(items, settings); }, settings.delay); 
				 	
			 		
			 	}
			 	
			 	
	  
	  		});

		
		
		
};

function tickerrotate (items, settings)
{
	topitem = items.children(':first');
		
		items.animate({
			top: -1*topitem.height()
			
		}, settings.speed, settings.easing, function()
				{
					//move the first to the last and then rerun. 
					topitem.remove().hide().appendTo(items).fadeIn(100); 
					items.css('top', 0);
					tickerrotate(items, settings); 
				} );
		
		
}; 
