// aimsIdentify.js
/*
*  JavaScript template file for ArcIMS HTML Viewer
*		dependent on aimsXML.js, ArcIMSparam.js, aimsCommon.js, aimsMap.js, and aimsLayers.js
*		To be interactive, dependent also on aimsDHTML.js, aimsClick.js, and aimsNavigation.js
*/

aimsIdentifyPresent=true;

// hyperlink variables
var currentHyperLinkLayer="";
var currentHyperLinkField="";
var hyperlinkWindowWidth=500;
var hyperlinkWindowHeight=400;

// variable for search tolerance... dynamically set in app
var searchTolerance=0.01;
// starting record position for returned records
var queryStartRecord=0;

if (imsQueryURL=="") {
	imsQueryURL= imsURL + "&CustomService=Query";
	//alert(imsQueryURL);
}
var canQuery=true;
var newSelectCount=0;
var selectPoints = new Array();

// variables to store values used in the buffering of the Comparable Sales Query for display in the results box.
var resultPrintDistance = "";
var resultPrintUnits = "";
var resultPrintSource = "";
// store reply to a query for use later
var storedReply = "";

var identifyMapService = new Array();	//listing of layers that may be identified in a map service
var identifyLayer = new Array();
identifyMapService[0]= "KCRC_FiveYearPlan";
identifyLayer[0]=["5 Year Program"];
identifyMapService[1]="KCRC_TruckOperator";
identifyLayer[1]=["City Designated Truck Routes","County All-Season","Narrow Passage","Restricted Bridges","Trunkline"];
identifyMapService[2]="Public_Parks";
identifyLayer[2]=["Parks","Trails and Bikeways","Street Centerlines"];
identifyMapService[3]="Public_PlannedLanduse";
identifyLayer[3]=["Planned Landuse Areas","Street Centerlines"];
identifyMapService[4]="Public_Voting";
identifyLayer[4]=["County Commissioner Districts","Intermediate School Districts","Library Districts","Parcels","School Districts","State House Districts","State Senate Districts","Street Centerlines","US House Districts","Wards and Precincts"];
identifyMapService[5]="Public_Zoning";
identifyLayer[5]=["Zoning Areas","Street Centerlines"];

var lastLayerIdentified = "";	//stores name of last layer identified in the automated process. Serves to track progress.
var identifyWin;		//stores the open identify results window object
var selectedIdentifyLayers = new Array();	//stores layers that user has selected for identification
var selectedIdentifyReplies = new Array();	//stores replies of automated identify for printing
/*
***************************************************************************************

Identify functions 

***************************************************************************************
*/
function tablePrint() {
	// CVG function to parse out HTML table and create a printable report document.
	//function can be found aimsPrint.js
	writeTablePage(); 

}

// identify feature
function identify(e) {
	highlightedOne="";
	var theX = mouseX;
	var theY = mouseY;
	getMapXY(theX,theY);
	autoIdentifyProgram();
}

function autoIdentifyProgram() {
	if (lastLayerIdentified == "") {
		for (var z=0;z<selectedIdentifyReplies.length;z++) {
			selectedIdentifyReplies[z] = "";
		}
	}
	//If lastLayerIdentified is empty, then we are at the start. Create the first HTML code
	if (lastLayerIdentified == "") generateStartHTML();
	//Decide which Layer to identify now
	var theLayerIndex = -1;
	var theServiceThisTime = "";
	if (selectedIdentifyLayers.length == 0) {
		alert("You have not picked any layers to identify. Please click on the 'Identify' button to open the layer window and pick at least one layer from the list");
		return;
	}
	if (lastLayerIdentified == ""){
		theServiceThisTime = selectedIdentifyLayers[0];
		lastLayerIdentified = theServiceThisTime;
	} else {
		for (var d=0;d<selectedIdentifyLayers.length;d++) {
			if (selectedIdentifyLayers[d] == lastLayerIdentified) {
				if (d != selectedIdentifyLayers.length-1) {
					theServiceThisTime = selectedIdentifyLayers[d+1];
					lastLayerIdentified = theServiceThisTime;
					break;
				} else {
					lastLayerIdentified = "";
					hideRetrieveData();
					generateEndHTML();
					return;
				}
			}
		}
	}
	fullSetActiveLayer(theServiceThisTime);
	//master function for automated identification of several layers
	searchTolerance = (xDistance/iWidth) * 5;
	var tempWest = mapX - searchTolerance;
	var tempNorth = mapY + searchTolerance;
	var tempEast = mapX + searchTolerance;
	var tempSouth = mapY - searchTolerance;
	var theString = writeGetFeatures(tempWest,tempSouth,tempEast,tempNorth);
	showRetrieveData();
	sendToServer(imsQueryURL,theString,identifyXMLMode);
}

