/**
 * Run slideshow with image download on demand
 *
 * @example jQuery("img").jSlideShow();
 *
 * @name slideShow
 * @type jQuery
 * @param Object	settings (not used yet)
 *								
 * @return jQuery
 * @author Dharma Ferrari (http://www.dharmaferrari.com)
 */

(function($) {

$.fn.jSlideShow = function(imageList, settings)
{
	settings = $.extend({}, $.fn.jSlideShow.defaults, settings);
	
	if(settings.shuffle) {
	  imageList.sort(function() {return 0.5 - Math.random()});
	}
	
  return this.each(
    function()
    {
  	  var $this = $(this);
  	  var parent = $this.parent();
      var imageListIndex = 0;
      
      parent
        .css('height', settings.height)
        .css('width', settings.width)
        .css('overflow', 'hidden')
        .css('background-color', settings.bgColor);
      
      $this.hide();
      
  	  
      /**
       * Bind image load fired on change of src attribute
       *
       */
      $this.load(function () {
        $this.fadeIn(settings.fadeDuration * 1000);
        parent.removeClass(settings.loadingClass);
        
        // swap only if there are more than one pictures
        if(imageList.length > 1) {
          setTimeout(function() {
            if(imageListIndex >= imageList.length-1) {imageListIndex = 0;}
            else {imageListIndex++;}
        
            $this.fadeOut(settings.fadeDuration * 1000, function() {
              parent.addClass(settings.loadingClass);
              $this.attr('src', settings.path + imageList[imageListIndex]);
            })
          },
          settings.imageStillDuration * 1000);
        }
        
      }).error(function () {
        parent.removeClass(settings.loadingClass);
        parent.append('<div id="jssError">' + settings.error404Msg + '</div>');
      }).attr('src', settings.path + imageList[imageListIndex]);
      
	});
};

$.fn.jSlideShow.defaults = {
  width : 400,
  height : 300,
  fadeDuration : .5,
  imageStillDuration : 5,
  loadingClass : 'jssLoading',
  error404Msg : '404: Errore nel caricamento',
  path : 'jssGallery/',
  bgColor : 'rgb(255,255,255)',
  shuffle : false
};

})(jQuery);

