// aimsQuery.js
/*
*  JavaScript template file for ArcIMS HTML Viewer
*		dependent on aimsXML.js, ArcIMSparam.js, aimsCommon.js, aimsMap.js, aimsIdentify.js, aimsSelect.js, and aimsLayers.js
*		To be interactive, dependent also on aimsDHTML.js, aimsClick.js, and aimsNavigation.js
*/

aimsQueryPresent=true;

var showSampleValues=false;
var nextSample=0;

var storedQueryCount = 0;

var storedQueryName = new Array();
var storedQueryString = new Array();
var storedQueryVariable = new Array();
var storedQueryVarCount = new Array();
var storedQueryFieldList = new Array();
var storedQueryIndex = 0;
//Inizio LabelFieldStoredQuery : LSQ
var storedQueryField = new Array();
//Fine LabelFieldStoredQuery : LSQ

/*
***************************************************************************************

Querying functions

***************************************************************************************
*/


// query form
function queryForm() {

	if (checkIfActiveLayerAvailable()) {

		fieldIndex=0;
		showSampleValues=false;
		setLayerFields(ActiveLayerIndex);

		if (showSampleValues) {
			var theText = writeFieldSample(LayerFields[fieldIndex]);
			sendToServer(imsQueryURL,theText,40);
		} else {
			writeQueryForm();
		}
	} else {
		toolMode=1;
	}

}

// write out a query form
function writeQueryForm() {
	var url = appDir + "query.htm";
	if (useTextFrame) {
		parent.TextFrame.document.location = url;
	} else {
		var Win1 = open(url,"QueryWindow","width=575,height=150,scrollbars=yes,resizable=yes");
	}
}


//Inizio NQB
//Funzione di lancio del NewQueryBuilder su jsp
function NewQueryBuilderForm() {
	if (checkIfActiveLayerAvailable()) {
		fieldIndex=0;
		showSampleValues=false;
		setLayerFields(ActiveLayerIndex);
		nqb_csi_QueryDaAggiungere = "";
		if ( (useProfProgr) && (findElementInArray(costrArrayGrPr("GROUP"),LayerName[ActiveLayerIndex])==true) ){
			//E' attiva la profilazione utente,
			//e l'attuale layer attivo è tra quelli su cui attivare la profilazione
			//viene aggiunta la stringa per filtrare in SPATIALQUERY
			nqb_csi_QueryDaAggiungere += " AND (" + campoQuery + '=' + costrArrayGrPr("PROGR")[0] ;
			if ( (costrArrayGrPr("PROGR").length == 1 )){
			        //E' presente solo un parametro da inserire nella Query
	  		        nqb_csi_QueryDaAggiungere += ') ';
   			}else{
				for (var indexQueryB=1;indexQueryB<costrArrayGrPr("PROGR").length;indexQueryB++){
				   nqb_csi_QueryDaAggiungere += ' OR ' + campoQuery + '=' + costrArrayGrPr("PROGR")[indexQueryB];
				}
				nqb_csi_QueryDaAggiungere += ') ';
			}
		}

		//alert(appDir);
		//var url = appDir + "query.htm";
		//alert();
		//parent.NewQueryBuilderFrame.document.location = "lanciaNQB.htm";
		//alert('NQB= ' + parent.MapFrame.ActiveLayerIndex);
		
		if (parent.MapFrame.nqb_csi_ArrayDBSource[parent.MapFrame.ActiveLayerIndex]=="") alert("Layer non abilitato");
		else parent.TextFrame.document.location = "lanciaNQB.htm";
	}

}

//Funzione di ritorno dalla jsp del NQB
function sendNewQueryBuilderString(theRequest, condizione) {
	QueryLayerAttivo=condizione;
	QueryLayerAttivo = QueryLayerAttivo.replace(/&apos;/g, '\'');
	//var newString = fixSingleQuotes(newString);
        //newString = swapQuotes(newString);
	//newString = makeXMLsafe(newString);
	//setQueryString=newString;
	selectionMode=1;
	selectData.length=0;
	LayerFields.length=0;
	LayerFieldType.length=0;
	LayerFieldCount=0;
	highlightedOne="";
	showBuffer=false;
	showRetrieveData();

	//var theString = writeQueryXML(newString);
	/*Sostituito con ...*/
	if (swapSelectFields) {
		selectFields=selFieldList[ActiveLayerIndex];
	}
	selectLayer=ActiveLayer;
	selectType=ActiveLayerType;
	selectCount=0;
	hightlightedOne="";
	selectPoints.length=1;
	selectLeft.length=1;
	selectRight.length=1;
	selectTop.length=1;
	selectBottom.length=1;
	/*Fine sostituzione*/
	var theString = theRequest.replace(/&quot;/g, '"');
	theString = theString.replace(/&apos;/g, '\'');
	//prompt(theString);
	sendToServer(imsQueryURL,theString,queryXMLMode);
}

