var ImageRotator = Class.create({
  config: {},
  
  //private
  active_index: 1,
  count:   false,
  timeout: false,
  
  //constructor
  initialize: function(config) {
    var THIS = this;
    this.config = $H({
      fadertimeout: false,
      image_class : 'image_class'
    }).merge(config).toObject();
    
    this.count = $$('.' + this.config['image_class']).length;
    window.onload = function () { THIS.init(); };
  },

  init: function () {
    var THIS = this;
    this.timeout = setTimeout(function () { THIS.rotate(); }, THIS.config['fadertimeout']*1000);
  
    for (var i = this.active_index + 1; i <= this.count; i++) {
      $('header-' + i).hide();
    }
  },
  
  rotate: function (new_active) {
    var THIS = this;
    var out_image = $('header-' + this.active_index);
    
    if (!new_active) {
      new_active = this.active_index + 1;
      if (new_active > this.count) {
        new_active = 1;
      }
    }
    
    var in_image = $('header-' + new_active);
    
    //hides the previous image only if it's not the same as the that must be displayed
    if (this.active_index != new_active) {
      out_image.fade();
    }
    
    in_image.appear();
    
    this.active_index = new_active;
    this.timeout = setTimeout(function () { THIS.rotate(); }, this.config['fadertimeout']*1000);
  },
  
  activate: function (image_index) {
    if(this.timeout) clearTimeout(this.timeout);
    this.rotate(image_index);
  },

  toggle: function () {
    var THIS = this;
    
    if(this.timeout) {
      clearTimeout(this.timeout);
      this.timeout = false;
    }
    else {
      this.timeout = setTimeout(function () { THIS.rotate(); }, this.config['fadertimeout']*1000);
    }
  }
  
});
