// 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
*/

//alert("You made it Here");

aimsIdentifyPresent=true;

// hyperlink variables
var currentHyperLinkLayer="";
var currentHyperLinkField="";
var hyperlinkWindowWidth=500;
var hyperlinkWindowHeight=400;
var parcelIDvalue = "";

// 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();

var selectedParcels = new Array();

/*
***************************************************************************************

Identify functions 

***************************************************************************************
*/

// identify feature
function identify(e) {
	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 theString = writeGetFeatures(tempWest,tempSouth,tempEast,tempNorth);
	//alert(theString);
	showRetrieveData();
	
	//<script language="JavaScript">
	//START "LOADING DATA" ANIMATED GIF
	parent.MapFrame.showLayer('LoadData');
	//</script>
	
	//showLayer("LoadData");
	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();
		//showLayer("LoadData");
		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) {
	var theString = '<ARCXML VERSION="1.0.1">\n<REQUEST>\n<GET_FEATURES outputmode="xml" envelope="true" 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(toolMode);
	setLayerFields(ActiveLayerIndex);
	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";
	var arrayCounter = 0;
	var INValue = "";
	if (featureCount > 0) {
		newSelectCount += 1;


		if ((showSelectedData) && (toolMode != 9)) {
			//alert("displayAttributeData()[opening html page]");
			if ((useExternalWindow) || (!useTextFrame)) {
				Win1 = window.open("","QueryWindow","width=575,height=120,scrollbars=yes,resizable=yes");
				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></head>');
//			Win1.document.writeln('<body bgcolor="' + textFrameBackColor + '" text="Black" link="Blue" vlink="Gray" LEFTMARGIN=0 onload="window.focus()">');
//			Win1.document.writeln('<center><FONT FACE="Arial" SIZE="-1"><b>' + LayerName[ActiveLayerIndex] + '</b>');
//			Win1.document.writeln('<table border="1" cellspacing="0" cellpadding="2" nowrap bgcolor="' + tableBackColor + '">');
		}
		endpos = 1;
		
		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;
			}
			//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 fName1 = getFieldNames(selectedData);
				//alert(fName1.length);
				var fValue1 = getFieldValues(selectedData);
				selectPoints[selectCount] = getIdValue(fName1, fValue1);
				
				if (selectCount==0) {
//					Win1.document.write('<tr><th><FONT FACE="Arial" SIZE="-2">Rec</FONT></a></th>');
					for (var f=0;f<fName1.length;f++) {
						var f2 = -1;
						if (useFieldAlias) {
							for (var f3=0;f3<AliasFieldName.length;f3++) {
								if (AliasFieldName[f3]==fName1[f]) f2 = f3;
							}
						}
						if (f2!=-1) {
//							Win1.document.write('<th><FONT FACE="Arial" SIZE="-2">' + AliasFieldAlias[f2] + '</FONT></a></th>');
						} else {
//							Win1.document.write('<th><FONT FACE="Arial" SIZE="-2">' + fName1[f] + '</FONT></a></th>');
						}
					}
//					Win1.document.writeln('</tr>');
				}
//				Win1.document.write('<tr><td>');
//				if (toolMode!=4) Win1.document.write('<a href="javascript:' + theFrame + '.showHighlight(' + selectCount + ')">');
//				Win1.document.write('<FONT FACE="Arial" SIZE="-2">' + (selectCount+queryStartRecord+1) + '</FONT>');
//				if (toolMode!=4) Win1.document.write('</a>');
//				Win1.document.writeln('</td>');
				for (var f=0;f<fName1.length;f++) {
			//TEMP ALERT FOR TESTING -RP		
				//alert("fName1: " + fName1[f]);
//					Win1.document.write('<TD>');
					var isHyper=false;
					if (showHyper) {
						for (var s1=0;s1<hyperLinkFields.length;s1++) {
							if (hyperLinkFields[s1]==fName1[f]) {
								Win1.document.write('<a href="' + fValue1[f] + '" target="_blank">');
								isHyper=true;
							}
						}
					}
					var s2 = -1;
					for (var s1=0;s1<LayerFields.length;s1++) {
						if (fName1[f]==LayerFields[s1]) s2=s1;
					}
					if (LayerFieldType[s2]=="91") {
						//alert(fName1[f]);
						if (isNaN(fValue1[f])) {
							var theDate = fValue1[f];
						} else {
							//var theDate = new Date(parseInt(fValue1[f]));
							var theDateObj = new Date(parseFloat(fValue1[f]));
							var theDate = theDateObj.toGMTString();
						}
	//					Win1.document.write('<FONT FACE="Arial" SIZE="-2">' + theDate + '</FONT>');
						theDate=null;
					} else {
						if ((toolMode==16) || (toolMode==10)){
							if ((fName1[f]==parField) && (fValue1[f]!="0")) {		
								selectedParcels[arrayCounter] = "" + fValue1[f] + "";
								arrayCounter = arrayCounter + 1;
							}
						}
						// IDENTIFY BEING PERFORMED
						if (toolMode==4){
						//alert("f " + f);
						//alert("layer " + LayerName[ActiveLayerIndex]);
						//alert("fname " + fName1[f]);
							if (LayerName[ActiveLayerIndex] == ParLayerName) {
								if ((fName1[f]==parField) && (fValue1[f]!="0")) {
		//						setQueryString = "" + parField + " = " + fValue1[f] + "";
		//						showHighlight(0);
	//							setQueryString = "" + parField + " = " + fValue1[f] + "";
	//							showHighlight(0);
	
								parcelIDvalue = fValue1[f];
									parent.TextFrame.document.location=appDir+"searchDetail.cfm?value=" + fValue1[f] + "000";
									//Keith TURN ON LOADING DATA ANIMATED GIF FOR IDENTIFY FUNCTION
									//showLayer('LoadData');

								}
							}else
							for(ID=0;ID<IDLayerName.length;ID++){
								if((LayerName[ActiveLayerIndex]==IDLayerName[ID]) && (fName1[f]==IDLayerField[ID])){
									parent.TextFrame.document.location=appDir+"idResults.cfm?layer=" + LayerName[ActiveLayerIndex] + "&Field=" + fName1[f] + "&value=" + fValue1[f] + "000";
								}
									//Keith TURN ON LOADING DATA ANIMATED GIF FOR IDENTIFY FUNCTION
									//showLayer('LoadData');
							}
							
	/*						
							if (LayerName[ActiveLayerIndex] == "Cities") {
								if (fName1[f]=="Cities") {
									parent.TextFrame.document.location=appDir+"idResults.cfm?layer=" + LayerName[ActiveLayerIndex] + "&Field=" + fName1[f] + "&value=" + fValue1[f] + "";
								}
							}
							if (LayerName[ActiveLayerIndex] == "Roads") {
								if (fName1[f]=="STREET") {
									parent.TextFrame.document.location=appDir+"idResults.cfm?layer=" + LayerName[ActiveLayerIndex] + "&Field=" + fName1[f] + "&value=" + fValue1[f] + "";
								}
							}
							if (LayerName[ActiveLayerIndex] == "Schools") {
								if (fName1[f]=="NAME") {
									parent.TextFrame.document.location=appDir+"idResults.cfm?layer=" + LayerName[ActiveLayerIndex] + "&Field=" + fName1[f] + "&value=" + fValue1[f] + "";
								}
							}

if (LayerName[ActiveLayerIndex] == "School Districts") {
if (fName1[f]=="DISTRICT") {
//alert ("Layer= " + LayerName[ActiveLayerIndex] + "fName1= " + fName1[f]);
parent.TextFrame.document.location=appDir+"idResults.cfm?layer=" + LayerName[ActiveLayerIndex] + "&Field=" + fName1[f] + "&value=" + fValue1[f] + "";
}
}

if (LayerName[ActiveLayerIndex] == "Zoning") {
if (fName1[f]=="ZONE") {
//alert ("Layer= " + LayerName[ActiveLayerIndex] + "fName1= " + fName1[f]);
parent.TextFrame.document.location=appDir+"idResults.cfm?layer=" + LayerName[ActiveLayerIndex] + "&Field=" + fName1[f] + "&value=" + fValue1[f] + "";
}
} 
*/
}
//}
					}
					if (isHyper) Win1.document.write('</a>');
//					Win1.document.writeln('</td>');
				}
	//			Win1.document.writeln('</tr>');
				fName1 = null;
				fValue1 = null;
				
			}
			selectCount += 1;
					
		}
		if (showSelectedData) {
			
//			Win1.document.writeln('</table>');
			if (toolMode!=25) {
				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></center></body></html>');
//			Win1.document.close();
		}
		//alert("toolMode:" + toolMode);
		
		if ((queryStartRecord==0) && (toolMode!=4) && (toolMode!=25)) {
			if ((selectCount==1) && (zoomToSingleSelect)) {
				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();
				left = selectLeft[0] - mWMargin;
				right = selectRight[0] + mWMargin;
				top = selectTop[0] + mHMargin;
				bottom = selectBottom[0] - mHMargin;
			}
			//Keith TURN ON LOADING DATA ANIMATED GIF FOR IDENTIFY FUNCTION
			showLayer('LoadData');
			
			if(toolMode != 4){
			sendMapXML();
			}
			
	//		showHighlight(0);
		}
			
	} else {
		//alert(tempString);
		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="White" TEXT="Black" LEFTMARGIN=0 TOPMARGIN=0>');
		Win1.document.writeln('<FONT FACE="Arial"><B>' + LayerName[ActiveLayerIndex] +'</B></font><FONT FACE="Arial" size="-2">');
		Win1.document.writeln('<br>No Features Found.');
		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('<script language="JavaScript">');
		Win1.document.writeln('// STOP LOADING DATA ANIMATED GIF');
		Win1.document.writeln('parent.MapFrame.hideLayer("LoadData");');
		Win1.document.writeln('</script>');
		Win1.document.writeln('</body></html>');
		Win1.document.close();
	}
	
	if ((toolMode==16) || (toolMode==10)){
	for(i=0;i<selectedParcels.length;i++){
		selectedParcels[i] = "'" + selectedParcels[i] + "'";
		}
	//alert(selectedParcels);
	
	parent.TextFrame.document.location=appDir+"searchResultSelect.cfm?value=" + selectedParcels + "";
	selectedParcels.length=0;
	//alert("selectedParcels = " + selectedParcels);
	}
	
	if ((toolMode==4) || (toolMode==9))  selectCount=0;
	Win1=null;
	//hideRetrieveData();

// Added by Keith 2.8.01	
if(toolMode==4){
//alert(selectCount);
//alert(
selectType=ActiveLayerType;
selectLeft[0] = left;
selectRight[0] = right;
selectTop[0] = top;
selectBottom[0] = bottom;
showHighlight(0);
}
}

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;

}


