
// iMouseDown represents the current mouse button state: up or down
/*
lMouseState represents the previous mouse button state so that we can
check for button clicks and button releases:

if(iMouseDown && !lMouseState) // button just clicked!
if(!iMouseDown && lMouseState) // button just released!
*/
var __w2dragdrop_mouseOffset = null;
var __w2dragdrop_iMouseDown  = false;
var __w2dragdrop_lMouseState = false;
var __w2dragdrop_dragObject  = null;

// variables
var __w2dragdrop_DragDrops   = [];
var __w2dragdrop_curTarget   = null;
var __w2dragdrop_lastTarget  = null;
var __w2dragdrop_dragHelper  = null;
var __w2drapdrop_tempDiv     = null;
var __w2dragdrop_rootParent  = null;
var __w2dragdrop_rootSibling = null;
var __w2dragdrop_saveStatus = false;
var __w2dragdrop_cookieName = "";
var __w2dragdrop_oldmousemove = null;
var __w2dragdrop_oldmouseup = null;

Number.prototype.NaN0=function(){return isNaN(this)?0:this;}


function w2dragdrop_CreateContainer()
{

    /*
	Create a new "Container Instance" so that items from one "Set" can not
	be dragged into items from another "Set"
	*/
	var cDrag        = __w2dragdrop_DragDrops.length;
	__w2dragdrop_DragDrops[cDrag] = [];


    /*
	Each item passed to this function should be a "container".  Store each
	of these items in our current container
	*/
	for(var i=0; i<arguments.length; i++)
	{
		var cObj = arguments[i];
		__w2dragdrop_DragDrops[cDrag].push(cObj);
		cObj.setAttribute('DropObj', cDrag);


        cObj.onmousemove = __w2dragdrop_mouseMove;
        cObj.onmousedown = __w2dragdrop_mouseDown;
        cObj.onmouseup = __w2dragdrop_mouseUp;


        /*
		Every top level item in these containers should be draggable.  Do this
		by setting the DragObj attribute on each item and then later checking
		this attribute in the mouseMove function
		*/
		for(var j=0; j<cObj.childNodes.length; j++)
		{

			// Firefox puts in lots of #text nodes...skip these
			if(cObj.childNodes[j].nodeName=='#text') continue;

			cObj.childNodes[j].setAttribute('DragObj', cDrag);
		}
	}
}

function __w2dragdrop_getPosition(e){
	var left = 0;
	var top  = 0;
	while (e.offsetParent){
		left += e.offsetLeft + (e.currentStyle?(parseInt(e.currentStyle.borderLeftWidth)).NaN0():0);
		top  += e.offsetTop  + (e.currentStyle?(parseInt(e.currentStyle.borderTopWidth)).NaN0():0);
		e     = e.offsetParent;
	}


	left += e.offsetLeft + (e.currentStyle?(parseInt(e.currentStyle.borderLeftWidth)).NaN0():0);
	top  += e.offsetTop  + (e.currentStyle?(parseInt(e.currentStyle.borderTopWidth)).NaN0():0);

	return {x:left, y:top};

}

function __w2dragdrop_mouseCoords(ev){
	if(ev.pageX || ev.pageY){
		return {x:ev.pageX, y:ev.pageY};
	}
	return {
		x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
		y:ev.clientY + document.body.scrollTop  - document.body.clientTop
	};
}


function __w2dragdrop_getMouseOffset(target, ev){
	ev = ev || window.event;

	var docPos    = __w2dragdrop_getPosition(target);
	var mousePos  = __w2dragdrop_mouseCoords(ev);
	return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
}

