// extended db javascript template for ArcIMS HTML Viewer
// aimsDB.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
*/

// global variables
var aimsDBPresent = true;

var theDBFrame = parent.DBFrame.document;
var dbLinkLayer = "parcels";
var dbLinkLayerID = "parcels";
var dbLinkLayerIndex = 1;
var dbQueryString = "";
var dbIdString = "";
var dbIdValue = "";
var dbNumValue = "";
var dbStreetValue = "";
var dbOwnerValue = "";
var dbDisplayValue = "";
var highlightIdentify = true;
var selectstring = ""
var wests = 0;
var souths = 0;
var easts =	0;
var norths = 0;


// set the active layer parameters to the dbLinkLayer
function matchDBLinkLayer(layerName) {
	var j = -1;
	for (var i=0;i<layerCount;i++) {
		if (LayerName[i]==layerName) j = i;
	}
	if (j>-1) {
		dbLinkLayerIndex = j
		//dbLinkLayerID = LayerID[dbLinkLayerIndex];
		dbLinkLayerID = "parcels";
		//dbLinkLayer = LayerName[dbLinkLayerIndex];
		dbLinkLayer = "parcels";
		//ActiveLayerIndex = dbLinkLayerIndex;
		ActiveLayerIndex = "parcels";
		ActiveLayer = dbLinkLayerID;
	}
}

// db Identify - external db access
//	XMLMode=70... response will be sent to parseIDFieldData()
function dbIdentify(e) {
	highlightedOne="";
	var theX = mouseX;
	var theY = mouseY;
	getMapXY(theX,theY);
	searchTolerance = (xDistance/iWidth) * pixelTolerance;
	var tempWest = mapX - searchTolerance;
	var tempNorth = mapY + searchTolerance;
	var tempEast = mapX + searchTolerance;
	var tempSouth = mapY - searchTolerance;
	var theString = writeGetFeatures(tempWest,tempSouth,tempEast,tempNorth);
	selectEnvelope='maxy="' + tempNorth + '" maxx="' + tempEast + '" miny="' + tempSouth + '" minx="' + tempWest + '"';
	drawSelectBoundary=true;
	showBuffer=false;
	selectionMode=2;
	showRetrieveData();
	sendToServer(imsQueryURL,theString,6);
	
}

// get the attribute values from the identify XML response
// 	then send request to external db access server
// 	and request for map highlighting feature
function parseIDFieldData(theReply) {
	//alert(theReply);
	var fList="";
	var iList="";
	var fieldPair = "";
	var fieldString = mapIDField + "=";
	var idString = LayerIDField[dbLinkLayerIndex] + "=";
	var qpos = 0;
	var pos = theReply.indexOf("<FEATURECOUNT count=");
	//alert(pos);
	var startpos = pos + 21;
	var endpos = theReply.indexOf(dQuote,startpos);
	//alert(endpos);
	var tempString = theReply.substring(startpos,endpos);
	var featureCount = parseInt(tempString);
	if (featureCount > 0) {
		endpos = 1;
		for (var i=0;i<featureCount;i++) {
			var startpos2 = theReply.indexOf("<FIELDS ",endpos);
			//alert(startpos2);
			pos = startpos2 + 8;
			qpos = fieldString.length + 87;
			//alert(qpos);
			startpos =theReply.indexOf(fieldString,pos);
			//alert(startpos);
			startpos = startpos + qpos
			endpos = theReply.indexOf(dQuote,startpos);
			tempString = theReply.substring(startpos,endpos);
			//tempString="GNT 1482997001";
			//alert(tempString);
			if (addIDQuotes) {
				tempString = '"' + tempString + '"';
			//} else {
			//	tempString = mapIDField + " = " + tempString;
			}
			if (i>0) tempString = "," + tempString;
			fList = fList + tempString;
			//fList= "GNT 1482997001";
			pos = startpos2 + 8;
			qpos = idString.length + 1;
			startpos =theReply.indexOf(idString,pos);
			startpos = startpos + qpos
			endpos = theReply.indexOf(dQuote,startpos);
			tempString = theReply.substring(startpos,endpos);
			//tempString = LayerIDField[dbLinkLayerIndex] + " = " + tempString;
			if (i>0) tempString = "," + tempString;
			iList = iList + tempString;
			
		}
		//alert(fList);
		//if (dbAccessType == "VB") {
		
			var featureString = "select " + dbFieldList + " from " + dbTableList + " where " + dbIDField + " IN (" + fList + ") order by " + dbIDField;
		//} else if ((dbAccessType == "ASP") || (dbAccessType == "ColdFusion")) {
		//	var featureString = fList;
		//} else {
		//	var featureString = "";
		//}
		
		writeDBResponsePage(featureString);
		if (highlightIdentify) {
			highlightedOne=LayerIDField[dbLinkLayerIndex] + " IN (" + iList + ")";
			sendMapXML();
		}
	} else {
		tempString = ActiveLayer + ":\nNo features located there.";
		//alert(tempString);
		var Win1;
		if ((useExternalWindow) || (!useTextFrame)) {
			Win1 = window.open("","QueryWindow","width=575,height=120,scrollbars=yes,resizable=yes");
		} else {
			Win1 = parent.TextFrame.document;
			Win1.open();
		}
		Win1.writeln('<html><head>');
		Win1.writeln('	<title>Identify Results</title>');
		Win1.writeln('</head>');
		Win1.writeln('<body BACKGROUND="white" text="Black" LEFTMARGIN=0 TOPMARGIN=0>');
		Win1.writeln('<FONT FACE="Arial"><B>' + ActiveLayer +'</B></font><FONT FACE="Arial" size="-2">');
		Win1.writeln('<br>Unable to locate feature. Try zooming in to pinpoint feature.</FONT>');
		Win1.writeln('</body></html>');
		Win1.close();
	}
	hideRetrieveData();
	
}


