/* 	
	Copyright (c) Art. Lebedev Studio | http://www.artlebedev.ru/

	Author - Andrew Shitov (ash@design.ru) | 2005-2006

	Original drag mechanics was written by Mike Hall (http://www.brainjar.com/dhtml/drag/) in 2001.
*/

var isMSIE = document.attachEvent != null;
var isGecko = !document.attachEvent && document.addEventListener;

var DraggingItem = new Object();

function StartDrag (event, _this, _afteraction)
{
	DraggingItem.This = _this;
	DraggingItem.AfterAction = _afteraction;

	var position = new Object();
	if (isMSIE)
	{
		position.x = window.event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
		position.y = window.event.clientY + document.documentElement.scrollTop + document.body.scrollTop;
	}
	if (isGecko)
	{
		position.x = event.clientX + window.scrollX;
		position.y = event.clientY + window.scrollY;
	}

	DraggingItem.cursorStartX = position.x;
	DraggingItem.cursorStartY = position.y;

	DraggingItem.StartLeft = parseInt (DraggingItem.This.style.left);
	DraggingItem.StartTop = parseInt (DraggingItem.This.style.top);

	if (isNaN (DraggingItem.StartLeft)) DraggingItem.StartLeft = 0;
	if (isNaN (DraggingItem.StartTop)) DraggingItem.StartTop = 0;

	if (isMSIE)
	{
		document.attachEvent ("onmousemove", ProceedDrag);
		document.attachEvent ("onmouseup", StopDrag);
		window.event.cancelBubble = true;
		window.event.returnValue = false;
	}
	if (isGecko)
	{
		document.addEventListener ("mousemove", ProceedDrag, true);
		document.addEventListener ("mouseup", StopDrag, true);
		event.preventDefault();
	}
}

function ProceedDrag (event)
{
	var position = new Object();

	if (isMSIE) {
		position.x = window.event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
		position.y = window.event.clientY + document.documentElement.scrollTop + document.body.scrollTop;
	}
	if (isGecko)
	{
		position.x = event.clientX + window.scrollX;
		position.y = event.clientY + window.scrollY;
	}	

	var nextX = DraggingItem.StartLeft + position.x - DraggingItem.cursorStartX;
	if (nextX < 0) nextX = 0;
	DraggingItem.This.style.left = nextX + "px";

	var nextY = DraggingItem.StartTop  + position.y - DraggingItem.cursorStartY;
	if (nextY < 0) nextY = 0;
	DraggingItem.This.style.top = nextY + "px";

	if (isMSIE)
	{
		window.event.cancelBubble = true;
		window.event.returnValue = false;
	}
	if (isGecko) event.preventDefault();
}

function StopDrag (event)
{	
	if (isMSIE)
	{
		document.detachEvent ("onmousemove", ProceedDrag);
		document.detachEvent ("onmouseup", StopDrag);
	}
	if (isGecko)
	{
		document.removeEventListener ("mousemove", ProceedDrag, true);
		document.removeEventListener ("mouseup", StopDrag, true);
	}

	if (DraggingItem.AfterAction) DraggingItem.AfterAction (DraggingItem.This);
}

function PutBack (item)
{
	item.style.zIndex = 2;;
}