function getPosition(e){
	var left = 0;
	var top  = 0;

	while (e.offsetParent){
		left += e.offsetLeft;
		top  += e.offsetTop;
		e     = e.offsetParent;
	}

	left += e.offsetLeft;
	top  += e.offsetTop;

	return {x:left, y:top};
}
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 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
	};
}

// 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 tempDiv     = null;
var rootParent  = null;
var rootSibling = null;

var DragDropMoveObj = null;
var DragDropMoveObjs   = [];

Number.prototype.NaN0=function(){return isNaN(this)?0:this;}

function FFCheckDragContainers(containers){
	var ids = String(containers).split(',');
	var objs = new Array();
	for (var i=0; i<ids.length;i++) {
		var obj = document.getElementById(ids[i]);
		if (obj) {
			objs.push(obj);
		}
	}
	if (isFirefox()) {
		for(var i=0; i<objs.length; i++){
			var cObj = objs[i];
			var div = document.createElement('DIV');
			div.style.width='100%';
			div.style.height='1px';
			cObj.appendChild(div);
		}
	}
}

function CreateDragContainer(cDrag,objs){
	/*
	Create a new "Container Instance" so that items from one "Set" can not
	be dragged into items from another "Set"
	*/
	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<objs.length; i++){
		var cObj = objs[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;

			cObj.childNodes[j].setAttribute('DragObj', cDrag);

		}
	}
}

function mouseMove(ev){

	ev         = ev || window.event;

	// por padrão retorna true para executar o evento
	var rvalue = true;

	/*
	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);

	try {

//		// 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;
//		}

	} catch(e) {}

	/*
	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.
	*/

	target = getDragTarget(target);

	try {

		var dragObj = target.getAttribute('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){

				// retorna falso para não selecionar
				rvalue = false;

				// 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));
				dragHelper.style.display = 'block';

				// set the class on our helper DIV if necessary
				var dragClass = curTarget.getAttribute('dragClass');
				if(dragClass){
					var c = dragHelper.firstChild.className;
					dragHelper.firstChild.className = c+' '+dragClass;
				}

				// especifica o tamanho para ficar igual ao original
				dragHelper.firstChild.style.width = parseInt(curTarget.offsetWidth);
				dragHelper.firstChild.style.height = parseInt(curTarget.offsetHeight);

				// 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));
				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) + 450);
						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]==curTarget)) continue;

							var pos = 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);
						}
					}
				}

				// loop through each possible drop container
				for(var i=0; i<DragDropMoveObjs.length; i++){
					with(DragDropMoveObjs[i]){
						var pos = getPosition(DragDropMoveObjs[i]);
						setAttribute('startWidth',  parseInt(offsetWidth));
						setAttribute('startHeight', parseInt(offsetHeight));
						setAttribute('startLeft',   pos.x);
						setAttribute('startTop',    pos.y);
					}
				}

			}
		}

	} catch(e) {}

	// If we get in here we are dragging something
	if(curTarget){

		// mouseOver event - Change the item's class if necessary
		if(curTarget){
			if (!curTarget.getAttribute('origClass')) {
				var oClass = curTarget.getAttribute('overClass');
				if(oClass){
					curTarget.setAttribute('origClass', curTarget.className);
					curTarget.className = curTarget.className+' '+oClass;
				}
			}
		}

		// retorna falso para não selecionar
		rvalue = false;

		// move our helper div to wherever the mouse is (adjusted by mouseOffset)
		dragHelper.style.top  = mousePos.y - mouseOffset.y;
		dragHelper.style.left = mousePos.x - mouseOffset.x;

		var dragConts  = DragDrops[curTarget.getAttribute('DragObj')];
		var activeCont = null;
		var activeMove = 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]){

				// parseInt é para funcionar direito no firefox
				if(((getAttribute('startLeft'))                               < xPos) &&
					((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;
				}
			}
		}

		// pega valor do scroll
		var phs = document.getElementById('phs').scrollLeft;

		// check each drop container to see if our target object is "inside" the container
		for(var i=0; i<DragDropMoveObjs.length; i++){
			with(DragDropMoveObjs[i]){

				// parseInt é para funcionar direito no firefox
				if(((getAttribute('startLeft'))                               < (mousePos.x + phs)) &&
					((getAttribute('startTop'))                                < mousePos.y) &&
					((parseInt(getAttribute('startLeft')) + parseInt(getAttribute('startWidth')))  > (mousePos.x + phs)) &&
					((parseInt(getAttribute('startTop'))  + parseInt(getAttribute('startHeight'))) > mousePos.y)){

						activeMove = DragDropMoveObjs[i];

						break;
				}
			}
		}

		// checa se é para mover para outra categoria
		if (activeMove) {

			// our drag item is not in a container, so hide it.
			if(curTarget.style.display!='none'){
				curTarget.style.display  = 'none';
			}

			// checa se não é a categoria ativa
			if (String(activeMove.className).search(/pha/) < 0)	{

				// guarda o objeto da categoria que receberá o item
				DragDropMoveObj = activeMove;

				for(var i=0; i<DragDropMoveObjs.length; i++){
					if (DragDropMoveObjs[i] == activeMove) {
						var moveClass = DragDropMoveObjs[i].getAttribute('moveClass');
						if (moveClass) {
							DragDropMoveObjs[i].className = DragDropMoveObjs[i].getAttribute('origClass')+' '+moveClass;
						}
					} else {
						DragDropMoveObjs[i].className = DragDropMoveObjs[i].getAttribute('origClass');
					}
				}

			} else {

				// limpa o objeto para não trocar de categoria
				DragDropMoveObj = null;

			}

		} else {

			// limpa o objeto para não trocar de categoria
			DragDropMoveObj = null;

			for(var i=0; i<DragDropMoveObjs.length; i++){
				DragDropMoveObjs[i].className = DragDropMoveObjs[i].getAttribute('origClass');
			}

			// 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(
							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!=curTarget.nextSibling){
						activeCont.insertBefore(curTarget, beforeNode);
					}

				// the item being dragged belongs at the end of the current container
				} else {
					if((curTarget.nextSibling) || (curTarget.parentNode!=activeCont)){
						activeCont.appendChild(curTarget);
					}
				}

				// make our drag item visible
				if(curTarget.style.display!=''){
					curTarget.style.display  = '';
				}
			} else {

				// our drag item is not in a container, so hide it.
				if(curTarget.style.display!='none'){
					curTarget.style.display  = 'none';
				}
			}

		}



	}

	// mouseMove target
	lastTarget  = target;

	// track the current mouse state so we can compare against it next time
	lMouseState = iMouseDown;

	// se for firefox sempre retorna true
	if (isFirefox()) {
		rvalue = true;
	}

	// this helps prevent items on the page from being highlighted while dragging
	return rvalue;
}