function sendNewQueryBuilderBuffer(theRequest,tmpIDLayerCT,tmpCondizioneCT,tmpCondizioneLayerAttivo) {
	//var newString = fixSingleQuotes(newString);
        //newString = swapQuotes(newString);
	//newString = makeXMLsafe(newString);
	//setQueryString=newString;

	IDLayerCT = tmpIDLayerCT;
	CondizioneCT = tmpCondizioneCT;
	QueryLayerAttivo = tmpCondizioneLayerAttivo;
	QueryLayerAttivo = QueryLayerAttivo.replace(/&apos;/g, '\'');

	bufferTargetLayerIndex=ActiveLayerIndex;
	selectionMode=1;
	selectData.length=0;
	LayerFields.length=0;
	LayerFieldType.length=0;
	LayerFieldCount=0;
	highlightedOne="";
	showBuffer=false;
	showRetrieveData();

	//var theString = writeQueryXML(newString);
	/*Sostituito con ...*/
	if (swapSelectFields) {
		selectFields=selFieldList[ActiveLayerIndex];
	}
	selectLayer=ActiveLayer;
	selectType=ActiveLayerType;
	selectCount=0;
	hightlightedOne="";
	selectPoints.length=1;
	selectLeft.length=1;
	selectRight.length=1;
	selectTop.length=1;
	selectBottom.length=1;
	/*Fine sostituzione*/
	var theString = theRequest.replace(/&quot;/g, '"');
	theString = theString.replace(/&apos;/g, '\'');
	sendToServer(imsQueryURL,theString,11);
	//sendToServer(imsQueryURL,theString,queryXMLMode);
}
//Fine NQB



// find Form
function findForm() {
	if (checkIfActiveLayerAvailable()) {
		setLayerFields(ActiveLayerIndex);
		if (useTextFrame) {
			parent.TextFrame.document.location= appDir + "findForm.htm";
		} else {
			var Win1 = open(appDir + "findForm.htm","QueryWindow","width=575,height=150,scrollbars=yes,resizable=yes");
		}
	}
}

//INIZIO Profilazione Utenti: PRU
// process query
function sendQueryString(newString) {

		if ( (useProfProgr) && (findElementInArray(costrArrayGrPr("GROUP"),LayerName[ActiveLayerIndex])==true) )
		{
		//E' attiva la profilazione utente,
		//e l'attuale layer attivo è tra quelli su cui attivare la profilazione
		//viene aggiunta la stringa per filtrare in SPATIALQUERY
		newString += " AND (" + campoQuery + '=' + costrArrayGrPr("PROGR")[0] ;
		if ( (costrArrayGrPr("PROGR").length == 1 ))
			{//E' presente solo un parametro da inserire nella Query
	  		newString += ') ';
   		}
		else
			{
			//newString += '<SPATIALQUERY where="' + campoQuery + '=' + arrayQuery[0];

			for (var indexQueryB=1;indexQueryB<costrArrayGrPr("PROGR").length;indexQueryB++)
				{
			   newString += ' OR ' + campoQuery + '=' + costrArrayGrPr("PROGR")[indexQueryB];
			   }
			newString += ') ';
			}
		}

		//L'apice singolo viene trasformato in doppio apice in modo che possibili
		//apostrofi all'interno della query manuale siano interpretati correttamente
		//dalle funzioni di trasformazione di caratteri che seguono.
		//newString = newString.replace(/'/g, "\"");

	//if (LayerIDField[ActiveLayerIndex]!="#ID#") {
		//Commentata la funzione fixSingleQuotes.
		var newString = fixSingleQuotes(newString);
//FINE Profilazione Utenti

	newString = swapQuotes(newString);
	
	newString = makeXMLsafe(newString);
	setQueryString=newString;
	selectionMode=1;
	selectData.length=0;
	LayerFields.length=0;
	LayerFieldType.length=0;
	LayerFieldCount=0;
	highlightedOne="";
	showBuffer=false;
	showRetrieveData();
	var theString = writeQueryXML(newString);
	sendToServer(imsQueryURL,theString,queryXMLMode);
}

// write out XML request to query attributes
function writeQueryXML(queryString) {
	if (swapSelectFields) {
		selectFields=selFieldList[ActiveLayerIndex];
	}
	var theString = '<ARCXML version="1.1">\n<REQUEST>\n<GET_FEATURES outputmode="xml" geometry="false" envelope="true" checkesc ="true"';
	//theString += ' featurelimit="' + maxFeaturesReturned + '" beginrecord="' + queryStartRecord + '">\n';
        theString += '>\n';
	theString += '<LAYER id="' + ActiveLayer + '" />';
	if (useLimitExtent) {
		// keep this within the limitExtent
		theString += '<SPATIALQUERY subfields="' + selectFields + '" where="' + queryString + '">';
		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 += '</SPATIALQUERY>\n';
	} else {
	//theString += '<QUERY subfields="' + selectFields + '" where="' + queryString + '" />';
	theString += '<SPATIALQUERY subfields="' + selectFields + '" where="' + queryString + '" />';
	}
	theString += '</GET_FEATURES>';
	theString += '</REQUEST>';
	theString += '</ARCXML>';
	//alert("writeQueryXML()\nQuery XML Request:\n" + theString);
	selectLayer=ActiveLayer;
	selectType=ActiveLayerType;
	selectCount=0;
	hightlightedOne="";
	selectPoints.length=1;
	selectLeft.length=1;
	selectRight.length=1;
	selectTop.length=1;
	selectBottom.length=1;
	return theString;

}

