// aimsMap.js
/*
*  JavaScript template file for ArcIMS HTML Viewer
*		dependent on aimsXML.js, ArcIMSparam.js, aimsCommon.js
*/

aimsMapPresent=true;

var useLimitExtent=false;
var getStartingExtent=true;
var getLimitExtent=true;
var enforceFullExtent=false;

// map extents. . . dynamically updated
var eLeft = -180.0;
var eRight = 180.0;
var eTop = 90.0;
var eBottom = -90.0;
var fullLeft = eLeft;
var fullRight = eRight;
var fullTop = eTop;
var fullBottom = eBottom;

// vista posterior a la anterior
var pLeft = eLeft;
var pRight = eRight;
var pTop = eTop;
var pBottom = eBottom;

// map size . . . dynamically updated
/*var iWidth = 630;
var iHeight = 512;*/
// Tamaños imagen
// Grande: 675x420
// Pequeña: 430x280
var iWidth = 430;
var iHeight = 280;
// location map size . . . dynamically updated
var i2Width = 150;
var i2Height = 120;

var imageLimitLeft = limitLeft;
var imageLimitTop = limitTop;
var imageLimitRight = limitRight;
var imageLimitBottom = limitBottom;

var appDir = "";

var xDistance = Math.abs(eRight-eLeft);
var yDistance = Math.abs(eTop-eBottom);
var panX = xDistance * panFactor;
var panY = yDistance * panFactor;
var pixelX = xDistance/iWidth;
var pixelY = yDistance/iHeight;
var mapX = eLeft;
var mapY = eTop;
var lastLeft = eLeft;
var lastRight = eRight;
var lastTop = eTop;
var lastBottom = eBottom;
var nextLeft = eLeft;
var nextRight = eRight;
var nextTop = eTop;
var nextBottom = eBottom;
var hasNextExtent = false;
var fullOVLeft = eLeft;
var fullOVRight = eRight;
var fullOVTop = eTop;
var fullOVBottom = eBottom;
var theCursor = "crosshair";
var canLoad=false;
//if (imsURL!="") canLoad=false;

var fullWidth = Math.abs(fullRight - fullLeft);
var fullHeight = Math.abs(fullTop - fullBottom);
var fullOVWidth = Math.abs(fullOVRight - fullOVLeft);
var fullOVHeight = Math.abs(fullOVTop - fullOVBottom);
var mapScaleFactor = xDistance / iWidth;

var geocodeX = 0;
var geocodeY = 0;
var showGeocode = false;
var geocodeLabel = "";

var sQuote = "'";
var dQuote = '"';

var toolMode = 1;
var legendVisible=true;

MapUnits = MapUnits.toUpperCase();
ScaleBarUnits = ScaleBarUnits.toUpperCase();

/* save the extent */
function saveLastExtent() {
	lastLeft = eLeft;
	lastRight = eRight;
	lastTop = eTop;
	lastBottom = eBottom;
	//window.status = 'Last extent: ' + '(' + lastLeft + ', ' + lastBottom + '; ' + lastRight + ', ' + lastTop + ')';
}

/* save the next extent */
function saveNextExtent() {
	nextLeft = eLeft;
	nextRight = eRight;
	nextTop = eTop;
	nextBottom = eBottom;
	hasNextExtent = true;
	//window.status = 'Next extent: ' + '(' + nextLeft + ', ' + nextBottom + '; ' + nextRight + ', ' + nextTop + ')';
}

/* zoom out to full extent */
function fullExtent() {
	if (aimsDHTMLPresent) moveLayer("theMap",hspc,vspc);
	window.scrollTo(0,0);
	saveLastExtent();
	eLeft = fullLeft;
	eRight = fullRight;
	eTop = fullTop;
	eBottom = fullBottom;
	//var theString = writeXML();
	sendMapXMLActiveX();
}

function startExtent() {
	if (aimsDHTMLPresent) moveLayer("theMap",hspc,vspc);
	window.scrollTo(0,0);
	saveLastExtent();
	eLeft = startLeft;
	eRight = startRight;
	eTop = startTop;
	eBottom = startBottom;
	//var theString = writeXML();
	sendMapXMLActiveX();
}

