// 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";
}
var canQuery=true;
var newSelectCount=0;
var selectPoints = 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);
	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) {
	var theString = '<?xml version="1.0" encoding="UTF-8"?>\n<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) {
	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);
	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 = parent.TextFrame;
	var theFrame = "parent.MapFrame";
	if (featureCount > 0) {
		newSelectCount += 1;
		if (showSelectedData) {
			//if ((useExternalWindow) || (!useTextFrame)) {
				Win1 = window.open("","QueryWindow","width=675,height=100,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" bordercolor="white" cellspacing="0" cellpadding="3" nowrap bgcolor="' + tableBackColor + '">');
		}
		endpos = 1;
		
		for (var i=0;i<fCount;i++) {
			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;
			}
			inData = parseRecordString(theReply, endpos);
			endpos = xmlEndPos;
			selectedData = clearLeadingSpace(inData);
			epos = theReply.indexOf("</FEATURE",endpos);
			if (showSelectedData) {
				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);
				var fValue1 = getFieldValues(selectedData);
				selectPoints[selectCount] = getIdValue(fName1, fValue1);
				
				if (selectCount==0) {
					Win1.document.write('<tr bgcolor=silver><th><FONT FACE="Arial" SIZE="-2"><STRONG>Rec</STRONG></FONT></a></th>');
					for (var f=0;(f<fName1.length - 2);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"><STRONG>' + AliasFieldAlias[f2] + '</STRONG></FONT></a></th>');
						} else {
							Win1.document.write('<th><FONT FACE="Arial" SIZE="-2"><STRONG>' + fName1[f] + '</STRONG></FONT></a></th>');
						}
					}
					Win1.document.writeln('</tr>');
				}
				Win1.document.write('<tr bgcolor="c5ffd3"><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 - 2);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") {
						if (isNaN(fValue1[f])) {
							var theDate = fValue1[f];
						} else {
							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 (fName1[f] == "LAYERS.GIS.ACCOUNTS.ACCOUNT") {
							Win1.document.write('<FONT FACE="Arial" SIZE="-2"><a href="http://www.ccappraiser.com/Show_parcel.asp?acct=' + fValue1[f] + '&gen=T&tax=T&bld=T&oth=T&sal=T&lnd=T&leg=T" target="_blank">' + fValue1[f] + '</a></FONT>');
					} else if (fName1[f] == "LAYERS.GIS.ELU.LANDUSE") {
							Win1.document.write('<FONT FACE="Arial" SIZE="-2"><a href="../gis/Existing Land Use.htm" target="_blank">' + fValue1[f] + '</a></FONT>');
					} else if (fName1[f] == "LAYERS.GIS.FEMA_W_LOMR.FZONE") {
							Win1.document.write('<FONT FACE="Arial" SIZE="-2"><a href="../gis/femanew.htm" target="_blank">' + fValue1[f] + '</a></FONT>');
					} else if (fName1[f] == "LAYERS.GIS.FEMA_W_LOMR.LOMC") {
							Win1.document.write('<FONT FACE="Arial" SIZE="-2"><a href="ftp://www.ccgis.com/PDFs/FEMA_LOMC/' + fValue1[f] + '" target="_blank">' + fValue1[f] + '</a></FONT>');
					} else if (fName1[f] == "LAYERS.GIS.MSBU.ACCOUNT") {
							Win1.document.write('<FONT FACE="Arial" SIZE="-2"><a href="http://www.charlottefl.com/MSBUApp/Public/acctinfo_results.asp?acct=' + fValue1[f] + '" target="_blank">' + fValue1[f] + '</a></FONT>');
					} else if (fName1[f] == "LAYERS.GIS.MSBU.MSBU_CODE") {
							Win1.document.write('<FONT FACE="Arial" SIZE="-2"><a href="http://www.charlottefl.com/MSBUApp/Public/pubmaster.aspx?mc=' + fValue1[f] + '" target="_blank">' + fValue1[f] + '</a></FONT>');
					} else if (fName1[f] == "LAYERS.GIS.PREFMAP.FZONE") {
							Win1.document.write('<FONT FACE="Arial" SIZE="-2"><a href="../gis/fema_old.htm" target="_blank">' + fValue1[f] + '</a></FONT>');
					} else if (fName1[f] == "LAYERS.GIS.ZONING_NEW.ZONE_") {
							Win1.document.write('<FONT FACE="Arial" SIZE="-2"><a href="../gis/zoning.htm" target="_blank">' + fValue1[f] + '</a></FONT>');
					} else if (fName1[f] == "LAYERS.GIS.CERTSALES.MORE") {
							Win1.document.write('<FONT FACE="Arial" SIZE="-2"><a href="http://cctaxcol.com/DOWNLOA.HTM" target="_blank">' + fValue1[f] + '</a></FONT>');
					} else if (fName1[f] == "LAYERS.GIS.LOTS.LOCID") {
							Win1.document.write('<FONT FACE="Arial" SIZE="-2"><a href="../gis/lotsize.asp?LocationID=' + fValue1[f] + '" target="_blank">' + "Area Information" + '</a></FONT>');
					} else if (fName1[f] == "LAYERS.GIS.LOTS.SUBDIV") {
							Win1.document.write('<FONT FACE="Arial" SIZE="-2"><a href="../gis/subdiv.htm" target="_blank">' + fValue1[f] + '</a></FONT>');
					} else if (fName1[f] == "LAYERS.GIS.PW_PROJECTS.PRJ_LINK") {
						if (fValue1[f] == "Completed") {
							Win1.document.write('<FONT FACE="Arial" SIZE="-2">COMPLETED</a></FONT>');
						} else if (fValue1[f] == "On Hold") {
							Win1.document.write('<FONT FACE="Arial" SIZE="-2">ON HOLD</a></FONT>');
						} else {
							Win1.document.write('<FONT FACE="Arial" SIZE="-2"><a href="' + fValue1[f] + '" target="_blank">' + "More Information" + '</a></FONT>');
						 }
					} else if (fName1[f] == "LAYERS.GIS.PW_PROJECTS.PHOTO_LINK") {
						if (fValue1[f] == "&nbsp;") {
							Win1.document.write('<FONT FACE="Arial" SIZE="-2">N/A</a></FONT>');
						} else {
							Win1.document.write('<FONT FACE="Arial" SIZE="-2"><a href="ftp://www.ccgis.com/Photos/PW/' + fValue1[f] + '" target="_blank">' + "Photo" + '</a></FONT>');
						}
					} else if (fName1[f] == "LAYERS.GIS.ADDRESSES.ACTIVE") {
						if (fValue1[f] == "78") {
							Win1.document.write('<FONT FACE="Arial" SIZE="-2">N</a></FONT>');
						} else if (fValue1[f] == "89") {
							Win1.document.write('<FONT FACE="Arial" SIZE="-2">Y</a></FONT>');
						} else if (fValue1[f] == "2") {
							Win1.document.write('<FONT FACE="Arial" SIZE="-2">Historic</a></FONT>');
						} else if (fValue1[f] == "3") {
							Win1.document.write('<FONT FACE="Arial" SIZE="-2">Retired</a></FONT>');
						} else {
							Win1.document.write('<FONT FACE="Arial" SIZE="-2">' + fValue1[f] + '</FONT>');
						 }
					} else if (fName1[f] == "LAYERS.GIS.FLU_NEW.NEWLU") {
						if (fValue1[f] == "Charlotte Harbor CRA") {
							Win1.document.write('<FONT FACE="Arial" SIZE="-2"><a href="http://www.charlottecountyfl.com/BoardsCommittees/CRA/MapsPhotos.asp" target="_blank">' + fValue1[f] + '</a></FONT>');
						} else {
							Win1.document.write('<FONT FACE="Arial" SIZE="-2">' + fValue1[f] + '</FONT>');
						}
					} else {
						Win1.document.write('<FONT FACE="Arial" SIZE="-2">' + fValue1[f] + '</FONT>');
					}
					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();
		}
		if ((queryStartRecord==0) && (toolMode!=4) && (toolMode!=9) && (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;
			}
			sendMapXML();
		}
	} 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="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('</body></html>');
		Win1.document.close();
	}
	if ((toolMode==4) || (toolMode==9))  selectCount=0;
	Win1=null;
	hideRetrieveData();
}

function parseHyperLink(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;
	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 {
		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;
	for (var i=0; i<hyperLinkLayers.length; i++) {
			if (LayerName[layerIndex]==hyperLinkLayers[i]) {
				canLink=true;
				currentHyperLinkLayer=LayerName[layerIndex];
				currentHyperLinkField=hyperLinkFields[i];
			}
	}
	return canLink;
}
