// aimsXML.js
var aimsXMLPresent=true;
var identifyXMLMode = 50;

// 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;
	// index of current active MapService - default is zero - multiples in MultiService sample
var activeMapServiceIndex = 0;
	// array for determining if extent coordinates should have comma instead of point for decimals
var forceCommaInRequest = new Array();
forceCommaInRequest[activeMapServiceIndex] = false;
var forceCommaInOV = false;


var pastStart=false;
if (hasOVMap != true) pastStart = true;

// send in XML request and get XML response - uses helper applet
function sendToServer(URLString,XMLRequest,theType) {
	if(parent.PostFrame.document.theForm != null) {
		if(parent.MapFrame.clearActive) { okToSend=true; }

		if(okToSend) {
			XMLMode = theType;
			if(XMLMode==1) showRetrieveMap();
			okToSend = false;
			parent.MapFrame.clearActive = false;

			var theForm = parent.PostFrame.document.theForm;
			theForm.action=URLString + "&Form=True&Encode=True";
			theForm.ArcXMLRequest.value=XMLRequest;
			theForm.submit();
		} else {
			alert(msgList[10]);
			hideRetrieveMap();
			hideRetrieveData();
		}
	} else {
		alert(msgList[11]);
		hideRetrieveMap();
		hideRetrieveData();
	}
}

// send custom XML request. . . set up custom response handler
function sendCustomToServer(URLString,XMLRequest,theType) {
	var theServlet = parent.PostFrame.document.theServlet;
	theServlet.submit();
}
// send the created xml request to map server
function sendMapXML() {
	// ask for the Main map
      beforeMapRefresh();
      showRetrieveMap();
	var theText = writeXML();
	sendToServer(imsURL,theText,1);
}

