/*
	Ticker jQuery Plugin.
	
	Create a ticker animation which displays each slide for a while before
	advancing to the next.
	
	Usage:
		Call the ticker function on the container element of a set of slide elements.
		
		$("#container").ticker();
		
		Example markup:
		
		<div id="container">
			<div class="item">Item #1</div>
			<div class="item">Item #2</div>
		</div>
			
	Options:
		itemSelector:
			jQuery selector to match the individual slides. Can be null in
			which case the direct child elements will be used.
		
		duration:
			Duration of animate when ticker changes slides.
		
		interval:
			Time taken before a slide automatically advances to the next. Set
			to 0 to disable automatic 
*/

(function($) {
	
	$.fn.ticker = function(options) {
		var opts = $.extend({}, $.fn.ticker.defaults, options);
		
		// Get the number of elements we are replacing.
		var numReplaced = this.length;
		
		this.each(function(el) {
			var ticker = $(this);
			
			var animating = false;
			var items = opts.itemSelector ? $(opts.itemSelector, this) : ticker.children();
			var scrollWidth = ticker.outerWidth(true);
			var activeItem = 0;
			var interval;
			
			// Set up required CSS.
			ticker.css({overflow: "hidden", position: "relative"});
			items.css({position: "absolute"});
			
			items.each(function(el) {
				if (el != activeItem) {
					$(this).hide();
				}
			});
			
			function play() {
				if (opts.interval < opts.duration) { return; }
				
				interval = setInterval(function() {
					slide(false);
				}, opts.interval);
			}
			
			function pause() {
				clearInterval(interval);
			}
			
			function slide(right) {
				if (animating) { return false; }
				animating = true;
				
				var next = right ? activeItem+1 : activeItem-1;
				next = next.mod(items.length);
				
				var curEl = $(items[activeItem]);
				var nextEl = $(items[next]);
				
				var completes = 0;
				function onComplete() {
					completes++;
					if (completes === 2) {
						curEl.hide();
						activeItem = next;
						animating = false;
					}
				}
				
				nextEl.show();
				nextEl.css("left", right ? -scrollWidth : scrollWidth);
				
				curEl.animate({left: right ? scrollWidth : -scrollWidth}, opts.duration, "linear", onComplete);
				nextEl.animate({left: 0}, opts.duration, "linear", onComplete);
			}
			
			// Bind callback events
			ticker.bind("next", function() {
				pause();
				slide(false);
			});
			
			ticker.bind("prev", function() {
				pause();
				slide(true);
			});
			
			ticker.bind("play", play);
			ticker.bind("pause", pause);
			
			// Start playing automatically.
			play();
		});
		
		return this;
	};
	
	// Allow access to defaults.
	$.fn.ticker.defaults = {
		itemSelector: null,
		duration: 500,
		interval: 5000
	};
	
})(jQuery);

