var mousex = 0;
var mousey = 0;
var grabx = 0;
var graby = 0;
var orix = 0;
var oriy = 0;
var elex = 0;
var eley = 0;

var dragobj = null;

function falsefunc() { return false; } // used to block cascading events

function init()
{
  document.onmousemove = update; // update(event) implied on NS, update(null) implied on IE
  window.onmousemove = update;
}

function getMouseXY(e) // works on IE6,FF,Moz,Opera7
{ 
    if (!e) e = window.event; // works on IE, but not NS (we rely on NS passing us the event)
  
    if (e)
    { 
        if (e.clientX || e.clientY)
        { 
           // works on IE6,FF,Moz,Opera7
           mousex = e.clientX ;
           mousey = e.clientY ;
        }  
     }
}

function update(e)
{
   getMouseXY(e); // NS is passing (event), while IE is passing (null)
}

function grab(context)
{
  document.onmousedown = falsefunc; // in NS this prevents cascading of events, thus disabling text selection
  window.onmousedown = falsefunc;

  dragobj = context;
  dragobj.style.zIndex = 10; // move it to the top
  
  document.onmousemove = drag;
  document.onmouseup = drop;
  window.onmousemove = drag;
  window.onmouseup = drop;

  grabx = window.event.x;
  graby = window.event.y;
  elex = orix = dragobj.offsetLeft;
  eley = oriy = dragobj.offsetTop;

}

function drag(e) // parameter passing is important for NS family 
{
  if (dragobj)
  {
     elex = orix + (mousex-grabx);
     eley = oriy + (mousey-graby);

     dragobj.style.position = "absolute";
     dragobj.style.left = (elex).toString(10) + 'px';
     dragobj.style.top  = (eley).toString(10) + 'px';
  }

  update(e);
  //grabx = window.event.x;
  //graby = window.event.y;

  return false; // in IE this prevents cascading of events, thus text selection is disabled
}

function drop()
{
  if(dragobj)
  {
     dragobj.style.zIndex = 0;
     dragobj = null;
  }

  window.moveBy(window.event.clientX-grabx, window.event.clientY-graby);

  document.onmousemove = update;
  document.onmouseup = null;
  document.onmousedown = null;   // re-enables text selection on NS

  window.onmousemove = update;
  window.onmouseup = null;
  window.onmousedown = null;   // re-enables text selection on NS
}
