/**
 * Simple HTML element rotator
 */

var Loop = Class.create({

    initialize: function (elems, options) 
    { 
        this.bDebug = false;
        
        // animation settings
        this.duration = options['duration'] ? options['duration'] : 1;
        this.delay = options['delay'] ? options['delay'] : 6;
    
        this.current = null;
        this.timeoutId = '';
        
        this.aElems = elems;
        
        // launches loops
        this.show(0);
    },

    next: function ()
    {
      this.debug('current: ' + this.current);
    
      if (this.current == this.aElems.length-1) {   // if end of the array...
        this.nextKey = 0;               //... back to the beginning
      } else { 
        this.nextKey = parseInt(this.current)+1;
      }
      
      this.debug('next: ' + this.nextKey);
      
      if (this.aElems[this.nextKey]) {
          this.show(this.nextKey);
      }
    },
    
    show: function (key)
    {
      if (this.aElems[key]) {
        
          this.loop('stop');
        
          this.debug('showing: ' + this.aElems[key]);
          this.aElems[key].appear({duration: this.duration});
        
          if (this.aElems[this.current])  {
            this.aElems[this.current].fade({duration: this.duration});
          }
          
          this.current = key;
          
          if (this.aElems.length > 1) {
              this.loop('start');
          }
      }
    },
    
    loop: function (action)
    {
        if (action == 'start') {
            this.timeoutId = this.next.bind(this).delay(this.delay);
            this.debug('loop start');
        } else if (action == 'stop') {
              if (this.timeoutId) clearTimeout(this.timeoutId);
              this.debug('loop stop');
        }
    },
    
    /*
     * debugging
     */
    debug: function (v)
    {
        if (typeof(console) != 'undefined' && this.bDebug) {    //firebug installed
            console.debug(v);
        } else if (this.bDebug) {
            alert(v);
        }
    }
});