// get the attribute values from the identify XML response
// 	then send request to external db access server
// 	and request for map highlighting feature
function parseCommonDataR(key) {
//alert(key)
var fList="";
fList= key;	
var featureString =  "select " + dbFieldList + " from " + dbTableList + " where " + dbIDField + " IN (" + fList + ") order by " + dbIDField;
writeDBResponsePage(featureString);
hideRetrieveData();
}

// get the attribute values from the identify XML response
// 	then send request to external db access server
// 	and request for map highlighting feature
function parseCommonData(key) {
	//alert(key);
	var flist = key;
	//alert(flist);
	buffer = true;
	var theFrame = "TOCFrame";
	if ((useExternalWindow) || (!useTextFrame)) theFrame = "_blank";
		var Win1 = parent.DBFrame.document;
		if (multilist) {
			multilist = false;
		}	
		theForm = Win1.forms[0];
		//theForm.SQLValue = featureString;
		theForm.IDValue.value = flist;
		theForm.DisplayValue.value = "**None**";
		//theForm.submit();
		parent.TOCFrame.location = appDir + "arcims_processresults.asp?PIN="+flist;
	featureString=null;
	Win1 = null;
hideRetrieveData();	
}


function parseBufferData(key) {
//alert(key);
		var	fList= key;	
		//alert(fList);
		//if (dbAccessType == "VB") {
		
			var featureString =  "select " + dbFieldList + " from " + dbTableList + " where " + dbIDField + " IN (" + fList + ") order by " + dbIDField;
		//} else if ((dbAccessType == "ASP") || (dbAccessType == "ColdFusion")) {
		//	var featureString = fList;
		//} else {
		//	var featureString = "";
		//}
		
		
		writeDBResponsePage(featureString);
	if (highlightIdentify) {
		//alert("hello");
			//alert(iList);
			//highlightedOne=LayerIDField[dbLinkLayerIndex] + " IN (" + iList + ")";
			//sendMapXML();
		}
	 else {
		tempString = ActiveLayer + ":\nNo features located there.";
		//alert(tempString);
		var Win1;
		if ((useExternalWindow) || (!useTextFrame)) {
			Win1 = window.open("","QueryWindow","width=575,height=120,scrollbars=yes,resizable=yes");
		} else {
			Win1 = parent.TextFrame.document;
			Win1.open();
		}
		Win1.writeln('<html><head>');
		Win1.writeln('	<title>Identify Results</title>');
		Win1.writeln('</head>');
		Win1.writeln('<body BACKGROUND="white" text="Black" LEFTMARGIN=0 TOPMARGIN=0>');
		Win1.writeln('<FONT FACE="Arial"><B>' + ActiveLayer +'</B></font><FONT FACE="Arial" size="-2">');
		Win1.writeln('<br>Unable to locate feature. Try zooming in to pinpoint feature.</FONT>');
		Win1.writeln('</body></html>');
		Win1.close();
	}
	hideRetrieveData();
}