// process the response xml
function processXML(theReplyIn) {
	theReplyIn = replacePlus(theReplyIn);
	var theReply = unescape(theReplyIn);
	okToSend = true;
	var theError = getXMLErrorMessage(theReply);

	switch(XMLMode) {
		case 1:
			var theURL = "";
			theURL = getURL(theReply);
			if(theURL != "") {
				getXYs(theReply);
				document.theImage.src = theURL;

				if(commentsBetween == true) {
					// GIS2B: Set the same image for applet
				      //document.KPApplet.setImage(theURL);
					KPApplet.setImage(theURL);
					kommentointiURL = theURL;
				}
				afterMapRefresh();
				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);
				}
			}
			if(toolMode==20) {
				updateMeasureBox();
			}
			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;
				}
			}
                        if(newUser == true) {
                          if(NaytaOverView == false) {
                            if(osoitepaikannus_geo==true)
                              setupGeocode();
                            if(osoitepaikannus_rak==true)
			      HaeTiet();
                          }
                          newUser = false;
                        }

			break

		case 2:
			// just put up an overview map
			var theURL = "";
			theURL = getURL(theReply);
			if (!pastStart) {
				getOVXYs(theReply);
				pastStart=true;
			}
			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);
				}

			}
			hideRetrieveMap();
			if(osoitepaikannus_geo==true)
                          setupGeocode();
                        else {
                          if(NimistoHaku == true)
                            HaeNimisto();
                        }
                        break

		case 3:
			//  just get full extent - service info
			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"?>\n<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"?>\n<ARCXML version="1.1">\n<REQUEST>\n<GET_SERVICE_INFO  renderer="false" />\n';
				theString += '</REQUEST>\n</ARCXML>';
				sendToServer(imsGeocodeURL,theString,200);
			} else {
				theString = '<?xml version="1.0" encoding="UTF-8"?>\n<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;
			}

			break

		case 4:
			// get service info - extent, layers
			processStartExtent(theReply);
			break

		case 5:
			// just put up a map with legend
			var theURL = "";
			theURL = getURL(theReply);
			if (theURL != "") {
				document.theImage.src = theURL;
			}
			if (legendVisible) {
				showLegend();
				drawLegendOnly=false;
			}
			hideRetrieveMap();

			break

		case 6:
			// print - get Map image
			printMapURL = getURL(theReply);
			printLegURL = getLegendURL(theReply);
			if(hasOVMap)
				getPrintOV();
			else
				getPrintLegend();

			break

		case 7:
			// print - get OV image
			printOVURL = getURL(theReply);
			legendImage = printLegURL
			getPrintLegend();

			break

		case 50:
			// Info-työkalu, oletus
			identifyXMLMode = XMLMode;
			// get query response esim. nimiston paikannus
			displayAttributeData(theReply);
                        //tutkitaan onko käytetty Nimistö hakua ja jos on niin palautetaan edellinen aktiivinen layer takaisin
                        if(GlobalNimisto == true){
                        	setActiveLayer(ViimeinenLayer - GlobalActiveLayer);
					GlobalNimisto = false;
                        }
			break

		case 51:
			// Info-työkalu, asuntohaku
			identifyXMLMode = XMLMode;
			// get query response
			displayAttributeData(theReply);

			break

		case 100:
			// Nimistöhaku
			parseFieldSamples(theReply,"nimisto");
        		break

		case 101:
			// Väestön ikäjakauma
			parseFieldSamples(theReply,"alue");
            	break

		case 102:
			// Osoitehaku
			parseFieldSamples(theReply,"osoite");
			if(osoitepaikannus_geo == true)
                            parent.TextFrame.document.location= appDir + "addmatch_geo.html";
			if(osoitepaikannus_rak == true)
                            parent.TextFrame.document.location= appDir + "addmatch_buil.html";
			break

		case 103:
			// Osoitehaku
			// get geocoding results
			parseGeocodeResults(theReply);

			break

		case 104:
			// Palveluhakemisto
			useCustomFunction(theReply);

			break

		case 105:
			// Palvelut
	          	getBufferShape(theReply);

			break

		case 106:
			// Asuntohaku
	          	displayAttributeDataHome(theReply);

			break

		case 107:
			// Lähestymiskartta, kuva 1
			// print - get Map image
			printMapURL = getURL(theReply);
			printLegURL = getLegendURL(theReply);

			printApproachMapStart();

			break

		case 108:
			// Lähestymiskartta, kuva 2
			// print - get Map image
			printMapURL = getURL(theReply);
			printLegURL = getLegendURL(theReply);

			printApproachMapContinue();

			break

		case 109:
			// Lähestymiskartta, kuva 3
			// print - get Map image
			printMapURL = getURL(theReply);
			printLegURL = getLegendURL(theReply);

			printApproachMapEnd();

			break

		case 110:
			// Osoitehaun numerohaku
			parseFieldSamples(theReply,"numero");

			break

		case 111:
			// Koulutoimen alueiden haku
			parent.TextFrame.displayAttribureAll(theReply);

			break;

		case 112:
			// Koulutoimen haku koulupiireistä
			identifyXMLMode = XMLMode;
			displayAttributeData(theReply);
			
			break;

		case 113:
            	// Koulutoimen haku piirtämällä
			countAttributeData(theReply);

			break

		case 114:
            	// Tonttihaun oletusasetusten hakeminen
			parent.TextFrame.displayAttribureAll(theReply);

			break

		case 115:
	      	// Tonttihaun alueiden haku
			displayAttributeDataSite(theReply);

			break

		case 200:
			// get geocoding layers
			parseGeocodeLayers(theReply);
			// get layers for display
			var theString = '<?xml version="1.0" encoding="UTF-8"?>\n<ARCXML version="1.1">\n<REQUEST>\n<GET_SERVICE_INFO  renderer="false" extensions="true" />\n';
			theString += '</REQUEST>\n</ARCXML>';
			sendToServer(imsURL,theString,4);

			break

		case 201:
			// get geocoding layers
			if (parseGeocodeParams(theReply,GCLayers[GCActiveLayer])) {

				var theAddressForm = appDir + "addmatch.htm";
			} 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";
				}
			}
                        if(NimistoHaku == true)
                          HaeNimisto();
			break

		case 202:
			// 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

		case 203:
			// Paikkalinkki
			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 204:
			// Koulutoimi moduulin piirtotyökalu
			var theURL = "";
			legendVisible=legendTemp;
			theURL = getURL(theReply);
			if (theURL != "") {
				document.theImage.src = theURL;
			}
			else {
				alert(msgList[14] + theReply);
			}
			hideRetrieveMap();

			break

		default:
			alert("Unable to execute response.\nXMLMode: " + XMLMode);
	}
}

