// 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 mouseOffset = null;
var iMouseDown  = false;
var lMouseState = false;
var dragObject  = null;

// Demo 0 variables
var DragDrops   = [];
var curTarget   = null;
var curTargetStartLeft = 0;
var curTargetStartRight = 0;
var curTargetStartIndex = 0;
var lastTarget  = null;
var dragHelper  = null;
var tempDiv     = null;
var rootParent  = null;
var rootSibling = null;
var withinContainer = false;
var horizontalDrag = false;

var dragdropCallbackObject = null;

function dragdropCallback()
{
    this.Initialize = function()
    {
        this.onMouseDownCallback = function(dragObject) {};
        this.onMouseUpCallback = function(dragObject) {};
        this.onMouseMoveCallback = function(dragObject) {};
    };
    
    this.Initialize();
};


Number.prototype.NaN0=function(){return isNaN(this)?0:this;}

window.onload = function(){
    CreateDragHelper();
}


function CreateDragHelper()
{
	dragHelper = document.createElement('DIV');
	dragHelper.style.cssText = 'position:absolute;display:none;';
    document.body.appendChild(dragHelper);
}

function CreateDragContainer(){
	/*
	Create a new "Container Instance" so that items from one "Set" can not
	be dragged into items from another "Set"
	*/
	
	
	var cDrag        = DragDrops.length;
	var numDragDrops = DragDrops.length;
	var dragDropIdx;
	for (dragDropIdx = 0; dragDropIdx < numDragDrops; dragDropIdx++)
	{
	    var dragConts=DragDrops[dragDropIdx];
        var container;
        var containerIdx;
        var numContainers = dragConts.length;
        for (containerIdx = 0; containerIdx < numContainers; containerIdx++)
        {
            container = dragConts[containerIdx];
            if (container==arguments[0])
            {
                cDrag = dragDropIdx;
                break;
            } 
        }

	}

	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];
		DragDrops[cDrag].push(cObj);
		cObj.setAttribute('DropObj', cDrag);

		/*
		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;
            if (noDrag(cObj.childNodes[j])) continue;
            
			cObj.childNodes[j].setAttribute('DragObj', cDrag);
		}
	}
}

function noDrag(node)
{
    var noDragAllowed = false;
    var noDragAttribute = node.getAttribute("nodrag");
    if (noDragAttribute && (noDragAttribute == "true")) {
        noDragAllowed = true;
    }
    return noDragAllowed;
}

function dragdropMouseMove(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 = mouseCoords(ev);

	// mouseOut event - fires if the item the mouse is on has changed
	if(lastTarget && (target!==lastTarget)){
		// reset the classname for the target element
		var origClass = lastTarget.getAttribute('origClass');
		if(origClass) 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');

	 // if the mouse was moved over an element that is draggable
	if(dragObj!=null){

		// mouseOver event - Change the item's class if necessary
		if(target!=lastTarget){
			var oClass = target.getAttribute('overClass');
			if(oClass){
				target.setAttribute('origClass', target.className);
				target.className = oClass;
			}
		}

		// if the user is just starting to drag the element
		if(iMouseDown && !lMouseState){
		
			// mouseDown target
			curTarget     = target;

			// Record the mouse x and y offset for the element
			rootParent    = curTarget.parentNode;
			rootSibling   = curTarget.nextSibling;

			mouseOffset   = getMouseOffset(target, ev);

			// We remove anything that is in our dragHelper DIV so we can put a new item in it.
			for(var i=0; i<dragHelper.childNodes.length; i++) dragHelper.removeChild(dragHelper.childNodes[i]);

			// Make a copy of the current item and put it in our drag helper.
			dragHelper.appendChild(curTarget.cloneNode(true));


			if (dragHelper.firstChild.style.position == "absolute")
			{
			    dragHelper.firstChild.style.left="0px";
			    dragHelper.firstChild.style.top="0px";
			}

			// set the class on our helper DIV if necessary
			//-- Note: drag class is ignored if there is a style set on the element in xhtml... GNPD
			var dragClass = curTarget.getAttribute('dragClass');
			if(dragClass){
				dragHelper.firstChild.className = dragClass;
			}
			

			dragHelper.style.display = 'block';
			// disable dragging from our helper DIV (it's already being dragged)
			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 = 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.
			*/
			curTarget.setAttribute('startWidth',  parseInt(curTarget.offsetWidth));
			curTarget.setAttribute('startHeight', parseInt(curTarget.offsetHeight));

			var curTargetPos = getPosition(curTarget);
            curTargetStartLeft = curTargetPos.x;
            curTargetStartRight = curTargetStartLeft + curTarget.offsetWidth;
            curTargetStartIndex = findChildIndex(getParent(curTarget), curTarget);

			curTarget.style.display  = 'none';

			// loop through each possible drop container
			for(var i=0; i<dragConts.length; i++){
				with(dragConts[i]){
					var pos = 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);
				}

                trace("setting start lefts");
				// 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')  continue;
                        if (getAttribute('DragObj') == null) continue;

						var pos = getPosition(dragConts[i].childNodes[j]);

                        //if (dragConts[i].childNodes[j]!=curTarget)
