/*
*  JavaScript template file for ArcIMS HTML Viewer
*		dependent on aimsXML.js, ArcIMSparam.js, aimsCommon.js, aimsMap.js,
*		aimsLayers.js, aimsDHTML.js
*		aimsNavigation.js
*/

var aimsClickPresent=true;
var toggleTOC = 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 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 panning=false;
var zooming=false;
var selectBox=false;
var blankImage = "images/map.gif";

var leftButton =1;
var rightButton = 2;
if (isNav) {
	leftButton = 1;
	rightButton = 3;
}

var intersection_click = false; 

//	Point click functions
// 	used by Measure and Select by Line/Polygon

// put a point at click and add to clickCount
function clickAddPoint() {
	var theX = mouseX;
	var theY = mouseY;
	getMapXY(theX,theY);
	clickPointX[clickCount]=mapX;
	clickPointY[clickCount]=mapY;
	clickCount += 1;
	selectCount=0;
	totalMeasure = totalMeasure + currentMeasure;
		var u = Math.pow(10,numDecimals);
		if (totalMeasure!=0) totalMeasure = parseInt(totalMeasure*u+0.5)/u;

	clickMeasure[clickCount]=totalMeasure;
	if (noOverlay) {
		legendTemp=legendVisible;
		legendVisible=false;
			var theString = writeXML();
			var theNum = 99;
	} else {
			var theString = writeOverlayXML();
			var theNum = 901;
	
	}
	sendToServer(imsURL,theString,theNum);

}

// zero out all clicks in clickCount
function resetClick() {
	var c1 = clickCount;
	clickCount=0;
	clickPointX.length=1;
	clickPointY.length=1;
	currentMeasure=0;
	totalMeasure=0;
	lastTotMeasure=0;
	clickMeasure.length=1;
	selectCount=0;
	
	if (noOverlay) {
		legendTemp=legendVisible;
		legendVisible=false;
		var theString = writeXML();
		var theNum = 99;
		sendToServer(imsURL,theString,theNum);
		
	} else {
		document.theClickImage.src = blankImage;
	}
	if (toolMode==20) updateMeasureBox();

}	

// remove last click from clickCount
function deleteClick() {
	var c1 = clickCount;
	clickCount=clickCount-1;
	selectCount=0;
	if (clickCount<0) clickCount=0;
	if (clickCount>0) {
		totalMeasure = clickMeasure[clickCount]
		clickPointX.length=clickCount;
		clickPointY.length=clickCount;
		clickMeasure.length=clickCount;
		
	} else {
		totalMeasure=0;
		clickMeasure[0]=0;
	}
	currentMeasure=0;
	if (c1>0) {
		if (noOverlay) {
			legendTemp=legendVisible;
			legendVisible=false;
				var theString = writeXML();
				var theNum = 99;
		} else {
				var theString = writeOverlayXML();
				var theNum = 901;
		
		}
		sendToServer(imsURL,theString,theNum);
	}
	
}


