// depends on dimensions plugin
;(function($){
	$.fn.liScroll = function(settings) {
		settings = $.extend({
				travelocity: 0.03
			}, settings);
		return this.each(function() {
			var $strip = $(this);
			$strip.addClass("newsticker")
			var lis = $strip.find("li");
			$strip.css({width: (lis.length*2000)+'px'}); // sperando che gli item non superino questa lunghezza...
			var stripWidth = 0;
			lis.each(function(i){
				stripWidth += $(this).outerWidth();
			});
			// $strip.width(stripWidth);
			$strip.css({width: stripWidth+'px'});
			
			var $mask = $strip.wrap("<div class='mask'></div>");
			var $tickercontainer = $strip.parent().wrap("<div class='tickercontainer'></div>");
			var containerWidth = $strip.parent().parent().innerWidth();	//a.k.a. 'mask' width
			var totalTravel = stripWidth+containerWidth;
			var defTiming = totalTravel/settings.travelocity;
			
			var timer = false;
			function scrollnews(spazio, tempo) {
				if (timer) {
					clearTimeout(timer);
					timer = false;
				}
				// per sicurezza metto anche un timeout, non si sa mai: magari non viene chiamata correttamente la callback...
				timer = setTimeout(
						function(){
							timer = false;
							$strip.stop();
							$strip.css({left: containerWidth});
							scrollnews(totalTravel, defTiming);
						},
						tempo+20
					);
				$strip.stop();
				$strip.animate(
					{
						left: '-=' + spazio
					},
					{
						duration: tempo,
						easing: "linear",
						complete: function() {
							if (timer) {
								clearTimeout(timer);
								timer = false;
								$strip.stop();
								$strip.css({left: containerWidth});
								// devo ritardare leggermente, altrimenti non riparte o.o'
								setTimeout(function() {
										scrollnews(totalTravel, defTiming);
									}, 10);
							} else {
								return false;
							}
						}
					}
				);
			}
			$tickercontainer.hover(function() {
					$strip.stop();
					if (timer) {
						clearTimeout(timer);
						timer = false;
					}
				},
				function() {
					var offset = $strip.offset();
					var residualSpace = offset.left + stripWidth;
					var residualTime = residualSpace/settings.travelocity;
					scrollnews(residualSpace, residualTime);
				}
			);
			$strip.css({left: containerWidth});
			scrollnews(totalTravel, defTiming);
		});
	};
})(jQuery);