function __w2dragdrop_mouseMove(ev)
{
    ev         = ev || window.event;

	/*
	We are setting target to whatever item the mouse is currently on

	Firefox uses event.target here, MSIE uses event.srcElement
	*/
	var target   = ev.target || ev.srcElement;
	var mousePos = __w2dragdrop_mouseCoords(ev);

    // check if this element is just a placeholder for the parent
   // var dragParent = target.getAttribute('dragParent');
   /* var dragParent = target.getAttribute('title');
    target.setAttribute("title","");
    if (dragParent != null)
	{
        // change target
        target = document.getElementById( dragParent  );
		if (target == null)
		{
            // set back
            target = ev.target || ev.srcElement;
		}
	} */

		// mouseOut event - fires if the item the mouse is on has changed
		if(!__w2dragdrop_iMouseDown && __w2dragdrop_lastTarget && (target!=__w2dragdrop_lastTarget))
		{
			// reset the classname for the target element
			var origClass = __w2dragdrop_lastTarget.getAttribute('origClass');
			if(origClass) __w2dragdrop_lastTarget.className = origClass;
		}

		/*
		dragObj is the grouping our item is in (set from the createDragContainer function).
		if the item is not in a grouping we ignore it since it can't be dragged with this
		script.
		*/

		var dragObj = target.getAttribute('DragObj');
        var text = target.getAttribute('title');
        target.setAttribute("title","");
        var x='';
        if (text!=null) {
            x = text.split(",");
        }
         // if the mouse was moved over an element that is draggable
		if(dragObj!=null)
		{

			// mouseOver event - Change the item's class if necessary
			if(!__w2dragdrop_iMouseDown && target!=__w2dragdrop_lastTarget)
			{
				var oClass = target.getAttribute('overClass');
                var newoClass = x[0];
                if(newoClass)
				{
					target.setAttribute('origClass', target.className);
					target.className = newoClass;
				}
			}

			// if the user is just starting to drag the element
			if(__w2dragdrop_iMouseDown && !__w2dragdrop_lMouseState)
			{

				// mouseDown target
				__w2dragdrop_curTarget     = target;

				// Record the mouse x and y offset for the element
				__w2dragdrop_rootParent    = __w2dragdrop_curTarget.parentNode;
				__w2dragdrop_rootSibling   = __w2dragdrop_curTarget.nextSibling;

				__w2dragdrop_mouseOffset   = __w2dragdrop_getMouseOffset(target, ev);

                if (__w2dragdrop_dragHelper == null)
                {
                    // Create our helper object that will show the item while dragging
                    __w2dragdrop_dragHelper = document.createElement('DIV');
                    document.body.appendChild(__w2dragdrop_dragHelper);
                }
                // We remove anything that is in our dragHelper DIV so we can put a new item in it.
				for(var i=0; i<__w2dragdrop_dragHelper.childNodes.length; i++) __w2dragdrop_dragHelper.removeChild(__w2dragdrop_dragHelper.childNodes[i]);

				// Make a copy of the current item and put it in our drag helper.
				__w2dragdrop_dragHelper.appendChild(__w2dragdrop_curTarget.cloneNode(true));
				__w2dragdrop_dragHelper.style.display = 'block';
                __w2dragdrop_dragHelper.style.cssText = 'position:absolute;';


                __w2dragdrop_dragHelper.style.width = __w2dragdrop_curTarget.offsetWidth;

                // set the class on our helper DIV if necessary
				var dragClass = __w2dragdrop_curTarget.getAttribute('dragClass');
                var newdragClass = x[1];
                /*if(dragClass){
					__w2dragdrop_dragHelper.firstChild.className = dragClass;
				} */
                if(newdragClass){
					__w2dragdrop_dragHelper.firstChild.className = newdragClass;
				}
				// disable dragging from our helper DIV (it's already being dragged)
				__w2dragdrop_dragHelper.firstChild.removeAttribute('DragObj');

				/*
				Record the current position of all drag/drop targets related
				to the element.  We do this here so that we do not have to do
				it on the general mouse move event which fires when the mouse
				moves even 1 pixel.  If we don't do this here the script
				would run much slower.
				*/
				var dragConts = __w2dragdrop_DragDrops[dragObj];

				/*
				first record the width/height of our drag item.  Then hide it since
				it is going to (potentially) be moved out of its parent.
				*/
				__w2dragdrop_curTarget.setAttribute('startWidth',  parseInt(__w2dragdrop_curTarget.offsetWidth));
				__w2dragdrop_curTarget.setAttribute('startHeight', parseInt(__w2dragdrop_curTarget.offsetHeight));

				var rClass = __w2dragdrop_curTarget.getAttribute('remainingClass');
                var newrClass = x[3];
                /*if(rClass){
					__w2dragdrop_curTarget.className = rClass;
				} */

                if(newrClass){
					__w2dragdrop_curTarget.className = newrClass;
				}

                __w2dragdrop_curTarget.style.display  = 'none';

                // loop through each possible drop container
				for(var i=0; i<dragConts.length; i++){
					with(dragConts[i]){
						var pos = __w2dragdrop_getPosition(dragConts[i]);

						/*
						save the width, height and position of each container.

						Even though we are saving the width and height of each
						container back to the container this is much faster because
						we are saving the number and do not have to run through
						any calculations again.  Also, offsetHeight and offsetWidth
						are both fairly slow.  You would never normally notice any
						performance hit from these two functions but our code is
						going to be running hundreds of times each second so every
						little bit helps!

						Note that the biggest performance gain here, by far, comes
						from not having to run through the getPosition function
						hundreds of times.
						*/
						setAttribute('startWidth',  parseInt(offsetWidth));
						setAttribute('startHeight', parseInt(offsetHeight));
						setAttribute('startLeft',   pos.x);
						setAttribute('startTop',    pos.y);
					}

					// loop through each child element of each container
					for(var j=0; j<dragConts[i].childNodes.length; j++){
						with(dragConts[i].childNodes[j]){
							if((nodeName=='#text') || (dragConts[i].childNodes[j]==__w2dragdrop_curTarget)) continue;

							var pos = __w2dragdrop_getPosition(dragConts[i].childNodes[j]);

							// save the width, height and position of each element
							setAttribute('startWidth',  parseInt(offsetWidth));
							setAttribute('startHeight', parseInt(offsetHeight));
							setAttribute('startLeft',   pos.x);
							setAttribute('startTop',    pos.y);
						}
					}
				}
			}
		}

		// If we get in here we are dragging something
		if(__w2dragdrop_curTarget)
		{
			// move our helper div to wherever the mouse is (adjusted by mouseOffset)

            if(__w2dragdrop_dragHelper==null)
            {
                // Create our helper object that will show the item while dragging
                __w2dragdrop_dragHelper = document.createElement('DIV');
                document.body.appendChild(__w2dragdrop_dragHelper);
            }
            __w2dragdrop_dragHelper.style.top  = mousePos.y - __w2dragdrop_mouseOffset.y;
			__w2dragdrop_dragHelper.style.left = mousePos.x - __w2dragdrop_mouseOffset.x;

			var dragConts  = __w2dragdrop_DragDrops[__w2dragdrop_curTarget.getAttribute('DragObj')];
			var activeCont = null;

			var xPos = mousePos.x - __w2dragdrop_mouseOffset.x + (parseInt(__w2dragdrop_curTarget.getAttribute('startWidth')) /2);
			var yPos = mousePos.y - __w2dragdrop_mouseOffset.y + (parseInt(__w2dragdrop_curTarget.getAttribute('startHeight'))/2);

            // check each drop container to see if our target object is "inside" the container
			for(var i=0; i<dragConts.length; i++){
				with(dragConts[i]){
					if((parseInt(getAttribute('startLeft'))                                           < xPos) &&
						(parseInt(getAttribute('startTop'))                                            < yPos) &&
						((parseInt(getAttribute('startLeft')) + parseInt(getAttribute('startWidth')))  > xPos) &&
						((parseInt(getAttribute('startTop'))  + parseInt(getAttribute('startHeight'))) > yPos)){

							/*
							our target is inside of our container so save the container into
							the activeCont variable and then exit the loop since we no longer
							need to check the rest of the containers
							*/
							activeCont = dragConts[i];

							// exit the for loop
							break;
					}
				}
			}
            if(!activeCont)
            {
                // Be a bit more leanient if we we are in no container  - check any corner

                var x = mousePos.x - __w2dragdrop_mouseOffset.x;
                var y = mousePos.y - __w2dragdrop_mouseOffset.y;

                var x1 = mousePos.x - __w2dragdrop_mouseOffset.x + (parseInt(__w2dragdrop_curTarget.getAttribute('startWidth')));
                var y1 = mousePos.y - __w2dragdrop_mouseOffset.y + (parseInt(__w2dragdrop_curTarget.getAttribute('startHeight')));

                for(var i=0; i<dragConts.length; i++){
				with(dragConts[i]){

                    var dx = parseInt(getAttribute('startLeft'));
                    var dy = parseInt(getAttribute('startTop'));
                    var dx1 = parseInt(getAttribute('startLeft'))+ parseInt(getAttribute('startWidth'));
                    var dy1 = parseInt(getAttribute('startTop'))  + parseInt(getAttribute('startHeight'));

                    if(x>dx&&x<dx1&&y>dy&&y<dy1||
                       x>dx&&x<dx1&&y1>dy&&y1<dy1||
                       x1>dx&&x1<dx1&&y>dy&&y<dy1||
                       x1>dx&&x1<dx1&&y1>dy&&y1<dy1||

                       dx>x&&dx<x1&&dy>y&&dy<y1||
                       dx>x&&dx<x1&&dy1>y&&dy1<y1||
                       dx1>x&&dx1<x1&&dy>y&&dy<y1||
                       dx1>x&&dx1<x1&&dy1>y&&dy1<y1

                            )
                     {
							/*
							our target is inside of our container so save the container into
							the activeCont variable and then exit the loop since we no longer
							need to check the rest of the containers
							*/
							activeCont = dragConts[i];

							// exit the for loop
							break;
					}
                 }
                }
			}

            // Our target object is in one of our containers.  Check to see where our div belongs
			if(activeCont){

				// beforeNode will hold the first node AFTER where our div belongs
				var beforeNode = null;

				// loop through each child node (skipping text nodes).
				for(var i=activeCont.childNodes.length-1; i>=0; i--){
					with(activeCont.childNodes[i]){
						if(nodeName=='#text') continue;

						// if the current item is "After" the item being dragged
						if(__w2dragdrop_curTarget != activeCont.childNodes[i]                                                  &&
							((parseInt(getAttribute('startLeft')) + parseInt(getAttribute('startWidth')))  > xPos) &&
							((parseInt(getAttribute('startTop'))  + parseInt(getAttribute('startHeight'))) > yPos)){
								beforeNode = activeCont.childNodes[i];
						}
					}
				}

				// the item being dragged belongs before another item
				if(beforeNode){
					if(beforeNode!=__w2dragdrop_curTarget.nextSibling){

						activeCont.insertBefore(__w2dragdrop_curTarget, beforeNode);
					}

				// the item being dragged belongs at the end of the current container
				} else {
					if((__w2dragdrop_curTarget.nextSibling) || (__w2dragdrop_curTarget.parentNode!=activeCont)){

						activeCont.appendChild(__w2dragdrop_curTarget);
					}
				}

				// the timeout is here because the container doesn't "immediately" resize
				setTimeout(function(){
				var contPos = __w2dragdrop_getPosition(activeCont);
				activeCont.setAttribute('startWidth',  parseInt(activeCont.offsetWidth));
				activeCont.setAttribute('startHeight', parseInt(activeCont.offsetHeight));
				activeCont.setAttribute('startLeft',   contPos.x);
				activeCont.setAttribute('startTop',    contPos.y);}, 5);

				// make our drag item visible
				if(__w2dragdrop_curTarget.style.display!=''){
					__w2dragdrop_curTarget.style.display    = '';
					__w2dragdrop_curTarget.style.visibility = 'visible';
				}

			} else {

				// our drag item is not in a container, so hide it.
				if(__w2dragdrop_curTarget.style.display!='none'){
					__w2dragdrop_curTarget.style.display  = 'none';
				}
			}
		}

		// track the current mouse state so we can compare against it next time
		__w2dragdrop_lMouseState = __w2dragdrop_iMouseDown;

		// mouseMove target
		__w2dragdrop_lastTarget  = target;


	if(__w2dragdrop_dragObject){
		__w2dragdrop_dragObject.style.position = 'absolute';
		__w2dragdrop_dragObject.style.top      = mousePos.y - __w2dragdrop_mouseOffset.y;
		__w2dragdrop_dragObject.style.left     = mousePos.x - __w2dragdrop_mouseOffset.x;
	}

	// track the current mouse state so we can compare against it next time
	__w2dragdrop_lMouseState = __w2dragdrop_iMouseDown;

	// this prevents items on the page from being highlighted while dragging
	if(__w2dragdrop_curTarget || __w2dragdrop_dragObject) return false;

}

