/* Description  : Very basic jQuery image slideshow that fades between all <img>
 *                within an element, such as a <div>.
 * Author       : Travis Haynes <travis.j.haynes@gmail.com>
 * Last Updated : Fri Apr 30 2011
 * 
 * Usage (with options and default values):
 *   $(".slideshow").startSlideshow({
 *     delay: 3000,     // Delay between frames
 *     duration: 'slow' // Duration of the fade animation
 *   });
 * 
 * At least 2 <img> tags must be present, or nothing happens, and a null value
 * is returned.
 * 
 */
 
(function( $ ){
  $.fn.startSlideshow = function(options) {
    var settings = $.extend({
      delay: 3000,
      duration: 'slow'
    }, options || {});
    
    if (this.length == 1) {
      if (this.find("img").length > 1) {
        var div = this;
        this.addClass("active");
        this.find("img:last").addClass("active");
        this.find("img").not(":last").hide(settings.duration);
        this.find("img:last").fadeIn(settings.duration, function(){
          setTimeout(
            function(){
              div.continueSlideshow(options);    
            },
            settings.delay
          );
        });
      } else {
        return null;
      }
    } else if (this.length > 1) {
      this.each(function(){
        $(this).startSlideshow(options);
      });
    } else {
      return null;
    }
    
    return this;
  }
  
  $.fn.continueSlideshow = function(options) {
    var settings = $.extend({
      delay: 3000,
      duration: 'slow'
    }, options || {});
    
    var active = this.find("img.active"),
        count  = this.find("img").length,
        index  = this.find("img").index(active),
        div    = this;
    
    index += 1;
    if (index > count-1) { index = 0; }
    var next = div.find("img:eq(" + index + ")");
    
    active.removeClass("active");
    next.addClass("active");
    
    active.fadeOut(settings.duration);
    next.fadeIn(settings.duration, function(){
      setTimeout(
        function(){
          div.continueSlideshow(options);
        },
        settings.delay
      );
    });

    return this;
  };
})( jQuery );