//keep track of currently selected tool, and display it to user
// set the imsMap cursor tool
function clickFunction (toolName) {
	if (hasLayer("measureBox"))
		hideLayer("measureBox");
	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 = "Zoom In";
		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 = "Zoom Out";
		break
	case "zoomlast":
		zoomBack();
		panning=false;
		zooming=false;
		selectBox=false;
		break
	case "zoomactive":
		var q = LayerExtent[ActiveLayerIndex].split(",");
		panning=false;
		zooming=false;
		selectBox=false;
		
		var l = parseFloat(q[0]);
		var b = parseFloat(q[1]);
		var r = parseFloat(q[2]);
		var t = parseFloat(q[3]);
		var w = r-l;
		var h = t-b;
		// add a bit of a margin around the layer
		var wm = w * 0.05;
		var hm = h * 0.05;
		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 = "Pan";
		break

	// Identify-Hyperlink functions
	case "identify":
		// identify mode - layer attributes - requires aimsIdentify.js
		panning=false;
		zooming=false;
		selectBox=false;
		if (canQuery) {
			toolMode = 4;
			intersection_click = true;
			if (isIE)	{
				document.all.theTop.style.cursor = "crosshair";
				theCursor = document.all.theTop.style.cursor;
			}
			modeBlurb = "Identify";
		} else {
			alert("Cannot query Service\nIdentify, Select, and Query functions are disabled.");
		}
	
		showGeocode=false;
		if (useTextFrame) parent.TextFrame.document.location= appDir + "text.htm";
		hideLayer("measureBox");
		break

	case "hyperlink":
		// hyperlink mode - requires aimsIdentify.js
		var isOk = false;
		var j=-1;
		panning=false;
		zooming=false;
		selectBox=false;
		toolMode = 15;
		modeBlurb = "HyperLink";
		showGeocode=false;
		if (useTextFrame) parent.TextFrame.document.location= appDir + "text.htm";
		hideLayer("measureBox");
		var isOk = checkHyperLinkLayer(ActiveLayerIndex)
		if (isOk) {
			if (canQuery) {
				
				
				if (isIE)	{
					document.all.theTop.style.cursor = "crosshair";
					theCursor = document.all.theTop.style.cursor;
				}
				
			} else {
				alert("Cannot query Service\nIdentify, Select, and Query functions are disabled.");
			}
		} else {
			currentHyperLinkLayer="";
			currentHyperLinkField="";
			alert("This layer does not have any HyperLinks.");

		}
		break
		
	// Measure-Unit function
	case "measure":
		panning=false;
		zooming=false;
		selectBox=false;
		if (clickCount>0) {
			if (totalMeasure==0) resetClick();
		}
		toolMode = 20;
		if (isIE)	{
			document.all.theTop.style.cursor = "crosshair";
			theCursor = document.all.theTop.style.cursor;
		}
		modeBlurb = "Measure";
		if (clickType==1) {
				showLayer("measureBox");
				updateMeasureBox();
		}
		showGeocode=false;
		break
		
	case "setunits":
		if (useTextFrame) {
			parent.TextFrame.location = "setUnits.htm";
		} else {
			window.open((appDir + "setUnits.htm"),"OptionWindow","width=575,height=120,scrollbars=yes,resizable=yes");
		}
		break
		
	// Graphic Selection functions
	case "shape":
		panning=false;
		zooming=false;
		selectBox=false;
		toolMode = 21;
		if (isIE)	{
			document.all.theTop.style.cursor = "crosshair";
			theCursor = document.all.theTop.style.cursor;
		}

		modeBlurb = "Create Shape Mode";
	
		showGeocode=false;

		hideLayer("measureBox");
		break
		
	case "selectbox":
		panning=false;
		zooming=false;
		// select mode - requires aimsSelect.js
		if (canQuery) {
			toolMode = 10;
			queryTool=0;
			clickCount=0;
			showBuffer=false;
			if (isIE)	{
				document.all.theTop.style.cursor = "crosshair";
				theCursor = document.all.theTop.style.cursor;
			}

			modeBlurb = "Select Rectangle";
		} else {
			alert("Cannot query Service\nIdentify, Select, and Query functions are disabled.");
		}
		showGeocode=false;
		if (useTextFrame) parent.TextFrame.document.location= appDir + "text.htm";
		hideLayer("measureBox");
		break
		
	case "selectpoint":
		panning=false;
		zooming=false;
		// select mode - requires aimsSelect.js
		if (canQuery) {
			toolMode = 11;
			queryTool=0;
			clickCount=0;
			 resetClick();
			if (isIE)	{
				document.all.theTop.style.cursor = "hand";
				theCursor = document.all.theTop.style.cursor;
			}

			modeBlurb = "Point Select Mode";
		} else {
			alert("Cannot query Service\nIdentify, Select, and Query functions are disabled.");
		}
		showGeocode=false;
		showBuffer=false;
		hideLayer("measureBox");
		break
		
	case "selectline":
		panning=false;
		zooming=false;
		// select mode - requires aimsSelect.js
		if (canQuery) {
			toolMode = 12;
			queryTool=0;
			if (isIE)	{
				document.all.theTop.style.cursor = "crosshair";
				theCursor = document.all.theTop.style.cursor;
			}
			hideLayer("measureBox");
			if (useTextFrame) {
				parent.TextFrame.document.location= appDir + "selectline.htm";
			} else {
				Win1 = open("selectline.htm","QueryWindow","width=575,height=150,scrollbars=yes,resizable=yes");
			}
			modeBlurb = "Select Line";
		} else {
			alert("Cannot query Service\nIdentify, Select, and Query functions are disabled.");
		}
		showGeocode=false;
		showBuffer=false;
		break
		
	case "selectpoly":
		panning=false;
		zooming=false;
		// select mode - requires aimsSelect.js
		if (canQuery) {
			toolMode = 13;
			queryTool=0;
			if (isIE)	{
				document.all.theTop.style.cursor = "crosshair";
				theCursor = document.all.theTop.style.cursor;
			}
			hideLayer("measureBox");
			if (useTextFrame) {
				parent.TextFrame.document.location= appDir + "selectpoly.htm";
			} else {
				Win1 = open("selectpoly.htm","QueryWindow","width=575,height=150,scrollbars=yes,resizable=yes");
			}
			modeBlurb = "Select Polygon";
		} else {
			alert("Cannot query Service\nIdentify, Select, and Query functions are disabled.");
		}
		showGeocode=false;
		showBuffer=false;
		break
		
	case "selectshape":
		panning=false;
		zooming=false;
		// select mode - requires aimsSelect.js
		if (canQuery) {
			toolMode = 16;
			queryTool=0;
			if (isIE)	{
				document.all.theTop.style.cursor = "crosshair";
				theCursor = document.all.theTop.style.cursor;
			}
			hideLayer("measureBox");
				Win1 = open("select.htm","QueryWindow","width=575,height=150,scrollbars=yes,resizable=yes");
			modeBlurb = "Select Line/Polygon";
		} else {
			alert("Cannot query Service\nIdentify, Select, and Query functions are disabled.");
		}
		showGeocode=false;
		showBuffer=false;
		break

/*
		// Geocode Function
	case "geocode":
		panning=false;
		zooming=false;
		selectBox=false;
		// geocode mode - requires aimsGeocode.js
		hideLayer("measureBox");
		modeBlurb = "Locate Address";
		setupGeocode();
		break

	// Query - Search - Find functions
	//if ((toolName=="attributesel") || (toolName=="query")) {
	case "query":
		// query mode - requires aimsQuery.js
		panning=false;
		zooming=false;
		selectBox=false;
		queryStartRecord=0;
		queryTool=51;
		if (canQuery) {	
			LayerFields.length=1;
			LayerFieldType.length=1;
			LayerFieldCount=0;
			toolMode=8;
			modeBlurb="Query";
			
			fieldIndex=0;
			setQueryString="";
			hideLayer("measureBox");
			queryForm();
		} else {
			alert("Cannot query Service\nIdentify, Select, and Query functions are disabled.");
		}
		showGeocode=false;
		showBuffer=false;
		break
		
	case "storedquery":
		// storedquery mode - requires aimsQuery.js
		panning=false;
		zooming=false;
		selectBox=false;
		queryStartRecord=0;
		queryTool=1;
		toolMode=51;
		modeBlurb="Search";
		if (canQuery) {	
			toolMode=51;
			modeBlurb="Search";
			fieldIndex=0;
			setQueryString="";
			hideLayer("measureBox");
			getStoredQueries();
		} else {
			alert("Cannot query Service\nIdentify, Select, and Query functions are disabled.");
		}
		showGeocode=false;
		showBuffer=false;
		break
		
	case "find":
		//find
		toolMode=9;
		panning=false;
		zooming=false;
		selectBox=false;
		queryStartRecord=0;
		queryTool=1;
		if (canQuery) {	
			LayerFields.length=1;
			LayerFieldType.length=1;
			LayerFieldCount=0;
			
			fieldIndex=0;
			setQueryString="";
			hideLayer("measureBox");
			modeBlurb = "Find";
			findForm();
		} else {
			alert("Cannot query Service\nIdentify, Select, and Query functions are disabled.");
		}
		showGeocode=false;
		showBuffer=false;
		break
	*/
	case "clearsel":
		 clearSelection();
		 break
		 
	// Buffer function
	case "buffer":
		//buffer - requires aimsBuffer.js
		if (useBuffer) {
			if (checkSelected()) {
				toolMode = 25;
				modeBlurb ="Buffer";
				writeBufferForm();	
			} else {
				showBuffer=false;
				alert("No selected features to buffer");
			}
		} else {
			alert("Buffer Mode disabled");
		}
		break
		
	case "options":
		writeOptionForm();
		break
		
	// Print function	
	case "print":
		//edited aimsPrint.js, changed function cal to getPrintMap() instead of printIt()
		 printIt();
		 //getPrintMap();
		 break
		 
	// custom modes
	case "dbidentify":
		panning=false;
		zooming=false;
		selectBox=false;
		// identify mode - requires custom db query - not in basic
		if (canQuery) {
			toolMode = 40;
			if (isIE)	{
				document.all.theTop.style.cursor = "hand";
				theCursor = document.all.theTop.style.cursor;
			}

			modeBlurb = "Identify";
		} else {
			alert("Cannot query Service\nIdentify, Select, and Query functions are disabled.");
		}
		
		showGeocode=false;
		if (useTextFrame) parent.TextFrame.document.location= appDir + "text.htm";
		hideLayer("measureBox");
		break
		
		
	case "extract":
		 extractIt();
		 break
		 
	case "legend":
		if (aimsLegendPresent) {
			if (imsURL!="") {
				if (hasTOC) {
						legendVisible=true;
						getLegend();
					}
			} else {
				alert("A MapService must be loaded");
			}
		} else {
			alert("Legend Library (aimsLegend.js) not loaded.");
		}
		break

	case "layertree":
		if (aimsLegendPresent) {
			if (imsURL!="") {
				if (hasTOC) {
						legendVisible=false;
						parent.TOCFrame.document.location=appDir+"toc.htm";
				}
			} else {
				alert("A MapService must be loaded");
			}
		} else {
			alert("Legend Library (aimsLegend.js) not loaded.");
		}
		break
		
	case "layerlist":
		// put LayerList in separate window
		writeLayerListForm();
		break
		
	default:
		alert("Function not enabled.");
	}
	modeName=modeBlurb;
	if (useModeFrame) {
		writeModeFrame(modeBlurb);
	} else if ((drawFloatingMode) && (modeLayerOn)) {
		writeModeLayers(modeBlurb);
	} else if ((modeRefreshMap) && (drawModeOnMap)) {
		sendMapXML();
	}
}