// write out XML request to get field value samples
function writeFieldSample(theField) {
	var theFields = theField;
	var theString = '<ARCXML version="1.1">\n<REQUEST>\n<GET_FEATURES outputmode="xml" geometry="false" envelope="false" checkesc ="true"';
	if (nextSample>0){
	   theString += ' beginrecord="'+numberDataSamples*nextSample+'" featurelimit="' + numberDataSamples + '">\n';
	} else {
	   theString += ' featurelimit="' + numberDataSamples + '">\n';
	}

	theString += '<LAYER id="' + ActiveLayer + '" />';

	//INIZIO Profilazione Utenti: PRU
	//Viene filtrata anche la funzione che ricava i valori che riempiono
	//la combobox degli esempi
	//Essendo la variabile "LayerID[ActiveLayerIndex]" l'id
	//del layer in esame
	//viene calcolato il rispettivo indice di posizione del layer
	//così come è presente nell'AXL con la funzione getLayerNameByIndex(index)
	//In questo modo si ottiene il nome del layer in esame
	var elemento = LayerName[getLayerNameByIndex(LayerID[ActiveLayerIndex])];

	//Se è presente la profilazione utenti (presente il comando GROUP)
	//Viene creata la <SPATIALQUERY... in base al gruppo e alla profilazione
	//Viene verificato che il layer passato come parametro in "elemento"
	//sia presente nell'array dei gruppi su cui effettuare la profilazione
	if ( (useProfProgr) && (findElementInArray(costrArrayGrPr("GROUP"),elemento)==true) )
		{
		theString += cr_useProfProgr(elemento,costrArrayGrPr("GROUP"),costrArrayGrPr("PROGR"),theFields);
		theString += ' />\n';
		/*theString += '<SPATIALQUERY subfields="' + theFields + ' " where="CATASTO.FOGLI.COD_FISC= \'A587\'"  />';*/
		}
	else
		{
	//theString += '<QUERY subfields="' + theFields + '" where="' + LayerIDField[ActiveLayerIndex] + ' GT 0" />';
	theString += '<QUERY subfields="' + theFields + '" />';
		}
	//FINE Profilazione Utenti

	theString += '</GET_FEATURES>';
	theString += '</REQUEST>';
	theString += '</ARCXML>';
	//alert(theString);
	selectLayer=ActiveLayer;
	selectType=ActiveLayerType;
	selectCount=0;
	hightlightedOne="";
	selectPoints.length=1;
	selectLeft.length=1;
	selectRight.length=1;
	selectTop.length=1;
	selectBottom.length=1;
	//alert(theString);
	return theString;
}
// send find request
function getFind(theValue) {
	//alert(theValue);
	selectCount=0;
	showBuffer=false;
	highlightedOne="";
	selectPoints.length=0;
	selectLeft.length=0;
	selectRight.length=0;
	selectTop.length=0;
	selectBottom.length=0;
	drawSelectBoundary=false;
	showGeocode=false;
	clickCount=0;
	totalMeasure=0;
	currentMeasure=0;
	selectionMode=1;
	var theNewQueryString = "";
	var theTempString = "";
	var fieldListString = LayerIDField[ActiveLayerIndex] + " " + LayerShapeField[ActiveLayerIndex];
	var elemCount = 0;
	for (var i=0;i<LayerFields.length;i++) {
		if (LayerFieldType[i].indexOf("12",0)!=-1) {
			if (queryCaseInsensitive) {
				theTempString = "(UPPER(" + LayerFields[i] + ") LIKE '%" + theValue.toUpperCase() + "%')";
			} else {
				theTempString = "(" + LayerFields[i] + " LIKE '%" + theValue + "%')";
			}
			if (elemCount>0) theTempString = " OR " + theTempString;
			//if (theNewQueryString.length + theTempString.length < 1024) {
				theNewQueryString = theNewQueryString + theTempString;
				fieldListString = fieldListString + " " + LayerFields[i];
				elemCount += 1;
			//}

		}
	}
	if (theNewQueryString!="") {
		showRetrieveData();
		showBuffer=false;
		theNewQueryString=makeXMLsafe(theNewQueryString);
		setQueryString = theNewQueryString;
		var theString = writeFindRequest(theNewQueryString,fieldListString);
		//alert(theString);
		sendToServer(imsQueryURL,theString,findXMLMode);
	} else {
		alert(msgList[80]);
	}
}

// write out find form
function writeFindRequest(findQuery,fieldList) {
	var theString = '<ARCXML version="1.1">\n<REQUEST>\n<GET_FEATURES outputmode="xml" geometry="false" envelope="true" checkesc ="true"';
	theString += ' featurelimit="' + maxFeaturesReturned + '" beginrecord="' + queryStartRecord + '">\n';
	theString += '<LAYER id="' + ActiveLayer + '" />\n';
	if (useLimitExtent) {
		// keep this within the limitExtent
		theString += '<SPATIALQUERY subfields="' + fieldList + '" where="' + findQuery + '" />';
		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 += '</SPATIALQUERY>\n';
	} else {
	theString += '<QUERY subfields="' + fieldList + '" where="' + findQuery + '" />';
	}
	theString += '</GET_FEATURES>\n';
	theString += '</REQUEST>\n';
	theString += '</ARCXML>';
	//alert(theString);
	selectLayer=ActiveLayer;
	selectType=ActiveLayerType;
	selectCount=0;
	hightlightedOne="";
	selectPoints.length=1;
	selectLeft.length=1;
	selectRight.length=1;
	selectTop.length=1;
	selectBottom.length=1;
	return theString;

}