// write out a blank map. . . to get image extents from limit extents
function writeBlankMapXML() {

	//var theString = '<?xml version="1.0" encoding="UTF-8"?>\n<ARCXML version="1.1">\n<REQUEST>\n<GET_IMAGE>\n<PROPERTIES>\n<ENVELOPE minx="' + limitLeft + '" miny="' + limitBottom + '" maxx="' + limitRight + '" maxy="' + limitTop + '" />\n';
	var theString = '<ARCXML version="1.1">\n<REQUEST>\n<GET_IMAGE>\n<PROPERTIES>\n<ENVELOPE minx="' + forceComma(limitLeft) + '" miny="' + forceComma(limitBottom) + '" maxx="' + forceComma(limitRight) + '" maxy="' + forceComma(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>';
	sendToServer(imsURL,theString,202);
}

// prepare the request in xml format for Main Map
function writeXML() {
	var theString = '<?xml version="1.0" encoding="UTF-8"?>\n<ARCXML version="1.1">\n<REQUEST>\n<GET_IMAGE>\n<PROPERTIES>\n<ENVELOPE minx="' + forceComma(left) + '" miny="' + forceComma(bottom) + '" maxx="' + forceComma(right) + '" maxy="' + forceComma(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';
			for(var i=0;i<layerCount;i++) {
				if(LayerVisible[i]==1) {
					theString += '<LAYERDEF id="' + LayerID[i] + '" visible="true">\n';
					if(LayerID[i] == 10 && refmap == true && mSkiValues.length > 0) {
						theString += '<GROUPRENDERER>';
						for(var j=0; j<mSkiValues.length; j++) {
							theString += '<VALUEMAPRENDERER lookupfield="NIMI">\n';
	      					theString += '<EXACT value="' + mSkiValues[j][0] + '" label="' + mSkiValues[j][0] + '">\n';
							theString += '<SIMPLELINESYMBOL type="solid" antialiasing="true"  width="4" color="' + mSkiValues[j][1] + '"/>\n';
							theString += '</EXACT>\n';
							theString += '</VALUEMAPRENDERER>\n';
						}
						theString += '</GROUPRENDERER>';
					}
					theString += '</LAYERDEF>';
				} 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
		//alert(legendVisible);
		if (legendVisible) theString += addLegendToMap();
	}

	theString += '</PROPERTIES>\n';

	// buffer
	if(aimsBufferPresent) {
		if (showBuffer) theString += addBufferToMap();

	}
	// select
	if(aimsSelectPresent) {
		theString += addSelectToMap();
  	}
	// any custom stuff to fit here
	if(aimsCustomPresent) theString += addCustomToMap1();

	// line background color
	if(lineBackColor && strSKIColor != "") {
		theString +='<LAYER type="FeatureClass" name="Valittu kohde" visible="true">\n';
		theString +='<DATASET fromlayer="' + LayerID[ActiveLayerIndex] + '" />\n';
		theString +='<SPATIALQUERY where="' + setQueryString + '" />\n';
		theString += '<GROUPRENDERER>\n';
		theString += '<SIMPLERENDERER>\n';
		theString += '<SIMPLELINESYMBOL type="solid" antialiasing="true" width="7" color="' + strSKIColor + '" />\n';
		theString += '</SIMPLERENDERER>\n';
		theString += '</GROUPRENDERER>\n';
		theString += '</LAYER>\n';
	}			
	if(showGeocode) {
		var coordsDelimiter = " ";
		// 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="' + forceComma(geocodeX) + ' ' + forceComma(geocodeY) + '">\n';
		theString += '<SIMPLEMARKERSYMBOL  type="' + geocodePointType + '"  color="' + geocodePointColor + '" width="' + geocodePointSize +'" overlap="false" antialiasing="False" />\n</POINT></OBJECT>\n';
		if (geocodeLabel!="") {
			theString += '<OBJECT units="DATABASE">\n<TEXT coords="' + forceComma(geocodeX) + ' ' + forceComma(geocodeY) + '" label="' + geocodeLabel + '">\n';
			theString += '<TEXTMARKERSYMBOL printmode ="titlecaps" antialiasing="true" font="' + geocodeLabelfont + '" fontstyle="' + geocodeLabelfontstyle + '" fontcolor="' + geocodeLabelfontcolor + '" fontsize="' + geocodeLabelfontsize + '" overlap="false" glowing="' + geocodeLabelfontbackground + '" interval="' + geocodeLabelfontinterval + '" 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="' + forceComma(clickPointX[0]) + " " + forceComma(clickPointY[0]);
				for (var i=1;i<clickCount;i++) {
					theString += " "  + forceComma(clickPointX[i]) + " " + forceComma(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="' + forceComma(clickPointX[0]) + " " + forceComma(clickPointY[0]);
				for (var i=1;i<clickCount;i++) {
					theString += " "  + forceComma(clickPointX[i]) + " " + forceComma(clickPointY[i]);
				}
				theString += '" >\n';
				theString += '<SIMPLELINESYMBOL transparency="' + transparentLevel + '" type="' + measurelineType + '" color="' + measurelineColor + '" width="' + measurelineWidth + '" />\n</LINE>\n</OBJECT>\n';
	 		}
			for (var i=0;i<clickCount;i++) {
				theString += '<OBJECT units="DATABASE">\n<POINT coords="' + forceComma(clickPointX[i]) + ' ' + forceComma(clickPointY[i]) + '">\n';
				theString += '<SIMPLEMARKERSYMBOL antialiasing="True" transparency="' + transparentLevel + '" type="' + measureMarkerType + '"';
				theString += ' color="' + measureMarkerColor + '" outline="' + measureoutlineMarkerColor +'" width="' + measureMarkerSize + '" />\n</POINT>\n</OBJECT>\n';
			}
			theString += '</LAYER>\n';
		}
	}

	// any custom stuff to fit here
	if (aimsCustomPresent)
		theString += addCustomToMap2();

	if(drawCopyright) {
		var yCoords = CopyrightCoords;
		var xCoords = CopyrightCoords;

		// Draw text on the map.
		theString += '<LAYER type="ACETATE" name="theCopyright">\n';

		if(CopyrightText1 != "") {
			theString += '<OBJECT units="PIXEL">\n';
			theString += '<TEXT coords="' + xCoords + ' ' + yCoords + '" label="' + CopyrightText1 + '">\n';
			theString += '<TEXTMARKERSYMBOL fontstyle="' + CopyrightStyle + '" fontsize="' + CopyrightSize + '" ';
			theString += 'font="' + CopyrightFont + '" fontcolor="' + CopyrightColor + '" antialiasing="True" ';
			theString += '/>\n</TEXT>\n';
			theString += '</OBJECT>\n';
			yCoords = parseInt(yCoords) + parseInt(CopyrightSize);
		} if(CopyrightText2 != "") {
			theString += '<OBJECT units="PIXEL">\n';
			theString += '<TEXT coords="' + xCoords + ' ' + yCoords + '" label="' + CopyrightText2 + '">\n';
			theString += '<TEXTMARKERSYMBOL fontstyle="' + CopyrightStyle + '" fontsize="' + CopyrightSize + '" ';
			theString += 'font="' + CopyrightFont + '" fontcolor="' + CopyrightColor + '" antialiasing="True" ';
			theString += '/>\n</TEXT>\n';
			theString += '</OBJECT>\n';
			yCoords = parseInt(yCoords) + parseInt(CopyrightSize);
		} if(CopyrightText3 != "") {
			theString += '<OBJECT units="PIXEL">\n';
			theString += '<TEXT coords="' + xCoords + ' ' + yCoords + '" label="' + CopyrightText3 + '">\n';
			theString += '<TEXTMARKERSYMBOL fontstyle="' + CopyrightStyle + '" fontsize="' + CopyrightSize + '" ';
			theString += 'font="' + CopyrightFont + '" fontcolor="' + CopyrightColor + '" antialiasing="True" ';
			theString += '/>\n</TEXT>\n';
			theString += '</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 + '"  fontstyle="' + ScaleBarStyle + '" barcolor="' + ScaleBarColor + '" ';
		theString += 'mapunits="' + MapUnits + '" ';
		theString += 'scaleunits="' + ScaleBarUnits + '" antialiasing="false" ';
		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);
	return theString;
}

// prepare the request in xml format for overview map
function writeOVXML() {
	var extentRatio = xDistance/fullWidth;
	var midX = left + xHalf;
	var midY = bottom + yHalf;
	var theString = '<ARCXML version="1.1">\n<REQUEST>\n<GET_IMAGE><PROPERTIES>\n';
	theString += '<ENVELOPE minx="' + forceOVComma(fullOVLeft) + '" miny="' + forceOVComma(fullOVBottom) + '" maxx="' + forceOVComma(fullOVRight) + '" maxy="' + forceOVComma(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';
	theString += '</GET_IMAGE>\n</REQUEST>\n</ARCXML>';
	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;
			if(LayerListOpen) writeLayerListForm();
			if(parent.TextFrame.location.pathname == appDir + "toc.html") parent.TextFrame.document.location = appDir + "toc.html";
		}
	}
}


// 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);
}

// 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);
				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);
				}
		}
	}
	legendImage = getLegendURL(theReply);
	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();
	//forceCommaInRequest[activeMapServiceIndex] = false;
	theString = theString.toUpperCase();
	var tempString = "";
	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);
		tempString = theString.substring(startpos,endpos);
		theEnvelope[0] = parseFloat(setDecimalString(tempString));
		startpos = theString.indexOf("MINY=",pos);
		startpos += 6;
		endpos = theString.indexOf(dQuote,startpos);
		tempString = theString.substring(startpos,endpos);
		theEnvelope[1] = parseFloat(setDecimalString(tempString));
		startpos = theString.indexOf("MAXX=",pos);
		startpos += 6;
		endpos = theString.indexOf(dQuote,startpos);
		tempString = theString.substring(startpos,endpos);
		theEnvelope[2] = parseFloat(setDecimalString(tempString));
		startpos = theString.indexOf("MAXY=",pos);
		startpos += 6;
		endpos = theString.indexOf(dQuote,startpos);
		tempString = theString.substring(startpos,endpos);
		theEnvelope[3] = parseFloat(setDecimalString(tempString));
		xmlEndPos = endpos;
	}
        //alert(theEnvelope[0]);
        //alert(theEnvelope[1]);
        //alert(theEnvelope[2]);
        //alert(theEnvelope[3]);
	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;

}

