/* ---------------------------------------------------------------------- */
/* ----------------------- Global Drag & Drop --------------------------- */
/* ---------------------------------------------------------------------- */

Drag = function() {
	Drag.superClass.apply( this, arguments );
	this.Id = 'Drag';
	this.set( false );
	this.processing = false;
	this.element = document.body;
	this.addHandler( this.element, 'mousedown', this.start );
}
Drag.inheritsFrom( IL );

/* ------------------------------ Start --------------------------------- */

Drag.prototype.start = function( params, ev ) {
	this.setHandlers( false );	

	if( this.obj === false ) return false;
	this.processing = true;
	this.setHandlers( true );

	this.notify( 'DragStart', this.obj );

	if( this.objStartHandler ) {
		var pos = this.getCursorPosition( ev );
		this.objStartHandler.call( this.obj, pos.x, pos.y );
	}
	this.preventDefault( ev );
}

/* ------------------------------ Move ---------------------------------- */

Drag.prototype.move = function( params, ev ) {
	if( this.objMoveHandler ) {
		var pos = this.getCursorPosition( ev );
		this.objMoveHandler.call( this.obj, pos.x, pos.y );
	}
	this.stopPropagation( ev );
	this.preventDefault( ev );
}

/* ------------------------------ Stop ---------------------------------- */

Drag.prototype.stop = function( params, ev ) {
	this.setHandlers( false );
	this.notify( 'DragStop', this.obj );

	if( this.objStopHandler ) {
		var pos = this.getCursorPosition( ev );
		this.objStopHandler.call( this.obj, pos.x, pos.y );
	}
	this.stopPropagation( ev );

	this.processing = false;
	this.set( false );
}

/* ------------------------------- Set ---------------------------------- */

Drag.prototype.set = function( obj, start, move, stop ) {
	this.obj = obj || false;
	this.objStartHandler = start || false;
	this.objMoveHandler = move || false;
	this.objStopHandler = stop || false;
}

Drag.prototype.remove = function() {};

/* -------------------------- Set Handlers ------------------------------ */

Drag.prototype.setHandlers = function( flag ) {
	var keyWord = ( flag ? 'add' : 'remove' );
	this[ keyWord + 'Handler' ]( this.element, 'mousemove', this.move, null, true );
	this[ keyWord + 'Handler' ]( this.element, 'mouseup', this.stop, null, true );
	if( window.event ) this[ keyWord + 'Handler']( this.element, 'losecapture', this.stop, null, true );
}

/* ----------------------- Get Cursor Position -------------------------- */

Drag.prototype.getCursorPosition = function( ev ) {
	if( !ev ) return false;
	
	var obj = {
		x: ev.clientX + ( window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft ),
		y: ev.clientY + ( window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop  )
	};

	return obj;
}