// There are lots of image cross faders out there. This is designed to crossfade a lot of images, arranged into groups
// It only fades one image at a time, avoiding the jumpiness of simultaneous animations
// Options:
// duration: {Number} ms  over which to fade the images.

(function($){

$.fn.random = function (){ // pick a random element. Note: no error checking. jQuery is a Monad!
  return this.eq(Math.floor(Math.random()*this.length));
};

// I keep getting incorrect results with fadeIn/FadeOut, so I manipulate opacity directly.
$.fn.multifader = function(opts){
	var containers = this.filter(function() {return $(this).children().length > 1}); // just get elements that have children to fade
	if (opts == 'stop'){
		containers.data('multifader', 'stop').children.stop(true, true);
	} else {
		containers.each(function(){$(this).children(':not(:last)').css({opacity: 0.01})});
		opts = $.extend({}, arguments.callee.defaults, opts);
		fade();
	}
  return this;
	
	function fade(){
		if (containers.data('multifader') == 'stop') return;
		var container = containers.random(), el = container.children().random();
		el.siblings().animate({opacity: 0.01}, opts.duration).end().animate({opacity: 1}, opts.duration, fade);
	}
};

$.fn.multifader.defaults = { duration: 1000 };

})(jQuery);;