// set number string to have decimal character to match browser language type - point or comma
function setDecimalString(numberString) {

	if (numberString.indexOf(",")!=-1) {
		forceCommaInRequest[activeMapServiceIndex] = true;
	}
	if (decimalChar==".") {
		numberString = numberString.replace(/,/g, ".");
	} else {
		numberString = numberString.replace(/./g, ",");
	}
	return numberString;
}

function forceComma(theNumber) {
	var comma = ",";
	var dot = ".";
	var charOut = comma;
	var charIn = dot;
	var numberString = new String(theNumber);
	if (forceCommaInRequest[activeMapServiceIndex]) {
		charOut = dot;
		charIn = comma;
	}
	var pos = numberString.indexOf(charOut);
	if (pos!=-1) {
		var begin = numberString.substring(0,pos);
		var ending = numberString.substring(pos+1, numberString.length);
		numberString = begin + charIn + ending;
	}
	//alert("force :" + numberString);
	return numberString;
}
function forceOVComma(theNumber) {
	var comma = ",";
	var dot = ".";
	var charOut = comma;
	var charIn = dot;
	var numberString = new String(theNumber);
	if (forceCommaInOV) {
		charOut = dot;
		charIn = comma;
	}
	var pos = numberString.indexOf(charOut);
	if (pos!=-1) {
		var begin = numberString.substring(0,pos);
		var ending = numberString.substring(pos+1, numberString.length);
		numberString = begin + charIn + ending;
	}
	return numberString;
}
function zoomToChoiceMeasure2(xTravel, yTravel) {
	var tmpLeft = parseInt(left);
	var tmpRight = parseInt(right);
	var tmpTop = parseInt(top);
	var tmpBottom = parseInt(bottom);

	var count_xDistance = parseInt(xDistance);
	var count_yDistance = parseInt(yDistance);

	while(count_xDistance != xTravel) {
		if(count_xDistance > xTravel) {
			tmpLeft += 0.5;
			tmpRight -= 0.5;
		}
		else {
			tmpLeft -= 0.5;
			tmpRight += 0.5;
		}
		count_xDistance = tmpRight - tmpLeft;
	}
	while(count_yDistance != yTravel) {
		if(count_yDistance > yTravel) {
			tmpTop -= 0.5;
			tmpBottom += 0.5;
		}
		else {
			tmpTop += 0.5;
			tmpBottom -= 0.5;
		}
		count_yDistance = tmpTop - tmpBottom;
	}

	left = tmpLeft;
	right = tmpRight;
	top = tmpTop;
	bottom = tmpBottom;
}
