// aimsMap.js
/*
*  JavaScript template file for ArcIMS HTML Viewer
*		dependent on aimsXML.js, ArcIMSparam.js, aimsCommon.js
*/

aimsMapPresent=true;

/*********************************************
Initialize extents and set dynamic extent vars
**********************************************/

// global variables

// map extents. . . dynamically updated
// replacement for eLeft,etc
var curExt= new extent(-180.0, -90, 180.0, 90);
var reqExt= new extent(-180.0, -90, 180.0, 90);

limitMinX = limitXYs[0];
limitMinY = limitXYs[1];
limitMaxX = limitXYs[2];
limitMaxY = limitXYs[3];
			
startOVLeft   = defaultSkin.ovStartXYs[0];
startOVBottom = defaultSkin.ovStartXYs[1];
startOVRight  = defaultSkin.ovStartXYs[2];
startOVTop    = defaultSkin.ovStartXYs[3];

var maxExt   = new extent(limitMinX, limitMinY, limitMaxX, limitMaxY);
var startExt = new extent(defaultSkin.startXYs[0], defaultSkin.startXYs[1], 
		defaultSkin.startXYs[2], defaultSkin.startXYs[3]);

var ovExt    = new extent(maxExt);

// USGS_NATMAP_Init.js has function which sets these to false if extents
// are not present.
var getStartingExtent = true;
var getLimitExtent = true;

var pixelX = curExt.xSize/iWidth;
var pixelY = curExt.ySize/iHeight;
var mapX = curExt.minX;
var mapY = curExt.maxY;

var mapScaleFactor = curExt.xSize/ iWidth;

var toolMode = MAPTOOL_ZOOMIN;

for (i=0;i<historyLength;i++) {
	extentsHistory[i] = new extent(curExt.minX, curExt.minY, curExt.maxX, curExt.maxY);
}

/*********************************************
    Functions
**********************************************/

function checkExt(ext) {	
  if (ext.within(maxExt) && ext.checkNumeric() && ext.checkBounds())
    return true
	else
    return false; 
} 

// save the extent 
function saveLastExtent() {
	  if (savedExtents < historyLength)
	    savedExtents++;
	  extentsHistory[historyIndex].setFrom(curExt);
	  if (historyIndex < historyLength -1 ){ 
		historyIndex++;
	  }
	  else{
		historyIndex = 0;
	  }
} 

// zoom back to last extent
function zoomBack() {
	if ( savedExtents < 1){
		alert("Zoom back limit has been reached.\nPrevious extents unavailable.");
	}
	else{
		savedExtents--;
		if (historyIndex > 0 ){ 
			historyIndex--;
		}
		else{
			historyIndex = historyLength-1;
		}
		reqExt.setFrom(extentsHistory[historyIndex]);
		requestNewMainMap();
	}
}

// zoom out to full extent
function fullExtent() {
	window.scrollTo(0,0);
	saveLastExtent();

	if (useCustomSkin) {
		// get extent from param
		reqExt.setWithArray(skin.startXYs);
	}
	else {
		reqExt.setFrom(maxExt);
	}

	requestNewMainMap();
}


function zoomToEnvelope(minXin,minYin,maxXin,maxYin) {
	saveLastExtent();
	reqExt.set(minXin,minYin,maxXin,maxYin);
	requestNewMainMap();
}

// zoom to center of fullextent at set scale
function zoomScale(inScale) {
	// inScale is scale factor where 1.0 = 100% of the limit X distance and limit Y Distance
	var halfWidth = (limitMaxX - limitMinX) / 2;
	var halfHeight = (limitMaxY - limitMinY) / 2
	var midX = curExt.maxX - (curExt.xSize / 2);
	var midY = curExt.maxY - (curExt.ySize / 2);
	var newWidth = halfWidth * inScale;
	var newHeight = halfHeight * inScale;
	saveLastExtent();
	reqExt.set(midX - newWidth, midY - newHeight, midX + newWidth, midY + newHeight)
	requestNewMainMap();	
}

