var ImageRotator = Class.create({
  config: {},
  
  //private
  active_index: 1,
  count:   false,
  timeout: false,
  debugfield: false,
  
  //constructor
  initialize: function(config) {
    this.config = $H({
      fadertimeout: false,
      image_class : 'image_class',
      debug: false
    }).merge(config).toObject();
    
    Event.observe(window, 'load', this.init.bind(this));
  },

  init: function () {
    if (this.config['debug']) {
      this.debugfield = $(this.config['debug']);
    }
    
    this.count = $$('.' + this.config['image_class']).length;
  
    for (var i = this.active_index + 1; i <= this.count; i++) {
      $('image' + i).hide();
    }
    
    this.timeout = setTimeout(this.rotate.bind(this, false), this.config['fadertimeout']*1000);
  },
  
  rotate: function (new_active) {
    var out_image = $('image' + this.active_index);
    if (!new_active) {
      new_active = this.active_index + 1;
      if (new_active > this.count) {
        new_active = 1;
      }
    }
    
    this.debug('switching to ' + new_active);

    $('carrousel-besturing').className='p' + new_active;
    
    var in_image = $('image' + new_active);
    
    //hides the previous image only if it's not the same as the that must be displayed
    if (new_active < this.active_index) {
      //new image is below old one
      in_image.show();
      out_image.fade();
    }
    if (new_active > this.active_index) {
      //new image is above old one
      in_image.appear({
        afterFinish: out_image.hide.bind(out_image)
      });
    }
    
    this.active_index = new_active;
    this.timeout = setTimeout(this.rotate.bind(this, false), this.config['fadertimeout']*1000);
  },
  
  activate: function (image_index) {
    this.clearTimeout();
    this.rotate(image_index);
  },

  toggle: function () {
    if(this.timeout) {
      $('carrousel-besturing').className='p6';
      
      this.clearTimeout();
      this.timeout = false;
    }
    else {
      $('carrousel-besturing').className='p' + this.active_index;
      
      this.timeout = setTimeout(this.rotate.bind(this, false), this.config['fadertimeout']*1000);
    }
  },
  
  clearTimeout: function() {
    if (this.timeout != false) {
      clearTimeout(this.timeout);
      this.timeout = false;
    }
  },
  
  debug: function(message) {
    if (this.debugfield) {
      this.debugfield.value = message;
    }
  }
  
});