(function($) {
	function _step(el, options) {
		var nextEl = el.nextInCrossfade;
		if(!nextEl)
			return;
	
		var cur = $(el);		
		var next = $(nextEl);
		cur.animate({opacity: 0}, options.fade);
		next.show();
		next.animate({opacity: 1}, options.fade, function() {
			cur.hide();
			setTimeout(function() {_step(nextEl, options);}, options.pause);
		});	
	}

	$.fn.crossfade = function(fadeDuration, pauseDuration, options) {
		var defaults = {
			fade: fadeDuration,
			pause: pauseDuration,
			cycle: true,
			randomStart: false
		};
		var options = $.extend(defaults, options);

		var startIdx = (!options.randomStart ? 0 : Math.floor(Math.random() * this.length));
		var idx = 0;
		var prev, first, start;
		
		//show first element, hide all others,
		//forward-chain elements
		this.each(function() {
			if(idx == 0)
				first = this;
			
			if(idx != startIdx)
				$(this).hide().css("opacity", 0);
			else {
				$(this).css("opacity", 1).show();
				start = this;
			}

			if(prev)
				prev.nextInCrossfade = this;
			prev = this;
			idx++;
		});
		if(prev && options.cycle)
			prev.nextInCrossfade = first;
		
		//start first pause timeout
		if(this.length > 1)
			setTimeout(function() {_step(start, options);}, options.pause);
 
		return this;
	};
})(jQuery);

