// global variables
var dragObject;
var mouseOffset;

// capture mouse events
aaManageEvent(document,'mouseup',mouseUp);
aaManageEvent(document,'mousemove',mouseMove);
aaManageEvent(window,'load', function() {
   makeDraggable('img1');
});
    
// create a mouse point
function mousePoint(x,y) {
   this.x = x;
   this.y = y;
}

// find mouse position
function mousePosition(evnt){
  var x = parseInt(evnt.clientX); 
  var y = parseInt(evnt.clientY); 
  return new mousePoint(x,y);
}

// get element's offset position within page 
function getMouseOffset(target, evnt){
   evnt = evnt || window.event;
   var mousePos  = mousePosition(evnt);
   var x = mousePos.x - target.offsetLeft;
   var y = mousePos.y - target.offsetTop;
   return new mousePoint(x,y);
}

// turn off dragging
function mouseUp(evnt){
   dragObject = null;
}

// capture mouse move, only if dragging
function mouseMove(evnt){
   if (!dragObject) return;
   evnt = evnt || window.event;
   var mousePos = mousePosition(evnt);

   // if draggable, set new absolute position
   if(dragObject){
      dragObject.style.position = 'absolute';

      dragObject.style.top      = mousePos.y - mouseOffset.y + "px";
      dragObject.style.left     = mousePos.x - mouseOffset.x + "px";
      return false;
    }
}

// make object draggable
function makeDraggable(item){
   if (item) {
      item = aaElem(item);
      item.onmousedown = function(evnt) {
                         dragObject  = this;
                         mouseOffset = getMouseOffset(this, evnt);
                         return false; };
   }
}

