// 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 currentHyperLinkPrefix="";
var currentHyperLinkSuffix="";
var hyperlinkWindowWidth=500;
var hyperlinkWindowHeight=400;

// variable for search tolerance... dynamically set in app
var searchTolerance=1/100;
// starting record position for returned records
var queryStartRecord=1;

if (imsQueryURL=="") {
	imsQueryURL= imsURL + "&CustomService=Query";
	//alert(imsQueryURL);
}
var canQuery=true;
var newSelectCount=0;
var selectPoints = new Array();

// can features be selected if invisible or not within layer scale threshholds?
var canSelectInvisible=false;

//Memorizza elenco attributi entita' elencate
var ElencoCampi = new Array();
var ElencoValori = new Array();

var CalcoloPrestazioni = 0 ;

/****************************************************************************************
Identify functions 
****************************************************************************************/

// identify feature
function identify(e) {
	if (checkIfActiveLayerAvailable()) {
		highlightedOne="";
		var theX = mouseX;
		var theY = mouseY;
		getMapXY(theX,theY);
		//Check se calcolo delle prestazioni in corso nel qual caso la tolleranza è 1/2 px
		if ((CPInCorso==true) && (ActiveLayerIndex == IDQuadrati)) {
			searchTolerance = (xDistance/iWidth) * 0.5;
		} else {
			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,maxFeaturesReturned);
		//Le tre linee seguenti sono state inserite per selezionare sulla 
		//mappa le entita che vengono interrogate (come per la query)
		selectType=ActiveLayerType;
		selectEnvelope='maxy="' + forceComma(tempNorth) + '" maxx="' + forceComma(tempEast) + '" miny="' + forceComma(tempSouth) + '" minx="' + forceComma(tempWest) + '"';
		selectionMode=2;
		//if (useTextFrame) parent.TextFrame.document.location = "text.htm";
		//alert(theString);
		showRetrieveData();
		sendToServer(imsQueryURL,theString,identifyXMLMode);
	}
}

// Milani - Questa funzione esegue un identify sul layer del quadro unione
//          usando le coordinate dell'extent corrente per ritornare la lista
//          delle tavole interessate nella visualizzazione corrente
function identifyQuadroUnione() {
//alert("sono in identifyQuadroUnione");
	setActiveLayer1(IDQuadroUnione);
	//if (checkIfActiveLayerAvailable()) {
		highlightedOne = "";
		var tempWest   = eLeft;
		var tempNorth  = eTop;
		var tempEast   = eRight;
		var tempSouth  = eBottom;
		var theString  = writeGetFeatures(tempWest,tempSouth,tempEast,tempNorth,0);
		//Le tre linee seguenti sono state inserite per selezionare sulla 
		//mappa le entita che vengono interrogate (come per la query)
		selectType=ActiveLayerType;
		selectEnvelope='maxy="' + forceComma(tempNorth) + '" maxx="' + forceComma(tempEast) + '" miny="' + forceComma(tempSouth) + '" minx="' + forceComma(tempWest) + '"';
		selectionMode=2;
		//if (useTextFrame) parent.TextFrame.document.location = "text.htm";
		showRetrieveData();
		sendToServer(imsQueryURL,theString,identifyXMLMode);
	//}
}

// hyperlink from feature in active layer
function hyperLink(e) {
	if (checkIfActiveLayerAvailable()) {
		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,maxFeaturesReturned);
			selectFields = tempSelect;
			swapSelectFields=tempSwap;
			showRetrieveData();
			//if (useTextFrame) parent.TextFrame.document.location = "text.htm";
			sendToServer(imsQueryURL,theString,hyperlinkXMLMode);
		} else {
			alert(msgList[47]);
		}
	}
}


// write out XML request to identify features
function writeGetFeatures(west1,south1,east1,north1,maxReturned) {
	if (swapSelectFields) {
		selectFields=selFieldList[ActiveLayerIndex];
	}
	var useString = writeIdentifyXML(ActiveLayer,ActiveLayerType,selectFields,west1,south1,east1,north1,maxReturned,useLimitExtent);
	hightlightedOne="";
	return useString;
}

