//*** This code is copyright 2004 by Gavin Kistner, gavin@refinery.com
//*** It is covered under the license viewable at http://phrogz.net/JS/_ReuseLicense.txt
//*** Reuse or modification is free provided you abide by the terms of that license.
//*** (Including the first two lines above in your source code satisfies the conditions.)

AttachEvent(window,'load',function(){
	function Init(){
		//DebugOut("Draggable.Init()",1);
		var els = document.getElementsByTagName('*');
		if ((!els || els.length==0) && document.all) els=document.all;
		for (var i=els.length-1;i>=0;i--){
			var el=els[i];
			if (!HasClass(el,'draggable')) continue;
			//DebugOut("Draggable.Init() -- found an element to drag: "+el.tagName,2);
			AttachEvent(el,'mousedown',StartDrag,false);
			AttachEvent(el,'selectstart',PreventDefault,false);
		}
	}
	
	function StartDrag(evt){
		//DebugOut("StartDrag("+evt+")",1);
		if (!evt && window.event) evt=event;
		if (!evt) return alert("ERROR: Can't find an event object for Start Drag!");
		var obj = evt.currentTarget || evt.srcElement;
		while (obj && !HasClass(obj,'draggable')) obj=obj.parentNode;
		if (!obj) return alert("ERROR: Can't find the object to drag.");
		window.draggableInfo={ obj:obj, x:parseInt(obj.style.left,10)-evt.clientX, y:parseInt(obj.style.top,10)-evt.clientY };
		AttachEvent(document.body,'mousemove',TrackDrag,false);
		AttachEvent(document.body,'mouseup',StopDrag,false);
		AttachEvent(document.body,'selectstart',PreventDefault,false);
		AddClass(obj,'draggingNOW');
	}

	function TrackDrag(evt){
		//DebugOut("TrackDrag("+evt+")",3);
		if (!evt && window.event) evt=event;
		if (!evt) return alert("ERROR: Can't find an event object for Start Drag!");
		if (!window.draggableInfo) return alert("ERROR: Where's my draggableInfo?!");
		var obj = draggableInfo.obj;
		obj.style.left = evt.clientX+draggableInfo.x+'px';
		obj.style.top = evt.clientY+draggableInfo.y+'px';
	}
	
	function StopDrag(){
		//DebugOut("StopDrag()",2);

          // Modified: Layer on top added by Michele Chinosi
          //
	  if (window.draggableInfo) {KillClass(draggableInfo.obj,'draggingNOW'); 
		                     AddClass(draggableInfo.obj,'draggingSTOP');}
		window.draggableInfo=null;
		DetachEvent(document.body,'mousemove',TrackDrag,false);
		DetachEvent(document.body,'mouseup',StopDrag,false);
		DetachEvent(document.body,'selectstart',PreventDefault,false);
	}
	
	Init();
},false);

//debugLevel=1;
