/**
 * Does nothing other than find all elements with the class popup and
 * setup events so that whenever the parent element to the popup is
 * moused over the popup with display until the mouse it outside of
 * the popup for about 2 seconds. At that point it will be hidden again.
 *
 * No positioning of the popup is done in this JavaScript. All
 * positioning should be done in the stylesheet.
 */

var Popup = Class.create({
  initialize: function(element) {
    this.element = element;
    this.displayed = false;
    this.pointerX = 0;
    this.pointerY = 0

    Event.observe(element.parentNode, 'mouseover',
      this.activate.bindAsEventListener(this));
    Event.observe(document, 'mouseover',
      this.trackMouse.bindAsEventListener(this));
  },

  activate: function(event) {
    if(this.displayed) return;
    this.displayed = true;
    this.element.show();
    new PeriodicalExecuter(this.attemptCancel.bind(this), 1)
  },

  attemptCancel: function(pe) {
    // NOTE: Position is deprecated but nothing replaces it yet
    Position.prepare();
    if(!Position.withinIncludingScrolloffsets(this.element.parentNode,
      this.pointerX, this.pointerY)) {
      pe.stop();
      this.element.hide();
      this.displayed = false;
    }
  },

  trackMouse: function(e) {
    this.pointerX = e.pointerX();
    this.pointerY = e.pointerY();
  }
});

Event.observe(document, 'dom:loaded', function() {
  $$('.popup').each(function(p) {new Popup(p);});
});
