//*=========================================================================
//Description:
//   Javascript include file that stores functions that handle map interaction
//		and other Dynamic HTML (DHTML) functionality.
//
//   Dependent References/Classes:
//       config.js
//
//   Source:
//       Aralola Akinmade - Woolpert, August 2003
//
//   Version History:
//       Version 1.0 Aralola Akinmade, Woolpert, August 2003
//=========================================================================

// Variables to store the values for client side conversions and display
// These variables are set on page load through the code-behind page
var hspc = 0; 					    // horizontal image offset
var vspc = 0; 						// vertical image offset
var ovBoxSize = 2; 					// Zoombox line width;
var state = "";						// zoomOut, pan
var zoomBoxWidth = 2;				//Width of zoom box
var activeLayer = 0;			    //The initial active layer ID
var activeLayerName = "";		    //Stores name of active layer
var helpURL = ""					//URL to Help file

var iWidth = 0;						// image width - will be set on server-side
var iHeight = 0;					// image height - will be set on server-side

var toolBorderWidth = 2;			//Width of tool image once selected

var MapUnits = "";
var ScaleBarUnits = "";
var numDecimals = 2;

var mapMinX = 0;
var mapMinY = 0;
var mapMaxX = 0;
var mapMaxY = 0;

var newMinx = 0;
var newMiny = 0;
var newMaxx = 0;
var newMaxy = 0;
var boxMinx = 0;
var boxMiny = 0;
var boxMaxx = 0;
var boxMaxy = 0;

var mapClickAsRecenter = true;
var mapBoxAsZoom = true;
var allowRubberband = true;
var allowMapClick = true;


// 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 zminx=0;
var zmaxx=0;
var zmaxy=0;
var zminy=0;

var minx=0;
var maxx=0;
var maxy=0;
var miny=0;

var mapX = 0; 
var mapY = 0; 

var zooming=false;
var panning=false;
var measuring=false;
var bottomBorderHeight = 13;

// setup test for Nav 4.0
var isIE = false;
var isNav = (navigator.appName.indexOf("Netscape")>=0);
var isNav4 = false;
var isIE4 = false;
var is5up = false;
var isMac = false;
var isWin = false;

//--------------------------------
// set up arrays for measure tool
var arryMeasureXY = new Array();
var totDist = 0;
var pnlMapHTML;
//--------------------------------

if (isNav) {
	
	if (parseFloat(navigator.appVersion)<5) {
		isNav4=true;
	} else {
		is5up = true;
	}
} else {
	isIE4=true;
	isIE=true;
	if (navigator.appVersion.indexOf("MSIE 5")>0) {
		isIE4 = false;
		is5up = true;
	}
}	

if (navigator.userAgent.indexOf("Win") >= 0) 
	isWin = true;
else
	isMac = true;

//***********************************************	
//***************** FUNCTIONS *******************
//***********************************************

//================================
// check for mouseup
//================================
function chkMouseUp(e) { 
	if (zooming || panning || measuring) {
		if (mouseX<0)
		 	mouseX = 0;
		if (mouseX>iWidth)
			mouseX = iWidth;
		if (mouseY<0)
			mouseY = 0;
		if (mouseY>iHeight)
			mouseY = iHeight;
		mapTool(e);
	}
	
}

function customMapBox(_newMinx, _newMiny, _newMaxx, _newMaxy) {

}

