/**
 * Copyright (c) 2009 Bleau A/S (http://www.bleau.dk)
 **/

(function($){
/**
 * Creates an imagefader, fading between elements within a choosen element.
 * 
 * @param Object s (optional) Customize your imagefader.
 * @option speed [3000] The speed in milliseconds between each image fade
 * @option fadeInSpeed [1300] The speed in milliseconds which a "fade-in" lasts
 * @option fadeOutSpeed [1200] The speed in milliseconds which a "fade-out" lasts
 * @option easing: [swing] The style which the fading is done in
 * @option selectorForImages [img] The selector used to specify the elements within the imagefader is applied to.
 * @type jQuery
 * @name imagefader
 * @cat plugins/datePicker
 * @author Sten Hougaard/www.bleau.dk
 * @version 1.0
 * @date 2009.04.20
 *
 * @example $('.fade').imagefader({speed:2000, fadeInSpeed:1300, fadeOutSpeed:1200});
 * @desc Activates an imagefader for the elements within the element with the class "fade".
 **/
 $.fn.imagefader = function(options) {   
    var iTotal, iCurrent = 0;
    var images;
    var oVisible = {opacity: 1};
    var oHidden = {opacity: 0};
    
    var defaults = {
     speed: 3000,   
     fadeInSpeed: 1300,   
     fadeOutSpeed: 1200,   
     easing: 'swing',
     selectorForImages: 'img'  
    };   
    var options = $.extend(defaults, options); 

    return this.each(function() {   
      var obj = $(this);
      
      images = $(options.selectorForImages, obj);
      iTotal = images.length;
      var offset = $(images[0]).offset();
      $(images[0]).css({
        zIndex: 2
      });
      images.not(':first').css({
        opacity: 0,
        position: 'absolute',
        marginLeft: (-$(images[0]).width())+'px',
        marginTop: '0px',
        zIndex: 1
      });
      window.setTimeout(function() {fade(obj)}, options.speed);
      
    });
    
    function fade(obj) {
      $(images[iCurrent]).animate(oHidden, options.fadeOutSpeed, options.easing).css('z-index', 1);
      iCurrent++;
      if (iCurrent>iTotal-1) {
        iCurrent = 0;
      }

      $(images[iCurrent]).animate(oVisible, options.fadeInSpeed, options.easing, function() {
        window.setTimeout(function() {fade(obj)}, options.speed);
      }).css('z-index', 2);
    }

 };   
})(jQuery);  