// parse layer field value samples
function parseFieldSamples(theReply) {
   var postemp=theReply.indexOf('hasmore="true"');
   if (postemp>-1)
      nextSample++;
   else
      nextSample=0;

   theReply=parseEntity(theReply);
	if (onlyUniqueSamples) {
		parseFieldSamplesUnique(theReply);
	} else {
		//alert("Reply Length: " + theReply.length);
		//alert(theReply);
		var fList="";
		var lpos1 = 1;
		var lpos2 = 1;
		var epos = 1;
		var spos = 1;
		var morePoints=true;
		var moreFeatures=true;
		var pos = 0;
		var startpos = 0;
		var endpos = 0;
		var featureCount = justGetFeatureCount(theReply);
		var tempString="";
		if (featureCount > 0) {
			selectData.length=featureCount;
			for (var i=0;i<featureCount;i++) {
				pos = theReply.indexOf("<FIELDS ",endpos);
				startpos = pos + 8;
				endpos =theReply.indexOf(' />',startpos);
				inData = theReply.substring(startpos,endpos);
				//inData = fixSingleQuotes(inData);
				//selectData[i] = clearLeadingSpace(inData);
				//selectData[i] = escape(inData);
				selectData[i] = inData;
			}
		} else {
			selectData.length=0;
		}
	}
}

//replace the original function parseFieldSamples with this function parseFieldSamples
// parse layer field value samples
function parseFieldSamplesUnique(theReply) {
	//alert("Reply Length: " + theReply.length);
	//alert(theReply);
	var fList="";
	var lpos1 = 1;
	var lpos2 = 1;
	var epos = 1;
	var spos = 1;
	var morePoints=true;
	var moreFeatures=true;
	var pos = 0;
	var startpos = 0;
	var endpos = 0;
	var featureCount = justGetFeatureCount(theReply);
	//alert(theReply);
	var tempString="";
	//variables added to original function
	var k = 1;
	var sdLeng = 0;
	var charSort = false;

	if (featureCount > 0) {

	//Add the first sample value
		for (var i=0;i<1;i++) {
			if (selectData.length>0) {
				selectData.length=0;
			}
			pos = theReply.indexOf("<FIELDS ",endpos);
			startpos = pos + 8;
			endpos =theReply.indexOf(' />',startpos);
			inData = theReply.substring(startpos,endpos);
			selectData[i] = inData;
		}

	//Add additional sample values
		for (var i=1;i<featureCount;i++) {

			pos = theReply.indexOf("<FIELDS ",endpos);
			startpos = pos + 8;
			endpos =theReply.indexOf(' />',startpos);
			inData = theReply.substring(startpos,endpos);
			sdLeng = selectData.length;

			for (var j=0;j<sdLeng;j++){
				if (selectData[j] == inData){
					addValue = false;
					break;
				} else {
					addValue = true;
				}
			}

			if (addValue){
				selectData[k] = inData;
				k = k + 1;
			}
		}

	} else {
		selectData.length=0;
	}
	//alert(selectData.length);
	var testSample = selectData[0];
	var testPos = testSample.indexOf('"');
	var testStartPos = testPos+1;
	var testEndPos = testSample.indexOf('"',testStartPos);
	var testValue = testSample.substring(testStartPos,testEndPos);
	var testLeng = testValue.length;
	///*
	//Test for non-numeric characters in the string
	for (l=0;l<testLeng;l++){
		testChar = testValue.substring(l+1);
		testChar = Number(testChar);
		if (isNaN(testChar)) {
			charSort = true;
			break;
		}
	}
	//*/
	if (charSort) {
		selectData.sort();
	} else {
	  selectData.sort(compare);
	}

}

//add this below the new function parseFieldSamples
//function to compare numeric values for function parseFieldSamples numeric sort
function compare(a,b){
	var returnVal = 0;
	var aPos = a.indexOf('"');
	var aStartPos = aPos+1;
	var aEndPos = a.indexOf('"',aStartPos);
	var aValue = a.substring(aStartPos,aEndPos);
	var aNum = Number(aValue);

	var bPos = b.indexOf('"');
	var bStartPos = bPos+1;
	var bEndPos = b.indexOf('"',bStartPos);
	var bValue = b.substring(bStartPos,bEndPos);
	var bNum = Number(bValue);

	var theVal =  aValue - bValue;

	if (isNaN(theVal)) {
		returnVal = -1;
	} else {
		returnVal = theVal;
	}

	return returnVal;

}


// temporarily change getSampleValues to true and load queryform
function tempGetSamples(theField) {
	showSampleValues=true;
	if (useTextFrame) {
		var Win1 = parent.TextFrame;

	} else {
		var Win1 = open("","QueryWindow","width=575,height=150,scrollbars=yes,resizable=yes");
	}
	Win1.document.open();
	Win1.document.writeln('<html><meta http-equiv="Content-Type" content="text/html; charset=' + charSet + '">');
	Win1.document.writeln('<HEAD><link rel="stylesheet" href="'+pagStile+'" type="text/css">');
	Win1.document.writeln('<body size="-1">');
	Win1.document.writeln('<div align="center"><b>');
	Win1.document.writeln(msgList[74] + LayerName[ActiveLayerIndex] + '. . .</b><br>');
	if (onlyUniqueSamples) {
		Win1.document.writeln('<font size="-1">' + msgList[75] + numberDataSamples + msgList[122] + '</font></div></body></html>');
	} else {
		Win1.document.writeln('<font size="-1">' + msgList[75] + numberDataSamples + msgList[76] + '</font></div></body></html>');
	}
	Win1.document.close();
	Win1=null;
	var theText = writeFieldSample(theField);
        //alert("theText\n" + theText);
	sendToServer(imsQueryURL,theText,40);

}

