/***********************************************
 * This is the javascript library to include
 * if you want to do drag/drop of html objects
 ***********************************************/

var objDrag = null;
var dragHandler = null;
var mouseOffset = null;

// register a page to use drag
function registerDrag() {
	document.onmousemove = handleDrag;
	document.onmouseup = dragMouseup;
}

// set to the onmousedown attribute of the object to drag
// will take a custom handler
function dragMouseDown(objSender, customHandler) {
	objDrag = objSender;
	dragHandler = customHandler;
}

// private method
function dragMouseup() {
	objDrag = null;
	dragHandler = null;
	mouseOffset = null;
}

// private method, calls acustomHandler if exists, otherwise calls 
// defaultDragHandler
function handleDrag(ev) {
	if (objDrag) {
		if (dragHandler) {
			dragHandler(ev);
		} else {
			defaultDragHandler(ev);
		}
		return false;
	}
}

// returns the mouseoffset of an object within
function getMouseOffset(target, ev) {
	ev = ev || window.event;

	var docPos    = getPosition(target);
	var mousePos  = getMouseCoords(ev);
	return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
}

// gets the absolute position of an object within the page.
function getPosition(e) {
	var left = 0;
	var top  = 0;

	while (e.offsetParent){
		left += e.offsetLeft;
		top  += e.offsetTop;
		e     = e.offsetParent;
	}

	left += e.offsetLeft;
	top  += e.offsetTop;

	return {x:left, y:top};
}

// Default drag handler, which will move an object
function defaultDragHandler(ev) {
	ev           = ev || window.event;
	var mousePos = getMouseCoords(ev);
	if(objDrag) {
		if (!mouseOffset) {
			mouseOffset = getMouseOffset(objDrag, ev);
		}
		
		var posY = mousePos.y - mouseOffset.y;
		var posX = mousePos.x - mouseOffset.x;
		
		objDrag.style.position = 'absolute';
		objDrag.style.top      = posY;
		objDrag.style.left     = posX;

		return false;
	}
}

// returns an object with absolute x/y mouse coordinates
function getMouseCoords(ev) {
	if(ev.pageX || ev.pageY) {
		return {x:ev.pageX, y:ev.pageY};
	}
	return {
		x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
		y:ev.clientY + document.body.scrollTop  - document.body.clientTop
	};
}