function __w2dragdrop_mouseUp(ev)
{
    if(__w2dragdrop_oldmouseup!=null)
    {
        document.onmouseup = __w2dragdrop_oldmouseup;
    }

    if(__w2dragdrop_oldmousemove!=null)
    {
        document.onmousemove = __w2dragdrop_oldmousemove;
    }

        if(__w2dragdrop_curTarget)
		{
            __w2dragdrop_dragHelper.style.display = 'none';
			if(__w2dragdrop_curTarget.style.display == 'none'){
				if(__w2dragdrop_rootSibling){
					__w2dragdrop_rootParent.insertBefore(__w2dragdrop_curTarget, __w2dragdrop_rootSibling);
				} else {
					__w2dragdrop_rootParent.appendChild(__w2dragdrop_curTarget);
				}
			}
			__w2dragdrop_curTarget.style.display    = '';
			__w2dragdrop_curTarget.style.visibility = 'visible';
			__w2dragdrop_saveStatus=true;

			var origClass = __w2dragdrop_curTarget.getAttribute('origClass');
			if(origClass) __w2dragdrop_curTarget.className = origClass;

		}
		__w2dragdrop_curTarget  = null;
	if(__w2dragdrop_dragObject)
	{
		ev           = ev || window.event;
		var mousePos = __w2dragdrop_mouseCoords(ev);

		var dT = __w2dragdrop_dragObject.getAttribute('droptarget');
		if(dT){
			var targObj = document.getElementById(dT);
			var objPos  = __w2dragdrop_getPosition(targObj);
			if((mousePos.x > objPos.x) && (mousePos.y > objPos.y) && (mousePos.x<(objPos.x+parseInt(targObj.offsetWidth))) && (mousePos.y<(objPos.y+parseInt(targObj.offsetHeight)))){
				var nSrc = targObj.getAttribute('newSrc');
				if(nSrc){
					__w2dragdrop_dragObject.src = nSrc;
					setTimeout(function(){
						if(!__w2dragdrop_dragObject || !__w2dragdrop_dragObject.parentNode) return;
						__w2dragdrop_dragObject.parentNode.removeChild(__w2dragdrop_dragObject);
						__w2dragdrop_dragObject = null;
					}, parseInt(targObj.getAttribute('timeout')));
				} else {
					__w2dragdrop_dragObject.parentNode.removeChild(__w2dragdrop_dragObject);
				}
			}
		}

	}
	if (__w2dragdrop_lastTarget)
	{
		var origClass = __w2dragdrop_lastTarget.getAttribute('origClass');
		if(origClass) __w2dragdrop_lastTarget.className = origClass;
	}
	__w2dragdrop_dragObject = null;
	__w2dragdrop_lastTarget = null;
	__w2dragdrop_iMouseDown = false;

	if (__w2dragdrop_saveStatus == true)
	{
		__w2dragdrop_saveStatus=false;
		__w2dragdrop_saveCurrentStatus();
	}
}