function writeIdentifyXML(theLayer,theLayerType,theFields,leftX,bottomY,rightX,topY,maxReturned,hasLimit) {
	//Modificata la linea sequente per ritornare l'extent delle entita (envelope=true)
	var theString = '<ARCXML version="1.1">\n<REQUEST>\n<GET_FEATURES outputmode="xml" envelope="true" geometry="false"'
	if (maxReturned > 0) theString += ' featurelimit="' + maxReturned + '"'
	theString += '>\n';
	theString += '<LAYER id="' + theLayer + '" />';
	theString += '<SPATIALQUERY subfields="' + theFields + '">';
	theString += '<SPATIALFILTER relation="area_intersection" >';
	theString += '<ENVELOPE maxy="' + forceComma(topY) + '" maxx="' + forceComma(rightX) + '" miny="' + forceComma(bottomY) + '" minx="' + forceComma(leftX) + '" />';
	theString += '</SPATIALFILTER>';
	theString += '</SPATIALQUERY>';
	if (hasLimit) {
		// keep this within the limitExtent
		theString += '<SPATIALFILTER relation="area_intersection">\n';
		theString += '<ENVELOPE maxx="' + forceComma(limitRight) + '" maxy="' + forceComma(limitTop) + '" minx="' + forceComma(limitLeft) + '" miny="' + forceComma(limitBottom) + '" />\n';
		theString += '</SPATIALFILTER>\n';
	}
	theString += '</GET_FEATURES>';
	theString += '</REQUEST>';
	theString += '</ARCXML>';
	return theString;
}

function getExtentedInfo(n) {
	var tempString = ElencoValori[n];
	//alert(tempString);
	tempString = tempString.replace(/&nbsp;/g, " ");
	var Win1 = window.open(appDir + "InfoExt.asp" + tempString,"","status=yes,toolbar=yes,menubar=yes,location=yes,scrollbars,resizable");
}

