// aimsXML.js
/*
*  JavaScript template file for ArcIMS HTML Viewer
*		dependent on ArcIMSparam.js, aimsCommon.js, aimsMap.js,
*/

var aimsXMLPresent=true;
 
/*
***************************************************************************************

Functions for sending XML requests and XML reponses

***************************************************************************************
*/

// global variables
// change these in aimsCustom.js to send XML response to custom function.
// use numbers >= 1000
var selectXMLMode = 6;
var identifyXMLMode = 7;
var queryXMLMode = 8;
var findXMLMode = 14;
var hyperlinkXMLMode = 15;

// common dynamic variables
var XMLMode = 1;
var okToSend = true;

var xHalf = xDistance/2;
var yHalf = yDistance/2;

// ending position to start parse scan of XML string
var xmlEndPos = 0;

var theImageType = "PNG";

var drawOVExtentBox=false;

var pastStart=false;
if (hasOVMap != true) pastStart = true;

//variable will run the functions for toolMode 5 ONCE
var toolFive = false;
//in the case of a zoom to Kent County, the automatic park query will not run
var parkQuery = false;
//in case of tool Mode 5, stores name of community for labelling purposes
var communityString = "";

// send in XML request and get XML response - uses helper applet
function sendToServer(URLString,XMLRequest,theType) {
        //alert("SENDTOSERVER");
	if (parent.PostFrame.document.forms[0]!=null) {
		if (okToSend) {
			XMLMode = theType;
			if (XMLMode==1) showRetrieveMap();
			//theForm = parent.AppletFrame.document.forms[0];
			if (debugOn>2) alert("ServiceName: " + URLString + "\nXMLRequest:\n " + XMLRequest + "\ntheType:\n " + theType);
			okToSend = false;
				var theForm = parent.PostFrame.document.forms[0];
				//alert(URLString);
				//alert(XMLRequest);
				theForm.action=URLString + "&Form=True&Encode=True";
				theForm.ArcXMLRequest.value=XMLRequest;
				theForm.HeaderFile.value = headerFilePath;
				theForm.FooterFile.value = footerFilePath;
				theForm.submit();
				//alert("you are here");
				
		} else {
			alert("Response from previous request(s) not yet received. Please wait.");
			//hideRetrieveMap();
			//hideRetrieveData();
		}
	} else {
		alert("Form for posting request not found. Unable to communicate with server.");
			hideRetrieveMap();
			hideRetrieveData();
	}
		
}

// send custom XML request. . . set up custom response handler
function sendCustomToServer(XMLRequest, theFunction, theType) {
	var theForm = parent.PostFrame.document.forms[0];
	theForm.JavaScriptFunction.value = theFunction;
	sendToServer(imsQueryURL,XMLRequest,theType)
}

// send the created xml request to map server
function sendMapXML() {
	// ask for the Main map
	beforeMapRefresh();
	showRetrieveMap();	
	var theText = writeXML();
	if (debugOn==2) alert("Sending:\n\n" + theText);
	sendToServer(imsURL,theText,98);

}