function __w2dragdrop_mouseDown(ev){
	ev         = ev || window.event;
	var target = ev.target || ev.srcElement;

	__w2dragdrop_iMouseDown = true;
	if(target.onmousedown || target.getAttribute('DragObj')){
		return false;
	}

    __w2dragdrop_oldmousemove = document.onmousemove;
    __w2dragdrop_oldmouseup = document.onmouseup;
    document.onmousemove = __w2dragdrop_mouseMove;
    document.onmouseup = __w2dragdrop_mouseUp;

}


// cookie function to save status of divs.
function w2dragdrop_setCookieName(name)
{
	__w2dragdrop_cookieName = name;

	// retrieve current details
	__w2dragdrop_setCurrentStatus( __w2dragdrop_readCookie(__w2dragdrop_cookieName) );
}

function __w2dragdrop_createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function __w2dragdrop_readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function __w2dragdrop_eraseCookie(name) {
	__w2dragdrop_createCookie(name,"",-1);
}

function __w2dragdrop_saveCurrentStatus()
{
	var currentDivs = "";
	// loop each set
	for (var i=0;i<__w2dragdrop_DragDrops.length;i++)
	{
		// loop each div in the set
		for (var j=0;j<__w2dragdrop_DragDrops[i].length;j++)
		{
			// add top div name
			if (currentDivs != '') currentDivs+="#"
			currentDivs+=__w2dragdrop_DragDrops[i][j].id;

			// loop each element in this div
			for (var k=0;k<__w2dragdrop_DragDrops[i][j].childNodes.length;k++)
			{
				// add chiold items
				with(__w2dragdrop_DragDrops[i][j].childNodes[k])
				{
					if(nodeName=='#text') continue;
					currentDivs+='|' + id;
				}
			}
		}
	}

	__w2dragdrop_createCookie(__w2dragdrop_cookieName, currentDivs);
}