function customMapClick(_newX, _newY) {

}
//================================
// Get the X & Y click location on
// the image
//================================
function getImageXY(e) {
	//if (document.layers) {
	if (isNav) {
		mouseX=e.pageX;
		mouseY=e.pageY;
	} else {
		mouseX=event.clientX + document.body.scrollLeft;
		mouseY=event.clientY + document.body.scrollTop;
	}
	// subtract offsets from page left and right
	mouseX = mouseX-hspc;
	mouseY = mouseY-vspc;
}	
//===============================================
// convert mouse click xy's into map coordinates
//===============================================
function getMapXY(xIn,yIn) {

	mouseX = xIn;
	var pixelX = (maxx-minx) / iWidth;
	
	mapX = pixelX * mouseX + minx;
	mouseY = iHeight - yIn;
	var pixelY = (maxy-miny) / iHeight;
		
	mapY = pixelY * mouseY + miny;
}
//===============================================
// get the coords at mouse position
//===============================================
function getMouse(e) {
 
	window.status="";
	getImageXY(e);
	
	if (zooming) {
		if (mouseX<0)
		 	mouseX = 0;
		if (mouseX>iWidth)
			mouseX = iWidth;
		if (mouseY<0)
			mouseY = 0;
		if (mouseY>iHeight-bottomBorderHeight)
			mouseY = iHeight-bottomBorderHeight;
		x2=mouseX;
		y2=mouseY;
		setClip();
		return false;
	} else if (panning) {
		x2=mouseX;
		y2=mouseY;			
		panMouse();	
		return false;
	} else 
    	return true;
	return true;
}
//===============================================
// Hide the Zoom Box
//===============================================
function hideZoomBox() {
	hideLayer("zoomBoxTop");
	hideLayer("zoomBoxLeft");
	hideLayer("zoomBoxRight");
	hideLayer("zoomBoxBottom");
}
//===============================================
// perform appropriate action with mapTool
//===============================================
function mapTool (e) {

	getImageXY(e);
	  
	   //Identify 	
	if ((state == "IDENTIFY") && 
	    (mouseX >= 0) && (mouseX <= iWidth) && 
	    (mouseY >= 0) && (mouseY <= iHeight)){
			//getMapXY(mouseX,mouseY);
			//sendIdentify(mapX,mapY);			
			sendIdentify();
			return false; // <-- false assures that the popup
			              //     box stays in front.
	}
	
	if ((!zooming) && (!panning) && (!measuring) &&
		(mouseX >= 0) && (mouseX <= iWidth) && 
		(mouseY >= 0) && (mouseY <= iHeight)) {
		
		if (state == "PAN") {
			startPan(e);
		}	
		else if (state == "MEASURE")
		{
			startDistTool(e);
		}else {
			startZoomBox(e);
		}
			
		return false;
	} else if (zooming) {
		getMouse(e);
		stopZoomBox(e);
	} else if (panning) {
		getMouse(e);
		stopPan(e);
	} else if (measuring) {
		startDistTool(e);
	}
	return true;
}
//===============================================
// move map image with mouse
//===============================================
function panMouse() {

	var xMove = x2-x1;
	var yMove = y2-y1;
	
	var cLeft = -xMove;
	var cTop = -yMove;
	
	var cRight = iWidth;
	var cBottom = iHeight;
	
	if (xMove>0) {
			cLeft = 0;
			cRight = iWidth - xMove;
	}
	if (yMove>0) {
			cTop = 0;
			cBottom = iHeight - yMove;
	}
	
	if (document.all)
	{
		document.all("pnlMap").style.position = "absolute";		
		//document.all("pnlFunctions").style.position = "absolute";	
		moveLayer("pnlFunctions",hspc,iHeight+vspc);			
				
		clipLayer("pnlMap",cLeft,cTop,cRight,cBottom);
		moveLayer("pnlMap",xMove+hspc,yMove+vspc);
	
	/*}else{
		document.getElementById("pnlMap").style.position = "absolute";
		document.getElementById("pnlFunctions").style.position = "absolute";	
		moveLayer("pnlFunctions",hspc,iHeight+vspc);			
				
		clipLayer("pnlMap",cLeft+hspc,cTop+vspc,cRight-hspc,cBottom-vspc);
		moveLayer("pnlMap",xMove+hspc,yMove+vspc);
	*/	
	}


	return false;
}
//===============================================
// recenter map is the default option
//===============================================
function recenter(e) {

	// otherwise we don't have these layers
	if (allowRubberband)
		hideZoomBox();
		
	getMapXY(mouseX,mouseY);
	if (mapClickAsRecenter) {
		var widthHalf = Math.abs(maxx - minx) / 2;
		var heightHalf = Math.abs(maxy - miny) / 2;
		
		newMinx = mapX - widthHalf;
		newMaxx = mapX + widthHalf;
		newMaxy = mapY + heightHalf;
		newMiny = mapY - heightHalf;

		refreshMap(); 
	} else
		customMapClick(mapX,mapY);
}
//===============================================
// Refresh the map by submitting the form
//===============================================
function refreshMap() {

  hideZoomBox();
  
  if (document.all)
  {
	if (document.all("searchValue") && state == "FIND") 
	{
		if (document.all("searchValue").value == "") {
			alert("Please type in a value");
			return false;
		} 
	}
 }	else { 
		if (document.getElementById("searchValue") && state == "FIND") {
			if (document.getElementById("searchValue").value == "") {
				alert("Please type in a value");
				return false;
			} 
		}
 }
  //show the loading map graphic
  showLayer("pnlLoadingMap");
  
 if (zminx != null) document.MapForm.hiddenZoomExtents.value = zminx + ','+ zminy + ',' + zmaxx + ',' + zmaxy;		 
 //alert(document.MapForm.hiddenZoomExtents.value );

 //Set Active Tool
 document.MapForm.hiddenActiveTool.value = state;
 //Set Active Layer
 document.MapForm.hiddenActiveLayer.value = activeLayer;
 document.MapForm.submit();	

}
//===============================================
// Send the identify click location by submitting
// the form
//===============================================
function sendIdentify() {
			
 //show the loading map graphic
 showLayer("pnlLoadingMap");
			   
if (mouseX != null) document.MapForm.hiddenZoomExtents.value = mouseX + ','+ mouseY + ',' + mouseX + ',' + mouseY;		
// alert(document.MapForm.hiddenZoomExtents.value );
 
 //Set Active Tool
 document.MapForm.hiddenActiveTool.value = state;
 //Set Active Layer
 document.MapForm.hiddenActiveLayer.value = activeLayer;
 document.MapForm.submit();	
}
//===============================================
// clip zoom box layer to mouse coords
//===============================================
function setClip() {	

	if (x1>x2) {
		zmaxx=x1;
		zminx=x2;
	} else {
		zminx=x1;
		zmaxx=x2;
	}
	if (y1>y2) {
		zminy=y1;
		zmaxy=y2;
	} else {
		zmaxy=y1;
		zminy=y2;
	}
	
	window.status = "Coords: " + zminx + ", " + zminy + ", " + zmaxx + ", " + zmaxy;
	
	if ((x1 != x2) && (y1 != y2)) {
		clipLayer("zoomBoxTop",zminx,zmaxy,zmaxx,zmaxy+zoomBoxWidth);
		clipLayer("zoomBoxLeft",zminx,zmaxy,zminx+zoomBoxWidth,zminy);
		clipLayer("zoomBoxRight",zmaxx-zoomBoxWidth,zmaxy,zmaxx,zminy);
		clipLayer("zoomBoxBottom",zminx,zminy-zoomBoxWidth,zmaxx,zminy);
	}
}
//===============================================
// Set the map extent
//===============================================
function setExtent(_minx,_miny,_maxx,_maxy) {
	minx = _minx;
	miny = _miny;
	maxx = _maxx;
	maxy = _maxy;
}
//===============================================
// Set the active tool
//===============================================
function setState(newState) {
	state = newState;
	
	//Set the cursor style
	setCursor(state);
	
	if (state == "ZOOMIN") {
		mapBoxAsZoom = true;			
		setZoomBoxColor(zoomBoxColor);
		setZoomBoxWidth(1);
	} else if (state == "ZOOMOUT") {
		mapBoxAsZoom = true;
		setZoomBoxColor(zoomBoxColor);
		setZoomBoxWidth(1);
	} else if ((state == "FULLEXTENT") || (state == "ZOOMLAST") || (state == "ZOOMNEXT") || (state == "ZOOMACTIVE") || (state == "CLEARSELECTION")) {
		refreshMap();	
	} else if (state == "FIND") {
		displayFindForm();
	} else if (state == "GEOCODE") {
		displayGeocodeForm();
	} else if (state == "PRINT") {
		displayPrintForm();	
	} else if ((state == "PANNORTH") || (state == "PANWEST") || (state == "PANEAST") || (state == "PANSOUTH")) {
		directionPan();
	}
	//Set the hidden box state
	document.getElementById("hiddenActiveTool").value = state;
}
//===============================================
// Set the cursor look
//===============================================
function setCursor(state)
{
 if (state == "PAN") {
		if (document.getElementById){   // DOM3 = IE5, NS6
				//document.getElementById('theTop').style.cursor = "move";
				document.getElementById('pnlMap').style.cursor = "move";
		}else if (document.layers){   // Netscape 4
				//document.theTop.style.cursor = "move";
				document.pnlMap.style.cursor = "move";
		}else {  // IE 4
				//document.all.theTop.style.cursor = "move";
				document.all.pnlMap.style.cursor = "move";
		}
	}
	else if (state == "IDENTIFY") {
		if (document.getElementById){   // DOM3 = IE5, NS6
				//document.getElementById('theTop').style.cursor = "hand";
				document.getElementById('pnlMap').style.cursor = "hand";
		}else if (document.layers){   // Netscape 4
				//document.theTop.style.cursor = "hand";
				document.pnlMap.style.cursor = "hand";
		}else {  // IE 4
				//document.all.theTop.style.cursor = "hand";
				document.all.pnlMap.style.cursor = "hand";
		}
	} 
	else if ((state == "ZOOMIN") || (state == "ZOOMOUT") || (state == "SELECT") || (state == "MEASURE")) {
		if (document.getElementById){   // DOM3 = IE5, NS6
				//document.getElementById('theTop').style.cursor = "crosshair";
				document.getElementById('pnlMap').style.cursor = "crosshair";
		}else if (document.layers){   // Netscape 4
				//document.theTop.style.cursor = "crosshair";
				document.pnlMap.style.cursor = "crosshair";
		}else {  // IE 4
				//document.all.theTop.style.cursor = "crosshair";
				document.all.pnlMap.style.cursor = "crosshair";
		}
	}
	else {
			if (document.getElementById){   // DOM3 = IE5, NS6
				//document.getElementById('theTop').style.cursor = "default";
				document.getElementById('pnlMap').style.cursor = "default";
		}else 	if (document.layers) {  // Netscape 4
				//document.theTop.style.cursor = "default";
				document.pnlMap.style.cursor = "default";
		}else  { // IE 4
				//document.all.theTop.style.cursor = "default";
				document.all.pnlMap.style.cursor = "default";
		}
	}

}
//===============================================
// Set the zoom box color
//===============================================
function setZoomBoxColor(color) {
	setLayerBackgroundColor("zoomBoxTop", color);
	setLayerBackgroundColor("zoomBoxLeft", color);
	setLayerBackgroundColor("zoomBoxRight", color);
	setLayerBackgroundColor("zoomBoxBottom", color);
}
//===============================================
// Set the zoom box settings
//===============================================
function setZoomBoxSettings() {

	//Hide the loading map graphic
	hideLayer("pnlLoadingMap");
	
	// Set up event capture for mouse movement
	if (isNav && is5up) {
		document.captureEvents(Event.MOUSEMOVE);
		document.captureEvents(Event.MOUSEDOWN);
		document.captureEvents(Event.MOUSEUP);
		document.onmousemove = getMouse;
		document.onmousedown = mapTool;
		document.onmouseup = chkMouseUp;
	} else if (isNav4) {
		// otherwise the buttons don't work
	
		getLayer("pnlMap").captureEvents(Event.MOUSEMOVE);
		getLayer("pnlMap").captureEvents(Event.MOUSEDOWN);
		getLayer("pnlMap").captureEvents(Event.MOUSEUP);
		getLayer("pnlMap").onmousemove = getMouse;
		getLayer("pnlMap").onmousedown = mapTool;
		getLayer("pnlMap").onmouseup = chkMouseUp;
		
	} else {
		document.onmousemove = getMouse;
		document.onmousedown = mapTool;
		document.onmouseup = chkMouseUp;
	}
	
	// Set image width, height, initial position, overflow
	var elt;
	if (document.all)
	{
		//Set Positioning of Map
		elt = document.all("pnlMap");
		hspc = getAbsX(elt);
		vspc = getAbsY(elt);
		document.all("pnlMap").style.width = iWidth;
		document.all("pnlMap").style.height = iHeight;
		document.all("pnlMap").style.zIndex = 2;
						
		document.all("imgMap").style.width = iWidth;
		document.all("imgMap").style.height = iHeight;
		document.all("imgMap").style.zIndex = 3;
						
								
	} else {		
		//Set Positioning of Map
		elt = document.getElementById("pnlMap")
		hspc = getAbsX(elt);
		vspc = getAbsY(elt);
		document.getElementById("pnlMap").style.width = iWidth;
		document.getElementById("pnlMap").style.height = iHeight;
		document.getElementById("pnlMap").style.zIndex = 2;
				
		document.getElementById("imgMap").style.width = iWidth;
		document.getElementById("imgMap").style.height = iHeight;
		document.getElementById("imgMap").style.zIndex = 3;
				
	}
	
	
	//Reset Cursor
	setCursor(state);
	
	//Store content of the map panel
	pnlMapHTML = document.getElementById("pnlMap").innerHTML;
}
//===============================================
// Set the zoom box width
//===============================================
function setZoomBoxWidth(size) {
	zoomBoxWidth = size;
}
//===============================================
// Show the zoom box
//===============================================
function showZoomBox() {
	showLayer("zoomBoxTop");
	showLayer("zoomBoxLeft");
	showLayer("zoomBoxRight");
	showLayer("zoomBoxBottom");
}
//===============================================
// start pan.... image will move
//===============================================
function startPan(e) {

if (document.all)
{	
	moveLayer("pnlMap",hspc,vspc);
}
	getImageXY(e);

	// keep it within the MapImage
	if ((mouseX<iWidth) && (mouseY<iHeight)) {
		if (panning) {
			stopPan(e);
		} else {
			x1=mouseX;
			y1=mouseY
			x2=x1+1;
			y2=y1+1;
			panning=true;
		}
	}
	return false;

}
//===============================================
// start zoom in.... box displayed
//===============================================
function startZoomBox(e) {

	getImageXY(e);	

	if (!allowRubberband) {
		stopZoomBox(e);
	} else {	
		// keep it within the MapImage
		if ((mouseX<iWidth) && (mouseY<iHeight-bottomBorderHeight)) {
			if (!zooming) {
				x1=mouseX;
				y1=mouseY;
				x2=x1+1;
				y2=y1+1;
				zooming=true;
				clipLayer("zoomBoxTop",x1,y1,x2,y2);
				clipLayer("zoomBoxLeft",x1,y1,x2,y2);
				clipLayer("zoomBoxRight",x1,y1,x2,y2);
				clipLayer("zoomBoxBottom",x1,y1,x2,y2);
				showZoomBox();
			}
		} else {
			if (zooming) {
				stopZoomBox(e);
			}
		}
	}
	return false;	
}
//===============================================
// stop moving image.... pan 
//===============================================
function stopPan(e) {

	//To capture single pan click
	//getImageXY(e);
	/*	
	zminx = mouseX;
	zminy = mouseY;
	zmaxx = mouseX;
	zmaxy = mouseY;
	*/
	//------------------------
		
	//if ((Math.abs(x2-x1) < 2) && (Math.abs(y2-y1) < 2)) {
		// the move is too small
	//	recenter(e);
	//} else  {
		window.scrollTo(0,0);
		panning=false;
		
		
		minx=hspc;
		maxx=hspc + iWidth;
		maxy=vspc + iHeight;
		miny=vspc;	

		var width = Math.abs(maxx - minx);
		var height = Math.abs(maxy - miny);
			
		var tempLeft=hspc;
		var tempRight=hspc + iWidth;
		var tempTop=vspc + iHeight;
		var tempBottom=vspc;
		var ixOffset = x2-x1;
		var iyOffset = y2-y1;
		
		pixelX = width / iWidth;
		var theY = iHeight - zmaxy;
		pixelY = height / iHeight;
		
		var xOffset = pixelX * ixOffset;
		var yOffset = pixelY * iyOffset;
		
		newMaxy = maxy - yOffset;			
		newMaxx = maxx - xOffset;
		newMinx = minx - xOffset;
		newMiny = miny - yOffset;
		
		zminx = newMinx;
		zminy = newMiny;
		zmaxx = newMaxx;
		zmaxy = newMaxy;
		
		/*
		zminx = x1;
		zminy = y1;
		zmaxx = x2;
		zmaxy = y2;
		*/		
		// AP specific setting
		attributeUpdate = false;
		
		refreshMap();
	//}
		
	return true;
	
}