function getInscale() {
  var t = parent.MapFrame;
  var halfWidth = (limitMaxX - limitMinX) / 2;
	var midX = curExt.maxX - (curExt.xSize / 2);
	var inscale=(curExt.maxX-midX)/halfWidth;

	if(inscale > MAX1_SCALE_FACTOR) t.parent.ScaleBar.moveScale("maximum");
  if(inscale > MAX2_SCALE_FACTOR && inscale <= MAX1_SCALE_FACTOR) t.parent.ScaleBar.moveScale("max1");
	if(inscale > MID_SCALE_FACTOR && inscale <= MAX2_SCALE_FACTOR) t.parent.ScaleBar.moveScale("max2");
	if(inscale > MIN2_SCALE_FACTOR && inscale <= MID_SCALE_FACTOR) t.parent.ScaleBar.moveScale("mid");
	if(inscale > MIN1_SCALE_FACTOR && inscale <= MIN2_SCALE_FACTOR) t.parent.ScaleBar.moveScale("min2");
	if(inscale > MIN_SCALE_FACTOR && inscale <= MIN1_SCALE_FACTOR) t.parent.ScaleBar.moveScale("min1");
	if(inscale > 0 && inscale <= MIN_SCALE_FACTOR) t.parent.ScaleBar.moveScale("minimum");
}

// 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 (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 "RetrieveData" image
function showRetrieveData() {
	if (hasLayer("LoadData")) {
		showLayer("LoadData");
	}
}

// hide the "RetrieveData" image
function hideRetrieveData() {
	if (hasLayer("LoadData")) {
		hideLayer("LoadData");
	}
}

// put up the "RetrieveMap" image
function showRetrieveMap() {
	if (hasLayer("LoadMap")) {
		showLayer("LoadMap");
	}
}

// hide the "RetrieveMap" image
function hideRetrieveMap() {
	if (hasLayer("LoadMap")) {
	    //alert("hide the layer");
		hideLayer("LoadMap");
	}
}

/******************************************************
*	Various Distance Conversion Functions
*	*****************************************************/

// calculate distance to current measureBoxUnits
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));
		}
		if (useFineMeasure && (curExt.maxY-curExt.minY < .01)) 
		{	
				
			 if (useMetric)
			{
				measureBoxUnits ="METERS";
				var theDist = convertUnits(mDistance,mUnits,measureBoxUnits);
			}
			else
			{
			  measureBoxUnits ="FEET";
				theDist = mDistance;
			}
			var u = Math.pow(10,0);
		}
		else
		{
			 if (useMetric)
			{
				measureBoxUnits ="KILOMETERS";
				var theDist = convertUnits(mDistance,mUnits,measureBoxUnits);
			}
			else
			{
				measureBoxUnits ="MILES";
				var theDist = convertUnits(mDistance,mUnits,measureBoxUnits);
			}	
			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) {
	sUnits = sUnits.toUpperCase();
	// 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;
}

// pan using arrow buttons
function panButton(panType) {
	saveLastExtent();
	var xDistance = curExt.xSize;
	var yDistance = curExt.ySize;
	var panX = xDistance * panFactor;
	var panY = yDistance * panFactor;
	switch(panType) {
	//if (panType == 1) {
	case 1:
		//west
		//revist- possible update extent method
		reqExt.minX = curExt.minX - panX;
		reqExt.maxX = reqExt.minX + xDistance
		break
	case 2:
		// north
		reqExt.maxY = curExt.maxY + panY;
		reqExt.minY = reqExt.maxY - yDistance;
		break
	case 3:
		// east
		reqExt.maxX = curExt.maxX + panX;
		reqExt.minX = reqExt.maxX - xDistance;
		break
	case 4:
		// south
		reqExt.minY = curExt.minY - panY;
		reqExt.maxY = reqExt.minY + yDistance
		break
	case 5:
		// southwest
		reqExt.maxY = curExt.maxY - panY;
		reqExt.minX = curExt.minX - panX;
		reqExt.minY = reqExt.maxY - yDistance;
		reqExt.maxX = reqExt.minX + xDistance;
		break
	case 6:
		// northwest
		reqExt.maxY = curExt.maxY + panY;
		reqExt.minX = curExt.minX - panX;
		reqExt.minY = reqExt.maxY - yDistance;
		reqExt.maxX = reqExt.minX + xDistance;
		break
	case 7:
		// northeast	
		reqExt.maxY = curExt.maxY + panY;
		reqExt.minX = curExt.minX + panX;
		reqExt.minY = reqExt.maxY - yDistance;
		reqExt.maxX = reqExt.minX + xDistance;		
		break
	case 8:
		// southeast
		reqExt.maxY = curExt.maxY - panY;
		reqExt.minX = curExt.minX + panX;
		reqExt.minY = reqExt.maxY - yDistance;
		reqExt.maxX = reqExt.minX + xDistance;
	}
	requestNewMainMap();
}
