// aimsClick.js
/*
*  JavaScript template file for ArcIMS HTML Viewer
*		dependent on aimsXML.js, ArcIMSparam.js, aimsCommon.js, aimsMap.js,
*		aimsLayers.js, aimsDHTML.js
*		aimsNavigation.js
*/

var onOVArea = false;

// Global vars to save mouse position
var mouseX=0;
var mouseY=0;
var x1=0;
var y1=0;
var x2=0;
var y2=0;
var zleft=0;
var zright=0;
var ztop=0;
var zbottom=0;

var totalArea=0;
var totalMeasure=0;
var currentMeasure=0;
var lastTotMeasure=0;

// variables for interactive clicks
var clickCount = 0;
var	clickPointX = new Array();
var clickPointY = new Array();
var clickMeasure = new Array();
	// type - 1=Measure; 2=SelectLine ; 3=SelectPolygon
var clickType = 1;

var shapeSelectBuffer = false;

var panning=false;
var zooming=false;
var consProd=false; // consulta de productos (mismo comportamiento que zooming)
var selectBox=false;
var blankImage = "images/map.gif";

var leftButton =1;
var rightButton = 2;
if (isNav) {
	leftButton = 1;
	rightButton = 3;
}


/*  *****************************************************
*	Point click functions
* 	used by Measure and Select by Line/Polygon
*	*****************************************************
*/

/* añade un punto a clickCount */
function clickAddPoint() {
	eliminarGeometria();
	var theX = mouseX;
	var theY = mouseY;
	if (XYinsideBox("measureBox", mouseX, mouseY) || XYinsideBox("areaBox", mouseX, mouseY)) return;
	getMapXY(theX,theY);
	clickPointX[clickCount]=mapX;
	clickPointY[clickCount]=mapY;
	clickCount += 1;
	totalMeasure = totalMeasure + currentMeasure;
		//var u = Math.pow(10,numDecimals);
		//if (totalMeasure!=0) totalMeasure = parseInt(totalMeasure*u+0.5)/u;

	clickMeasure[clickCount]=totalMeasure;
	/*legendTemp=legendVisible;
	legendVisible=false;*/
	/*var theString = writeXML();
	var theNum = 99;
	sendToServer(imsURL,theString,theNum);*/
	// seguimos el path trazado
	measureClick();
	if (toolMode==1020 /*|| toolMode==1030*/) creaForma();
	//else if(toolMode==20) updateMeasureBox();
}

/* añade una arista al path de medicion */
function measureClick()
{
	// Incrementamos el número de elementos	
	if (ElementosDeMedida == 1) {
		// Recuperamos el camino al hacer clic
		var pad = document.getElementById('nr' + ElementosDeMedida).firstChild;
		MeasureVML = pad.getAttribute('v').substring(0, pad.getAttribute('v').indexOf('e'));
		return true;
	}

	ElementosDeMedida++;
	X = event.clientX;
	Y = event.clientY;
	
	// Características
	var sFill = '<v:fill on="false" />';
	var sSize = '1px';
	var sStroke = '<v:stroke weight="1.25pt" color="#ff0000" />';
	
	// Array de formas
	var aTools = new Array(); 
	aTools['linea'] = '<v:shape id="nr' + ElementosDeMedida + '" style="position: absolute; left: ' + X + '; top: ' + Y + '; width: ' + document.body.clientWidth + 'px; height: ' + document.body.clientHeight + 'px;" coordsize="' + document.body.clientWidth + ',' + document.body.clientHeight + '"><v:path v="m0,0 l0,0 e" />' + sFill + sStroke + '</v:shape>';
	
	// Agregamos el codigo de la forma al HTML
	parent.MapFrame.theDraw.insertAdjacentHTML('beforeend', (aTools['linea'] + '<br>'));
}

/* Crea el polígono y lo superpone */
function creaForma()
{
	if (clickCount<3) return;
	var pad = document.getElementById('nr' + ElementosDeMedida);
	var sFill = '<v:fill on="true" color="#ff0000" opacity="0.25"/>';
	var sSize = '1px';
	var sStroke = '<v:stroke weight="1.25pt" color="#ff0000" />';
	var forma = ""; 
	var X = parseInt(pad.getAttribute('style').left);
	var Y = parseInt(pad.getAttribute('style').top);
	forma = '<v:shape title="forma" id="forma" style="position: absolute; left: ' + X + '; top: ' + Y + '; width: ' + document.body.clientWidth + 'px; height: ' + document.body.clientHeight + 'px;" coordsize="' + document.body.clientWidth + ',' + document.body.clientHeight + '">';
	forma += '<v:path v="' + MeasureVML + ' e" />' + sFill + sStroke + '</v:shape>';
	
	// Agregamos el codigo de la forma al HTML
	var oForma = document.getElementById('forma');
	if (oForma!=null) {
		oForma = oForma.firstChild;
		oForma.setAttribute('v', MeasureVML);
	}
	else {
		parent.MapFrame.theDraw.insertAdjacentHTML('beforeend', (forma + '<br>'));
	}
}