//                        {
//                            curTargetStartLeft = parseInt(pos.x);
//                        }
//                        else
                        {
						    // 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);
						}
					}
				}
				
				//-- remove from curTarget
//				curTarget.removeAttribute('startWidth');
//				curTarget.removeAttribute('startHeight');
//				curTarget.removeAttribute('startLeft');
//				curTarget.removeAttribute('startTop');
			}
		}
	}

	// If we get in here we are dragging something
	if(curTarget){
	
	    ev.cancelBubble = true;
	    ev.returnValue = false;
	
		// move our helper div to wherever the mouse is (adjusted by mouseOffset)
		dragHelper.style.top  = (mousePos.y - mouseOffset.y) + "px";
		dragHelper.style.left = (mousePos.x - mouseOffset.x) + "px";
		
		var dragConts  = DragDrops[curTarget.getAttribute('DragObj')];
		var activeCont = null;

		var xPos = mousePos.x - mouseOffset.x + (parseInt(curTarget.getAttribute('startWidth')) /2);
		var yPos = mousePos.y - mouseOffset.y + (parseInt(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(((getAttribute('startLeft'))                               < xPos) &&
					((getAttribute('startTop'))                                < yPos) &&
					((getAttribute('startLeft') + getAttribute('startWidth'))  > xPos) &&
					((getAttribute('startTop')  + 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;
				}
			}
		}

		// Our target object is in one of our containers.  Check to see where our div belongs
		if(activeCont){
		    withinContainer = true;

            //-- GNPD if we use css to force a single row of divs then the logic for placement changes 
		    var dragstyle = activeCont.getAttribute("dragstyle");
		    if (dragstyle && (dragstyle == "horizontal"))
		    {
		        horizontalDrag = true;
            }

			// beforeNode will hold the first node AFTER where our div belongs
			var beforeNode = null;

	
            if (horizontalDrag)
            {
                var curTargetIdx = findChildIndex(activeCont, curTarget);
                beforeNode = nextDragObjSibling(activeCont, curTargetIdx);
                
//                beforeNode = curTarget.nextSibling;
			    // loop through each child node (skipping text nodes).
			    var traceString = "activeCont.childNodes.length = " + activeCont.childNodes.length ;
			    for(var i=activeCont.childNodes.length-1; i>=0; i--){

				    with(activeCont.childNodes[i]){
					    if(nodeName=='#text') continue;
					    if(getAttribute('DragObj')==null) continue;

					    if( curTarget != activeCont.childNodes[i])
					    {
					        var startLeft  = getAttribute('startLeft');
					        var startWidth = getAttribute('startWidth');
					        var startRight = parseInt(startLeft)+parseInt(startWidth);
                            
						    if ( (mousePos.x > startLeft) && (mousePos.x < startRight))
						    {
						        traceString += "; i = " + i + "; startLeft = " + startLeft + "; startRight = " + startRight + "; mousePos.x = " + mousePos.x + "; curTargetStartLeft = " + curTargetStartLeft;
						        if (startLeft < curTargetStartLeft)
						        {
					                beforeNode = activeCont.childNodes[i];
					            }
					            else
					            {
					                if (i<(activeCont.childNodes.length-1))
					                {
                                        beforeNode = nextDragObjSibling(activeCont, i);
					                }
					                else
					                {
    					                beforeNode = null;
					                }
					            }
                            }
					    }
					    else
					    {
						    if ( (mousePos.x > curTargetStartLeft) && (mousePos.x < curTargetStartRight))
						    {
                                beforeNode = nextDragObjSibling(activeCont, curTargetStartIndex);
						    }
					    }
				    }
			    }
			    trace(traceString);
            }
            else
            {
			    // 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(
						    curTarget != activeCont.childNodes[i]                              &&
						    ((getAttribute('startLeft') + getAttribute('startWidth'))  > xPos) &&
						    ((getAttribute('startTop')  + getAttribute('startHeight')) > yPos)){
							    beforeNode = activeCont.childNodes[i];
					    }
				    }
			    }
			}

		    // the item being dragged belongs before another item
		    var changed = false;
		    if(beforeNode){
                var curTargetIdx = findChildIndex(activeCont, curTarget);
                trace("curTargetIdx == "+curTargetIdx);
                lastBeforeNode = nextDragObjSibling(activeCont, curTargetIdx);
			    if(beforeNode!=lastBeforeNode){
				    activeCont.insertBefore(curTarget, beforeNode);
			        changed = true;
			    }

		    // the item being dragged belongs at the end of the current container
		    } else {
			    if((curTarget.nextSibling) || (curTarget.parentNode!=activeCont)){
				    activeCont.appendChild(curTarget);
			        changed = true;
			    }
		    }
			if (changed && horizontalDrag)
			{
			    var dragstyle = activeCont.getAttribute("dragstyle");
			    if (dragstyle && (dragstyle == "horizontal"))
			    {
			        //-- need to shuffle through the children adjusting the left style attribute
			        var children = getChildren(activeCont);
			        var childIdx;
			        var left = 0;
			        for (childIdx=0; childIdx<children.length; childIdx++)
			        {
			            var node = children[childIdx];
		                if (node.getAttribute('DragObj')==null) continue;

			            node.style.left = left+"px";
			            left += parseInt(node.style.width);
//			            left += parseInt(node.style.paddingLeft);
//			            left += parseInt(node.style.paddingRight);
			        }
			    }
			}

			// make our drag item visible
//			if(curTarget.style.display!=''){
//				curTarget.style.display  = '';
//			}
		} else {
		    withinContainer = false;

			// our drag item is not in a container, so hide it.
//			if(curTarget.style.display!='none'){
//				curTarget.style.display  = 'none';
//			}
		}
	}

	// track the current mouse state so we can compare against it next time
	lMouseState = iMouseDown;

	// mouseMove target
	lastTarget  = target;

	// track the current mouse state so we can compare against it next time
	lMouseState = iMouseDown;

	// this helps prevent items on the page from being highlighted while dragging
	return false;
}