// process the response xml
function processXML(theReplyIn) {
	//alert(top.TOCFrame.document.forms[0].LayerVisible[0].value);
	theReplyIn = replacePlus(theReplyIn);
	var theReply = unescape(theReplyIn);
	
	okToSend = true;
	if (debugOn>2) alert("XMLResponse:\n " + theReply + "\nTheMode: " + XMLMode);
	//if (debugOn>2) alert("TheMode: " + XMLMode);
	var theError = getXMLErrorMessage(theReply);
	//if (theError!="") {
	//	alert(theError);
	//} else {
	switch(XMLMode) {
		case 1:
			//alert ("Received:\n\n" + theReply);
			var theURL = "";
			theURL = getURL(theReply);
			
			//alert(theURL);
			if (theURL != "") {
				getXYs(theReply);
				document.theImage.src = theURL;
				
				afterMapRefresh();
				//window.onerror=resetError;
				if (toolMode==3) {
					moveLayer("theMap",hspc,vspc);
					clipLayer("theMap",0,0,iWidth,iHeight);
					window.setTimeout('showLayer("theMap");',1000);
					if (hasLayer("theMapClicks")) {
						moveLayer("theMapClicks",hspc,vspc);
						clipLayer("theMapClicks",0,0,iWidth,iHeight);
				
					}
				}
				
			}
			else {
				
				if (debugOn>0) {
					alert("Unable to display Map image\nDebug On\n" + theReply);
				} else {
					alert("Unable to display MapService\nServer returned:" + theError);
				}
			}
			if (toolMode==20) {
				updateMeasureBox();
			}
			if (legendVisible) {
                                //alert("Step 5");
				getNewLegend();
			}
			if (!noOverlay) {
				if (aimsClickPresent) {
					if (clickCount>0) {
						theText = writeOverlayXML();
						showRetrieveMap();
						sendToServer(imsURL,theText,901);
					}
				}
			}
			
			if (hasOVMap) {
				if (ovIsVisible) {
				// ask for the overview
					if (!pastStart) {
						
						theText = writeOVXML();
						//pastStart=true;
						sendToServer(imsOVURL,theText,2);
					} else {
						putExtentOnOVMap();
						hideRetrieveMap();
					}
				} else {
					if (!pastStart) {
						theText = writeOVXML();
						sendToServer(imsOVURL,theText,2);
					} else {
						hideRetrieveMap();
					}
				
				}
			} else {
				hideRetrieveMap();
			}
			if (aimsBufferPresent) {
				if (getBufferedData) {
					var buffString = writeGetBufferedData();
					if (buffString!="") {
						sendToServer(imsQueryURL,buffString,11);
					} else {
						alert("Cannot send request");
					}
					getBufferedData=false;
				} 
			}
			break

		case 2:
			// just put up an overview map
			var theURL = "";
			theURL = getURL(theReply);
			if (!pastStart) {
				getOVXYs(theReply);
				pastStart=true;
				
			}
			//alert(theURL);
			if (theURL != "") {
				ovImageVar.src = theURL; 
			}
			else {
			
				if (debugOn>0) {
					alert("Unable to display Reference Map image\nDebug On\n" + theReply);
				} else {
					alert("Unable to display Reference Map MapService\nServer returned: " + theError);
				}
				
			}
			putExtentOnOVMap();
			hideRetrieveMap();
			if (firstTime) setupGeocode();
			break

		case 3:
			//  just get full extent - service info
			//alert("processXML()[3]\n" + theReply);
			if (getLimitExtent) {
				getXYs(theReply);
				fullLeft = left;
				fullRight = right;
				fullTop = top;
				fullBottom = bottom;
				fullOVLeft = left;
				fullOVRight = right;
				fullOVTop = top;
				fullOVBottom = bottom;
				limitLeft = left;
				limitRight = right;
				limitTop = top;
				limitBottom = bottom;
			} else {
				fullLeft = limitLeft;
				fullRight = limitRight;
				fullTop = limitTop;
				fullBottom = limitBottom;
				fullOVLeft = limitLeft;
				fullOVRight = limitRight;
				fullOVTop = limitTop;
				fullOVBottom = limitBottom;				
			}
			fullWidth = Math.abs(fullRight - fullLeft);
			fullHeight = Math.abs(fullTop - fullBottom);
			fullOVWidth = Math.abs(fullOVRight - fullOVLeft);
			fullOVHeight = Math.abs(fullOVTop - fullOVBottom);
			theString = '<?xml version="1.0" encoding="UTF-8"?><ARCXML VERSION="1.1">\n<REQUEST>\n<GET_SERVICE_INFO />\n';
			theString += '</REQUEST>\n</ARCXML>';
			// get list of geocoding layers
			if((aimsGeocodePresent) && ((useGeocode) || (useReverseGeocode))) {
				theString = '<?xml version="1.0" encoding="UTF-8"?><ARCXML VERSION="1.1">\n<REQUEST>\n<GET_SERVICE_INFO  renderer="false" />\n';
				theString += '</REQUEST>\n</ARCXML>';
                                //alert("Hi There");
                                //alert(theString);
				sendToServer(imsGeocodeURL,theString,25);
			} else {
				theString = '<?xml version="1.0" encoding="UTF-8"?><ARCXML VERSION="1.1">\n<REQUEST>\n<GET_SERVICE_INFO  renderer="false" extensions="true" />\n';
				theString += '</REQUEST>\n</ARCXML>';
				sendToServer(imsURL,theString,4);
				useGeocode=false;
				useReverseGeocode=false;
			}
                        getGeocodeLayers();
			
			break

		case 4:
			// get service info - extent, layers
			//alert("processXML()[4]\n" + theReply);
			processStartExtent(theReply);
			
			break

		case 5:
			// get a list of ImageServices
			//alert("processXML()[5]\n" + theReply);
			processCatalog(theReply);
			
			break

		case 6:
			// get select response
			displayAttributeData(theReply);
			
			break

		case 7:
			// get identify response
			generateResultsHTML(theReply);
			autoIdentifyProgram();			

			break

		case 8:
			// get query response
			//alert("processXML()[8]\nQuery XML Response:\n" + theReply);
			if (loadThisService == "Public_Parcel_Find" && (searchType == "ppn" || searchType == "name")) {
				parcelReportProcessor(theReply);
			} else {
				displayAttributeData(theReply);
			}
			break

		case 9:
			// get geocode response
			processGeocode(theReply);
			
			break
		/*
		case 10:
			// get reverse geocode response
			processReverseGeocode(theReply);
			
			break
		*/
		case 11:
			// get buffer response
			//getBufferAttributeData(theReply);
			displayAttributeData(theReply);
			break
		/*
		case 12:
			// get proximity response
			processProx(theReply);
			
			break

		case 13:
			// get route response
			processRoute(theReply);
			
			break
		*/
		case 14:
			// get find response
			//alert(theReply);
			displayAttributeData(theReply);
			
			break	

		case 15:
			// get hyperlink response
			parseHyperLink(theReply);
			
			break

		case 16:
			// get parcel report response
			//alert(theReply);
			parcelReportProcessor(theReply);
			
			break

		case 17:
			//autoretrieval of parcel number: public_parcel_find
			hideRetrieveData();
			var startPos = theReply.indexOf('PPN="') + 5;
			var endPos = theReply.indexOf('"',startPos);
			var thePPN = theReply.slice(startPos,endPos);
			accessKentTransfer(thePPN);
			break

		case 18:
			//automated identify sequence: Public_Voting
			autoVotingProgram(theReply);
			break;
		
		case 20:
			// Get Layer Information for Switching between Services on the Fly 
                        showRetrieveMap();
                        //alert("Mode 20");
			getLayers(theReply);
	 		parent.TOCFrame.document.location = appDir + "toc.htm"; 	
                        hideRetrieveMap();
			if((aimsGeocodePresent) && ((useGeocode) || (useReverseGeocode))) {
				theString = '<?xml version="1.0" encoding="UTF-8"?><ARCXML VERSION="1.1">\n<REQUEST>\n<GET_SERVICE_INFO  renderer="false" />\n';
				theString += '</REQUEST>\n</ARCXML>';
				sendToServer(imsGeocodeURL,theString,21);
			} else {
				theString = '<?xml version="1.0" encoding="UTF-8"?><ARCXML VERSION="1.1">\n<REQUEST>\n<GET_SERVICE_INFO  renderer="false" extensions="true" />\n';
				theString += '</REQUEST>\n</ARCXML>';
				sendToServer(imsURL,theString,4);
				useGeocode=false;
				useReverseGeocode=false;
                        	getGeocodeLayers();
			}
			//  CVG - Hardcoded a check for PTAS layer since it's the only one with stored Queries
                        switch (parent.MapFrame.RegisServiceName) {
				case 'PTAS':
					useStoredQuery = true;
					break;
				default:
					useStoredQuery = false;
					break;
			}
			if (parent.ToolFrame!=null) {
				//parent.ToolFrame.document.location= appDir + "toolbar.htm";
			} else if (hasToolBarOnLayer) {
				var content = getLayerListContent();
				if (isNav) {
					replaceLayerContent("theToolBar",content);
				} else {
					content = swapStuff(content,"\\'",sQuote);
					document.all.theToolBar.innerHTML = content;
				}
			}
			
 			sendMapXML();
			break

		case 21:
			// get geocoding layers without calling for processMapExtent
                        //alert("Case 21")
			parseGeocodeLayers(theReply);
                        sendMapXML();
			break

		case 25:
			// get geocoding layers
			parseGeocodeLayers(theReply);
			// get layers for display
			var theString = '<?xml version="1.0" encoding="UTF-8"?><ARCXML VERSION="1.1">\n<REQUEST>\n<GET_SERVICE_INFO  renderer="false" extensions="true" fields="true"/>\n';
			theString += '</REQUEST>\n</ARCXML>';
			sendToServer(imsURL,theString,4);
			
			break

		case 26:
			// get geocoding layers
			if (parseGeocodeParams(theReply)) {
				if (firstTime) {
					
					setActiveGeocode(GCLayers[0]);
					oneTime();
				}
			} else {
				if (debugOn>0) {
					alert("Unable to set parameters\nDebug On\n" + theReply);
					if (parent.TextFrame!=null) parent.TextFrame.document.location= appDir + "blank.htm";
				} else {
					alert("Unable to set parameters");
					if (parent.TextFrame!=null) parent.TextFrame.document.location= appDir + "blank.htm";
				}
			}
			break

		case 27:
			// get geocoding results
			parseGeocodeResults(theReply);
			
			break
		case 40:
			// get list of sample field values
			parseFieldSamples(theReply);
			writeQueryForm();
			
			break
		case 55:
			// get layer storedqueries
			//alert("55\n" + theReply);
			parseStoredQueries(theReply);
			
			break

		case 70:
			// get layer field for submission to external db
			parseIDFieldData(theReply);	
			
			break

		case 98:
			// just put up a map with legend
			mapLoaded = true;	
			getLBRT(theReply);
			var theURL = "";
			theURL = getURL(theReply);
			if (theURL != "") {
				document.theImage.src = theURL;
			}
			//else {
			//	alert(theReply + "\nUnable to display Map image");
			//}
			if (toolMode == 7 && areaQueryStage == 2) {
				bufGetAttribute = false;
				areaQueryStage = 0;
			}
			
			if (legendVisible) {
				showLegend();
				drawLegendOnly=false;
			}
			hideRetrieveMap();
			hideRetrieveData();
                        //alert("step 9");
			if (!noOverlay) {
				if (aimsClickPresent) {
					if (clickCount>0) {
						theText = writeOverlayXML();
						showRetrieveMap();
						sendToServer(imsURL,theText,901);
					}
				}
			}
			if (hasOVMap) {
				if (ovIsVisible) {
				// ask for the overview
					if (!pastStart) {
						
						theText = writeOVXML();
						//pastStart=true;
						sendToServer(imsOVURL,theText,2);
					} else {
						putExtentOnOVMap();
						hideRetrieveMap();
					}
				} else {
					if (!pastStart) {
						theText = writeOVXML();
						sendToServer(imsOVURL,theText,2);
					} else {
						hideRetrieveMap();
					}
				}
			} else {
				hideRetrieveMap();
			}
			if (toolMode == 4 && waitingForRefresh == true) {
				waitingForRefresh = false;
				var Win1;
				if (useExternalWindow) {
					for (var f=0;f<identifyMapService.length;f++) {
						if (identifyMapService[f] == loadThisService) {
							if (identifyLayer[f].length == 1) {
								selectedIdentifyLayers = identifyLayer[f];
								selectedIdentifyReplies.length = 1;
							} else {
								Win1 = window.open(appDir+"identify.htm","QueryWindow","left=120,top=400,width=450,height=200,scrollbars=yes,resizable=yes");
							}
						}
					}
				} else {
					Win1 = parent.TextFrame;
					Win1.document.location = appDir + "identify.htm";
				}
				if (isIE)	{
					document.body.style.cursor="hand";
					//document.all.theTop.style.cursor = "crosshair";
					theCursor = document.all.theTop.style.cursor;
				}	
			}
			if ((toolMode == 7) && (areaQueryStage == 1)) {
				if (GCpointCount > 0) {
					autoIdentify(geocodeX, geocodeY);
					if (useExternalWindow) {
						var Win1 = window.open("","QueryWindow","width=200,height=200,scrollbars=yes,resizable=yes");
						Win1.close();
					}
				}
			}
			if ((toolMode == 5) && (toolFive)){
				toolFive = false;
				var theIndex = -1;
				var foundParks = false;
				for (var i=0;i<LayerName.length;i++) {
					if (loadThisService == "Public_PlannedLanduse") {
						if (LayerName[i] == "Planned Landuse Areas") theIndex = i;
					} else if (loadThisService == "Public_Zoning") {
						if (LayerName[i] == "Zoning Areas") theIndex = i;
					} else if (loadThisService == "Public_Parks") {
						if (LayerName[i] == "Parks") {
							theIndex = i;
							foundParks = true;
						}
					}
				}
				if (theIndex > -1) {
					ActiveLayer = LayerID[theIndex];
					ActiveLayerType = LayerType[theIndex];
					ActiveLayerIndex = theIndex;
					setActiveLayer(theIndex);
					if (topLayerActiveTab == 0) parent.TOCFrame.document.location = "http://" + hostName + "/website/public/toc.htm";
				}
				if ((loadThisService == "Public_Parks") && (foundParks) && (parkQuery)) {
					parkQuery = false;
					var queryString = "PLANNING.PLANNING_PARK.GOVT_UNIT_NAME = ";
					queryString += '"'+communityParkValue+'"'
					publicSelCleared == false;
					zoomToSingleSelect = false;
					sendQueryString(queryString);
				} 
			} 
			break

		case 99:
			// just put up a map
			var theURL = "";
			legendVisible=legendTemp;
			theURL = getURL(theReply);
			if (theURL != "") {
				document.theImage.src = theURL;
				if (!noOverlay) {
					if (clickCount>0) {
						theText = writeOverlayXML();
						showRetrieveMap();
						sendToServer(imsURL,theText,901);
					} else {
						if (hasLayer("theMapClicks")) {
							document.theClickImage.src = blankImage;
						}
					}
				}
			}
			else {
				alert(theReply + "\nUnable to display Map image");

			}
			hideRetrieveMap();
			
			break

		case 100:
			//called from redlining tool: the map has been generated and now it will be passed to a cgi script.
			hideRetrieveMap();	
			getName(theReply);
			break


		case 101:
			// print - get Map image
			printMapURL = getURL(theReply);
			printLegURL = getLegendURL(theReply);

			if (hasOVMap) {
				getPrintOV();
			} else {
				//writePrintPage();
				getPrintLegend();
			}
			
			break



		case 102:
			// print - get OV image
			printOVURL = getURL(theReply);
			legendImage = printLegURL
			legendVisible = true;
			getPrintLegend();
			
			break

		case 103:
			// print - get Legend image
			
			hideRetrieveMap();
			writePrintPage();
			break
		case 105:
			// CVG - print - get Legend Image Only 
                        //alert("step 7");
		        printLegURL = getLegendURL(theReply);
			if (printLegURL == "") printLegURL = "images/nolegend.gif";	
			writePrintPage();
		        break	

		case 900:
			// just make a map
			var theURL = "";
			theURL = getURL(theReply);
			if (theURL != "") {
				getXYs(theReply);

				document.theImage.src = theURL;
			}
			
			break

		case 901:
			// just make a map
			var theURL = "";
			theURL = getURL(theReply);
			if (theURL != "") {
				if (!noOverlay) 
					document.theClickImage.src = theURL;
				if (toolMode==3) {
					if (hasLayer("theMapClicks")) {
						clipLayer("theMapClicks",0,0,iWidth,iHeight);
						moveLayer("theMapClicks",hspc,vspc);
						window.setTimeout('showLayer("theMapClicks");',1000);
				
					}
				}
				
			} else {
				alert("Unable to get image for click positions.");
			}
			hideRetrieveMap();
			
			break

		case 902:
			// just put up an overview map
			var theURL = "";
			theURL = getURL(theReply);
			//alert(theURL);
			if (theURL != "") {
				document.ovImage2.src = theURL; 
			}
			var tempLeft = fullLeft;
			var tempRight = fullRight;
			var tempTop = fullTop;
			var tempBottom = fullBottom;
			getOVXYs(theReply);
			fullLeft = tempLeft;

			fullRight = tempRight;
			fullTop = tempTop;
			fullBottom = tempBottom;
			
			
			break

		case 999:
			// get a blank map to get modified limit extents according image proportions
			var tempLeft = left;
			var tempRight = right;
			var tempTop = top;
			var tempBottom = bottom;
			getXYs(theReply)
			imageLimitLeft=left;
			imageLimitRight=right;
			imageLimitTop=top
			imageLimitBottom=bottom;
			left = tempLeft;
			right = tempRight;
			top = tempTop;
			bottom = tempBottom;
			sendMapXML();
			
			break

		default:
			// send any responses to custom requests off to the custom handler
				// XMLMode >= 1000 are reserved for custom requests/responses
			if (XMLMode >= 1000) {
				useCustomFunction(theReply);	
			} else {
				alert(theReply + "\nUnable to execute response.");
			}


			
		}
	//}
		
	
}