/* pone a cero clickCount */
function resetClick() {
	var c1 = clickCount;
	clickCount=0;
	clickPointX.length=1;
	clickPointY.length=1;
	currentMeasure=0;
	totalMeasure=0;
	totalArea=0;
	lastTotMeasure=0;
	clickMeasure.length=1;
	
	legendTemp=legendVisible;
	legendVisible=false;
	var theString = writeXML();
	var theNum = 99;
		//showRetrieveMap();
	sendToServer(imsURL,theString,theNum);
		
	switch (toolMode) {
		case 20:
			updateMeasureBox();
			break;
		case 1020:
		/*case 1030:*/
			updateAreaBox();
	}

}	

/* esta al tanto de la herramienta actualmente seleccionada */
function clickFunction (toolName) {
	ocultarMedidas();
	switch(toolName) {
	// Zooming functions
	case "zoomin":
		// zoom in mode
		toolMode = 1;
		panning=false;
		selectBox=false;
		if (isIE)	{
			document.all.theTop.style.cursor = "crosshair";
			theCursor = document.all.theTop.style.cursor;
		}
		modeBlurb = modeList[0];
		//if (useTextFrame) parent.TextFrame.document.location= appDir + "text.htm";
		break;
	case "zoomout":
		// zoom out mode
		toolMode = 2;
		panning=false;
		selectBox=false;
		if (isIE)	{
			document.all.theTop.style.cursor = "crosshair";
			theCursor = document.all.theTop.style.cursor;
		}
		modeBlurb = modeList[1];
		//if (useTextFrame) parent.TextFrame.document.location= appDir + "text.htm";
		break;
	case "zoomlast":
		zoomBack();
		panning=false;
		zooming=false;
		selectBox=false;
		break;
	case "zoomnext":
		zoomNext();
		panning=false;
		zooming=false;
		selectBox=false;
		break;
	case "zoomactive":
		//alert(LayerExtent[ActiveLayerIndex]);
		var q = LayerExtent[ActiveLayerIndex].split("|");
		panning=false;
		zooming=false;
		selectBox=false;
		//zoomToEnvelope(parseFloat(q[0]),parseFloat(q[1]),parseFloat(q[2]),parseFloat(q[3]));
		
		var l = parseFloat(setDecimalString(q[0]));
		var b = parseFloat(setDecimalString(q[1]));
		var r = parseFloat(setDecimalString(q[2]));
		var t = parseFloat(setDecimalString(q[3]));
		var w = r-l;
		var h = t-b;
		// add a bit of a margin around the layer
		var wm = w * (5/100);
		var hm = h * (5/100);
		l = l - wm;
		r = r + wm;
		b = b - hm;
		t = t + hm;
		zoomToEnvelope(l,b,r,t);
		break;
	case "fullextent":
		fullExtent();
		break;
		
	// Pan functions
	case "pan":
		// pan mode
		toolMode = 3;
		
		zooming=false;
		selectBox=false;
		if (isIE)	{
			document.all.theTop.style.cursor = "move";
			theCursor = document.all.theTop.style.cursor;
		}
		modeBlurb = modeList[2];
		break;
		
	// Measure-Unit function
	case "measure":
		panning=false;
		zooming=false;
		selectBox=false;
		shapeSelectBuffer = false;
		if (clickCount>0) {
			if (totalMeasure==0) resetClick();
		}
		toolMode = 20;
		/* felisuco */
		MeasureVML = defaultMeasureVML;
		ElementosDeMedida = 0;
		/**/
		if (isIE)	{
			document.all.theTop.style.cursor = "crosshair";
			theCursor = document.all.theTop.style.cursor;
		}
		modeBlurb = modeList[12];
		showGeocode=false;
		break;
		
	case "measurearea":
		panning=false;
		zooming=false;
		selectBox=false;
		shapeSelectBuffer = false;
		if (clickCount>0) {
			if (totalArea==0) resetClick();
		}
		toolMode = 1020;
		/* felisuco */
		MeasureVML = defaultMeasureVML;
		ElementosDeMedida = 0;
		/**/
		if (isIE)	{
			document.all.theTop.style.cursor = "crosshair";
			theCursor = document.all.theTop.style.cursor;
		}
		modeBlurb = modeList[22];
		showGeocode=false;
		break;
		
	case "addPoint":
		toolMode = 1002;
		break;
		
	case "removePoint":
		toolMode = 1003;
		break;

	case "info":
		toolMode = 1004;
		break;

	case "consProd": // consulta de productos
		toolMode = 1030;
		panning=false;
		selectBox=false;
		if (isIE)	{
			document.all.theTop.style.cursor = "crosshair";
			theCursor = document.all.theTop.style.cursor;
		}
		modeBlurb = modeList[0];
		break;
		/*
		panning=false;
		zooming=false;
		selectBox=false;
		shapeSelectBuffer = false;
		if (clickCount>0) {
			if (totalArea==0) resetClick();
		}
		toolMode = 1030;
		MeasureVML = defaultMeasureVML;
		ElementosDeMedida = 0;
		if (isIE)	{
			document.all.theTop.style.cursor = "crosshair";
			theCursor = document.all.theTop.style.cursor;
		}
		modeBlurb = modeList[22];
		showGeocode=false;
		break;*/

	default:
		alert(msgList[51]);
	}
	modeName=modeBlurb;
}

