// Demo variables
// 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 lastTarget  = null;
var dragHelper  = null;
var curTargetTmp  = null;
var tempDiv     = null;
var rootParent  = null;
var rootSibling = null;
var newParent = null;
var newSibling = null;
var nImg        = new Image();

nImg.src        = 'images/drag_drop_poof.gif';

// Demo1 variables
var D1Target    = null;

Number.prototype.NaN0=function(){return isNaN(this)?0:this;}

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;
	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++){
			// if (cObj.childNodes[j].tagName == 'DIV') {
				// if (cObj.childNodes[j].childNodes[0].tagName == 'H3') cObj.childNodes[j].childNodes[0].style.cursor = 'move';
			// }
			// Firefox puts in lots of #text nodes...skip these
			if(cObj.childNodes[j].nodeName != '#text' && cObj.childNodes[j].nodeName != '#comment') {
				for(var k=0; k<cObj.childNodes[j].childNodes.length; k++){
					if (cObj.childNodes[j].childNodes[k].nodeName == 'H3') {
						cObj.childNodes[j].childNodes[k].style.cursor = 'move';
						cObj.childNodes[j].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);

	// $('his').innerHTML = [left,top]+'<br>';
	return {x:left, y:top};

}
function setPageCoords(){
	var myPageX;
	var myPageY;
	if(document.documentElement.scrollLeft>=0){
		myPageX=document.documentElement.scrollLeft;
		myPageY=document.documentElement.scrollTop;
	}else if(document.body.scrollLeft>=0){
		myPageX=document.body.scrollLeft;
		myPageY=document.body.scrollTop;
	}else{
		myPageX=window.pageXOffset;
		myPageY=window.pageYOffset;
	}
	return [document.documentElement.scrollTop];
}


function mouseCoords(ev){
	if(ev.pageX || ev.pageY){
		return {x:ev.pageX, y:ev.pageY};
	}
	
	if(document.documentElement.scrollLeft >=0 || document.documentElement.scrollTop >=0){
		scrollLeft = document.documentElement.scrollLeft;
		scrollTop = document.documentElement.scrollTop;
	} else if (document.body.scrollLeft>=0 || document.body.scrollTop >=0) {
		scrollLeft = document.body.scrollLeft;
		scrollTop = document.body.scrollTop;
	} else {
		scrollLeft = window.pageXOffset;
		scrollTop = window.pageYOffset;
	}
	
	return {
		x:ev.clientX + scrollLeft - document.body.clientLeft,
		y:ev.clientY + scrollTop  - document.body.clientTop
	};
}

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};
}

