/*
 * Draggable
 * 
 * @website http://clonedoppelganger.net/
 * @version 0.0.1
 */
/*
Example:
[CSS]--------------------------------------------
#element_id {
  position: absolute;
  top: 10px;
  left: 35px;
  width: 150px;
  height: 100px;
  background-color: #00b;
  cursor: move;
}
[HTML]-------------------------------------------
<div id="element_id"></div>
[JavaScript]-------------------------------------
var draggable = new Draggable("element_id");
-------------------------------------------------
*/
var DraggableNHM = Class.create();
DraggableNHM.prototype = {
	initialize: function ( element ) {
		this.element = $( element );
		this.style = this.element.style;
		this.thisBaseX;
		this.thisBaseY;
		this.pageBaseX;
		this.pageBaseY;
		this.isMoving = false;
		this.observers = {};
		var html = this.getHTML();
		var thisObject = this;
		Event.observe( this.element, "mousemove", function () { return false; }, false );
		Event.observe( this.element, "mousedown", function ( event ) {
			if ( thisObject.isMoving ) return;
			var position = thisObject.getPosition();
			thisObject.thisBaseX = position["x"];
			thisObject.thisBaseY = position["y"];
			thisObject.pageBaseX = event.pageX || event.clientX;
			thisObject.pageBaseY = event.pageY || event.clientY;
			thisObject.isMoving = true;
		}, false );
		Event.observe( html, "mousemove", function ( event ) {
			if ( !thisObject.isMoving ) return;
			event = event || window.event;
			thisObject.setPosition( ( event.pageX || event.clientX ) - thisObject.pageBaseX + thisObject.thisBaseX, ( event.pageY || event.clientY ) - thisObject.pageBaseY + thisObject.thisBaseY );
		}, false );
		Event.observe( html, "mouseup", function ( event ) {
			if ( !thisObject.isMoving ) return;
			thisObject.isMoving = false;
		}, false );
	},
	destroy: function () {
		var html = this.getHTML();
		this.detach( this.element, "mousedown", this.observers["mousedown"] );
		this.detach( html, "mouseup", this.observers["mouseup"] );
		this.detach( html, "mousemove", this.observers["mousemove"] );
		this.element.onmousemove = null;
	},
	setPosition: function( x, y ) {
		this.style.left = x + 'px';
		this.style.top = y + 'px';
	},
	getPosition: function () {
		var x, y;
		if ( this.style.top == "" || this.style.left == "" ) {
			if ( this.element.currentStyle ) {
				x = this.element.currentStyle["left"];
				y = this.element.currentStyle["top"];
			} else {
				var computedStyle = document.defaultView.getComputedStyle( this.element, null );
				x = computedStyle["left"];
				y = computedStyle["top"];
			}
		} else {
			x = this.style.left;
			y = this.style.top;
		}
		return { "x": parseInt( x.replace( /px/, "" ) ) || 0, "y": parseInt( y.replace( /px/, "" ) ) || 0 };
	},
	getHTML: function () {
		return document.getElementsByTagName( 'html' ).item(0);
	}
};