// 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);
	}
		
	return false;
	
}

// perform appropriate action with mapTool
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==leftButton) {
		getImageXY(e);
		if ((mouseX>=0) && (mouseX<iWidth) && (mouseY>=0) && (mouseY<iHeight)) {
			if ((hasOVMap) && (ovIsVisible) && (mouseX<i2Width+ovBoxSize) && (mouseY<i2Height) && (ovMapIsLayer)) {
				//ovMapClick(mouseX,mouseY);
			} else {
				switch(toolMode) {
				case 1:
						startZoomBox(e);
						return false;
						break
					
				case 2:
						startZoomOutBox(e);
						return false;
						break
				case 3:
						startPan(e);
						return false;
						break

				case 4:
					// call drillIdentify()
					drillIdentify(e);
					//identify(e);
					break
				// custom modes

				case 10:
					//select(e);
						startSelectBox(e);
						return false;
						break
				case 11:
					//select point
					select(e);
					break
				case 12:
					//select line
					clickType=2;
					clickAddPoint();
					if (useTextFrame) {
						if (parent.TextFrame.document.title!="Select Line") {
							parent.TextFrame.document.location= appDir + "selectline.htm";
						}
					}
					break
				case 13:
					//select polygon
					clickType=3;
					clickAddPoint();
					if (useTextFrame) {
						if (parent.TextFrame.document.title!="Select Polygon") {
							parent.TextFrame.document.location= appDir + "selectpoly.htm";
						}
					}
					break
				case 15:
					// hyperlink
					hyperLink(e);
					break
				case 16:
					//select shape
					clickType=2;
					clickAddPoint();
					if (useTextFrame) {
						if (parent.TextFrame.document.title!="Select Line/Shape") {
							parent.TextFrame.document.location= appDir + "select.htm";
						}
					}
					break

				case 20:
					// measure
					clickType=1;
					clickAddPoint();
					break
				case 21:
					// shape
					clickType=4;
					clickAddPoint();
					break
				case 40:
					// db identify - requires custom db query - not in default
					if (aimsDBPresent) {
						matchDBLinkLayer(dbLinkLayer);
						dbIdentify(e);
					}
					break
				default:
					if (toolMode>=1000) {
						customMapTool(e);
					}
				}
			}
		}
	}
}

