var DEBUG = 0;
var _startX = 0;			// mouse starting positions
var _startY = 0;
var _offsetX = 0;			// current element offset
var _offsetY = 0;
var _dragElement;			// needs to be passed from OnMouseDown to OnMouseMove
var _oldZIndex = 0;			// we temporarily increase the z-index during drag
var saved = '';				// pipe sep between entries, dash between values

function InitDragDrop()
{
	if(DEBUG) { console.log("InitDragDrop\n"); }
	document.onmousedown = OnMouseDown;
	document.onmouseup = OnMouseUp;
}

function OnMouseDown(e)
{
	if(DEBUG) { console.debug("OnMouseDown =" + e + "\n"); }
	if(DEBUG) { console.info(e); }
	if (e == null) e = window.event; 
	var target = e.target != null ? e.target : e.srcElement;
	if(DEBUG) { console.debug("OnMouseDown target=" + target + "\n"); }
	if(DEBUG) { console.info(target); }
	
	if ((e.button == 1 && window.event != null || e.button == 0) && target.className == 'drag') {
		_startX = e.clientX;
		_startY = e.clientY;
		if(DEBUG) { console.debug("OnMouseDown startXY=" + _startX + " : " + _startY + "\n"); }
		_offsetX = ExtractNumber(target.style.left);
		_offsetY = ExtractNumber(target.style.top);
		_oldZIndex = target.style.zIndex;
		target.style.zIndex = 10000;
		_dragElement = target;
		document.onmousemove = OnMouseMove;
		document.body.focus();
		document.onselectstart = function () { return false; };
		target.ondragstart = function() { return false; };
		return false;
	}
}

function ExtractNumber(value)
{
	var n = parseInt(value);
	return n == null || isNaN(n) ? 0 : n;
}

function OnMouseMove(e)
{
	if (e == null) var e = window.event; 
	_dragElement.style.left = (_offsetX + e.clientX - _startX) + 'px';
	_dragElement.style.top = (_offsetY + e.clientY - _startY) + 'px';
}

function OnMouseUp(e) {
	if(DEBUG) { console.log("OnMouseUp =" + e + "\n"); }
	if (e == null) e = window.event; 
	var target = e.target != null ? e.target : e.srcElement;
	if(DEBUG) { console.log("OnMouseUp target=" + target + "\n"); }
	if(DEBUG) { console.info(target); }
	if (_dragElement != null) {
		_dragElement.style.zIndex = _oldZIndex;
		document.onmousemove = null;
		document.onselectstart = null;
		_dragElement.ondragstart = null;
		if(DEBUG) { console.debug('final position: (' + _dragElement.style.left + ', ' + _dragElement.style.top + ')');	}
		if(DEBUG) { console.debug("OnMouseUp endXY=" + e.clientX + " : " + e.clientY + "\n"); }
		if(e.clientX > 0 && e.clientY > 0) { saved = saved + target.id + "-" + e.clientX + "-" + e.clientY + "|"; }
		if(DEBUG) { console.debug("OnMouseUp saved=" + saved + "\n"); }
		_dragElement = null;
	}
}

