
/**
 * Creates a ticker, scrolling elements vertically.
 * 
 * speed		speed value to use, default: 0.1
 * wait			waiting time in ms, default 4 seconds
 * 
 */
;(function($) {
	// If the UI scope is not available, add it
	$.ui = $.ui || {};
	$.fn.extend({
		ticker: function(options) {
			return this.each(function() {
				if (!$(this).is(".ui-ticker"))
					$.data(this,"ui-ticker", new $.ui.ticker(this,options));
			});
		}
	});

	$.ui.ticker = function(container,options) {
		var cobj = $(container);
		var defaults = {
			speed: 0.1,
			wait: 4000
		};
		var config = $.extend(defaults,options);
		var lastTimeout = null;

		// setup container
		cobj.addClass("ui-ticker").css("overflow", "hidden");
		cobj.children().css("margin-top","0");

		// don't animate when there are too few items
		if(cobj.get(0).scrollHeight <= cobj.height())
			return;

		// mousein/out
	    cobj.mouseenter(function(){
	    	cobj.children().stop();
	    	window.clearTimeout(lastTimeout);
	    });
	    cobj.mouseleave(function(){
	    	lastTimeout = window.setTimeout(function(){animator(cobj.children(":first"));},config.wait/2);
	    });

 		function animator(currentItem) {
			//work out new anim duration
			var distance = currentItem.height();
			var duration = (distance - Math.abs(parseInt(currentItem.css("marginTop")))) / config.speed;

			//animate the first child of the ticker
			currentItem.animate({ marginTop: -distance }, duration, "swing",function() {
				currentItem.appendTo(currentItem.parent()).css("marginTop", 0);

				//recurse
				window.clearTimeout(lastTimeout);
				lastTimeout = window.setTimeout(function(){animator(currentItem.parent().children(":first"));},config.wait);
			});
		};
		window.clearTimeout(lastTimeout);
		lastTimeout = window.setTimeout(function(){animator(cobj.children(":first"));},config.wait);
	};
})(jQuery);