function __w2dragdrop_setCurrentStatus(encodedStatus)
{
	// any value stored?
	if (encodedStatus == null) return;

	// get top level containers
	var topContainers = encodedStatus.split('#');

	// store new version of top levels
	var newTops = [];

	// get the items that should be in it
	for(var i=0;i < topContainers.length;i++)
	{
		var items = topContainers[i].split('|');

		// first will be the top div name followed by a list of items
		var topDiv = items[0];

		newTops[i] = document.getElementById(topDiv).cloneNode(false);

		//alert( topDiv + " will contain the following ");
		for (var j=1;j<items.length;j++)
		{

			var child = document.getElementById( items[j] );
			if (child != null)
			{
				newTops[i].appendChild( child.cloneNode(true) );
			}
		}
	}

	// now replace top divs with new versions
	for (var i=0;i<newTops.length;i++)
	{
		// get this div
		var topDiv = document.getElementById(newTops[i].id);

		// remove current elements
		for (var j=topDiv.childNodes.length-1;j>=0; j--) topDiv.removeChild(topDiv.childNodes[j]);

		// add ours
		for (var k=0;k<newTops[i].childNodes.length;k++)
		{
			//alert(newTops[i].childNodes.id);
			topDiv.appendChild(newTops[i].childNodes[k].cloneNode(true));
		}
	}
}
