// JavaScript Document
// See http://www.brainjar.com for terms of use.

// Global object to hold drag information.
var DragManager = new Object();
DragManager.zIndex = 10;

function dragStart(event, id)
{
	var el;
	var x, y;
	
	// If an element id was given, find it. Otherwise use the element being clicked on.
	
	DragManager.elNode = id ? document.getElementById(id) : getTarget(event);
	
	// Get cursor position with respect to the page.
	
	if(Browser.isIE)
	{
		x = window.event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
		y = window.event.clientY + document.documentElement.scrollTop + document.body.scrollTop;
	}
	if(Browser.isNS)
	{
		x = event.clientX + window.scrollX;
		y = event.clientY + window.scrollY;
	}
	
	// Save starting positions of cursor and element.
	
	DragManager.cursorStartX = x;
	DragManager.cursorStartY = y;
	DragManager.elStartLeft  = parseInt(DragManager.elNode.style.left, 10);
	DragManager.elStartTop   = parseInt(DragManager.elNode.style.top,  10);
	
	if(isNaN(DragManager.elStartLeft))
	{
		DragManager.elStartLeft = 0;
	}
	if(isNaN(DragManager.elStartTop))
	{
		DragManager.elStartTop  = 0;
	}
	
	// Update element's z-index.
	//DragManager.elNode.style.zIndex = ++DragManager.zIndex;
	
	// Capture mousemove and mouseup events on the page.
	registerListener('mousemove', dragGo);
	registerListener('mouseup', dragStop);
	
	stopEventPropagation(event);
}

function dragGo(event)
{
	var x, y;
	
	// Get cursor position with respect to the page.
	
	if(Browser.isIE)
	{
		x = window.event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
		y = window.event.clientY + document.documentElement.scrollTop + document.body.scrollTop;
	}
	if(Browser.isNS)
	{
		x = event.clientX + window.scrollX;
		y = event.clientY + window.scrollY;
	}
	
	// Move drag element by the same amount the cursor has moved.	
	DragManager.elNode.style.left = (DragManager.elStartLeft + x - DragManager.cursorStartX) + "px";
	DragManager.elNode.style.top  = (DragManager.elStartTop  + y - DragManager.cursorStartY) + "px";
	
	stopEventPropagation(event);
}

function dragStop(event)
{
	// Stop capturing mousemove and mouseup events.
	unregisterListener('mousemove', dragGo);
	unregisterListener('mouseup', dragStop);
}