function getDBQuery(value) {
toolMode=1;
selectionMode=1;
	var queryString = "";
	queryString = mapIDField + " IN ('" + value + "')";
	//alert(queryString);
	setQueryString=  queryString ;
	hideRetrieveData();
	var theString = getDBEnvelope(queryString);
	//alert(theString)
	sendDBXMLRequest(theString, 3001)
}

function getDBQuery2(value1,value2) {
	// for vb implementation
	var queryString = "";
	
	queryString = mapIDField + " IN (" + value1 + ")";
	setQueryString=  queryString ;
	dbQueryString = dbIDField + " IN (" + value1 + ") AND " + dbDisplayField + " = '" + value2 + "'";
	dbQueryString = "select " + dbFieldList + " from " + dbTableList + " where " + dbQueryString + " order by " + dbIDField;
	hideRetrieveData();
	var theString = getDBEnvelope(queryString);
	sendDBXMLRequest(theString, 3001)
}

// create the ArcXML query request with feature id
//	used to match external db record to feature. . .
// 	envelope will parsed from response
function getDBEnvelope(queryString) {
	var theFields = LayerIDField[dbLinkLayerIndex] + " " + LayerShapeField[dbLinkLayerIndex];
	var selectFields=selFieldList[ActiveLayerIndex];
	var theString = '<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="' + ActiveLayerIndex + '" ftype="' + ActiveLayerType + '" />';
	if (useLimitExtent) {
		// keep this within the limitExtent
		theString += '<SPATIALQUERY subfields="' + theFields + '" 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 += '</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;
	//alert(theString);
	return theString;

}

// after matching feature to external db record
// 	parse out envelope and send zoom to envelope request.
function parseDBEnvelope(theReply) {
	var theError = getXMLErrorMessage(theReply);
	var featureCount = justGetFeatureCount(theReply);
	//alert(theReply);
	var theXYs = getEnvelopeXYs(theReply,0);
	//alert(theXYs);
	var endpos = 0;
	selectLeft[0] = theXYs[0];
	selectBottom[0] = theXYs[1];
	selectRight[0] = theXYs[2];
	selectTop[0] = theXYs[3];
	wests = selectLeft[0] + 125;
	souths = selectBottom[0] + 65;
	easts =	selectRight[0] - 250;
	norths = selectTop[0] - 220;
	endpos = xmlEndPos;
	var inData = parseRecordString(theReply, endpos);
	endpos = xmlEndPos;
	var selectedData = clearLeadingSpace(inData);
	var fName1 = getFieldNames(selectedData);
	var fValue1 = getFieldValues(selectedData);
	selectPoints[0] = getIdValue(fName1, fValue1);
	highlightedOne = LayerIDField[ActiveLayerIndex] + " = " + selectPoints[0];
	//alert(selectLeft[selNum] + "," + selectRight[selNum]);
	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;
	} else {
		mWMargin = fWidth * selectMargin;
		mHMargin = fHeight * selectMargin; 
	}
	saveLastExtent();
	left = selectLeft[0] - mWMargin;
	right = selectRight[0] + mWMargin;
	top = selectTop[0] + mHMargin;
	bottom = selectBottom[0] - mHMargin;
		//alert(highlightedOne);
	legendTemp=legendVisible;
	legendVisible=false;
	//var featureString = "select " + dbFieldList + " from " + dbTableList + " where " + dbQueryString + " order by " + dbIDField;
	
	/*
	var preString = "";
	var postString = "";
	var newString = "";
	var pos = dbQueryString.indexOf(" order by ");
	if (pos!=-1) {
		preString = dbQueryString.substring(0,pos);
		postString = dbQueryString.substring(pos,dbQueryString.length);
		newString = preString + " and " + dbIdString + postString;
	
	} else {
		newString = dbQueryString + " and " + dbIdString;
	}
	*/
	if (dbAccessType == "VB") writeDBResponsePage(dbQueryString);
	//sendMapXML();

	if (swapSelectFields) {
		selectFields=selFieldList[ActiveLayerIndex];
	}
	//selectstring = writeIdentifyXML(ActiveLayer,ActiveLayerType,selectFields,maxFeaturesReturned,queryStartRecord,wests,souths,easts,norths,useLimitExtent);
	//alert(selectstring);
	selectLayer=ActiveLayer;
	selectType=ActiveLayerType;
	selectCount=0;
	hightlightedOne="";
	selectPoints.length=1;
	selectLeft.length=1;
	selectRight.length=1;
	selectTop.length=1;
	selectBottom.length=1;
	displayAttributeData(theReply);
}