// parse XML response for selected features
function displayAttributeData(theReply) {

	//Modificata la funzione per fare funzionare l'interrogazione come la
	//per cui modificato controllo su toolMode=4 in  toolMode=44
	//alert(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);
	//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 tempString = "";
	var fCount = featureCount;
	//alert("displayAttributeData()[featurecount=" + featureCount + "]");
	selectCount = 0;
	var tempString="";
	var Win1 = parent.TextFrame;
	var theFrame = "parent.MapFrame";
	if (featureCount > 0) {
		newSelectCount += 1;

		if (showSelectedData) {
			//alert("displayAttributeData()[opening html page]");
			if ((useExternalWindow) || (!useTextFrame)) {
			//alert("primo if");
				var pos = (screen.width - parent.parent.parent.document.body.clientWidth)/2;
				Win1 = window.open("","QueryWindow","width="+parent.document.body.clientWidth+",height=200,left="+pos+",top=0,scrollbars=yes,resizable=yes");
				theFrame = "opener";
				if (parent.MapFrame!=null) theFrame = "opener.parent.MapFrame";
				//alert("secondo if");
			} else {
				Win1 = parent.TextFrame;
				Win1.document.open();
				alert("primo else");
			}
			Win1.document.open();
			Win1.document.writeln('<html><meta http-equiv="Content-Type" content="text/html; charset=' + charSet + '"><head><title>' + titleList[7] + '</title><link rel="stylesheet" type="text/css" href="' + appDir + 'css/style1.css"></head>');
			Win1.document.writeln('<body bgcolor="' + textFrameBackColor + '" text="Black" link="Blue" vlink="Gray" LEFTMARGIN=0 TOPMARGIN=0 onload="window.focus()">');
			Win1.document.writeln('<center>');
			//Win1.document.writeln('<FONT FACE="Verdana,Arial" SIZE="-1"><b>' + LayerName[ActiveLayerIndex] + '</b></FONT>');
			Win1.document.writeln('<table width=100% border="1" cellspacing="0" cellpadding="2" nowrap bgcolor="' + tableBackColor + '">');
		//alert("fuori ciclo if");
		}
		endpos = 1;
		
		for (var i=0;i<fCount;i++) {
			//alert(endpos);
			if (toolMode!=0 && toolMode!=44) {
				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);
			selectedData = 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);
				var fValue1 = getFieldValues(selectedData);
				selectPoints[selectCount] = getIdValue(fName1, fValue1);
				
				var idFieldNum = -1;
				var shapeFieldNum = -1;
				if (hideIDFieldData) {
					// hide ID column header
					for (var f=0;f<fName1.length;f++) {
						if (fName1[f]==LayerIDField[ActiveLayerIndex]) idFieldNum = f;
					}
				}
				if (hideShapeFieldData) {
					// hide Shape column header
					for (var f=0;f<fName1.length;f++) {
						if (fName1[f]==LayerShapeField[ActiveLayerIndex]) shapeFieldNum = f;
					}
				}
				
				//Prima riga della tabella con i nomi dei campi
				if (selectCount==0) {
					Win1.document.write('<tr><th>' + LayerName[ActiveLayerIndex] + '</th>');
					//Se il tema corrente ha degli alias sui campi ne mantiene l'ordine
					if ((useFieldAlias) && (AliasFieldName.length>0)) {
						for (var f=0;f<AliasFieldName.length;f++) {
							ElencoCampi[f] = AliasFieldName[f];
							Win1.document.write('<th>' + AliasFieldAlias[f] + '</th>');
						}
					} else {
						for (var f=0;f<fName1.length;f++) {
							if ((f!=idFieldNum) && (f!=shapeFieldNum)) {
								var f2 = -1;
								if (useFieldAlias) {
									for (var f3=0;f3<AliasFieldName.length;f3++) {
										if (AliasFieldName[f3]==fName1[f]) f2 = f3;
									}
								}
								if (f2!=-1) {
									//ElencoCampi[f] = AliasFieldAlias[f2];
									ElencoCampi[f] = fName1[f];
									Win1.document.write('<th>' + AliasFieldAlias[f2] + '</th>');
								} else {
									ElencoCampi[f] = fName1[f];
									Win1.document.write('<th>' + fName1[f] + '</th>');
								}
							}
						}
					}
					Win1.document.writeln('</tr>');
				}
				Win1.document.write('<tr><td align=center>');

				//Inserisce immagini per azioni sulle entita' elencate
				if (toolMode!=0 && toolMode!=44) {
					Win1.document.write('<a href="javascript:' + theFrame + '.showHighlight(' + selectCount + ')">');
					Win1.document.write('<img alt="Localizza" src="' + appDir + 'images/trova4.gif" border=0 hspace=0 vspace=0 width=16 height=16>');
				    Win1.document.write('</a>');
					//Win1.document.write('<FONT FACE="Arial" SIZE="-2">' + (selectCount+queryStartRecord) + '</FONT>');
				} else {
					Win1.document.write('<FONT FACE="Arial" SIZE="-2">' + (selectCount+queryStartRecord) + '</FONT>');
				}

				Win1.document.writeln('</td>');

				//Azzera campo per memorizzare tutti i valori dell'enetita'
				ElencoValori[selectCount] = "?Anno="+StoricoAnno[StoricoDef]+"&Entita="+LayerName[ActiveLayerIndex];

				//Se il tema corrente ha degli alias sui campi ne mantiene l'ordine
				if ((useFieldAlias) && (AliasFieldName.length>0)) {
					for (var f=0;f<AliasFieldName.length;f++) {
						for (var f1=0;f1<fName1.length;f1++) {	
							if (AliasFieldName[f]==fName1[f1]) {
								Win1.document.write('<TD>');
								var isHyper=false;
								if (showHyper) {
									for (var s1=0;s1<hyperLinkFields.length;s1++) {
									  
										if (hyperLinkFields[s1]==fName1[f1]) { 
										//alert("hyperLinkFields " + hyperLinkFields[s1]);
									    //alert("fname " + fName1[f1]);
											var theLinkURL = appDir + currentHyperLinkPrefix + fValue1[f1] + currentHyperLinkSuffix;
											//alert("theLinkURL" + theLinkURL + "f1  " + f1);
											//controllo se il campo è TIPO per acquisire il valore del campo successivo REGIONE
											if (fName1[f1]=="TIPO")
												theLinkURL = appDir + currentHyperLinkPrefix + fValue1[2] + "_legenda.htm";
												//test
											if (fName1[f1]=="TAVOLA")
												theLinkURL = appDir + hyperLinkPrefix[2] + fValue1[f1] + hyperLinkSuffix[2];
											if (fName1[f1]=="RASTER")
												theLinkURL = appDir + hyperLinkPrefix[3] + fValue1[f1] + hyperLinkSuffix[3];
											//alert(currentHyperLinkPrefix);
											//alert(currentHyperLinkSuffix);
											
											Win1.document.write('<a href="' + theLinkURL + '" target="_blank">');
											isHyper=true;
										}
									}
								}
								//Carica campo per memorizzare tutti i valori dell'enetita'
								ElencoValori[selectCount] = ElencoValori[selectCount] + '&' + ElencoCampi[f] + '=' + fValue1[f1];
								tempString = fValue1[f1].replace(/ /g, "&nbsp;");
								Win1.document.write(tempString);
								if (isHyper) Win1.document.write('</a>');
								Win1.document.writeln('</td>');
							}
						}
					}
				} else {
				alert("else");
					for (var f=0;f<fName1.length;f++) {	
						if ((f!=idFieldNum) && (f!=shapeFieldNum)) {
							Win1.document.write('<TD>');
							var isHyper=false;
							if (showHyper) {
								for (var s1=0;s1<hyperLinkFields.length;s1++) {
									if (hyperLinkFields[s1]==fName1[f]) {
										var theLinkURL = appDir + currentHyperLinkPrefix + fValue1[f] + currentHyperLinkSuffix;
										Win1.document.write('<a href="' + theLinkURL + '" 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 d = theDateObj.toUTCString();
									var theDate = d.replace(/GMT|UTC/,"");
								}
								Win1.document.write(theDate);
								theDate=null;
								//Carica campo per memorizzare tutti i valori dell'enetita'
								ElencoValori[selectCount] = ElencoValori[selectCount] + '&' + ElencoCampi[f] + '=' + theDate;
							} else {
								//Milani - Carica campo per memorizzare tutti i valori dell'enetita'
								ElencoValori[selectCount] = ElencoValori[selectCount] + '&' + ElencoCampi[f] + '=' + fValue1[f];
								// put html entity for spaces so display is correct - browsers trim extra spaces
								tempString = fValue1[f].replace(/ /g, "&nbsp;");
								Win1.document.write(tempString);
							}
							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><FONT FACE="Verdana,Arial" SIZE="-2">');
			Win1.document.write('<table><tr>');
			if (toolMode!=25) {
				if (queryStartRecord>1) {
					var prevRecord = queryStartRecord - maxFeaturesReturned;
					if (prevRecord<1) prevRecord=1;
					Win1.document.write('<td align=center><a href="javascript:' + theFrame + '.getMoreData(' + prevRecord + ')"><img alt="Visualizza precedenti" border=0 src="' + appDir + 'images/panovest.gif"></a><br>&nbsp;&nbsp;&nbsp;<b>' + msgList[61] + '</b>&nbsp;&nbsp;&nbsp;</td>');
				}
				if (stillMore) {
					var nextRecord=featureCount + queryStartRecord;
					Win1.document.writeln('<td align=center><a href="javascript:' + theFrame + '.getMoreData(' + nextRecord + ')"><img alt="Visualizza successivi" border=0 src="' + appDir + 'images/panest.gif"></a><br>&nbsp;&nbsp;&nbsp;<b>' + msgList[63] + '</b>&nbsp;&nbsp;&nbsp;</td>');
				}
			}
			if ((toolMode!=0) && (toolMode!=44) && (toolMode!=25) && (selectCount>1)) {
				Win1.document.writeln('<td align=center><a href="javascript:' + theFrame + '.zoomToReturnedRecords()"><img alt="Zoom sulla mappa in base agli elementi in elenco" border=0 src="' + appDir + 'images/find_1.gif"></a><br>&nbsp;&nbsp;&nbsp;<b>Zoom elenco</b>&nbsp;&nbsp;&nbsp;</td>');
			}
			Win1.document.writeln('<td align=center><a href="javascript:print();"><img alt="Stampa elenco" border=0 src="' + appDir + 'images/print_1.gif"></a><br>&nbsp;&nbsp;&nbsp;<b>Stampa</b>&nbsp;&nbsp;&nbsp;</td>');
			Win1.document.write('</tr></table>');
			Win1.document.writeln('</font></center></body></html>');
			Win1.document.close();
		}
		
		if ((queryStartRecord==1) && (toolMode!=0) && (toolMode!=44) && (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();
				eLeft = selectLeft[0] - mWMargin;
				eRight = selectRight[0] + mWMargin;
				eTop = selectTop[0] + mHMargin;
				eBottom = selectBottom[0] - mHMargin;
			}
			sendMapXML();
		}
	} else {
		//alert(tempString);
		if ((useExternalWindow) || (!useTextFrame)) {
			alert(msgList[64]);
			//Win1 = window.open("","QueryWindow","width=575,height=120,scrollbars=yes,resizable=yes");
		} else {
			Win1 = parent.TextFrame;
			Win1.document.open();
			Win1.document.writeln('<html><meta http-equiv="Content-Type" content="text/html; charset=' + charSet + '"><head>');
			Win1.document.writeln('	<title>' + titleList[8] + '</title>');
			Win1.document.writeln('</head>');
			Win1.document.writeln('<body BGCOLOR="White" TEXT="Black" LEFTMARGIN=0 TOPMARGIN=0>');
			Win1.document.writeln('<FONT FACE="Verdana,Arial"><B>' + LayerName[ActiveLayerIndex] +'</B></font><FONT FACE="Verdana,Arial" size="-2">');
			Win1.document.writeln('<br>' + msgList[64]);
			if (debugOn>0) {
				Win1.document.writeln('<p>' + msgList[65] + '<br>');
				Win1.document.writeln(untag(theReply));
			} else {
				if (theError!="") {
					Win1.document.writeln('<p>' + msgList[66] + '<br>');
					Win1.document.writeln(theError);
				}
			}
			Win1.document.writeln('</FONT>');
			Win1.document.writeln('</body></html>');
			Win1.document.close();
		}
	}
	if (toolMode==0 || toolMode==44) selectCount=0;
	
	//Se tema corrente e' quello del quadro di unione setta tema corrente gli impianti
	//if (ActiveLayerIndex==IDQuadroUnione) setActiveLayer1(IDImpiantiPunti);
	
	Win1=null;
	hideRetrieveData();
}

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);
		var theLinkURL = currentHyperLinkPrefix + inData + currentHyperLinkSuffix;
		if (parent.TextFrame!=null) {
			parent.TextFrame.document.open();
			parent.TextFrame.document.writeln('<html><meta http-equiv="Content-Type" content="text/html; charset=' + charSet + '"><head>');
			parent.TextFrame.document.writeln('	<title>' + titleList[9] + 's</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>' + msgList[67] + theLinkURL );
			parent.TextFrame.document.writeln('</FONT>');
			parent.TextFrame.document.writeln('</body></html>');
			parent.TextFrame.document.close();
		}
		var Win1=open(theLinkURL,"",linkString);
	} else {
	
		//alert(tempString);
		if (parent.TextFrame!=null) {
			parent.TextFrame.document.open();
			parent.TextFrame.document.writeln('<html><meta http-equiv="Content-Type" content="text/html; charset=' + charSet + '"><head>');
			parent.TextFrame.document.writeln('	<title>' + titleList[9] + '</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>' + msgList[68]);
			if (debugOn>0) {
				parent.TextFrame.document.writeln('<p>' + msgList[65] + '<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 = msgList[69];
			if (debugOn>0) {
				msg = msg + msgList[9] + 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("lunghezza= " + hyperLinkLayers.length);
	for (var i=0; i<hyperLinkLayers.length; i++) {
	
			if (LayerName[layerIndex]==hyperLinkLayers[i]) {
			//alert ("indice " + i);
				canLink=true;
				currentHyperLinkLayer=LayerName[layerIndex];
				currentHyperLinkField=hyperLinkFields[i];
				currentHyperLinkPrefix=hyperLinkPrefix[i];
				currentHyperLinkSuffix=hyperLinkSuffix[i];
				//alert(currentHyperLinkLayer + currentHyperLinkField + currentHyperLinkPrefix + currentHyperLinkSuffix + i);
			}
	}
	return canLink;

}

// check to see if active layer is in scale threshold and visible 
// so it can be used for querying
function checkIfActiveLayerAvailable() {
	// is the override flag set 
	// se e' in corso il calcolo delle prestazioni non deve eseguire il controllo
	if ((canSelectInvisible) || (CPInCorso == true)) {
		return true;
	} else {
		// is the current scale within the scale min and max?
		if ((mapScaleFactor>=LayerMinScale[ActiveLayerIndex]) && (mapScaleFactor<=LayerMaxScale[ActiveLayerIndex])) {
			// is the active layer visible?
			if (LayerVisible[ActiveLayerIndex]==1) {
				return true;
			} else {
				var msg = msgList[104] + LayerName[ActiveLayerIndex] + msgList[102] + LayerName[ActiveLayerIndex] + msgList[108];
				alert(msg);
				return false;
			}
		} else {
			var msg = msgList[104] + LayerName[ActiveLayerIndex] + msgList[101];
			//if ((!listAllLayers) && (hasTOC)) msg += msgList[103];
			alert(msg);
			return false;
		}
	}
}


/**************************************************************
*	functions and variables for Identify All
*	drill down through visible layers
**************************************************************/

var replyArray = new Array();
var fID = 0;
var fIndex = 0;
var idEast;
var idWest;
var idSouth;
var idNorth;


// identify feature
function identifyAll(e) {
	fID = 0;
	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;
	idSouth = tempSouth;
	idNorth = tempNorth;
	idWest = tempWest;
	idEast = tempEast;
	replyArray.length=0;
	var j =-1;
	for (var i=(LayerID.length-1);i>=0;i--) {
		replyArray[i]="";
		if ((mapScaleFactor>=LayerMinScale[i]) && (mapScaleFactor<=LayerMaxScale[i]) && (LayerVisible[i]) && (LayerIsFeature[i])) j = i;

	}
	if (j>-1) {
		fID=j;
		var theString = writeGetFeaturesDrill(tempWest,tempSouth,tempEast,tempNorth,fID);
		//if (useTextFrame) parent.TextFrame.document.location = "text.htm";
		//alert(theString);
		showRetrieveData();
		sendToServer(imsQueryURL,theString,10);
	} else {
		alert(msgList[111]);
	}
}


function doIdentifyAll(theReply) {
    //drill tool loop sequence
	//alert(theReply);
   replyArray[fID] = theReply;
   fID++;
   if (fID < (LayerID.length)) {
   		if ((mapScaleFactor>=LayerMinScale[fID]) && (mapScaleFactor<=LayerMaxScale[fID]) && (LayerVisible[fID]) && (LayerIsFeature[fID])) {
      		theString = writeGetFeaturesDrill(idWest,idSouth,idEast,idNorth,fID);
			//alert(theString);
	  		sendToServer(imsQueryURL,theString,10);
	   	} else {
			doIdentifyAll("");
		}
   }
   
   if (fID == (LayerID.length)) {
	//createDrillPage = false;
	//replyArray.reverse();
	displayAttributeDataforDrill(replyArray);
	fID = 0;
	//var ActiveLayerIndex = 4;
   }
 }  //end doDrill()


 // write XML to identify features for drill ID
function writeGetFeaturesDrill(west1,south1,east1,north1,thefID) {
	if (swapSelectFields) {
		selectFields=selFieldList[thefID];
	}
	var useString = writeIdentifyXML(LayerID[thefID],LayerType[thefID],selectFields,west1,south1,east1,north1,maxFeaturesReturned,useLimitExtent);
	hightlightedOne="";
	return useString;
}

// parse XML response for drill functions
function displayAttributeDataforDrill(theReplyArray) {
   showRetrieveData();
	var theFrame = "parent.MapFrame";
	if ((useExternalWindow) || (!useTextFrame)) {
			var Win1 = window.open("","QueryWindow","width=575,height=120,scrollbars=yes,resizable=yes");
			theFrame = "opener";
			if (parent.MapFrame!=null) theFrame = "opener.parent.MapFrame";
	} else {
			var Win1 = parent.TextFrame;
			Win1.document.open();
	}
	Win1.document.open();
	Win1.document.writeln('<html><head><title>Risultati della interrogazione</title></head>');
	Win1.document.writeln('<body bgcolor="' + textFrameBackColor + '" text="Black" link="Blue" vlink="Gray" LEFTMARGIN=0 onload="window.focus()"><center>');
	var lyrCount = 0;
	 for (b=0;b<theReplyArray.length;b++) {
	 	if (theReplyArray[b]!="") {
		    //alert(theReply);
			theReply = theReplyArray[b];
			setLayerFields(b);
			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 fCount = featureCount;
			//alert("displayAttributeData()[featurecount=" + featureCount + "]");
			selectCount = 0;
			var tempString="";
			if (featureCount > 0) {
				//alert(featureCount);
				newSelectCount += 1;
				endpos = 1;
				Win1.document.writeln('<center><br><FONT FACE="Arial" SIZE="-1"><b>' + LayerName[b] + '</b><br>');
				Win1.document.writeln('<table border="1" size="95%" cellspacing="0" cellpadding="2" nowrap bgcolor="' + tableBackColor + '">');						
				for (var i=0;i<fCount;i++) {
		
					inData = parseRecordString(theReply, endpos);
					endpos = xmlEndPos;
					//selectedData = clearLeadingSpace(inData);
					selectedData = 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[b]) showHyper=true;
							}
						}
							
						var fName1 = getFieldNames(selectedData);
						var fValue1 = getFieldValues(selectedData);
						//selectPoints[selectCount] = getIdValue(fName1, fValue1);
						var idFieldNum = -1;
						var shapeFieldNum = -1;
						if (hideIDFieldData) {
							// hide ID column header
							for (var f=0;f<fName1.length;f++) {
								if (fName1[f]==LayerIDField[ActiveLayerIndex]) idFieldNum = f;
							}
						}
						if (hideShapeFieldData) {
							// hide Shape column header
							for (var f=0;f<fName1.length;f++) {
								if (fName1[f]==LayerShapeField[ActiveLayerIndex]) shapeFieldNum = f;
							}
						}
						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++) {
								if ((f!=idFieldNum) && (f!=shapeFieldNum)) {
									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>');
						Win1.document.write('<FONT FACE="Arial" SIZE="-2">' + (selectCount+queryStartRecord) + '</FONT>');
						Win1.document.writeln('</td>');
						for (var f=0;f<fName1.length;f++) {	
							if ((f!=idFieldNum) && (f!=shapeFieldNum)) {
								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 d = theDateObj.toUTCString();
										var theDate = d.replace(/GMT|UTC/,"");
									}
									Win1.document.write('<FONT FACE="Arial" SIZE="-2">' + theDate + '</FONT>');
									theDate=null;
								} 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;
					//					
				}
				Win1.document.writeln('</table></center>');
				lyrCount++

			} else {
				if (listAllLayersInIDAll) {
		        	Win1.document.writeln('<center><FONT FACE="Arial" SIZE="-1"><b>' + LayerName[b] + '</b>');
					Win1.document.writeln('<br>' + msgList[64] + '<br><br></font></center>');
		     	}

			}
	  	}
	  }//end for 
	  
	  if (lyrCount==0) {
        	Win1.document.writeln('<center><FONT FACE="Arial" SIZE="-1"><b>' + msgList[112] + '</b></font></center>');
	  }
 
    Win1.document.writeln('</body></html>');
    Win1.document.close();
    Win1=null;
    hideRetrieveData();
} //end function


// checks if any layer has hyperlink at location and links to first one matching
function hyperLinkAny(e) {
	if (hyperLinkLayers.length>0) {
		var j = -1;
		fIndex = 0;
		for (var i=layerCount-1;i>-1;i--) {
			
			if ((mapScaleFactor>=LayerMinScale[i]) && (mapScaleFactor<=LayerMaxScale[i]) && (LayerVisible[i]==1)) {
				fIindex = -1;
				for (var k = hyperLinkLayers.length-1;k>-1;k--) {
					if (hyperLinkLayers[k]==LayerName[i]) {
						fIndex = k;
						j = i;
					}
				}
			}

		}
		if (j>-1) {
			fID = j;
			highlightedOne="";
			var theX = mouseX;
			var theY = mouseY;
			getMapXY(theX,theY);
			searchTolerance = (xDistance/iWidth) * pixelTolerance;
			var west1 = mapX - searchTolerance;
			var north1 = mapY + searchTolerance;
			var east1 = mapX + searchTolerance;
			var south1 = mapY - searchTolerance;
			idSouth = south1;
			idNorth = north1;
			idWest = west1;
			idEast = east1;
			var tempSwap = swapSelectFields;
			swapSelectFields=false;
			var tempSelect = selectFields;
			selectFields = LayerIDField[fID] + " " + LayerShapeField[fID] + " " + hyperLinkFields[fIndex];
			var theString = writeIdentifyXML(LayerID[fID],LayerType[fID],selectFields,west1,south1,east1,north1,maxFeaturesReturned,useLimitExtent);

			selectFields = tempSelect;
			swapSelectFields=tempSwap;
			showRetrieveData();
			//if (useTextFrame) parent.TextFrame.document.location = "text.htm";
			sendToServer(imsQueryURL,theString,16);
			
		} else {
			alert(msgList[114]);
		}
	} else {
		alert(msgList[115]);
	}
}

function parseHyperLinkAny(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 = hyperLinkFields[fIndex] + "=";
		
		newSelectCount += 1;

		endpos = 1;
		pos = theReply.indexOf(searchStr,1);
		startpos = pos + searchStr.length + 1;
		endpos =theReply.indexOf(dQuote,startpos);
		inData = theReply.substring(startpos,endpos);
		var theLinkURL = hyperLinkPrefix[fIndex] + inData + hyperLinkSuffix[fIndex];
		if (parent.TextFrame!=null) {
			parent.TextFrame.document.open();
			parent.TextFrame.document.writeln('<html><meta http-equiv="Content-Type" content="text/html; charset=' + charSet + '"><head>');
			parent.TextFrame.document.writeln('	<title>' + titleList[9] + 's</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[fID] +'</B></font><FONT FACE="Arial" size="-2">');
			parent.TextFrame.document.writeln('<br>' + msgList[67] + theLinkURL );
			parent.TextFrame.document.writeln('</FONT>');
			parent.TextFrame.document.writeln('</body></html>');
			parent.TextFrame.document.close();
		}
		var Win1=open(theLinkURL,"",linkString);
	} else if (fID<layerCount) {
			fID++;
			var j = -1;
			if ((mapScaleFactor>=LayerMinScale[fID]) && (mapScaleFactor<=LayerMaxScale[fID]) && (LayerVisible[fID]==1)) {
				fIindex = -1;
				for (var k = hyperLinkLayers.length-1;k>-1;k--) {
					if (hyperLinkLayers[k]==LayerName[fID]) {
						fIndex = k;
						j = fID;
					}
				}
			}
			if (j>-1) {
				var tempSwap = swapSelectFields;
				swapSelectFields=false;
				var tempSelect = selectFields;
				selectFields = LayerIDField[fID] + " " + LayerShapeField[fID] + " " + hyperLinkFields[fIndex];
				var theString = writeIdentifyXML(LayerID[fID],LayerType[fID],selectFields,idWest,idSouth,idEast,idNorth,maxFeaturesReturned,useLimitExtent);
	
				selectFields = tempSelect;
				swapSelectFields=tempSwap;
				showRetrieveData();
				//if (useTextFrame) parent.TextFrame.document.location = "text.htm";
				sendToServer(imsQueryURL,theString,16);
			} else {
				parseHyperLinkAny("");
			}
	

	} else {
	
		//alert(tempString);
		if (parent.TextFrame!=null) {
			parent.TextFrame.document.open();
			parent.TextFrame.document.writeln('<html><meta http-equiv="Content-Type" content="text/html; charset=' + charSet + '"><head>');
			parent.TextFrame.document.writeln('	<title>' + titleList[9] + '</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" size="-1">');
			//parent.TextFrame.document.writeln('<B>' + LayerName[ActiveLayerIndex] +'</B></font><FONT FACE="Arial" size="-2">');
			parent.TextFrame.document.writeln('<br>' + msgList[116]);
			/*
			if (debugOn>0) {
				parent.TextFrame.document.writeln('<p>' + msgList[65] + '<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 = msgList[69];
			if (debugOn>0) {
				msg = msg + msgList[9] + theReply;
			}
			alert(msg);
		}
	}
	hideRetrieveData();
}

// Calcolo delle prestazioni in corso:
// - estrae dal layer con il finto grid i valori della cella in cui si trova il cursore
// - interroga il layer dei comuni
function prestazioniStep1(theReply) {

	setLayerFields(ActiveLayerIndex);

	var featureCount = justGetFeatureCount(theReply);
	var startpos     = 0;
	var endpos       = xmlEndPos;
	var selectedData = "";

	if (featureCount == 0) {
	
		hideRetrieveData();
	
	} else {
	
		endpos       = 1;
		selectedData = parseRecordString(theReply, endpos);
		endpos       = xmlEndPos;

		var fName1  = getFieldNames(selectedData);
		var fValue1 = getFieldValues(selectedData);
				
		var idFieldNum    = -1;
		var shapeFieldNum = -1;
		if (hideIDFieldData) {
			// hide ID column header
			for (var f=0;f<fName1.length;f++) {
				if (fName1[f]==LayerIDField[ActiveLayerIndex]) idFieldNum = f;
			}
		}
		if (hideShapeFieldData) {
			// hide Shape column header
			for (var f=0;f<fName1.length;f++) {
				if (fName1[f]==LayerShapeField[ActiveLayerIndex]) shapeFieldNum = f;
			}
		}
		
		//Inserisce le coordinate del mouse		
		CPElencoValori  = "X=" + mapX + "&Y=" + mapY;
		
		//Loop sui campi del layer
		for (var f=0;f<fName1.length;f++) {	
			if ((f!=idFieldNum) && (f!=shapeFieldNum)) {
				CPElencoValori = CPElencoValori + '&' + fName1[f] + '=' + fValue1[f];
			}
		}

		fName1 = null;
		fValue1 = null;

		//Attiva il layer dei comuni ed esegue la stessa interrogazione
		setActiveLayer1(IDComuniLn);
		var tempWest  = mapX - searchTolerance;
		var tempNorth = mapY + searchTolerance;
		var tempEast  = mapX + searchTolerance;
		var tempSouth = mapY - searchTolerance;
		var theString = writeGetFeatures(tempWest,tempSouth,tempEast,tempNorth,maxFeaturesReturned);
		sendToServer(imsQueryURL,theString,identifyXMLMode);

	}
					
}

// Calcolo delle prestazioni in corso
// - estrae dal layer dei comuni i dati del comune in cui si trova il cursore
function prestazioniStep2(theReply) {

	setLayerFields(ActiveLayerIndex);

	var featureCount = justGetFeatureCount(theReply);
	var startpos     = 0;
	var endpos       = xmlEndPos;
	var selectedData = "";

	if (featureCount > 0) {
	
		endpos       = 1;
		selectedData = parseRecordString(theReply, endpos);
		endpos       = xmlEndPos;

		var fName1  = getFieldNames(selectedData);
		var fValue1 = getFieldValues(selectedData);
				
		var idFieldNum    = -1;
		var shapeFieldNum = -1;
		if (hideIDFieldData) {
			// hide ID column header
			for (var f=0;f<fName1.length;f++) {
				if (fName1[f]==LayerIDField[ActiveLayerIndex]) idFieldNum = f;
			}
		}
		if (hideShapeFieldData) {
			// hide Shape column header
			for (var f=0;f<fName1.length;f++) {
				if (fName1[f]==LayerShapeField[ActiveLayerIndex]) shapeFieldNum = f;
			}
		}
				
		//Loop sui campi del layer
		for (var f=0;f<fName1.length;f++) {	
			if ((f!=idFieldNum) && (f!=shapeFieldNum)) {
				CPElencoValori = CPElencoValori + '&' + fName1[f] + '=' + fValue1[f];
			}
		}

		fName1 = null;
		fValue1 = null;

	}
					
	hideRetrieveData();

	//Apre il foglio per il calcolo delle prestazioni
	CalcoloPrestazioni = CalcoloPrestazioni + 1;
	var Win1 = window.open(appDir + "prestazioni.asp?" + CPElencoValori,"CalcoloPrestazioni"+CalcoloPrestazioni,"width="+screen.width+",height="+screen.height+",left=0,top=0,scrollbars=yes,resizable=yes,status=yes,toolbar=yes,menubar=yes,location=no");		

	//Attiva il layer con il finto grid per un nuovo calcolo
	setActiveLayer1(IDQuadrati);

}
