var ImageCycler = Class.create({
  initialize: function(elem) {
    this.ads = elem.select('div.cycleable');
    if (this.ads.length <= 1) return;
    this.elem = elem;
    this.elem.makePositioned();
    this.current = 0;
    this.ads.each(function(elem, i) {
      if (i > 0) elem.hide();
    });
    Event.observe(window, 'load', this.setup.bind(this));
  },

  next: function() {
    var current = this.current;
    this.current = this.current == this.ads.length - 1 ? 0 : this.current + 1;
    this.ads[current].fade({ duration: 1, from: 1, to: 0 });
    this.ads[this.current].appear({ duration: 1, from: 0 })
  },

  setup: function() {
    this.ads.invoke('setStyle', { left: 0, position: 'absolute', top: 0 });
    var max = this.ads.max(function(elem) { return elem.getHeight(); });
    this.elem.setStyle({ height: max + 'px' });
    this.interval = setInterval(this.next.bind(this), 7000);
  }
});
