(function( $ ){
	$.fn.rotate = function(t, prev, curr, auto) {
		auto = (typeof(auto) != 'undefined') ? auto : true;
		var group = this;
		
		// Cannot be chained - returns controller object instead
		return new function() {
			var time = t;
			var self = this;
			var updt = true;
			var item;
			var lidx;
			var index = 0;
			
			this.root = group;
			
			this.update = function() {
				// Persist the last item information
				lidx = index;
				var last = item;
				
				// Go to the next item
				item = $(self.root[index++]);
				if((index % self.root.length) == 0) index = 0;
				
				// Run the rotation callbacks for the item
				if(last != null) prev(last, self);
				curr(item, self);
			}
			
			this.start = function() {
				// Start the rotation if and only if not currently running
				if(self.id == 'undefined' || self.id == null) {
					self.id = setInterval(self.update, time);
					if(updt) self.update();
				}
			}
			
			this.stop = function() {
				// Stop the rotation if running
				if(self.id != 'undefined' && self.id != null) {
					clearInterval(self.id);
					self.id = null;
					updt = false;
					setTimeout(function(){updt = true;}, time);
				}
			}
			
			this.goto = function(idx) {
				// Go to a specific index.
				index = idx;
				self.stop();
				self.update();
				self.start();
			}
			
			// Get the current index
			this.index = function() { return lidx; }

			// Set hover function to pause
			this.root.parent().hover(function(){
				self.stop();
			}, function(){
				self.start();
			});
			
			// Start the rotation automatically by default
			if(auto && self.root.length > 1) this.start();
		}
	}
})( jQuery )

