// 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 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;

/*
***************************************************************************************

Querying functions 

***************************************************************************************
*/


// query form
function queryForm() {
	fieldIndex=0;
	showSampleValues=false;
		if (mapLoaded) {
			setLayerFields(ActiveLayerIndex);
		} else {
			alert("This function cannot be used until a map is loaded."); 
			return;
		}
		if (showSampleValues) {
			var theText = writeFieldSample(LayerFields[fieldIndex]);
			sendToServer(imsQueryURL,theText,40);
		} else {
			writeQueryForm();
		}
		
}

// find Form
function findForm() {
	if (mapLoaded) {
		setLayerFields(ActiveLayerIndex);
	} else {
		alert("This function cannot be used until a map is loaded.");
		return;
	}
	if (usingSearchName == true) {
		if (useTextFrame) {
			parent.TextFrame.document.location= appDir + "addmatch.htm";
		} else {
			Win1 = open(appDir + "addmatch.htm","QueryWindow","width=575,height=150,scrollbars=yes,resizable=yes");
		}
	} else {
		if (useTextFrame) {
			parent.TextFrame.document.location= appDir + "findForm.htm";
		} else {
			Win1 = open(appDir + "findForm.htm","QueryWindow","width=575,height=150,scrollbars=yes,resizable=yes");
		}
	}
}



// process query
function sendQueryString(newString) {
	//if (LayerIDField[ActiveLayerIndex]!="#ID#") {
		newString = fixSingleQuotes(newString);
		newString = swapQuotes(newString);
	//}
	//alert(newString);
	newString = makeXMLsafe(newString);
	setQueryString=newString;
	selectionMode=1;
	selectData.length=1;
	LayerFields.length=1;
	LayerFieldType.length=1;
	LayerFieldCount=0;
	showBuffer=false;
	showRetrieveData();
	var theString = writeQueryXML(newString);
	sendToServer(imsQueryURL,theString,queryXMLMode);
}

// write out XML request to query attributes
//variant only for use to retrieve a response, not effect the selection set
function justGetQueryXML(queryString) {
	if (swapSelectFields) {
		selectFields=selFieldList[ActiveLayerIndex];
	}
	var theString = '<?xml version="1.0" encoding="UTF-8"?><ARCXML VERSION="1.1">\n<REQUEST>\n<GET_FEATURES outputmode="xml" geometry="false" envelope="true"';
	theString += ' compact="true" featurelimit="' + maxFeaturesReturned + '" beginrecord="' + queryStartRecord + '">\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="' + limitRight + '" maxy="' + limitTop + '" minx="' + limitLeft + '" miny="' + 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);
	return theString;
	
}

