var Features = Class.create({
  initialize: function(element) {
    this.element  = $(element);
    this.features = this.element.getElementsBySelector("ul a").map(function(el) { 
      return new Features.Feature(el, this);
    }.bind(this));
    this.select(this.features.first());
  },
  select: function(feature, delay) {
    if (feature != this.activeFeature) {
      if (this.activeFeature) this.activeFeature.hide();
      this.activeFeature = feature.show();
      this.timedNext(delay);
    }
  },
  next: function() {
    index = this.features.indexOf(this.activeFeature);
    this.select(this.features[index==this.features.length-1 ? 0 : index+1]);
    this.timedNext();
  },
  timedNext: function(delay) {
    window.clearTimeout(this.timer);
    this.timer = this.next.bind(this).delay(delay || 5);
  }
});

Features.Feature = Class.create({
  initialize: function(tab, features) {
    this.features = features;
    this.tab      = tab;
    this.element  = $(this.tab.href.split("#").last());
    this.active   = this.element.visible();
    
    this.tab.observe("click", this.onSelect.bindAsEventListener(this));
  },
  show: function() {
    if (this.showFX) this.showFX.cancel();
    this.showFX = new Effect.Appear(this.element, {duration: 1});
    this.tab.addClassName("active");
    return this;
  },
  hide: function() {
    if (this.hideFX) this.hideFX.cancel();
    this.hideFX = new Effect.Fade(this.element, {duration: 1});
    this.tab.removeClassName("active");
    return this;
  },
  onSelect: function(event) {
    event.stop();
    this.tab.blur();
    this.features.select(this, 10);
  }
});


document.observe("dom:loaded", function() {
  var features = $("features");
  if (features) new Features(features);
});