// 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; - CAT - seems to be deprecated...
var dbLinkLayer = "Parcels";                                      // This must match the name tag of the <map axl file> layer entry for the parcel layer -
var dbLinkLayerID = "1";                                            //  CAT created method aimsXML::getDBLinkLayerIndex() to dynamically determine this - you must still set the dbLinkLayer value obviously, otherwise we have nothing to link to.
//var dbLinkLayerIndex = 8;                                         // CAT created method aimsXML::getDBLinkLayerIndex() to dynamically determine this - you must still set the dbLinkLayer value obviously, otherwise we have nothing to link to.
var dbLinkLayerIndex = 20;                                         // CAT created method aimsXML::getDBLinkLayerIndex() to dynamically determine this - you must still set the dbLinkLayer value obviously, otherwise we have nothing to link to.
ActiveLayerIndex = dbLinkLayerIndex;
var dbQueryString = "";
var dbIdString = "";
var dbIdValue = "";
var dbNumValue = "";
var dbStreetValue = "";
var dbOwnerValue = "";
var dbDisplayValue = "";

var goTo = false;
var idFeat = false;
var findStreet = false;


//For Printing
var printCount = "0";




function featureIdentify(lName,lID,mX,mY) {
  parent.MapFrame.idFeat = true;
  dbIDLinkLayer = lName;
  dbLinkLayerID = lID;
  dbLinkLayerIndex = lID;
  ActiveLayerIndex = dbLinkLayerIndex;

  clickCount=0;  
  showBuffer=false;  

    matchIDBLinkLayer(lName);


}


// set the active layer parameters to the dbLinkLayer
function matchIDBLinkLayer(layerName) {
//alert ("match ID Link Layer " + layerName);
//alert (" In MatchIDBLinkLayer");
	var j = -1;
	for (var i=0;i<layerCount;i++) {
		if (LayerName[i]==layerName) j = i;
	}
	if (j>-1) {
		dbLinkLayerIndex = j
		dbLinkLayerID = LayerID[dbLinkLayerIndex];
		dbLinkLayer = LayerName[dbLinkLayerIndex];
		ActiveLayerIndex = dbLinkLayerIndex;
		ActiveLayer = dbLinkLayerID;
		//alert ("active layer " + ActiveLayer);
	}	

		  dbElse_Identify();

}		  




function getGoTo(value) {
      
      parent.MapFrame.goTo = true;	  
		parent.MapFrame.ActiveLayerType = "point";  
	  matchDBLinkLayer(zoomGoToName);	
	  highlightedOne="";
	var queryString = "";
	   queryString = goToIDField + " IN ('" + value + "')";	  
	   setQueryString = queryString;	
	   hideRetrieveData();
	   //alert (queryString);

	var theString = getDBEnvelope(queryString);
   //alert (theString);
	sendDBXMLRequest(theString, 3001)
	
}




function getGeog(value) {
// Following line ensures the feature will be highlighted (does not have anything to do w/ zooming)
parent.MapFrame.findStreet = true;
 matchDBLinkLayer(dbRoadLinkLayer);
  
		  
	var queryString = "";

	if (geogIDFieldIsText) 
	   queryString = mapGEOGIDField + " IN ('" + value + "')";
	else		
	   queryString = mapGEOGIDField + " IN (" + value + ")";
	   
	setQueryString = queryString;
	
	//alert ("query string in get geog" + queryString);
	
	
	hideRetrieveData();
	
	selectionMode = 1;
    showBuffer = false;
    currentlySelectedFeatureID = "";

	var theString = getDBEnvelope(queryString);
    //alert ("the string in get geog" + theString);
	sendDBXMLRequest(theString, 3001)
	
}




// controls the Zoom To Parcel 

function getDBQuery(value) {

    dbLinkLayer = "Parcels";
	//parent.MapFrame.ActiveLayerType = "poly";
    matchDBLinkLayer(dbLinkLayer);
    //below is original
    /*if (dbIDFieldIsText)
       setQueryString = mapIDField + " IN ('" + value + "')";
    else
        setQueryString = mapIDField + " IN (" + value + ")";*/
    //below is new JR 1/10/2008
    if (dbIDFieldIsText)
       setQueryString = dbGISIDField + " IN ('" + value + "')";
    else
        setQueryString = dbGISIDField + " IN (" + value + ")";
    selectionMode = 1;
    showBuffer = true;
    currentlySelectedFeatureID = "'" + value + "'";
    var theString = getDBEnvelope(setQueryString);
    sendDBXMLRequest(theString, 3001);
    hideRetrieveData();
}