//part of automated identify sequence. Places opening set of HTML code for document
function generateStartHTML(){
	if ((useExternalWindow) || (!useTextFrame)) {
		identifyWin = window.open("","QueryWindow","left=120,top=400,width=575,height=200,scrollbars=yes,resizable=yes");
	} else {
		identifyWin = parent.TextFrame;
	}
	var Win1 = identifyWin;
	if (loadThisService == "KCRC_FiveYearPlan") {
		Win1.moveTo(10,400);
		Win1.resizeTo(800,200);
	} else if (loadThisService == "KCRC_TruckOperator") {
		Win1.moveTo(10,100);
		Win1.resizeTo(800,650);
	}
	Win1.document.open();
	Win1.document.writeln('<html><head><title>Query/Selection Results</title>');
	Win1.document.writeln('<SCRIPT TYPE="text/javascript" LANGUAGE="JavaScript">');
	Win1.document.writeln('var t;');
	Win1.document.writeln('var par;');
	Win1.document.writeln(' if (opener) {  ');
	Win1.document.writeln(' 	if (opener.name=="MapFrame") {  ');
	Win1.document.writeln(' 		t = opener.parent.MapFrame;  ');
	Win1.document.writeln('			par = opener.parent;  ');
	Win1.document.writeln(' 	} else {  ');
	Win1.document.writeln('	        	t = opener; ');
	Win1.document.writeln('			par = opener;  ');
	Win1.document.writeln('		}  ');
	Win1.document.writeln(' } else {  ');
	Win1.document.writeln('		if (parent.MapFrame) {  ');
	Win1.document.writeln('			t = parent.MapFrame;  ');
	Win1.document.writeln('			par = parent;  ');
	Win1.document.writeln('		} else {  ');
	Win1.document.writeln('			t=document;  ');
	Win1.document.writeln('		}  ');
	Win1.document.writeln('	}  ');
	Win1.document.writeln('</SCRIPT></head>');
	Win1.document.writeln('<body bgcolor=#006600 text="#006600" link="Red" vlink="Blue" LEFTMARGIN=0 onload="window.focus()">');
	Win1.document.writeln('<SCRIPT TYPE="text/javascript" LANGUAGE="JavaScript">');
	Win1.document.writeln('var srtTextID=""');
	Win1.document.writeln('function CVGprint() {');
	Win1.document.writeln('// CVG function to parse out HTML table and create a printable report document.');
	Win1.document.writeln('//alert("Print Function")'); 
	Win1.document.writeln('}');
	Win1.document.writeln('function loadHelp() {');
	Win1.document.writeln('var Win2;');
	Win1.document.writeln('Win2 = window.open("http://'+hostName+'/website/KCRC/helpIdentifyResults.htm","Help","width=800,height=550,scrollbars=yes,resizable=yes");');
	Win1.document.writeln('Win2 = null;');
	Win1.document.writeln('}');
	Win1.document.writeln('function extract() {');
	Win1.document.writeln('    if (document.all){');
	Win1.document.writeln('    var aryHead = new Array();');
	Win1.document.writeln('    var aryCells = new Array();');
	Win1.document.writeln('    var aryCount=0');
	Win1.document.writeln('        for (var i=0;i < parent.TextFrame.document.all.length; i++){');
	Win1.document.writeln('		//alert(parent.TextFrame.document.all(i).tagName);');
	Win1.document.writeln('            if (parent.TextFrame.document.all(i).tagName == "TH"){');
	Win1.document.writeln('              aryHead[aryCount] = parent.TextFrame.document.all(i).outerHTML');
	Win1.document.writeln('              aryCount++');
	Win1.document.writeln('            } ');
	Win1.document.writeln('         }');
	Win1.document.writeln('         aryCount = 0');
	Win1.document.writeln('         for (var i=0;i < parent.TextFrame.document.all.length; i++){');
	Win1.document.writeln('            if (parent.TextFrame.document.all(i).tagName == "TD"){');
	Win1.document.writeln('               aryCells[aryCount] = parent.TextFrame.document.all(i).outerHTML');
	Win1.document.writeln('              aryCount++');
	Win1.document.writeln('            } ');
	Win1.document.writeln('         } ');   
	Win1.document.writeln('      formatTable(aryHead,aryCells);');
	Win1.document.writeln('    }');
	Win1.document.writeln('}');
	Win1.document.writeln('function formatTable(aryHead,aryCells) {');
	Win1.document.writeln('  alert(aryHead,aryCells);');
	Win1.document.writeln('  strTextID = "<TABLE width=\'600\' bgColor=white border=1 cellPadding=0 cellSpacing=0><TBODY>";');
	Win1.document.writeln('  numMax = Math.ceil(aryHead.length / 8)');
	Win1.document.writeln('  numLimit1 = 0');
	Win1.document.writeln('  numLimit2 = 0');
	Win1.document.writeln('  numRunningTotal1 = 0');
	Win1.document.writeln('  numRunningTotal2 = 0');
	Win1.document.writeln('  rowNumber = 0');
	Win1.document.writeln('  //alert(aryHead.length);');
	Win1.document.writeln('  if (aryHead.length <= 8) {');
        Win1.document.writeln('    //alert("Case 1");');
	Win1.document.writeln('    for (var j=0;j < numMax;j++){');
	Win1.document.writeln('      strTextID += "<TR>"');
	Win1.document.writeln('      for (numRunningTotal1;numRunningTotal1 < aryHead.length; numRunningTotal1++){');
	Win1.document.writeln('        numLimit1++');
	Win1.document.writeln('        strTextID += aryHead[numRunningTotal1]');
	Win1.document.writeln('      }');
	Win1.document.writeln('      numRunningTotal1++');
	Win1.document.writeln('      numLimit1 = 0');
	Win1.document.writeln('      strTextID += "</TR>"');
	Win1.document.writeln('      for (numRunningTotal2;numRunningTotal2 < aryCells.length; numRunningTotal2++){');
	Win1.document.writeln('        numLimit2++');
	Win1.document.writeln('        strTextID += aryCells[numRunningTotal2]');
	Win1.document.writeln('        if (numLimit2 == 8 || numLimit2 == aryHead.length) {');
	Win1.document.writeln('          numLimit2 = 0');
	Win1.document.writeln('          strTextID += "</TR><TR>"');
	Win1.document.writeln('        }');
	Win1.document.writeln('      }');
	Win1.document.writeln('      strTextID += "</TR>"');
	Win1.document.writeln('    }');
	Win1.document.writeln('  } else { ');
        Win1.document.writeln('    //alert("Case 2");');
        Win1.document.writeln('    alert("More than eight attributes present.  Unable to print.");');
        Win1.document.writeln('    return;');
	Win1.document.writeln('    for (var j=0;j < numMax;j++){');
	Win1.document.writeln('      strTextID += "<TR>"');
	Win1.document.writeln('      for (numRunningTotal1;numRunningTotal1 < aryHead.length; numRunningTotal1++){');
	Win1.document.writeln('        numLimit1++');
	Win1.document.writeln('        strTextID += aryHead[numRunningTotal1]');
	Win1.document.writeln('        if ((numLimit1 % 8 == 0) || numLimit1 == aryHead.length) {');
	Win1.document.writeln('          strTextID += "</TR><TR>"');
	Win1.document.writeln('          startCol = numLimit1 - 7');
	Win1.document.writeln('          //alert("Start Col: " + startCol)');
	Win1.document.writeln('          endCol = numLimit1');
	Win1.document.writeln('          //alert("End Col: " + endCol)');
	Win1.document.writeln('          //alert("Row Number: " + rowNumber)');
	Win1.document.writeln('          for (numRunningTotal2;numRunningTotal2 < aryCells.length; numRunningTotal2++){');
	Win1.document.writeln('            for (colCheck = startCol;colCheck < endCol; colCheck++){');
	Win1.document.writeln('              //alert("RowNumber: " + rowNumber);');
	Win1.document.writeln('              //alert("Head Length: " + aryHead.length);');
	Win1.document.writeln('              //alert("col Check: " + colCheck);');
	Win1.document.writeln('              //alert("Running Total: " + numRunningTotal2);');
	Win1.document.writeln('              //alert((((rowNumber - 1) * aryHead.length) + colCheck));');
	Win1.document.writeln('              if (numRunningTotal2 == (((rowNumber * aryHead.length) + colCheck)) - 1) {');
	Win1.document.writeln('                strTextID += aryCells[numRunningTotal2]');
	Win1.document.writeln('              }');
	Win1.document.writeln('            }');
	Win1.document.writeln('            if ((numRunningTotal2 == 8) || (numRunningTotal2 % 8 == 0 && numRunningTotal2 != 0)) {');
	Win1.document.writeln('              rowNumber++');
	Win1.document.writeln('              strTextID += "</TR><TR>"');
	Win1.document.writeln('            }');
	Win1.document.writeln('          }');
	Win1.document.writeln('        }');
	Win1.document.writeln('      }');
	Win1.document.writeln('    }');
	Win1.document.writeln('  }');
	Win1.document.writeln(' strTextID += "</TBODY></TABLE>"');
	Win1.document.writeln(' writePage();');
	Win1.document.writeln('}');
        Win1.document.writeln(' ');
	Win1.document.writeln('function trapper(curfunction) {');
	Win1.document.writeln(' if (t.loading) {');
	Win1.document.writeln('		alert("A request is currently pending with the IMS server. This is indicated by the spinning globe in the middle of the screen. When the globe disappears, you will be free to use this button.")');
	Win1.document.writeln('		return;');
	Win1.document.writeln('	}');
	Win1.document.writeln(' if(t.toolMode == 35) t.publicSelCleared = true;  ');
	Win1.document.writeln('	t.clickFunction(curfunction);');
	Win1.document.writeln(' window.close();  ');
	Win1.document.writeln('}');
	Win1.document.writeln('function closeWinFirst(thePPNValue) {   ');
	Win1.document.writeln('		t.accessKentTransfer(thePPNValue) ');
	Win1.document.writeln('		//window.close();		');
	Win1.document.writeln('	} ');
	Win1.document.writeln('function writePage() {');
        Win1.document.writeln('Win2 = window.open("","ReportWindow","width=675,height=240,scrollbars,resizable,alwaysRaised,toolbar");');
	Win1.document.writeln('Win2.document.writeln("<html><head><title>Query/Selection Results</title></head>");');
	Win1.document.writeln('Win2.document.writeln(strTextID);');
	Win1.document.writeln('}');
	Win1.document.writeln('</SCRIPT>');

        // CVG Added Code to add a print button to the Table View 
        Win1.document.writeln('<BODY><div align="center">');	
        Win1.document.writeln('<input type="image" src="'+appPath+appDir+'images/smallprint1.gif" width="16" height="16" border=0 alt="Print this table" onclick="t.multiTablePrint();" onmouseover="window.status=\'Print this table\'" > </a>');	Win1.document.writeln('<FONT size="4" color="white">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;The following features were found at the spot you indicated:</FONT><br>');			
}