// get the StoredQueries in the MapService
function getStoredQueries() {
	if (checkIfActiveLayerAvailable()) {
		var theString = '<ARCXML version="1.1">\n<REQUEST>\n<GET_SERVICE_INFO renderer="false" extensions="true" fields="false" />\n';
		theString += '</REQUEST>\n</ARCXML>';
		
alert(theString);
		
		sendToServer(imsQueryURL,theString,55);
	}
}

// get the StoredQueries in the MapService
function parseStoredQueries(theReply) {
	//alert(theReply);
	storedQueryCount=0;
	storedQueryName.length=1;
	storedQueryString.length=1;
	storedQueryVariable.length=1;
	storedQueryVarCount.length=1;
	storedQueryFieldList.length=1;

        //Inizio LabelFieldStoredQuery : LSQ
	storedQueryField.length=1;
	//Fine LabelFieldStoredQuery : LSQ

	storedQueryIndex=0;
	var endpos = 1;
	var pos = -1;
	var blurb = 'id="' + ActiveLayer;
	var startpos = theReply.indexOf("<LAYERINFO",1);
	var thePos = 1;
	while (thePos!=-1) {
		startpos = theReply.indexOf("<LAYERINFO",1);
		endpos = theReply.indexOf(">",startpos);
		thePos = theReply.indexOf(blurb,1);
		if (thePos!=-1) {
			pos = thePos;
			thePos=-1;
		}
	}
	var sqpos = 0;
	var sqvpos = 0;
	var sqpos2 = 0;
	var vCount=0;
	if (pos!=-1) {
		var fieldCount = 0;
		epos = theReply.indexOf("</LAYERINFO>",pos);
		startpos=0;
		endpos=pos;
		sqpos = theReply.indexOf("<STOREDQUERY name=",endpos);
		sqpos2 = theReply.indexOf("</STOREDQUERY>",endpos);
		while ((epos>sqpos) && (sqpos!=-1)) {

			if (sqpos!=-1) {
				startpos = sqpos + 19;
				endpos = theReply.indexOf(dQuote, startpos);
				blurb = theReply.substring(startpos,endpos);
				//alert(blurb);
				storedQueryName[storedQueryCount] = blurb;

				//startpos = theReply.indexOf("<QUERY where=",endpos);
				var sp2 = theReply.indexOf("<QUERY ",endpos);
				sp2 += 7;
				startpos = theReply.indexOf("where=",sp2);
				startpos += 7;
				endpos = theReply.indexOf(dQuote, startpos);
				blurb = theReply.substring(startpos,endpos);
				storedQueryString[storedQueryCount] = blurb;
				startpos = theReply.indexOf("subfields=",sp2);
				startpos += 11;
				endpos = theReply.indexOf(dQuote, startpos);
				storedQueryFieldList[storedQueryCount] = theReply.substring(startpos,endpos);
				storedQueryVariable[storedQueryCount]="";
                                //Inizio LabelFieldStoredQuery : LSQ
				storedQueryField[storedQueryCount]="";
				//Fine LabelFieldStoredQuery : LSQ
				sqvpos = theReply.indexOf("<SQVAR",startpos);
				vCount = 0;
				while ((sqvpos!=-1) && (sqvpos<sqpos2)) {
					endpos = sqvpos;
					startpos = theReply.indexOf("name=",endpos);
					startpos += 6;
					endpos = theReply.indexOf(dQuote, startpos);
					blurb = theReply.substring(startpos,endpos);
					if (vCount > 0) blurb = "|" + blurb;
					storedQueryVariable[storedQueryCount] = storedQueryVariable[storedQueryCount] + blurb;
					//Inizio LabelFieldStoredQuery : LSQ
					//individuo anche il nome del campo a cui è associato il valore
					startpos = theReply.indexOf("name=",endpos);
					startpos += 6;
					endpos = theReply.indexOf(dQuote, startpos);
					blurb = theReply.substring(startpos,endpos);
					//alert("blurb = "+blurb);
					if (vCount > 0) blurb = "|" + blurb;
					storedQueryField[storedQueryCount] = storedQueryField[storedQueryCount] + blurb;
					//Fine LabelFieldStoredQuery : LSQ
                                        vCount += 1;
					sqvpos = theReply.indexOf("<SQVAR",startpos);
				}
				storedQueryVarCount[storedQueryCount] = vCount;

                                //Inizio LabelFieldStoredQuery : LSQ
				caricaLabelStoredQuery(storedQueryField[storedQueryCount],storedQueryVarCount[storedQueryCount],storedQueryCount);
				//Fine LabelFieldStoredQuery : LSQ
				storedQueryCount += 1;
			}


			sqpos = theReply.indexOf("<STOREDQUERY name=",endpos);
			sqpos2 = theReply.indexOf("</STOREDQUERY>",sqpos);
		}
	}
	blurb=null;
	if (storedQueryCount==0) {
		alert(LayerName[ActiveLayerIndex] + msgList[77]);
	} else {
		storedQueryForm();
	}
}

// storedQuery Form
function storedQueryForm() {
	if (checkIfActiveLayerAvailable()) {
		writeStoredQueryForm(storedQueryIndex);
	}
}

function writeStoredQueryForm(theIndex) {
	storedQueryIndex=theIndex;
	var url = appDir + "storedquery.htm";
	if (storedQueryVarCount==0) {
		sendStoredQuery(theIndex,"");
	} else {
		if (useTextFrame) {
			parent.TextFrame.document.location = url;
		} else {
			var Win1 = open(url,"QueryWindow","width=575,height=150,scrollbars=yes,resizable=yes");
		}

	}
}


