// based on Image Cross Fade Redux--http://slayeroffice.com/code/imageCrossFade/xfade2.html
// and jQuery slideshow--http://www.gizone.co.uk/web-design/jquery-plugins/simple-jquery-slideshow/
// container is assumed to have appropriately styled img's, each of which is faded in & out in turn
// Options:
// pause: {Number} minimum number of ms to show the picture. Default: 1000.
// random: {Number} 0 to this number will randomly be added to pause. Default 0.
//  This keeps all the xfaders on a page from fading at the same time.
// fadeTime: {Number} ms for the fade effect. Default: 2000.
// fadeIn: {Boolean} true to have the images start invisible and fade in. Default: false;
// the Xfade object is attached to each container, so you can use $('.made_xfade')[0].xfade.stop() and .start()

(function($){

$.fn.xfade = $.extend(function(opts){
  opts = $.extend({}, arguments.callee['default'], opts);
  return this.each(function(){
    this.xfade = new $.fn.xfade.Xfade(this, opts);
  });
},{ // option sets
  'default': {pause: 1000, random: 0, fadeTime: 2000, fadeIn: false},
  random: {pause: 100, random: 4000},
  randomFadein: {pause: 100, random: 4000, fadeIn: true},

  // constructor
  Xfade: function(container, opts){
    var imgs = $.map($('img',container).hide(), '$(a)'); // turn imgs into an array of jquery objects, each with one image
    var current = imgs.length-1;
    if (current == -1) return; // no images
    if (!opts.fadeIn) imgs[current].show();

    this.start = function(){
      imgs[current].filter(':visible').fadeOut(opts.fadeTime);
      current = imgs[current+1] ? current+1 : 0;
      imgs[current].fadeIn(opts.fadeTime);
      if (imgs.length == 1) return; // just one image? show it and stop
      timer = setTimeout(arguments.callee, opts.fadeTime+opts.pause+opts.random*Math.random()); // wait for the fade to end, then pause
    } // start

    this.stop = function(){
      clearTimeout (timer);
      timer = null;
    }; // stop

    this.isStopped = function() {return timer == null};

    var timer = setTimeout(this.start, opts.random*Math.random()); // start fading
  } // Xfade
});

})(jQuery);