var DYKShow = Class.create();
DYKShow.prototype = {
  initialize: function(element, options) {
    this.element = $(element);
    this.options = Object.extend({className: 'dyk', duration: 10}, options);
    this.dyks = document.getElementsByClassName(this.options.className, this.element);

    this.prepareDYKs();
    this.registerCallback();
  },

  prepareDYKs: function() {
    this.currentDYK = this.dyks.first();
    this.element.style.position = 'relative';
    this.element.style.height = this.dyks.max(function(dyk) {
      var visible = Element.visible(dyk), height;
      Element.setStyle(dyk, {position: 'absolute', width: '100%', left: '0px'});
      if (!visible) Element.show(dyk);
      height = Element.getHeight(dyk);
      if (!visible) Element.hide(dyk);
      return height;
    }).toString() + 'px';
  },

  nextDYK: function() {
    i = Math.round(Math.floor(Math.random()*this.dyks.length));
    return this.dyks[i];
  },

  registerCallback: function() {
    window.setTimeout(this.tick.bind(this), this.options.duration * 1000);
  },

  tick: function() {
    var currentDYK = this.currentDYK, nextDYK = this.nextDYK();

    if (currentDYK != nextDYK) {
      new Effect.Parallel([
        new Effect.Fade(currentDYK, {sync: true}),
        new Effect.Appear(nextDYK, {sync: true})
      ], {
        duration: 2,
        afterFinish: (function(effect) {
          this.currentDYK = nextDYK;
          this.registerCallback();
        }).bind(this)
      })
    }
    else
    {
      this.currentDYK = nextDYK;
      this.registerCallback();
    }
  }
}