// write out XML request to query attributes
function writeQueryXML(queryString) {
	alert("You're in writeQueryXML");
	if (swapSelectFields) {
		selectFields=selFieldList[ActiveLayerIndex];
	}
	var theString = '<?xml version="1.0" encoding="UTF-8"?><ARCXML VERSION="1.1">\n<REQUEST>\n<GET_FEATURES outputmode="xml" geometry="false" envelope="true"';
	if (toolMode == 14 || toolMode == 5) { 
		theString += ' globalenvelope="true" ';
	}
	theString += ' compact="true" featurelimit="' + maxFeaturesReturned + '" beginrecord="' + queryStartRecord + '">\n';
	theString += '<LAYER id="' + ActiveLayer + '" />';
	//if (toolMode == 25) {
	//	if (setQueryString == "") {
	//		theString += '<SPATIALQUERY >\n';
	//	} else {
	//		theString += '<SPATIALQUERY where="' + setQueryString + '">\n';
	//	}
	//	theString += '<BUFFER distance="' + bufferDistance + '" bufferunits="' + ScaleBarUnits + '" >\n'; //
	//	theString += '<TARGETLAYER id="' + LayerID[bufferTargetLayerIndex] + '"/>\n';
	//	if ((tableJoinString[bufferTargetLayerIndex] == undefined) || (layerTableString[bufferTargetLayerIndex] == undefined)) {
	//		theString += '<SPATIALQUERY subfields="' + selectFields + '" />\n';
	//	} else {	
	//		theString += '<SPATIALQUERY subfields="' + selectFields + '" where="' + tableJoinString[bufferTargetLayerIndex] + '" jointables = "' + layerTableString[bufferTargetLayerIndex] + '" />\n';//
	//	}
	//	theString += '</BUFFER>\n';
	//	if ((useLimitExtent) || (setQueryString == "")) {
	//		theString += '<SPATIALFILTER relation="area_intersection">\n';
	//		theString += '<ENVELOPE maxx="' + right + '" maxy="' + top + '" minx="' + left + '" miny="' + bottom + '" />\n';
	//		theString += '</SPATIALFILTER>\n';
	//	
	//	}
	//	theString += '</SPATIALQUERY>\n';	
	//} else {
		if (useLimitExtent) {
			// keep this within the limitExtent
			theString += '<SPATIALQUERY subfields="' + selectFields + '" where="' + queryString + '">';
			theString += '<SPATIALFILTER relation="area_intersection">\n';
			theString += '<ENVELOPE maxx="' + limitRight + '" maxy="' + limitTop + '" minx="' + limitLeft + '" miny="' + 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;
	numberDataSamples = 50;
	var theString = '<?xml version="1.0" encoding="UTF-8"?><ARCXML VERSION="1.1">\n<REQUEST>\n<GET_FEATURES outputmode="xml" geometry="false" envelope="false"';
	theString += ' compact="true" featurelimit="' + numberDataSamples + '">\n';
	theString += '<LAYER id="' + ActiveLayer + '" />';
	//theString += '<QUERY subfields="' + theFields + '" where="' + LayerIDField[ActiveLayerIndex] + ' GT 0" />';
	theString += '<QUERY subfields="' + theFields + '" />';
	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) {
	var addTaxpayer = false;
	var addPPN = false;
	if ((usingSearchName == true) && (selSearchName == true)) {
		addTaxpayer = true;
	} else if ((usingSearchPPN == true) && (selSearchPPN == true)) {
		addPPN = true;
	} else if (loadThisService == "Public_Parcel_Find" && findPPN) {
		addPPN = true;
	}
	showRetrieveData();
	var theNewQueryString = "";
	var theTempString = "";
	var theLowerValue = theValue.toLowerCase();
	var theUpperValue = theValue.toUpperCase();
	//alert(LayerIDField[ActiveLayerIndex]);
	//alert(LayerShapeField[ActiveLayerIndex]);
	//var fieldListString = LayerIDField[ActiveLayerIndex] + " " + LayerShapeField[ActiveLayerIndex];
	var fieldListString = LayerShapeField[ActiveLayerIndex];
	var elemCount = 0;

	
	for (var i=0;i<LayerFields.length;i++) {
	//alert(fieldListString = fieldListString + " " + LayerFields[i]);
		fieldListString = fieldListString + " " + LayerFields[i];
		//alert(LayerIDField[ActiveLayerIndex]);
/*
		if ((LayerFieldType[i].indexOf("12",0)!=-1)&&(LayerIDField[ActiveLayerIndex]="PLANNING.CEMETERYGRAVES.OBJECTID")){
			theTempString = "(" + LayerFields[i] + " LIKE '%" + theValue + "%')";
			theLowerTempString = " OR (" + LayerFields[i] + " LIKE '%" + theLowerValue + "%')";
			theUpperTempString = " OR (" + LayerFields[i] + " LIKE '%" + theUpperValue + "%')"; 
			if (elemCount>0) theTempString = " OR " + theTempString;
			//old limit was 1024
			if (theNewQueryString.length + theTempString.length < 99999) {
				theNewQueryString = theNewQueryString + "(" + theTempString + theLowerTempString + theUpperTempString +")";
				//fieldListString = fieldListString + " " + LayerFields[i];
				elemCount += 1;
			alert(theNewQueryString);
			}
			
		}

*/

		if (LayerFieldType[i].indexOf("12",0)!=-1) {
			theTempString = "(" + LayerFields[i] + " LIKE '%" + theValue + "%')";
			theLowerTempString = " OR (" + LayerFields[i] + " LIKE '%" + theLowerValue + "%')";
			theUpperTempString = " OR (" + LayerFields[i] + " LIKE '%" + theUpperValue + "%')"; 
			if (elemCount>0) theTempString = " OR " + theTempString;
			//old limit was 1024
			if (theNewQueryString.length + theTempString.length < 99999) {
				theNewQueryString = theNewQueryString + theTempString + theLowerTempString + theUpperTempString;
				//fieldListString = fieldListString + " " + LayerFields[i];
				elemCount += 1;
			}
			
		}
	}


	//alert(addPPN);
	if ((isPartner == false) && (addTaxpayer)) {
		//currently not necessary - taxpayer already automatic part of search
		theTempString = " OR (CADASTRAL.EQ_NAME_ADDRESS.OWNERNAME LIKE '%" + theValue + "%')";
		theLowerTempString = " OR (CADASTRAL.EQ_NAME_ADDRESS.OWNERNAME LIKE '%" + theLowerValue + "%')";
		theUpperTempString = " OR (CADASTRAL.EQ_NAME_ADDRESS.OWNERNAME LIKE '%" + theUpperValue + "%')";
		if (theNewQueryString.length + theTempString.length < 99999) {
			theNewQueryString = theNewQueryString + theTempString + theLowerTempString + theUpperTempString;
			fieldListString = fieldListString + " CADASTRAL.EQ_NAME_ADDRESS.OWNERNAME";
			elemCount += 1;
		}
	} else if (addPPN) {
		//still need this: the search is only automatic for string type values
		if (isPartner) {
			theNewQueryString = "PPN = '"+theValue+"'";
		} else {
			theNewQueryString = "CADASTRAL.Parcels.PPN = "+theValue;
			//fieldListString = fieldListString + " CADASTRAL.Parcels.PPN";
		}
		elemCount += 1;
	}
	if (theNewQueryString!="") {
		showBuffer=false;
		//alert("aimsQuery - here we are");
		theNewQueryString=makeXMLsafe(theNewQueryString);
		setQueryString = theNewQueryString;
		var theString = writeFindRequest(theNewQueryString,fieldListString);
		//alert(theString);
		sendToServer(imsQueryURL,theString,findXMLMode);
	} else {
		alert("Unable to build Query String.");
	}
}




// find request for searching by first & last name for Cemeteries

function getFind2(theValue,theValue2) {
	//alert(theValue);
	//alert(theValue2);
	showRetrieveData();
	var theNewQueryString = "";
	var theTempString = "";
	var theLowerValue = theValue.toLowerCase();
	var theUpperValue = theValue.toUpperCase();
	var theLowerValue2 = theValue2.toLowerCase();
	var theUpperValue2 = theValue2.toUpperCase();
	//alert(LayerIDField[ActiveLayerIndex]);
	//alert(LayerShapeField[ActiveLayerIndex]);
	var fieldListString = LayerShapeField[ActiveLayerIndex];
	var elemCount = 0;
	

	
	for (var i=0;i<LayerFields.length;i++) {
		fieldListString = fieldListString + " " + LayerFields[i];
		//alert("i: " + i);
		//alert("fieldListString: " + fieldListString);
		//alert("LayerField: " + LayerFields[i]);

		if (LayerFields[i]="PLANNING.CEMETERYGRAVES.BURIAL_FIRST_NAME") {
			theTempString = "((" + LayerFields[i] + " LIKE '%" + theValue2 + "%')";
			theLowerTempString = " OR ( LOWER(" + LayerFields[i] + ") LIKE '%" + theLowerValue2 + "%')";
			theUpperTempString = " OR ( UPPER(" + LayerFields[i] + ") LIKE '%" + theUpperValue2 + "%'))"; 
			if (elemCount>0) theTempString = " AND " + theTempString;
			//old limit was 1024
			if (theNewQueryString.length + theTempString.length < 99999) {
				theNewQueryString = theNewQueryString + theTempString + theLowerTempString + theUpperTempString;
				elemCount += 1;
				//alert("123theNewQueryString: " + theNewQueryString);
			}
		}
		if (LayerFields[i]="PLANNING.CEMETERYGRAVES.BURIAL_LAST_NAME") {
			theTempString = "((" + LayerFields[i] + " LIKE '%" + theValue + "%')";
			theLowerTempString = " OR ( LOWER(" + LayerFields[i] + ") LIKE '%" + theLowerValue + "%')";
			theUpperTempString = " OR ( UPPER(" + LayerFields[i] + ") LIKE '%" + theUpperValue + "%'))"; 
			if (elemCount>0) theTempString = " AND " + theTempString;
			if (theNewQueryString.length + theTempString.length < 99999) {
				theNewQueryString = theNewQueryString + theTempString + theLowerTempString + theUpperTempString;
				elemCount += 1;
			//alert(theNewQueryString);
			}
		}
	}

	if (theNewQueryString!="") {
		showBuffer=false;
		//alert("aimsQuery - here we are");
		theNewQueryString=makeXMLsafe(theNewQueryString);
		setQueryString = theNewQueryString;
		var theString = writeFindRequest(theNewQueryString,fieldListString);
		//alert(theString);
		sendToServer(imsQueryURL,theString,findXMLMode);
	} else {
		alert("Unable to build Query String.");
	}
}








// write out find form
function writeFindRequest(findQuery,fieldList) {
	var theString = '<?xml version="1.0" encoding="UTF-8"?><ARCXML VERSION="1.1">\n<REQUEST>\n<GET_FEATURES outputmode="xml" geometry="false" envelope="true"';
	if (toolMode == 14 || toolMode == 18) theString += ' globalenvelope="true"';
	theString += ' compact="true" 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="' + limitRight + '" maxy="' + limitTop + '" minx="' + limitLeft + '" miny="' + 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_orig(theReply) {
	//alert("Reply Length: " + theReply.length);
	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);
			alert(selectData[i]);

		}
	} else {
		selectData.length=0;
	}
	
}

