/** The drag function sets up callbacks so that the mouse can be used to
* drag-move the current HTML element. Call this function with the element
* and the event: <div onmousedown="drag(this, event);"></div>
* @param {Element} element The element that will move with the mouse
*	(children will move too)
* @param (Event) event The mouse down event that starts the drag
*/
function drag(element, event) 
{
  // Drag start position
  var startX = event.clientX;
  var startY = event.clientY;
  // Element start position
  var origX = element.offsetLeft;
  var origY = element.offsetTop;
  // Calculate the start delta 
  var deltaX = startX - origX; 
  var deltaY = startY - origY;
  // Register handlers for the mousemove and mouseup that will cause the drag
  // and end the drag
  if ( document.addEventListener )
  {
    document.addEventListener("mousemove", moveHandler, true);
    document.addEventListener("mouseup", upHandler, true); 
  }
  else if ( document.attachEvent ) //IE 
  {
    element.setCapture();
    element.attachEvent("onmousemove", moveHandler);
    element.attachEvent("onmouseup", upHandler);
    element.attachEvent("onlosecapture", upHandler); 
  }
  else 
  {
    displayMessage("Compatibility error",
                   "Unrecognized browser type.  Dragging disabled. "+ 
                   "Contact web developer to add support to your browser"); 
  }
  // stop event handling
  if ( event.stopPropagation )
    event.stopPropagation(); 
  else
    event.cancelBubble = true; //IE 
  if ( event.preventDefault )
    event.preventDefault();
  else
    event.returnValue = false; //IE
  // Define the move handler 
  function moveHandler(e) 
  {
    if ( !e )
      e = window.event; // IE
    // Move the element
    element.style.left = (e.clientX - deltaX) + "px"; 
    element.style.top = (e.clientY - deltaY) + "px"; 
    // Stop the event 
    if ( e.stopPropagation )
      e.stopPropagation(); 
    else
      e.cancelBubble = true; //IE
  }
  // Define the upHander 
  function upHandler(e)
  {
    if ( !e )
      e = window.event; // IE 
    // Unregister our event handlers 
    if ( document.removeEventListener )
    {
      document.removeEventListener("mouseup", upHandler, true); 
      document.removeEventListener("mousemove", moveHandler, true);
    }
    else
    {
      element.detachEvent("onlosecapture", upHandler); 
      element.detachEvent("onmouseup", upHandler); 
      element.detachEvent("onmousemove", moveHandler); 
      element.releaseCapture();
    }
    // Stop the event
    if ( e.stopPropagation )
      e.stopPropagation(); 
    else
      e.cancelBubble = true; //IE 
  }
}