var mouseMove = function(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;
	if (target.tagName == 'H3' && instr('panel',target.parentNode.className)) target = target.parentNode;
	// else target = null;
	if (target) {
		target = $(target);
		// document.onselectstart = function() {return false;} 
		var mousePos = mouseCoords(ev);
		var dragObj = target.getAttributes('DragObj');

		 // if the mouse was moved over an element that is draggable
		if(dragObj!=null){

			// if the user is just starting to drag the element
			if(iMouseDown && !lMouseState){
				curTarget     = target;

				rootParent    = curTarget.parentNode;
				rootSibling   = curTarget.nextSibling;

				// Record the mouse x and y offset for the element
				mouseOffset   = getMouseOffset(target, ev);

				// We remove anything that is in our dragHelper DIV so we can put a new item in it.
				dragHelper = new ezElement('DIV').setStyle('position','absolute').appendTo(target.parentNode);
				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.
				target.style.height = target.offsetHeight + 'px';
				curTargetTmp = curTarget.cloneNode(true);
				curTargetTmp = $(curTargetTmp);
				dragHelper.appendChild(curTargetTmp.cloneNode(true));
				dragHelper.show();
				// dragHelper.style.width = target.offsetWidth + 'px';
				dragHelper.setStyles({width : target.offsetWidth + 'px', opacity : 0.6});
				// dragHelper.style.width = target.offsetWidth + 'px';
		    // dragHelper.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=60,finishOpacity=100,style=0)';
		    // dragHelper.style.opacity = 0.6;
				

				// set the class on our helper DIV if necessary
				/*var dragClass = curTarget.getAttribute('dragClass');
				if(dragClass){
					dragHelper.firstChild.className = dragClass;
				}*/

				// 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.
				*/
				curTargetTmp.setAttributes({startWidth : parseInt(curTarget.offsetWidth), startHeight : parseInt(curTarget.offsetHeight)});
				// curTargetTmp.setAttribute('startHeight', parseInt(curTarget.offsetHeight));
				curTargetTmp.className = 'panel panelTmp';
				// curTarget.style.border = '1px dashed #aaaaaa';
				curTargetTmp.innerHTML = '';
				curTargetTmp.hide();
				curTarget.hide();

				// 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.
						*/
						dragConts[i].setAttributes({
							startWidth : parseInt(dragConts[i].offsetWidth),
							startHeight : parseInt(dragConts[i].offsetHeight),
							startLeft : pos.x,
							startTop : pos.y
						});
						// setAttribute('startHeight', parseInt(offsetHeight));
						// setAttribute('startLeft',   pos.x);
						// setAttribute('startTop',    pos.y);
					// }

					// loop through each child element of each container
					var dChild = dragConts[i].getChilds();
					for(var j=0; j<dChild.length; j++){
						if((dChild[j].nodeName=='#text') || (dChild[j].nodeName=='#comment') || (dChild[j]==curTargetTmp)) continue;

						var pos = getPosition(dChild[j]);

						// save the width, height and position of each element
						dChild[j].setAttributes({
							startWidth : parseInt(dChild[j].offsetWidth),
							startHeight : parseInt(dChild[j].offsetHeight),
							startLeft : pos.x,
							startTop : pos.y
						});
						// 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(curTarget){
			// move our helper div to wherever the mouse is (adjusted by mouseOffset)
			dragHelper.setStyles({top : (mousePos.y - mouseOffset.y) + 'px', left : (mousePos.x - mouseOffset.x) + 'px', cursor : 'move'});
			// dragHelper.style.top  = (mousePos.y - mouseOffset.y) + 'px';
			// dragHelper.style.left = (mousePos.x - mouseOffset.x) + 'px';
			// dragHelper.style.cursor = 'move';
			// $('his').innerHTML += [dragHelper.style.top,dragHelper.style.left] + '<br>';
			// alert([(mousePos.y - mouseOffset.y),(mousePos.x - mouseOffset.x)]);

			var dragConts  = DragDrops[curTarget.getAttributes('DragObj')];
			var activeCont = null;
			var pos = mouseCoords(ev);

			var xPos = pos.x;
			var yPos = pos.y;
			
			// 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(getAttributes('startLeft'))                                           < xPos) &&
						(parseInt(getAttributes('startTop'))                                            < yPos) &&
						((parseInt(getAttributes('startLeft')) + parseInt(getAttributes('startWidth')))  > xPos) &&
						((parseInt(getAttributes('startTop'))  + parseInt(getAttributes('startHeight'))) > yPos)){

							// $('his').innerHTML = [parseInt(getAttribute('startLeft')),parseInt(getAttribute('startTop'))];
							/*
							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){
				curTargetTmp.className = 'panel panelTmp';
				// curTarget.style.border = '1px dashed #aaaaaa';
				// beforeNode will hold the first node AFTER where our div belongs
				var beforeNode = null;

				// loop through each child node (skipping text nodes).
				var aChild = activeCont.getChilds()
				for(var i=aChild.length-1; i>=0; i--){
					with(aChild[i]){
						if(nodeName=='#text' || nodeName=='#comment') continue;

						// if the current item is "After" the item being dragged
						if(curTargetTmp != activeCont.childNodes[i]                                                  &&
							((parseInt(getAttributes('startLeft')) + parseInt(getAttributes('startWidth')))  > xPos) &&
							((parseInt(getAttributes('startTop'))  + parseInt(getAttributes('startHeight'))) > yPos)){
								beforeNode = activeCont.childNodes[i];
						}
					}
				}

				// the item being dragged belongs before another item
				if(beforeNode){
					if(beforeNode!=curTargetTmp.nextSibling){
						activeCont.insertBefore(curTargetTmp, beforeNode);
						newParent = activeCont;
						newSibling = beforeNode;
					}

				// the item being dragged belongs at the end of the current container
				} else {
					if((curTargetTmp.nextSibling) || (curTargetTmp.parentNode!=activeCont)){
						activeCont.appendChild(curTargetTmp);
						newParent = activeCont;
						newSibling = null;
					}
				}

				// the timeout is here because the container doesn't "immediately" resize
				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);

				// make our drag item visible
				if(curTargetTmp.isHide()){
					curTargetTmp.show();
					// if(activeCont.id == 'dragNone') curTargetTmp.style.width = '90%';
					// else curTargetTmp.style.width = curTarget.offsetWidth + 'px';
					// curTarget.style.visibility = 'hidden';
					// curTarget.style.border = '1px solid black';
				}
				if(activeCont.id == 'dragNone') curTargetTmp = addClassName(curTargetTmp,'panelNoneTmp');
				else curTargetTmp = removeClassName(curTargetTmp,'panelNoneTmp');
			} else {

				// our drag item is not in a container, so hide it.
				if(curTargetTmp.style.display!='none'){
					curTargetTmp.style.display  = 'none';
				}
			}
		}

		// track the current mouse state so we can compare against it next time
		lMouseState = iMouseDown;

		// mouseMove target
		lastTarget  = target;

		if(dragObject){
			dragObject.style.position = 'absolute';
			dragObject.style.top      = mousePos.y - mouseOffset.y;
			dragObject.style.left     = mousePos.x - mouseOffset.x;
		}

		// track the current mouse state so we can compare against it next time
		lMouseState = iMouseDown;

		// this prevents items on the page from being highlighted while dragging
		if(curTargetTmp || dragObject) return false;
	}
}

var mouseUp = function(ev){
	if(curTarget){
		// if(rootParent.childNodes.length <= 1) {
			// // alert('Must has at least 1 panel in side');
			// // newSibling  = rootSibling;
		// }
		dragHelper.hide();
		// alert(curTarget.innerHTML);
		// curTarget.className = 'panel';
		//curTarget.innerHTML = dragHelper.firstChild.innerHTML;
		curTarget.style.height = 'auto';
		if(curTargetTmp.parentNode.id == 'dragNone') {
			curTarget = removeClassName(curTarget,'green','blue','orange','pink','gray','purple');
			curTarget = addClassName(curTarget,'gray');
			curTarget = addClassName(curTarget,'panelNone');
		} else {
			curTarget = removeClassName(curTarget,'panelNone');
		}

		if(curTargetTmp.style.display != 'none'){
			if(newSibling){
				curTargetTmp.parentNode.insertBefore(curTarget, newSibling);
			} else {
				curTargetTmp.parentNode.appendChild(curTarget);
			}
			
			if(mouseupSave) {
				if (rootSibling && newSibling) {
					if (rootSibling.id != newSibling.id) saveSetting();
				} else if ((rootSibling && !newSibling) || (newSibling && !rootSibling)) {
					saveSetting();
				} else {
					if (rootParent.id != newParent.id) saveSetting();
				}
			} else {
				updateSort();
			}
		}
		
		curTarget.style.display    = '';
		curTarget.style.visibility = 'visible';
		curTargetTmp.parentNode.removeChild(curTargetTmp);
		
	}
	curTarget  = null;
	curTargetTmp  = null;

	dragObject = null;

	iMouseDown = false;
	
	/*if ($('content2')) {
		height = $('content2').offsetHeight;

		if ($('containerLeft')) $('containerLeft').style.height = (height-90) + 'px';
		if ($('containerRight')) $('containerRight').style.height = (height-90) + 'px';
	}*/
}

var mouseDown = function(ev){
	ev         = ev || window.event;
	var target = ev.target || ev.srcElement;

	iMouseDown = true;
	if(target.onmousedown || (target.tagName == 'H3' && instr('panel',target.parentNode.className))){
		if (target.parentNode.getAttributes('DragObj')) return false;
	}
	
	if ($('colorPlate') || $('tcolorPlate') || $('uploadBox')) while (target.nodeType != 1) target = target.parentNode;

	if ($('colorPlate')) {
		if(target.id != 'colorPlate' && target.parentNode.id != 'colorPlate' && target.parentNode.parentNode.id != 'colorPlate') {
			$('colorPlate').style.display = 'none';
		}
	}
	
	if ($('tcolorPlate')) {
		if(target.id != 'tcolorPlate' && target.parentNode.id != 'tcolorPlate' && target.parentNode.parentNode.id != 'tcolorPlate') {
			$('tcolorPlate').style.display = 'none';
		}
	}
	
	if ($('uploadBox')) {
		if(target.id != 'uploadBox' && target.parentNode.id != 'uploadBox' && target.parentNode.parentNode.id != 'uploadBox') {
			$('uploadBox').style.display = 'none';
		}
	}
}

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);
}

//==============================================================================================================================================
// GADGET
//==============================================================================================================================================

function updateSort() {
	var sortLeft = '';
	var sortCenter = '';
	var sortRight = '';
	var theme = getSort();
	var sort = {'left' : '', 'right' : '', 'center' : ''};
	
	for(k in sort) {
		if (theme.sort[k]) {
			var tmp = theme.sort[k].split(',');
			var ctmp = theme.color[k].split(',');
			for(var i in tmp) sort[k] += (sort[k] ? '&' : '') + tmp[i] + '=' + ctmp[i];
		}
	}
	
	if($('sortLeft')) $('sortLeft').value = sort.left;
	if($('sortCenter')) $('sortCenter').value = sort.center;
	if($('sortRight')) $('sortRight').value = sort.right;
}

function getSort(id) {
	var objs = {'left' : 'dragLeft', 'right' : 'dragRight', 'center' : 'dragCenter'};
	var sort = {'left' : '', 'right' : '', 'center' : ''};
	var color = {'left' : '', 'right' : '', 'center' : ''};
	
	// alert(print_r(objs));
	for(k in objs) {
		if ($(objs[k])) {
			var obj = $(objs[k]).getChilds({tagName : 'DIV'});
			for(i=0;i<obj.length;i++) {
				if(!obj[i].hasClassName('panelTmp') && obj[i].hasClassName('panel') && instr('panel_',obj[i].id)) {
					sort[k] += (sort[k] ? ',' : '') + obj[i].id.replace('panel_','');
					color[k] += (color[k] ? ',' : '') + trim(obj[i].className.replace('panel',''));
				}
			}
		}
	}
	
	// var obj = $('containerLeft').getElementsByTagName('DIV');
	// for(i=0;i<obj.length;i++) {
		// if(!instr('panelTmp',obj[i].className) && instr('panel',obj[i].className) && instr('panel_',obj[i].id)) {
			// leftDiv = true;
			// strL += (strL ? ',' : '') + obj[i].id.replace('panel_','');
		// }
	// }

	// var rightDiv = false;
	// var obj = $('containerRight').getElementsByTagName('DIV');
	// for(i=0;i<obj.length;i++) {
		// if(!instr('panelTmp',obj[i].className) && instr('panel',obj[i].className) && instr('panel_',obj[i].id)) {
			// rightDiv = true;
			// strR += (strR ? ',' : '') + obj[i].id.replace('panel_','');
		// }
	// }

	// var centerDiv = false;
	// var obj = $('containerCenter').getElementsByTagName('DIV');
	// for(i=0;i<obj.length;i++) {
		// if(!instr('panelTmp',obj[i].className) && instr('panel',obj[i].className) && instr('panel_',obj[i].id)) {
			// centerDiv = true;
			// strR += (strR ? ',' : '')+ obj[i].id.replace('panel_','');
		// }
	// }
	// return sort;
	return {'sort' : sort, 'color' : color};
}

function showMenu(id) {
	if ($(id)) {
		var titleInner = $(id).getElementsByTagName('h3')[0].innerHTML;
		var contentDiv = $(id).getElementsByTagName('div')[0];
		contentDiv.style.display = contentDiv.style.display == 'none' ? 'block' : 'none';
	}
}