var mouseOffset = null;
var iMouseDown  = false;
var lMouseState = false;
var dragObject  = null;

var DragDrops   = [];
var curTarget   = null;
var lastTarget  = null;
var dragHelper  = null;
var tempDiv     = null;
var rootParent  = null;
var rootSibling = null;

var draghtmldisplay;
var dragtmpobject;

Number.prototype.NaN0=function(){return isNaN(this)?0:this;}
function hasClass(ele,cls) {
	return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
 
function addClass(ele,cls) {
	if (!this.hasClass(ele,cls)) ele.className += " "+cls;
}
 
function removeClass(ele,cls) {
	if (hasClass(ele,cls)) {
    	var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
		ele.className=ele.className.replace(reg,' ');
	}
}

function CreateDragContainer(containers){
   var cDrag        = DragDrops.length;
   DragDrops[cDrag] = [];
   
   for(var i=0; i<containers.length; i++){
      var cObj = containers[i];
      DragDrops[cDrag].push(cObj);
      cObj.setAttribute('DropObj', cDrag);
      for(var j=0; j<cObj.childNodes.length; j++){
         if(cObj.childNodes[j].nodeName=='#text') continue;
         if(cObj.childNodes[j].nodeName=='#comment') continue;
         cObj.childNodes[j].setAttribute('DragObj', cDrag);
         var headerItem = document.getElementById(cObj.childNodes[j].id + "_itemHeader");
         if (headerItem) {
            headerItem.setAttribute('DragObj', cDrag);
         }
      }
   }
}

function 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 mouseCoords(ev){
   if(ev.pageX || ev.pageY){
      return {x:ev.pageX, y:ev.pageY};
   }
try {
   return {
        x:ev.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft),
        y:ev.clientY + (document.documentElement.scrollTop || document.body.scrollTop)
   };
} catch(errorObject) {
    return {x:0, y:0};
}
}
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 mouseMove(ev){
   ev         = ev || window.event;
   var target   = ev.target || ev.srcElement;
   var mousePos = mouseCoords(ev);
   if(lastTarget && (target!==lastTarget)){
      var origClass = lastTarget.getAttribute('origClass');
      if(origClass) lastTarget.className = origClass;
   }
   var dragObj = target.getAttribute('DragObj');
   if(dragObj!=null){
      if (target.className == "itemHeader") {
         target = target.parentNode.parentNode; 
      }
      if(target!=lastTarget){
         var oClass = target.getAttribute('overClass');
         if(oClass){
            target.setAttribute('origClass', target.className);
            target.className = oClass;
         }
      }
   if(iMouseDown && !lMouseState){
      curTarget     = target;
      rootParent    = curTarget.parentNode;
      rootSibling   = curTarget.nextSibling;
      mouseOffset   = getMouseOffset(target, ev);
      for(var i=0; i<dragHelper.childNodes.length; i++) dragHelper.removeChild(dragHelper.childNodes[i]);
      for(var i=0; i<dragtmpobject.childNodes.length; i++) dragtmpobject.removeChild(dragtmpobject.childNodes[i]);
         dragHelper.appendChild(curTarget.cloneNode(true));
         dragHelper.style.display = 'block';
         for(var i=0; i<curTarget.childNodes.length; i++) {
            if(curTarget.childNodes[i].nodeName=='#text') continue;
            if(curTarget.childNodes[i].nodeName=='#comment') continue;
            dragtmpobject.appendChild(curTarget.childNodes[i].cloneNode(true));
         }
         dragtmpobject.style.visibility = 'hidden';
         for(var i=0; i<dragtmpobject.childNodes.length; i++) {
            dragtmpobject.childNodes[i].style.visibility = 'hidden';
         }
         var dragClass = curTarget.getAttribute('dragClass');
         if(dragClass){
            dragHelper.firstChild.className = dragClass;
         }
         dragHelper.firstChild.removeAttribute('DragObj');
         var dragConts = DragDrops[dragObj];
         curTarget.setAttribute('startWidth',  parseInt(curTarget.offsetWidth));
         curTarget.setAttribute('startHeight', parseInt(curTarget.offsetHeight));
         //curTarget.style.border  = '3px dotted black';
         addClass(curTarget,'DDBorder');
         draghtmldisplay = 'none';
         for(var i=0; i<dragConts.length; i++){
            with(dragConts[i]){
               var pos = getPosition(dragConts[i]);
               setAttribute('startWidth',  parseInt(offsetWidth));
               setAttribute('startHeight', parseInt(offsetHeight));
               setAttribute('startLeft',   pos.x);
               setAttribute('startTop',    pos.y);
            }
            for(var j=0; j<dragConts[i].childNodes.length; j++){
               with(dragConts[i].childNodes[j]){
                  if((nodeName=='#text') || nodeName=='#comment'||(dragConts[i].childNodes[j]==curTarget)) continue;
                     var pos = getPosition(dragConts[i].childNodes[j]);
                     setAttribute('startWidth',  parseInt(offsetWidth));
                     setAttribute('startHeight', parseInt(offsetHeight));
                     setAttribute('startLeft',   pos.x);
                     setAttribute('startTop',    pos.y);
                  }
               }
            }
         }
      }
      if(curTarget){
         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;
         var yPos = mousePos.y;
         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)){
                  activeCont = dragConts[i];
                  break;
               }
            }
         }
         if(activeCont){
            var beforeNode = null;
            for(var i=activeCont.childNodes.length-1; i>=0; i--){
               with(activeCont.childNodes[i]){
               if(nodeName=='#text') continue;
               if(nodeName=='#comment') continue;
               if(curTarget != activeCont.childNodes[i]                                                  &&
                  ((parseInt(getAttribute('startLeft')) + parseInt(getAttribute('startWidth')))  > xPos) &&
                  ((parseInt(getAttribute('startTop'))  + parseInt(getAttribute('startHeight'))) > yPos)){
                  beforeNode = activeCont.childNodes[i];
               }
            }
         }
         if(beforeNode){
            if(beforeNode!=curTarget.nextSibling){
               activeCont.insertBefore(curTarget, beforeNode);
            }
         } else {
            if((curTarget.nextSibling) || (curTarget.parentNode!=activeCont)){
               activeCont.appendChild(curTarget);
            }
         }
         setTimeout(function(){
         var contPos = 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);
         if(draghtmldisplay!=''){
            //curTarget.style.border    = '3px dotted black';
            addClass(curTarget,'DDBorder');
 

            draghtmldisplay = '';
            for(var j=0; j<curTarget.childNodes.length; j++){
               if(curTarget.childNodes[j].nodeName=='#text') continue;
               if(curTarget.childNodes[j].nodeName=='#comment') continue;
               curTarget.childNodes[j].style.visibility = 'hidden';
            }
         }
      } else {
         if(draghtmldisplay!='none'){
            //curTarget.style.border    = '3px dotted black';
            addClass(curTarget,'DDBorder');

            for(var j=0; j<curTarget.childNodes.length; j++){
               if(curTarget.childNodes[j].nodeName=='#text') continue;
               if(curTarget.childNodes[j].nodeName=='#comment') continue;
               curTarget.childNodes[j].style.visibility = 'hidden';
            }
            draghtmldisplay = 'none';
         }
      }
   }
   lMouseState = iMouseDown;
   lastTarget  = target;
   if(dragObject){
      dragObject.style.position = 'absolute';
      dragObject.style.top      = mousePos.y - mouseOffset.y;
      dragObject.style.left     = mousePos.x - mouseOffset.x;
   }
   lMouseState = iMouseDown;
   if(curTarget || dragObject) return false;
}