// check for mouseup
function chkMouseUp(e) { 
	if ((toolMode == 1) && (zooming)) {
			stopZoomBox(e);		
	}
	if ((toolMode == 2) && (zooming)) {
			stopZoomOutBox(e);
	}
	if ((toolMode == 3) && (panning)) {
			stopPan(e);

	}
	/*if ((toolMode == 10) && (selectBox)) {
			stopSelectBox(e);
	}*/
	if ((toolMode == 1030) && (consProd)) {
			stopConsProdBox(e);
		
	}

	return false;
	
}

/* realiza acciones acordes a la mapTool activa */
function mapTool (e) {
	var theButton= 0;
	// get the button pushed... if right, ignore... let browser do the popup... it will anyway
	if (isNav) {
		theButton = e.which;
	} else {
		theButton =window.event.button;
	}	
	if (theButton==rightButton && TieneInfo[idxServicio]) {
		//descargar(e);
		return;
	}
	//if (theButton==leftButton) {
		if (pendingRequest()) return;
		getImageXY(e);
		if ((mouseX>=0) && (mouseX<iWidth) && (mouseY>=0) && (mouseY<iHeight)) {
			switch(toolMode) {
			case 1: /* Zoom In */
				startZoomBox(e);
				return false;
				break;
				
			case 2: /* Zoom Out */
				startZoomOutBox(e);
				return false;
				break;

			case 3: /* Pan */
				startPan(e);
				return false;
				break;

			// custom modes
			case 20: /* Measure */
				clickType=1;
				clickAddPoint();
				break;
				
			case 1020: /* Area */
			/*case 1030:*/
				clickType=1;
				clickAddPoint();
				calcArea();
				break;

			case 1030: /* Consultar Productos */
				startConsProdBox(e);
				return false;
				break;

			default:
				if (toolMode>=1000) {
					customMapTool(e);
				}
			}
		}
	//}
}

/* actualiza la capa measureBox */
function updateMeasureBox() {
	var umbral = 10000;
	var unidad = "m.";
	var decimales = 0;
	if (isNav4) {
		var theForm = document.layers["measureBox"].document.forms[0];
	} else {
		//var theForm = document.measureBox.forms[0];
		var theForm = document.forms[0];
	}
	var j = 1;
	for (var i=0;i<sUnitList.length;i++) {
		if (ScaleBarUnits==sUnitList[i]) j=i;
	}
	var u = Math.pow(10,numDecimals);
	var tMeas = 0;
	tMeas = parseInt(totalMeasure*u+0.5)/u;
	if (tMeas >= umbral) {
		unidad = "Km.";
		decimales = 2;
		tMeas = tMeas / 1000;
	}
	theForm.all.oDistancia.innerText = FormatNumber(tMeas,decimales,false,false,true) + " " + unidad;

	showLayer("measureBox");
}

function updateAreaBox() {
	var umbral = 10000;
	var unidad = "m<font size=-2><span style='vertical-align:super'>2</span></font>";
	var decimales = 0;
	var j = 1;
	for (var i=0;i<sUnitList.length;i++) {
		if (ScaleBarUnits==sUnitList[i]) j=i;
	}
	var u = Math.pow(10,numDecimals);
	var tMeas = 0;
	tMeas = parseInt(totalArea*u+0.5)/u;
	if (tMeas >= umbral) {
		unidad = "Ha";
		decimales = 2;
		tMeas = tMeas / 10000;
	}
	document.all.oArea.innerHTML = FormatNumber(tMeas,decimales,false,false,true) + " " + unidad;

	showLayer("areaBox");
}

function XYinsideBox(nBox, X, Y) {
	if (isNav4) {
		var oMBox = document.layers[nBox];
	} else {
		var oMBox = document.all(nBox);
	}
	if (oMBox.style.visibility!="visible") return false;
	if (X>=oMBox.style.pixelLeft && X<eval(oMBox.style.pixelLeft+oMBox.style.pixelWidth) &&
		Y>=oMBox.style.pixelTop && Y<eval(oMBox.style.pixelTop+oMBox.style.pixelHeight)) return true;
	return false;
}

