// jquery.arrayfade.js
// James Home, http://jameshome.com
//
// based on jquery.innerfade.js by Torsten Baldes, http://medienfreunde.com

(function($) {

    $.fn.arrayfade = function(options) {
        return this.each(function() {   
            $.arrayfade(this, options);
        });
    };

    $.arrayfade = function(container, options) {
      var settings = {
          'speed':            'slow',
          'timeout':          2000,
          'containerheight':  'auto',
          'images':           0
      };

      if (options)
          $.extend(settings, options);

      elements = settings.images;

      if (elements.length > 1) {
        $(container).css('position', 'relative').css('height', settings.containerheight).addClass(settings.runningclass);

				var current = Math.floor ( Math.random () * ( elements.length ) );

        currentimg = $("<img>").attr({"src": elements[current]});
        currentimg.appendTo(container);
        var zindex = elements.length - elements[current];
        $(currentimg).css('z-index', zindex).css('position', 'absolute').hide();            

        currentimg.fadeIn(settings.speed);
        
        if ((current + 1) < elements.length) {
            current = current + 1;
        } else {
            current = 0;
        }
        
        currentimg = $("<img>").attr({"src": elements[current]});

				setTimeout(function(){
					$.arrayfade.next(elements, container, settings, (current + 1) %  elements.length, currentimg);
				}, settings.timeout);
		  }
    };

    $.arrayfade.next = function(elements, container, settings, current, lastimg) {
      
      currentimg.appendTo(container);
      var zindex = elements.length - elements[current];
      $(currentimg).css('z-index', zindex).css('position', 'absolute').hide();            
    
      $(lastimg).fadeOut(settings.speed);
      
      $(currentimg).fadeIn(settings.speed, function() {
				removeFilter($(this)[0]);
			});
			
      if ((current + 1) < elements.length) {
          current = current + 1;
      } else {
          current = 0;
      }
      currentimg = $("<img>").attr({"src": elements[current]});

      setTimeout((function() {
          $.arrayfade.next(elements, container, settings, current, currentimg);
      }), settings.timeout);
    };

})(jQuery);

// **** remove Opacity-Filter in ie ****
function removeFilter(element) {
	if(element.style.removeAttribute){
		element.style.removeAttribute('filter');
	}
}

