/*
Joseph Riesen

NOTE: Some work needs to be done in consolidation here.  Ignoring mouseout events between the
      overlay_link and the overlay itself can likely be done in a single function.
*/

$(document).ready(function(){
  $('div.overlay').each(function() {
    this.triggerLink = $('#' + this.id.replace('overlay_', ''))[0];
  });
  
  $('a.overlay_link').each(function() {
    this.myOverlay = $('#overlay_' + this.id)[0];
  });
  
  $('div.overlay').mouseout(function(event) {
    // From http://www.quirksmode.org/js/events_mouse.html
    // Ensure the element we're moving _into_ is not simply a child element of the overlay itself:
    if (!this.triggerLink) return;
    if (
      event.relatedTarget.id == this.triggerLink.id || 
      event.relatedTarget.id == this.id || 
      $(event.relatedTarget).parents().filter('#' + this.id + ', #' + this.triggerLink.id).length > 0
    ) return;
    this.overlayVisible = false;
    $(this).hide();
  });

  $('a.overlay_link').mouseout(function(event) {
    if (!this.myOverlay) return;
    if (
      event.relatedTarget.id == this.myOverlay.id || 
      event.relatedTarget.id == this.id || 
      $(event.relatedTarget).parents().filter('#' + this.id + ', #' + this.myOverlay.id).length > 0
    ) return;
    this.myOverlay.overlayVisible = false;
    $(this.myOverlay).hide();
  });
  
  $('a.overlay_link').mouseover(function(event) {
    if (!this.myOverlay || this.myOverlay.overlayVisible) return;
    
    this.myOverlay.style.left = (event.pageX - 20) + 'px';
    $(this.myOverlay).show();
    this.myOverlay.overlayVisible = true;
    this.myOverlay.style.top = (event.pageY - this.myOverlay.offsetHeight + 5) + 'px';
  });
});