//part of automated identify sequence. Places results into HTML document
function generateResultsHTML(theReply){
	var theError = getXMLErrorMessage(theReply);
	var fList="";
	var lpos1 = 1;
	var lpos2 = 1;
	var epos = 1;
	var spos = 1;
	var morePoints=true;
	var moreFeatures=true;
	var featureCount = justGetFeatureCount(theReply);
	var pos = 0;
	var startpos = 0;
	var endpos = xmlEndPos;
	var stillMore = false
	pos = theReply.indexOf('hasmore="true"',endpos);
	if (pos!=-1) stillMore = true;
	pos=0;
	var tempCount = 0;
	var selectedData="";
	var inData="";
	var xStr="";
	var yStr="";
	var eNorth="";
	var eSouth="";
	var eWest="";
	var eEast="";
	var fCount = featureCount;
	selectCount = 0;
	var tempString="";
	var Win1 = identifyWin;
	var theFrame = "parent.MapFrame";
	for (var f=0;f<selectedIdentifyReplies.length;f++) {
		if (selectedIdentifyReplies[f] == "") {
			selectedIdentifyReplies[f] = theReply;
			break;
		}
	}
	//****below here is unaltered text****
	if (featureCount > 0) {
		Win1.document.writeln('<br>');
		Win1.document.write('<center><FONT COLOR="White" FACE="Arial"><b>Results from ' + LayerName[ActiveLayerIndex] + '</b></font>');
		Win1.document.writeln('<table border="1" cellspacing="0" cellpadding="2" nowrap bgcolor=#ffff99>');
		newSelectCount += 1;
		endpos = 1;
		var intEndPos = theReply.lastIndexOf("</FEATURE>");
		var strReplyEnd = theReply.slice(intEndPos);
		var intEnvelopePos = strReplyEnd.indexOf("<ENVELOPE");
		if (intEnvelopePos != -1) {
			//that's a global envelope: let's use that
			var intStartPos = strReplyEnd.indexOf('minx="');
			var intNextPos = strReplyEnd.indexOf('"',intStartPos+7);
			customLeft = strReplyEnd.slice(intStartPos+6,intNextPos);
			intStartPos = strReplyEnd.indexOf('miny="');
			intNextPos = strReplyEnd.indexOf('"',intStartPos+7);
			customBottom = strReplyEnd.slice(intStartPos+6,intNextPos);
			intStartPos = strReplyEnd.indexOf('maxx="');
			intNextPos = strReplyEnd.indexOf('"',intStartPos+7);
			customRight = strReplyEnd.slice(intStartPos+6,intNextPos);
			intStartPos = strReplyEnd.indexOf('maxy="');
			intNextPos = strReplyEnd.indexOf('"',intStartPos+7);
			customTop = strReplyEnd.slice(intStartPos+6,intNextPos);
			useCustomCoords = true;
			
		} 
		for (var i=0;i<fCount;i++) {
			//alert(endpos);
			if (toolMode!=4) {
				var theXYs = getEnvelopeXYs(theReply, endpos)
				selectLeft[selectCount] = theXYs[0];
				selectBottom[selectCount] = theXYs[1];
				selectRight[selectCount] = theXYs[2];
				selectTop[selectCount] = theXYs[3];
				endpos = xmlEndPos;
                                 
                                // CVG Code added to Zoom to Extent of selected features - CVG
                                if( i == 0 ) {
                                	var maxLeft = theXYs[0];
                                	var maxBottom = theXYs[1];
                                	var maxRight = theXYs[2];
                                	var maxTop = theXYs[3];
                                } else {
                                	var maxLeft = Math.min( maxLeft, theXYs[0] );
                                	var maxBottom = Math.min( maxBottom, theXYs[1] );
                                	var maxRight = Math.max( maxRight, theXYs[2] );
                                	var maxTop = Math.max( maxTop, theXYs[3] );
                                }
			}
			//alert(endpos);
			inData = parseRecordString(theReply, endpos);
			endpos = xmlEndPos;
			selectedData = clearLeadingSpace(inData);
			
			epos = theReply.indexOf("</FEATURE",endpos);
			if (showSelectedData) {
				//alert("2\n" + selectedData);
				var showHyper = false;
				if (hyperLinkLayers!=null) {
					for (var s1=0;s1<hyperLinkLayers.length;s1++) {
						if (hyperLinkLayers[s1] == LayerName[ActiveLayerIndex]) showHyper=true;
					}
				}
				var fName = getFieldNames(selectedData);
				var fValue = getFieldValues(selectedData);
                                 //alert(fName);
                                // Bob - The following code removes the ID and Shape fields from the fName and fValue strings
				var currentName = "";
				var currentValue = "";
				var y = 0;
				var fName1 = new Array();
				var fValue1 = new Array();
				var fName2 = new Array();
				var fValue2 = new Array();
				for(var z = 0;z<fName.length;z++) {
					currentName = fName[z];

					currentValue = fValue[z];
					if ((currentName.indexOf("SE_ROW_ID") == -1) && (currentName.indexOf(".FID") == -1)&& (currentName.indexOf("#SHAPE#") == -1) && (currentName.indexOf("#ID#") == -1)) {
						fName1[y] = currentName;
						fValue1[y] = currentValue;
						y++;
					}
				}	 
				selectPoints[selectCount] = getIdValue(fName1, fValue1);

				//now we eliminate fields without aliases listed in imsParams
				var q = 0;
				for (var f=0;f<fName1.length;f++) {
					if (useFieldAlias) {
						for (var f3=0;f3<AliasFieldName.length;f3++) {
							if (AliasFieldName[f3]==fName1[f]) {
								fName2[q] = fName1[f];
								fValue2[q] = fValue1[f];
								q++;
							}
						}
					}
				}
					
				if (selectCount==0) {
					Win1.document.write('<tr>');
					for (var f=0;f<fName2.length;f++) {
						var f2 = -1;
						if (useFieldAlias) {
							for (var f3=0;f3<AliasFieldName.length;f3++) {
								if (AliasFieldName[f3]==fName2[f]) f2=f3;
							}
						}
						if (f2!=-1) {
							Win1.document.write('<th><FONT FACE="Arial" STYLE="Bold" SIZE="-2" color="#006600">' + AliasFieldAlias[f2] + '</FONT></a></th>');
						}
					}
					Win1.document.writeln('</tr>');
				}
				Win1.document.write('<tr>');
				for (var f=0;f<fName2.length;f++) {	
					Win1.document.write('<TD valign="top">');
					var isHyper=false;
					if (showHyper) {
						for (var s1=0;s1<hyperLinkFields.length;s1++) {
							if (hyperLinkFields[s1]==fName2[f]) {
								Win1.document.write('<a href="' + fValue2[f] + '" target="_blank">');
								isHyper=true;
							}

						}
					}
					var s2 = -1;
					for (var s1=0;s1<LayerFields.length;s1++) {
						if (fName2[f]==LayerFields[s1]) s2=s1;
					}

					if (LayerFieldType[s2]=="91") {
						//alert(fName2[f]);
						if (isNaN(fValue2[f])) {
							var theDate = fValue2[f];
						} else {
							//var theDate = new Date(parseInt(fValue2[f]));
							var theDateObj = new Date(parseFloat(fValue2[f]));
                                                        // CVG Modified Date format to Locale rather than GMT
							var theDate = theDateObj.toLocaleString();
						}
						Win1.document.write('<FONT FACE="Arial" SIZE="-2">' + theDate + '</FONT>');
						theDate=null;
					} else {
						Win1.document.write('<FONT FACE="Arial" SIZE="-2" color="#006600">' + fValue2[f] + '</FONT>');
					}
					if (isHyper) Win1.document.write('</a>');
					Win1.document.writeln('</td>');
				}
				if (loadThisService == "Public_Parcel_Find" && ActiveLayer == "parcels"){
					for (var r=0;r<fName2.length;r++) {
						if (fName2[r] == "LANDR.PTAS_PARCEL_INFO.PPN") {
							var thePpnValue = fValue2[r]; 
							Win1.document.writeln('<td><input type="button" value="More Details!" onClick="closeWinFirst(' + thePpnValue + ')" style="font-size: xx-small; font-weight: bold; color: #000000; background: #ffff99;"></td>');
						}
					}
				}
				Win1.document.writeln('</tr>');
				fName1 = null;


				fValue1 = null;
				fName2 = null;
				fValue2 = null;
				
			}
			selectCount += 1;
					
		}		
		Win1.document.writeln('</table>');
		if (queryStartRecord>0) {
			var prevRecord = queryStartRecord - maxFeaturesReturned;
			if (prevRecord<0) prevRecord=0;
			Win1.document.write('<a href="javascript:' + theFrame + '.getMoreData(' + prevRecord + ')">Previous ' + maxFeaturesReturned + ' Records</a>&nbsp;&nbsp;&nbsp;');
		}
		if (stillMore) {
			var nextRecord=featureCount + queryStartRecord;
			Win1.document.writeln('<a href="javascript:' + theFrame + '.getMoreData(' + nextRecord + ')">More Records</a>');
		}
		Win1.document.writeln('</font>');		
	} else {
		Win1.document.writeln('<br>');
		Win1.document.writeln('<div align="center">');
		Win1.document.writeln('<HR width="60%">');
		Win1.document.writeln('<FONT FACE="Arial" color="white"><B>' + LayerName[ActiveLayerIndex] +'</B></font><FONT FACE="Arial" size="-2" color="white">');
		Win1.document.writeln('<br>No Features Found.');
		Win1.document.writeln('<HR width="60%"></div>');
		if (debugOn>0) {
			Win1.document.writeln('<p>Returned ArcXML Response:<br>');
			Win1.document.writeln(untag(theReply));
		} else {
			if (theError!="") {
				Win1.document.writeln('<p>Server returned:<br>');
				Win1.document.writeln(theError);
			}
		}	
		Win1.document.writeln('</FONT>');
	}
	
}