function mouseUp(ev){
	if(curTarget){
		// hide our helper object - it is no longer needed
		dragHelper.style.display = 'none';

		// volta as categorias para classe original
		for(var i=0; i<DragDropMoveObjs.length; i++){
			DragDropMoveObjs[i].className = DragDropMoveObjs[i].getAttribute('origClass');
		}

		// checa se é troca de categoria
		if (DragDropMoveObj) {

			// troca a categoria de um item
			chCat(curTarget,DragDropMoveObj);

		} else {

			var cDrag = curTarget.getAttribute('DragObj');
			if (cDrag!=null) {
				chkPos(cDrag);
			}

			// mouseOver event - Change the item's class if necessary
			if (curTarget.getAttribute('origClass')) {
				curTarget.className = curTarget.getAttribute('origClass');
				curTarget.removeAttribute('origClass');
			}

			// if the drag item is invisible put it back where it was before moving it
			if(curTarget.style.display == 'none'){
				if(rootSibling){
					rootParent.insertBefore(curTarget, rootSibling);
				} else {
					rootParent.appendChild(curTarget);
				}
			}

			// make sure the drag item is visible
			curTarget.style.display = '';

		}

	}
	curTarget  = null;
	iMouseDown = false;
}

function mouseDown(event){
	event = event || window.event;
	var target = event.target || event.srcElement;
	if (getProp(target,'dragStart') == 'true') {
		iMouseDown = true;
		if(lastTarget){
			if (isFirefox()) {
				target = getDragTarget(target);
				var dragObj = target.getAttribute('DragObj');
				if (dragObj!=null) {
					return false;
				}
				return true;
			}
			return false;
		}
	}
	return true;
}

