var AttorneyPopup = Class.create({
  initialize: function(line) {
    this.line = line;
    this.popup = line.down('.attny-mouseover');

    this.line.cleanWhitespace();
    this.popup.show();
    var popup_offset = this.popup.cumulativeOffset();
    this.popup.hide();
    var offset = popup_offset.top + this.popup.getHeight() -
      AttorneyPopup.container_bottom;
    if( offset > 0 ) this.popup.setStyle({top: (-1 * offset)+'px'});

    this.line.observe('mouseover', this.show.bindAsEventListener(this));
    this.line.observe('mouseout', this.hide.bindAsEventListener(this));
  },

  show: function(event) {
    this.cancelHide();
    if( this.in_popup(event) ) return;
    if( this.line.hasClassName('hover') ) return;
    AttorneyPopup.container.select('.attny-mouseover').each((function(e) {
      if( e.visible() ) {
        this.swap(e.up('li').down('a'));
        e.up('li').removeClassName('hover')
        e.hide();
      }
    }).bind(this));
    this.line.addClassName('hover');
    this.swap(this.line.down('a'));
    this.popup.show();
  },

  hide: function(event) {
    this.cancelHide();
    AttorneyPopup.timer = setTimeout((function() {
      if( this.in_popup(event) ) return;
      this.line.removeClassName('hover');
      this.swap(this.line.down('a'));
      this.popup.hide();
    }).bind(this), 1000);
  },

  swap: function(link) {
    if(!link) return;
    var tmp = link.getAttribute('title');
    link.setAttribute('title', link.innerHTML);
    link.innerHTML = tmp;
  },

  in_popup: function(event) {
    var in_popup = false
    AttorneyPopup.container.select('.attny-mouseover').each((function(e) {
      if( e.visible() && e.hasPosition(event.pointerX(), event.pointerY()))
        in_popup = true;
    }).bind(this));
    return in_popup;
  },

  cancelHide: function() {
    if(AttorneyPopup.timer) {
      clearTimeout(AttorneyPopup.timer);
      AttorneyPopup.timer = null;
    }
  }

});
AttorneyPopup.timer = null;

/* Since Postion.within is deprecated borrowed from:
http://groups.google.com/group/prototype-scriptaculous/msg/9110309abd0a163d */
Element.addMethods({
  hasPosition : function(element, x, y){
    element = $(element);
    this.topleft = Element.cumulativeOffset(element);
    this.bottomright = [
      this.topleft[0] + element.offsetWidth,
      this.topleft[1] + element.offsetHeight,
    ];
    return (y >= this.topleft[1] &&
      y <  this.bottomright[1] &&
      x >= this.topleft[0] &&
      x <  this.bottomright[0]);
  }
}); 

Event.observe(document, 'dom:loaded', function() {
  AttorneyPopup.container = $$('.attorneys-index').first();
  var offset = AttorneyPopup.container.cumulativeOffset();
  var height = AttorneyPopup.container.getHeight();
  AttorneyPopup.container_bottom = offset.top + height;
  $$('.attorneys-index li').each(function(e) {new AttorneyPopup(e)});
});