// create the querystring for storedQuery and send it
function sendStoredQuery(theIndex,theValue) {
	showRetrieveData();
	var oldString = storedQueryString[theIndex];
	if (theValue!=""){
		if (storedQueryVarCount[theIndex]>0) {
			var var1 = storedQueryVariable[theIndex].split("|");
			var var2 = theValue.split("|");
			for (var i=0;i<var1.length;i++) {
				oldString = swapStuff(oldString,var1[i],var2[i]);
			}

		} else {
			oldString = swapStuff(oldString,storedQueryVariable[theIndex],theValue);
		}
	}
	//var newString = parseEntity(oldString);
	//alert("makeXMLsafe");
	var newString = makeXMLsafe(oldString);
	//alert(newString);
	setQueryString = newString;
	selectionMode=1;
	var theString = writeQueryXML(newString);
	//alert("StoredQuery Request:\n" + theString);
        //prompt("StoredQuery Request: " , theString);
	sendToServer(imsQueryURL,theString,queryXMLMode);
}

// see if there are storedQueries (Search)
function checkStoredQueries(theReply) {

	var startpos = theReply.indexOf("<STOREDQUERY",1);
	if (startpos==-1) {
		//no storedqueries. . . do not display button
		useStoredQuery=false;
	}

}

function writeStartQueryXML(queryString, idAndShapeOnly) {
	if (swapSelectFields) {
		selectFields=selFieldList[ActiveLayerIndex];
	}
	var theString = '<ARCXML VERSION="1.1">\n<REQUEST>\n<GET_FEATURES outputmode="xml" geometry="false" envelope="true" checkesc ="true"';
	theString += ' compact="true" featurelimit="' + maxFeaturesReturned + '" beginrecord="0">\n';
	theString += '<LAYER id="' + LayerID[ActiveLayerIndex] + '" />';
	if (idAndShapeOnly) {
		theString += '<QUERY subfields="#ID# #SHAPE#" where="' + queryString + '" />';
	} else {
		theString += '<QUERY subfields="' + selectFields + '" where="' + queryString + '" />';
	}
	theString += '</GET_FEATURES>';
	theString += '</REQUEST>';
	theString += '</ARCXML>';
	//alert(theString);
	return theString;

}

//DIEGO setStartQuery() FUNZIONE SOSTITUITA PRESA DA UN ALTRO GEDEONE ELIMINATA L'AGGIUNTA DRV
//DRV CREA PROBLEMI CON IL PARAMETRO QUERYZOOM=YES NECESSARIO IN ALCUNE CHIAMATE A DRV
function setStartQuery()
	{

	//INIZIO LAYER QUERY: laq
	if (laq_csi_useZoomGRP) {
		//Nella URL è presente GRP=x: x indica quale record dell'array
		//laq_csi_GroupIdLayer[] deve essere utilizzato per ricercare l'id passato
		//in OR=id|y|z e che, una volta trovato all'interno di uno dei layer
		//indicati nel record di laq_csi_GroupIdLayer[] stesso, individuerà proprio il
		//layer che dovrà essere reso attivo e su cui verranno evidenziati
		//tutti gli oggetti presenti con id= y z.
		//E' ovvio che id dovrà essere UNIVOCO	e cioè dovrà essere presente
		//solo in uno dei layer elencati nel record di laq_csi_GroupIdLayer[]
		//Ad ogni modo la ricerca si fermerà al primo layer che contiene gli
		//id ricercati
		//

		if (laq_csi_idGRP == -2) {
			laq_csi_idGRP = laq_csi_recordOfGroupIdLayer.length - 1;
		}
    if (laq_csi_idGRP >= 0 ) {
			//arcIMS va in crash se si attiva un layer che non ha il campo id_stato
			//Viene attivato il layer su cui effettuare la ricerca.
			//parent.MapFrame.toc.layerSetActive(3);
      //Inizio NewToc : NTO
      //parent.MapFrame.toc.layerSetActive(getLayerIndexByName(laq_csi_recordOfGroupIdLayer[laq_csi_idGRP]));
			parent.MapFrame.toc[parent.MapFrame.toc_csi_tocIndex].layerSetActive(getLayerIndexByName(laq_csi_recordOfGroupIdLayer[laq_csi_idGRP]));
      //Fine NewToc : NTO
	    //FINE LAYER QUERY
	    var theString = writeStartQueryXML(highlightedOne,true);

	    //INIZIO LAYER QUERY: laq
			laq_csi_idGRP = laq_csi_idGRP - 1;
			sendToServer(imsQueryURL, theString, laq_csi_useZoomGRPXMLMode);
		}
  } else {
    //setStartQuery() originale
    var theString = writeStartQueryXML(highlightedOne,true);
    //FINE LAYER QUERY
    //INIZIO StartQuery
    document.all.theTop.style.cursor = "wait";
    theCursor = document.all.theTop.style.cursor;
    //FINE StartQuery
    sendToServer(imsQueryURL, theString, 20);
  }
}


