/* 
	j123 -- JavaScript common library
	mail: sebastian.hanula@gmail.com
	www:  http://www.hanula.com/lab/j123

	j123 drag library
*/

j123.drag = {
	object : null,
	
	init : function(el,root) {
		j123.events.add(el,'mousedown',j123.drag.start);		
		el.root =  root;
		if(isNaN(parseInt(el.root.style.left))) el.root.style.left="0px";
		if(isNaN(parseInt(el.root.style.top))) el.root.style.top="0px";		
		
		if(!el.root.onDragStart) el.root.onDragStart = function(x,y,cx,cy) {};
		if(!el.root.onDragEnd)el.root.onDragEnd = function(x,y) {};
		if(!el.root.onDrag)el.root.onDrag = function(x,y,cx,cy,e) {return {x:x,y:y}};
		

	},
	
	start : function(e) {
		var b = j123.drag.object = this;
		e=j123.events.fix(e);
		var x=parseInt(b.root.style.top);
		var y=parseInt(b.root.style.left);

		b.root.onDragStart(x,y,e.clientX,e.clientY);
		b.lastMouseX=e.clientX;
		b.lastMouseY=e.clientY;
		j123.events.add(document,'mousemove',j123.drag.drag);
		j123.events.add(document,'mouseup',j123.drag.end);
	},
	
	drag : function(a) {
		a = j123.events.fix(a);
		
		if(typeof a=="undefined")a=window.event;
		if(typeof a.layerX=="undefined")a.layerX=a.offsetX;
		if(typeof a.layerY=="undefined")a.layerY=a.offsetY;
		
		
		var b=j123.drag.object;
		var c=a.clientY;
		var d=a.clientX;
		var e=parseInt(b.root.style.top);
		var f=parseInt(b.root.style.left);
		var h,g;
		h=f+d-b.lastMouseX;
		g=e+c-b.lastMouseY;

		var point = b.root.onDrag(h,g,a.clientX,a.clientY,a);
		if(point.x)	b.root.style.left=point.x+"px";
		if(point.y)	b.root.style.top=point.y+"px";		
		b.lastMouseX=d;
		b.lastMouseY=c;

		
	},
	
	end : function(e) {
		
		j123.events.remove(document,'mousemove',j123.drag.drag);
		j123.events.remove(document,'mouseup',j123.drag.end);
		j123.drag.object.root.onDragEnd(parseInt(j123.drag.object.root.style.left),parseInt(j123.drag.object.root.style.top));
	}
};
