var mouseOffset = null;
var iMouseDown  = false;
var lMouseState = false;
var dragObject  = null;
var DragDrops   = [];
var curTarget   = null;
var rootParent  = null;
var rootSibling = null;
var targetIndex	= 0;
var dropTargets	= [];

Number.prototype.NaN0=function(){return isNaN(this)?0:this;}

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};
	}
	return {
		x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
		y:ev.clientY + document.body.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};
}

function 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 = mouseCoords(ev);
	
	if ( dragObject ) {
		dragObject.style.position = 'absolute';
		dragObject.style.top      = mousePos.y - mouseOffset.y;
		dragObject.style.left     = mousePos.x - mouseOffset.x;

		if ( mousePos.x > 403) {
			dragObject.setAttribute("workingPage", "left");
		} else {
			dragObject.setAttribute("workingPage", "right" );
		}
	}

	// 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 ( curTarget || dragObject ) return false;
}

function mouseUp( ev ) {
	if ( dragObject ) {
		ev				= ev || window.event;
		var mousePos	= mouseCoords(ev);
		var dropou		= false;

		for ( i = 0; i < dropTargets.length; i++ ) {
			var curTarget	= dropTargets[i];
			var targPos		= getPosition(curTarget);
			
			/*var targWidth	= parseInt(curTarget.offsetWidth);
			var targHeight	= parseInt(curTarget.offsetHeight);*/ //correção do Bug informado pelo Alexandre em 09/08/2007 no e-mail "Retornos de homologação"

			var targHeight	= parseInt($('clipout_'+curTarget.id).style.height);
			var targWidth	= parseInt($('clipout_'+curTarget.id).style.width);

			if (
			(curTarget.id.indexOf(dragObject.getAttribute("workingPage")) > -1)	&&
			(mousePos.x > targPos.x)											&&
			(mousePos.x < (targPos.x + targWidth))						&&
			(mousePos.y > targPos.y)											&&
			(mousePos.y < (targPos.y + targHeight))) {

				dropou			= true;
				ultimoObjeto	= curTarget.getAttribute('ultimoObj_id');

				if ( ultimoObjeto != null ) { //faz a foto que está na moldura retornar para a condição inicial
					document.getElementById(ultimoObjeto).style.left	= curTarget.getAttribute('ultimoObj_x');
					document.getElementById(ultimoObjeto).style.top		= curTarget.getAttribute('ultimoObj_y');
					document.getElementById(ultimoObjeto).style.display	= "";				
				}

				//-------------------
				var book_id ;
				var sOrder   ;
				var v_order ;

				book_id		               = document.frmPages.livro.value ;
				sOrder                     = curTarget.id                  ;
				v_order                    = new Array()                   ;
				v_order                    = sOrder.split("_")             ;
				photo_position_order       = v_order[2]                    ; 
				
				// Remove os aligns da foto
				var url = 'actions/savePhotoProperties.asp?action=delPhotoAlign&book_id=' + book_id + '&page_number=' +  curTarget.getAttribute("pageNumber") + '&photo_position_order=' + photo_position_order ;
				SendRequest(url);
				
				// Salva a foto no banco
				//alert('PageNumber:' +  curTarget.getAttribute("pageNumber") )

				savePhoto( curTarget.id, dragObject.id, curTarget.getAttribute("pageNumber") );
				swapImg( curTarget, dragObject );

				if ( curTarget.getAttribute('itens') == null ) {
					curTarget.setAttribute('itens', dragObject.id+"||");
				} else {
					curTarget.setAttribute('itens', curTarget.getAttribute('itens')+dragObject.id+"||");
				}
				
				dragObject.style.display		= "none";				
				curTarget.setAttribute('ultimoObj_id', dragObject.id );
				curTarget.setAttribute('ultimoObj_x', dragObject.getAttribute('originalCoords_x') );
				curTarget.setAttribute('ultimoObj_y', dragObject.getAttribute('originalCoords_y') );

				break;
			}
		}

		if ( dropou == false ) {
			dragObject.style.left				= dragObject.getAttribute('originalCoords_x');
			dragObject.style.top				= dragObject.getAttribute('originalCoords_y');
		}

		var dragClone							= new Image();
		dragClone.id							= dragObject.id;
		dragClone.src							= dragObject.src;
		dragClone.style.position				= "absolute";
		dragClone.style.left					= dragObject.getAttribute('originalCoords_x');
		dragClone.style.top					= dragObject.getAttribute('originalCoords_y');
		dragClone.style.cursor				= "pointer";
		dragClone.border						= 0;
		dragClone.setAttribute('newsrc', dragObject.getAttribute('newsrc'));
		dragClone.setAttribute('height_medium', dragObject.getAttribute('height_medium'));
		dragClone.setAttribute('width_medium', dragObject.getAttribute('width_medium'));
		document.body.appendChild( dragClone );
		makeDraggable( dragClone );
		
		dragObject	= null;
		dragClone	= null;
	}
}