function findChildIndex(parent, childTarget)
{
    var result = 0;
    var children = getChildren(parent);
    var childIdx;
    for (childIdx=0; childIdx<children.length; childIdx++)
    {
        var child = children[childIdx];
        if (child == childTarget)
        {
            result = childIdx;
            break;
        }
    }
    return result;
}


function nextDragObjSibling(parent, index)
{
    var result = null;
    var children = getChildren(parent);
    var childIdx;
    for (childIdx=index+1; childIdx<children.length; childIdx++)
    {
        var child = children[childIdx];
        if (child.getAttribute('DragObj') == null) continue;
        result = child;
        break;
    }
    return result;
}

function dragdropMouseUp(ev){
	if(curTarget){

		// hide our helper object - it is no longer needed
		dragHelper.style.display = 'none';

		// if the drag item is invisible put it back where it was before moving it
		if (!horizontalDrag)
		{
		    if (!withinContainer){
			    if(rootSibling){
				    rootParent.insertBefore(curTarget, rootSibling);
			    } else {
				    rootParent.appendChild(curTarget);
			    }
		    }
        }
		// make sure the drag item is visible
		curTarget.style.display = '';
        if (dragdropCallbackObject)
        {
            dragdropCallbackObject.onMouseUpCallback(curTarget);
        }
	}
	withinContainer = false;
	curTarget  = null;
	iMouseDown = false;
	horizontalDrag = false;
}

function dragdropMouseDown(){
	iMouseDown = true;
	if(lastTarget){
		return false;
	}
}


function mouseCoords(ev){
	if(ev.pageX || ev.pageY){
		return {x:ev.pageX, y:ev.pageY};
	}
//    trace('ev.clientX ==' + ev.clientX + ', document.body.scrollLeft == '+ document.body.scrollLeft +', document.body.clientLeft == ' + document.body.clientLeft +', document.body.offsetLeft == ' + document.body.offsetLeft  +', document.documentElement.scrollLeft == ' + document.documentElement.scrollLeft);
	
	 if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
	    return {
		    x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
		    y:ev.clientY + document.body.scrollTop  - document.body.clientTop
	    };
      } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
	    return {
		    x:ev.clientX + document.documentElement.scrollLeft,
		    y:ev.clientY + document.documentElement.scrollTop
	    };
      }
      else
      {
	    return {
		    x:ev.clientX,
		    y:ev.clientY 
	    };
      }
}


function getMouseOffset(target, ev){
	ev = ev || window.event;

	var docPos    = getPosition(target);
	var mousePos  = mouseCoords(ev);

	return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
}

function getPosition(e){
	var left = 0;
	var top  = 0;

	while (e.offsetParent){
		left += e.offsetLeft;
		left -= e.scrollLeft;
		top  += e.offsetTop;
		top  -= e.scrollTop;
		e     = e.offsetParent;
	}

	left += e.offsetLeft;
	top  += e.offsetTop;


//	left += document.body.scrollLeft - document.body.clientLeft;
//	top += document.body.scrollTop  - document.body.clientTop;



	return {x:left, y:top};
}




/*
document.onmousemove = dragdropMouseMove;
document.onmousedown = dragdropMouseDown;
document.onmouseup   = dragdropMouseUp;

window.onload = function(){
	// Create our helper object that will show the item while dragging
	dragHelper = document.createElement('DIV');
	dragHelper.style.cssText = 'position:absolute;display:none;';
		
	CreateDragContainer(
		document.getElementById('DragContainer1'),
		document.getElementById('DragContainer2'),
		document.getElementById('DragContainer3')
	);

	document.body.appendChild(dragHelper);
}
*/