// dynamically write out page with form that automatically submits upon loading. . .
// 	sends request to external vb db access module with sql query
function writeDBResponsePage(featureString) {
	//alert(dbSQLurl);
	var theFrame = "TextFrame";
	//alert(dbAccessType)
	if ((useExternalWindow) || (!useTextFrame)) theFrame = "_blank";
	var Win1 = parent.DBFrame.document;
	var startpos = featureString.indexOf("IN (");
	startpos += 4;
	var endpos = featureString.indexOf(")",startpos);
	if (endpos==-1) endpos = featureString.length;
	var flist = featureString.substring(startpos, endpos);
	//alert("Where Clause: " + flist);
	if (dbAccessType == "VB") {
		/*
		Win1.open();
		Win1.writeln('<html><head>');
		Win1.writeln('	<title>Identify Form</title>');
		Win1.writeln('<script language="javascript">');
		Win1.writeln('	function sendForm() {');
		Win1.writeln('		document.forms[0].submit();')
		Win1.writeln('	}');
		Win1.writeln('</script>');
		Win1.writeln('</head>');
		Win1.writeln('<body onload="sendForm()" BACKGROUND="white" text="Black" LINK="Gray" VLINK="Gray" ALINK="Gray" topmargin=10>');
		//Win1.writeln('<body BACKGROUND="white" text="Black" LINK="Gray" VLINK="Gray" ALINK="Gray">');
		//Win1.writeln('<form action="http://aardvark/servlet/com.esri.esrimap.Esrimap" target="TOCFrame">');
		Win1.writeln('<p>&nbsp;<p><form action="' + dbSQLurl + '" target="LabelFrame">');
		//Win1.writeln('<INPUT TYPE="submit" NAME="submit" VALUE="Show Data">');
		Win1.writeln('<input type="Hidden" name="Name" value="' + dbSQLservice + '">');
		//Win1.writeln('<input type="Hidden" name="Name" value="SQLsend">');
		Win1.writeln('<input type="Hidden" name="Database" value="' + dbNumber + '">');
		Win1.writeln('<input type="Hidden" name="Connect" value="' + dbConnect + '">');
		Win1.writeln('<input type="Hidden" name="Response" value="1">');
		Win1.writeln('<input type="Hidden" name="Style" value="' + dbStyle + '">');
		Win1.writeln('<input type="text" name="IDValue" value="' + flist + '">');
		Win1.writeln('<textarea name="SQL" cols="30" rows="10">');
		Win1.writeln(featureString);
		Win1.writeln('</textarea>');

		Win1.writeln('</form>');
		Win1.writeln('</body></html>');
		Win1.close();
		*/
		//featureString = featureString + " AND " + dbDisplayField + " = " + dbDisplayValue;
		var f = Win1.forms[0];
		f.action = dbSQLurl;
		f.Database.value = dbDatabase;
		f.Connect.value = dbConnectString;
		f.IDField.value = dbIDField;
		f.SQL.value = featureString;
		f.Response.value = "1";
		f.Style.value = dbStyle;
		f.IDValue.value = flist;
		f.Function.value = "sendValue";
		f.ListDescript.value = dbFieldListDescript;
		f.submit();
		
	} else if ((dbAccessType == "ColdFusion") || (dbAccessType == "ASP"))  {
		theForm = Win1.forms[0];
		//theForm.SQLValue = featureString;
		//alert(flist)
		theForm.IDValue.value = flist;
		theForm.DisplayValue.value = "**None**";
		theForm.submit();

	}
	
	featureString=null;
	Win1 = null;
	
}


// Custom function to send ArcXML requests
//	points response to processDBXML()
function sendDBXMLRequest(XMLRequest, theType) {
	var theFunction = "parent.MapFrame.processDBXML";
	sendCustomToServer(XMLRequest,theFunction, theType)
}

// Custom XML processor for db access
function processDBXML(theReplyIn) {
//alert(theReplyIn);
	theReplyIn = replacePlus(theReplyIn);
	var theReply = unescape(theReplyIn);
	okToSend = true;
	if (debugOn>2) alert("XMLResponse:\n " + theReply);
	if (XMLMode == 3001) {
		// parse out envelope and send zoom to envelope request.
		//alert("parseDBEnvelope");
		//parseDBEnvelope(theReply);
		//getBufferDBData(theReply)
		//displayAttributeData(theReply);
		displayFeatureData(theReply)
	}
	if (XMLMode == 3002) {
		alert("XMLMode=3002");
		
	
	}
}
