(function($) {
	
	$.fn.carousel = function(options) {
		var dontSpazzClick = false;
		var config = {
			items: "",
			autoStart: false
		};
		var opts = $.extend({}, config, options);
		var totalCount = this.length;
		var triggers = this.parent().not('.first, .last').find('a');
		var count = triggers.length;
		var autoRotate;
		
		var gotoIndex = function(i, isAuto) {
			
			dontSpazzClick = true;
			
			//Finds the set that is being viewed
			var oldIndex = triggers.index(triggers.filter('.on'));
			
			//Hides old image
			$(opts.items).eq(oldIndex).stop().fadeOut('slow', function() {
				$(opts.items).eq(i).fadeIn('slow', function() {
					dontSpazzClick = false;
					if(isAuto === true) {
						autoRotate = (i + 1) < count ? setTimeout(function() { gotoIndex((i + 1), true); }, 10000) : setTimeout(function() { gotoIndex((0), true); }, 10000);
					}
					triggers.eq(oldIndex)[0].className = "";
					triggers.eq(i)[0].className = "on";
				});
			});
		};
		
		//Kick off
		if(opts.autoStart && !dontSpazzClick) {
			autoRotate = setTimeout(function() { gotoIndex(1, true); }, 10000);
		}
		
		return this.each(function(i, ele) {
			$(ele).click(function() {
				clearTimeout(autoRotate);
				if(dontSpazzClick === false) {
					if(i > 0 && i < totalCount - 1) {
						gotoIndex(i - 1, false);
					} else {
						var oldIndex = triggers.index(triggers.filter('.on'));
						if(i == 0) {
							oldIndex > 0 && oldIndex < count ? gotoIndex(oldIndex - 1, false) : gotoIndex(count - 1, false);
						} else {
							oldIndex < count -1 ? gotoIndex(oldIndex + 1, false) : gotoIndex(0, false);
						}
					}
				}
				return false;
			});
		});
	};
	
})(jQuery);