//VERSIONE DI setStartQuery CON IL CODICE CHE GESTISCE DRV (CREA PROBLEMI CON QUERYZOOM=YES)
//function setStartQuery() {
//
//	//INIZIO LAYER QUERY: laq
//	if (laq_csi_useZoomGRP) {
//		//Nella URL è presente GRP=x: x indica quale record dell'array
//		//laq_csi_GroupIdLayer[] deve essere utilizzato per ricercare l'id passato
//		//in OR=id|y|z e che, una volta trovato all'interno di uno dei layer
//		//indicati nel record di laq_csi_GroupIdLayer[] stesso, individuerà proprio il
//		//layer che dovrà essere reso attivo e su cui verranno evidenziati
//		//tutti gli oggetti presenti con id= y z.
//		//E' ovvio che id dovrà essere UNIVOCO	e cioè dovrà essere presente
//		//solo in uno dei layer elencati nel record di laq_csi_GroupIdLayer[]
//		//Ad ogni modo la ricerca si fermerà al primo layer che contiene gli
//		//id ricercati
//		//
//
//		if (laq_csi_idGRP == -2) {
//			laq_csi_idGRP = laq_csi_recordOfGroupIdLayer.length - 1;
//		}
//
//		if (laq_csi_idGRP >= 0 ) {
//				//arcIMS va in crash se si attiva un layer che non ha il campo id_stato
//				//Viene attivato il layer su cui effettuare la ricerca.
//				//parent.MapFrame.toc.layerSetActive(3);
//		  //Inizio NewToc : NTO
//		  //parent.MapFrame.toc.layerSetActive(getLayerIndexByName(laq_csi_recordOfGroupIdLayer[laq_csi_idGRP]));
//				parent.MapFrame.toc[parent.MapFrame.toc_csi_tocIndex].layerSetActive(getLayerIndexByName(laq_csi_recordOfGroupIdLayer[laq_csi_idGRP]));
//		  //Fine NewToc : NTO
//			//FINE LAYER QUERY
//			var theString = writeStartQueryXML(highlightedOne,true);
//
//			//INIZIO LAYER QUERY: laq
//				laq_csi_idGRP = laq_csi_idGRP - 1;
//				sendToServer(imsQueryURL, theString, laq_csi_useZoomGRPXMLMode);
//		}
//
//
//		//INIZIO DRV
//		fSet_isLayerInDerivazione(laq_csi_recordOfGroupIdLayer);
//		//FINE DRV
//  }

//  //INIZIO DRV
//  else {
//  	if (drv_csi_useDRV) {
//		fSet_isLayerInDerivazione(laq_csi_recordOfGroupIdLayer);
//		if (drv_csi_countLayersDrv < LayerID.length){
//			var i = drv_csi_countLayersDrv;
//			if ((isLayerInDerivazione[i]) && (LayerIsFeature[i])){
//				var theString = writeIdentifyDerivazioneXML(LayerID[i],LayerType[i],selFieldList[i],maxFeaturesReturned,highlightedOne);
//				sendToServer(imsQueryURL,theString,8000);
//			} else {
//				replyArray[drv_csi_countLayersDrv] = "";
//				drv_csi_countLayersDrv = ++drv_csi_countLayersDrv ;
//				setStartQuery();
//			}
//		} else {
//			zoomToReturnedRecordsDerivazione();
//			drv_csi_useDRV = false;
//		}
		//FINE DRV

////  else {
    //setStartQuery() originale
//    var theString = writeStartQueryXML(highlightedOne,true);
    //FINE LAYER QUERY
    //INIZIO StartQuery
//    document.all.theTop.style.cursor = "wait";
//    theCursor = document.all.theTop.style.cursor;
//    //FINE StartQuery
//    sendToServer(imsQueryURL, theString, 20);
//	}
//  }
//}


//Vecchia versione di parseStartQuery, in cui non era possibile
//avere un'estensione che comprendesse tutti gli eventuali oggetti
//risultanti dalla query passata come parametro iniziale. E' stata sostituita
//con quella successiva.

//function parseStartQuery(theReply) {
//	//alert(theReply);
//	var theError = getXMLErrorMessage(theReply);
//	if (theError=="") {
//		if (queryZoom) {
//			getXYs(theReply);
//			startLeft = eLeft;
//			startTop = eTop;
//			startRight = eRight;
//			startBottom = eBottom;
//			var fWidth = eRight - eLeft;
//			var fHeight = eTop - eBottom;
//			var mWMargin = 0;
//			var mHMargin = 0;
//			//alert(LayerType[ActiveLayerIndex]);
//			if (LayerType[ActiveLayerIndex]=="point") {
//				selectType="point";
//				//alert("fullWidth=" + fullWidth + "\nfullHeight=" + fullHeight);
//				mWMargin = fullWidth * selectPointMargin;
//				mHMargin = fullHeight * selectPointMargin;
//			} else {
//				mWMargin = fWidth * selectMargin;
//				mHMargin = fHeight * selectMargin;
//			}
//			//alert("mWMargin=" + mWMargin + "\nmHMargin=" + mHMargin);
//			eLeft = eLeft - mWMargin;
//			eRight = eRight + mWMargin;
//			eTop = eTop + mHMargin;
//			eBottom = eBottom - mHMargin;
//			startLeft = eLeft;
//			startTop = eTop;
//			startRight = eRight;
//			startBottom = eBottom;
//
//
//		}
//		sendMapXML();
//	} else {
//		alert(theError);
//	}
//}