// write out a blank map. . . to get image extents from limit extents
function writeBlankMapXML() {
	var theString = '<?xml version="1.0" encoding="UTF-8"?><ARCXML VERSION="1.1">\n<REQUEST>\n<GET_IMAGE>\n<PROPERTIES>\n<ENVELOPE minx="' + limitLeft + '" miny="' + limitBottom + '" maxx="' + limitRight + '" maxy="' + limitTop + '" />\n';
	theString += '<IMAGESIZE height="' + iHeight + '" width="' + iWidth + '" />\n';
	var visString = "";
	// tell the server which layers are to be visible
	if (aimsLayersPresent) {
		theString += '<LAYERLIST >\n';
		for (var i=0;i<layerCount;i++) {
			theString += '<LAYERDEF name="' + LayerName[i] + '" visible="false" />\n';	
		}
		theString += '</LAYERLIST>\n';
	}
	theString += '</PROPERTIES>\n';
	theString += '</GET_IMAGE>\n</REQUEST>\n</ARCXML>';
	//alert(theString);
	sendToServer(imsURL,theString,999);

}
//updates layer visibility before sending XML request
//function localUpdateLayers() {
	
	//var theForm = parent.TOCFrame.document.forms[0];
	//var j = 0;
	//if (theForm.LayerVisible.length>1){
	//	for(var i=0;i<theForm.LayerVisible.length;i++){
	//		j=theForm.LayerVisible[i].value;
	//		if (theForm.LayerVisible[i].checked){

	//			t.LayerVisible[j] = 1;
	//		}
	//		else {
	//			t.LayerVisible[j] = 0;
	//		}
	//	}
	//} else {
	//	if(theForm.LayerVisible.checked){
	//		j = theForm.LayerVisible.value;
	//		t.LayerVisible[j] = 1;
	//	}


	//	else {
	//		t.LayerVisible[j] = 0;
	//	}
	//}