//Identify all other features that are not listed
function dbElse_Identify(e){
//alert ("in db else Identify");
	highlightedOne="";
	var mapX = idX;
	var mapY = idY;
	
	//alert ("Map X : " + mapX + " Map Y : " + mapY);
	
	//getMapXY(theX,theY);
	searchTolerance = (xDistance/iWidth) * pixelTolerance;
	//alert (searchTolerance);
	var tempWest = mapX - searchTolerance;
	var tempNorth = mapY + searchTolerance;
	var tempEast = mapX + searchTolerance;
	var tempSouth = mapY - searchTolerance;
	//var dbIIDLinkLayerType = IDlType;
	//writeIdentifyXML(theLayer,theLayerType,theFields,leftX,bottomY,rightX,topY,maxReturned,hasLimit)
	//writeIdentifyXML(LayerID[thefID],LayerType[thefID],selectFields,west1,south1,east1,north1,maxFeaturesReturned,useLimitExtent);
	//var theString = writeGetIFeatures(tempWest,tempSouth,tempEast,tempNorth);
	var theString = writeIIdentifyXML(LayerID[ActiveLayerIndex],LayerType[ActiveLayerIndex],"#ALL#",tempWest,tempSouth,tempEast,tempNorth,200,false);

	showRetrieveData();
	//alert ("dbElse_Identify String: \n" + theString);
	
	sendToServer(imsQueryURL,theString,84);
}



//parses all other response statements for attribute display
//dbElse_Identify()  XMLMODE = 84
function parseElseIDFieldData(theReply){
	//alert ("The Reply in parseElseIDFieldData " + theReply);
	var fList="";
	var iList="";
	var fieldPair = "";
	var fieldString = LayerIDField[dbLinkLayerIndex] + "=";
	var idString = LayerIDField[dbLinkLayerIndex] + "=";       
	var qpos = 0;
	var pos = theReply.indexOf("<FEATURECOUNT count=");
	var startpos = pos + 21;
	var endpos = theReply.indexOf(dQuote,startpos);
	var tempString = theReply.substring(startpos,endpos);
	var featureCount = parseInt(tempString);
	//alert("parseElseIDFieldData:featureCount: " + featureCount);
	if (featureCount > 0) {
		endpos = 1;
		for (var i=0;i<featureCount;i++) {
			var startpos2 = theReply.indexOf("<FIELDS ",endpos);
			pos = startpos2 + 8;
			qpos = fieldString.length + 1;
			startpos =theReply.indexOf(fieldString,pos);
			startpos = startpos + qpos
			endpos = theReply.indexOf(dQuote,startpos);
			tempString = theReply.substring(startpos,endpos);
			if (addIDQuotes) {
				tempString = '\'' + tempString + '\'';
			} else {
				tempString = tempString;
			}
			if (i>0) tempString = "," + tempString;
			fList = fList + tempString;
			
			//alert ("this is the flist");
			//alert (fList);
			
			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;
			
		}
		layersVisible=false;
		setLayerFields(ActiveLayerIndex);
		var url = "http://" + hostName + "/" + SiteName + "/displayShpAttributeData.htm";
		//alert (url);
		//alert (url);
		//Use textframe
		parent.TextFrame.document.location = url;
		//alert("iList: " + iList);
		if (highlightIdentify) {
			highlightedOne=LayerIDField[dbLinkLayerIndex] + " IN (" + iList + ")";
			sendMapXML();
		}
	}
	hideRetrieveData();
}



// 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];
        dbLinkLayer = LayerName[dbLinkLayerIndex];
        ActiveLayerIndex = dbLinkLayerIndex;
        ActiveLayer = dbLinkLayerID;
		//alert ("Active Layer" + ActiveLayer);
		
    }
}

// db Identify - external db access
//  XMLMode=70... response will be sent to parseIDFieldData()
function dbIdentify(e) {
//alert ("In Function dbIdentify");
dbLinkLayer = "Parcels";
matchDBLinkLayer(dbLinkLayer);


    highlightedOne="";
    var theX = mouseX;
    var theY = mouseY;
    getMapXY(theX,theY);
    searchTolerance = (xDistance/iWidth) * pixelTolerance;
    var tempWest = mapX - searchTolerance;
    var tempNorth = mapY + searchTolerance;
    var tempEast = mapX + searchTolerance;
    var tempSouth = mapY - searchTolerance;
    var theString = writeGetFeatures(tempWest,tempSouth,tempEast,tempNorth);
    showRetrieveData();
    sendToServer(imsQueryURL,theString,70);
}

/* Modularilized the parsing of the GIS - DB link field from the
   ArcXML reply
   @param theReply - The XML reply from the arcXML query.
   @param featureCount - The number of features returned by the query.
   @return parseGISLinkFields The comma-separated list of GIS-DB link field values.
   */