// update measureBox layer
function updateMeasureBox() {
	if (isNav4) {
		var theForm = document.layers["measureBox"].document.forms[0];
	} else {
		//var theForm = document.measureBox.forms[0];
		var theForm = document.forms[0];
	}
	theForm.theMeasTotal.value = totalMeasure + " " + ScaleBarUnits;
	theForm.theMeasSegment.value = currentMeasure + " " + ScaleBarUnits;
	showLayer("measureBox");

}

function writeOverlayXML() {
	var theString = '<ARCXML VERSION="1.1">\n<REQUEST>\n<GET_IMAGE>\n<PROPERTIES>\n<ENVIRONMENT><SEPARATORS cs=" " td=";"/></ENVIRONMENT>\n<EXTENT minx="' + left + '" miny="' + bottom + '" maxx="' + right + '" maxy="' + top + '" />\n';
	theString += '<IMAGESIZE height="' + iHeight + '" width="' + iWidth + '" />\n';
	// tell the server that the layers are to be invisible
	theString += '<LAYERLIST >\n';
	for (var i=0;i<layerCount;i++) {
		theString += '<LAYERDEF name="' + LayerName[i] + '" visible="false" />\n';
	}
	theString += '</LAYERLIST>\n';
	// map background color
	theString += '<BACKGROUND color="255,255,254" transcolor="255,255,254" />\n';
	var theImage = theServiceName + "_" + hostName.toUpperCase() + (Math.round(Math.random()*100000000)).toString() + "." + theImageType;
	var thePath = theImagePath + theImage;
	var theURL = theImageURLPath + theImage;
	theString += '<OUTPUT name="' + thePath + '" url="' + theURL + '" ';
	theString += 'type="' + theImageType + '" />\n';
	theString += '</PROPERTIES>\n';
	if (clickCount>0) {
		theString += '<LAYER type="ACETATE" name="allTheClicks">\n';
		if (clickCount>1) {
			theString += '<OBJECT units="DATABASE">\n<LINE coords="' + clickPointX[0] + " " + clickPointY[0];
			for (var i=1;i<clickCount;i++) {
				theString += ","  + clickPointX[i] + "," + clickPointY[i]; 
			}
			theString += '" >\n';
			theString += '<SIMPLELINESYMBOL type="SOLID" color="' + clickMarkerColor;
			theString += '" width="3" />\n</LINE>\n</OBJECT>\n'; 
			theString += '<OBJECT units="DATABASE">\n<LINE coords="' + clickPointX[0] + " " + clickPointY[0];
			for (var i=1;i<clickCount;i++) {
				theString += ","  + clickPointX[i] + "," + clickPointY[i]; 
			}
			theString += '" >\n';
			theString += '<SIMPLELINESYMBOL type="SOLID" color="255,255,255" width="1" />\n</LINE>\n</OBJECT>\n'; 
 		}
		for (var i=0;i<clickCount;i++) {
			theString += '<OBJECT units="DATABASE">\n<POINT coords="' + clickPointX[i] + ' ' + clickPointY[i] + '">\n';
			theString += '<SIMPLEMARKERSYMBOL  type="' + clickMarkerType + '"';
			theString += ' color="' + clickMarkerColor + '" size="' + clickMarkerSize + '" />\n</POINT>\n</OBJECT>\n';
			}
		theString += '</LAYER>\n';
	}
	theString += '</GET_IMAGE>\n</REQUEST>\n</ARCXML>';
	return theString;

}
