/*
* News Ticker
* Chris Froese
* 
*/
(function($) {
jQuery.fn.ticker = function(options) {
	
	// Default options
	var defaults = {
		itemWraper		:	"li",
		showItems		:	1,
		transition		:	'fade',
		transitionSpeed	:	500,
		interval		:	5000,
		pauseOnHover	:	true,
		debug			:	false
	};	
	
	var options = $.extend(defaults, options);
	
	
	next = function(_this) {
		_debug("next() called.");
		
		var $this = $(_this);
		
		if($this.data('paused')) 
		{
			_debug('Paused. Returning from next().');
			return;
		}
		
		if ($this.data('nextItem') >= $this.data('itemsLength'))
		{
			$this.data('prevItem', $this.data('itemsLength') - 1);
			$this.data('currentItem', 0);
			$this.data('nextItem', 1);
		}
		else
		{
			$this.data('prevItem', $this.data('currentItem'));
			$this.data('currentItem', $this.data('nextItem'));
			$this.data('nextItem', $this.data('nextItem') + 1);
		}
		
		$this.find(options.itemWraper+':eq('+$this.data('prevItem')+')').fadeOut(options.transitionSpeed);
		$this.find(options.itemWraper+':eq('+$this.data('currentItem')+')').fadeIn(options.transitionSpeed);
	};
	
	previous = function(_this) {
		_debug("previous() called.");
		
		var $this = $(_this);
		
		if($this.data('paused')) 
		{
			_debug('Paused. Returning from previous().');
			return;
		}
		
		_currentItem = $this.data('currentItem');
		
		if($this.data('prevItem') == 0)
		{
			$this.data('currentItem', 0);
			$this.data('prevItem', $this.data('itemsLength') - 1);
			$this.data('nextItem', 1);
		}
		else
		{
			$this.data('nextItem', $this.data('currentItem'));
			$this.data('currentItem', $this.data('prevItem'));
			$this.data('prevItem', $this.data('currentItem') - 1);
		}
		
		$this.find(options.itemWraper+':eq('+$this.data('currentItem')+')').fadeIn(options.transitionSpeed);
		$this.find(options.itemWraper+':eq('+_currentItem+')').fadeOut(options.transitionSpeed);
	};
	
	_debug = function(message) {
		if (options.debug)
		{
			console.log(message);
		}
		return;
	};
	
	return this.each(function() {
		
		var $this = $(this);
		
		var data = {
			currentItem	:	0,
			prevItem	:	0,
			nextItem	:	1,
			paused		:	false,
			itemsLength	:	$(options.itemWraper, $this).length
		};
		// prevItem is last item
		data.prevItem = data.itemsLength - 1;
		
		// assign this element data
		$this.data(data);
		
		// make sure all the matched elements are hidden
		$(options.itemWraper, $this).each(function() { 
			$(this).hide();
		});
		
		// bind mouse event
		if(options.pauseOnHover)
		{
			$this.bind({
				mouseenter: function() { $this.data('paused', true); },
				mouseleave: function() { $this.data('paused', false); }
			});
		}
		
		// show the first item
		$this.find(options.itemWraper+':eq(0)').fadeIn(options.transitionSpeed);
		
		// set the timer
		var intervalId = setInterval(previous, options.interval, this);
	});
	
};
})(jQuery);