// New parse layer field value samples code - Removes Duplicates
function parseFieldSamples(theReply) {
	//alert("Reply Length: " + theReply.length);
	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="";
	var fieldVals = new Array();
	var fldVals = "";
	var j = 0;
	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);
            if ((fldVals.indexOf(inData, 1) < 1) && (inData!="")) {
		fieldVals[j] = inData;
               fldVals = fldVals + ',' + clearLeadingSpace(inData);               
               j = j + 1;
		    }
			selectData[i] = clearLeadingSpace(fldVals);			
		}
	} else {
		fieldVals.length=0;
		selectData.length=0;
	}
	fieldVals.sort();
	selectData = fieldVals;
	
}


// write out a query form
function writeQueryForm() {
	var startpos = 0;

	var endpos = 0;
	var SampleCount = selectData.length;
	var theIndex = fieldIndex;

	var sampleList = new Array();       
	var qField = AliasFieldName[fieldIndex] + '="';
	var zField = AliasFieldName[fieldIndex];
	//the order of  listed fields (from ArcIMSparam.js) is not the same as the one downloaded via ArcXML...
	//...from the server. This code will rectify that.
	if (theIndex > 1) {
		for(var j = 0; j < LayerFields.length; j++) {
			var field = LayerFields[j];
			if (field == zField) 
				theIndex =j;
		}
	}
	var valueTitle = "Value";
	if (showSampleValues) {
		for (var i=0;i<SampleCount;i++) {
			startpos = selectData[i].indexOf(qField,0);
			startpos = startpos + qField.length;
			endpos = selectData[i].indexOf('"',startpos);
			//alert("SelectData: " + selectData);
			//alert("LayerFieldType: " + LayerFieldType);
			if (LayerFieldType[theIndex].indexOf("12",0)!=-1) {
				var vData = selectData[i].substring(startpos,endpos);
				//vData = fixSingleQuotes(vData);
				sampleList[i] = dQuote + vData + dQuote;
			} else {
				sampleList[i] = selectData[i].substring(startpos,endpos);
			}
		}
		valueTitle = "Sample Values";
	}
	if (useTextFrame) {
		var Win1 = parent.TextFrame;
		Win1.document.open();
		var t = "parent.MapFrame";
		
	} else {
		var Win1 = open("","QueryWindow","width=575,height=150,scrollbars=yes,resizable=yes");
		var t = "opener";
		if (parent.MapFrame!=null) t = "opener.parent.MapFrame";
	}
	
	Win1.document.writeln('<html><HEAD>');
	Win1.document.writeln('			<script language="javascript">');
		Win1.document.writeln('var t = ' + t);
		Win1.document.writeln('var dQuote = \'"\';');
		Win1.document.writeln('			var lastExpr = "";');
		Win1.document.writeln('			var currExpr = "";');
		Win1.document.writeln('			var sampleList = new Array();');
		Win1.document.writeln('			var qField = "";');
		Win1.document.writeln('			function addString() {');
		Win1.document.writeln('				lastExpr = document.QueryStuff.QueryString.value;');
		Win1.document.writeln('				qField = document.QueryStuff.QueryField.options[document.QueryStuff.QueryField.selectedIndex].value;');
		Win1.document.writeln('				var qOperator = document.QueryStuff.QueryOperator.options[document.QueryStuff.QueryOperator.selectedIndex].value;');
		if (showSampleValues) {
			Win1.document.writeln('				var qString = document.QueryStuff.QueryValue.options[document.QueryStuff.QueryValue.selectedIndex].text;');
		} else{
			Win1.document.writeln('					var qString = document.QueryStuff.QueryValue.value;');
			Win1.document.writeln('					//if (t.LayerFieldType[document.QueryStuff.QueryField.selectedIndex+2].indexOf("12",0)!=-1) {');
			Win1.document.writeln('					//	if (qString.indexOf(dQuote)==-1) {');
			Win1.document.writeln('					//		qString = dQuote + qString + dQuote;');
			Win1.document.writeln('					//	}');
			Win1.document.writeln('					//}');
		}
		Win1.document.writeln('				var qString2 = document.QueryStuff.QueryString.value;');
		Win1.document.writeln('				var theString =  qField + " " + qOperator + " " + qString;');
		Win1.document.writeln('				document.QueryStuff.QueryString.value = qString2 + theString;');
		Win1.document.writeln('				currExpr = document.QueryStuff.QueryString.value;');
		Win1.document.writeln('			}');
			
		Win1.document.writeln('			function sendQuery() {');
		Win1.document.writeln('				var theString = document.QueryStuff.QueryString.value;');
		Win1.document.writeln('				if (theString!="") {');
		Win1.document.writeln('					sampleList=null;');
		Win1.document.writeln('					t.sendQueryString(theString);');
		Win1.document.writeln('					t=null;');
		Win1.document.writeln('				} else {');
		Win1.document.writeln('					alert("Query expression is blank.\\nNo features have been selected.");');
		Win1.document.writeln('				}');
		//Win1.document.writeln('				if (opener) window.close();');
				
		Win1.document.writeln('			}');
			
		Win1.document.writeln('			function addAnd() {');
		Win1.document.writeln('				lastExpr = document.QueryStuff.QueryString.value;');
		Win1.document.writeln('				var qString2 = document.QueryStuff.QueryString.value;');
		Win1.document.writeln('				document.QueryStuff.QueryString.value = qString2 + " AND ";');
		Win1.document.writeln('				currExpr = document.QueryStuff.QueryString.value;');
		Win1.document.writeln('			}');
			
		Win1.document.writeln('			function addOr() {');
		Win1.document.writeln('				lastExpr = document.QueryStuff.QueryString.value;');
		Win1.document.writeln('				var qString2 = document.QueryStuff.QueryString.value;');
		Win1.document.writeln('				document.QueryStuff.QueryString.value = qString2 + " OR ";');
		Win1.document.writeln('				currExpr = document.QueryStuff.QueryString.value;');
		Win1.document.writeln('			}');
	
		Win1.document.writeln('			function addNot() {');
		Win1.document.writeln('				lastExpr = document.QueryStuff.QueryString.value;');
		Win1.document.writeln('				var qString2 = document.QueryStuff.QueryString.value;');
		Win1.document.writeln('				document.QueryStuff.QueryString.value = qString2 + "NOT ";');
		Win1.document.writeln('				currExpr = document.QueryStuff.QueryString.value;');
		Win1.document.writeln('			}');
			
		Win1.document.writeln('			function addLeftPara() {');
		Win1.document.writeln('				lastExpr = document.QueryStuff.QueryString.value;');
		Win1.document.writeln('				var qString2 = document.QueryStuff.QueryString.value;');
		Win1.document.writeln('				document.QueryStuff.QueryString.value = qString2 + "(";');
		Win1.document.writeln('				currExpr = document.QueryStuff.QueryString.value;');
		Win1.document.writeln('			}');
	
		Win1.document.writeln('			function addRightPara() {');
		Win1.document.writeln('				lastExpr = document.QueryStuff.QueryString.value;');
		Win1.document.writeln('				var qString2 = document.QueryStuff.QueryString.value;');
		Win1.document.writeln('				document.QueryStuff.QueryString.value = qString2 + ")";');
		Win1.document.writeln('				currExpr = document.QueryStuff.QueryString.value;');
		Win1.document.writeln('			}');
	
		Win1.document.writeln('			function undoString() {');
		Win1.document.writeln('				currExpr = document.QueryStuff.QueryString.value;');
		Win1.document.writeln('				document.QueryStuff.QueryString.value = lastExpr;');
		Win1.document.writeln('				t.setQueryString = document.QueryStuff.QueryString.value;');
		Win1.document.writeln('				lastExpr = currExpr;');
		Win1.document.writeln('			}');
			
		Win1.document.writeln('			function clearString() {');
		Win1.document.writeln('				lastExpr = document.QueryStuff.QueryString.value;');
		Win1.document.writeln('				document.QueryStuff.QueryString.value = "";	');
		Win1.document.writeln('				t.setQueryString = "";');
		Win1.document.writeln('			}');
			
		Win1.document.writeln('			function setUp() {');
		Win1.document.writeln('				if (t.showSampleValues) {');
		Win1.document.writeln('					t.fieldIndex = document.QueryStuff.QueryField.selectedIndex+2;');
		Win1.document.writeln('					t.setQueryString = document.QueryStuff.QueryString.value;');
		Win1.document.writeln('					var theField = t.AliasFieldName[t.fieldIndex];');
		Win1.document.writeln('					//alert("theField: " + theField);');
		Win1.document.writeln('					t.tempGetSamples(theField);');
		Win1.document.writeln('					t.writeQueryForm();');
		Win1.document.writeln('				}');
		Win1.document.writeln('			}');
		
		Win1.document.writeln('			function changeToSamples() {');	
		Win1.document.writeln('				t.fieldIndex = document.QueryStuff.QueryField.selectedIndex+2;');
		Win1.document.writeln('				t.setQueryString = document.QueryStuff.QueryString.value;');
		Win1.document.writeln('				t.tempGetSamples(t.AliasFieldName[t.fieldIndex]);');
		Win1.document.writeln('			}');
					
		Win1.document.writeln('		</script>');
		Win1.document.writeln('		</head>');
	
		Win1.document.writeln('		<body link="Blue" vlink="Blue" alink="Blue" leftmargin=0 text="white" topmargin=0 bgcolor=#003366 onload="window.focus(); ' + t + '.queryOpen=true;" onunload="' + t + '.queryOpen=false;">');
		Win1.document.writeln('			<center>');
		Win1.document.writeln('			<form name="QueryStuff" onsubmit="sendQuery();return false;">');
		Win1.document.writeln('			<font face="Arial" size="-3">');
		Win1.document.writeln('			<table border="0" cellspacing="0" cellpadding="2" width=100%>');
		Win1.document.writeln('			<tr><td align="CENTER" bgcolor=#003366><font face="Arial" size="-2" color=white>Step 1: Choose Field</font></td>');
		Win1.document.writeln('			<td align="CENTER" bgcolor=#003366><font face="Arial" size="-2" color=white>Step 2: Choose Operator</font></td>');
		Win1.document.writeln('			<td align="CENTER" bgcolor=#003366><font face="Arial" size="-2" color=white>Step 3: Choose Value</font></td>');
		Win1.document.writeln('			<td rowspan="2" align="CENTER" bgcolor=#003366>');
		Win1.document.writeln('			<input type="button" name="theAnd" value=" And " onclick="addAnd()" style="font-size: x-small; color: #000000; background: #CCCC99;">');
		Win1.document.writeln('			<input type="button" name="theOr" value=" Or " onclick="addOr()" style="font-size: x-small; color: #000000; background: #CCCC99;">');
		Win1.document.writeln('			<input type="button" name="theNot" value=" Not " onclick="addNot()" style="font-size: x-small; color: #000000; background: #CCCC99;"><br>');
		Win1.document.writeln('			<input type="button" name="theLeft" value="  (  " onclick="addLeftPara()" style="font-size: x-small; #000000: white; background: #CCCC99;">');
		Win1.document.writeln('			<input type="button" name="theRight" value="  )  " onclick="addRightPara()" style="font-size: x-small; #000000: white; background: #CCCC99;">');
		Win1.document.writeln('			</td>');
			
		Win1.document.writeln('			</tr>');
		Win1.document.writeln('			<tr><td align="CENTER" bgcolor=#003366>');
			Win1.document.writeln('			<select name="QueryField" onchange="setUp();">');

			for (var i=0;i<AliasFieldName.length;i++) {
				if (AliasFieldAlias[i] == "ID" || AliasFieldAlias[i] == "shape") {
					continue;
				} else {
					Win1.document.write('<option value="' + AliasFieldName[i] + '"');
					if (i==fieldIndex) Win1.document.write(' selected');
					//alert(AliasFieldName[i] + ' ' + AliasFieldAlias[i] + i);
					Win1.document.writeln('>' + AliasFieldAlias[i]);
				}
			}
			Win1.document.writeln('			</select>');
		Win1.document.writeln('			</td><td align="CENTER" bgcolor=#003366>');
		Win1.document.writeln('			<select name="QueryOperator">');
		Win1.document.writeln('			<OPTION selected value=" = ">=');
		Win1.document.writeln('			<option value=" < ">&lt;');
		Win1.document.writeln('			<option value=" > ">&gt;');
		Win1.document.writeln('			<option value=" <= ">&lt;=');
		Win1.document.writeln('			<option value=" >= ">&gt;=');
		Win1.document.writeln('			<option value=" LIKE ">LIKE');
		//Win1.document.writeln('			<option value=" CN ">CN	');
		Win1.document.writeln('			</select>');
	             
		Win1.document.writeln('			</td><td align="CENTER" bgcolor=#003366>');
			
		if (showSampleValues) {
			Win1.document.writeln('			<select name="QueryValue">');
				for (var i=0;i<SampleCount;i++) {
					Win1.document.writeln('<option value=\'' + sampleList[i] + '\'>' + sampleList[i]);
				}
			Win1.document.writeln('			</select>');
	    } else {
			Win1.document.writeln('<input name="QueryValue" size="25" maxlength="1000" >');
			Win1.document.writeln('			&nbsp;&nbsp;<input type="button" name="makeList" value="Get Samples" onclick="changeToSamples()"style="font-size: x-small; color: #000000; background: #CCCC99;">');
			Win1.document.writeln('			</td>');
		}         
		Win1.document.writeln('			</td>');
		Win1.document.writeln('			</tr>');
		Win1.document.writeln('			<tr><td colspan="4" align="center" bgcolor=#003366>');
		Win1.document.writeln('			<br><font face="Arial" size="-2" color=white>Step 4: Add to query string and make any necessary changes.</font><br><input type="button" name="addIt" value="Add to Query String" onclick="addString()" style="font-size: x-small; color: #000000; background: #CCCC99;">');
		Win1.document.writeln('<input type="Text" name="QueryString" size="50" maxlength="1024" value=\'' + setQueryString + '\'><br><br>');
		Win1.document.writeln('<font face="Arial" size="-2" color=white>Step 5: Execute query or Clear and start over.&nbsp;&nbsp;&nbsp;</font><input type="submit" value="Execute" name="submit" style="font-size: x-small; color: #000000; background: #CCCC99;">'); 
		//Win1.document.writeln('			<input type="button" name="UnDo" value="UnDo" onclick="undoString()" style="font-size: x-small; color: #000000; background: #CCCC99;">');
		Win1.document.writeln('			<input type="button" name="Clear" value="Clear" onclick="clearString()" style="font-size: x-small; color: #000000; background: #CCCC99;">');
		Win1.document.writeln('			</td></tr>');
		Win1.document.writeln('			</table>');
		Win1.document.writeln('			</font></center></FORM></body></html>');
	

		Win1.document.close();

		Win1=null;
		sampleList=null;
}


