(function($) {

	$.fn.imagefader = function(options) {
		var settings = {fadeSpeed: 1000, rotateSpeed: 5000};
		options = $.extend(settings, options);
		
		var $images = this,
				current = 0,
				rotateInterval = null;
		
		// Fade in from nothing.
		transition(null, 0);
		// Start rotation timer.
		rotateInterval = setInterval(rotate, options.rotateSpeed);
		
		function rotate() {
			var next = current + 1;
			if (next >= $images.length) {
				next = 0;
			}
			transition(current, next);
			current = next;
		}
		
		function transition(from, to) {
			if (from === null) {
				$images.css({display: 'none'});
			} else {
				var $current = $images.eq(from);
				$images.not($current).css({display: 'none'});
				$current.css({zIndex: 0});
			}
			var $next = $images.eq(to);
			$next.css({zIndex: 1});
			$next.fadeIn(options.fadeSpeed);		
		}
	}
	
})(jQuery);