function mouseDown(ev) {
	ev         = ev || window.event;
	var target = ev.target || ev.srcElement;
	
	//var idBorder = getAttribute('target', 'pageNumber')
	//$('photoBorder_'+idBorder).style.zIndex = 0;

	target.style.zIndex = 10;

	iMouseDown = true;
	if(target.onmousedown || target.getAttribute('DragObj')){
		return false;
	}
}

function makeDraggable( item ) {
	if(!item) return;
	
	item.setAttribute("originalCoords_x", getPosition(item).x);
	item.setAttribute("originalCoords_y", getPosition(item).y);

	item.onmousedown = function(ev){
		dragObject	= this;
		mouseOffset = getMouseOffset(this, ev);
		return false;
	}
}

function addDropTarget() {
	for ( i = 0; i < arguments.length; i++ ) {
		dropTargets.push(arguments[i]);
	}	
}

function resetItem( moldura ) {
	itens								= moldura.getAttribute('itens').split("||");
	objUltimoItem					= document.getElementById(itens[itens.length-2]);
	objUltimoItem.style.left		= objUltimoItem.getAttribute('originalCoords_x');
	objUltimoItem.style.top		= objUltimoItem.getAttribute('originalCoords_y');
	objUltimoItem.style.display	= "";
	objUltimoItem					= null;
	moldura.src						= "img/foto_maior.gif";
}

function swapImg( target, newPhoto, outPutDebug ) {
	try{
		var templateHeight		= parseInt(newPhoto.getAttribute('height_medium'));
		var templateWidth		= parseInt(newPhoto.getAttribute('width_medium'));
		var photoHeight			= parseInt($('clipout_'+target.id).style.height);
		var photoWidth			= parseInt($('clipout_'+target.id).style.width);
		var nRatio					= 0;
		var clipMarginLeft			= 0;
		var clipMarginTop			= 0;
		var clipInDiv				= $('clipin_'+target.id);
		
		strDb	= "templateWidth: "+templateWidth+"<BR>";
		strDb  += "templateHeight: "+templateHeight+"<BR>";
		strDb  += "photoWidth: "+photoWidth+"<BR>";
		strDb  += "photoHeight: "+photoHeight+"<BR>";

		if ( (templateWidth/templateHeight) >= (photoWidth/photoHeight) ) {
			if ( photoHeight >= templateHeight ) {
				nRatio			= templateHeight/photoHeight;
			} else {
				nRatio			= photoHeight/templateHeight;
			}

			if ( (templateWidth * nRatio) > photoWidth ) {
				clipMarginLeft	= "-"+parseInt( ((templateWidth * nRatio)-photoWidth)/2 );		
			}
		} else {
			/*if ( photoWidth >= templateWidth ) {
				nRatio			= templateWidth/photoWidth;
			} else {*/
				nRatio			= photoWidth/templateWidth;
			//}
				
			if ( (templateHeight * nRatio) > photoHeight ) {
				clipMarginTop	= "-"+parseInt( ((templateHeight * nRatio)-photoHeight)/2 );
			}
		}

		strDb  += "nRatio: "+nRatio;
		
		if ( outPutDebug ) {
			document.write(strDb);
		}

		clipInDiv.style.marginTop	= clipMarginTop+"px";
		clipInDiv.style.marginLeft	= clipMarginLeft+"px";
		target.height					= Math.ceil(templateHeight * nRatio)+2;
		target.width					= Math.ceil(templateWidth * nRatio)+4;
		target.src						= newPhoto.getAttribute("newsrc");
		newPhotoID						= newPhoto.id.substr( newPhoto.id.indexOf("_")+1, newPhoto.id.length );
		
		checkPhotoResolution( newPhotoID, target );

	} catch ( Erro ) {
		alert( "Erro: " + Erro.message );
	}
}

document.onmousemove	= mouseMove;
document.onmousedown	= mouseDown;
document.onmouseup		= mouseUp;