// 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><HEAD>');
	Win1.document.writeln('<body BGCOLOR=#003366 TEXT="White" size="-1">');
	Win1.document.writeln('<div align="center"><font face="Arial"><b>');
	Win1.document.writeln('Requesting sample values for the layer ' + LayerName[ActiveLayerIndex] + '. . .</b></font><br>');
	Win1.document.writeln('<font face="Arial" size="-1">Unique values from the first ' + numberDataSamples + ' records are being accessed.</font></div></body></html>');
	Win1.document.close();
	Win1=null;
	
	var theText = writeFieldSample(theField);
	//alert(theText);
	sendToServer(imsQueryURL,theText,40);

}

// get the StoredQueries in the MapService
function getStoredQueries() {
	var theString = '<?xml version="1.0" encoding="UTF-8"?><ARCXML VERSION="1.1">\n<REQUEST>\n<GET_SERVICE_INFO renderer="false" extensions="true" fields="false" />\n';
	theString += '</REQUEST>\n</ARCXML>';
	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;
	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;
				
				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]="";			
				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;
					vCount += 1;
					sqvpos = theReply.indexOf("<SQVAR",startpos);
				}
				storedQueryVarCount[storedQueryCount] = vCount;
			
				storedQueryCount += 1;
			}
			
			
			sqpos = theReply.indexOf("<STOREDQUERY name=",endpos);
			sqpos2 = theReply.indexOf("</STOREDQUERY>",sqpos);
		}
	}
	blurb=null;
	if (storedQueryCount==0) {
		alert(LayerName[ActiveLayerIndex] + ":\nThis Layer does not have any StoredQueries.");
	} else {
		storedQueryForm();
	}
}