//PER EFFETTUARE L'ESTENSIONE MASSIMA CHE COMPRENDA PIU' DI UN OGGETTO
function parseStartQuery(theReply) {
	//INIZIO StartQuery
	document.all.theTop.style.cursor = "crosshair";
	theCursor = document.all.theTop.style.cursor;
	//FINE StartQuery
	//alert(theReply);
	var theError = getXMLErrorMessage(theReply);
	if (theError=="") {
		if (queryZoom) {
		   getMaxXY(theReply);
		   var fWidth = selMaxEnvelope[2] - selMaxEnvelope[0];
	      var fHeight = selMaxEnvelope[3] - selMaxEnvelope[1];
	      var mWMargin = 0;
	      var mHMargin = 0;
	      if (LayerType[ActiveLayerIndex]=="point") {
				selectType="point";
		      mWMargin = fullWidth * selectPointMargin;
		      mHMargin = fullHeight * selectPointMargin;
		      if (mWMargin > xDistance/2) {
			      mWMargin = xDistance/2;
			      mHMargin = yDistance/2;
		      }
	      } else {
	         if (LayerType[ActiveLayerIndex]=="line") {
	            selectType="line";
	         }
		      mWMargin = fWidth * selectMargin;
		      mHMargin = fHeight * selectMargin;
	      }
	      eLeft = selMaxEnvelope[0] - mWMargin;
	      eRight = selMaxEnvelope[2] + mWMargin;
	      eTop = selMaxEnvelope[3] + mHMargin;
	      eBottom = selMaxEnvelope[1] - mHMargin;
	      startLeft = eLeft;
			startTop = eTop;
			startRight = eRight;
			startBottom = eBottom;
		}
		sendMapXML();
	} else {
		alert(theError);
	}
}


//Restituisce i valori massimi dell'Envelope nel caso di query che
//prevedono la restituzione di più features
function getMaxXY(theReply){

   var queryFeauterCount=justGetFeatureCount(theReply);

	selectCount=queryFeauterCount;
	var endpos = 1;
	var querycount = 0;
	var fCount=selectCount

	for (var i=0;i<fCount;i++) {
	   var theXYs = getEnvelopeXYs(theReply, endpos)
		selectLeft[querycount] = theXYs[0];
		selectBottom[querycount] = theXYs[1];
		selectRight[querycount] = theXYs[2];
		selectTop[querycount] = theXYs[3];
		endpos = xmlEndPos;

		querycount+=1;
	}
	calcSelectEnvelope();
	selectCount=0;
}

//FINE PER EFFETTUARE L'ESTENSIONE MASSIMA CHE COMPRENDA PIU' DI UN OGGETTO

//Inizio LabelFieldStoredQuery : LSQ
function caricaLabelStoredQuery(stringaCampi, numVar, cont){
	//alert("stringaCampi = "+stringaCampi);
	//alert("numVar = "+numVar);
	//alert("cont = "+cont);
        splitCampi = stringaCampi.split("|");
        var tmpLabelCampi = "";
        var pos;

//alert("numVar = "+numVar);
	for (var n=0;n<numVar;n++){
		//alert(n);
		//identifico il campo da visualizzare

		if (setLabelStoredQuery[ActiveLayerIndex]==""){
			//Leggo dagli alias
			//es. fieldAliasList[ActiveLayerIndex]="CATASTO.FOGLI.N_FOGLIO:Numero foglio|#SHAPE#:_SHAPE_|"
			pos = fieldAliasList[ActiveLayerIndex].indexOf(splitCampi[n]);
			pos = pos + splitCampi[n].length + 1;
			tmpLabelCampi = tmpLabelCampi + fieldAliasList[ActiveLayerIndex].substring(pos,fieldAliasList[ActiveLayerIndex].indexOf("|",pos));
			//if (n!=numVar-1)
			tmpLabelCampi = tmpLabelCampi + "|";

		}else{
			//Leggo le nuove etichette
			//alert('splitCampi[n]='+splitCampi[n]);
			//alert('setLabelStoredQuery[ActiveLayerIndex]='+setLabelStoredQuery[ActiveLayerIndex]);
			/*
			pos = setLabelStoredQuery[ActiveLayerIndex].indexOf(splitCampi[n]);
			//pos = pos + splitCampi[n].length + 1;
			pos = setLabelStoredQuery[ActiveLayerIndex].indexOf(":", pos)+1;
			tmpLabelCampi= tmpLabelCampi + setLabelStoredQuery[ActiveLayerIndex].substring (pos,setLabelStoredQuery[ActiveLayerIndex].indexOf("|",pos));
			//if (n!=numVar-1)
			tmpLabelCampi = tmpLabelCampi + "|";
			*/
			tmp = splitCampi[n].substring(splitCampi[n].indexOf(".")+1,splitCampi[n].length);
			//alert("tmp = "+tmp);
			tmp = tmp.substring(tmp.indexOf(".")+1,tmp.length);
			//alert("tmp = "+tmp);
			pos = setLabelStoredQuery[ActiveLayerIndex].indexOf(tmp);
			//alert("pos tmp = "+pos);
			//pos = pos + splitCampi[n].length + 1;
			pos = setLabelStoredQuery[ActiveLayerIndex].indexOf(":", pos)+1;
			//alert("pos : = "+pos);
			tmpLabelCampi= tmpLabelCampi + setLabelStoredQuery[ActiveLayerIndex].substring (pos,setLabelStoredQuery[ActiveLayerIndex].indexOf("|",pos));
			//if (n!=numVar-1)
			tmpLabelCampi = tmpLabelCampi + "|";
			//alert('tmpLabelCampi => '+tmpLabelCampi );
		}
	}
	//alert('Finale tmpLabelCampi => '+tmpLabelCampi );
	storedQueryField[cont]=tmpLabelCampi;

}
//Fine LabelFieldStoredQuery : LSQ

