var ElementTransition = Class.create();
Object.extend(ElementTransition.prototype, {
  initialize: function(element, options) {
    this.element = $(element);
    this.element.makePositioned();
    this.options = $H({
      elements_selector: '.transition-element',
      effect: 'appear',
      delay: 8,
      duration: 2,
      even_height: false,
      centered: false,
      condition: function() {return false;}
    }).merge(options);
    this.options['condition'] = this.options['condition'].bind(this);

    this.elements = $$(this.options['elements_selector']);
    this.elements.each(function(e) {
      e.setStyle({
        position: 'absolute',
        top: 0,
        left: 0
      });
    });
    if(this.options['even_height']) {
      var max_height = this.elements.max(function(e) {return e.getHeight()});
      this.elements.each(function(e) {e.setStyle({height: max_height + 'px'})});
      this.element.setStyle({height: max_height + 'px'});
    }
    if(this.options['centered']) {
      this.element.setStyle({
        width: this.elements.max(function(e) {return e.getWidth()})+'px',
        height: this.elements.max(function(e) {return e.getHeight()})+'px'
      });
      this.elements.each((function(e) {
        e.setStyle({
          left: (this.element.getWidth()-e.getWidth())/2 + 'px',
          top: (this.element.getHeight()-e.getHeight())/2 + 'px'
        });
      }).bind(this));
    }
    this.index = 0;
    var delay = this.options['delay'];
    if(delay) new PeriodicalExecuter(this.transition.bind(this), delay);
  },

  transition: function() {
    if(this.options['condition']()) return;
    this.elements[this.index].setStyle({zIndex: 0});
    Effect[Effect.PAIRS[this.options['effect']][1]](
      this.elements[this.index],
      {duration: this.options['duration']});
    this.index++;
    if(this.index >= this.elements.length) this.index = 0;
    this.elements[this.index].setStyle({zIndex: 1});
    Effect[Effect.PAIRS[this.options['effect']][0]](
      this.elements[this.index],
      {duration: this.options['duration']});
  },

  observing_mouse: false,
  last_x: 0,
  last_y: 0,
  over_element: function() {
    if(!this.observing_mouse) {
      this.observing_mouse = true;
      Event.observe(document.body, 'mouseover', (function(e) {
        this.last_x = e.pointerX();
        this.last_y = e.pointerY();
      }).bindAsEventListener(this));
    }
    return Position.within(this.element, this.last_x, this.last_y);
  }
});