function getDragTarget(target) {
	try	{
		if (target) {
			var dragObj = target.getAttribute('DragObj');
			if(dragObj==null) {
				if (target.parentNode && target.parentNode.getAttribute) {
					for (var p=0;p<5;p++) {
						if(dragObj==null){
							if (target.parentNode && target.parentNode.getAttribute) {
								target = target.parentNode;
								dragObj = target.getAttribute('DragObj');
							} else {
								break;
							}
						}
					}
				}
			}
		}
	}
	catch (e) {}
	return target;
}

function chCat(item,category) {
	if (category.getAttribute('category') && item.getAttribute('item')) {
		changeItemCat(item.getAttribute('item'),category.getAttribute('category'));
	}
}

var lastPos = '';
function chkPos(cDrag) {
	// pega o grupo de dragp and drop do objeto
	var cols = new Array();
	var dragConts  = DragDrops[cDrag];
	for(var c=0; c<dragConts.length; c++) {
		var order = new Array();
		for(var i=0; i<dragConts[c].childNodes.length; i++){
			if(dragConts[c].childNodes[i].nodeName=='#text') continue;
			order.push(dragConts[c].childNodes[i].id);
		}
		cols.push(dragConts[c].id+':'+order.join(","));
	}

	// pega a posição atual
	var curPos = cols.join(";");
	if (String(lastPos).length > 0) {
		if (lastPos != curPos) {
			saveItemPos(curPos);
			lastPos = curPos;
		}
	} else {
		lastPos = curPos;
	}

	return true;
}

function initDragAndDrop(containers){

	document.onmousemove = mouseMove;
	document.onmousedown = mouseDown;
	document.onmouseup   = mouseUp;

	// Create our helper object that will show the item while dragging
	dragHelper = document.createElement('DIV');
	dragHelper.style.cssText = 'position:absolute;display:none;';

	var ids = String(containers).split(',');
	var objs = new Array();
	for (var i=0; i<ids.length;i++) {
		var obj = document.getElementById(ids[i]);
		if (obj) {
			objs.push(obj);
		}
	}

	CreateDragContainer(0,objs);
	chkPos(0);

	for(var i=0; i<DragDropMoveObjs.length; i++){
		var obj = DragDropMoveObjs[i];
		obj.setAttribute('origClass',obj.className);
	}

	document.body.appendChild(dragHelper);
}

// ---------------------------------------------------------------------------------- //

// inicializa o scroll
function initScroll() {
	active_cscroll();
}

// timers para scroll
var cscrollTimer;
var cscrollDelay;

// scroll para o atual
function active_cscroll() {
	var div = document.getElementById('phs');
	if (div) {
		var limit = 0;
		for(var i=0; i<DragDropMoveObjs.length; i++){
			limit += parseInt(DragDropMoveObjs[i].offsetWidth) + 4;
		}
		if (limit > parseInt(div.offsetWidth)) {
			document.getElementById('phsrimg').src = 'imgs/arrow_right_on.gif';
			limit -= parseInt(div.offsetWidth);
			var total = 0;
			for(var i=0; i<DragDropMoveObjs.length; i++){
				var obj = DragDropMoveObjs[i];
				total += parseInt(obj.offsetWidth) + 4;
				if (String(obj.className).search(/pha/) > -1) {
					total += 50;
					break;
				}
			}
			var scroll = total - parseInt(div.offsetWidth);
			if (scroll > limit) {
				div.scrollLeft = limit + 4;
				document.getElementById('phslimg').src = 'imgs/arrow_left_on.gif';
				document.getElementById('phsrimg').src = 'imgs/arrow_right_off.gif';
			} else {
				if (scroll > 0) {
					document.getElementById('phslimg').src = 'imgs/arrow_left_on.gif';
				}
				div.scrollLeft = total - parseInt(div.offsetWidth);
			}
		}
	}
}

// para de fazer scroll
function stop_cscroll() {
	clearTimeout(cscrollDelay);
	clearInterval(cscrollTimer);
}

// começa scroll para esquerda
function start_clscroll() {
	clearInterval(cscrollTimer);
	cscrollDelay = setTimeout(function() {
		cscrollTimer = setInterval(clscroll,1);
	},0);
}

