/**
 * Fader
 *
 * provides ability to cycle through a list of images
 * each time the funciton runs the last image is faded
 * out and the new image is faded in
 */
var Fader = Class.create({
    
    /**
     * initialize
     *
     * sets up the fader object
     */
    initialize: function(){
      
        // setup default config (10 seconds, currently on image 0)
        this.timeout  = 10000;
        this.currImg  = 0;
        this.fadeTime = 1.0;
        this.images   = new Array();
        
        return this;
      },
      
      /**
       * setTimeout
       *
       * updates the time between changes (default is 10)
       *
       * @param int newSeconds the new interval in seconds
       */
      setTimeout: function(newSeconds){
      
        // try to retrieve number
        newSeconds = parseInt(newSeconds);
      
        // update
        if( newSeconds > 0 )
          this.timeout = newSeconds * 1000;
          
        return this;
      },
      
      /**
       * setFade
       *
       * sets the time the fade process takes
       * default is 1.0 seconds
       *
       * @param float newFade new time in seconds
       */
      setFade: function(newFade){
        
        // try to retrieve number
        newFade = parseFloat(newFade);
        
        if( newFade > 0 )
            this.fadeTime = newFade;
            
        return this;
      },
      
      /**
       * addImage
       *
       * adds an image to the list
       * you should specify the image that is visible first
       * all other images should be set display: none in the html
       *
       * @param string elementId id of the img element
       */
      addImage: function(elementId){
        
        // check it's an image and add to list
        // (this class could probably be used with other elements?)
        if( $(elementId) && $(elementId).tagName == 'IMG' )
          this.images[this.images.length] = $(elementId);
          
        return this;
      },
      
      /**
       * start
       *
       * starts the fader running
       * should be called after all images have been added, interval set etc
       */
      start: function(){
      
        // set timeout this call ourself
        setTimeout(this._change.bind(this), this.timeout);
      },
      
      /**
       * change
       *
       * changes the currently visible image
       * will fade the images using scriptaculous
       */
      _change: function(){
      
        // get next image id
        nextImage = this.currImg + 1;

        // check
        if( nextImage == this.images.length )
          nextImage = 0;
        
        // change image
        this.images[this.currImg].fade({ duration: this.fadeTime });
        this.images[nextImage].appear({ duration: this.fadeTime });
        
        // update current image
        this.currImg = nextImage;
        
        // run again
        this.start();
      }
});