//}	

// prepare the request in xml format for Main Map
function writeXML() {
	if (useCustomCoords) {
		 var theString = '<?xml version="1.0" encoding="UTF-8"?><ARCXML VERSION="1.1">\n<REQUEST>\n<GET_IMAGE>\n<PROPERTIES>\n<ENVELOPE minx="' + customLeft + '" miny="' + customBottom + '" maxx="' + customRight + '" maxy="' + customTop + '" />\n';
	}
	else var theString = '<?xml version="1.0" encoding="UTF-8"?><ARCXML VERSION="1.1">\n<REQUEST>\n<GET_IMAGE>\n<PROPERTIES>\n<ENVELOPE minx="' + left + '" miny="' + bottom + '" maxx="' + right + '" maxy="' + top + '" />\n'; 
	theString += '<IMAGESIZE height="' + iHeight + '" width="' + iWidth + '" />\n';
	var visString = "";
	// store the index positions of orthos in order to reference it in the XML statement
	var orthoIndex = -1;
	for (var i=0;i<layerCount;i++) {
		if (LayerID[i] == "ortho") orthoIndex = i;
	}
	if (aimsLayersPresent) {
		// tell the server which layers are to be visible
		if (toggleVisible) {
			theString += '<LAYERLIST >\n';
			for (var i=0;i<layerCount;i++) {
				if (LayerVisible[i]==1) {
					theString += '<LAYERDEF id="' + LayerID[i] + '" visible="true">\n';
					if (showOneRoute){
						if (LayerID[i] == "routes") {
							theString += addBusXML();
						}
						//else theString += '/>\n';

					}
					if ((hasOrthos) && (LayerVisible[orthoIndex]==1)) {
						if (LayerID[i] == "parcels") theString += addSymbolXML('parcels');
						if (LayerID[i] == "parcelanno") theString += addSymbolXML('parcelanno');	
					}
					if (aimsClassRenderPresent) {
						theString += addSpecialRenderToMap(i);
					} else {
						theString += "</LAYERDEF>\n";
					}	
				}


				else {
					theString += '<LAYERDEF id="' + LayerID[i] + '" visible="false" />\n';
				}
				
			}
			theString += '</LAYERLIST>\n';
		}
	}
	
	// map background color
	if (mapBackColor!="") {
		theString += '<BACKGROUND color="' + mapBackColor + '" />\n\n';
	}
	if (aimsLegendPresent) {
		// create a legend image
		if (legendVisible) theString += addLegendToMap();
	}
	
	theString += '</PROPERTIES>\n';
	
	// buffer
	if (aimsBufferPresent) {
		if (showBuffer) theString += addBufferToMap();
	}
	
	// select
	if (aimsSelectPresent) {
		//in the case of Zoom to Community tool, don't want the gvt unit highlighted
		if ((toolMode == 5) && ((loadThisService == "Public_PlannedLanduse") || (loadThisService == "Public_Zoning"))) {
			setQueryString = "";
			selectCount=0;
		}
		else theString += addSelectToMap();
	}		

	// any custom stuff to fit here
	if (aimsCustomPresent) theString += addCustomToMap1();
	
	// geocoding or point with label
	if (showGeocode) {
		var geoString = "";
		if (GCpointCount > 1) {
			for (var g=0;g<GCpointCount;g++) {
				// just draw the point . . . also used to display any point with a label on map
				geoString += '<LAYER type="ACETATE" name="GeoCode'+g+'">\n';
				geoString += '<OBJECT units="DATABASE">\n<POINT coords="' + GCpointX[g] + ' ' + GCpointY[g] + '">\n';
				geoString += '<SIMPLEMARKERSYMBOL  type="Star"  color="' + geocodePointColor + '" width="' + geocodePointSize +'" overlap="false"/>\n</POINT></OBJECT>\n';
				geoString += '<OBJECT units="DATABASE">\n<TEXT coords="' + GCpointX[g] + ' ' + GCpointY[g] + '" label="' + (g+1) + '">\n';
				geoString += '<TEXTMARKERSYMBOL fontcolor="255,0,0" fontsize="12" glowing="255,255,0" overlap="false"/></TEXT></OBJECT>\n';
				geoString += '</LAYER>\n';	
			}
		} else {
			//alert(geocodeLabel);
			// just draw the point . . . also used to display any point with a label on map
			geoString += '<LAYER type="ACETATE" name="GeoCode1">\n';
			geoString += '<OBJECT units="DATABASE">\n<POINT coords="' + geocodeX + ' ' + geocodeY + '">\n';
			geoString += '<SIMPLEMARKERSYMBOL  type="Circle"  color="' + geocodePointColor + '" width="' + geocodePointSize +'" />\n</POINT></OBJECT>\n';
			if (geocodeLabel!="") {
				geoString += '<OBJECT units="DATABASE">\n<TEXT coords="' + geocodeX + ' ' + geocodeY + '" label="' + geocodeLabel + '">\n';
				geoString += '<TEXTMARKERSYMBOL fontcolor="' + geocodePointColor + '" fontsize="12" shadow="64,64,64" glowing="255,255,0" halignment="RIGHT" valignment="TOP" overlap="false" /></TEXT></OBJECT>\n';
			}
			geoString += '</LAYER>\n';
		}
		//alert(geoString);
		theString += geoString;
	}
	
	
	//calls a function in aimsRedline to add redline acetate layers to the map
	if (addRedlineReq) {
	
		theString += redlineXML();
	}
//	if ((aimsClickPresent) && (noOverlay)) {
		// clickpoints 
//		if (clickCount>0) {
			// draw click points and lines between them on map
//			var clickColor = selectColor;
//			if (clickType==1) clickColor = clickMarkerColor;
//			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 + '" width="' + clickMarkerSize + '" />\n</POINT>\n</OBJECT>\n';
//			}
//			theString += '</LAYER>\n';
//		}
//	}
	
	
	// any custom stuff to fit here
	if (aimsCustomPresent) theString += addCustomToMap2();

	if (drawCopyright) {
		// draw text on the map - 3 parts
		// first write 'copyright'
		//var theNewString = "";
		theString += '<LAYER type="ACETATE" name="theCopyText">\n';
		theString += '<OBJECT units="PIXEL">\n<TEXT coords="' + CopyTextCoords + '" label="copyright">\n';
		theString += '<TEXTMARKERSYMBOL fontstyle="' + CopyrightStyle + '" fontsize="8" ';
		theString += 'font="' + CopyrightFont + '" fontcolor="' + CopyrightColor + '" antialiasing="True" ';
		//if (CopyrightBackground.toUpperCase()=="TRUE") theString += 'background="' + CopyrightBackground + '" backcolor="' + CopyrightBGColor + '" ';
		//if (CopyrightBackground.toUpperCase()=="TRUE") theString += 'blockout="' + CopyrightBGColor + '" ';
		//theString += 'shadow="32,32,32" overlap="false" ';
		if (CopyrightGlow.toUpperCase()=="TRUE") theString += ' glowing="' + CopyrightGlowColor + '" ';
		theString += '/>\n</TEXT>\n</OBJECT>\n';
		theString += '</LAYER>\n';
		//second add copyright symbol
		theString += '<LAYER type="ACETATE" name="theCopySym">\n';
		theString += '<OBJECT units="PIXEL">\n';
		theString += '<POINT coords="'+CopySymCoords+'">\n';
		theString += '<TRUETYPEMARKERSYMBOL character="211" fontcolor="0,0,0" font="Symbol" fontstyle="regular" fontsize="12" overlap="true" glowing="' + CopyrightGlowColor + '"/>\n';
		theString += '</POINT>\n';
		theString += '</OBJECT>\n';
		theString += '</LAYER>\n';
		//third draw the copyright text
		theString += '<LAYER type="ACETATE" name="theCopyright">\n';		
		theString += '<OBJECT units="PIXEL">\n<TEXT coords="' + CopyrightCoords + '" label="' + CopyrightText + '">\n';
		theString += '<TEXTMARKERSYMBOL fontstyle="' + CopyrightStyle + '" fontsize="' + CopyrightSize + '"';
		theString += ' font="' + CopyrightFont + '" fontcolor="' + CopyrightColor + '" antialiasing="True"';
		//if (CopyrightBackground.toUpperCase()=="TRUE") theString += 'background="' + CopyrightBackground + '" backcolor="' + CopyrightBGColor + '" ';
		//if (CopyrightBackground.toUpperCase()=="TRUE") theString += 'blockout="' + CopyrightBGColor + '" ';
		//theString += 'shadow="32,32,32" overlap="false" ';
		if (CopyrightGlow.toUpperCase()=="TRUE") theString += ' glowing="' + CopyrightGlowColor + '" ';
		theString += '/>\n</TEXT>\n</OBJECT>\n';
		theString += '</LAYER>\n';
		//alert(theNewString);
	}
	if (drawNorthArrow) {
		// draw a north arrow
		theString += '<LAYER type="ACETATE" name="theNorthArrow">\n';
		theString += '<OBJECT units="PIXEL">\n<NORTHARROW type="' + NorthArrowType + '" size="' + NorthArrowSize + '" coords="' + NorthArrowCoords + '" shadow="32,32,32" ';
		theString += 'angle="' + NorthArrowAngle + '" antialiasing="True" overlap="False" />\n</OBJECT>\n';
		theString += '</LAYER>\n';
	}
	if (drawScaleBar) {
		// draw a scale bar
		//ScaleBarPrecision = numDecimals;
		var theScaleString = "";
		theScaleString += '<LAYER type="ACETATE" name="theScaleBar">\n';

		theScaleString += '<OBJECT units="PIXEL">\n';
		theScaleString += '<SCALEBAR coords="' + parseInt(iWidth * 0.60) + ' 2" outline="' + ScaleBarBackColor + '" ';
		theScaleString += 'font="' + ScaleBarFont + '" fontcolor="' + ScaleBarFontColor + '" style="' + ScaleBarStyle + '" barcolor="' + ScaleBarColor + '" ';
		theScaleString += 'mapunits="' + MapUnits + '" ';
		theScaleString += 'scaleunits="' + ScaleBarUnits + '" antialiasing="True" ';
		var sDistance = getScaleBarDistance();
		if (sDistance<1) theScaleString += 'precision="' + ScaleBarPrecision + '" ';
		//theString += 'screenlength="' + parseInt(iWidth * 0.25) + '" ';
		theScaleString += 'distance="' + sDistance + '" ';
		theScaleString += 'fontsize="' + ScaleBarSize + '" barwidth="' + ScaleBarWidth + '" overlap="False"  />\n</OBJECT>\n';
		theScaleString += '</LAYER>\n';
		//alert(theScaleString);
		theString += theScaleString;	
		
	}
	
	// any custom stuff to fit here
	if (aimsCustomPresent) theString += addCustomToMap3();

	if (drawModeOnMap) {
		// draw the current mode on the map
		theString += '<LAYER type="ACETATE" name="theMode">\n';
		theString += '<OBJECT units="PIXEL">\n<TEXT coords="5 ' + (iHeight-10) + '" label="' + modeBlurb + '">\n';
		theString += '<TEXTMARKERSYMBOL fontstyle="BOLD" fontsize="12" font="ARIAL" fontcolor="' + modeMapColor + '" ';
		theString += 'threed="TRUE" glowing="' + modeMapGlow + '" />\n</TEXT>\n</OBJECT>';
	
	}
	
	// any custom stuff to be drawn on top of everything
	if (aimsCustomPresent) theString += addCustomToMap4();

	theString += '</GET_IMAGE>\n</REQUEST>\n</ARCXML>';
	useCustomCoords = false;
	//alert(theString);
	return theString;
}