//part of automated identify sequence. Places closing set of HTML code for document
function generateEndHTML(){
	Win1 = identifyWin;
	Win1.document.writeln('</center></body></html>');
	Win1.document.close();
	identifyWin = null;		
}

function autoIdentify(autox, autoy) {
	//one-time automatic identify
	highlightedOne="";
	//var theX = autox;
	//var theY = autoy;
	//getMapXY(theX,theY);
	mapX = autox;
	mapY = autoy;
	//searchTolerance = (xDistance/iWidth) * pixelTolerance;
	//searchTolerance = (xDistance/iWidth) * 5;
	//searchTolerance is usually 1634
	searchTolerance = 5;
	var tempWest = autox - searchTolerance;
	var tempNorth = autoy + searchTolerance;
	var tempEast = autox + searchTolerance;
	var tempSouth = autoy - searchTolerance;
	var theString = writeGetFeatures(tempWest,tempSouth,tempEast,tempNorth);
	// alert(theString);
	showRetrieveData();
	sendToServer(imsQueryURL,theString,identifyXMLMode);
}

// hyperlink from feature
function hyperLink(e) {
	if (currentHyperLinkLayer!="") {
		highlightedOne="";
		var theX = mouseX;
		var theY = mouseY;
		getMapXY(theX,theY);
		searchTolerance = (xDistance/iWidth) * pixelTolerance;
		var tempWest = mapX - searchTolerance;
		var tempNorth = mapY - searchTolerance;
		var tempEast = mapX + searchTolerance;
		var tempSouth = mapY + searchTolerance;
		var tempSwap = swapSelectFields;
		swapSelectFields=false;
		var tempSelect = selectFields;
		selectFields = LayerIDField[ActiveLayerIndex] + " " + LayerShapeField[ActiveLayerIndex] + " " + currentHyperLinkField;
		var theString = writeGetFeatures(tempWest,tempSouth,tempEast,tempNorth);
		selectFields = tempSelect;
		swapSelectFields=tempSwap;
		showRetrieveData();
		sendToServer(imsQueryURL,theString,hyperlinkXMLMode);
	} else {
		alert("This layer does not have any HyperLinks.");
	}
}

// write out XML request to identify features
function writeGetFeatures(west1,south1,east1,north1) {
	if (swapSelectFields) {
		selectFields=selFieldList[ActiveLayerIndex];
	}
	var useString = writeIdentifyXML(ActiveLayer,ActiveLayerType,selectFields,west1,south1,east1,north1,useLimitExtent);
	hightlightedOne="";
	return useString;
}

function writeIdentifyXML(theLayer,theLayerType,theFields,leftX,bottomY,rightX,topY,hasLimit) {
	//alert(theLayer);
	if (runningVoterSearch && theLayer == "WardsPrecincts") {
		var theString = '<?xml version="1.0" encoding="UTF-8"?><ARCXML VERSION="1.1">\n<REQUEST>\n<GET_FEATURES outputmode="xml" envelope="true" globalenvelope="true" geometry="false">\n';
	} else {
		var theString = '<?xml version="1.0" encoding="UTF-8"?><ARCXML VERSION="1.1">\n<REQUEST>\n<GET_FEATURES outputmode="xml" envelope="false" geometry="false">\n';
	}
	theString += '<LAYER id="' + theLayer + '" />';
	theString += '<SPATIALQUERY subfields="' + theFields + '">';
	theString += '<SPATIALFILTER relation="area_intersection" >';
	theString += '<ENVELOPE maxy="' + topY + '" maxx="' + rightX + '" miny="' + bottomY + '" minx="' + leftX + '" />';
	theString += '</SPATIALFILTER>';
	theString += '</SPATIALQUERY>';
	if (hasLimit) {
		// keep this within the limitExtent
		theString += '<SPATIALFILTER relation="area_intersection">\n';
		theString += '<ENVELOPE maxx="' + limitRight + '" maxy="' + limitTop + '" minx="' + limitLeft + '" miny="' + limitBottom + '" />\n';
		theString += '</SPATIALFILTER>\n';
	}
	theString += '</GET_FEATURES>';
	theString += '</REQUEST>';
	theString += '</ARCXML>';
	return theString;

}

