/**
 * Tickertape
 * 
 * This plugin is not intended to be a full-fledged tickertape plugin.
 * The jquery plugin method just seemed a good way to write this in. 
 * 
 * expected html
 * -------------
 * <div id="tickertape"><!-- or any other id or class -->
 *   <ul>
 *     <li></li><!-- any number of lists, containing text -->
 *   </ul>
 * </div>
 * 
 * example usage
 * -------------
 * $('#tickertape').tickertape();
 * 
 * You can pause the ticker from outside the script by using the jQuery
 * function trigger('pauseTicker').
 * Unpause with trigger('unpauseTicker').
 * 
 * @author jorn@info.nl
 * @version 0.1
 * @requires jQuery 1.3
 * @copyright 2009 info.nl
 * 
 * @param {int} iTpp Time per pixel (based on speed tests 5000 ms for 500 pixels)
 */
(function($){
	$.fn.tickertape = function(iTpp){
		
		return this.each(function(i, oElem){
		  $elem = $(oElem);
			var $ul = $('ul', $elem);
			var $items = $('li', $ul);
			
			$ul.tickertape = {}; // create object in ul to store data
			
			// make sure ul has dimensions
			$ul.css({
				display: 'block',
				visibility: 'hidden'
			});
			
			// set initial values
			$ul.tickertape.iInitial_left = $elem.width();
			$ul.tickertape.iItems_length = itemsLength($items);
			$ul.tickertape.iTime = $ul.tickertape.iItems_length * iTpp;
			
			$ul.css({
				width: $ul.tickertape.iItems_length +'px',
				visibility: 'visible'
			});
			
			cycle($ul); // go ticker!
		});
		
		/**
		 * 
		 * @param {Object} $ul
		 */
		function cycle($ul)
		{
			$ul.css('left', $ul.tickertape.iInitial_left);
			
			$ul.animate({left:-$ul.tickertape.iItems_length +'px'}, $ul.tickertape.iTime, 'linear', function(){
				setTimeout(function(){
					cycle($ul);
				}, 1000);
			});
		}
		
		/**
		 * Calculate total width of items
		 * @param {Object} items
		 */
		function itemsLength($items)
		{
			var iLength = 0;
			$.each($items, function(){
				iLength += $(this).outerWidth(true); // add up the length
			});
			return iLength;
		}
	} // end $.fn.tickertape
})(jQuery);