/*
Drag'n'Drop objects implementation
*/
function ThDrag()
{
}
function ThDrag( element )
{
	if(null != element){
		this._element = element;
		element.isDraggable = true;
		this._bdown = false;
		this._transforms = new TH.transforms( this._element );
		this._mouseposX = 0;
		this._mouseposY = 0;
		this._elementX = 0;
		this._elementY = 0;
		var pos_style = TH.styles(element).read('position');
		if (pos_style == 'static')
		{
			TH.styles(element).write('position','relative');
		}
	}
}

ThDrag.prototype.setTransforms = function ( transforms )
{
	this._element.transofrms = transforms;
}

ThDrag.prototype.init = function (handle )
{
	if(null != handle)
	{
		this._handle = handle;
		handle.isHandle = true;
		if (handle != this._element)
		{
			handle.haveHandle = true;
		}
		else
		{
			handle.haveHandle = false;
		}		
		TH.events(document).add(handle,'mousedown',this._start);
		TH.events(document).add(handle,'mouseup',this._end);
		TH.events(document).add(handle,'mousemove',this._move);
		document.onmousemove = function() { return false } 
	}
}

ThDrag.prototype._end = function( event )
{
	if (this._bdown)
	{
		event = TH.events().get(event);
		this._element = event.target;
	
		if (this._element.parentNode.isDraggable == true)
		{
			this._handle = this._element.parentNode;
		}
		else
		{ 
			this._handle = this._element;
		}
		
		TH.events(document).remove(this._handle,'mousemove',this._move);
		TH.events(document).remove(this._handle,'mousedown',this._start);
		TH.events(document).remove(this._handle,'mouseup',this._end);
		this._bdown = false;
		document.onmousedown = null;
	}
}

ThDrag.prototype._start = function( event )
{
	event = TH.events(document).get(event);
	var elt = event.target;
	this._element = elt;
	
	if (elt.parentNode.isDraggable == true)
	{
		this._handle = elt.parentNode;
	}
	else
	{ 
		this._handle = this._element;
	}
	if (this._handle.isHandle != true && this._element.haveHandle != true)
		return;
	this._bdown = true;
	var coords = TH.coordinates(this._handle);
	var crd = coords.mousePos(event);
//	var crd_elt = coords.elementPos(this._element);
//	var crd_elt_p = coords.elementPos(this._handle);
	var crd_elt_p = coords.position();
	var mo = coords.mouseOffset(event);
	this._mouseposX = crd.x;
	this._mouseposY = crd.y;
	this._elementX = crd_elt_p.x;
	this._elementY = crd_elt_p.y;
}

ThDrag.prototype._move = function( event )
{
	event = TH.events().get(event);
	
	if( this._bdown)
	{
			var coords = TH.coordinates(this._handle);
			
			var crd = coords.mousePos(event);
			var mouseMoveX = crd.x - this._mouseposX;
			var mouseMoveY = crd.y - this._mouseposY;
			coords.displayMousePos(event);
			coords.displayElementPos(this._handle);
			crd.display();
			
			coords.moveTo(this._elementY+mouseMoveY,this._elementX+mouseMoveX);
			//coords.moveTo(mouseMoveY,mouseMoveX);
	}
}