;(function($) {
	$.fn.extend({
		imageRotate: function(args) {
			$this = $(this);
			
			var defaults = {
				start: 1,
				end: 4,
				random: true,
				change: null,
				preload: null,
				seconds: 3
			}
			
			var preloaded = [];
			
			args = $.extend({}, defaults, args);
			
			if (typeof args.change == "function") {
				
				// Stop any previous rotation.
				$this.stopTime("imageRotate");
				
				$this.data("imageRotateNum", args.random
						   ? Math.floor(Math.random() * (args.end - args.start + 1)) + args.start //random start
						   : args.start); // start from beginning
				
				args.change.call($this, $this.data("imageRotateNum"));
				
				if (typeof args.preload == "function") {
					args.preload.call($this, ($this.data("imageRotateNum") == args.end ? args.start : $this.data("imageRotateNum") + 1));
				}
				
				$this.everyTime(args.seconds * 1000, "imageRotate", function() {
					var nextnum = $this.data("imageRotateNum") + 1;
					if (nextnum > args.end) {
						nextnum = args.start;
					}
					$this.data("imageRotateNum", nextnum);
					args.change.call($this, nextnum);
					
					if (typeof args.preload == "function") {
						args.preload.call($this, (nextnum == args.end ? args.start : nextnum + 1));
					}
				});
			}
		}
	});
})(jQuery);