/* zoom back to last extent */
function zoomBack() {
	if (lastLeft==eLeft && lastRight==eRight && lastTop==eTop && lastBottom==eBottom) return;
	if (aimsDHTMLPresent) moveLayer("theMap",hspc,vspc);
	var left1 = eLeft;
	var right1 = eRight;
	var top1 = eTop;
	var bottom1 = eBottom;
	saveNextExtent();
	eLeft = lastLeft;
	eRight = lastRight;
	eTop = lastTop;
	eBottom = lastBottom;
	/*lastLeft = left1;
	lastRight = right1;
	lastTop = top1;
	lastBottom = bottom1;*/
	//var theString = writeXML();
	sendMapXMLActiveX();	
}

/* zoom to next extent */
function zoomNext() {
	if (!hasNextExtent) return;
	if (nextLeft==eLeft && nextRight==eRight && nextTop==eTop && nextBottom==eBottom) return;
	if (aimsDHTMLPresent) moveLayer("theMap",hspc,vspc);
	var left1 = eLeft;
	var right1 = eRight;
	var top1 = eTop;
	var bottom1 = eBottom;
	//saveLastExtent();
	eLeft = nextLeft;
	eRight = nextRight;
	eTop = nextTop;
	eBottom = nextBottom;
	/*lastLeft = left1;
	lastRight = right1;
	lastTop = top1;
	lastBottom = bottom1;*/
	//var theString = writeXML();
	sendMapXMLActiveX();	
}

function zoomToPoint(xIn, yIn, drawIt, theLabel) {
	//alert(xIn + "," + yIn); 
	var mWMargin = 0;
	var mHMargin = 0;
	mWMargin = Math.abs(limitRight-limitLeft) * selectPointMargin;
	mHMargin = Math.abs(limitTop-limitBottom) * selectPointMargin;
	var xNum = parseFloat(xIn);
	var yNum = parseFloat(yIn);
	saveLastExtent();
	eLeft = xNum - mWMargin;
	eRight = xNum + mWMargin;
	eTop = yNum + mHMargin;
	eBottom = yNum - mHMargin;
	if (drawIt) {
		showGeocode=true;
		geocodeX=xNum;
		geocodeY=yNum;
		geocodeLabel=theLabel;
	}
	sendMapXMLActiveX();
}

function zoomToEnvelope(minXin,minYin,maxXin,maxYin) {
	saveLastExtent();
	eLeft=minXin;
	eBottom=minYin;
	eRight=maxXin;
	eTop=maxYin;
	checkFullExtent();
	sendMapXMLActiveX();	
}

/* zoom to center of fullextent at set scale */
function zoomScale(inScale) {
	// inScale is scale factor where 1.0 = 100% of fullWidth and fullHeight
	var halfWidth = fullWidth / 2;
	var halfHeight = fullHeight / 2
	var midX = eRight - (xDistance / 2);
	var midY = eTop - (yDistance / 2);
	var newWidth = halfWidth * inScale;
	var newHeight = halfHeight * inScale;
	saveLastExtent();
	eLeft = midX - newWidth;
	eRight = midX + newWidth;
	eTop = midY + newHeight;
	eBottom = midY - newHeight;
	sendMapXMLActiveX();
	
}

/* get directory path of URL */
function getPath(theFullPath) {
	var theSlash = theFullPath.lastIndexOf("/");
	var theDir = theFullPath.substring(0,theSlash);
	if (theDir==null) theDir="";
	theDir = theDir + "/";
	return theDir;

}

/* check for existance of layer */
function hasLayer(name) {
	var result = false;
	if (isNav4) {
		if (document.layers[name]!=null) result=true;
	}  else if (isIE) {
		if (eval('document.all.' + name)!=null) result=true;
	} else if (isNav) {
		var theElements = document.getElementsByTagName("DIV");
		var theObj;
		var j = -1;
		for (i=0;i<theElements.length;i++) {
			if (theElements[i].id==name) result=true;
		}
    }
	return result;
}

/* put up the "RetriveData" image */
function showRetrieveData() {
	if (hasLayer("LoadData")) {
		showLayer("LoadData");
	}
}

/* hide the "RetriveData" image */
function hideRetrieveData() {
	if (hasLayer("LoadData")) {
		hideLayer("LoadData");
	}
}