// parse XML response for selected features
function displayAttributeData(theReply) {
	//alert(theReply);
	//alert("bufGetAttribute: " + bufGetAttribute);
	if (bufGetAttribute) {
		setLayerFields(bufferTargetLayerIndex);
	} else {
		setLayerFields(ActiveLayerIndex);
	}
	//alert("aimsselectpresent: "+aimsSelectPresent);
	//alert("AliasFieldName: " + AliasFieldName);
	var theError = getXMLErrorMessage(theReply);
	var fList="";
	var lpos1 = 1;
	var lpos2 = 1;
	var epos = 1;
	var spos = 1;
	var morePoints=true;
	var moreFeatures=true;
	var featureCount = justGetFeatureCount(theReply);
	//alert(featureCount);
	var pos = 0;
	var startpos = 0;
	var endpos = xmlEndPos;
	var stillMore = false
	pos = theReply.indexOf('hasmore="true"',endpos);
	if (pos!=-1) stillMore = true;
	pos=0;
	var tempCount = 0;
	var selectedData="";
	var inData="";
	var xStr="";
	var yStr="";
	var eNorth="";
	var eSouth="";
	var eWest="";
	var eEast="";
	var fCount = featureCount;
	//alert("displayAttributeData()[featurecount=" + featureCount + "]");
	selectCount = 0;
	var tempString="";
	var Win1 = parent.TextFrame;
	var theFrame = "parent.MapFrame";
	if (featureCount > 0) {
		storedReply = theReply;
		newSelectCount += 1;
		if ((toolMode == 7) && (areaQueryStage == 1)) {
			//we made it this far...
			if (areaQueryMode == "geocode") {
				var startpos = -1;
				var endpos = -1;
				startpos = theReply.indexOf("PPN=");
				endpos = theReply.indexOf('"',(startpos + 6));
				setQueryString = "PPN=&apos;" + theReply.slice(startpos+5,endpos) + "&apos;";
				//now we check for a second match. If there is one, there's a problem.
				startpos = -1;
				startpos = theReply.indexOf("PPN=",endpos);
				if (startpos != -1) alert("There were two or more matches here. You may not buffer around the exact parcel you want");
			}
			selectCount = 1;
			areaQueryStage = 2;
			var Win1 = window.open(appDir+"comparablesales.htm","StandardQueryWindow","left=120,top=400,width=650,height=175,scrollbars=yes,resizable=yes");
			Win1 = null;
			hideRetrieveMap();
			hideRetrieveData();
			return;
		}

		if (showSelectedData) {
			//alert("displayAttributeData()[opening html page]");
			if ((useExternalWindow) || (!useTextFrame)) {
				Win1 = window.open("","QueryWindow","left=120,top=400,width=575,height=200,scrollbars=yes,resizable=yes");
				Win1.resizeTo(950,200);
				Win1.moveTo(10,500);
				theFrame = "opener";
				if (parent.MapFrame!=null) theFrame = "opener.parent.MapFrame";
			} else {
				Win1 = parent.TextFrame;
				Win1.document.open();
			}
			Win1.document.open();
			Win1.document.writeln('<html><head><title>Query/Selection Results</title>');
			Win1.document.writeln('<SCRIPT TYPE="text/javascript" LANGUAGE="JavaScript">');
			Win1.document.writeln('var t;');
			Win1.document.writeln('var par;');
			Win1.document.writeln(' if (opener) {  ');
			Win1.document.writeln(' 	if (opener.name=="MapFrame") {  ');
			Win1.document.writeln(' 		t = opener.parent.MapFrame;  ');
			Win1.document.writeln('			par = opener.parent;  ');
			Win1.document.writeln(' 	} else {  ');
			Win1.document.writeln('	        	t = opener; ');
			Win1.document.writeln('			par = opener;  ');
			Win1.document.writeln('		}  ');
			Win1.document.writeln(' } else {  ');
			Win1.document.writeln('		if (parent.MapFrame) {  ');
			Win1.document.writeln('			t = parent.MapFrame;  ');
			Win1.document.writeln('			par = parent;  ');
			Win1.document.writeln('		} else {  ');
			Win1.document.writeln('			t=document;  ');
			Win1.document.writeln('		}  ');
			Win1.document.writeln('	}  ');
			Win1.document.writeln('</SCRIPT></head>');
			//Win1.document.writeln('<body bgcolor=#006600 text="#006600" link="Red" vlink="Blue" LEFTMARGIN=0 onload="window.focus()" onunload="par.MapFrame.clearSelection()">');
			Win1.document.writeln('<body bgcolor=#006600 text="#006600" link="Red" vlink="Blue" LEFTMARGIN=0 onload="window.focus()">');
			Win1.document.writeln('<SCRIPT TYPE="text/javascript" LANGUAGE="JavaScript">');
			Win1.document.writeln('var srtTextID=""');
			Win1.document.writeln('function CVGprint() {');
			Win1.document.writeln('// CVG function to parse out HTML table and create a printable report document.');
			Win1.document.writeln('//alert("Print Function")'); 

			Win1.document.writeln('}');
			Win1.document.writeln('function loadHelp() {');
			Win1.document.writeln('var Win2;');
			Win1.document.writeln('Win2 = window.open("http://'+hostName+'/website/KCRC/helpIdentifyResults.htm","Help","width=800,height=550,scrollbars=yes,resizable=yes");');
			Win1.document.writeln('Win2 = null;');
			Win1.document.writeln('}');
			Win1.document.writeln('function extract() {');
			Win1.document.writeln('    if (document.all){');
			Win1.document.writeln('    var aryHead = new Array();');
			Win1.document.writeln('    var aryCells = new Array();');
			Win1.document.writeln('    var aryCount=0');
			Win1.document.writeln('        for (var i=0;i < parent.TextFrame.document.all.length; i++){');
			Win1.document.writeln('		//alert(parent.TextFrame.document.all(i).tagName);');
			Win1.document.writeln('            if (parent.TextFrame.document.all(i).tagName == "TH"){');
			Win1.document.writeln('              aryHead[aryCount] = parent.TextFrame.document.all(i).outerHTML');
			Win1.document.writeln('              aryCount++');
			Win1.document.writeln('            } ');
			Win1.document.writeln('         }');
			Win1.document.writeln('         aryCount = 0');
			Win1.document.writeln('         for (var i=0;i < parent.TextFrame.document.all.length; i++){');
			Win1.document.writeln('            if (parent.TextFrame.document.all(i).tagName == "TD"){');
			Win1.document.writeln('               aryCells[aryCount] = parent.TextFrame.document.all(i).outerHTML');
			Win1.document.writeln('              aryCount++');
			Win1.document.writeln('            } ');
			Win1.document.writeln('         } ');   
			Win1.document.writeln('      formatTable(aryHead,aryCells);');
			Win1.document.writeln('    }');
			Win1.document.writeln('}');

			Win1.document.writeln('function formatTable(aryHead,aryCells) {');
			Win1.document.writeln('  alert(aryHead,aryCells);');
			Win1.document.writeln('  strTextID = "<TABLE width=\'600\' bgColor=white border=1 cellPadding=0 cellSpacing=0><TBODY>";');
			Win1.document.writeln('  numMax = Math.ceil(aryHead.length / 8)');
			Win1.document.writeln('  numLimit1 = 0');
			Win1.document.writeln('  numLimit2 = 0');
			Win1.document.writeln('  numRunningTotal1 = 0');
			Win1.document.writeln('  numRunningTotal2 = 0');
			Win1.document.writeln('  rowNumber = 0');
			Win1.document.writeln('  //alert(aryHead.length);');
			Win1.document.writeln('  if (aryHead.length <= 8) {');
                        Win1.document.writeln('    //alert("Case 1");');
			Win1.document.writeln('    for (var j=0;j < numMax;j++){');
			Win1.document.writeln('      strTextID += "<TR>"');
			Win1.document.writeln('      for (numRunningTotal1;numRunningTotal1 < aryHead.length; numRunningTotal1++){');
			Win1.document.writeln('        numLimit1++');
			Win1.document.writeln('        strTextID += aryHead[numRunningTotal1]');

			Win1.document.writeln('      }');
			Win1.document.writeln('      numRunningTotal1++');
			Win1.document.writeln('      numLimit1 = 0');
			Win1.document.writeln('      strTextID += "</TR>"');
			Win1.document.writeln('      for (numRunningTotal2;numRunningTotal2 < aryCells.length; numRunningTotal2++){');
			Win1.document.writeln('        numLimit2++');
			Win1.document.writeln('        strTextID += aryCells[numRunningTotal2]');
			Win1.document.writeln('        if (numLimit2 == 8 || numLimit2 == aryHead.length) {');
			Win1.document.writeln('          numLimit2 = 0');
			Win1.document.writeln('          strTextID += "</TR><TR>"');
			Win1.document.writeln('        }');
			Win1.document.writeln('      }');
			Win1.document.writeln('      strTextID += "</TR>"');
			Win1.document.writeln('    }');
			Win1.document.writeln('  } else { ');
                        Win1.document.writeln('    //alert("Case 2");');
                        Win1.document.writeln('    alert("More than eight attributes present.  Unable to print.");');
                        Win1.document.writeln('    return;');
			Win1.document.writeln('    for (var j=0;j < numMax;j++){');
			Win1.document.writeln('      strTextID += "<TR>"');
			Win1.document.writeln('      for (numRunningTotal1;numRunningTotal1 < aryHead.length; numRunningTotal1++){');
			Win1.document.writeln('        numLimit1++');
			Win1.document.writeln('        strTextID += aryHead[numRunningTotal1]');
			Win1.document.writeln('        if ((numLimit1 % 8 == 0) || numLimit1 == aryHead.length) {');
			Win1.document.writeln('          strTextID += "</TR><TR>"');
			Win1.document.writeln('          startCol = numLimit1 - 7');
			Win1.document.writeln('          //alert("Start Col: " + startCol)');
			Win1.document.writeln('          endCol = numLimit1');
			Win1.document.writeln('          //alert("End Col: " + endCol)');
			Win1.document.writeln('          //alert("Row Number: " + rowNumber)');
			Win1.document.writeln('          for (numRunningTotal2;numRunningTotal2 < aryCells.length; numRunningTotal2++){');
			Win1.document.writeln('            for (colCheck = startCol;colCheck < endCol; colCheck++){');
			Win1.document.writeln('              //alert("RowNumber: " + rowNumber);');
			Win1.document.writeln('              //alert("Head Length: " + aryHead.length);');
			Win1.document.writeln('              //alert("col Check: " + colCheck);');
			Win1.document.writeln('              //alert("Running Total: " + numRunningTotal2);');
			Win1.document.writeln('              //alert((((rowNumber - 1) * aryHead.length) + colCheck));');
			Win1.document.writeln('              if (numRunningTotal2 == (((rowNumber * aryHead.length) + colCheck)) - 1) {');
			Win1.document.writeln('                strTextID += aryCells[numRunningTotal2]');
			Win1.document.writeln('              }');
			Win1.document.writeln('            }');
			Win1.document.writeln('            if ((numRunningTotal2 == 8) || (numRunningTotal2 % 8 == 0 && numRunningTotal2 != 0)) {');
			Win1.document.writeln('              rowNumber++');
			Win1.document.writeln('              strTextID += "</TR><TR>"');
			Win1.document.writeln('            }');
			Win1.document.writeln('          }');
			Win1.document.writeln('        }');
			Win1.document.writeln('      }');
			Win1.document.writeln('    }');
			Win1.document.writeln('  }');
			Win1.document.writeln(' strTextID += "</TBODY></TABLE>"');
			Win1.document.writeln(' writePage();');
			Win1.document.writeln('}');
                        Win1.document.writeln(' ');
			Win1.document.writeln('function trapper(curfunction) {');
			Win1.document.writeln(' if (t.loading) {');
			Win1.document.writeln('		alert("A request is currently pending with the IMS server. This is indicated by the spinning globe in the middle of the screen. When the globe disappears, you will be free to use this button.")');
			Win1.document.writeln('		return;');
			Win1.document.writeln('	}');
			Win1.document.writeln(' if(t.toolMode == 35) t.publicSelCleared = true;  ');
			Win1.document.writeln('	t.clickFunction(curfunction);');
			Win1.document.writeln(' //window.close();  ');
			Win1.document.writeln('}');
			Win1.document.writeln('function writePage() {');
                        Win1.document.writeln('Win2 = window.open("","ReportWindow","width=675,height=240,scrollbars,resizable,alwaysRaised,toolbar");');
			Win1.document.writeln('Win2.document.writeln("<html><head><title>Query/Selection Results</title></head>");');
			Win1.document.writeln('Win2.document.writeln(strTextID);');
			Win1.document.writeln('}');
			Win1.document.writeln('function closeWinFirst(thePPNValue) {   ');
			Win1.document.writeln('		t.accessKentTransfer(thePPNValue) ');
			Win1.document.writeln('		//window.close();		');
			Win1.document.writeln('	} ');
			Win1.document.writeln('</SCRIPT>');

                        // CVG Added Code to add a print button to the Table View 
                        Win1.document.writeln('<div align="left">');	
                        Win1.document.writeln('<input type="image" src="'+appPath+appDir+'images/smallprint1.gif" width="16" height="16" border=0 alt="Print this table" onclick="t.tablePrint();" onmouseover="window.status=\'Print this table\'" > </a>');
			if ((toolMode == 5) && (LayerName[ActiveLayerIndex] == "Parks")) {
				Win1.document.writeln('<center><FONT COLOR="White" FACE="Arial"><b>Parks in '+communityString+'</b>');
			} else if ((toolMode == 7) && (areaQueryStage == 2)) {
				Win1.document.writeln('<center><FONT COLOR="White" FACE="Arial"><b>All available sales data on parcels within '+resultPrintDistance+' '+resultPrintUnits+' of '+resultPrintSource+'</b>');
			} else if (bufGetAttribute) {
				Win1.document.writeln('<center><FONT COLOR="White" FACE="Arial"><b>' + LayerName[bufferTargetLayerIndex] + '</b>');
			} else {	
			Win1.document.write('<center><FONT COLOR="White" FACE="Arial"><b>Results from ' + LayerName[ActiveLayerIndex] + '</b></font>');
			if (isPublic) Win1.document.write('&nbsp;&nbsp;&nbsp;&nbsp;<img src="http://'+hostName+'/website/KCRC/KCRC_Images/buttonnarr_help.gif" width=20 height=20 hspace=1 vspace=1 border=0 alt="Help" name="help" onmousedown="loadHelp()">');
			}
			if (toolMode != 4 && featureCount > 1) Win1.document.writeln('<br><font color="FFFFFF">Click on a magnifying glass icon to view that feature on the Map</font>');
			else if (toolMode != 4 && featureCount == 1) Win1.document.writeln('<br><font color="FFFFFF">Please wait while we zoom in to this feature!</font>');
			Win1.document.writeln('<table border="1" cellspacing="0" cellpadding="2" nowrap bgcolor=#ffff99>');
		}
		endpos = 1;
		var intEndPos = theReply.lastIndexOf("</FEATURE>");
		var strReplyEnd = theReply.slice(intEndPos);
		var intEnvelopePos = strReplyEnd.indexOf("<ENVELOPE");
		if (intEnvelopePos != -1) {
			//that's a global envelope: let's use that
			//alert("using global envelope");
			var intStartPos = strReplyEnd.indexOf('minx="');
			var intNextPos = strReplyEnd.indexOf('"',intStartPos+7);
			customLeft = strReplyEnd.slice(intStartPos+6,intNextPos);
			intStartPos = strReplyEnd.indexOf('miny="');
			intNextPos = strReplyEnd.indexOf('"',intStartPos+7);
			customBottom = strReplyEnd.slice(intStartPos+6,intNextPos);
			intStartPos = strReplyEnd.indexOf('maxx="');
			intNextPos = strReplyEnd.indexOf('"',intStartPos+7);
			customRight = strReplyEnd.slice(intStartPos+6,intNextPos);
			intStartPos = strReplyEnd.indexOf('maxy="');
			intNextPos = strReplyEnd.indexOf('"',intStartPos+7);
			customTop = strReplyEnd.slice(intStartPos+6,intNextPos);
			useCustomCoords = true;
			
		} 
		for (var i=0;i<fCount;i++) {
			//alert(endpos);
			if (toolMode!=4) {
				var theXYs = getEnvelopeXYs(theReply, endpos)
				selectLeft[selectCount] = theXYs[0];
				selectBottom[selectCount] = theXYs[1];
				selectRight[selectCount] = theXYs[2];
				selectTop[selectCount] = theXYs[3];
				endpos = xmlEndPos;
                                 
                                // CVG Code added to Zoom to Extent of selected features - CVG
                                if( i == 0 ) {
                                	var maxLeft = theXYs[0];
                                	var maxBottom = theXYs[1];
                                	var maxRight = theXYs[2];
                                	var maxTop = theXYs[3];
                                } else {
                                	var maxLeft = Math.min( maxLeft, theXYs[0] );
                                	var maxBottom = Math.min( maxBottom, theXYs[1] );
                                	var maxRight = Math.max( maxRight, theXYs[2] );
                                	var maxTop = Math.max( maxTop, theXYs[3] );
                                }
			}
			//alert(endpos);
			inData = parseRecordString(theReply, endpos);
			endpos = xmlEndPos;
			selectedData = clearLeadingSpace(inData);
			
			epos = theReply.indexOf("</FEATURE",endpos);
			if (showSelectedData) {
				//alert("2\n" + selectedData);
				var showHyper = false;
				if (hyperLinkLayers!=null) {
					for (var s1=0;s1<hyperLinkLayers.length;s1++) {
						if (hyperLinkLayers[s1] == LayerName[ActiveLayerIndex]) showHyper=true;
					}
				}
				var fName = getFieldNames(selectedData);
				var fValue = getFieldValues(selectedData);
                                 //alert(fName);
                                // Bob - The following code removes the ID and Shape fields from the fName and fValue strings
				var currentName = "";
				var currentValue = "";
				var y = 0;
				var fName1 = new Array();
				var fValue1 = new Array();
				var fName2 = new Array();
				var fValue2 = new Array();
				for(var z = 0;z<fName.length;z++) {
					currentName = fName[z];

					currentValue = fValue[z];
					if ((currentName.indexOf("SE_ROW_ID") == -1) && (currentName.indexOf(".FID") == -1)&& (currentName.indexOf("#SHAPE#") == -1) && (currentName.indexOf("#ID#") == -1)) {
						fName1[y] = currentName;
						fValue1[y] = currentValue;
						y++;
					}
				}	 
				selectPoints[selectCount] = getIdValue(fName1, fValue1);

				//now we eliminate fields without aliases listed in imsParams
				var q = 0;
				for (var f=0;f<fName1.length;f++) {
					if (useFieldAlias) {
						for (var f3=0;f3<AliasFieldName.length;f3++) {
							if (AliasFieldName[f3]==fName1[f]) {
								fName2[q] = fName1[f];
								fValue2[q] = fValue1[f];
								q++;
							}
						}
					}
				}
					
				if (selectCount==0) {
					Win1.document.write('<tr><th><FONT FACE="Arial" SIZE="-2" color="#006600">Rec</FONT></a></th>');
					for (var f=0;f<fName2.length;f++) {
						var f2 = -1;
						if (useFieldAlias) {
							for (var f3=0;f3<AliasFieldName.length;f3++) {
								if (AliasFieldName[f3]==fName2[f]) f2=f3;
							}
						}
						if (f2!=-1) {
							Win1.document.write('<th><FONT FACE="Arial" STYLE="Bold" SIZE="-2" color="#006600">' + AliasFieldAlias[f2] + '</FONT></a></th>');
						}
					}
					Win1.document.writeln('</tr>');
				}
				Win1.document.write('<tr><td>');
				if (toolMode!=4) Win1.document.write('<a href="javascript:' + theFrame + '.showHighlight(' + selectCount + ')">');
				if (toolMode == 4) Win1.document.write('<FONT FACE="Arial" SIZE="-2">' + (selectCount+queryStartRecord+1) + '</FONT>');
				if (toolMode!=4) Win1.document.write('<img src="'+appPath+appDir+'images/smallzoomin1.gif" width=17 height=15 border=0>');
				if (toolMode!=4) Win1.document.write('</a>');
				Win1.document.writeln('</td>');
				for (var f=0;f<fName2.length;f++) {	
					Win1.document.write('<TD valign="top">');
					var isHyper=false;
					if (showHyper) {
						for (var s1=0;s1<hyperLinkFields.length;s1++) {
							if (hyperLinkFields[s1]==fName2[f]) {
								Win1.document.write('<a href="' + fValue2[f] + '" target="_blank">');
								isHyper=true;
							}

						}
					}
					var s2 = -1;
					for (var s1=0;s1<LayerFields.length;s1++) {
						if (fName2[f]==LayerFields[s1]) s2=s1;
					}

					if (LayerFieldType[s2]=="91") {
						//alert(fName2[f]);
						if (isNaN(fValue2[f])) {
							var theDate = fValue2[f];
						} else {
							//var theDate = new Date(parseInt(fValue2[f]));
							var theDateObj = new Date(parseFloat(fValue2[f]));
                                                        // CVG Modified Date format to Locale rather than GMT
							var theDate = theDateObj.toLocaleString();
						}
						Win1.document.write('<FONT FACE="Arial" SIZE="-2">' + theDate + '</FONT>');
						theDate=null;
					} else {
						Win1.document.write('<FONT FACE="Arial" SIZE="-2" color="#006600">' + fValue2[f] + '</FONT>');
					}
					if (isHyper) Win1.document.write('</a>');
					Win1.document.writeln('</td>');
				}
				if (loadThisService == "Public_Parcel_Find" && ActiveLayer == "parcels"){
					for (var r=0;r<fName2.length;r++) {
						if (fName2[r] == "LANDR.PTAS_PARCEL_INFO.PPN") {
							var thePpnValue = fValue2[r]; 
							Win1.document.writeln('<td><input type="button" value="More Details!" onClick="closeWinFirst(' + thePpnValue + ')" style="font-size: xx-small; font-weight: bold; color: #000000; background: #ffff99;"></td>');
						}
					}
				}
				Win1.document.writeln('</tr>');
				fName1 = null;


				fValue1 = null;
				fName2 = null;
				fValue2 = null;
				
			}
			selectCount += 1;
					
		}
		if (showSelectedData) {			
			Win1.document.writeln('</table>');
			if (toolMode != 4) Win1.document.writeln('<Font color="white">Records '+queryStartRecord+' to '+(queryStartRecord+featureCount)+'</font><br>');
			if (queryStartRecord>0) {
				var prevRecord = queryStartRecord - maxFeaturesReturned;
				if (prevRecord<0) prevRecord=0;
				Win1.document.write('<a href="javascript:' + theFrame + '.getMoreData(' + prevRecord + ')">Previous ' + maxFeaturesReturned + ' Records</a>&nbsp;&nbsp;&nbsp;');
			}
			if (stillMore) {
				var nextRecord=featureCount + queryStartRecord;
				Win1.document.writeln('<a href="javascript:' + theFrame + '.getMoreData(' + nextRecord + ')">More Records</a>');
			}
			Win1.document.writeln('</table></font>');
			Win1.document.writeln('<form>');
			if (toolMode == 5) {
				parent.MapFrame.publicSelCleared = false;
				Win1.document.writeln('<br><br><input type="button" onclick="trapper(\'zoomcommunity\');" value="Locate Another Community" style="font-size: xx-small; font-weight: bold; color: #000000; background: #ffff99;">');
			}
			if (toolMode == 35) {
				Win1.document.writeln('<br><br><input type="button" onclick="trapper(\'geocode\');" value="Locate Another Address" style="font-size: xx-small; font-weight: bold; color: #000000; background: #ffff99;">');
			}
			if (toolMode == 14) {
				Win1.document.writeln('<br><input type="button" onclick="trapper(\'busfind\');" value="Locate Another Bus Stop/Route" style="font-size: xx-small; font-weight: bold; color: #000000; background: #ffff99;">');
			}
			if (toolMode == 18) {
				Win1.document.writeln('<br><input type="button" onclick="trapper(\'parkfind\');" value="Locate Another Park/Trail" style="font-size: xx-small; font-weight: bold; color: #000000; background: #ffff99;">');
			}
			if (isPublic) {
				if ((toolMode == 5) && ((loadThisService == "Public_PlannedLanduse") || (loadThisService == "Public_Zoning"))) {
					//nothing in this case
				}
				else if (toolMode == 4) {
					//identify mode - nothing selected
				} else {
					Win1.document.writeln('<input type="button" onclick="par.MapFrame.clearSelection()" value="Remove Red Outline/Yellow Highlight" style="font-size: xx-small; font-weight: bold; color: #000000; background: #ffff99;">');
				}
			}
			Win1.document.writeln('</form></center></body></html>');
			Win1.document.close();
		}		
		
		if ((queryStartRecord==0) && (toolMode!=4) && (toolMode!=9)) {
                        // CVG Added code to zoom to selected features
			if (((selectCount==1) && (zoomToSingleSelect)) || (ZoomToSelected == 1)) {
				// CVG - property/street search, zoom to selected extent
                                if ( ZoomToSelected == 1) {
                                	var fWidth = maxRight - maxLeft;
                                	var fHeight = maxTop - maxBottom;
                                } else { 
		                	var fWidth = selectRight[0] - selectLeft[0];
		                	var fHeight = selectTop[0] - selectBottom[0];
                                }
				var mWMargin = 0;
				var mHMargin = 0;
				if (selectType=="point") {			
					mWMargin = fullWidth * selectPointMargin;
					mHMargin = fullHeight * selectPointMargin;
					if (mWMargin > xDistance/2) {
						mWMargin = xDistance/2;
						mHMargin = yDistance/2;
					}
				} else {
					mWMargin = fWidth * selectMargin;
					mHMargin = fHeight * selectMargin; 
				}
				saveLastExtent();
                                if ( ZoomToSelected == 1 ) {
                                	// CVG: property/street search, zoom to selected extent
                                	left = maxLeft - mWMargin;


                                	right = maxRight + mWMargin;
                                	top = maxTop + mHMargin;
                                	bottom = maxBottom - mHMargin;
                                } else {
  					left = selectLeft[0] - mWMargin;
					right = selectRight[0] + mWMargin;
					top = selectTop[0] + mHMargin;
					bottom = selectBottom[0] - mHMargin;
                                }
			}
			zoomToSingleSelect = true;
			if ((toolFive) && (selectCount > 1)) {
				switch(communityParkValue) {
				case "VSP":
					customLeft = 12754101.1234;
					customBottom = 600468.2517;
					customRight = 12774618.6473;
					customTop = 611843.0935;
					break;
				case "CED":
					customLeft = 12794863.9292;
					customBottom = 623090.6942;
					customRight = 12817515.0391;
					customTop = 635411.3816;
					break;
				case "CRT":
					customLeft = 12786284.5571;
					customBottom = 587325.1603;
					customRight = 12860989.6599;
					customTop = 627959.7351;
					break;
				case "GRT":
					customLeft = 12759332.1405;
					customBottom = 524641.5115;
					customRight = 12830058.5202;
					customTop = 563111.9272;
					break;
				case "LWT":
					customLeft = 12822292.9953;
					customBottom = 493848.8300;
					customRight = 12886746.2497;
					customTop = 529581.4838;
					break;
				case "SOL":
					customLeft = 12757315.5334;
					customBottom = 622205.0135;
					customRight = 12824028.8160;
					customTop = 659190.6188;
					break;
			}
			legendVisible = true;
			saveLastExtent();
			useCustomCoords = true;				
			sendMapXML();
			}
			else sendMapXML();
		}	
	} else {
		//alert(toolMode);
		//alert(tempString);
		if ((toolMode == 9) || (toolMode == 35) || (toolMode == 14)) {
			alert("No matches found. Try a different search."); 
			if (toolMode == 9) parent.MapFrame.clickFunction("find");
			if (toolMode == 35) parent.MapFrame.clickFunction("geocode");
			if (toolMode == 14) parent.MapFrame.clickFunction("busfind");
			if (toolMode == 5) parent.MapFrame.clickFunction("zoomcommunity");	
		} else {
			if ((useExternalWindow) || (!useTextFrame)) {
				Win1 = window.open("","QueryWindow","width=575,height=120,scrollbars=yes,resizable=yes");
			} else {
				Win1 = parent.TextFrame;
				Win1.document.open();

			}
			Win1.document.writeln('<html><head>');
			Win1.document.writeln('	<title>Select Results</title>');
			Win1.document.writeln('</head>');
			Win1.document.writeln('<body BGCOLOR=#006600 TEXT="WHITE" LEFTMARGIN=0 TOPMARGIN=0>');
			Win1.document.writeln('<HR width="60%">');
			Win1.document.writeln('<div align="center">');
			Win1.document.writeln('<FONT FACE="Arial"><B>' + LayerName[ActiveLayerIndex] +'</B></font><FONT FACE="Arial" size="-2">');
			Win1.document.writeln('<br>No Features Found.</div>');
			Win1.document.writeln('<HR width="60%">');
			if (debugOn>0) {
				Win1.document.writeln('<p>Returned ArcXML Response:<br>');
				Win1.document.writeln(untag(theReply));
			} else {
				if (theError!="") {
					Win1.document.writeln('<p>Server returned:<br>');
					Win1.document.writeln(theError);
				}
			}	
			Win1.document.writeln('</FONT>');
			Win1.document.writeln('</body></html>');
			Win1.document.close();
		}
	}
	
	hideRetrieveData();
	//don't know why this stuff is here. We'll block it off for now.
	return;
	if ((toolMode==4) || (toolMode==9))  selectCount=0;
	Win1=null;
	if(bufGetAttribute) {
		bufGetAttribute = false;
		sendMapXML();
	}
}



