/**
 *  file: courseDescriptions.js
 *  created: mvellines - 2007/03/02
 *  updated: mvellines - 2007/03/30 | fixed problem with child elements inside anchors.
 *  purpose: separate behavioral enhancements from structural markup
 *
 *  Adds event handlers to all anchors which point to course.php
 *  in order to display course titles and descriptions in a popup
 *  window without using HTML attributes.
 */


// Ensures all prior page-load handlers run plus the specifed one.
function addLoadEvent(fn) {
  var old = window.onload;
  if(typeof window.onload != 'function') {
    window.onload = fn;
  } else {
    window.onload = function() {
      old();
      fn();
    }
  }
}


// Add event handlers for the course description links.
function wireDescPopups(e) {
  var links = document.getElementsByTagName('a');
  for(var i = 0; i < links.length; i++) {
  
    // Skip anchors that do not link to the course description script.
    if(!links[i].href || links[i].href.lastIndexOf('course.php') < 0) { continue; }
    
    // Add event handler and target property to this anchor.
    links[i].onclick = showCourseInfo;
    links[i].target = "_new";
  }
  return true;
}


// Retrieve the href value of the anchor element whence the event occurred.
// This function will recursively climb the element hierarchy until the anchor
// element's href value can be read or the document element is reached. It is
// needed because child elements can reside inside the anchor element which may
// be the source of the click event.
function getHrefForIE(elem) {
  if(elem.nodeType == 9) { return null; } // failed: reached top of document.
  else if(elem.nodeType == 1 && elem.href) { return elem.href; } // Found it!
  else { return getHrefForIE(elem.parentNode); }
}


// Click-handler for course description links.
function showCourseInfo(e) {
  if(!e) e = window.event; // IE only
  var atts = 'height=350,width=520,scrollbars=yes';
  
  // Get reference to event-generating element.
  var url;
  if (e.currentTarget) {
    // Safari and Konqueror sometimes reference text and cdata node instead of <a>.
    url = (e.currentTarget.nodeType == 3 || e.currentTarget.nodeType == 4)
        ? e.parentNode.currentTarget.href
        : e.currentTarget.href;

  // Naturally, IE must do it differently.
  } else if (e.srcElement) {
    url = getHrefForIE(e.srcElement);
  }

  // Open new window and load content in it.
  window.open(url, '_new', atts);
  
  // Prevent main window from following link.
  if(e.preventDefault) {
    e.preventDefault();
  } else {
//     e.cancelBubble= true;
    e.returnValue = false;
  }
  return true;
}

// Hook the initializer function to the document load.
addLoadEvent(wireDescPopups);