//===============================================
// stop moving image.... directional pan 
//===============================================
function directionPan(e) {
	
	if ((Math.abs(x2-x1) < 2) && (Math.abs(y2-y1) < 2)) {
		// the move is too small
		recenter(e);
	} else  {
		window.scrollTo(0,0);
		panning=false;
		
		var width = Math.abs(maxx - minx);
		var height = Math.abs(maxy - miny);
		var tempLeft=minx;
		var tempRight=maxx;
		var tempTop=maxy;
		var tempBottom=miny;
		
				
		var ixOffset = x2-x1;
		var iyOffset = y1-y2;
		pixelX = width / iWidth;
		var theY = iHeight - zmaxy;
		pixelY = height / iHeight;
		var xOffset = pixelX * ixOffset;
		var yOffset = pixelY * iyOffset;
		newMaxy = maxy - yOffset;
		newMaxx = maxx - xOffset;
		newMinx = minx - xOffset;
		newMiny = miny - yOffset;		
		// AP specific setting
		attributeUpdate = false;
		
		refreshMap();
	}
	return true;
}
//===============================================
// stop zoom box display... zoom in
//===============================================
function stopZoomBox(e) {
	zooming=false;
	if ((zmaxx <zminx+2) && (zmaxy < zminy+2)) {
		// if the zoom box is too small
		recenter(e);
	} else {
		var width = Math.abs(maxx - minx);
		var height = Math.abs(maxy - miny);
		var pixelX = width / iWidth;
		var theY = iHeight - zmaxy;
		var pixelY = height / iHeight;
		newMaxy = pixelY * theY + miny;
		newMaxx = pixelX * zmaxx + minx;
		newMinx = pixelX * zminx + minx;
		theY = iHeight - zminy;
		pixelY = height / iHeight;
		newMiny = pixelY * theY + miny;

		if (mapBoxAsZoom) {
			if (state == "ZOOMOUT") {
				percentX = (maxx-minx)/(newMaxx-newMinx);
				percentY = (maxy-miny)/(newMaxy-newMiny);
				percent = (percentX+percentY)/2;
				
				widthH = (maxx-minx)/2;
				heightH = (maxy-miny)/2;
				cx = newMinx + widthH;
				cy = newMiny + heightH;
				
				newMinx = cx - percent * widthH;
				newMiny = cy - percent * heightH;
				newMaxx = cx + percent * widthH;
				newMaxy = cy + percent * heightH;
			}
			refreshMap();
		} else
			customMapBox(newMinx, newMiny, newMaxx, newMaxy);
			
	}
	return true;
}