// prepare the request in xml format for Main Map
function writeLegendXML() {
	var theString = '<?xml version="1.0" encoding="UTF-8"?><ARCXML VERSION="1.1">\n<REQUEST>\n<GET_IMAGE>\n<PROPERTIES>\n<ENVELOPE minx="' + left + '" miny="' + bottom + '" maxx="' + right + '" maxy="' + top + '" />\n';
	theString += '<IMAGESIZE height="' + iHeight + '" width="' + iWidth + '" />\n';
	var visString = "";
	if (aimsLayersPresent) {
		// tell the server which layers are to be visible
		if (toggleVisible) {
			theString += '<LAYERLIST >\n';
                        //alert("Step 3");

			for (var i=0;i<layerCount;i++) {
				if (LayerVisible[i]==1) {
                                	var isVisible = true;
                                	for (var xx=0;xx<hiddenLayers.length;xx++) {
                                                //alert("Hidden String: " + hiddenLayers[xx] + " Layer Name: " + LayerName[i]); 
                                		if (hiddenLayers[xx] == LayerName[i]) {
							isVisible = false;
							break;
						}
                                	}
                                        if (isVisible) {
						theString += '<LAYERDEF id="' + LayerID[i] + '" visible="true" ';
						if (aimsClassRenderPresent) {
							theString += addSpecialRenderToMap(i);
						} else {
							theString += '/>\n';
						}
                                        }
					else {
						theString += '<LAYERDEF id="' + LayerID[i] + '" visible="false" />\n';
					}
				}
				else {
					theString += '<LAYERDEF id="' + LayerID[i] + '" visible="false" />\n';
				}
				
			}
			theString += '</LAYERLIST>\n';
		}
	}
	
	// map background color
	if (mapBackColor!="") {
		theString += '<BACKGROUND color="' + mapBackColor + '" />\n\n';

	}
	if (aimsLegendPresent) {
		// create a legend image
		if (legendVisible) theString += addLegendToMap();
	}
	
	theString += '</PROPERTIES>\n';
	
	// buffer
	if (aimsBufferPresent) {
		if (showBuffer) theString += addBufferToMap();
	}
	
	// select
	if (aimsSelectPresent) {
		//alert(toolMode);
		if ((toolMode == 5) && ((loadThisService == "Public_PlannedLanduse") || (loadThisService == "Public_Zoning"))) {
			alert("nothing will happen");
			//nothing in this case
		}
		else theString += addSelectToMap();
	}	
	
	// any custom stuff to fit here

	if (aimsCustomPresent) theString += addCustomToMap1();
	
	// geocoding or point with label



	if (showGeocode) {
		// draw the point . . . also used to display any point with a label on map
		theString += '<LAYER type="ACETATE" name="GeoCode1">\n';
		theString += '<OBJECT units="DATABASE">\n<POINT coords="' + geocodeX + ' ' + geocodeY + '">\n';
		theString += '<SIMPLEMARKERSYMBOL  type="Circle"  color="' + geocodePointColor + '" width="' + geocodePointSize +'" />\n</POINT></OBJECT>\n';
		if (geocodeLabel!="") {
			theString += '<OBJECT units="DATABASE">\n<TEXT coords="' + geocodeX + ' ' + geocodeY + '" label="' + geocodeLabel + '">\n';
			theString += '<TEXTMARKERSYMBOL fontcolor="' + geocodePointColor + '" fontsize="12" shadow="64,64,64" glowing="255,255,0" halignment="RIGHT" valignment="TOP" /></TEXT></OBJECT>\n';
		}
		theString += '</LAYER>\n';
		
	}
	
	if ((aimsClickPresent) && (noOverlay)) {
		// clickpoints 
		if (clickCount>0) {
			// draw click points and lines between them on map
			var clickColor = selectColor;
			if (clickType==1) clickColor = clickMarkerColor;
			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 + '" width="' + clickMarkerSize + '" />\n</POINT>\n</OBJECT>\n';
			}

			theString += '</LAYER>\n';

		}
	}

	
	
	// any custom stuff to fit here
	if (aimsCustomPresent) theString += addCustomToMap2();

	if (drawCopyright) {
		// draw text on the map
		theString += '<LAYER type="ACETATE" name="theCopyright">\n';		
		theString += '<OBJECT units="PIXEL">\n<TEXT coords="' + CopyrightCoords + '" label="' + CopyrightText + '">\n';
		theString += '<TEXTMARKERSYMBOL fontstyle="' + CopyrightStyle + '" fontsize="' + CopyrightSize + '" ';
		theString += 'font="' + CopyrightFont + '" fontcolor="' + CopyrightColor + '" antialiasing="True" ';
		//if (CopyrightBackground.toUpperCase()=="TRUE") theString += 'background="' + CopyrightBackground + '" backcolor="' + CopyrightBGColor + '" ';
		if (CopyrightBackground.toUpperCase()=="TRUE") theString += 'blockout="' + CopyrightBGColor + '" ';
		theString += 'shadow="32,32,32" overlap="false" ';
		if (CopyrightGlow.toUpperCase()=="TRUE") theString += ' glowing="' + CopyrightGlowColor + '" ';
		theString += '/>\n</TEXT>\n</OBJECT>\n';
		theString += '</LAYER>\n';
	}
	if (drawNorthArrow) {
		// draw a north arrow
		theString += '<LAYER type="ACETATE" name="theNorthArrow">\n';
		theString += '<OBJECT units="PIXEL">\n<NORTHARROW type="' + NorthArrowType + '" size="' + NorthArrowSize + '" coords="' + NorthArrowCoords + '" shadow="32,32,32" ';
		theString += 'angle="' + NorthArrowAngle + '" antialiasing="True" overlap="False" />\n</OBJECT>\n';

		theString += '</LAYER>\n';

	}
	if (drawScaleBar) {
		// draw a scale bar
		//ScaleBarPrecision = numDecimals;
		theString += '<LAYER type="ACETATE" name="theScaleBar">\n';
		theString += '<OBJECT units="PIXEL">\n';
		theString += '<SCALEBAR coords="' + parseInt(iWidth * 0.60) + ' 2" outline="' + ScaleBarBackColor + '" ';
		theString += 'font="' + ScaleBarFont + '" fontcolor="' + ScaleBarFontColor + '" style="' + ScaleBarStyle + '" barcolor="' + ScaleBarColor + '" ';
		theString += 'mapunits="' + MapUnits + '" ';
		theString += 'scaleunits="' + ScaleBarUnits + '" antialiasing="True" ';
		var sDistance = getScaleBarDistance();
		if (sDistance<1) theString += 'precision="' + ScaleBarPrecision + '" ';
		//theString += 'screenlength="' + parseInt(iWidth * 0.25) + '" ';
		theString += 'distance="' + sDistance + '" ';
		theString += 'fontsize="' + ScaleBarSize + '" barwidth="' + ScaleBarWidth + '" overlap="False"  />\n</OBJECT>\n';
		theString += '</LAYER>\n';	
		
	}
	
	// any custom stuff to fit here
	if (aimsCustomPresent) theString += addCustomToMap3();



	if (drawModeOnMap) {
		// draw the current mode on the map
		theString += '<LAYER type="ACETATE" name="theMode">\n';
		theString += '<OBJECT units="PIXEL">\n<TEXT coords="5 ' + (iHeight-10) + '" label="' + modeBlurb + '">\n';
		theString += '<TEXTMARKERSYMBOL fontstyle="BOLD" fontsize="12" font="ARIAL" fontcolor="' + modeMapColor + '" ';
		theString += 'threed="TRUE" glowing="' + modeMapGlow + '" />\n</TEXT>\n</OBJECT>';
	
	}
	
	// any custom stuff to be drawn on top of everything
	if (aimsCustomPresent) theString += addCustomToMap4();

	theString += '</GET_IMAGE>\n</REQUEST>\n</ARCXML>';
	//alert(theString);
        //alert("Leaving writeLegendXML");

	return theString;
}