function parseGISLinkFields(theReply, featureCount) {
    var LinkValues = "";
    var startpos2 = 0;
    var startpos = 0;
    var pos = 0;
    var qpos = 0;
    var endpos = 1;
    var fieldString = mapIDField + "=";
    for (var i=0;i<featureCount;i++) {
        startpos2 = theReply.indexOf("<FIELDS ",endpos);
        pos = startpos2 + 8;
        qpos = fieldString.length + 1;
        startpos =theReply.indexOf(fieldString,pos);
        startpos = startpos + qpos
        endpos = theReply.indexOf(dQuote,startpos);
        tempString = theReply.substring(startpos,endpos);
        if (addIDQuotes) {
            tempString = '\'' + tempString + '\'';
        }
        if (i>0) tempString = "," + tempString;
            LinkValues = LinkValues + tempString;
    }
    return LinkValues;
}

/* Modularilized the parsing of the key GIS fields from the
   ArcXML reply
   @param theReply - The XML reply from the arcXML query.
   @param featureCount - The number of features returned by the query.
   @return parseGISIDFields The comma-separated list of fields values for the GIS key.
   */
function parseGISIDFields(theReply, featureCount) {
    var GISIDValues = "";
    var startpos2 = 0;
    var startpos = 0;
    var pos = 0;
    var qpos = 0;
    var endpos = 1;
    var idString = LayerIDField[dbLinkLayerIndex] + "=";
    for (var i=0;i<featureCount;i++) {
        startpos2 = theReply.indexOf("<FIELDS ",endpos);
        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);
        if (i>0) tempString = "," + tempString;
        GISIDValues = GISIDValues + tempString;
    }
	
    return GISIDValues;
}
// 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 (" Parse ID Field Data ");
 //alert (theReply);
	var fList="";
	var iList="";
	var fieldPair = "";
	var fieldString = mapIDField + "=";
	var idString = LayerIDField[dbLinkLayerIndex] + "=";
	var qpos = 0;
	var pos = theReply.indexOf("<FEATURECOUNT count=");
	var startpos = pos + 21;
	var endpos = theReply.indexOf(dQuote,startpos);
	var tempString = theReply.substring(startpos,endpos);
	var featureCount = parseInt(tempString);
	
    //Add selectCount so that buffer knows features are selected.
	selectCount = featureCount;
	
	if (featureCount > 0) {
		endpos = 1;
		for (var i=0;i<featureCount;i++) {
			var startpos2 = theReply.indexOf("<FIELDS ",endpos);
			pos = startpos2 + 8;
			qpos = fieldString.length + 1;
			startpos =theReply.indexOf(fieldString,pos);
			startpos = startpos + qpos
			endpos = theReply.indexOf(dQuote,startpos);
			tempString = theReply.substring(startpos,endpos);
			//if (addIDQuotes) {
			//	tempString = '\'' + tempString + '\'';
			//} else {
			//	tempString = mapIDField + " = " + tempString;
			//}
			if (i>0) tempString = "," + tempString;
			fList = fList + tempString;
		
		    //alert ("flist");	
			//alert (fList);
			
			
			
			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;
			
	
			
			if (currentSelectionState == 0)
            currentlySelectedFeatureID = fList;
              else if(currentSelectionState == 1) {
            addIDsToSelectedList (fList);
             } else if(currentSelectionState == 2) {
            removeIDsFromSelectedList (fList);
        }

        if ((currentSelectionState == 1) || (currentSelectionState == 2)) {
            selectionMode = 1;
        }
			
	
			
		}
		
		//if (dbAccessType == "VB") {
			var featureString = "select " + dbFieldList + " from " + dbTableList + " where " + dbIDField + " IN (" + currentlySelectedFeatureID + ") order by " + dbIDField;
		//} else if ((dbAccessType == "ASP") || (dbAccessType == "ColdFusion")) {
		//	var featureString = fList;
		//} else {
		//	var featureString = "";
		//}
		
		 //alert (featureString)
		
		 
		 
		writeDBResponsePage(featureString);


		if (highlightIdentify) {
		
		
//		if (currentSelectionState == 0)
           // currentlySelectedObjectID = iList;
         //     else if(currentSelectionState == 1) {
       //     addOBIDsToSelectedList (iList);
     //        } else if(currentSelectionState == 2) {
   //         removeOBIDsFromSelectedList (iList);
 //       }
		
		
	//	alert ("currentlySelectedObjectID");
	//	alert (currentlySelectedObjectID);
		
		
		//	highlightedOne=LayerIDField[dbLinkLayerIndex] + " IN (" + currentlySelectedObjectID + ")";
		
		    //MB:  Create a setQueryString to allow selected feature for buffering
	      
		  
	//	  alert ("Highlightedone");
	//	  alert (highlightedOne);
		  
		  //alert(currentlySelectedFeatureID);
		  //alert(fList);
		    if (dbIDFieldIsText) {
			  queryString = mapIDField + " IN (" + currentlySelectedFeatureID + ")";
	        } else {
	          queryString = mapIDField + " IN (" + currentlySelectedFeatureID.replace(/'/g,'') + ")";
	        }   
	        setQueryString = queryString; 
		
		    //alert ("setQuery");
		    //alert (setQueryString);
			
			sendMapXML();
		}
		
	} else {
	
		
		tempString = ActiveLayer + ":\n" + dbList[0];
		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><meta http-equiv="Content-Type" content="text/html; charset=' + charSet + '"><head>');
		Win1.writeln('	<title>' + dbList[1] + '</title>');
		Win1.writeln('</head>');
		Win1.writeln('<body BGCOLOR="White" TEXT="Black" LEFTMARGIN=0 TOPMARGIN=0><CENTER>');
		Win1.writeln('<FONT FACE="Tahoma" SIZE="-1"><B>' + LayerName[ActiveLayerIndex] + '</B></font><FONT FACE="Tahoma" size="-2">');
		Win1.writeln('<br>' + dbList[2] + '</FONT>');
		Win1.writeln('</FONT></body></html>');
		Win1.close();
	}
	
	hideRetrieveData();
	
}




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 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="' + LayerID[dbLinkLayerIndex] + '" 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="' + theFields + '" where="' + queryString + '" />';
    }
    theString += '</GET_FEATURES>';
    theString += '</REQUEST>';
    theString += '</ARCXML>';
    selectLayer=ActiveLayer;
    selectType=ActiveLayerType;
    selectCount=0;
    hightlightedOne="";
    selectPoints.length=1;
    selectLeft.length=1;
    selectRight.length=1;
    selectTop.length=1;
    selectBottom.length=1;
    return theString;
}