function getElementsByClassName(startobj,tagname,needle) {
   var my_array = startobj.getElementsByTagName(tagname);
   var retvalue = new Array();
   var i;
   var j;
   for (i=0,j=0;i<my_array.length;i++) {
      var c = " " + my_array[i].className + " ";
      if (c.indexOf(" " + needle + " ") != -1) retvalue[j++] = my_array[i];
   }
   return retvalue;
}

function mouseUp(ev){
   if(curTarget){
      dragHelper.style.display = 'none';
      if(draghtmldisplay == 'none'){
         if(rootSibling){
           rootParent.insertBefore(curTarget, rootSibling);
         } else {
            rootParent.appendChild(curTarget);
         }
      }
      for(var i=0; i<curTarget.childNodes.length; i++) {
         if(curTarget.childNodes[i].nodeName=='#text') continue;
         if(curTarget.childNodes[i].nodeName=='#comment') continue;
         curTarget.removeChild(curTarget.childNodes[i]);
      }
      //curTarget.style.border    = '';
      removeClass(curTarget,'DDBorder');
      for(var i=0; i<dragtmpobject.childNodes.length; i++) {
         if(dragtmpobject.childNodes[i].nodeName=='#text') continue;
         if(dragtmpobject.childNodes[i].nodeName=='#comment') continue;
         curTarget.appendChild(dragtmpobject.childNodes[i].cloneNode(true));
      }
      for(var i=0; i<curTarget.childNodes.length; i++) {
         if(curTarget.childNodes[i].nodeName=='#text') continue;
         if(curTarget.childNodes[i].nodeName=='#comment') continue;
         curTarget.childNodes[i].style.visibility = 'visible';
      }

      curTarget.style.visibility = 'visible';
      draghtmldisplay = '';
      //for(var j=0; j<curTarget.childNodes.length; j++){
         //if(curTarget.childNodes[j].nodeName=='#text') continue;
         //if(curTarget.childNodes[j].nodeName=='#comment') continue;
         //curTarget.childNodes[j].style.visibility = 'visible';
      //}
      var dragConts  = DragDrops[curTarget.getAttribute('DragObj')];
      var pos = "info=position";
      for(var i=0; i<dragConts.length; i++){
         pos =  pos + "&container" + i + "=" + dragConts[i].id ; 
         var els = getElementsByClassName(dragConts[i],"div","groupItem");
         for (var j=0; j<els.length;j++) {
            pos = pos + "&pos_" +i + "_" + j + "=" + els[j].id ;
         }
      }
      var url = "save_pos.html";
      var xmlHttpReq = false;
      var self = this;
      // Mozilla/Safari
      if (window.XMLHttpRequest) {
          self.xmlHttpReq = new XMLHttpRequest();
      }
      // IE
      else if (window.ActiveXObject) {
          self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
      }
      self.xmlHttpReq.open('POST', url, true);
      self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

      //var http = new XMLHttpRequest();
      //http.open("POST",url,true);
      //http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      //http.setRequestHeader("Content-length", pos.length);
      //http.setRequestHeader("Connection", "close");
      self.xmlHttpReq.send(pos);
   }
   curTarget  = null;
//   dragtmpobject = null;
   dragObject = null;
   iMouseDown = false;
}

function mouseDown(ev){
   ev         = ev || window.event;
   var target = ev.target || ev.srcElement;
   iMouseDown = true;
   if(target.onmousedown || target.getAttribute('DragObj')){
      return false;
   }
}

function makeDraggable(item){
   if(!item) return;
   item.onmousedown = function(ev){
      dragObject  = this;
      mouseOffset = getMouseOffset(this, ev);
      return false;
   }
}

function makeClickable(item){
   if(!item) return;
   item.onmousedown = function(ev){
      document.getElementById('ClickImage').value = this.name;
   }
}

function addDropTarget(item, target){
   item.setAttribute('droptarget', target);
}

document.onmousemove = mouseMove;
document.onmousedown = mouseDown;
document.onmouseup   = mouseUp;

function init_dnd(){
   var containers = [];
   for(var i=0; i<arguments.length; i++){
      containers[i]=document.getElementById(arguments[i]);
   }
   CreateDragContainer(containers);
   dragHelper = document.createElement('DIV');
   dragtmpobject = document.createElement('DIV');
   dragHelper.style.cssText = 'position:absolute;display:none;width:300px';
   document.body.appendChild(dragHelper);
   document.body.appendChild(dragtmpobject);
}