// prepare the request in xml format for overview map
function writeOVXML() {
	//default coordinates set in aimsMap.js not valid for overview.
	//below are the Initial extent values from the overview.axl file.
	fullOVLeft = 12676983.9333736;
	fullOVBottom = 457604.543329122;
	fullOVRight = 12933171.47278;
	fullOVTop = 666137.132959656;



	var extentRatio = xDistance/fullWidth;
	var xDist = right - left;
	var yDist = top - bottom;
	var midX = left + xDist;
	var midY = bottom + yDist;
	//var midX = left + xHalf;
	//var midY = bottom + yHalf;
	var theString = '<?xml version="1.0" encoding="UTF-8"?><ARCXML VERSION="1.1">\n<REQUEST>\n<GET_IMAGE><PROPERTIES>\n<ENVELOPE minx="' + fullOVLeft + '" miny="' + fullOVBottom + '" maxx="' + fullOVRight + '" maxy="' + fullOVTop + '" />\n';
	theString += '<IMAGESIZE height="' + i2Height + '" width="' + i2Width + '" />\n';
	if ((toggleOVVisible) && (imsURL==imsOVURL)) {
		theString += '<LAYERLIST >\n';
		for (var i=0;i<layerCount;i++) {
			if (LayerVisible[i]==1) {

				visString = "true";
			}
			else {
				visString = "false";
			}
			theString += '<LAYERDEF name="' + LayerName[i] + '" visible="' + visString + '" />\n';
			
		}
		theString += '</LAYERLIST>\n';
	}
	if (mapBackColor!="") {
		theString += '<BACKGROUND color="' + mapBackColor + '" />\n';
	}
	
	theString += '</PROPERTIES>\n';
	if (drawOVExtentBox) {
		theString += '<LAYER type="ACETATE" name="ACETATE">\n';
		//alert(extentRatio);
		if (extentRatio<10.00) {
			//alert(midX+"   "+midY);
			theString += '<OBJECT units="DATABASE">\n<POINT coords="' + midX + ' ' + midY + '">\n';
			//theString += '<SIMPLEMARKERSYMBOL  type="Square" color="' + ovBoxColor + '" width="4" />\n</POINT></OBJECT>\n';
			theString += '<SIMPLEMARKERSYMBOL  type="Circle" color="' + ovBoxColor + '" width="10" />\n</POINT></OBJECT>\n'
		} else {
			theString += '<OBJECT units="DATABASE">\n<LINE coords="' + left + ' ' + bottom + ';' + left + ' ' + top + ';';
			theString += right + ' ' + top + ';' + right + ' ' + bottom + ';' + left + ' ' + bottom + '">\n';
			theString += '<SIMPLELINESYMBOL type="SOLID" color="' + ovBoxColor + '" width="3" />\n</LINE></OBJECT>\n';
		}
		theString += '</LAYER>\n';
	}
	theString += '</GET_IMAGE>\n</REQUEST>\n</ARCXML>';
	//alert(theString);
	return theString;
}