//-------- LAYER SUPPORT FUNCTIONS --------------

//===============================================
// clip layer display to clipleft, cliptip, clipright, clipbottom
//==================================================
function clipLayer(name, clipleft, cliptop, clipright, clipbottom) {		
	var layer = getLayer(name);		
	if (layer != null) {
  		if (isNav4) {
			layer.clip.left   = clipleft;
			layer.clip.top    = cliptop;
		    layer.clip.right  = clipright;
			layer.clip.bottom = clipbottom;
		} else if (isIE) {
			layer.clip = 'rect(' + cliptop + ' ' +  clipright + ' ' + clipbottom + ' ' + clipleft +')';
	    } else {
     		layer.height = clipbottom - cliptop;
			layer.width	= clipright - clipleft;
			layer.top	= (cliptop+vspc) + "px";
			layer.left	= (clipleft+hspc) + "px";
		}
	}
}
//=============================================
// Create a DHTML layer
//=============================================
function createLayer(name, left, top, width, height, visible, content, zindx) {
	  var layer;
	  if (isNav4) {
	    document.writeln('<layer name="' + name + '" z-index="' + zindx + '" position="absolute" left=' + left + ' top=' + top + ' width=' + width + ' height=' + height +  ' visibility=' + (visible ? '"show"' : '"hide"') +  '>');
	    document.writeln(content);
	    document.writeln('</layer>');
	    layer = getLayer(name);
	    layer.width = width;
	    layer.height = height;
	  } else {
	    document.writeln('<div id="' + name + '" style="z-index:' + zindx + '; overflow:none; position:absolute; left:' + left + 'px; top:' + top + 'px; width:' + width + 'px; height:' + height + 'px;' + ' visibility:' + (visible ? 'visible;' : 'hidden;') +  '">');
	    document.writeln(content);
	    document.writeln('</div>');
	  }
	  clipLayer(name, 0, 0, width, height);
	  moveLayer(name, left, top);
}
//=============================================
// get the layer object called "name"
//=============================================
function getLayer(name) {
	  if (isNav4)
	    return(document.layers[name]);
	  else if (isIE4) {
	  	if ( eval('document.all.' + name) != null) {
		    layer = eval('document.all.' + name + '.style');
		    return(layer);
		} else
			return(null);
	  } else if (is5up) {
		var theObj = document.getElementById(name);
		return theObj.style
	  } else
	    return(null);
}
//=============================================
// toggle layer to invisible
//=============================================
function hideLayer(name) {		
  	var layer = getLayer(name);		
	if (layer != null) {
	 	if (isNav4)
    		layer.visibility = "hide";
		else
   			 layer.visibility = "hidden";
	}
}
//=============================================
// move layer to x,y
//=============================================
function moveLayer(name, x, y) {		
  	var layer = getLayer(name);		
	if (layer != null) {
	  	if (isNav4)
    		layer.moveTo(x, y);
	 	else if (isIE) {
    		layer.left = x + "px";
   			layer.top  = y + "px";
		} else {
			layer.height = iHeight - y;
			layer.width	= iWidth - x;
    		layer.left = x + "px";
   			layer.top  = y + "px";
	  	}
	}
}
//=============================================
// replace layer's content with new content
//=============================================
function replaceLayerContent(name, content) {
	  if (isNav4) {
		    var layer = getLayer(name);
			if (layer != null) {
			    layer.document.open();
			    layer.document.writeln(content);
			    layer.document.close();
			}
	  }  else if (isIE) {
			if (eval("document.all." + name) != null) {
		  		content = content.replace(/\'/g,"\\'");
			    var str = "document.all." + name + ".innerHTML = '" + content + "'";
			    eval(str);
			}
	  }
}
//=============================================
// set layer background color
//=============================================
function setLayerBackgroundColor(name, color) {		
  	var layer = getLayer(name);		
	if (layer != null) {
	    if (isNav4) 
    		layer.bgColor = color;
		else 
    		layer.backgroundColor = color;
	}
}
//=============================================
// toggle layer to visible
//=============================================
function showLayer(name) {		
  	var layer = getLayer(name);		
	if (layer != null) {
	  	if (isNav4)
    		layer.visibility = "show";
		else
   		 	layer.visibility = "visible";
	}
}
	//======================================================
	//Functions for determining the position of the map
	//------------------------------------------------------
	function getAbsX(elt) { return (elt.x) ? elt.x : getAbsPos(elt,"Left"); }
	function getAbsY(elt) { return (elt.y) ? elt.y : getAbsPos(elt,"Top"); }
	function getAbsPos(elt,which) {
	iPos = 0;
		while (elt != null) {
			iPos += elt["offset" + which];
			elt = elt.offsetParent;
		}
		return iPos;
	}	

//=======================================
// For measuring distance and area
//========================================
function startDistTool(e)
{
	getImageXY(e);	
	
	var arryLen = arryMeasureXY.length;
	
	// keep it within the MapImage
	if ((mouseX>-1) && (mouseY>-1) && (mouseX<iWidth) && (mouseY<iHeight-bottomBorderHeight)) 
	{		
		if (document.all){
			drawVectorPoint(mouseX,mouseY);
			arryMeasureXY[arryLen] = mouseX + "," + mouseY;
		}else{
			drawVectorPoint(mouseX+hspc,mouseY+vspc);
			arryMeasureXY[arryLen] = (mouseX+hspc) + "," + (mouseY+vspc);
		}
		if (arryLen > 1) {
			//draw the line
			drawVectorLine(arryMeasureXY[arryLen-2], arryMeasureXY[arryLen-1]);
			//calculate distance
			calcDistance(arryMeasureXY[arryLen-2], arryMeasureXY[arryLen-1]);
		}	
		measuring=true;
	}
	return false;	
}
//=============================================
// Draw the vector line
//=============================================
function drawVectorLine(xy1, xy2)
{  
  var xyCoords = xy1 + "," + xy2;
  var numXYCoords = xyCoords.split(",");
  
  var jg = new jsGraphics("pnlMap");
  jg.setColor("#ff0000");		//red 
  jg.drawLine(parseInt(numXYCoords[0]), parseInt(numXYCoords[1]), parseInt(numXYCoords[2]), parseInt(numXYCoords[3]));	//x1, y1, x2, y2 co-ordinates related to "pnlMap"
  jg.paint();    
}
//=============================================
// Draw the vector point
//=============================================
function drawVectorPoint(x,y)
{ 
  var jg = new jsGraphics("pnlMap");
  jg.setColor("#ff0000");		//red 
  jg.fillEllipse(x,y,3,3);	    //x1, y1, x2, y2 co-ordinates related to "pnlMap"
  jg.paint();    
}
//=============================================
//Clear the vectors
//=============================================
function clearVectors()
{
    var jg = new jsGraphics("pnlMap");
	jg.clear();
	document.getElementById("pnlMap").innerHTML = pnlMapHTML;
	arryMeasureXY.length = 0;
	totDist = 0;
	displayMeasureForm(0,0);		
}
//-------------------------------------------------
// Calculate distance to current scalebarunits
//-------------------------------------------------
function calcDistance(xy1,xy2) 
{
  var curDist;
  var xyCoords = xy1 + "," + xy2;
  var numXYCoords = xyCoords.split(",");
  var x1, x2, y1, y2;
  
  //Grab the mouse coordinates
  x1 = parseInt(numXYCoords[0]);
  y1 = parseInt(numXYCoords[1]);
  x2 = parseInt(numXYCoords[2]);
  y2 = parseInt(numXYCoords[3]);
  
  //Convert mouse coordinates to map coordinates
  x1 = mapMinX + (((parseInt(x1) / iWidth)) * (mapMaxX - mapMinX));
  y1 = mapMinY + (((iHeight -parseInt(y1)) / iHeight) * (mapMaxY - mapMinY));
  x2 = mapMinX + (((parseInt(x2) / iWidth)) * (mapMaxX - mapMinX));
  y2 = mapMinY + (((iHeight -parseInt(y2)) / iHeight) * (mapMaxY - mapMinY));

  	// Note: decimal are not hard coded to allow use with locales using commas instead of points.
	
		var mUnits = MapUnits;
		var mDistance = 0;
		var Lon1 = x1 * Math.PI / 180; //x1
		var Lon2 = x2 * Math.PI / 180; //x2
		var Lat1 = y1 * Math.PI / 180; //y1
		var Lat2 = y2 * Math.PI / 180; //y2
			
		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 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(x1 - x2);
			var yD = Math.abs(y1 - y2);
			mDistance = Math.sqrt(Math.pow(xD,2) + Math.pow(yD,2));
		}
			
		var theDist = convertUnits(mDistance,mUnits,ScaleBarUnits);
		var u = Math.pow(10,numDecimals);
			
		curDist = parseInt(theDist*u+(5/10))/u;		
		totDist = totDist + parseFloat(curDist);
		totDist = parseInt(totDist*u+(5/10))/u;	
		
		displayMeasureForm(curDist, totDist);			
}
//---------------------------------
//Convert 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;
	var numDecimals = 2;
		
	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;
}