// começa scroll para direita
function start_crscroll() {
	clearInterval(cscrollTimer);
	cscrollDelay = setTimeout(function() {
		cscrollTimer = setInterval(crscroll,1);
	},0);
}

// scroll para o início
function cbscroll() {
	clearTimeout(cscrollDelay);
	document.getElementById('phs').scrollLeft=0;
	var limit = 0;
	for(var i=0; i<DragDropMoveObjs.length; i++){
		limit += parseInt(DragDropMoveObjs[i].offsetWidth) + 4;
	}
	var div = document.getElementById('phs');
	if (limit > parseInt(div.offsetWidth)) {
		document.getElementById('phsrimg').src = 'imgs/arrow_right_on.gif';
	}
	document.getElementById('phslimg').src = 'imgs/arrow_left_off.gif';
}

// scroll para o final
function cescroll() {
	clearTimeout(cscrollDelay);
	var div = document.getElementById('phs');
	var limit = 0;
	for(var i=0; i<DragDropMoveObjs.length; i++){
		limit += parseInt(DragDropMoveObjs[i].offsetWidth) + 4;
	}
	if (limit > parseInt(div.offsetWidth)) {
		document.getElementById('phslimg').src = 'imgs/arrow_left_on.gif';
	}
	limit -= parseInt(div.offsetWidth);
	div.scrollLeft = limit + 4;
	document.getElementById('phsrimg').src = 'imgs/arrow_right_off.gif';
}

// scroll para direita
function crscroll() {
	var size = 10;
	var div = document.getElementById('phs');
	var limit = 0;
	for(var i=0; i<DragDropMoveObjs.length; i++){
		limit += parseInt(DragDropMoveObjs[i].offsetWidth) + 4;
	}
	limit -= parseInt(div.offsetWidth);
	if ((div.scrollLeft + size) < limit) {
		div.scrollLeft = div.scrollLeft + size;
		document.getElementById('phslimg').src = 'imgs/arrow_left_on.gif';
		document.getElementById('phsrimg').src = 'imgs/arrow_right_on.gif';
	} else {
		div.scrollLeft = limit + 4;
		document.getElementById('phsrimg').src = 'imgs/arrow_right_off.gif';
	}
}

// scroll para esquerda
function clscroll() {
	var size = 10;
	var div = document.getElementById('phs');
	if (div.scrollLeft > 0) {
		div.scrollLeft = div.scrollLeft - size;
	}
	if (div.scrollLeft <= 0) {
		document.getElementById('phslimg').src = 'imgs/arrow_left_off.gif';
	}
	var limit = 0;
	for(var i=0; i<DragDropMoveObjs.length; i++){
		limit += parseInt(DragDropMoveObjs[i].offsetWidth) + 4;
	}
	if (limit > parseInt(div.offsetWidth)) {
		document.getElementById('phsrimg').src = 'imgs/arrow_right_on.gif';
	}
}

// timer para lista
var clistTimer;

// dimensiona o menu de categorias
function phlistsize(event) {
	try {
		if (window.event) { event = window.event; }
		var m = mouseCoords(event).y;
		var h = document.body.offsetHeight;
		var s = document.app.scrollTop();
		var sh = (h - m + s - 10);
		var rh = 0;
		var div = document.getElementById('phlist');
		for(var i=0; i<div.childNodes.length; i++){
			var obj = div.childNodes[i];
			if (obj.nodeName != '#text') {
				rh += parseInt(obj.offsetHeight);
				if (!isFirefox()) {
					rh += 4;
				}
			}
		}
		if (rh >= sh) {
			rh = sh;
		}

		if (clistTimer) {
			clearInterval(clistTimer);
		}
		div.style.height = 1;
		div.style.overflow = 'hidden';
		clistTimer = setInterval(function() {
			var ih = 15;
			var dh = parseInt(div.style.height);
			if (dh <= rh) {
				if ((dh + ih) > rh) {
					div.style.height = dh + (rh - dh);
				} else {
					div.style.height = (dh + ih);
				}
				if ((dh + ih + ih) >= rh) {
					div.style.overflow = 'auto';
				}
			} else {
				clearInterval(clistTimer);
			}
		},1);

	} catch(e) {}
}

// esconde a lista
function phlisthide(event) {
	try {
		var div = document.getElementById('phlist');
		div.style.left = 0;
		div.style.height = 1;
	} catch(e) {}
}