// get the map extents from xml reply
function getXYs(theString) {
	var tempStr = "";
	var smallStr = "";
	var startpos = 0;
	var endpos = 0;

	var theReply = theString
	var theXYs =  getEnvelopeXYs(theString, 0)
	left = theXYs[0];
	bottom = theXYs[1];
	right = theXYs[2];
	top = theXYs[3];
	xDistance = Math.abs(right-left);
	yDistance = Math.abs(top-bottom);
	xHalf = xDistance / 2;
	yHalf = yDistance / 2;







	panX = xDistance * panFactor;
	panY = yDistance * panFactor;
	var sFactor = xDistance / iWidth

	if (aimsLayersPresent) {

		if (sFactor!=mapScaleFactor) {
			mapScaleFactor = sFactor;
                        trueMapScale = sFactor * 72
			if ((hasTOC) && (!legendVisible)) parent.TOCFrame.document.location = appDir + "toc.htm";
			if (aimsLayersPresent) {

				if (LayerListOpen) writeLayerListForm();
			}
			
		} 
	}
}


// get the map extents from xml reply
function getOVXYs(theString) {
	var tempStr = "";
	var smallStr = "";
	var startpos = 0;
	var endpos = 0;
	var theXYs =  getEnvelopeXYs(theString, 0)

	fullOVLeft = theXYs[0];
	fullOVBottom = theXYs[1];
	fullOVRight = theXYs[2];
	fullOVTop = theXYs[3];
	fullOVWidth = Math.abs(fullOVRight - fullOVLeft);
	fullOVHeight = Math.abs(fullOVTop - fullOVBottom);
	//alert("Left:" + fullOVLeft + "\nTop:" + fullOVTop + "\nRight:" + fullOVRight + "\nBottom:" + fullOVBottom);
}