// storedQuery Form
function storedQueryForm() {

	writeStoredQueryForm(storedQueryIndex);
}

function writeStoredQueryForm(theIndex) {
	storedQueryIndex=theIndex;
	if (storedQueryVarCount==0) {
		sendStoredQuery(theIndex,"");
	} else {
	
		if (useTextFrame) {
			var Win1 = parent.TextFrame;
			Win1.document.open();
			var t = "parent.MapFrame";
			
		} else {
			var Win1 = open("","QueryWindow","width=575,height=150,scrollbars=yes,resizable=yes");
			var t = "opener";
			if (parent.MapFrame!=null) t = "opener.parent.MapFrame";
		}
		
		Win1.document.writeln('<html><HEAD>');
		Win1.document.writeln('			<script language="javascript">');
		Win1.document.writeln('var t = ' + t);
		
		Win1.document.writeln('function setStyle() {');
		Win1.document.writeln('	var f = document.forms[0];');
		Win1.document.writeln('	var theCount = t.storedQueryIndex;');
		Win1.document.writeln('	var okValue = 0;');
		Win1.document.writeln('	if (t.storedQueryVarCount[theCount]==1) {');
		Win1.document.writeln('		var theValue = f.theStyle.value;');
		Win1.document.writeln('		if (theValue!="") okValue = 1;');
		Win1.document.writeln('	} else {');
		Win1.document.writeln('		var theValue = f.theStyle[0].value;');
		Win1.document.writeln('		if (f.theStyle[0].value!="") okValue = 1;');
		Win1.document.writeln('		for (var i=1;i<t.storedQueryVarCount[theCount];i++) {');
		Win1.document.writeln('			theValue = theValue + "|" + f.theStyle[i].value;');
		Win1.document.writeln('			if (f.theStyle[i].value!="") okValue += 1;');
		Win1.document.writeln('		}');
		Win1.document.writeln('	}');
		Win1.document.writeln('	if (okValue==t.storedQueryVarCount[theCount]) {');
		Win1.document.writeln('		t.sendStoredQuery(theCount,theValue);');
		Win1.document.writeln('	} else {');
		Win1.document.writeln('		alert("Please enter appropriate value");');
		Win1.document.writeln('	}');
		Win1.document.writeln('}');
		Win1.document.writeln('function selectQuery() {');
		Win1.document.writeln('	var f = document.forms[0];');
		Win1.document.writeln('	var theIndex = f.theQuery.selectedIndex;');
		Win1.document.writeln('	t.writeStoredQueryForm(theIndex);');
		Win1.document.writeln('}');
		Win1.document.writeln('</script>');
		Win1.document.writeln('</head>');
		
		Win1.document.writeln('<body bgcolor=#003366 text="White" topmargin=0 leftmargin=0 rightmargin=0 onload="window.focus()">');
		Win1.document.writeln('<div align="center">');
		Win1.document.writeln('<font face="Arial" size="-2"><b>');
		Win1.document.writeln('<form action="" name="theStoreQueryForm" onsubmit="setStyle(); return false;">');
		Win1.document.writeln('<table cellspacing="2" nowrap bgcolor=#6699cc width=100%>');
		Win1.document.writeln('<tr><th colspan="3" align="CENTER">');
		Win1.document.writeln('<font face="Arial" size="-1"><b>Search</b><br></font>');
		Win1.document.writeln('<font face="Arial" size="-2"><b>Search is Case-Sensitive</b></font>');
		Win1.document.writeln('</th></tr>');
		Win1.document.writeln('<tr>');
		Win1.document.writeln('<td align="Left">');
		Win1.document.writeln('<font face="Arial" size="-1">' + LayerName[ActiveLayerIndex] + ':');
		Win1.document.writeln('<select name="theQuery" onchange="selectQuery()">')
		for (var i=0;i<storedQueryCount;i++) {
			Win1.document.write('	<option value=' + i);
			if (i==storedQueryIndex) Win1.document.write(' selected');
			Win1.document.writeln('>' + storedQueryName[i]);
		
		}
		Win1.document.writeln('</select>');

		Win1.document.writeln('</font></td>');
		Win1.document.writeln('<td align="RIGHT"><font face="Arial" size="-1">');
		for (var i=0;i<storedQueryVarCount[storedQueryIndex];i++) {
			Win1.document.write('Value');
			if (storedQueryVarCount[storedQueryIndex]>1) Win1.document.write(' ' + (i+1));
			Win1.document.writeln(':');
			Win1.document.writeln('<input type=text name="theStyle" value=""><br>');
		}
		Win1.document.writeln('</font>');
		Win1.document.writeln('</td>');
		Win1.document.writeln('<td align="CENTER">');
		Win1.document.writeln('<input type="Button" name="setDU" value="Execute" onclick="setStyle()">  <br>');
		
		Win1.document.writeln('</td></tr></table></form>');
		Win1.document.writeln('</b></font></div>');
		Win1.document.writeln('</body></html>');
		Win1.document.close();
		Win1=null;
	
	}

}

// create the querystring for storedQuery and send it
function sendStoredQuery(theIndex,theValue) {
	showRetrieveData();
	var oldString = storedQueryString[theIndex];
	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);
	var newString = makeXMLsafe(oldString);
	//alert(newString);
	setQueryString = newString;
	var theString = writeQueryXML(newString);
	//alert("StoredQuery Request:\n" + theString);
	sendToServer(imsQueryURL,theString,queryXMLMode);
}

// see if there are storedQueries (Search) 
function checkStoredQueries(theReply) {
	var startpos = theReply.indexOf("<STOREDQUERY",1);
        useStoredQuery=true;
	if (startpos==-1) {
		//no storedqueries. . . do not display button
		useStoredQuery=false;
	}
}



