// include Utils.MouseDevice.js
// include Libs.prototype.js
// include Utils.Utils.js

/*
with this script added Elements can be dragged and dropped
	- you can even drag multiple objects at a time ;) ... eg. draggin a bunch of flowers 
*/

if( ! document.aDragDropElements )
{
	document.aDragDropElements = new Array();
}

function g_dragDropAddElement( sElementId )
{
	var dde = new DragDropElement( sElementId );
	 
	document.aDragDropElements.push( dde );
	
	return dde;
}

DragDropElement = Class.create(
{
	initialize : function( sElementID )
	{
		this.element = $( sElementID );
		assert( this.element, "ERROR cant find '"+sElementID+"' for DragDrop!" );
		
		g_mouseDevice.registerListener( this );
		
		
		if( ! this.element.style.left )
		{
			this.element.style.left = g_getPX( g_getLeft(this.element) );
		}
		if( ! this.element.style.top )
			this.element.style.top =  g_getPX( g_getTop(this.element) );
		
		this.setInitialPos(); 
		
		this.bResetToInitialAfterDrag = false;
		
		//WARNING in the zoomer this was set to relative
		//this.element.style.position = 'relative';
		this.element.style.zIndex = 10;
		
		
		this.bDrag = false;
		this.iDragStartPosX = 0;
		this.iDragStartPosY = 0;
	},
	
	setInitialPos : function()
	{
		this.iInitialPosX = g_int( this.element.style.left );
		this.iInitialPosY = g_int( this.element.style.top );
	},
	
	getPosX : function()
	{
		return g_getLeft(this.element);
	},
	
	getPosY : function()
	{
		return g_getTop(this.element);
	},
	
	onMouseDown : function(e)
	{
		if( g_pointWithinElement( g_mouseDevice.getMousePosX(), g_mouseDevice.getMousePosY(), this.element ) )
		{
			this.bDrag = true;
			
			this.setInitialPos();
			
			this.iDragStartPosX = g_mouseDevice.getMousePosX() ;
			this.iDragStartPosY = g_mouseDevice.getMousePosY() ;
			
			if( document.dragDropOnGrab )
				document.dragDropOnGrab( this );
			
			return true;		
		}
		
		return false;
	},
	
	onMouseMove : function(e)
	{
		if( this.bDrag )
		{
			this.element.style.left = g_getPX( this.iInitialPosX + g_mouseDevice.getMousePosX() - this.iDragStartPosX );
			this.element.style.top  = g_getPX( this.iInitialPosY + g_mouseDevice.getMousePosY() - this.iDragStartPosY );
			
			return true;
		}
		return false;
	},
	
	onMouseUp : function(e)
	{
		if( this.bDrag )
		{
			this.bDrag = false;
			if( document.dragDropOnDrop )
				document.dragDropOnDrop( this );
				
			//goto initial position
			if( this.bResetToInitialAfterDrag )
			{
				this.element.style.left = g_getPX( this.iInitialPosX );
				this.element.style.top  = g_getPX( this.iInitialPosY );
			}
			else
			{
				this.setInitialPos();
			}
		}
	}
	
});