/* put up the "RetriveMap" image */
function showRetrieveMap() {
	if (hasLayer("LoadMap")) {
		showLayer("LoadMap");
		// Aunque se haya recibido la imagen, tarda unos segundos (dependiendo de la Cx) en visualizarse
		mapLoaded = false;
		disableGUI(true);
	}
}

/* hide the "RetriveMap" image */
function hideRetrieveMap() {
	if (hasLayer("LoadMap")) {
		hideLayer("LoadMap");
		mapLoaded = true;
		disableGUI(false);
	}
}

/*  *****************************************************
*	Various Distance Conversion Functions
*	*****************************************************
*/

/* Calcula el area */
function calcArea() {
	var polygonArea=0;
	var myCounter=0;

	if (clickCount>0) {
		for (i=0; i<clickCount; i++) {
			myCounter=i+1;
			if (myCounter<clickCount)
				polygonArea += (clickPointX[i]*clickPointY[i+1]-clickPointX[i+1]*clickPointY[i]);
			else
				polygonArea += (clickPointX[i]*clickPointY[0]-clickPointX[0]*clickPointY[i]);
		}
		
		// Hectareas
		//totalArea = (Math.floor(0.5*Math.abs(polygonArea) / 100) / 100);
		// Metros
		totalArea = Math.floor(0.5*Math.abs(polygonArea));
	
		updateAreaBox();
	}
}

/* calculate distance to current scalebarunits */
function calcDistance(mX,mY) {
	// Note: decimal are not hard coded to allow use with locales using commas instead of points.
	if (clickCount>0) {
		var mUnits = MapUnits;
		var mDistance = 0;
		var p = clickCount-1;
		var Lon1 = clickPointX[p] * Math.PI / 180;
		var Lon2 = mX * Math.PI / 180;
		var Lat1 = clickPointY[p] * Math.PI / 180;
		var Lat2 = mY * Math.PI / 180;
		var LonDist = Lon1-Lon2;
		var LatDist = Lat1-Lat2;
		if (MapUnits=="DEGREES") {
			var A = Math.pow(Math.sin(LatDist / 2),2) + Math.cos(Lat1) * Math.cos(Lat2) * Math.pow(Math.sin(LonDist /2),2);
			//var A = Math.cos(Lat1) * Math.cos(Lat2) * Math.pow(Math.sin(LonDist /2),2);
			var C = 2 * Math.asin(Math.min(1, Math.sqrt(A)));
			var D = (3963 - 13 * Math.sin((Lat1 + Lat2) / 2)) * C
			mDistance = D * 5280;
			mUnits = "FEET";
		} else {
			var xD = Math.abs(mX - clickPointX[p]);
			var yD = Math.abs(mY - clickPointY[p]);
			mDistance = Math.sqrt(Math.pow(xD,2) + Math.pow(yD,2));
		}
		
		var theDist = convertUnits(mDistance,mUnits,ScaleBarUnits);
		var u = Math.pow(10,numDecimals);
		currentMeasure = parseInt(theDist*u+(5/10))/u;
		
		updateMeasureBox();
		
	}
}

/* convert the amounts to new units */
function convertUnits(theDist1,mUnits,sUnits) {
	// Note: decimal are not hard coded to allow use with locales using commas instead of points.	
	var theDist = parseFloat(theDist1);
	var mDistance = theDist;
	//alert(theDist);
	if (mUnits == "FEET") {
		if (sUnits=="MILES") {
			mDistance = theDist / 5280;
		} else if (sUnits == "METERS") {
			mDistance = theDist * (3048/10000);
		} else if (sUnits == "KILOMETERS") {
			mDistance = theDist * (3048/10000000);
		}
	} else {
		if (sUnits=="MILES") {
			mDistance = theDist * (6213711922/10000000000000);
		} else if (sUnits == "FEET") {
			mDistance = theDist * (3280839895/1000000000);
		} else if (sUnits == "KILOMETERS") {
			mDistance = theDist / 1000;
		}
	}
	var u = Math.pow(10,numDecimals);
	//alert(u);
	if (!isNav) mDistance = parseInt(mDistance * u + (5/10)) / u
	//alert(mDistance);
	return mDistance;
}

// set new map extent 
function setExtent(newLeft, newTop, newRight, newBottom) {
	eLeft = newLeft;
	eTop = newTop;
	eRight = newRight;
	eBottom = newBottom;
}