function parseHyperLink(theReply) {
	//alert(theReply);
	var fList="";
	var lpos1 = 1;
	var lpos2 = 1;
	var pos = 0;
	var startpos = 0;
	var endpos = 0;
	var fString = theReply.substring(startpos,endpos);
	var featureCount = justGetFeatureCount(theReply);
	var linkString = "width=" + hyperlinkWindowWidth + ",height=" + hyperlinkWindowHeight + ",scrollbars=yes,resizable=yes"
	var selectedData="";
	var fCount = featureCount;
	//alert("displayAttributeData()[featurecount=" + featureCount + "]");
	selectCount = 0;
	var tempString="";
	if (featureCount > 0) {
		var searchStr = currentHyperLinkField + "=";
		
		newSelectCount += 1;

		endpos = 1;
		pos = theReply.indexOf(searchStr,1);
		startpos = pos + searchStr.length + 1;
		endpos =theReply.indexOf(dQuote,startpos);
		inData = theReply.substring(startpos,endpos);
		if (parent.TextFrame!=null) {
			parent.TextFrame.document.open();
			parent.TextFrame.document.writeln('<html><head>');
			parent.TextFrame.document.writeln('	<title>Select Results</title>');
			parent.TextFrame.document.writeln('</head>');
			parent.TextFrame.document.writeln('<body BGCOLOR="White" TEXT="Black" LEFTMARGIN=0 TOPMARGIN=0>');
			parent.TextFrame.document.writeln('<FONT FACE="Arial"><B>' + LayerName[ActiveLayerIndex] +'</B></font><FONT FACE="Arial" size="-2">');
			parent.TextFrame.document.writeln('<br>HyperLink to ' + inData );
			parent.TextFrame.document.writeln('</FONT>');
			parent.TextFrame.document.writeln('</body></html>');
			parent.TextFrame.document.close();
		}
		var Win1=open(inData,"",linkString);
	} else {
	
		//alert(tempString);
		if (parent.TextFrame!=null) {
			parent.TextFrame.document.open();
			parent.TextFrame.document.writeln('<html><head>');
			parent.TextFrame.document.writeln('	<title>Select Results</title>');
			parent.TextFrame.document.writeln('</head>');
			parent.TextFrame.document.writeln('<body BGCOLOR="White" TEXT="Black" LEFTMARGIN=0 TOPMARGIN=0>');
			parent.TextFrame.document.writeln('<FONT FACE="Arial"><B>' + LayerName[ActiveLayerIndex] +'</B></font><FONT FACE="Arial" size="-2">');
			parent.TextFrame.document.writeln('<br>Unable to hyperlink with submitted request.');
			if (debugOn>0) {
				parent.TextFrame.document.writeln('<p>Returned ArcXML Response:<br>');
				parent.TextFrame.document.writeln(untag(theReply));
			}
			parent.TextFrame.document.writeln('</FONT>');
			parent.TextFrame.document.writeln('</body></html>');
			parent.TextFrame.document.close();


		} else {
			var msg = "Unable to hyperlink.";
			if (debugOn>0) {
				msg = msg + "\nServer ArcXML response:\n" + theReply;
			}
			alert(msg);
		}
	}
	hideRetrieveData();
}

// are there any selected features?
function checkSelected() {
	var isOk = false;
	if (selectCount>0) isOk = true;
	return isOk;
}

function checkHyperLinkLayer(layerIndex) {
	var canLink = false;
	//alert(hyperLinkLayers.length);
	for (var i=0; i<hyperLinkLayers.length; i++) {
			if (LayerName[layerIndex]==hyperLinkLayers[i]) {
				canLink=true;
				currentHyperLinkLayer=LayerName[layerIndex];
				currentHyperLinkField=hyperLinkFields[i];
			}
	}
	return canLink;
}