// get URL
function getURL(theReply) {
	var theURL = "";
	var startpos = 0;
	var endpos = 0;

	
	var pos = theReply.indexOf("OUTPUT");
	if (pos != -1) {
		theURL = getInsideString(theReply,'url="',dQuote,pos,0,false);
		if (theURL!="") {
				endpos = theURL.lastIndexOf("/");
				theImageURLPath = theURL.substring(0,(endpos+1));
				startpos = theURL.lastIndexOf(".");
				var theType = theURL.substring(startpos+1,theURL.length);
				//alert("Image type: " + theType);
				if (theType.toUpperCase()=="GIF") {
					theImageType = "GIF";
				} else {
					theImageType = "PNG";
				}
				if (theType.toUpperCase()=="JPG") {
					noOverlay = true;
				}
				startpos = theReply.indexOf("file=",pos);
				if (startpos != -1) {
					startpos += 6;
					endpos = theReply.indexOf(dQuote,startpos);
					thePath = theReply.substring(startpos,endpos);
					endpos = thePath.lastIndexOf("\\");
					
					theImagePath = thePath.substring(0,(endpos+1));
					startpos = endpos + 1;
					endpos = thePath.indexOf("_",startpos);
					theServiceName = thePath.substring(startpos,endpos);

				}
		}
	}
	var tempImage = getLegendURL(theReply);
	if (tempImage != "") legendImage = tempImage;
	return theURL;

}



// getLegendURL
function getLegendURL(theReply) {
	var theURL = "";
	var startpos = 0;
	var endpos = 0;

	var pos = theReply.indexOf("LEGEND");
	//alert(pos);

	if (pos != -1) {
		theURL = getInsideString(theReply,'url="',dQuote,pos,0,false);
	}
	//alert("Legend:" + theURL);
	return theURL;

}

// just make a map with URL and  extent
function justGetMap(theURL, extentLeft, extentTop, extentRight, extentBottom, getOVMap) {
	var mode = 900;
	if (getOVMap) mode = 1;
	if (extentLeft!="") left = extentLeft;
	if (extentTop!="") top = extentTop
	if (extentRight!="") right = extentRight;
	if (extentBottom!="") bottom = extentBottom;
	var theText = writeXML();
	if (debugOn==2) alert("Sending:\n\n" + theText);	
	sendToServer(theURL,theText,mode);
	
}

// get min and max x,y's from xml stream . . . return an array with values
function getEnvelopeXYs(theString, startpos) {
	var theEnvelope = new Array();
	theString = theString.toUpperCase();
	var pos = theString.indexOf("ENVELOPE",startpos);
	if (pos!=-1) {
		pos = pos + 8;
		startpos = theString.indexOf("MINX=",pos);
		startpos += 6;

		var endpos = theString.indexOf(dQuote,startpos);
		theEnvelope[0] = parseFloat(theString.substring(startpos,endpos)); 
		startpos = theString.indexOf("MINY=",pos);
		startpos += 6;
		endpos = theString.indexOf(dQuote,startpos);
		theEnvelope[1] = parseFloat(theString.substring(startpos,endpos)); 
		startpos = theString.indexOf("MAXX=",pos);
		startpos += 6;
		endpos = theString.indexOf(dQuote,startpos);
		theEnvelope[2] = parseFloat(theString.substring(startpos,endpos)); 
		startpos = theString.indexOf("MAXY=",pos);
		startpos += 6;
		endpos = theString.indexOf(dQuote,startpos);
		theEnvelope[3] = parseFloat(theString.substring(startpos,endpos)); 
		xmlEndPos = endpos;
	}
	return theEnvelope;

}

// check if there is an error message in the response
function getXMLErrorMessage(theString) {
	var pos1 = 0;
	var pos2 = 0;
	var pos3 = 0;
	theError = "";
	pos3 = theString.indexOf("<ERROR");

	if (pos3!=-1) {
		pos1 = theString.indexOf(">",pos3);
		pos1 += 1;
		pos2 = theString.indexOf("</ERROR");

		theError = theString.substring(pos1,pos2)

	}
	return theError;

}