//  set new full extent 
function setFullExtent(maxLeft, maxTop, maxRight, maxBottom) {
	fullLeft = maxLeft;
	fullTop = maxTop;
	fullRight = maxRight;
	fullBottom = maxBottom;
	fullWidth = Math.abs(fullRight-fullLeft);
	fullHeight = Math.abs(fullTop-fullBottom);
}

function beforeMapRefresh() {
 // add any code for checking parameters before map update
 // called by sendXML() before writing XML request
 //alert("Yup. It works.[1]");
}
 
function afterMapRefresh() {
 // add any code for checking parameters after map update
 // called by processXML() if XMMmode=1 after image and extent is updated
 //alert("Yup. It works.[1]"); 
}	

// pan using arrow buttons
function panButton(panType) {
	// si nos encontramos en el borde del mapa de situación, no hacemos panning
	if (!parent.herramientas.notInTheBorder(panType)) return false;
	// almacenamos el desplazamiento realizado (uso en función rojo() que dibuja la ventana del mapa de situación)
	parent.MapFrame.panDirection = panType;
	//alert("Left:" + left + "\nTop:" + top + "\nRight:" + right + "\nBottom:" + bottom + "\nWidth:" + xDistance + "\nHeight:" + yDistance + "\nPanX:" + panX + "\nPanY:" + panY);
	saveLastExtent();
	xDistance = Math.abs(eRight-eLeft);
	yDistance = Math.abs(eTop-eBottom);
	panX = xDistance * panFactor;
	panY = yDistance * panFactor;
	switch(panType) {
	//if (panType == 1) {
	case 1:
		//west
		eLeft = eLeft - panX;
		eRight = eLeft + xDistance;
		break
	case 2:
		// north
		eTop = eTop + panY;
		eBottom = eTop - yDistance;
		break
	case 3:
		// east
		eRight = eRight + panX;
		eLeft = eRight - xDistance;
		break
	case 4:
		// south
		eBottom = eBottom - panY;
		eTop = eBottom + yDistance;
		break
	case 5:
		// southwest
		eTop = eTop - panY;
		eLeft = eLeft - panX;
		eBottom = eTop - yDistance;
		eRight = eLeft + xDistance;
		break
	case 6:
		// northwest
		eTop = eTop + panY;
		eLeft = eLeft - panX;
		eBottom = eTop - yDistance;
		eRight = eLeft + xDistance;
		break
	case 7:
		// northeast
		eTop = eTop + panY;
		eLeft = eLeft + panX;
		eBottom = eTop - yDistance;
		eRight = eLeft + xDistance;
		break
	case 8:
		// southeast
		eTop = eTop - panY;
		eLeft = eLeft + panX;
		eBottom = eTop - yDistance;
		eRight = eLeft + xDistance;
	}
	checkFullExtent();
	//alert("Left:" + left + "\nTop:" + top + "\nRight:" + right + "\nBottom:" + bottom + "\nWidth:" + xDistance + "\nHeight:" + yDistance + "\nPanX:" + panX + "\nPanY:" + panY);
	//var theString = writeXML();
	sendMapXMLActiveX();
	
}

function checkFullExtent() {
	if (enforceFullExtent) {
		var xDistance1 = eRight - eLeft;
		var yDistance1 = eTop - eBottom;

		if (xDistance1>fullWidth) xDistance1 = fullWidth;
		if (yDistance1>fullHeight) yDistance1 = fullHeight;

		//alert("Adjusting extent to image proportions");
		if ((eLeft < limitLeft) && (eTop > limitTop)) {
			eLeft = limitLeft;
			eRight = limitRight;
		} else {
			if (eLeft < limitLeft) {
				eLeft = limitLeft;
				eRight = eLeft + xDistance1;
			} else if (eRight > limitRight) {
				eRight = limitRight;
				eLeft = eRight - xDistance1;
			}	
		}
		if ((eLeft < limitLeft) && (eTop > limitTop)) {
			eTop = limitTop;
			eBottom = limitBottom;
		} else {
			if (eTop > limitTop) {
				eTop = limitTop;	
				eBottom = eTop - yDistance1;
			} else if (eBottom < limitBottom) {
				eBottom = limitBottom;	
				eTop = eBottom + yDistance1;
			}	
		}
	}

}