// after matching feature to external db record
//  parse out envelope and send zoom to envelope request.
function parseDBEnvelope(theReply) {
	//alert ("the reply in parse : " + theReply);
	//alert ("In Parse DB Envelope");
    var theError = getXMLErrorMessage(theReply);
    var featureCount = justGetFeatureCount(theReply);
    var theXYs = getEnvelopeXYs(theReply, 0)
    var endpos = 0;
    selectLeft[0] = theXYs[0];
    selectBottom[0] = theXYs[1];
    selectRight[0] = theXYs[2];
    selectTop[0] = theXYs[3];
    endpos = xmlEndPos;
    var inData = parseRecordString(theReply, endpos);
    //bunsongsikult
    if (featureCount > 1) {
        var lstData = parseFullRecordString(theReply);
    }
    endpos = xmlEndPos;
    var selectedData = clearLeadingSpace(inData);
    var fName1 = getFieldNames(selectedData);
    var fValue1 = getFieldValues(selectedData);
    selectPoints[0] = getIdValue(fName1, fValue1);
    //bunsongsikult
    if (featureCount > 1) {
      //highlight multiple objectid
      highlightedOne = LayerIDField[ActiveLayerIndex] + " IN (" + lstData + ")";
    } else {
      highlightedOne = LayerIDField[ActiveLayerIndex] + " IN (" + selectPoints[0] + ")";
    }
    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();
    eLeft = selectLeft[0] - mWMargin;
    eRight = selectRight[0] + mWMargin;
    eTop = selectTop[0] + mHMargin;
    eBottom = selectBottom[0] - mHMargin;
    legendTemp=legendVisible;
    legendVisible=false;
    layersVisible=false;
    selectCount = featureCount; // Added by CAT - to enable the Select by Owner, Address, etc - to actually result in a select.  3262003
    // parent.Debugger.document.write ("aimsDB.parseDBEnvelope: " + currentlySelectedFeatureID + " -- " + highlightedOne);
    if (dbAccessType == "VB") writeDBResponsePage(dbQueryString);
    sendMapXML();

}

// 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(featureString);
    var theFrame = "TextFrame";
    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);
    if (dbAccessType == "VB") {
        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;
        theForm.IDValue.value = flist;
        theForm.DisplayValue.value = "**None**";
        var startRec = parent.MapFrame.queryStartRecord;
        var recordCnt = parent.MapFrame.currentSelectCount;
        theForm.sms.value=startRec;
        theForm.smt.value=recordCnt;
        theForm.smc.value=maxFeaturesDisplayed;
        theForm.sme.value=(((startRec + maxFeaturesDisplayed) <= recordCnt) ? startRec + maxFeaturesDisplayed : recordCnt);
        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) {
    theReplyIn = replacePlus(theReplyIn);
    var theReply = unescape(theReplyIn);
    okToSend = true;
    if (debugOn>2) alert(msgList[13] + theReply);
    if (XMLMode == 3001) {
        // parse out envelope and send zoom to envelope request.
        parseDBEnvelope(theReply);
    }
    if (XMLMode == 3002) {
        alert("XMLMode=3002");
    }
}
