/*
 * jQuery HBCarousel
 * @requires jQuery v1.4.0+
 *
 * Copyright (c) 2010 James Lee
 * No License
*/

;(function($) {
 	$.fn.extend({
		hbcarousel: function(options) {
			var defaults = {
				fadeInInterval: 1000,
				fadeOutInterval: 1000,
				rotationInterval: 6000
			},

			options = $.extend(defaults, options),

			globalDefaults = {
				totalItems: 0,
				currentIndex: 0,
				nextIndex: 0
			};

			return this.each(function() {
				var $this = $(this),
					$items = $this.find("li"),
					data = {
						$this: $this,
						$items: $items,
						options: options,
						totalItems: $items.length
					};

				data = $.extend(globalDefaults, data);

				// instantiate class
				var carousel = new carouselClass(data);

				// display first item
				if (data.totalItems)
					$($items[0]).show();

				// rotate items
				if (data.totalItems > 1) {
					carousel.createNavigation(data.totalItems);
					$this.next().find("li:eq(0) a").addClass('selected');
					carousel.itemto = window.setTimeout(function() {
						carousel.transitionItem(false);
					}, data.options.rotationInterval);
				}

				// click on navigation
				$this.parents().find("a.itemSelect").bind("click.hbcarousel", function() {
					carousel.transitionItem( $(this).parentsUntil('ul').index() );
					return false;
				});
			});

			function carouselClass(data) {
				this.data = data || null;
				this.itemto = null;

				this.createNavigation = function(totalItems) {
					var $container = this.data.$this,
						html = new Array();
					for (var i=1; i<=totalItems; i++)
						html.push('<li><a href="#" class="itemSelect">'+i+'</a></li>');
					$container.parent().append('<div class="containerNav"><ul>'+html.join('')+'</ul></div>');
				};

				this.transitionItem = function(selectIndex, data) {
					var self = this;
					data = data || this.data;
					if (selectIndex === data.currentIndex) return false;
					window.clearTimeout(this.itemto);
					data.nextIndex = (selectIndex !== false) ? selectIndex : ((data.currentIndex + 1 === data.totalItems) ? 0 : data.currentIndex + 1);
					data.$this.parent().find(".containerNav li a").removeClass('selected');
					data.$this.parent().find(".containerNav li:eq("+data.nextIndex+") a").addClass('selected');
					$(data.$items[data.currentIndex]).stop(true, true).fadeOut(data.options.fadeOutInterval);
					$(data.$items[data.nextIndex]).stop(true, true).fadeIn(data.options.fadeInInterval);
					data.currentIndex = data.nextIndex;
					this.itemto = window.setInterval(function() {
						self.transitionItem(false, data);
					}, data.options.rotationInterval);
				};
			};
		}
	});
})(jQuery);
