<!--
/*
function Test_Access(strValue, intBit)
function GetCookie(sName)
function SetCookie(sName, sValue)
function UpdateCoordinateText(ObjSelect, ObjDest)
function UpdateCoordinateSelection(ObjText, ObjDest)
function NeighborhoodDefWindow(board_id)
function NeighborhoodDefWindowAdvanced()
function FormatComma(number) 
function SessionTimer()
function SessionTimerReset()
function loadXMLDocObjectFromServer(strXMLfilename)
function getXMLDocObject(strXMLFileName, strVersion)
function keyPress(d)
function mouseClick(d)
function sayHello()
function SearchCriteria()
function GetAreas()
function SelectCriteria()
function LoadPrimary(strHTML)
function LoadSecondary(strHTML)
function SortAdditionalFields(xmlDocTemp, formSelectElement, strSortField, strSelectField, strTestField)
function LoadFeatures(strHTML)
function RemoveOrphanedCriteria()
function CallSelectCriteria(myform)
function LoadDefaultSearch()
function NewSearch(myform)
function FlipCoBroke(value)
function DoSearch(myform)
function GetCount()
function LoadSearch(theField)
function ReLoad(theType)
function DoDelete(myform)
function DoDeleteProspect(myform)
function DoFileSaveAs(strSaveName, strOverWrite, bHotsheet)
function AddCriteria(theField, theText, theCount, AutoCount)
function ChangeCriteria(theField, theText)
function EditCriteria(myform)
function DoDB(theAction, theField, theType, bHotsheet)
function DoRemove()
function DoClear()
function DoSaveAs()
function openTheNewWindow(fileName,theWindowName,theWidth,theHeight) 
function AdditionalFieldTree()
function AdditionalField(theField)
function AdditionalFeature(theField)
function OpenChild(theFieldName, theFieldType)
function LoadHrefWindow(theURL, theWidth, theHeight)
function DoAgent(myform, theField, thePrompt, theClause, addQuotes, FormType)
function AddCriteria2(myform, theField, thePrompt, theCount, theClause, addQuotes, limitHigh, FormType)
function test_status(status)
function URLEncode(strURL)
function CompareStatusDates(intArrayRef, intOffset, strDate)
function GetDateValue(i, theValue)
function AddQuotes(addQuotes)
function HiddenDB(thePropType, theAction, theField, AutoCount, bHotsheet)
function DoSavedSearch(myform)
function DoFeature(myform, thePrompt, theField)
function DoContact(myform, thePrompt, theField)
function ShiftBits(bits)
function ValToSql()
function RemoveCriteriaItem(myform, theField)
function FixApostrophe(strFixText)
function CheckRequireds(myform)
*/

var ButtonOffset = 5;
var blnRepaint = false;
var iTimerIdentifier = 0;

var boolcobroke=false;

function Test_Access(strValue, intBit)
{
	if(strValue.length == 0) //there is nothing to test
		return false;
	else if( (strValue.charCodeAt(5 - parseInt(intBit / 8.0)) && (2 ^ (intBit % 8))) > 0)
		return true;
	return false;
}

function GetCookie(sName)
{
	// cookies are separated by semicolons
	var aCookie = document.cookie.split("; ");
	for (var i=0; i < aCookie.length; i++)
	{
		// a name/value pair (a crumb) is separated by an equal sign
		//alert('aCookie[i]=' + aCookie[i]);
		var aCrumb = aCookie[i].split("=");
		//alert("Name=" + aCrumb[0] + " value=" + aCrumb[1]);
		if (sName == aCrumb[0]) 
			return unescape(aCrumb[1]);
	}
	return null;
}

function SetCookie(sName, sValue)
{
  date = new Date();
  date.setFullYear(date.getFullYear() + 1); //expire in one year
  //alert('Setting ' + sName + '=' + sValue + ' : ' + date);
  document.cookie = sName + "=" + escape(sValue) + "; expires=" + date.toGMTString();
}

function UpdateCoordinateText(ObjSelect, ObjDest)
{
	ObjDest.value = ObjSelect.options[ObjSelect.selectedIndex].text;
}

function UpdateCoordinateSelection(ObjText, ObjDest)
{
	if(ObjText.value == '')
		return;
	if(isaPosInt(ObjText.value) && ObjText.value > 0 && ObjText.value < 221)
	{
		for(var x=0;x<ObjDest.options.length;x++)
		{
			if(ObjDest.options[x].text == ObjText.value)
			{
				ObjDest.selectedIndex = x;
				break;
			}
		}
	}
	else
	{
		alert('Please enter a number between 1 and 220');
		ObjText.value = '';
		ObjText.focus();
	}
}

function NeighborhoodDefWindow(board_id)
{
	var Destination = 'NeighborhoodDefs.asp';
	Destination += '?area=' + document.mainform.BOROUGH_ID.options[document.mainform.BOROUGH_ID.selectedIndex].value;
	var width;
	var height;
	if(board_id == 'C')
	{
		width = 750;
		height= 550;
	}
	else
	{
		width = 575;
		height= 440;
	}
	openModalWindow(Destination,window,width,height);
}

function NeighborhoodDefWindowAdvanced()
{
	var Destination = 'NeighborhoodDefs.asp';
	var root = rstSearchTemp.documentElement.selectNodes("rs:data/z:row[@VIEW_NAME = 'AREA']");
	//alert("xml=" + root.item(0).xml);
	//root.item(0).getAttributeNode("VALUE1").text
	Destination += '?area=' + root.item(0).getAttributeNode("VALUE1").text;
	if(strBoard_ID == 'C')
	{
		width = 750;
		height= 550;
	}
	else
	{
		width = 575;
		height= 440;
	}
	openModalWindow(Destination,window,width,height);
}

function FormatComma(number) 
{
	number = '' + number;
	if (number.length > 3) 
	{
		var mod = number.length % 3;
		var output = (mod > 0 ? (number.substring(0,mod)) : '');
		for (i=0 ; i < Math.floor(number.length / 3); i++) 
		{
		if ((mod == 0) && (i == 0))
			output += number.substring(mod+ 3 * i, mod + 3 * i + 3);
		else
			output+= ',' + number.substring(mod + 3 * i, mod + 3 * i + 3);
		}
	return (output);
	}
else return number;
}


function SessionTimer()
{
	
	intSessionTime--;
	if(intSessionTime == 0)
	{
		//alert('Your session has timed out. You must login to the system.');
		//location.href = "/"; //go to the login page
		alert('Your session has timed out. This window will be closed and you must re-login to the system.');
		self.close();
	}
	window.status = "Session Time Remaining..." + parseInt(intSessionTime / 60.0) + ":" + (intSessionTime % 60);
	iTimerIdentifier = setTimeout('SessionTimer();',1000);
}

function SessionTimerReset()
{
	intSessionTime = intTimeOut * 60;
}


/*
function openXMLDoc(theXMLDoc, XMLVersion)
{
	var xmlDocTemp = new ActiveXObject("Microsoft.XMLDOM");
	xmlDocTemp.async = false;
	xmlDocTemp.load(getXMLFile(theXMLDoc, XMLVersion));
	return xmlDocTemp;
}

function getXMLFile(strXMLFileName, strVersion)
{
	var tmpVersion;
	var strNewXMLFileName;
	var objXML = new ActiveXObject("Microsoft.XMLDOM");
	objXML.async = false;
  
	strNewXMLFileName = strXMLFileName;
	var strXML = "";
	var objectExists = true;
    //test to see if the file object is installed
    try 
    {
		tmpVersion = XMLFile.getTimeStampOnFile(strNewXMLFileName);
	}
    catch(e)
    {
		tmpVersion = strVersion; //fool the code to think that the file exists locally, but is an old version
		objectExists = false;
	}
	
	if (tmpVersion==strVersion)
	{
		if(objectExists)
			strXML = XMLFile.getXMLFile(strNewXMLFileName);
		else
			strXML = "Not Found";
		
			
		if (strXML == "Not Found")
		{
			objXML.load(strXMLFileName);
			if(objectExists)
			{
				XMLFile.putXMLFile(strNewXMLFileName,objXML.xml);
				XMLFile.putTimeStampOnFile(strNewXMLFileName,strVersion);
			}
			//alert(strXMLFileName + " was loaded from the server with version: " + strVersion);
		}
		else
		{
	        objXML.loadXML(strXML);
		}
	}
	else
    {
		objXML.load(strXMLFileName);
		XMLFile.putXMLFile(strNewXMLFileName,objXML.xml);
		XMLFile.putTimeStampOnFile(strNewXMLFileName,strVersion);
		//alert(strXMLFileName + " was loaded from the server due to a different version: " + strVersion);
    }
	return objXML;
}
*/

function loadXMLDocObjectFromServer(strXMLfilename)
{
	var xmlDocTemp = new ActiveXObject("Microsoft.XMLDOM");
	xmlDocTemp.async = false;
	xmlDocTemp.load(strXMLfilename);
	if (xmlDocTemp.parseError.errorCode != 0)
		alert("error:" + strXMLfilename + " was not loaded because " + xmlDocTemp.parseError.reason);
	return xmlDocTemp;
}

function getXMLDocObject(strXMLFileName, strVersion)
{
	var blnShowAlerts = false;
	var tmpVersion;
  	var rtnXMLDocObject = null;
  	
	var objectExists = true;
	//alert("Top of GetXMLDoc");

	// Force load of xml from server without rebuilding XML docs if on dev
	// RJO - 06.28.2001
	if(false && domain.indexOf('dev.') > -1 && strXMLFileName.indexOf('.asp') > -1)
	{
		rtnXMLDocObject = loadXMLDocObjectFromServer(strXMLFileName);
		return rtnXMLDocObject;
	}

    //test to see if the file object is installed
    try 
    {
		tmpVersion = XMLFileCacher.getTimeStampOnFile(strXMLFileName);
	}
    catch(e)
    {
		//throw e;
		//alert('error:' + e);
		objectExists = false;
	}
	
	if(objectExists)
	{
		if(tmpVersion==strVersion)
		{
			if(blnShowAlerts) alert(strXMLFileName + " loaded by FileCacher with timestamp = " + strVersion);
			if(window.status.substring(window.status.length-1,window.status.length) == ')')
				window.status = window.status.substring(0,window.status.length-1) + ':Local)';
			rtnXMLDocObject = XMLFileCacher.getXMLFileObject(strXMLFileName);
		}
		else
		{
			//alert(strXMLFileName + " timestamp:" + tmpVersion + " <> database timestamp:" + strVersion);
			if(window.status.substring(window.status.length-1,window.status.length) == ')')
				window.status = window.status.substring(0,window.status.length-1) + ':Server)';
			rtnXMLDocObject = loadXMLDocObjectFromServer(strXMLFileName);
			if(blnShowAlerts) alert(strXMLFileName + " loaded from server with timestamp = " + strVersion);
			var boolRtn = XMLFileCacher.putXMLFile(strXMLFileName, rtnXMLDocObject.xml);

			//put object only works when the object was loaded from the XMLFileCacher
			//var boolRtn = XMLFileCacher.putXMLFileObject(strXMLFileName, rtnXMLDocObject);
			if(boolRtn)
			{
				XMLFileCacher.putTimestampOnFile(strXMLFileName, strVersion);
				//alert("db timestamp:" + strVersion);
				strVersion = XMLFileCacher.getTimeStampOnFile(strXMLFileName);
				//alert("file timestamp:" + strVersion);
			}
			else
				alert("failed to save xml file:" + strXMLFileName);
		}
	}
	else
	{
		//alert('Loaded XML from Server(' + strXMLFileName + ')');
		window.status = window.status.substring(0,window.status.length-1) + ':Server)';
		rtnXMLDocObject = loadXMLDocObjectFromServer(strXMLFileName);
	}

	return rtnXMLDocObject;
}

function keyPress(d)
{
	
	var key = event.keyCode
	if (key == 13) 
		EditCriteria(document.searchform);
	else if (key == 46) 
		DoRemove();
	//alert("key=" + key);
}

function mouseClick(d)
{
	EditCriteria(document.searchform);
}

function sayHello()
{
	alert("Hello");
}

var intProp_Type = 0;
var intFeatGroupRef = 0; //used to provide a unique alias for nested subqueries
var strFeatJoinBuf = ""; //used to store any JOIN statements needed forthe search

function SearchCriteria()
{
	var root, root2;
	var intCount = 0;
	rstSearchTemp = getXMLDocObject("XML/search_temp.xml", fakeXMLTimestamp);
	
	//theSearchCriteria.innerHTML = "";
	var strHTML = "";
	
	var strFeatTable = "propfeat";
	var RecordID = "LISTING_ID";

	intFeatGroupRef = 0; //used to provide a unique alias for nested subqueries
	strFeatJoinBuf = ""; //used to store any JOIN statements needed forthe search
	var intMaxFeatGroupRef = 0; // track the highest reference number

	if(intSearchID == "Last Search")
	{
			//root = rstSearchLast.getElementsByTagName('z:row');
			root = rstSearchLast.getElementsByTagName("z:row[@AGENT_ID = '" + strAgentID + "']");
			if(root.length > 0) //check to see if there was a last search
			{
				/*
				var dispitems = '';
				for(var q=0;q<root.length;q++)
					dispitems += root.item(q).xml + '\n';
				alert('Restore\n' + strAgentID + '\n' + dispitems);
				*/
				if(false || root.item(0).getAttributeNode('AGENT_ID').text == strAgentID)
				{
					truncateXMLDoc(rstSearchTemp);
					intProp_Type = root.item(0).getAttributeNode('PROP_TYPE').text;
					intPropType = intProp_Type;
					//if(strAgentID == 'LAURIEH' || strAgentID == 'ROVER')
					//	alert('intPropType=' + intPropType);
					
					for(var x=0;x<root.length;x++)
					{
						// Added true so that last search is loaded regardless of search type - RJO 1/19/2001
						if(true || root.item(x).getAttributeNode('SEARCH_TYPE').text == strSearchType)
						{
							insertRecord2(rstSearchTemp, strAgentID, intProp_Type, strSearchType, root.item(x).getAttributeNode('SNIPPET').text, root.item(x).getAttributeNode('STRING').text, root.item(x).getAttributeNode('VALUE1').text, root.item(x).getAttributeNode('VALUE2').text, root.item(x).getAttributeNode('VIEW_NAME').text)
							intPFIndex = root.item(x).getAttributeNode('SNIPPET').text.indexOf("pf", 0)
							if(intPFIndex > -1) //then we need to restore the join statement
							{	
							intFeatGroupRef = parseInt(root.item(x).getAttributeNode('SNIPPET').text.substring(intPFIndex + 2, root.item(x).getAttributeNode('SNIPPET').text.indexOf(".", intPFIndex + 2))); //get the reference number
							switch(intFeatGroupRef)
							{
								case 2:
									if(intPropType >= 3)
									{
										strFeatTable = "buildfeat";
										RecordID = "BLDG_ID";
									}
									else
									{
										strFeatTable = "unitfeat";
										RecordID = "UNIT_ID";
									}
									break;
								case 5:
								case 7:
								case 9:
								case 10:
									strFeatTable = "buildfeat";
									RecordID = "BLDG_ID";
									break;
								case 1:
								case 4:
								case 6:
								case 8:
									strFeatTable = "unitfeat";
									RecordID = "UNIT_ID";
									break;
							}
							if(intFeatGroupRef > intMaxFeatGroupRef)
								intMaxFeatGroupRef = intFeatGroupRef;
							strFeatJoinBuf += " RIGHT JOIN " + strFeatTable + " pf" + intFeatGroupRef + " ON pf" + intFeatGroupRef + "." + RecordID + " = detail_p" + intPropType + "." + RecordID;
							}
						}
					}				
					intFeatGroupRef = intMaxFeatGroupRef;
				}
				else
				{
					alert('The last search run on this computer was not run by you.\nPlease load a saved search or build a new one.');
					strSearchName = ""
					NewSearch(document.mainform)
					return false;
				}
			}
			else
			{
				if(strSearchType != 'PROSPECT')
					alert('No search appears to have been run on this computer with the current login.');
				strSearchName = ""
				NewSearch(document.mainform)
				return false;
			}
	}
	else if(intSearchID == "New Search")
	{
		truncateXMLDoc(rstSearchTemp);
	}
	else if(intSearchID != "")
	{
		
		root = rstSavedSearches.documentElement.selectSingleNode("rs:data/z:row[@SEARCH_ID = '" + intSearchID + "']");
		if(root == null)
			{
			
			truncateXMLDoc(rstSearchTemp);
			}
		else
		{
			
			intProp_Type = root.getAttributeNode('PROP_TYPE').text;
			intPropType = intProp_Type;
			
			if (root.getAttributeNode('SEARCH_NAME').text=="default");
				intPropType = strDefaultPropType;


			truncateXMLDoc(rstSearchTemp);
			root = rstSearch.documentElement.selectNodes("rs:data/z:row[@SEARCH_ID = '" + intSearchID + "']");
			for(var x=0;x<root.length;x++)
			{
				insertRecord2(rstSearchTemp, strAgentID, intProp_Type, strSearchType, root.item(x).getAttributeNode('SNIPPET').text, root.item(x).getAttributeNode('STRING').text, root.item(x).getAttributeNode('VALUE1').text, root.item(x).getAttributeNode('VALUE2').text, root.item(x).getAttributeNode('VIEW_NAME').text)
				intPFIndex = root.item(x).getAttributeNode('SNIPPET').text.indexOf("pf", 0)
				if(intPFIndex > -1) //then we need to restore the join statement
				{
					intFeatGroupRef = parseInt(root.item(x).getAttributeNode('SNIPPET').text.substring(intPFIndex + 2, root.item(x).getAttributeNode('SNIPPET').text.indexOf(".", intPFIndex + 2))); //get the reference number
					switch(intFeatGroupRef)
					{
						case 2:
							if(intPropType >= 3)
							{
								strFeatTable = "buildfeat";
								RecordID = "BLDG_ID";
							}
							else
							{
								strFeatTable = "unitfeat";
								RecordID = "UNIT_ID";
							}
							break;
						case 5:
						case 7:
						case 9:
						case 10:
							strFeatTable = "buildfeat";
							RecordID = "BLDG_ID";
							break;
						case 1:
						case 4:
						case 6:
						case 8:
							strFeatTable = "unitfeat";
							RecordID = "UNIT_ID";
							break;
					}
					if(intFeatGroupRef > intMaxFeatGroupRef)
						intMaxFeatGroupRef = intFeatGroupRef;
					strFeatJoinBuf += " RIGHT JOIN " + strFeatTable + " pf" + intFeatGroupRef + " ON pf" + intFeatGroupRef + "." + RecordID + " = detail_p" + intPropType + "." + RecordID;
				}
			}
			intFeatGroupRef = intMaxFeatGroupRef;
		}
	}	

	//set up the select criteria frame
	//strSearchType	= '" + strSearchType + "';
	//intPropType		= intProp_Type.toString();

	//strHTML += "<table border=0 cellpadding=0 cellspacing=0 width=400>";
	//strHTML += "  <tr>";
	//strHTML += "    <td width=20% valign=middle><em><font face=Arial size=2><b>" + strUserName + "'s Search Fields</b></font></em></td>";
    //strHTML += "  </tr>"
    //strHTML += "</table>"
	//theSearchCriteria.innerHTML = strHTML;
	
	//alert("SearchCriteria " + intProp_Type);
	intPropType = intProp_Type;
	SelectCriteria();
	GetAreas();	
}

function GetAreas()
{
	strAreas = "";
	var root3 = rstSearchTemp.documentElement.selectSingleNode("rs:data/z:row[@VIEW_NAME = 'AREA']");
	if(root3 != null)
	{
		var tmpAreas = root3.getAttributeNode("VALUE1").text.split(",");
		for (var x=0;x<tmpAreas.length;x++)
			strAreas += "@AREA='" + tmpAreas[x] + "'||";
		strAreas = "[" + strAreas.substring(0, strAreas.length - 2) + "]";
		//alert("strAreas=" + strAreas);
	}
}

	

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//	Primary Criteria List, Additional Criteria List Box, Criteria Display Window
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
function SelectCriteria()
{
	theSelectCriteria.innerHTML = "";
	var strHTML = "";
	strHTML += "		<table border=0 cellpadding=2 cellspacing=0 width=100%>";
	strHTML += "			<tr>";
	strHTML += "				<td width=100%>";
	strHTML += "				<table border=0 cellpadding=1 cellspacing=0 width=100% height=100%>";
	strHTML += "					<tr>";
	strHTML += "					<form name=SearchCriteriaForm>";
	strHTML += "					<input type=hidden name=search_id value='" + intSearchID + "'>";
	strHTML += "					<input type=hidden name=search_type value='PROP'>";
	strHTML += "						<td width=60% valign=middle align=left><font face=verdana,arail size=2 color=#000000>&nbsp; <b>Property Category:</b></font></td>";
	strHTML += "						<td width=40% valign=middle align=right><select name=PROP_TYPE id=sPROP_TYPE size=1 onchange='CallSelectCriteria(document.SearchCriteriaForm);'TABINDEX=7>";
	// DECO does not want a Prop Type 0 search
	//strHTML += "							<option value='0'>------------ All ------------</option>";
	var root3
	var strSelected = "";
	root3 = rstPropTypes.getElementsByTagName("z:row");
	//alert(intPropType);
	var intopt=0;
	
	for(var x=0;x<root3.length;x++)
	{
		intopt=parseInt(root3.item(x).getAttributeNode("PROP_TYPE").text);
		strSelected = "";
		

			if(intPropType == parseInt(root3.item(x).getAttributeNode("PROP_TYPE").text))
				strSelected = " selected";
				
			//if(strDefaultPropType == parseInt(root3.item(x).getAttributeNode("PROP_TYPE").text))
			//{
			//	strSelected = " selected";			
			//}	
			
			if ((intopt==5) || (intopt==6))  //check to display healthcare type
			{
				if (hc_enabled)
					strHTML += "<option value='" + Trim(root3.item(x).getAttributeNode("PROP_TYPE").text) + "'" + strSelected + ">" + root3.item(x).getAttributeNode("LONG_DESC").text + "</option>";
			}
			else
				strHTML += "<option value='" + Trim(root3.item(x).getAttributeNode("PROP_TYPE").text) + "'" + strSelected + ">" + root3.item(x).getAttributeNode("LONG_DESC").text + "</option>";
	}
	
	
	
	strHTML += "							</select></td>";
	strHTML += "					</tr>";
	strHTML += "				</table>";
	strHTML += "				</td>";
	strHTML += "			</tr>";
	strHTML += "			<tr>";
	strHTML += "				<td height=100 valign=top align=center>";
	strHTML = LoadPrimary(strHTML);
	strHTML += "				</td>";
	strHTML += "			</tr>";
	strHTML += "			<tr>";
	strHTML += "				<td>";
	strHTML += "				<table border=0 cellpadding=3 cellspacing=0 width=100%>";
	strHTML += "					<tr>";
	strHTML += "						<td width=100% align=right>";
	strHTML += "							<select name=MORE_FIELDS id=MORE_FIELDS size=1 onChange=" + String.fromCharCode(34) + "javascript:AdditionalField(this);" + String.fromCharCode(34) + "TABINDEX=9>";
	strHTML += "								<option value=" + String.fromCharCode(34) + String.fromCharCode(34) + ">-----Additional Criteria-----</option>";
	strHTML += "							</select></td>";
	strHTML += "					</tr>";
	strHTML += "					</form>";
	strHTML += "				</table>";
	//strHTML += "				</td>";
	//strHTML += "			</tr>";
	//strHTML += "		</table>";
	strHTML += "</form>";
	theSelectCriteria.innerHTML = strHTML;
	SortAdditionalFields(rstSearchDefinitions, SearchCriteriaForm.MORE_FIELDS, "@PROMPT_", "xml/rs:data/z:row[@PROP_TYPE = '" + intPropType + "' || @PROP_TYPE = '0']", "SEARCH_SECONDARY");
	//	Criteria Display Window
	strHTML = "			<table border=0 cellpadding=0 cellspacing=0 width=715>";
	strHTML += "			<tr>";
	strHTML += "				<td align=left valign=middle width=10 height=20>&nbsp;&nbsp;</td>"
	strHTML += "				<td align=left valign=middle width=430 nowrap><font color=#000000 face=verdana,arial><b> Search Criteria</b>&nbsp;&nbsp;<small><small><small><!--(To choose more than 1 hold down your Ctrl key)--></small></small></small></font></td>";
	//strHTML += "				<td align=right valign=middle width=3><img src='../images/buttons/gray/btnSeperator.gif'></td>";
	//If we ever go to buttons.
	//strHTML += "				<td align=right><a href=" + String.fromCharCode(34) + "javascript:EditCriteria(document.searchform);" + String.fromCharCode(34) + " ONMOUSEOVER=" + String.fromCharCode(34) + "changeImages('btnEditCriteria', '../images/buttons/gray/btnEditCriteria-over.gif'); return true;" + String.fromCharCode(34) + " ONMOUSEOUT=" + String.fromCharCode(34) + "changeImages('btnEditCriteria', '../images/buttons/gray/btnEditCriteria.gif'); return true;" + String.fromCharCode(34) + "><img NAME='btnEditCriteria' SRC='../images/buttons/gray/btnEditCriteria.gif' WIDTH=161 HEIGHT=22 BORDER=0></a></td>";
	//strHTML += "				<td align=right><a href=" + String.fromCharCode(34) + "javascript:DoRemove();" + String.fromCharCode(34) + " ONMOUSEOVER=" + String.fromCharCode(34) + "changeImages('btnRemCriteria', '../images/buttons/gray/btnRemCriteria-over.gif'); return true;" + String.fromCharCode(34) + " ONMOUSEOUT=" + String.fromCharCode(34) + "changeImages('btnRemCriteria', '../images/buttons/gray/btnRemCriteria.gif'); return true;" + String.fromCharCode(34) + "><img NAME='btnRemCriteria' SRC='../images/buttons/gray/btnRemCriteria.gif' WIDTH=161 HEIGHT=22 BORDER=0></a>&nbsp;&nbsp;&nbsp;</td>";
	strHTML +=					"<td align=right><img src=" + String.fromCharCode(34) + "../images/menu/ball_button_gold.gif" + String.fromCharCode(34) + " width=10 height=10 name=" + String.fromCharCode(34) + "globeEdit" + String.fromCharCode(34) + ">&nbsp;&nbsp;<a class=go href=" + String.fromCharCode(34) + "javascript:EditCriteria(document.searchform);" + String.fromCharCode(34) + " onmouseover=" + String.fromCharCode(34) + "swapImage('document.globeEdit','document.globeEdit','../images/menu/ball_button_green.gif');return document.returnValue" + String.fromCharCode(34) + " onmouseout=" + String.fromCharCode(34) + "swapImgRestore();" + String.fromCharCode(34) + " TABINDEX=10>Edit Highlighted</a></td>";
	strHTML +=					"<td align=right><img src=" + String.fromCharCode(34) + "../images/menu/ball_button_gold.gif" + String.fromCharCode(34) + " width=10 height=10 name=" + String.fromCharCode(34) + "globeRem" + String.fromCharCode(34) + ">&nbsp;&nbsp;<a class=go href=" + String.fromCharCode(34) + "javascript:DoRemove();" + String.fromCharCode(34) + " onmouseover=" + String.fromCharCode(34) + "swapImage('document.globeRem','document.globeRem','../images/menu/ball_button_green.gif');return document.returnValue" + String.fromCharCode(34) + " onmouseout=" + String.fromCharCode(34) + "swapImgRestore();" + String.fromCharCode(34) + " TABINDEX=11>Remove Highlighted</a>&nbsp;&nbsp;&nbsp;</td>";
	strHTML += "			</tr>";
	strHTML += "			<tr>";
	strHTML += "				<td width=100% align=center colspan=4>";
	strHTML += "				<table border=0 cellpadding=0 cellspacing=0>";
	strHTML += "					<tr>";
	strHTML += "					<form name='searchform'>";
	strHTML += "						<td width=100%>";
	strHTML += "							<select name=CRITERIA style='background-color: #ffffff;' id=CRITERIA size=7 style='width=700;' onkeydown='keyPress();' ondblclick='mouseClick();'TABINDEX=12>";
	root = rstSearchTemp.getElementsByTagName('z:row');
	theIndex = 0;
    var STRING="";
	for(var x=0;x<root.length;x++)
	{
		theFields[theIndex] = root.item(x).getAttributeNode('VIEW_NAME').text;
		STRING=root.item(x).getAttributeNode('STRING').text;
		//if (STRING.indexOf('Budget Search')>-1)
		//alert(STRING);
		    STRING=STRING.replace("Budget Search","Monthly");
		
		strHTML += "<option value='" + root.item(x).getAttributeNode('VIEW_NAME').text + "' selected>" + STRING + "</option>";
		theIndex++;
	}
	strHTML += "							</select>";
	strHTML += "						</td>";
	strHTML += "					</form>";
	strHTML += "					</tr>";
	strHTML += "				</table>";
	strHTML += "				</td>";
	strHTML += "			</tr>";
	strHTML += "		</table>";
	strHTML += "		</td>";
	strHTML += "	</tr>";
	strHTML += "</table>";
	theDisplayCriteria.innerHTML = strHTML;
}

function LoadPrimary(strHTML)
{
	var root;
	var intMax_Columns = 3;
	
//alert("Primary = " + intPropType);
	root = rstSearchDefinitions.documentElement.selectNodes("rs:data/z:row[@PROP_TYPE = '" + intPropType + "']");

	strHTML += "<table class=FieldPick border=0 bgcolor=#ffffee cellspacing=0 cellpadding=0 width=97% height=95>";
	strHTML += "<tr>";
	strHTML += "<td valign=top>";
	strHTML += "<table border=0 cellspacing=0 cellpadding=0 width=100%>";
 	intMax_Columns = 3;
	intLineNumber = intMax_Columns;
	buttonRef = 1;

	for(var x=0;x<root.length;x++)
	{
		//alert(root.item(x).xml);
		if(root.item(x).getAttributeNode("SEARCH_PRIMARY").text.indexOf("," + intPropType + ",") >= 0)
		{
		//alert(root.item(x).xml);
  			if(intLineNumber == intMax_Columns)
 			{
				strHTML += "<TR>";
 					intLineNumber = 0
			}
 				intLineNumber++;
 				buttonRef = buttonRef ^ 1;
				strHTML += "<td>&nbsp;<img src=" + String.fromCharCode(34) + "../images/menu/ball_button_gold.gif" + String.fromCharCode(34) + " width=10 height=10 name=" + String.fromCharCode(34) + "globe" + (x + ButtonOffset) + String.fromCharCode(34) + "></td><td>&nbsp;&nbsp;<a class=go href=" + String.fromCharCode(34) + "javascript:OpenChild('" + root.item(x).getAttributeNode('VIEW_NAME').text + "', 'standard');" + String.fromCharCode(34) + " onmouseover=" + String.fromCharCode(34) + "swapImage('document.globe" + (x + ButtonOffset) + "','document.globe" + (x + ButtonOffset) + "','../images/menu/ball_button_green.gif');return document.returnValue" + String.fromCharCode(34) + " onmouseout=" + String.fromCharCode(34) + "swapImgRestore();" + String.fromCharCode(34) + "TABINDEX=8>" + root.item(x).getAttributeNode('PROMPT_').text + "</a></td>";
 				if(intLineNumber == intMax_Columns)
					strHTML += "</TR>";
		}
		//else
			//alert("NOT " + root.item(x).xml);
	}
	if(intLineNumber != intMax_Columns)
	{
		for(i=intLineNumber;i<intMax_Columns;i++)
			strHTML += "<td>&nbsp;</td>";
		strHTML += "</TR>";
	}
	strHTML += "</table>";
	strHTML += "</td>";
	strHTML += "</tr>";
	strHTML += "</table>";
	return strHTML;
}

function LoadSecondary(strHTML)
{
	var root;
	root = rstSearchDefinitions.documentElement.selectNodes("rs:data/z:row[@PROP_TYPE = '" + intPropType + "']");
	for(var x=0;x<root.length;x++)
	{
		//alert(root.item(x).xml);
		if(root.item(x).getAttributeNode("SEARCH_SECONDARY").text.indexOf("," + intPropType + ",") >= 0)
			strHTML += "<option value='" + root.item(x).getAttributeNode('VIEW_NAME').text + "'>" + root.item(x).getAttributeNode('PROMPT_').text + "</option>";
	}
	return strHTML;
}


function SortAdditionalFields(xmlDocTemp, formSelectElement, strSortField, strSelectField, strTestField)
{
	var sortField;
	var selectField;
	var ifExpr;
	
	sortField = sortAddFields.XMLDocument.selectSingleNode("//@order-by");
	selectField = sortAddFields.XMLDocument.selectSingleNode("//@select");
	ifExpr = sortAddFields.XMLDocument.selectSingleNode("//@expr");

	sortField.value = strSortField;
	selectField.value = strSelectField;
	ifExpr.value = "IsType" + intPropType + ".test(this.selectSingleNode('@" + strTestField + "').text)";		
	
	newList = xmlDocTemp.transformNode(sortAddFields.XMLDocument);
	
	var strNewSelect = formSelectElement.outerHTML;
	strNewSelect=strNewSelect.substring(0,strNewSelect.length-9);
	//strNewSelect+="<option value=\"\" selected>-----Additional Fields-----</option>";
	strNewSelect+=newList;
	strNewSelect+="</SELECT>"
	formSelectElement.outerHTML = strNewSelect;
	
	formSelectElement.selectedIndex = 0;
}


function LoadFeatures(strHTML)
{
	var root;
		
	root = rstFeatures.documentElement.selectNodes("rs:data/z:row[@PROP_TYPE = '" + intPropType + "']");
	for(var x=0;x<root.length;x++)
		strHTML += "<option value='F" + root.item(x).getAttributeNode('VIEW_NAME').text + "'>" + root.item(x).getAttributeNode('PROMPT_').text + "</option>";
	return strHTML;
}


function RemoveOrphanedCriteria()
{
	var root;
	//Remove any search criteria, that don't match the new selected property type 
	if(document.searchform.CRITERIA.options.length > 0)
	{
		for (var i=document.searchform.CRITERIA.options.length - 1; i >= 0;i--)
		{
			if (theFields[i] != "")
			{
				root = rstSearchDefinitions.documentElement.selectSingleNode("rs:data/z:row[@VIEW_NAME = '" + theFields[i] + "']");
				if(root != null)
				{
					if(parseInt(root.getAttributeNode("VIEW_NAME").text) > 0 || (root.getAttributeNode("SEARCH_PRIMARY").text.indexOf("," + intPropType + ",") == -1 && root.getAttributeNode("SEARCH_SECONDARY").text.indexOf("," + intPropType + ",") == -1))
					{
						document.searchform.CRITERIA.selectedIndex = i;
						DoRemove();
					}
				}
			}
		}
	}
}


function CallSelectCriteria(myform)
{
	/*
	if(blnRepaint)
	{
		alert("You must wait for the page to finish reloading.")
		for(var i=0;i<myform.PROP_TYPE.options.length;i++)
		{
			if(intPropType == myform.PROP_TYPE.options[i].value)
			{
				myform.PROP_TYPE.selectedIndex = i;
				break;
			}
		}
		return;
	}
	blnRepaint = true;
	*/
	//alert("myform.search_type.value=" + myform.search_type.value);
	//alert("myform.search_type.value=" + myform.PROP_TYPE.options[myform.PROP_TYPE.selectedIndex].value);
	//strSearchType	= myform.search_type.value;
	//alert(intPropType);
	intPropType		= myform.PROP_TYPE.options[myform.PROP_TYPE.selectedIndex].value;
	if(intPropType == '1' || intPropType == '3' ||intPropType == '5' )
	{
		//MlsStatus = DefaultMLSStatuses.slice(0, -1);
		//MlsStatusNames = DefaultMLSStatusNames.slice(0, -1);
		//JTF code was not accepting SLDO status
		MlsStatus = DefaultMLSStatuses;
		MlsStatusNames = DefaultMLSStatusNames;
	}
	else
	{
	
		MlsStatus = DefaultMLSStatuses.slice(0, -3);
		MlsStatusNames = DefaultMLSStatusNames.slice(0, -3);
	// By Kin	
		MlsStatus.push("RNTD");
		MlsStatusNames.push("Rented");
		
		MlsStatus[MlsStatus.length] = DefaultMLSStatuses[DefaultMLSStatuses.length-1];
		MlsStatusNames[MlsStatusNames.length] = DefaultMLSStatusNames[DefaultMLSStatusNames.length-1];
	}
	ClearCriteriaWindow();
	RemoveOrphanedCriteria();
	//alert("CallSelectCriteria");
	SelectCriteria();
	blnRepaint = false;
}

function LoadDefaultSearch()
{
	//alert(strDefaultPropType);
	root = rstSavedSearches.documentElement.selectNodes("rs:data/z:row[@SEARCH_TYPE = 'PROP']");
	for(var x=0;x<root.length;x++)
	{
		if(root.item(x).getAttributeNode('SEARCH_NAME').text.toUpperCase() == 'DEFAULT')
		{
			//alert("j");
			strSearchName = root.item(x).getAttributeNode('SEARCH_NAME').text;
			intSearchID = root.item(x).getAttributeNode('SEARCH_ID').text;
			intPropType = root.item(x).getAttributeNode('PROP_TYPE').text;
			//intPropType = 1;
			//alert(intPropType);
			SearchCriteria();
			GetAreas();
			return;
		}
	}
	// if no default search was found, load blank
	NewSearch(document.mainform);
}

function NewSearch(myform)
{
	intSearchID = "New Search"
	myform.NEW_SEARCH.value = "1";
	intPropType = strDefaultPropType;
	document.SearchCriteriaForm.PROP_TYPE.selectedIndex = intPropType - 1; //DECO does not have Prop Type 0 so we need to subtract 1
	FlipCoBroke(false);
	SAVEAS.value="";
	truncateXMLDoc(rstSearchTemp);
	CallSelectCriteria(document.SearchCriteriaForm);
	if (go)
		DoClear();
}

function FlipCoBroke(value)
{
	boolcobroke=value;
	if (value)
		{
			document.all.banner.style.display="none";
			document.all.banner.style.visibility="hidden";
			document.all.cobrokespan.style.display="block";
			document.all.cobrokespan.style.visibility="visible";
		
		}
	else
		{
			document.all.banner.style.display="block";
			document.all.banner.style.visibility="visible";
			document.all.cobrokespan.style.display="none";
			document.all.cobrokespan.style.visibility="hidden";
		}

}

function DoSearch(myform)
{
	SessionTimerReset()
	ClearCriteriaWindow();					//Clear all criteria window contents.
	theRecordCount.innerText = "        ";	//Replace count box with 8 spaces

	var strHTML = "";
	theFields = new Array();
	if(myform.SEARCHES.value == "New Search")
	{
	    mapsearchid="NEW";
		strSearchName = "";
		LoadDefaultSearch();
		//Load the default instead
		//NewSearch(myform);
		return;

	}
	myform.NEW_SEARCH.value = "0";

	if(myform.SEARCHES.value == "Last Search")
		{
		strSearchName = "";
		intSearchID = myform.SEARCHES.value;
		intPropType = PropTypes[1];
		FlipCoBroke(false);
		}
	else
	{
		if(myform.SAVED_SEARCHES.selectedIndex < 0)
		{
			strSearchName = "";
			intSearchID = "New Search";
			mapsearchid="NEW";
			intPropType = 1;
			strHotsheet = 'N';
			FlipCoBroke(false);

		}
		else
		{
			strSearchName = myform.SAVED_SEARCHES.options[myform.SAVED_SEARCHES.selectedIndex].text;
			if(strSearchName.substring(strSearchName.length-4,strSearchName.length) == " [H]")
				strSearchName = strSearchName.substring(0,strSearchName.length-4);
			intSearchID = myform.SAVED_SEARCHES.options[myform.SAVED_SEARCHES.selectedIndex].value;
			mapsearchid=myform.SAVED_SEARCHES.options[myform.SAVED_SEARCHES.selectedIndex].value;
			intPropType = PropTypes[myform.SAVED_SEARCHES.selectedIndex + 2];
			strHotsheet = myform.SAVED_SEARCHES.options[myform.SAVED_SEARCHES.selectedIndex].hotsheet;
		}
		
	}
	SearchCriteria();
	GetAreas();

	if (strSearchName=="CoBroke Listing Search" || strSearchName=="CoBroke Critical Change")
		{
			FlipCoBroke(true);
			alert('To complete the criteria for the CoBroke Report, please enter a date range.');
			if(intSearchID == 63 || intSearchID == 809 || intSearchID == 2058) // the search_id's are 63, 97 and 808, 809 and 2057, 2058
				OpenChild('EXCL_AGREE_START','standard');
			else
				OpenChild('DATE_LAST','standard'); //this value is also used in XMLSearch/Search_Setup.asp and XMLSearch/Searchdb.asp
		}
	else
		{	FlipCoBroke(false);}
}

function GetCount()
{
	
		//Reset session time
		//SessionTimerReset();
		//Disabled 2/14/01 by RJO - if no criteria was entered, we do NOT want to reset the timer.
		
		//If Criteria window is open when the user clicks count then
		//click the OK button, leaving the the criteria window visible.
		//DoDB will be called from the addCriteria2() function.
		if (OKCancelButtons.style.visibility =="visible")
			{	
			blnLeaveCriteria = true;
			//Reset session time
			SessionTimerReset();
			CriteriaOKButton.click();
			}
		else
			{
			if(document.searchform.CRITERIA.options.length == 0)
			{
				alert("You must enter at least one search criteria, before you can get a record count.");
				return;
			}
			else
			{
			//Reset session time
			//alert('1');
			SessionTimerReset();
			//alert('2');
			DoDB('count', '', '', false);
			//alert('3');
			}
		}
}


function LoadSearch(theField)
{
	if (theField.options[theField.selectedIndex].value == "New Search")
		alert("You cannot search from a New Search.\nYou must save the search first.")
	else if (theField.options[theField.selectedIndex].value == "Last Search")
		alert("You cannot search from the Last Search.\nYou must edit the search first.")
	else
		location.href="Search_Selection.asp?dosavedsearch=" + theField.options[theField.selectedIndex].value
}

function ReLoad(theType)
{
	location.href="Search_Selection.asp?reload=" + theType
}

function DoDelete(myform)
{
    
	if (myform.SAVED_SEARCHES.value =="")
	{
		alert("You must select a saved search");
		return;
	}
//	if (myform.elements[Get_Fieldname(myform, "R1") + 1].checked)
//	{	
//		DoDeleteProspect(myform);
//		return;
//	}
	if (myform.SAVED_SEARCHES.options[myform.SAVED_SEARCHES.selectedIndex].text=="CoBroke Listing Search" || myform.SAVED_SEARCHES.options[myform.SAVED_SEARCHES.selectedIndex].text=="CoBroke Critical Change")
	{
		alert("You cannot delete the Cooperating Broker Searches");
		return;
	}
	if(confirm('Are you sure you want to delete the search named "' + myform.SAVED_SEARCHES.options[myform.SAVED_SEARCHES.selectedIndex].text + '"?'))
		{
		ClearCriteriaWindow()
		var strPOSTURL = "Search_Delete.asp";
		var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		xmlhttp.Open("POST", strPOSTURL, false);
	   
		var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.loadXML("<XML></XML>");
		var temproot = xmlDoc.documentElement;
		var intSearchID = myform.SAVED_SEARCHES.value;
			
		var newNode = rstSearchTemp.createNode (1, "FORM_ELEMENTS", "")
		temproot.appendChild(newNode)
		newNode = rstSearchTemp.createNode(2, "SEARCH_ID", "")
		temproot.childNodes.item(temproot.childNodes.length - 1).attributes.setNamedItem (newNode)
		newNode = rstSearchTemp.createNode(2, "SEARCH_TYPE", "")
		temproot.childNodes.item(temproot.childNodes.length - 1).attributes.setNamedItem (newNode)
		newNode = rstSearchTemp.createNode(2, "HOTSHEET", "")
		temproot.childNodes.item(temproot.childNodes.length - 1).attributes.setNamedItem (newNode)
		newNode = rstSearchTemp.createNode(2, "REPLY", "")
		temproot.childNodes.item(temproot.childNodes.length - 1).attributes.setNamedItem (newNode)

		temproot.childNodes.item(temproot.childNodes.length - 1).setAttribute("SEARCH_ID", "'" + intSearchID + "'");
		temproot.childNodes.item(temproot.childNodes.length - 1).setAttribute("SEARCH_TYPE", strSearchType);
		temproot.childNodes.item(temproot.childNodes.length - 1).setAttribute("HOTSHEET", myform.SAVED_SEARCHES.options[myform.SAVED_SEARCHES.selectedIndex].hotsheet);
		temproot.childNodes.item(temproot.childNodes.length - 1).setAttribute("REPLY", "");	//alert("SEND xmlhttp.xml=" + xmlDoc.xml);	

		//alert('SEND= ' + xmlDoc.xml);
		//Displ('SEND= ' + xmlDoc.xml);
		xmlhttp.Send(xmlDoc.xml);
		xmlhttp = xmlhttp.responseXML
		//alert('RETURN= ' + xmlhttp.xml);

		if(xmlhttp.xml != '')
		{
			var strStatus = xmlhttp.documentElement.childNodes.item(0).getAttributeNode("REPLY").text
			//var currNode = rstSavedSearches.documentElement.childNodes.item(0)
			//var oldChild = rstSavedSearches.documentElement.removeChild(rstSavedSearches.documentElement.childNodes.item(0))
			if (strStatus.indexOf("Failure=", 0) == -1) //successful save
			{
				//alert("rstSearch=" + rstSearch.xml);
				temproot = rstSavedSearches.documentElement.selectNodes("rs:data/z:row[@SEARCH_ID = '" + myform.SAVED_SEARCHES.options[myform.SAVED_SEARCHES.selectedIndex].value + "']");
				var currNode;
				var oldChild;

				for(var x=0;x<temproot.length;x++)
				{
					currNode = rstSavedSearches.documentElement.childNodes.item(1)
					oldChild = currNode.removeChild(temproot.item(x))
				}
				temproot = rstSearch.documentElement.selectNodes("rs:data/z:row[@SEARCH_ID = '" + myform.SAVED_SEARCHES.options[myform.SAVED_SEARCHES.selectedIndex].value + "']");
				for(var x=0;x<temproot.length;x++)
				{
					currNode = rstSearch.documentElement.childNodes.item(1)
					oldChild = currNode.removeChild(temproot.item(x))
				}
				myform.SAVED_SEARCHES.options.remove(myform.SAVED_SEARCHES.selectedIndex);
				//myform.SAVED_SEARCHES.selectedIndex = 0;
				document.mainform.NEW_SEARCH.value = 1;
				document.mainform.SEARCHES.value = "New Search";
				intSearchID = "New Search";
				DoSearch(myform);
				SearchCriteria();
				alert("Your search was deleted successfully.");
			}
			else
			{
				alert("Error deleting your search.");
			}
		}
		else
		{
			alert("Error deleting your search.");
		}
	}
}

function DoDeleteProspect(myform)
{
	
	if (myform.SEARCHES.value == "New Search")
		alert("You cannot delete a New Search")
	else if (myform.SEARCHES.value == "Last Search")
		alert("You cannot delete the Last Search")
	else
	{
//		if(confirm('Are you sure you want to delete the prospect named "' + myform.SEARCHES.options[myform.SEARCHES.selectedIndex].text + '"?'))
//			location.href="Search_Selection.asp?delete_prospect=" + myform.SEARCHES.value
	}
}



function ChkSrchName(strSaveName)
{

	var s="";
    var url="Search_Check.asp?SearchName=" + strSaveName + "&SearchType=" + strSearchType + "&userid=" + strAgentID;
    
    xmlHttp=GetXmlHttpObject();
    xmlHttp.onreadystatechange=function() {
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
    { 
        if (xmlHttp.status==200) 
        {
                s=xmlHttp.responseText;
        }
    } 

   }
   //alert(url);
   xmlHttp.open("GET",url,false); 
   xmlHttp.send(null);
   
   return s;
}








function DoFileSaveAs(strSaveName, strOverWrite, bHotsheet)
{
	var strPOSTURL = "Search_Save.asp";
	var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	xmlhttp.Open("POST", strPOSTURL, false);
    
	var temproot = rstSearchTemp.documentElement
//alert("temproot.childNodes.length=" + temproot.childNodes.length);		
	if(temproot.childNodes.length > 1)
	{
		var newNode = rstSearchTemp.createNode (1, "FORM_ELEMENTS", "")
		temproot.appendChild(newNode)
		newNode = rstSearchTemp.createNode(2, "PROP_TYPE", "")
		temproot.childNodes.item(2).attributes.setNamedItem (newNode)
		newNode = rstSearchTemp.createNode(2, "SEARCH_ID", "")
		temproot.childNodes.item(2).attributes.setNamedItem (newNode)
		newNode = rstSearchTemp.createNode(2, "PROSPECT_ID", "")
		temproot.childNodes.item(2).attributes.setNamedItem (newNode)
		newNode = rstSearchTemp.createNode(2, "SEARCH_TYPE", "")
		temproot.childNodes.item(2).attributes.setNamedItem (newNode)
		newNode = rstSearchTemp.createNode(2, "SEARCH_NAME", "")
		temproot.childNodes.item(2).attributes.setNamedItem (newNode)
		newNode = rstSearchTemp.createNode(2, "OVERWRITE", "")
		temproot.childNodes.item(2).attributes.setNamedItem (newNode)
		newNode = rstSearchTemp.createNode(2, "TIMESTAMP", "")
		temproot.childNodes.item(2).attributes.setNamedItem (newNode)
		
		temproot.childNodes.item(2).setAttribute("PROP_TYPE", document.SearchCriteriaForm.PROP_TYPE.options[document.SearchCriteriaForm.PROP_TYPE.selectedIndex].value);
		temproot.childNodes.item(2).setAttribute("SEARCH_ID", intSearchID);
		temproot.childNodes.item(2).setAttribute("PROSPECT_ID", document.mainform.prospect_id.value);
		temproot.childNodes.item(2).setAttribute("SEARCH_TYPE", strSearchType);
		temproot.childNodes.item(2).setAttribute("SEARCH_NAME", strSaveName);
		temproot.childNodes.item(2).setAttribute("OVERWRITE", strOverWrite);
		if(bHotsheet)
			temproot.childNodes.item(2).setAttribute("HOTSHEET", 'Y');
		else
			temproot.childNodes.item(2).setAttribute("HOTSHEET", 'N');
		temproot.childNodes.item(2).setAttribute("TIMESTAMP", rstXMLVersions.documentElement.selectSingleNode("rs:data/z:row[@filename = 'GetSearches.asp']").getAttributeNode("timestamp").text);
	}
	//alert("before: "+intSearchID);
//alert("SEND xmlhttp.xml=" + rstSearchTemp.xml);
//if(bdebug) theSQL.innerText = "SEND xmlhttp.xml=" + rstSearchTemp.xml;
	xmlhttp.Send(rstSearchTemp.xml);
    //alert(intSearchID);
    //if (domain.indexOf('dev.') > -1 ) //only for dev cuz it won't get rstSearchTemp.xml working on dev
   // {
        //alert("getxml.asp?searchid=" + intSearchID + "&userid=" + strAgentID);
        xmlhttp.Open("POST", "getxml.asp?&searchid=" + intSearchID + "&userid=" + strAgentID, false); 
        xmlhttp.Send(null); 
   // }


//alert("RETURNED xmlhttp=" + xmlhttp.responseXML);	
	xmlhttp = xmlhttp.responseXML

//alert("RETURNED xmlhttp.xml=" + xmlhttp.xml);	
	var strStatus = xmlhttp.documentElement.childNodes.item(2).getAttributeNode("SEARCH_NAME").text;	
	
	intSearchID = xmlhttp.documentElement.childNodes.item(2).getAttributeNode("SEARCH_ID").text;
	
    //var strStatus = strSaveName;
    
    
	//save map search coords if any
	if (PointX.length>0)
	    storecoords_prospect();
	
	
	
	
	
	
	
	
	
	document.mainform.prospect_id.value = xmlhttp.documentElement.childNodes.item(2).getAttributeNode("PROSPECT_ID").text;
//alert("strStatus=" + strStatus);
	//alert("Before TimeStamp=" + rstXMLVersions.documentElement.selectSingleNode("rs:data/z:row[@filename = 'GetSearches.asp']").getAttributeNode("timestamp").text);
	//alert("XML TimeStamp=" + rstXMLVersions.xml);
	
	temproot = rstXMLVersions.documentElement.selectSingleNode("rs:data/z:row[@filename = 'GetSearches.asp']");
	temproot.setAttribute("timestamp", xmlhttp.documentElement.childNodes.item(2).getAttributeNode("TIMESTAMP").text);
	temproot = rstXMLVersions.documentElement.selectSingleNode("rs:data/z:row[@filename = 'GetSavedSearches.asp']");
	temproot.setAttribute("timestamp", xmlhttp.documentElement.childNodes.item(2).getAttributeNode("TIMESTAMP").text);
	rstXMLVersions.documentElement.selectSingleNode("rs:data/z:row[@filename = 'GetSavedSearches.asp']").setAttribute("timestamp", xmlhttp.documentElement.childNodes.item(2).getAttributeNode("TIMESTAMP").text);
	rstXMLVersions.documentElement.selectSingleNode("rs:data/z:row[@filename = 'GetSearches.asp']").setAttribute("timestamp", xmlhttp.documentElement.childNodes.item(2).getAttributeNode("TIMESTAMP").text);
	//theSQL.innerText = xmlhttp.documentElement.childNodes.item(xmlhttp.documentElement.childNodes.length - 1).getAttributeNode("SEARCH_TYPE").text;
	
	//alert("After TimeStamp=" + rstXMLVersions.documentElement.selectSingleNode("rs:data/z:row[@filename = 'GetSearches.asp']").getAttributeNode("timestamp").text);
	//alert("XML TimeStamp=" + rstXMLVersions.xml);
	
	var oldChild = rstSearchTemp.documentElement.removeChild(rstSearchTemp.documentElement.childNodes.item(2));
//alert("rstSearchTemp=" + rstSearchTemp.xml);    

    //alert(intSearchID);
	return strStatus;
}


function AddCriteria(theField, theText, theCount, AutoCount)
{
	var newItem;
	if (!ChangeCriteria(theField, theText))
	{
		theFields[theIndex] = theField;
		newItem = new Option(theText, theIndex.toString(), false, true);
		document.searchform.CRITERIA.options[theIndex] = newItem;
		theIndex++;
	}
	//if (AutoCount == "true")
		//document.countform.RECORDCOUNT.value = theCount;
}

function ChangeCriteria(theField, theText)
{
	for (var i=0; i<theFields.length; i++)
	{
		//alert("i=" + i + " theFields=" + theFields[i] + " theField=" + theField);
		if(theFields[i] == theField)
		{
			if(document.searchform.CRITERIA.options.length > i)
				document.searchform.CRITERIA.options[i].text = theText;
			else
				return false;
			return true;
		}
	}
	return false;
}

function EditCriteria(myform)
{
    
	if(document.searchform.CRITERIA.options.length > 0)
	{
		strFieldType = ""; //clear this, since we can't know if it is a feature field or not
		theField= theFields[myform.CRITERIA.selectedIndex]
		//alert(theField);
		intPropType = document.SearchCriteriaForm.PROP_TYPE.options[document.SearchCriteriaForm.PROP_TYPE.selectedIndex].value
		
		 if(theField=='App_Out') {
		        theField = 'STATUS';
		    }
		    
		//if(document.countform.AUTOCOUNT.checked)
		//	strAutoCount = "true";
		//else
			strAutoCount = "false";

        
        
		if(strFieldType == "feature" || isaPosInt(theField))
		{
			root = rstFeatures.documentElement.selectSingleNode("rs:data/z:row[@PROP_TYPE = '" + intPropType + "'][@VIEW_NAME = '" + theField.charAt(theField.length - 1) + "']");
			LoadCriteriaWindow();
			
			
			return;
		}
		else
		{
		
		   
		   
			root = rstSearchDefinitions.documentElement.selectSingleNode("rs:data/z:row[@PROP_TYPE = '" + intPropType + "'][@VIEW_NAME = '" + theField + "']")
		}
		if(theField == "")
		{
			theCriteriaWindow.innerHTML = "";
			OKCancelButtons.style.visibility="hidden";	
			document.searchform.CRITERIA.focus();		
			return;
		}
		else if(root == null)
        {
		    //alert("Sorry, there is no configuration for this criteria.\nPlease choose another criteria.");
            alert("This field can only be edited in TAXI 2.0.  In TAXI 1.0, it can only be removed.");
        }
		else if(root.getAttributeNode("WINDOW").text == "0")    
			LoadCriteriaWindow();
		else
		{
			//var theURL = "search_window.htm?search_id=" + intSearchID + "&field=" + theField + "&prop_type=" + intPropType + "&search_type=" + strSearchType + "&fieldType=" + theFieldType + "&autocount=" + document.countform.AUTOCOUNT.checked
			var theURL = "search_window.htm?search_id=" + intSearchID + "&field=" + theField + "&prop_type=" + intPropType + "&search_type=" + strSearchType + "&fieldType=" + theFieldType + "&autocount=false"
			windowName = "newMessageWindow";
			openTheNewWindow(theURL,windowName,550,435);
			LoadChildWindow(windowName);
		}
	}
	else
		alert("Sorry, no search criteria available to edit.");
}


function DoDB(theAction, theField, theType, bHotsheet)
{
    
    
	HiddenDB(document.SearchCriteriaForm.PROP_TYPE.options[document.SearchCriteriaForm.PROP_TYPE.selectedIndex].value, theAction, theField, false, bHotsheet)
}


function DoRemove()
{
	if(document.searchform.CRITERIA.options.length > 0 && document.searchform.CRITERIA.selectedIndex >= 0)
	{
		if (theFields[document.searchform.CRITERIA.selectedIndex] != "")
		{
			var theField = theFields[document.searchform.CRITERIA.selectedIndex]
			
			for (var i=document.searchform.CRITERIA.selectedIndex; i < (document.searchform.CRITERIA.options.length - 1);i++)
			{
				document.searchform.CRITERIA.options[i].text = document.searchform.CRITERIA.options[i+1].text;
				theFields[i] = theFields[i+1];
			}
			document.searchform.CRITERIA.options.remove(document.searchform.CRITERIA.options.length - 1);
			document.searchform.CRITERIA.selectedIndex = document.searchform.CRITERIA.options.length - 1;
	    
			if(parseInt(theField) >= 0)
			{
			
			
				var myNodeList = rstSearchTemp.documentElement.selectSingleNode("rs:data/z:row[@VIEW_NAME = '" + theField + "']")
				if(myNodeList != null)
				{
					//If this is a feature, we'll need to remove the alias reference from strFeatJoinBuf
					var theSnippet = myNodeList.getAttributeNode('SNIPPET').text;
					
					
					var intPFValue = theSnippet.substring(theSnippet.indexOf("and (pf") + 7, theSnippet.indexOf(".group_id = "));
					var strJoinClause = " RIGHT JOIN propfeat pf" + intPFValue + " ON pf" + intPFValue + ".listing_id = detail_p"
					var intStartIndex = (strFeatJoinBuf.indexOf(strJoinClause) + strJoinClause.length)
					var intTempPropType = strFeatJoinBuf.substring(intStartIndex, strFeatJoinBuf.indexOf(".listing_id", intStartIndex));
					strJoinClause += intTempPropType + ".listing_id"
					var intStartIndex = strFeatJoinBuf.indexOf(strJoinClause);
					var intEndIndex = strFeatJoinBuf.indexOf(" RIGHT JOIN propfeat pf", (intStartIndex + strJoinClause.length));
					if(intEndIndex == -1 && (intStartIndex + strJoinClause.length) >= strFeatJoinBuf.length) //we are at the end of the string
						intEndIndex = strFeatJoinBuf.length;
					//strFeatJoinBuf = strFeatJoinBuf.substring(0, intStartIndex) + strFeatJoinBuf.substring(intEndIndex, strFeatJoinBuf.length)
				}
			}
			
			theFields[i] = "";
			theIndex--;

            
			DoDB('remove', theField, strSearchType, false)



		}
	}
	else if(document.searchform.CRITERIA.options.length == 0)
		alert("Sorry, no search criteria available to remove.");
	else
		alert("Please select the criteria you wish to remove.");
}

function DoClear()
{
	if(document.searchform.CRITERIA.options.length > 0)
	{
		for (var i=document.searchform.CRITERIA.options.length - 1; i >= 0;i--)
		{
			document.searchform.CRITERIA.options.remove(i);
			theFields[i] = "";
		}
		document.searchform.CRITERIA.selectedIndex = 0;
		theIndex = 0;
	}
	//else
	//	alert("Sorry, no search criteria available to delete.");
}

function DoSaveAs()
{
	if(document.searchform.CRITERIA.options.length > 0)
	{
		if(SAVEAS.value.length < 1)
		{
			alert("You must enter a name for this search.")
			SAVEAS.focus();
			return;
		}
		//if(SAVEAS.value.toUpperCase() == "CoBroke Listing Search")
		//{
		//	alert("You cannot save a search under this name.")
		//	SAVEAS.focus();
		//	return;
		//}
		else
		{
			//alert(strSearchType);
			if(SAVEASHOTSHEET.checked)
				strHotsheet = 'Y';
			else
				strHotsheet = 'N';
			
			
			if (SAVEAS.value.toUpperCase() == "DEFAULT")
			{
			    //alert("vffb: "+intSearchID);
				DoDB('saveas', SAVEAS.value, strSearchType, SAVEASHOTSHEET.checked);
				ClearCriteriaWindow();		
			}
			else
			{
			
			    //check the total records to see if it is more than the limit
			    DoDB('chkcount', '', '', false);
			    //alert(chktotal);
			
			
			    if ((chktotal>MAX_SEARCH))
			    {
		
				    alert("Your search exceeds the limit of " +MAX_SEARCH +" records. Please narrow down your criteria");

			    }
			    else
			    {		
				    DoDB('saveas', SAVEAS.value, strSearchType, SAVEASHOTSHEET.checked);
				    ClearCriteriaWindow();
			    }
			}
		}
	}
	else
		alert("Sorry, no search criteria available to save.");
}

function openTheNewWindow(fileName,theWindowName,theWidth,theHeight) 
{
	//windowName = theWindowName;
	//windowName = window.open(fileName,windowName,"dependent, alwaysRaised, toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=no,resizable=0,width=" + theWidth + ",height=" + theHeight)
	//windowName = openNewWindow(fileName,windowName,theWidth,theHeight,1,1)

	//center the new window
	//var ScreenWidth = window.screen.width;
	//var ScreenHeight = window.screen.height;
	//var theLeft = (ScreenWidth-theWidth)/2;
	//var theTop = (ScreenHeight-theHeight)/2;
	//windowName.moveTo(theLeft, theTop);

	DialogWindow = showModelessDialog(fileName,window,"center:Yes;status:no;help:no;dialogWidth:" +  theWidth +"px;dialogHeight:" + theHeight + "px");

	//window.name = "MainWindow";
	//windowName = window.showModalDialog(fileName,window,"center:Yes;dialogHeight:" + theHeight + "px;dialogWidth:" + theWidth + "px;status:no;resizable:no");
}

function AdditionalFieldTree()
{
	windowName = "newMessageWindow";
	openTheNewWindow("FieldTree.htm",windowName,550,435);
}

function AdditionalField(theField)
{
	OpenChild(theField.options[theField.selectedIndex].value, "standard")
}

function AdditionalFeature(theField)
{
	OpenChild(theField.options[theField.selectedIndex].value, "feature")
}

function OpenChild(theFieldName, theFieldType)
{
	var root;
	theField = theFieldName;
	strFieldType = theFieldType;
	//if(document.countform.AUTOCOUNT.checked)
	//	strAutoCount = "true";
	//else
		strAutoCount = "false";

	//alert("intPropType=" + intPropType + " theField=" + theField);
	
	
	if(strFieldType == "feature" || isaPosInt(theField))
	{
		root = rstFeatures.documentElement.selectSingleNode("rs:data/z:row[@PROP_TYPE = '" + intPropType + "'][@VIEW_NAME = '" + theField + "']");
        
		LoadCriteriaWindow();
		return;
	}
	else
	{
	
		root = rstSearchDefinitions.documentElement.selectSingleNode("rs:data/z:row[@PROP_TYPE = '" + intPropType + "'][@VIEW_NAME = '" + theField + "']")
	}
	if(theField == "")
	{
		theCriteriaWindow.innerHTML = "";
		OKCancelButtons.style.visibility="hidden";	
		document.searchform.CRITERIA.focus();		
		return;
	}
	else if(root == null){
		//alert("Sorry, there is no configuration for this criteria.\nPlease choose another criteria.");
        alert("This field can only be edited in TAXI 2.0.  In TAXI 1.0, it can only be removed.");
    }
	else if(root.getAttributeNode("WINDOW").text == "0")
		LoadCriteriaWindow();
	else
	{
		var theURL = "Blank.htm"
		windowName = "newMessageWindow";
		openTheNewWindow(theURL,windowName,550,435);
		LoadChildWindow(windowName);
	}
}

function LoadHrefWindow(theURL, theWidth, theHeight)
{
	if(theURL == "AreaList.asp")
		strAreas = getXSLAreaString("");
	windowName = "newMessageWindow";
	openTheNewWindow(theURL,windowName,theWidth,theHeight);
}

function DoAgent(myform, theField, thePrompt, theClause, addQuotes, FormType)
{
	myform.elements[myform.elements.length -1].blur;
	var theNewField;
	var theNewFieldSuff = "";
	var theString = "";
	var theSnippet = "";
	var theVal1 = "";
	var theVal2 = "";

	theString = thePrompt + " = "
	//alert('theField=' + theField + ' theClause=' + theClause);
	
	var intRef = Get_Fieldname(myform, theField);
	var intIndex = myform.elements[intRef].selectedIndex;
	if(intIndex == -1)
	{
		RemoveCriteriaItem(myform, theField);
		return;
	}
	for (var i=0; i < myform.elements[intRef].options.length; i++)
	{	
		if (myform.elements[intRef].options[i].selected)
		{
			theSnippet = theSnippet + AddQuotes(addQuotes) + myform.elements[intRef].options[i].value + AddQuotes(addQuotes) + ", ";
			theVal1 = theVal1 + myform.elements[intRef].options[i].value + ", ";
			theString = theString + myform.elements[intRef].options[i].text + ", ";
		}
	}
	if (theVal1 != "")
	{
		theVal1 = theVal1.substring(0, theVal1.length - 2);
		theString = theString.substring(0, theString.length - 2);
	}
	if(theField.indexOf('EXCL_BROKER') > -1)
	{
		theNewField = theField.substring(0, theField.length - 1);
		theNewFieldSuff = "";
	}
	if(theField.indexOf('L_AG') > -1 && theField.indexOf('_ID') > -1)
	{
		theNewField = theField.substring(0, 4);
		theNewFieldSuff = "_ID";
	}
	if (theSnippet != "")
	{
		var tempSnippet;
		tempSnippet = theSnippet.substring(0, theSnippet.length - 2)
		theSnippet = "";
		for(var iCount=1;iCount<4;iCount++)
			theSnippet += theNewField + iCount + theNewFieldSuff + " IN (" + tempSnippet + ") or ";
		theSnippet = " and (" + theSnippet.substring(0, theSnippet.length - 4) + ")";
	}
			
	//Deal with Selling Broker
	//Only see selling broker for CBRK and OPEN
	if(theField.indexOf('S_AG') > -1 && theField.indexOf('_ID') > -1)
	{
		theNewField = theField.substring(0, 4);
		theNewFieldSuff = "_ID";
		
		if(theSnippet != "")
		{
		var tempSnippet;
		tempSnippet = theSnippet.substring(0, theSnippet.length - 2)
		theSnippet = "";
		for(var iCount=1;iCount<4;iCount++)
			theSnippet += theNewField + iCount + theNewFieldSuff + " IN (" + tempSnippet + ") or ";
		theSnippet = " and ((" + theSnippet.substring(0, theSnippet.length - 4) + ") and LISTING_TYPE IN ('CBRK','OPEN'))";
		//alert(theSnippet);
		}
	}
	
	var myNodeList = rstSearchTemp.documentElement.selectSingleNode("rs:data/z:row[@VIEW_NAME = '" + theField + "']")

	if(myNodeList != null)
		updateRecord2(myNodeList, strAgentID, intPropType, strSearchType, theSnippet, theString, theVal1, theVal2, theField);
	else
		insertRecord2(rstSearchTemp, strAgentID, intPropType, strSearchType, theSnippet, theString, theVal1, theVal2, theField);


	var intRecordCount = 0; //this used to be returned by the AutoCount function above
	
	AddCriteria(theField, theString, intRecordCount, strAutoCount);
	
	//alert("windowName=" + windowName);
	/*
	if(myform != document.CriteriaForm)
		windowName.close();
	else
		theCriteriaWindow.innerHTML = "";
	*/
	
	//If user selected count while leaving the criteria window open.
	if (blnLeaveCriteria == true)
	{
		DoDB('count', '', '', false);
	}		

	//Close criteria window if user clicks OK
	if(myform == document.CriteriaForm && blnLeaveCriteria==false)
	{
		theCriteriaWindow.innerHTML = "";
		OKCancelButtons.style.visibility="hidden";
	}
	
	blnLeaveCriteria =false	

	if(theField == "AREA")
		GetAreas();	

	document.searchform.CRITERIA.focus();
}

var AppOutClause;
function AddCriteria2(myform, theField, thePrompt, theCount, theClause, addQuotes, limitHigh, FormType)
{


    AppOutClause ='';
    if(theCriteriaWindow.innerHTML == "") //for some reason, we end up coming through this code twice when the user presses the enter key. So, if the criteria window is already blank, just return.
		return;
	myform.elements[myform.elements.length -1].blur;
	var theString = "";
	var theSnippet = "";
	var theVal1 = "";
	var theVal2 = "";

	theString = thePrompt + " = "
	//alert('theField=' + theField + ' theClause=' + theClause + ' theCount=' + theCount);
	

	
	
	if ((theField == "STATUS" || theField == "LISTING_TYPE") && theClause != "SpecialIN")
	{
	
		var intRef = Get_Fieldname(myform, theField)
	
		theString = "";
		theSnippet = " and (";
		theVal1 = "";
		theVal2 = "";
		
		
		
		for (var i=0;i<=(theCount * 4);i=i+4)
		{
			var doDate = false;
			
			
			
			if (myform.elements[intRef + i].checked)
			{
			
			

			
				if (test_status(myform.elements[intRef + i].value))
				{
					theString = theString + " " + thePrompt + " = " + myform.elements[intRef + i].value + " and "
					theSnippet = theSnippet + " (" + theField + " = '" + myform.elements[intRef + i].value + "' and "
					theVal1 = theVal1 + myform.elements[intRef + i].value + ", "
			
					if (myform.elements[intRef + i + 2].value != "" || myform.elements[intRef + i + 3].value != "")
					{
						if (myform.elements[intRef + i + 2].value != "" && myform.elements[intRef + i + 3].value != "")
						{
							theString = theString + theDateFields[(i/4)] + " Between " + myform.elements[intRef + i + 2].value + " and " + myform.elements[intRef + i + 3].value + " or"
							theSnippet = theSnippet + theDateFields[(i/4)] + " Between '" + myform.elements[intRef + i + 2].value + "' and '" + myform.elements[intRef + i + 3].value + "') or"
							theVal2 = theVal2 + ", " + myform.elements[intRef + i + 2].value + ", " + myform.elements[intRef + i + 3].value + ", "
						}
						else if (myform.elements[intRef + i + 2].value != "")
						{
							theString = theString + theDateFields[(i/4)] + " GTE " + myform.elements[intRef + i + 2].value + " or"
							theSnippet = theSnippet + theDateFields[(i/4)] + " >= '" + myform.elements[intRef + i + 2].value + "') or"
							theVal2 = theVal2 + ", " + myform.elements[intRef + i + 2].value + ", , "
						}
						else
						{
							theString = theString + theDateFields[(i/4)] + " LTE " + myform.elements[intRef + i + 3].value + " or"
							theSnippet = theSnippet + theDateFields[(i/4)] + " <= '" + myform.elements[intRef + i + 3].value + "') or"
							theVal2 = theVal2 + ", , " + myform.elements[intRef + i + 3].value + ", "
						}
						doDate = true;
					}
					else if (myform.elements[intRef + i + 1].value != "")
					{
						theString = theString + theDateFields[(i/4)] + " GTE " + myform.elements[intRef + i + 1].value + " or"
						theSnippet = theSnippet + theDateFields[(i/4)] + " >= '" + myform.elements[intRef + i + 1].value + "') or"
						theVal2 = theVal2 + myform.elements[intRef + i + 1].value + ", , , "
						doDate = true;
					}
					if (!doDate)
					{
						theString = theString.substring(0, theString.length - 4) + " or";
						theSnippet = theSnippet.substring(0, theSnippet.length - 5) + ") or";
						theVal2 = theVal2 + ", , , "
					}
				}
			}
			else
				theVal2 = theVal2 + ", , , "
		}
		if (theSnippet == " and (")
		{
			ClearCriteriaWindow()
			RemoveCriteriaItem(myform, theField);
			return;
		}
		theString = theString.substring(0, theString.length - 2);
		theSnippet = theSnippet.substring(0, theSnippet.length - 3) + ")";
		theVal1 = theVal1.substring(0, theVal1.length - 2);
		theVal2 = theVal2.substring(0, theVal2.length - 2);
	}
	else
	{
	
	
		if ((theField == "COORDINATE_X" || theField == "COORDINATE_Y") && theClause == "SpecialBETWEEN")
		{
		
            //getCoords("X");
            //getCoords("Y");
            
            //alert(PointXs);

			//alert('Building Grid Criteria');
			var intRef = Get_Fieldname(myform, "COORDINATE_Y"); // get the first control
			
			theString = "";
			theSnippet = " and (";
			theVal1 = "";
			theVal2 = "";
			
			if((myform.elements[intRef].selectedIndex != 0 || myform.elements[intRef+1].selectedIndex != 0 || myform.elements[intRef+2].selectedIndex != 0 || myform.elements[intRef+3].selectedIndex != 0) && (!usemapgrid) )
			{
				for(var i=0;i<4;i++)
				{
					theVal1 = theVal1 + myform.elements[intRef + i].options[myform.elements[intRef + i].selectedIndex].value + ","
				}
				
				theString = theString + " " + thePrompt + " = ";
				theSnippet = theSnippet + " (";
				
				//Do the North/South first
				if(myform.elements[intRef].selectedIndex != 0 && myform.elements[intRef+2].selectedIndex != 0)
				{
					theString = theString + "Streets Between " + myform.elements[intRef].options[myform.elements[intRef].selectedIndex].text + " and " + myform.elements[intRef+2].options[myform.elements[intRef+2].selectedIndex].text + " AND "
					theSnippet = theSnippet + "COORDINATE_Y Between " + myform.elements[intRef+2].options[myform.elements[intRef+2].selectedIndex].value + " and " + myform.elements[intRef].options[myform.elements[intRef].selectedIndex].value + ") and ("
				}
				if(myform.elements[intRef].selectedIndex == 0 && myform.elements[intRef+2].selectedIndex != 0)
				{
					theString = theString + "Streets Above " + myform.elements[intRef+2].options[myform.elements[intRef+2].selectedIndex].text + " AND "
					theSnippet = theSnippet + "COORDINATE_Y >= " + myform.elements[intRef+2].options[myform.elements[intRef+2].selectedIndex].value + ") and ("
				}
				if(myform.elements[intRef].selectedIndex != 0 && myform.elements[intRef+2].selectedIndex == 0)
				{
					theString = theString + "Streets Below " + myform.elements[intRef].options[myform.elements[intRef].selectedIndex].text + " AND "
					theSnippet = theSnippet + "COORDINATE_Y <= " + myform.elements[intRef].options[myform.elements[intRef].selectedIndex].value + " and COORDINATE_Y >1  ) and ("
				}

				// Now do the East/West
				if(myform.elements[intRef+1].selectedIndex != 0 && myform.elements[intRef+3].selectedIndex != 0)
				{
					theString = theString + "Avenues Between " + myform.elements[intRef+1].options[myform.elements[intRef+1].selectedIndex].text + " and " + myform.elements[intRef+3].options[myform.elements[intRef+3].selectedIndex].text + " AND "
					theSnippet = theSnippet + "COORDINATE_X Between " + myform.elements[intRef+3].options[myform.elements[intRef+3].selectedIndex].value + " and " + myform.elements[intRef+1].options[myform.elements[intRef+1].selectedIndex].value + ") and ("
				}
				if(myform.elements[intRef+1].selectedIndex == 0 && myform.elements[intRef+3].selectedIndex != 0)
				{
					theString = theString + "Avenues East of " + myform.elements[intRef+3].options[myform.elements[intRef+3].selectedIndex].text + " AND "
					theSnippet = theSnippet + "COORDINATE_X >= " + myform.elements[intRef+3].options[myform.elements[intRef+3].selectedIndex].value + ") and ("
				}
				if(myform.elements[intRef+1].selectedIndex != 0 && myform.elements[intRef+3].selectedIndex == 0)
				{
					theString = theString + "Avenues West of " + myform.elements[intRef+1].options[myform.elements[intRef+1].selectedIndex].text + " AND "
					theSnippet = theSnippet + "COORDINATE_X <= " + myform.elements[intRef+1].options[myform.elements[intRef+1].selectedIndex].value + ") and ("
				}

			}
			//else if (ShowMap && (PointXs!="") && (theString == ""))
			else if (ShowMap && (PointXs!="") && usemapgrid)
			{

		
			    theString = theString + " " + thePrompt + " = ";
				//theSnippet = theSnippet + " (";
			    if (document.getElementById("MapTitle").value!="")
			        theString = theString + document.getElementById("MapTitle").value + " AND " ;			    
			    else
			        theString = theString + "Inside Map Polygon AND " ;
			    
			    var ArrPointYs=PointYs.split(",");
			  
			  	if (ArrPointYs.length > 0)  
			        theSnippet = theSnippet + "/*polyon*/        ";  	
			  	
			    /*
			    if (ArrPointYs.length > 0)
			        theSnippet = theSnippet + "latitude >= " + ArrPointYs[0] + ") and ("
			        
			    if (ArrPointYs.length> 1)    
			        theSnippet = theSnippet + "latitude <= " + ArrPointYs[1] + ") and ("
			    
			    var ArrPointXs=PointXs.split(",");
			    if (ArrPointXs.length > 0)   
			    theSnippet = theSnippet + "longitude >= " + ArrPointXs[0]+ ") and ("
			    
			    if (ArrPointXs.length > 1)   
			    theSnippet = theSnippet + "longitude <= " + ArrPointXs[1] + ") and ("
			    */
			}
			else
			{
			
			
				ClearCriteriaWindow()
				RemoveCriteriaItem(myform, theField);
				return;
			}
			
			theVal2 = theVal2 + ", , , , "
			
			theString = theString.substring(0, theString.length - 4);
			theSnippet = theSnippet.substring(0, theSnippet.length - 5) + ")";
			theVal1 = theVal1.substring(0, theVal1.length - 1);
			theVal2 = theVal2.substring(0, theVal2.length - 2);
			
			//alert('theVal1=' + theVal1);
			//alert('theSnippet=' + theSnippet);
		}
		else
		{
		
		
			switch(theClause)
			{
			case "=":
					if(myform.elements[Get_Fieldname(myform, theField)].checked)
					{
						//theString = thePrompt + "=" + myform.elements[Get_Fieldname(myform, theField)].value;
						theString = thePrompt;
						theSnippet = " and (" + theField + " = '" + myform.elements[Get_Fieldname(myform, theField)].value + "') ";
						theVal1 = myform.elements[Get_Fieldname(myform, theField)].value;
						theVal2 = '';
					}
					else
					{
						ClearCriteriaWindow()
						RemoveCriteriaItem(myform, theField);
						return;
					}
			break;
			case "YESNONA":
				var elemRef = Get_Fieldname(myform, theField);
				for (var i=0;i<theCount;i++)
				{
					if(myform.elements[elemRef + i].checked)
					{
						if(myform.elements[elemRef + i].value == "")
						{
							ClearCriteriaWindow()
							RemoveCriteriaItem(myform, theField);
							return;
						} 
						else
						{
							theString = thePrompt + " = " + myform.elements[elemRef + i].value;
							theSnippet = " and (" + theField + " = '" + myform.elements[elemRef + i].value + "') ";
							theVal1 = myform.elements[elemRef + i].value;
							theVal2 = '';
							break;
						}
					}
				}
			break;
			case "LIKE":
					if(myform.elements[Get_Fieldname(myform, theField)].value.length > 0)
					{
						theString = thePrompt + " Begins With " + myform.elements[Get_Fieldname(myform, theField)].value;
						theSnippet = " and (" + theField + " LIKE '" + myform.elements[Get_Fieldname(myform, theField)].value + "%') ";
						theVal1 = myform.elements[Get_Fieldname(myform, theField)].value;
						theVal2 = '';
					}
					else
					{
						/*
						if(myform != document.CriteriaForm)
							windowName.close();
						else
							theCriteriaWindow.innerHTML = "";
						*/
						if(myform == document.CriteriaForm)
						//	theCriteriaWindow.innerHTML = "";
						RemoveCriteriaItem(myform, theField);
						//return;
					}
			break;
case "BETWEEN":
				
				if(myform.elements[Get_Fieldname(myform, theField)].value.length == 0 && myform.elements[Get_Fieldname(myform, theField) + 1].value.length == 0)
				{
					RemoveCriteriaItem(myform, theField);
					return;
				}
				if(FormType == '5') // Date Field
				{
					// Do start date
					if(myform.elements[Get_Fieldname(myform, theField)].value.length > 0)
					{
						theString = thePrompt + " = " + myform.elements[Get_Fieldname(myform, theField)].value + " to ";
						/*
					    if(theField == 'DATE_AVAIL' && (myform.elements[Get_Fieldname(myform, theField) + 4].value.length > 0)) // no limit in start date if 'end date' is presented for 'DATE_AVAIL'
					    {
						    theSnippet = " and (" + theField + " between '01/01/1990' and ";
						}
						else
                        */
						    theSnippet = " and (" + theField + " between " + AddQuotes(addQuotes) + myform.elements[Get_Fieldname(myform, theField)].value + AddQuotes(addQuotes) + " and ";
						
						
						theVal1 = myform.elements[Get_Fieldname(myform, theField)].value;
					}
					else
					{
						if(addQuotes) //must be a date field
							theString = thePrompt + " = 1/1/1990 to ";
						else
							theString = thePrompt + " = 0 to ";
										
						theSnippet = " and (" + theField + " between 0 and ";
						theVal1 = 0;
					}
					
					if (theField=="BUDGET")
						theString = "Monthly Budget = 0 to ";
				
					// Do end date
					if(myform.elements[Get_Fieldname(myform, theField) + 4].value.length == 0)
					{
						if(limitHigh == "")
						{
							if(addQuotes) //must be a date field
							{
								var thisDate = new Date();
								limitHigh = ((thisDate.getMonth() + 1) + "/" + thisDate.getDate() + "/" + thisDate.getYear())
							}
							else
								limitHigh = "99";
						}
						theString += limitHigh;
						theSnippet = theSnippet + AddQuotes(addQuotes) + limitHigh + AddQuotes(addQuotes) + ")";
						theVal2 = limitHigh;
					}
					else
					{
						theString += myform.elements[Get_Fieldname(myform, theField) + 4].value;
						theSnippet = theSnippet + AddQuotes(addQuotes) + myform.elements[Get_Fieldname(myform, theField) + 4].value + AddQuotes(addQuotes) + ")";
						theVal2 = myform.elements[Get_Fieldname(myform, theField) + 4].value;
					}
					
					
								                    //include null value for DATE_AVAIL
					if(theField == 'DATE_AVAIL')
					{
					    var intRefx2 = Get_Fieldname(myform, "DATE_AVAIL_NULL")
						if (myform.elements[intRefx2].checked)
						{
						    theString +=" or " + thePrompt +" = ''";
						    theSnippet = theSnippet.replace(' and (',' and ((') + " or (isnull(DATE_AVAIL,'') = '' ))";
							
							ChkDATE_AVAIL_NULL="Y"; //set it in global variable
						}
						else
							ChkDATE_AVAIL_NULL="";
					}
					
				
				}
				else
				{
					for (var i=0;i<theCount;i++)
					{
						var CurValue = myform.elements[Get_Fieldname(myform, theField) + i].value;
						CurValue =Trim(CurValue);
						
						if ((i + 1) != theCount)
						{
							if(CurValue.length > 0)
							{
								theVal1 = CurValue;
								if(theField == 'PRICE_CURRENT' && (intPropType == 1 || intPropType == 3 ||intPropType == 5 ))
									CurValue += '000';
									
								if (theField == 'BUDGET')
								{
								    DoBudget ="Y";
								    var Period=myform.elements[Get_Fieldname(myform, "DpMortYr")].options[myform.elements[Get_Fieldname(myform, "DpMortYr")].selectedIndex].value *12;
								    var DwnPmt=myform.elements[Get_Fieldname(myform, "txtDnPmt")].value;
								    var mRate=myform.elements[Get_Fieldname(myform, "txtRate")].value.replace("%","");
								    if (mRate >= 1) 
								        { mRate /= 100; }
		                                mRate /= 12;
								    
								    theString = "Monthly Budget= " + CurValue + " to ";
								    CurValue = MonthlyToPrice(CurValue,mRate,Period,DwnPmt);
								    
								}	
								else	
                            		theString = thePrompt + " = " + CurValue + " to ";
                            		
								theSnippet = " and (" + theField + " between " + AddQuotes(addQuotes) + CurValue + AddQuotes(addQuotes) + " and ";
								
								
								
								
							}
							else
							{
								if(addQuotes) //must be a date field
								{
								    if (theField=="BUDGET" || theField=="PRICE_PER_SQFT")
									    theString = thePrompt + " = 0 to ";								    
								    else
									    theString = thePrompt + " = 1/1/1990 to ";
								}
								else
									theString = thePrompt + " = 0 to ";
								theSnippet = " and (" + theField + " between 0 and ";
								theVal1 = 0;
							}
							
						    //if (theField=="BUDGET")
						     //   theString = "Monthly = h0 to ";
							
						}
						else
						{
							if(CurValue.length == 0)
							{
								if(limitHigh == "")
								{
									if(addQuotes) //must be a date field
									{
										var thisDate = new Date();
										limitHigh = ((thisDate.getMonth() + 1) + "/" + thisDate.getDate() + "/" + thisDate.getYear())
									}
									else
										limitHigh = "99";
								}
								theVal2 = limitHigh;
								if(theField == 'PRICE_CURRENT' && (intPropType == 1 || intPropType == 3 || intPropType == 5))
									limitHigh += '000';
									
								theString += limitHigh;	
								
								if (theField == 'BUDGET')
								{
								    var Period=myform.elements[Get_Fieldname(myform, "DpMortYr")].options[myform.elements[Get_Fieldname(myform, "DpMortYr")].selectedIndex].value *12;
								    var DwnPmt=myform.elements[Get_Fieldname(myform, "txtDnPmt")].value;
								    var mRate=myform.elements[Get_Fieldname(myform, "txtRate")].value.replace("%","");
								    if (mRate >= 1) 
								        { mRate /= 100; }
		                                mRate /= 12;
								    
								    
								    limitHigh = MonthlyToPrice(limitHigh,mRate,Period,DwnPmt);
								}	
									
									
								
								//theSnippet = theSnippet + AddQuotes(addQuotes) + limitHigh + AddQuotes(addQuotes) + ")";
								
								theSnippet = theSnippet + AddQuotes(addQuotes) + limitHigh + AddQuotes(addQuotes);							
								
								//include null value for SQFT_INT
								if(theField == 'SQFT_INT')
								{
									var intRefx = Get_Fieldname(myform, "SQFT_NULL")
									if (myform.elements[intRefx].checked)
									{
										theSnippet +=" or (isnull(SQFT_INT,'') = '') ";
										theString +=" or " + thePrompt +" = ''";
										ChkSQFT_NULL="Y"; //set it in global variable
									}
									else
										ChkSQFT_NULL="";
								}
								
								
								
								theSnippet +=")";
								
							}
							else
							{
								theVal2 = CurValue;
								if(theField == 'PRICE_CURRENT' && (intPropType == 1 || intPropType == 3 || intPropType == 5))
									CurValue += '000';
									
								
								theString += CurValue;
								if (theField == 'BUDGET')
								{
								    var Period=myform.elements[Get_Fieldname(myform, "DpMortYr")].options[myform.elements[Get_Fieldname(myform, "DpMortYr")].selectedIndex].value *12;
								    var DwnPmt=myform.elements[Get_Fieldname(myform, "txtDnPmt")].value;
								    var mRate=myform.elements[Get_Fieldname(myform, "txtRate")].value.replace("%","");
								    if (mRate >= 1) 
								        { mRate /= 100; }
		                                mRate /= 12;
								    

								    
								    
								    CurValue = MonthlyToPrice(CurValue,mRate,Period,DwnPmt);
								}	
								
								
								
								
								//theSnippet = theSnippet + AddQuotes(addQuotes) + CurValue + AddQuotes(addQuotes) + ")";
								
								theSnippet = theSnippet + AddQuotes(addQuotes) + CurValue + AddQuotes(addQuotes) ;
								//include null value for SQFT_INT
								if(theField == 'SQFT_INT')
								{
									var intRefx = Get_Fieldname(myform, "SQFT_NULL")
									if (myform.elements[intRefx].checked)
									{
										theSnippet +=" or (isnull(SQFT_INT,'') = '') ";
										theString +=" or " + thePrompt +" = ''";
										ChkSQFT_NULL="Y"; //set it in global variable
									}
									else
										ChkSQFT_NULL="";
								}
								
								
								theSnippet +=")";		
								
							}
						}
				
					} // end for
				} // end if
				
				if(theField == 'BUDGET')
				{
				    DoBudget="Y";
				    var s=theSnippet;
				    var bfield="PRICE_CURRENT";
                    if (myform.elements[Get_Fieldname(myform, "ChkMaint")].checked)
				    {
				        if (intPropType == 1 || intPropType == 2)
				            bfield="(PRICE_CURRENT + (Isnull(MAINT_CC,0)+ Isnull(RE_TAX_MONTHLY,0))*12*" + myform.elements[Get_Fieldname(myform, "DpMortYr")].options[myform.elements[Get_Fieldname(myform, "DpMortYr")].selectedIndex].value +" ) " ;
				        else
				            bfield="(PRICE_CURRENT + (Isnull(EXPENSE_RETAX,0))*" + myform.elements[Get_Fieldname(myform, "DpMortYr")].options[myform.elements[Get_Fieldname(myform, "DpMortYr")].selectedIndex].value +" ) " ;
				       
				       
				        ChkMaint_Y		="Y";
				    }
				    else
				    {
				        ChkMaint_Y		="";

				    }   
				        
                    MtxtDnPmt=myform.elements[Get_Fieldname(myform, "txtDnPmt")].value;
                    MtxtRate=myform.elements[Get_Fieldname(myform, "txtRate")].value;
				    MDpMortYr=myform.elements[Get_Fieldname(myform, "DpMortYr")].options[myform.elements[Get_Fieldname(myform, "DpMortYr")].selectedIndex].value;
	
	
					var Period=myform.elements[Get_Fieldname(myform, "DpMortYr")].options[myform.elements[Get_Fieldname(myform, "DpMortYr")].selectedIndex].value *12;
					var DwnPmt=myform.elements[Get_Fieldname(myform, "txtDnPmt")].value;
					var mRate=myform.elements[Get_Fieldname(myform, "txtRate")].value.replace("%","");
					if (mRate >= 1) 
						{ mRate /= 100; }
		                mRate /= 12;	
	
	
				    //store budget data
				    var strPOSTURL = "/include/StoreBudget.aspx?userid="+ strAgentID +"&dmt=" + DwnPmt +"&rate=" + mRate +"&period=" + Period +"&MaintIncluded=" + ChkMaint_Y ;
                    //alert(strPOSTURL);
	                var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	                xmlhttp.Open("GET", strPOSTURL, true);
	                xmlhttp.send(null)
				    
				    
				    
				    s=s.replace("BUDGET",bfield);
				    theSnippet=s;
				}
				
				if(theField == 'PRICE_PER_SQFT')
				{
				    var PValue = document.SearchCriteriaForm.PROP_TYPE.options[document.SearchCriteriaForm.PROP_TYPE.selectedIndex].value;
					
				    var s=theSnippet;
				    var bfield='';
/*
				    if (PValue==1 || PValue==5)
				        bfield="PRICE_CURRENT/ISNULL(NULLIF(SQFT_INT,0),1)";
				    else if  (PValue==2 || PValue==6)
				        bfield="PRICE_CURRENT*12/ISNULL(NULLIF(SQFT_INT,0),1)";
				    else if  (PValue==3) 
				  		bfield="PRICE_CURRENT/ISNULL(NULLIF(BLDG_SQFT,0),1)";  
				    else if (PValue==4)
				        bfield="PRICE_CURRENT*12/ISNULL(NULLIF(BLDG_SQFT,0),1)";
				    else
				        bfield="PRICE_CURRENT/ISNULL(NULLIF(SQFT_INT,0),1)";
*/

				    if (PValue==1 || PValue==5)
				        bfield="PRICE_CURRENT/SQFT_INT";
				    else if  (PValue==2 || PValue==6)
				        bfield="PRICE_CURRENT*12/SQFT_INT";
				    else if  (PValue==3) 
				  		bfield="PRICE_CURRENT/ISNULL(NULLIF(BLDG_SQFT,0),1)";  
				    else if (PValue==4)
				        bfield="PRICE_CURRENT*12/ISNULL(NULLIF(BLDG_SQFT,0),1)";
				    else
				        bfield="PRICE_CURRENT/SQFT_INT";
				    
				    //s=s.replace("PRICE_PER_SQFT",bfield) + " and (SQFT_INT >0) ";
				    s=s.replace("PRICE_PER_SQFT",bfield) + " ";
				    
				    theSnippet=s;
				}				
			
			break;
			case "IN":
			
			    
				var intRef = Get_Fieldname(myform, theField);
				var intIndex = myform.elements[intRef].selectedIndex;
				if(intIndex == -1)
				{
					RemoveCriteriaItem(myform, theField);
					return;
				}
				for (var i=0; i < myform.elements[intRef].options.length; i++)
				{	
					if (myform.elements[intRef].options[i].selected)
					{
						theSnippet = theSnippet + AddQuotes(addQuotes) + myform.elements[intRef].options[i].value + AddQuotes(addQuotes) + ", ";
						theVal1 = theVal1 + myform.elements[intRef].options[i].value + ", ";
						theString = theString + myform.elements[intRef].options[i].text + ", ";
					}
				}
				if (theVal1 != "")
				{
					theVal1 = theVal1.substring(0, theVal1.length - 2);
					theString = theString.substring(0, theString.length - 2);
				}
				if (theSnippet != "")
					theSnippet = " and (" + theField + " IN (" + theSnippet.substring(0, theSnippet.length - 2) + "))";
			break;
			case "COMMASEP":
					
				var intRefx;
					
					
				//keyword
				if (theField=="REMARKS_GENERAL_BLDG")
				{
					intRefx = Get_Fieldname(myform, "KW_REMARKS_GENERAL")
					if (myform.elements[intRefx].checked)
					{
						chkKW_REMARKS_GENERAL="Y"; //set it in global variable
					}
					else
						chkKW_REMARKS_GENERAL="";
										
										
					intRefx = Get_Fieldname(myform, "KW_REMARKS_GENERAL_BLDG")
					if (myform.elements[intRefx].checked)
					{
						chkKW_REMARKS_GENERAL_BLDG="Y"; //set it in global variable
					}
					else
						chkKW_REMARKS_GENERAL_BLDG="";			
										
										
					intRefx = Get_Fieldname(myform, "KW_REMARKS_BD_REQ")
					if (myform.elements[intRefx].checked)
					{
						chkKW_REMARKS_BD_REQ="Y"; //set it in global variable
					}
					else
						chkKW_REMARKS_BD_REQ="";			
					//keyword end
				}
			
				intRef = Get_Fieldname(myform, theField);

				if(myform.elements[intRef].value.length == 0)
				{
					RemoveCriteriaItem(myform, theField);
					return;
				}
				var commaList = myform.elements[intRef].value.split(",");
				if (addQuotes) //then do multiple LIKE clauses
				{
				
					intRef = Get_Fieldname(myform, "TYPE");
					for(i=intRef;i<intRef + 3;i++)
					{
						if(myform.elements[i].checked)
							theVal2 = myform.elements[i].value;
					}
					for (var i=0; i < commaList.length; i++)
					{	
						if(Trim(commaList[i]) != "")
						{
							switch (theVal2)
							{
							case "0":
								theSnippet = theSnippet + theField + " LIKE " + AddQuotes(addQuotes) + Trim(commaList[i]) + "%" + AddQuotes(addQuotes) + " OR ";
							break;
							case "1":
								theSnippet = theSnippet + theField + " LIKE " + AddQuotes(addQuotes) + "%" + Trim(commaList[i]) + "%" + AddQuotes(addQuotes) + " OR ";
							break;
							case "2":
								theSnippet = theSnippet + theField + " LIKE " + AddQuotes(addQuotes) + "%" + Trim(commaList[i]) + AddQuotes(addQuotes) + " OR ";
							break;
							default:
								theSnippet = theSnippet + theField + " LIKE " + AddQuotes(addQuotes) + "%" + Trim(commaList[i]) + "%" + AddQuotes(addQuotes) + " OR ";
							}
							theVal1 = theVal1 + Trim(commaList[i]) + ", ";
							theString = theString + Trim(commaList[i]) + " or ";
						}
					}
					if (theVal1 != "")
					{
						theVal1 = theVal1.substring(0, theVal1.length - 2);
						theString = theString.substring(0, theString.length - 4);
					}
					if (theSnippet != "")
					{
						var strfield=theSnippet.substring(0, theSnippet.length - 4);
						
						
						//keyword srch
						if (strfield.indexOf('REMARKS_GENERAL_BLDG') > -1)
						{
							var strREMARKS_GENERAL="",strREMARKS_GENERAL_BLDG="",strREMARKS_BD_REQ="";
							
							var strDefaultfield=strfield;
							
							
							if (chkKW_REMARKS_GENERAL=="Y")
								strREMARKS_GENERAL = strfield.replace("REMARKS_GENERAL_BLDG", "REMARKS_GENERAL") + " or ";
								
							if (chkKW_REMARKS_GENERAL_BLDG=="Y")
								strREMARKS_GENERAL_BLDG = strfield + " or ";
								
							if (chkKW_REMARKS_BD_REQ=="Y")
								strREMARKS_BD_REQ = strfield.replace("REMARKS_GENERAL_BLDG", "REMARKS_BD_REQ") + " or ";								
								
							strfield=strREMARKS_GENERAL+ strREMARKS_GENERAL_BLDG + strREMARKS_BD_REQ;
							
							if (strfield!="")
								strfield=strfield.substring(0, strfield.length - 4);
							else
								strfield=strDefaultfield;	
								
						}
						//keyword srch end
					
						theSnippet = " and (" + strfield + ")";
					}	
					
						//alert(theSnippet);
				}
				else //just do an IN clause
				{
				    
					for (var i=0; i < commaList.length; i++)
					{	
						if(Trim(commaList[i]) != "")
						{
							theSnippet = theSnippet + AddQuotes(addQuotes) + Trim(commaList[i]) + AddQuotes(addQuotes) + ", ";
							theVal1 = theVal1 + Trim(commaList[i]) + ", ";
							theString = theString + Trim(commaList[i]) + " or ";
						}
					}
					if (theVal1 != "")
					{
						theVal1 = theVal1.substring(0, theVal1.length - 2);
						theString = theString.substring(0, theString.length - 4);
					}
					if (theSnippet != "")
						theSnippet = " and (" + theField + " IN (" + theSnippet.substring(0, theSnippet.length - 2) + "))";
				}
			break;
			case "SpecialIN":
					if (theField == "STATUS")
					{
					
			
			            
						//myform.elements[0].checked = false
						ChkStatusesAll()
						
						if(!ChkStatuses()) //the user has selected nothing
						{
						
						
						    if(!myform.chk_EXPR.checked)
					    	{
						   
						
							ClearCriteriaWindow()
							RemoveCriteriaItem(myform, theField);
							return; 
						    
						    }
						 
						
						}
						
					}
					if (theField == "LISTING_TYPE")
					{
						//myform.elements[0].checked = false
						ChkListingTypesAll()
						
						if(!ChkListTypes()) //the user has selects nothing
						{
							ClearCriteriaWindow()
							RemoveCriteriaItem(myform, theField);
							return;
						}
						
					}
					var intRef = Get_Fieldname(myform, theField);
					
					
		
					
					if (theField == "NEIGHBORHOOD")
					{
						if(myform.elements[intRef].options.length == 0 || myform.elements[intRef].options[0].value == '')
						{
						    
							RemoveCriteriaItem(myform, theField);
							return;
						}
						var arraySpecial = new Array();
						for(var x=0;x<myform.elements[intRef].options.length;x++)
							arraySpecial[x] = myform.elements[intRef].options[x].value;
					}
					else
					{
					  
					  
						//var intIndex = myform.elements[intRef].selectedIndex;
						if(myform.elements[intRef].value.length == 0)
						{
						
						
						
							RemoveCriteriaItem(myform, theField);
							return;
						}
						
						
						
						
						var arraySpecial = myform.elements[intRef].value.split(",");
						
					
						if(theField == 'STATUS'){
						    if(myform.chk_EXPR.checked)
					    	{
						   
						    arraySpecial.push('EXPR');
						    
						    }
						 }
					}
					
					//alert(arraySpecial);
					
					for (var i=0; i < arraySpecial.length; i++)
					{	
					  
					       
					    
						if ((Trim(arraySpecial[i]) != "" && theField == "STATUS"))
						{
						   
						   //TEST EXPR 
						   //alert(myform.chk_EXPR.checked);
						   //alert('EXPR:'+test_status('EXPR'));
						   //alert(arraySpecial[i]);
					
					
					var PValue = document.SearchCriteriaForm.PROP_TYPE.options[document.SearchCriteriaForm.PROP_TYPE.selectedIndex].value;
					
					
					    if(PValue == 1) 
					    {
						
						if(test_status(Trim(arraySpecial[i])) && Trim(arraySpecial[i]) != "Y" )
							{
							
							    
								theSnippet = theSnippet + AddQuotes(addQuotes) + Trim(arraySpecial[i]) + AddQuotes(addQuotes) + ", ";
								theVal1 = theVal1 + Trim(arraySpecial[i]) + ", ";
								
							    //alert(arraySpecial[i]);
					        }
						
						}   
						else
						{
						   if(test_status(Trim(arraySpecial[i])) && Trim(arraySpecial[i]) != "Y" )
							{
							
							    if(theVal1.indexOf('EXPR') == -1) {
								theSnippet = theSnippet + AddQuotes(addQuotes) + Trim(arraySpecial[i]) + AddQuotes(addQuotes) + ", ";
								theVal1 = theVal1 + Trim(arraySpecial[i]) + ", ";
								}
							    //alert(arraySpecial[i]);
					        }
					     }  
					   
					   //alert(PValue);
					   
					    if(PValue == 2) 
					    {
					       if(myform.ckAppOut.checked) {					   
					          AppOutClause = "";
					            RemoveCriteriaItem(myform, 'App_Out');
					    
					        }
					       else{
					           
					           AppOutClause = " and (isnull(App_Out,'') <> 'Y')";
					        }
					       
					     }  
						}
						
						else
						{
							if (Trim(arraySpecial[i]) != "" && theField == "LISTING_TYPE")
							{
								theSnippet = theSnippet + AddQuotes(addQuotes) + Trim(arraySpecial[i]) + AddQuotes(addQuotes) + ", ";
								theVal1 = theVal1 + Trim(arraySpecial[i]) + ", ";
							}
							else
							{
								theSnippet = theSnippet + AddQuotes(addQuotes) + Trim(arraySpecial[i]) + AddQuotes(addQuotes) + ", ";
								theVal1 = theVal1 + Trim(arraySpecial[i]) + ", ";
							}
						}
					}
					if (theVal1 != "")
					{
						theVal1 = theVal1.substring(0, theVal1.length - 2);
						theString = theString + theVal1;
					}
					//alert(theSnippet.length);
					if (theSnippet != "")
						theSnippet = " and (" + theField + " IN (" + theSnippet.substring(0, theSnippet.length - 2) + "))"  ;
					else
					{
 						ClearCriteriaWindow();
						RemoveCriteriaItem(myform, theField);
						return;
					}

			}
		}
	} //end if theField == STATUS

	var myNodeList = rstSearchTemp.documentElement.selectSingleNode("rs:data/z:row[@VIEW_NAME = '" + theField + "' && @AGENT_ID = '" + strAgentID + "']");
	//var myNodeList = rstSearchTemp.documentElement.selectSingleNode("rs:data/z:row[@VIEW_NAME = '" + theField + "']");

	//alert(theSnippet);
	//alert(theString);
	if(myNodeList != null)
	{
		//alert(myNodeList.xml);
		updateRecord2(myNodeList, strAgentID, intPropType, strSearchType, theSnippet, theString, theVal1, theVal2, theField);		
	}
	else
	{
	
	
	//alert('insert crit');
		insertRecord2(rstSearchTemp, strAgentID, intPropType, strSearchType, theSnippet, theString, theVal1, theVal2, theField);
		
	
	}
	//alert(rstSearchTemp.xml);
	

/*
//alert("submitting");
	var strPOSTURL = "SearchDB.asp";
    var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    xmlhttp.Open("POST", strPOSTURL, false);
    
//alert(rstSearchTemp.xml);    
    

	var temproot = rstSearchTemp.documentElement
	
//alert("temproot.childNodes.length=" + temproot.childNodes.length);
	if(temproot.childNodes.length == 2)
	{
		var newNode = rstSearchTemp.createNode (1, "FORM_ELEMENTS", "")
		temproot.appendChild(newNode)
		newNode = rstSearchTemp.createNode(2, "PROP_TYPE", "")
		temproot.childNodes.item(2).attributes.setNamedItem (newNode)
		newNode = rstSearchTemp.createNode(2, "AUTOCOUNT", "")
		temproot.childNodes.item(2).attributes.setNamedItem (newNode)
		newNode = rstSearchTemp.createNode(2, "RECORDCOUNT", "")
		temproot.childNodes.item(2).attributes.setNamedItem (newNode)
		temproot.childNodes.item(2).setAttribute("PROP_TYPE", intPropType);
		temproot.childNodes.item(2).setAttribute("AUTOCOUNT", strAutoCount);
		temproot.childNodes.item(2).setAttribute("RECORDCOUNT", "");
	}

    xmlhttp.Send(rstSearchTemp.xml);
	xmlhttp = xmlhttp.responseXML
//alert("Round tripped XML document:\n\n" + xmlhttp.xml);	
//alert("Autocount=" + xmlhttp.documentElement.childNodes.item(2).getAttributeNode("RECORDCOUNT").text)
	var intRecordCount = xmlhttp.documentElement.childNodes.item(2).getAttributeNode("RECORDCOUNT").text
	var oldChild = rstSearchTemp.documentElement.removeChild(rstSearchTemp.documentElement.childNodes.item(2))
//alert("tempXML.xml=" + rstSearchTemp.xml);    
*/	
	var intRecordCount = 0; //this used to be returned by the AutoCount function above
	
//alert("3AddC:"+theField+" ,"+ theString+", "+intRecordCount+", "+strAutoCount);

	AddCriteria(theField, theString, intRecordCount, strAutoCount);
    
   if(AppOutClause != "")   
    {
        insertRecord2(rstSearchTemp, strAgentID, intPropType, strSearchType, AppOutClause, "Do not include App Pending", "Y", "", "App_Out");
        AddCriteria("App_Out", "Do not include App Pending", intRecordCount, strAutoCount);    	
    }	
	//alert("windowName=" + windowName);
	/*
	if(myform != document.CriteriaForm)
		windowName.close();
	else
		theCriteriaWindow.innerHTML = "";
	*/
	
	//If user selected count while leaving the criteria window open.
	if (blnLeaveCriteria == true)
	{
		DoDB('count', '', '', false);
	}		

	//Close criteria window if user clicks OK
	if(myform == document.CriteriaForm && blnLeaveCriteria==false)
	{
		theCriteriaWindow.innerHTML = "";
		OKCancelButtons.style.visibility="hidden";
	}
	
	blnLeaveCriteria =false	

	if(theField == "AREA")
		GetAreas();	

	document.searchform.CRITERIA.focus();
}

function test_status(status)
{
    if (inArray(active_stat,status) && (active_check == true))
        return true;
    else
       if(inArray(off_mkt_stat,status) && (off_mkt_check == true))
			return true;
       else
			return false;
}


function URLEncode(strURL)
{
	var pat = / /
	while(strURL.indexOf(" ", 0) > 0)
		strURL = strURL.replace(pat, "+");
	return strURL;
}

function CompareStatusDates(intArrayRef, intOffset, strDate)
{
	var result = "";
	if(FieldArray.length > ((intArrayRef * 3) + intOffset))
	{
		if(FieldArray[(i * 3) + intOffset] == strDate)
			result = " selected";
	}
	return result;
}

function GetDateValue(i, theValue)
{
	if(FieldArray.length > ((i * 3) + 3))
		return theValue;
	else
		return "";
}

function AddQuotes(addQuotes)
{
	if (addQuotes)
		return "'";
	else
		return "";
}


function HiddenDB(thePropType, theAction, theField, AutoCount, bHotsheet)
{	
	
	
		
	switch(Trim(theAction))
	{
	case  "clear":
		truncateXMLDoc(rstSearchTemp);
		DoClear();
	break;
	case  "save":
		var strStatus = DoFileSaveAs(document.mainform.SEARCHES.value, "true", bHotsheet);
		if (strStatus.indexOf("Failure=", 0) == -1) //successful save
		{
			temproot = rstSavedSearches.documentElement.selectSingleNode("rs:data/z:row[@SEARCH_TYPE = '" + strSearchType + "'][@SEARCH_ID = '" + intSearchID + "']");
			if(temproot == null)
				alert("Error: Could not find Previously Saved Search!");
			else
			{
				temproot.setAttribute("PROP_TYPE", thePropType);
				temproot = rstSearch.documentElement.selectNodes("rs:data/z:row[@SEARCH_ID = '" + intSearchID + "']");
				var currNode;
				var oldChild;
				for(var x=0;x<temproot.length;x++)
				{
					currNode = rstSearch.documentElement.childNodes.item(1)
					oldChild = currNode.removeChild(temproot.item(x))
				}
				var root = rstSearchTemp.getElementsByTagName("z:row");
				for(var x=0;x<root.length;x++)
				{
					insertRecord(rstSearch, intSearchID, root.item(x).getAttributeNode("SNIPPET").text, root.item(x).getAttributeNode("STRING").text, root.item(x).getAttributeNode("VALUE1").text, root.item(x).getAttributeNode("VALUE2").text, root.item(x).getAttributeNode("VIEW_NAME").text, root.item(x).getAttributeNode("PROP_TYPE").text)
				}
			}
			alert('The search "' + strStatus + '" was saved successfully.');
			strSearchName = strStatus;
		}
		else
		{
			alert("Error saving your search.\n" + strStatus);
		}
	break;
	case  "saveas":
	
	    var disave=true;
	    
	    //check if the new searh name is the same as the existing srch. Only check for new search 
	    if (document.mainform.prospect_id.value==""  && document.mainform.CID.value != "0")
	    {
	        var ChkName = ChkSrchName(theField);
	        if (ChkName!="")
	        {
	            alert(ChkName);
	            disave=false;
	        }
	    }
	    
	    
	    if (disave)
	    {
	    
	    
	    var strStatus = DoFileSaveAs(theField, "", bHotsheet);
	    
	    
	    //alert(strStatus);
	    //if (strStatus=="")
		//    strStatus = DoFileSaveAs(theField, "true", bHotsheet);

		
		if(strStatus.indexOf("You already have a search named") >= 0)
		{
			//if(confirm(strStatus))
			//{
				strStatus = DoFileSaveAs(theField, "true", bHotsheet);
				if(strStatus.indexOf("Failure=", 0) == -1) //successful save
				{
					temproot = rstSavedSearches.documentElement.selectSingleNode('rs:data/z:row[@SEARCH_TYPE = "' + strSearchType + '"][@SEARCH_NAME = "' + theField + '"]');
					if(temproot == null)
						alert("Error: Could not find Previously Saved Search!");
					else
					{
						temproot.setAttribute("PROP_TYPE", thePropType);
						temproot = rstSearch.documentElement.selectNodes("rs:data/z:row[@SEARCH_ID = '" + intSearchID + "']");
						var currNode;
						var oldChild;
						for(var x=0;x<temproot.length;x++)
						{
							currNode = rstSearch.documentElement.childNodes.item(1)
							oldChild = currNode.removeChild(temproot.item(x))
						}
						var root = rstSearchTemp.getElementsByTagName("z:row");
						for(var x=0;x<root.length;x++)
						{
							insertRecord(rstSearch, intSearchID, root.item(x).getAttributeNode("SNIPPET").text, root.item(x).getAttributeNode("STRING").text, root.item(x).getAttributeNode("VALUE1").text, root.item(x).getAttributeNode("VALUE2").text, root.item(x).getAttributeNode("VIEW_NAME").text, thePropType)
						}
					}
					//var theIndex = document.mainform.SEARCHES.options.length;
					//newItem = new Option(theField, theIndex.toString(), false, true);
					//document.mainform.SEARCHES.options[theIndex] = newItem;
					//document.mainform.SEARCHES.options[theIndex].value = intSearchID;
					if(strSearchType == "PROSPECT")
					{
						//alert('New Prospect');
						clearTimeout(iTimerIdentifier);
						location.href = "../Prospecting/prospect_new.asp?make_profile=1&cid=" + document.mainform.CID.value + "&prop_type=" + thePropType + "&search_id=" + intSearchID + "&PropType=" + thePropType + "&prospect_id=" + document.mainform.prospect_id.value + "&pn=" + URLEncode(strStatus);
					}
					else if(bHotsheet)
					{
						//alert('New Hotsheet');
						clearTimeout(iTimerIdentifier);
						location.href = "../Prospecting/prospect_new.asp?make_profile=1&cid=0&prop_type=" + thePropType + "&search_id=" + intSearchID + "&PropType=" + thePropType + "&prospect_id=" + document.mainform.prospect_id.value + "&pn=" + URLEncode(strStatus);
						//location.href = '../Prospecting/AutoSearchResults.asp?prospect_id=' + document.mainform.prospect_id.value + '&viewall=0';
					}
					else
						alert('The search "' + strStatus + '" was saved successfully.');
					strSearchName = strStatus;

					for(var x=0;x<document.mainform.SAVED_SEARCHES.options.length;x++)
						if(document.mainform.SAVED_SEARCHES.options[x].value == intSearchID)
						{
							theIndex = x;
							break;
						}
					if(bHotsheet)
					{
						document.mainform.SAVED_SEARCHES.options[theIndex].hotsheet = 'Y';
						if(document.mainform.SAVED_SEARCHES.options[theIndex].text.substring(document.mainform.SAVED_SEARCHES.options[theIndex].text.length-4,document.mainform.SAVED_SEARCHES.options[theIndex].text.length) != ' [H]')
							document.mainform.SAVED_SEARCHES.options[theIndex].text = document.mainform.SAVED_SEARCHES.options[theIndex].text + ' [H]';
					}
					else
					{
						document.mainform.SAVED_SEARCHES.options[theIndex].hotsheet = 'N';
						if(document.mainform.SAVED_SEARCHES.options[theIndex].text.substring(document.mainform.SAVED_SEARCHES.options[theIndex].text.length-4,document.mainform.SAVED_SEARCHES.options[theIndex].text.length) == ' [H]')
							document.mainform.SAVED_SEARCHES.options[theIndex].text = document.mainform.SAVED_SEARCHES.options[theIndex].text.substring(0,document.mainform.SAVED_SEARCHES.options[theIndex].text.length-4);
					}


				}
				else
					alert("Error saving your search.\n\n" + strStatus + "\n\nlen=" + strStatus.indexOf("You already have a search named"));
			//}
		}
		else if (strStatus.indexOf("Failure=", 0) == -1) //successful save
		{
			temproot = rstSavedSearches.documentElement.selectSingleNode('rs:data/z:row[@SEARCH_TYPE = "' + strSearchType + '"][@SEARCH_NAME = "' + theField + '"]');
			if(temproot != null)
			{
				if(temproot.length == 0)
					temproot = null;
			}
			if(temproot == null)
			{
				//if (intSearchID != intSearchID) //create a new Saved Search record
				insertRecord3(rstSavedSearches, strAgentID, thePropType, intSearchID, theField, strSearchType)
				temproot = rstSearch.documentElement.selectNodes("rs:data/z:row[@SEARCH_ID = '" + intSearchID + "']");
				for(var x=0;x<temproot.length;x++)
					deleteRecord(rstSearch, x);
				var root = rstSearchTemp.getElementsByTagName("z:row");
				for(var x=0;x<root.length;x++)
					insertRecord(rstSearch, intSearchID, root.item(x).getAttributeNode("SNIPPET").text, root.item(x).getAttributeNode("STRING").text, root.item(x).getAttributeNode("VALUE1").text, root.item(x).getAttributeNode("VALUE2").text, root.item(x).getAttributeNode("VIEW_NAME").text, root.item(x).getAttributeNode("PROP_TYPE").text)
			}
			var theIndex = document.mainform.SAVED_SEARCHES.options.length;
			newItem = new Option(theField, theIndex.toString(), false, true);

			document.mainform.SAVED_SEARCHES.options[theIndex] = newItem;
			document.mainform.SAVED_SEARCHES.options[theIndex].value = intSearchID;
			if(bHotsheet)
			{
				document.mainform.SAVED_SEARCHES.options[theIndex].hotsheet = 'Y';
				if(document.mainform.SAVED_SEARCHES.options[theIndex].text.substring(document.mainform.SAVED_SEARCHES.options[theIndex].text.length-4,document.mainform.SAVED_SEARCHES.options[theIndex].text.length) != ' [H]')
					document.mainform.SAVED_SEARCHES.options[theIndex].text = document.mainform.SAVED_SEARCHES.options[theIndex].text + ' [H]';
			}
			else
				document.mainform.SAVED_SEARCHES.options[theIndex].hotsheet = 'N';

			//add the new search record to the XML doc
			//insertSavedSearchRecord(rstSavedSearches, strAgentID, thePropType, intSearchID, strStatus, strSearchType)			
			if(strSearchType == "PROSPECT")
			{
				//alert("../Prospecting/prospect_new.asp?make_profile=1&cid=" + document.mainform.CID.value + "&prop_type=" + thePropType + "&search_id=" + intSearchID + "&PropType=" + thePropType + "&prospect_id=" + document.mainform.prospect_id.value + "&pn=" + URLEncode(strStatus));
				clearTimeout(iTimerIdentifier);
				location.href = "../Prospecting/prospect_new.asp?make_profile=1&cid=" + document.mainform.CID.value + "&prop_type=" + thePropType + "&search_id=" + intSearchID + "&PropType=" + thePropType + "&prospect_id=" + document.mainform.prospect_id.value + "&pn=" + URLEncode(strStatus);
			}
			else if(bHotsheet)
			{
				//alert('New Hotsheet');
				clearTimeout(iTimerIdentifier);
				location.href = "../Prospecting/prospect_new.asp?make_profile=1&cid=0&prop_type=" + thePropType + "&search_id=" + intSearchID + "&PropType=" + thePropType + "&prospect_id=" + document.mainform.prospect_id.value + "&pn=" + URLEncode(strStatus);
				//location.href = '../Prospecting/AutoSearchResults.asp?prospect_id=' + document.mainform.prospect_id.value + '&viewall=0';
			}
			else
				alert('The search "' + strStatus + '" was saved successfully.');
			strSearchName = strStatus;
		}
		else
			alert("Error saving your search.\n\n" + strStatus + "\n\nlen=" + strStatus.indexOf("You already have a search named"));
			
		} //disave	
	break;
	case  "remove":
	
			var root = rstSearchTemp.documentElement.selectSingleNode("rs:data/z:row[@VIEW_NAME = '" + theField + "']");
			if(root == null)
				return;
			var currNode;
			var oldChild;
			currNode = rstSearchTemp.documentElement.childNodes.item(1)

			currNode = rstSearchTemp.documentElement.childNodes.item(1)
			oldChild = currNode.removeChild(root)
  
        //Action Remove App_Out
		if(AutoCount == "true")
		{
	        
	        	    
			theRecordCount.innerText = '#####';	
			window.status = "Getting Record Count...";

			var strPOSTURL = "SearchDB.asp";
			var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			xmlhttp.Open("POST", strPOSTURL, false);
//alert(rstSearchTemp.xml);    
			var temproot = rstSearchTemp.documentElement
//alert("temproot.childNodes.length=" + temproot.childNodes.length);
			if(temproot.childNodes.length == 2)
			{
				var newNode = rstSearchTemp.createNode (1, "FORM_ELEMENTS", "")
				temproot.appendChild(newNode)
				newNode = rstSearchTemp.createNode(2, "PROP_TYPE", "")
				temproot.childNodes.item(2).attributes.setNamedItem (newNode)
				newNode = rstSearchTemp.createNode(2, "AUTOCOUNT", "")
				temproot.childNodes.item(2).attributes.setNamedItem (newNode)
				newNode = rstSearchTemp.createNode(2, "RECORDCOUNT", "")
				temproot.childNodes.item(2).attributes.setNamedItem (newNode)
				temproot.childNodes.item(2).setAttribute("PROP_TYPE", thePropType);
				temproot.childNodes.item(2).setAttribute("AUTOCOUNT", "true");
				temproot.childNodes.item(2).setAttribute("RECORDCOUNT", "");
				temproot.childNodes.item(2).setAttribute("COBROKE", String(boolcobroke));
				temproot.childNodes.item(2).setAttribute("SEARCH_NAME", strSearchName);
			}

			xmlhttp.Send(rstSearchTemp.xml);
			xmlhttp = xmlhttp.responseXML

//alert("RETURNED xmlhttp.xml=" + xmlhttp.xml);	
//alert("Autocount=" + xmlhttp.documentElement.childNodes.item(2).getAttributeNode("RECORDCOUNT").text)
			var intRecordCount = xmlhttp.documentElement.childNodes.item(2).getAttributeNode("RECORDCOUNT").text


			var oldChild = rstSearchTemp.documentElement.removeChild(rstSearchTemp.documentElement.childNodes.item(2))

//alert("Sending tempXML.xml=" + rstSearchTemp.xml);    
	
			//document.countform.RECORDCOUNT.value = intRecordCount;
			theRecordCount.innerText = intRecordCount;	
		}
	break;
	case "chkcount":

		if(!CheckRequireds(document.searchform))
			return;
		//alert('2.1');
		var strPOSTURL = "SearchDB.asp";
		var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		xmlhttp.Open("POST", strPOSTURL, false);
//alert("Sending tempXML.xml=" + rstSearchTemp.xml);    
		var temproot = rstSearchTemp.documentElement
//alert("temproot.childNodes.length=" + temproot.childNodes.length);

		if(temproot.childNodes.length == 2)
		{
			var newNode = rstSearchTemp.createNode (1, "FORM_ELEMENTS", "")
			temproot.appendChild(newNode)
			newNode = rstSearchTemp.createNode(2, "PROP_TYPE", "")
			temproot.childNodes.item(2).attributes.setNamedItem (newNode)
			newNode = rstSearchTemp.createNode(2, "AUTOCOUNT", "")
			temproot.childNodes.item(2).attributes.setNamedItem (newNode)
			newNode = rstSearchTemp.createNode(2, "RECORDCOUNT", "")
			temproot.childNodes.item(2).attributes.setNamedItem (newNode)
			newNode = rstSearchTemp.createNode(2, "COBROKE", "")
			temproot.childNodes.item(2).attributes.setNamedItem (newNode)
			newNode = rstSearchTemp.createNode(2, "SEARCH_NAME", "")
			temproot.childNodes.item(2).attributes.setNamedItem (newNode)
		}
		temproot.childNodes.item(2).setAttribute("PROP_TYPE", thePropType);
		temproot.childNodes.item(2).setAttribute("AUTOCOUNT", "true");
		temproot.childNodes.item(2).setAttribute("RECORDCOUNT", strFeatJoinBuf);
		temproot.childNodes.item(2).setAttribute("COBROKE", String(boolcobroke));
		temproot.childNodes.item(2).setAttribute("SEARCH_NAME", strSearchName);

//alert("Sending tempXML.xml=" + rstSearchTemp.xml);    
  
	    //alert('2.2');
	    // !!! If the following line is not commented out, IE 5.0 crashes due to some bug.	RJO - 9/3/2002
	    //theSQL.innerText = rstSearchTemp.xml; //RJO
	    xmlhttp.Send(rstSearchTemp.xml);
		xmlhttp = xmlhttp.responseXML

//alert("RETURNED xmlhttp.xml=" + xmlhttp.xml);	
//alert("Autocount=" + xmlhttp.documentElement.childNodes.item(2).getAttributeNode("RECORDCOUNT").text)
		//alert('2.3');
		var intRecordCount = xmlhttp.documentElement.childNodes.item(2).getAttributeNode("RECORDCOUNT").text
		theSQL.innerText = xmlhttp.documentElement.childNodes.item(2).getAttributeNode("AUTOCOUNT").text;
		var oldChild = rstSearchTemp.documentElement.removeChild(rstSearchTemp.documentElement.childNodes.item(2))

//alert("tempXML.xml=" + rstSearchTemp.xml);    
	
		chktotal = intRecordCount;
		/*
		if(parseInt(intRecordCount) > MAX_SEARCH)
		{
			theRecordCount.color ="#990000"
			theRecordCountMsg.innerText ="Note: Only top "+ MAX_SEARCH + " listings will be returned in search results"
		}
		else
		{
			theRecordCount.color ="green"
			theRecordCountMsg.innerText =""	
		}
		//alert('2.4');
		theRecordCount.innerText = FormatComma(parseInt(intRecordCount));	
		*/
		break;	
	
	
	
	
	
	case "count":

		if(!CheckRequireds(document.searchform))
			return;
		//alert('2.1');
		var strPOSTURL = "SearchDB.asp";
		var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		xmlhttp.Open("POST", strPOSTURL, false);
//alert("Sending tempXML.xml=" + rstSearchTemp.xml);    
		var temproot = rstSearchTemp.documentElement
//alert("temproot.childNodes.length=" + temproot.childNodes.length);

		if(temproot.childNodes.length == 2)
		{
			var newNode = rstSearchTemp.createNode (1, "FORM_ELEMENTS", "")
			temproot.appendChild(newNode)
			newNode = rstSearchTemp.createNode(2, "PROP_TYPE", "")
			temproot.childNodes.item(2).attributes.setNamedItem (newNode)
			newNode = rstSearchTemp.createNode(2, "AUTOCOUNT", "")
			temproot.childNodes.item(2).attributes.setNamedItem (newNode)
			newNode = rstSearchTemp.createNode(2, "RECORDCOUNT", "")
			temproot.childNodes.item(2).attributes.setNamedItem (newNode)
			newNode = rstSearchTemp.createNode(2, "COBROKE", "")
			temproot.childNodes.item(2).attributes.setNamedItem (newNode)
			newNode = rstSearchTemp.createNode(2, "SEARCH_NAME", "")
			temproot.childNodes.item(2).attributes.setNamedItem (newNode)
		}
		temproot.childNodes.item(2).setAttribute("PROP_TYPE", thePropType);
		temproot.childNodes.item(2).setAttribute("AUTOCOUNT", "true");
		temproot.childNodes.item(2).setAttribute("RECORDCOUNT", strFeatJoinBuf);
		temproot.childNodes.item(2).setAttribute("COBROKE", String(boolcobroke));
		temproot.childNodes.item(2).setAttribute("SEARCH_NAME", strSearchName);

//alert("Sending tempXML.xml=" + rstSearchTemp.xml);    
  
	    //alert('2.2');
	    // !!! If the following line is not commented out, IE 5.0 crashes due to some bug.	RJO - 9/3/2002
	    //theSQL.innerText = rstSearchTemp.xml; //RJO
	    xmlhttp.Send(rstSearchTemp.xml);
		xmlhttp = xmlhttp.responseXML

//alert("RETURNED xmlhttp.xml=" + xmlhttp.xml);	
//alert("Autocount=" + xmlhttp.documentElement.childNodes.item(2).getAttributeNode("RECORDCOUNT").text)
		//alert('2.3');
		var intRecordCount = xmlhttp.documentElement.childNodes.item(2).getAttributeNode("RECORDCOUNT").text
		theSQL.innerText = xmlhttp.documentElement.childNodes.item(2).getAttributeNode("AUTOCOUNT").text;
		var oldChild = rstSearchTemp.documentElement.removeChild(rstSearchTemp.documentElement.childNodes.item(2))

//alert("tempXML.xml=" + rstSearchTemp.xml);    
	
		//document.countform.RECORDCOUNT.value = intRecordCount;
		if(parseInt(intRecordCount) > MAX_SEARCH)
		{
			theRecordCount.color ="#990000"
			theRecordCountMsg.innerText ="Note: Only top "+ MAX_SEARCH + " listings will be returned in search results"
		}
		else
		{
			theRecordCount.color ="green"
			theRecordCountMsg.innerText =""	
		}
		//alert('2.4');
		theRecordCount.innerText = FormatComma(parseInt(intRecordCount));	

	} //end switch of DB operation
}


var DoNewRst        ="N";

function DoOldSavedSearch(myform)
{
    DoNewRst        ="N";
    DoSavedSearch(myform);
}

function DoNewSavedSearch(myform)
{
    DoNewRst        ="Y";
    DoSavedSearch(myform);
}



function DoSavedSearch(myform)
{
	if(!CheckRequireds(document.searchform))
		return;
	if(document.searchform.CRITERIA.options.length == 0)
	{
		alert("You must enter at least one search criteria, before you can search.");
		return;
	}
	
	/*
	var charstring="";
	var fieldstring="";
	if(document.searchform.CRITERIA.options.length > 0)
    {
	    for (var i=0; i < document.searchform.CRITERIA.options.length;i++)
	    {
		    charstring +=document.searchform.CRITERIA.options[i].text +"\n";
		    fieldstring +=document.searchform.CRITERIA.options[i].value +"\n";
	    }
    }
	
	alert(charstring);
	alert(fieldstring);
	*/
	

	var startTime = new Date();
	//alert("Displaying Search Results.\nThis may take a while, so be patient.\n\nStart At: " + startTime + "\n\nThe Search and Report times will be displayed at the bottom of the Search Results Page.");
	startTime = new Date(); //get a new date/time since we displayed a dialog to the user
	
	//truncateXMLDoc(rstSearchLast);
	//var root = rstSearchTemp.getElementsByTagName("z:row");
	//for(var x=0;x<root.length;x++)
	//	insertRecord2(rstSearchLast, strAgentID, root.item(x).getAttributeNode("PROP_TYPE").text, strSearchType, root.item(x).getAttributeNode("SNIPPET").text, root.item(x).getAttributeNode("STRING").text, root.item(x).getAttributeNode("VALUE1").text, root.item(x).getAttributeNode("VALUE2").text, root.item(x).getAttributeNode("VIEW_NAME").text)
	//alert("rstSearchLast=" + rstSearchLast.xml)
	
	//alert("rstSearchTemp=" + rstSearchTemp.xml)
	SaveLastSearch(rstSearchTemp, strAgentID, strSearchType)

	//alert("rstSearchLast=" + rstSearchLast.xml)

	var temproot = rstSearchTemp.documentElement
	if(temproot.childNodes.length == 2)
	{
		var newNode = rstSearchTemp.createNode (1, "FORM_ELEMENTS", "");
		temproot.appendChild(newNode);
		newNode = rstSearchTemp.createNode(2, "PROP_TYPE", "");
		temproot.childNodes.item(2).attributes.setNamedItem (newNode);
		newNode = rstSearchTemp.createNode(2, "AUTOCOUNT", "");
		temproot.childNodes.item(2).attributes.setNamedItem (newNode);
		newNode = rstSearchTemp.createNode(2, "RECORDCOUNT", "");
		temproot.childNodes.item(2).attributes.setNamedItem (newNode);
		newNode = rstSearchTemp.createNode(2, "COBROKE", "")
		temproot.childNodes.item(2).attributes.setNamedItem (newNode)
		newNode = rstSearchTemp.createNode(2, "SEARCH_NAME", "")
		temproot.childNodes.item(2).attributes.setNamedItem (newNode)
	}
	temproot.childNodes.item(2).setAttribute("PROP_TYPE", intPropType);
	temproot.childNodes.item(2).setAttribute("AUTOCOUNT", "false");
	temproot.childNodes.item(2).setAttribute("RECORDCOUNT", strFeatJoinBuf);
	temproot.childNodes.item(2).setAttribute("COBROKE", String(boolcobroke));
	temproot.childNodes.item(2).setAttribute("SEARCH_NAME", strSearchName);
	
	var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");	
	xmlhttp.Open("POST", "Search_Setup.asp", false);
	//alert("Sending: " + rstSearchTemp.xml);
    xmlhttp.Send(rstSearchTemp.xml);

	xmlhttp = xmlhttp.responseXML
	//alert("xmlhttp=" + xmlhttp.xml);

    //alert(theSQL.innerText);
    //alert(theSnippet);


//	if(document.mainform.XSL.checked)
//		location.href = "XSLSearchResults.asp?PropType=" + intPropType
//	else
//		location.href = "../SearchResultsReport.asp?PropType=" + intPropType + "&SearchID=20373&random=" + Math.random();
	var destin;
	destin = "../SearchResultsReport.asp?PropType=" + intPropType + "&SearchID=20373&random=" + Math.random();
	
	//for budget srch
	if (DoBudget=="Y")
	    destin+="&BudgetSrch=Y";
	
	//show new Srch Rst    
	if (DoNewRst=="Y")    
	    destin+="&NewRst=Y";	    
	
	if(boolcobroke)
	{
		destin += "&cb=true";
	}
	if(strSearchName=="CoBroke Critical Change")
		destin += "&cobroke=true";
	location.href = destin;
		//location.href = "DisplaySQL.asp";
	return;
}


function DoFeature(myform, thePrompt, theField)
{
	var blnFeature = false;
	var buffer = "";
	var GroupId = theField;
	var theFieldRef; //
	var strFeatTable = "PROPFEAT";
	var RecordID = "LISTING_ID";
	if(inArray(theFields, GroupId))
	{
		var myNodeList = rstSearchTemp.documentElement.selectSingleNode("rs:data/z:row[@VIEW_NAME = '" + theField + "']")
		var theSnippet = myNodeList.getAttributeNode('SNIPPET').text;
		intPFValue = theSnippet.substring(theSnippet.indexOf("and (pf") + 7, theSnippet.indexOf(".group_id = "));
		theFieldRef = Get_Fieldname(myform, theField);
		if(myform.elements[theFieldRef].options.selectedIndex == -1) //if no options are selected, delete this feature item
		{
			for(var x=0;x<theFields.length;x++)
			{
				if (theFields[x] == theField)
				{
					document.searchform.CRITERIA.selectedIndex = x;
					DoRemove();
					return;
				}
			}
		}
	}
	else
	{
		theFieldRef = Get_Fieldname(myform, theField);
		if(myform.elements[theFieldRef].options.selectedIndex == -1) //if no options are selected, ignore this feature item
		{
			if(myform != document.CriteriaForm)
				windowName.close();
			else
				theCriteriaWindow.innerHTML = "";
		
			OKCancelButtons.style.visibility="hidden";	
			document.searchform.CRITERIA.focus();
			return;
		}
		intFeatGroupRef++;
		intPFValue = intFeatGroupRef;
	}
	
	switch(GroupId)
	{
		case "2":
			if(intPropType >= 3)
			{
				strFeatTable = "buildfeat";
				RecordID = "BLDG_ID";
			}
			else
			{
				strFeatTable = "unitfeat";
				RecordID = "UNIT_ID";
			}
			break;
		case "5":
		case "7":
		case "9":
		case "10":
			strFeatTable = "buildfeat";
			RecordID = "BLDG_ID";
			break;
		case "1":
		case "4":
		case "6":
		case "8":
			strFeatTable = "unitfeat";
			RecordID = "UNIT_ID";
			break;
	}
	var blnAddFeat = false;
	if (myform.elements[0].checked && myform.elements[0].value == "AND") // we are performing and AND Bit selection
	{
		blnAddFeat = true;
		buffer = "";
	}
	else
	{
		if(myform.elements[2].checked && myform.elements[2].value == "NOT") 
			buffer =  " AND NOT EXISTS (SELECT * FROM " + strFeatTable + " pf WHERE m." + RecordID + " = pf." + RecordID + " AND m.BOARD_ID=pf.BOARD_ID AND (pf.group_id = " + GroupId + " AND (";
		else
			buffer =  " AND EXISTS (SELECT * FROM " + strFeatTable + " pf WHERE m." + RecordID + " = pf." + RecordID + " AND m.BOARD_ID=pf.BOARD_ID AND (pf.group_id = " + GroupId + " AND (";
	}

	var theDBForm;
	if(myform != document.CriteriaForm)
		theDBForm = windowName.DBform;
	else
		theDBForm = DBform

	theDBForm.theString.value = "";
	theDBForm.theField.value = theField;
	theFieldRef = Get_Fieldname(myform, theField);

	for (var i=0;i<myform.elements[theFieldRef].options.length;i++)
	{
		if (myform.elements[theFieldRef].options[i].selected)
		{
			if(Trim(myform.elements[theFieldRef].options[i].value) == "") // the user has select ANY as one of thier choices, so skip this feature
				return;
			else
			{
				theDBForm.VALUE2.value += myform.elements[theFieldRef].options[i].value + ", ";
				if (myform.elements[0].checked && myform.elements[0].value == "AND") // we are performing and AND Bit selection
				{
					buffer += " AND EXISTS (SELECT * FROM " + strFeatTable + " pf WHERE m." + RecordID + " = pf." + RecordID + " AND m.BOARD_ID = pf.BOARD_ID AND (pf.group_id = " + GroupId + " AND pf.feat_id = " + myform.elements[theFieldRef].options[i].value +"))"
					theDBForm.theString.value += myform.elements[theFieldRef].options[i].text + " AND ";
				}
				else if (myform.elements[1].checked && myform.elements[1].value == "OR") // we are performing an OR Bit selection
				{
					buffer += "pf.feat_id = " + myform.elements[theFieldRef].options[i].value + " OR  "
					theDBForm.theString.value += myform.elements[theFieldRef].options[i].text + " OR ";
				}
				else if (myform.elements[2].checked && myform.elements[2].value == "NOT") // we are performing an NOT Bit selection
				{
					buffer += "pf.feat_id = " + myform.elements[theFieldRef].options[i].value + " OR  "
					theDBForm.theString.value += " NOT " + myform.elements[theFieldRef].options[i].text + " AND ";
				}
			}
		}	
	}
	if(buffer !=  " AND (pf.group_id = " + GroupId + " AND (" && blnAddFeat ==false)
		buffer = buffer.substring(0, buffer.length - 5) + ")))"
	
	if (myform.elements[0].checked && myform.elements[0].value == "AND")
	{
		theDBForm.SNIPPET.value = buffer;
		theDBForm.VALUE1.value = "AND";
		theDBForm.theString.value = thePrompt + " = " + theDBForm.theString.value.substring(0, theDBForm.theString.value.length - 5);
		theDBForm.VALUE2.value = theDBForm.VALUE2.value.substring(0, theDBForm.VALUE2.value.length - 2);
	}
	else if (myform.elements[1].checked && myform.elements[1].value == "OR")
	{
		theDBForm.SNIPPET.value = buffer;
		theDBForm.VALUE1.value = "OR";
		theDBForm.theString.value = thePrompt + " = " + theDBForm.theString.value.substring(0, theDBForm.theString.value.length - 4);
		theDBForm.VALUE2.value = theDBForm.VALUE2.value.substring(0, theDBForm.VALUE2.value.length - 2);
	}
	else if (myform.elements[2].checked && myform.elements[2].value == "NOT")
	{
		theDBForm.SNIPPET.value = buffer;
		theDBForm.VALUE1.value = "NOT";
		theDBForm.theString.value = thePrompt + " = " + theDBForm.theString.value.substring(0, theDBForm.theString.value.length - 5);
		theDBForm.VALUE2.value = theDBForm.VALUE2.value.substring(0, theDBForm.VALUE2.value.length - 2);
	}
	var intRecordCount = 0;

	var myNodeList = rstSearchTemp.documentElement.selectSingleNode("rs:data/z:row[@VIEW_NAME = '" + theField + "']")
	if(myNodeList != null)
		updateRecord2(myNodeList, strAgentID, intPropType, strSearchType, theDBForm.SNIPPET.value, theDBForm.theString.value, theDBForm.VALUE1.value, theDBForm.VALUE2.value, theField);
	else	
		insertRecord2(rstSearchTemp, strAgentID, intPropType, strSearchType, theDBForm.SNIPPET.value, theDBForm.theString.value, theDBForm.VALUE1.value, theDBForm.VALUE2.value, theField);

	AddCriteria(theField, theDBForm.theString.value, intRecordCount, strAutoCount);

	if(myform != document.CriteriaForm)
		windowName.close();
	else
		theCriteriaWindow.innerHTML = "";
	
	OKCancelButtons.style.visibility="hidden";	
	document.searchform.CRITERIA.focus();		
}

function DoContact(myform, thePrompt, theField)
{
	var blnFeature = false;
	var buffer = "";
	var GroupId = theField;
	var theFieldRef; //

	theFieldRef = Get_Fieldname(myform, theField);
	if(myform.elements[theFieldRef].value == '') //if no value selected, ignore
	{
		if(myform != document.CriteriaForm)
			windowName.close();
		else
			theCriteriaWindow.innerHTML = "";
		
		OKCancelButtons.style.visibility="hidden";	
		document.searchform.CRITERIA.focus();
		return;
	}
	
	if(theField.indexOf('CONTACT') > -1)
	{
		if(myform.elements[theFieldRef+1].value != '')
		{
			//buffer =  " AND (" + theField + " LIKE '" + myform.elements[theFieldRef].value + "%' AND CONTACT_PHONE1_EXT LIKE '" + myform.elements[theFieldRef+1].value + "%')";
			buffer =  " AND EXISTS (SELECT * FROM prop_contacts pc WITH (NOLOCK) WHERE m.listing_id = pc.listing_id AND (";
			buffer +="(pc.CONTACT_PHONE1 LIKE '" + myform.elements[theFieldRef].value + "%' AND CONTACT_PHONE1_EXT LIKE '" + myform.elements[theFieldRef+1].value + "%')";
			buffer +=" or "			
			buffer +="(pc.CONTACT_PHONE2 LIKE '" + myform.elements[theFieldRef].value + "%' AND CONTACT_PHONE2_EXT LIKE '" + myform.elements[theFieldRef+1].value + "%')";
			buffer +=" or "			
			buffer +="(pc.CONTACT_PHONE3 LIKE '" + myform.elements[theFieldRef].value + "%' AND CONTACT_PHONE3_EXT LIKE '" + myform.elements[theFieldRef+1].value + "%')";
							
			buffer +="))";
		}
		else
		{
			//buffer =  " AND " + theField + " LIKE '" + myform.elements[theFieldRef].value + "%'";
			buffer =  " AND EXISTS (SELECT * FROM prop_contacts pc WITH (NOLOCK) WHERE m.listing_id = pc.listing_id AND (";
			buffer +="(pc.CONTACT_PHONE1 LIKE '" + myform.elements[theFieldRef].value + "%')";
			buffer +=" or ";
			buffer +="(pc.CONTACT_PHONE2 LIKE '" + myform.elements[theFieldRef].value + "%')";
			buffer +=" or ";
			buffer +="(pc.CONTACT_PHONE3 LIKE '" + myform.elements[theFieldRef].value + "%')";						
			buffer +="))";
		}
	}
	else
	{
		//buffer =  " AND EXISTS (SELECT * FROM prop_contacts pc WITH (NOLOCK) WHERE m.listing_id = pc.listing_id AND (pc.CONTACT_NAME LIKE '" + myform.elements[theFieldRef].value + "%' AND CONTACT_TYPE=1))"; // CONTACT_TYPE 1 is Excl Broker
		buffer =  " AND EXISTS (SELECT * FROM prop_contacts pc WITH (NOLOCK) WHERE m.listing_id = pc.listing_id AND (pc.CONTACT_NAME LIKE '" + myform.elements[theFieldRef].value + "%' AND CONTACT_TYPE=1))"; // CONTACT_TYPE 1 is Excl Broker
	}

	var theDBForm;
	if(myform != document.CriteriaForm)
		theDBForm = windowName.DBform;
	else
		theDBForm = DBform;

	theDBForm.theString.value = "";
	theDBForm.theField.value = theField;

	theDBForm.theString.value += myform.elements[theFieldRef].value;
	
	theDBForm.SNIPPET.value = buffer;
	theDBForm.VALUE1.value += myform.elements[theFieldRef].value;
	theDBForm.VALUE2.value += myform.elements[theFieldRef+1].value;
	theDBForm.theString.value = thePrompt + " = " + theDBForm.theString.value;
	if(theDBForm.VALUE2.value != '')
		theDBForm.theString.value += " xt:" + theDBForm.VALUE2.value;

	var intRecordCount = 0;

	var myNodeList = rstSearchTemp.documentElement.selectSingleNode("rs:data/z:row[@VIEW_NAME = '" + theField + "']")
	if(myNodeList != null)
		updateRecord2(myNodeList, strAgentID, intPropType, strSearchType, theDBForm.SNIPPET.value, theDBForm.theString.value, theDBForm.VALUE1.value, theDBForm.VALUE2.value, theField);
	else	
		insertRecord2(rstSearchTemp, strAgentID, intPropType, strSearchType, theDBForm.SNIPPET.value, theDBForm.theString.value, theDBForm.VALUE1.value, theDBForm.VALUE2.value, theField);

	AddCriteria(theField, theDBForm.theString.value, intRecordCount, strAutoCount);

	if(myform != document.CriteriaForm)
		windowName.close();
	else
		theCriteriaWindow.innerHTML = "";
	
	OKCancelButtons.style.visibility="hidden";	
	document.searchform.CRITERIA.focus();		
}


function ShiftBits(bits)
{
	myValue[parseInt(bits / 8)] |= (1 << (bits % 8))
}

function ValToSql()
{
	var non_zero = false;
	var buffer = "0x";
	for (var i=myValue.length - 1;i>=0;i--)
            buffer = buffer + toHex[myValue[i]]
	return buffer;
}

function RemoveCriteriaItem(myform, theField)
{
	var myNodeList = rstSearchTemp.documentElement.selectSingleNode("rs:data/z:row[@VIEW_NAME = '" + theField + "']")
	if(myNodeList != null)
	{
		for(var x=0;x<theFields.length;x++)
		{
			if (theFields[x] == theField)
			{
				document.searchform.CRITERIA.selectedIndex = x;
				DoRemove();
				break;
			}
		}
	}
//	if(myform == document.CriteriaForm)
//		theCriteriaWindow.innerHTML = "";
//	OKCancelButtons.style.visibility="hidden";
}

function FixApostrophe(strFixText)
{
	var pat = /'/
	while(strFixText.indexOf("'", 0) > 0)
		strFixText = strFixText.replace(pat, "&#x27;");
	return strFixText;
}

function CheckRequireds(myform)
{
	var strMsg = "The following fields are required in this search:\n\n"
	var returnVal = true;
	var tempRoot = rstSearchDefinitions.documentElement.selectNodes("rs:data/z:row[@PROP_TYPE = '" + intPropType + "'][@REQUIRED = '1']")
	
	for(var x=0;x<tempRoot.length;x++)
	{
		var myNodeList = rstSearchTemp.documentElement.selectSingleNode("rs:data/z:row[@VIEW_NAME = '" + tempRoot.item(x).getAttributeNode('VIEW_NAME').text + "']")
		if(myNodeList == null)
		{
			returnVal = false;
			strMsg += tempRoot.item(x).getAttributeNode('PROMPT_').text + "\n"
		}
	}
	if(!returnVal)
		alert(strMsg)
	return returnVal;
}


function MonthlyToPrice(pmt, r, p, d)
{
	var x=(pmt/(r * Math.pow((1+r), p)) * (Math.pow((1+r), p) - 1)) + d*1;
	return Math.floor(x);
}




//google MapGridWindow functions


var xmlHttp;   









function getCoords(z)
{
    //alert(intSearchID);
    var s="";
    //alert(mapsearchid);
    var r= Math.round(Math.random()*10000);  //to prevent cache
    
    var url="/mapquest/getCoords.aspx?UserID="+ strAgentID +"&sPoint=" + z + "&SearchID=" + mapsearchid;
    url+="&rand=" +r;
    
    
    
    xmlHttp=GetXmlHttpObject();
    xmlHttp.onreadystatechange=function() {
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
    { 
        if (xmlHttp.status==200) 
        {
                s=xmlHttp.responseText;
        }
    } 

   }

   xmlHttp.open("GET",url,false); 
   xmlHttp.send(null);
   
   return s;
 
 
 
    
}

function MapGridWindow()
{
    //var root3 = rstSearchTemp.documentElement.selectSingleNode("rs:data/z:row[@VIEW_NAME = 'AREA']");

    //var area=root3.getAttributeNode("VALUE1").text;
    ShowMap=true;
    //popupGeneral("/mapquest/mappoint.aspx?area="+ area +"&userid="+ strAgentID ,750,650);
    clearMap();

    document.getElementById("Maptitle").value="";
    /*
    if (document.mainform.prospect_id.value=="")  //if blank new search, no polyon shown
    {
        clearMap();
    }
    else    
        CheckInitalPts();
    */
        
    if (mapsearchid=="NEW")
        clearMap();
    else    
        CheckInitalPts();
        
    //clearMap();
    
    document.getElementById("MapBox").style.visibility='visible';
    
    document.getElementById("CRITERIA").style.visibility='hidden';
    document.getElementById("sPROP_TYPE").style.visibility='hidden';
    document.getElementById("hCOORDINATE_X").style.visibility='hidden';
    document.getElementById("hCOORDINATE_Y").style.visibility='hidden';
    document.getElementById("mCOORDINATE_X").style.visibility='hidden';
    document.getElementById("mCOORDINATE_Y").style.visibility='hidden';
    document.getElementById("MORE_FIELDS").style.visibility='hidden';
    //document.getElementById("boxB").style.top=150;

} 


function CheckInitalPts()
{
    //alert(getCoords("X"));
    //alert(getCoords("y"));
    //if (!isNaN(intSearchID))
    //{

        var Xs=getCoords("X").split(",");
        var Ys=getCoords("Y").split(",");
        var pts = [];

        
        if (Xs.length>2)
        {
            document.getElementById("Maptitle").value=getCoords("T");
            clearMap();   
            for (var i=0;i < Xs.length; i++)
            {
                
               //polyPoints[i] = new GLatLng(parseFloat(Xs[i]),parseFloat(Ys[i])) ;
               polyPoints[i] = new GLatLng(parseFloat(Ys[i]),parseFloat(Xs[i])) ;
               polygonMode = document.getElementById("drawMode_polygon").checked;
               polyPoints.push(polyPoints[i]);
               drawCoordinates();
            }
            //set center with the saved coordinates
            map.setCenter(new GLatLng(Ys[0], Xs[0]), 15);
        }
   // }
    
}


    var map;
    var polyShape;
    var polygonMode;
    var polygonDepth = "20";
    var polyPoint = [];
    var polyPoints = [];
    var marker;
    var geocoder = null;
    
    var PointX = [];
    var PointY = [];

    var fillColor = "#0000FF"; // blue fill
    var lineColor = "#000000"; // black line
    var opacity = .5;
    var lineWeight = 2;

    var kmlFillColor = "7dff0000"; // half-opaque blue fill


    function load() {
        
      if (GBrowserIsCompatible()) { 
        map = new GMap2(document.getElementById("map"));
        if (strAreas=='B')
            map.setCenter(new GLatLng(40.67448, -73.9699), 13);
        else if (strAreas=='Q')
            map.setCenter(new GLatLng(40.7342506899291, -73.88511657714844), 14);  
        else if (strAreas=='X')
            map.setCenter(new GLatLng(40.83017710272148, -73.90640258789062), 14);          
        else
            map.setCenter(new GLatLng(40.759906, -73.966920), 15);
            
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
	GEvent.addListener(map, 'click', mapClick);
        geocoder = new GClientGeocoder();
      }
    }


   // mapClick - Handles the event of a user clicking anywhere on the map
   // Adds a new point to the map and draws either a new line from the last point
   // or a new polygon section depending on the drawing mode.
    function mapClick(marker, clickedPoint) {
      polygonMode = document.getElementById("drawMode_polygon").checked;
        //alert(polyPoints.length);
        if (polyPoints.length+1>8)
            alert("You cannot have more than 8 points on map.")
      else
      {      
        // Push onto polypoints of existing polygon
        //alert("gf");
         if (clickedPoint) 
         { 
            polyPoints.push(clickedPoint);
            drawCoordinates(); 
        } 
      } 
   }


      // Clear current Map
      function clearMap(){
        map.clearOverlays();
        polyPoints = [];
        PointX = [];
        PointY = [];
	//document.getElementById("coords").value =  "&lt;-- Click on the map to digitize!";
      }


      // Toggle from Polygon PolyLine mode

      function toggleDrawMode(){
        map.clearOverlays();
        polyShape = null;
        polygonMode = document.getElementById("drawMode_polygon").checked;
        drawCoordinates();
      }


    // Delete last Point
    // This function removes the last point from the Polyline/Polygon and redraws
    // map.
    arraymarker= new Array();

    function deleteLastPoint(){
            map.clearOverlays();
      map.removeOverlay(polyShape);
      map.removeOverlay(arraymarker[arraymarker.length -1]);
      /*
      var arraymarker2 = new Array();
     for (var i = 0; i<(arraymarker.length-1); i++) 
     {
      arraymarker2[i]=arraymarker[i];
     }
     arraymarker = [];
     
     for (var i = 0; i<(arraymarker2.length); i++) 
     {
      arraymarker[i]=arraymarker2[i];
     }
     
     //arraymarker=arraymarker2;
     
     
     
      arraymarker.pop();
      // pop last element of polypoint array
      */
      polyPoints.pop();

      drawCoordinates();
      //alert(polyPoints.length);
      //alert(arraymarker.length);
     }


    // drawCoordinates
    function drawCoordinates(){

      //Re-create Polyline/Polygon
      if (polygonMode) {
        polyShape = new GPolygon(polyPoints,lineColor,lineWeight,opacity,fillColor,opacity);
      } else {
        polyShape = new GPolyline(polyPoints,lineColor,lineWeight,opacity);
      }
      //map.clearOverlays();
        
      // Grab last point of polyPoints to add marker
      for (var i=0;i<polyPoints.length;i++)
      {
      //marker = new GMarker(polyPoints[polyPoints.length -1]);
      marker = new GMarker(polyPoints[i]);
      arraymarker.push(marker);
      map.addOverlay(marker);
      map.addOverlay(polyShape);
      }
      logCoordinates();
    }


    // logCoordinates - prints out coordinates of global polyPoints array
    //  This version only logs KML, but could be extended to log different types of output

    var strcoord="";

    function logCoordinates(){


       // check mode
       if (polygonMode)
       {



         // loop to print coords 
         
         PointX = [];
         PointY = [];
         
         
         for (var i = 0; i<(polyPoints.length); i++) 
         {
           //var lat = polyPoints[i].lat();
           //var longi = polyPoints[i].lng();
           
           PointX[i]  = polyPoints[i].lng();
           PointY[i] = polyPoints[i].lat();

	     }
	     //alert("pointx 1:"+ PointX.length);
      }
      else 
      {

        // loop to print coords 
        for (var i = 0; i<(polyPoints.length); i++) 
        {
          PointX[i]  = polyPoints[i].lng();
          PointY[i] = polyPoints[i].lat();
        }
     }
     
   }




var lat_min=0;
var lat_max=0;
var lng_min=0;
var lng_max=0;
var usemapgrid=false;

    function map_getcoords()
    {
        //alert(strcoord);
        //var Long=-73.98279190063476;
        //var Lat=40.76624155398039;
        //MapByGeoCode(Lat,Long);
        
        lat_min=PointY[0];
        lat_max=PointY[0];
        lng_min=PointX[0];
        lng_max=PointX[0];     
        
        
        for (var i = 0; i<(PointX.length); i++) 
        {
            if (PointY[i] < lat_min )
                lat_min = PointY[i];

            if (PointY[i] > lat_max )
                lat_max = PointY[i];

            if (PointX[i] < lng_min)
                lng_min = PointX[i];

            if (PointX[i] > lng_max)
                lng_max = PointX[i];

        }
      

        if (PointX.length<3 )
        {
           alert("You must have at least 3 points on the map.");
        }
        else
        {

            PointYs=lat_min +","  + lat_max;
            PointXs=lng_min +","  + lng_max;
            document.getElementById("MapBox").style.visibility='hidden';
            
            document.getElementById("CRITERIA").style.visibility='visible';
            document.getElementById("sPROP_TYPE").style.visibility='visible';
            document.getElementById("hCOORDINATE_X").style.visibility='visible';
            document.getElementById("hCOORDINATE_Y").style.visibility='visible';
            document.getElementById("mCOORDINATE_X").style.visibility='visible';
            document.getElementById("mCOORDINATE_Y").style.visibility='visible';
            document.getElementById("MORE_FIELDS").style.visibility='visible';            
            usemapgrid=true;

            //show alert if grid saerch is using b4
            var charstring="";
            var showalert=false;
            if(document.searchform.CRITERIA.options.length > 0)
            {
	            for (var i=0; i < document.searchform.CRITERIA.options.length;i++)
	            {
		            charstring =document.searchform.CRITERIA.options[i].text;
		            if (charstring.indexOf("Streets ")>-1)
			            showalert=true;
	            }
            }
            
            if (showalert)
            {
                alert("The Map Grid will be using instead of Grid Search.");
            }
            
            storecoords();

            
            AddCriteria2(document.CriteriaForm, 'COORDINATE_X', 'Grid', 2, 'SpecialBETWEEN', 'Grid');
        }    
      
    }

    function storecoords_prospect()
    {
        var cPointX="";
        var cPointY="";
        for (var i = 0; i<(PointX.length); i++) 
        {
            cPointX +=PointX[i] + ",";
            cPointY +=PointY[i] + ",";
        }
        if (cPointX!="")
            cPointX=cPointX.substring(0,cPointX.length-1);
  
        if (cPointY!="")
           cPointY=cPointY.substring(0,cPointY.length-1);   

        var url="/mapquest/storeCoord.aspx?UserID="+ strAgentID +"&sPointX=" + cPointX + "&sPointY=" + cPointY +"&SearchID=" +  intSearchID;
        url +="&MapTitle=" + document.getElementById("MapTitle").value;
        //alert(url);
        xmlHttp=GetXmlHttpObject();
        xmlHttp.open("GET",url,false);
        xmlHttp.send(null);
    
    }



    function storecoords()
    {
        var cPointX="";
        var cPointY="";
	    //alert("pointx 2:"+ PointX.length);
        for (var i = 0; i<(PointX.length); i++) 
        {
            cPointX +=PointX[i] + ",";
            cPointY +=PointY[i] + ",";
        }
        if (cPointX!="")
            cPointX=cPointX.substring(0,cPointX.length-1);
  
        if (cPointY!="")
           cPointY=cPointY.substring(0,cPointY.length-1);   
    
        var url="/mapquest/storeCoord.aspx?UserID="+ strAgentID +"&sPointX=" + cPointX + "&sPointY=" + cPointY  ;
        url +="&MapTitle=" + document.getElementById("MapTitle").value;
        //alert(url);
        xmlHttp=GetXmlHttpObject();
        xmlHttp.open("GET",url,false);
        xmlHttp.send(null);
        mapsearchid="0";
        
    
    }










    function map_cancel()
    {
            usemapgrid=false;
            document.getElementById("MapBox").style.visibility='hidden';
            document.getElementById("CRITERIA").style.visibility='visible';
            document.getElementById("sPROP_TYPE").style.visibility='visible';
            document.getElementById("hCOORDINATE_X").style.visibility='visible';
            document.getElementById("hCOORDINATE_Y").style.visibility='visible';
            document.getElementById("mCOORDINATE_X").style.visibility='visible';
            document.getElementById("mCOORDINATE_Y").style.visibility='visible';
            document.getElementById("MORE_FIELDS").style.visibility='visible';             
        ClearCriteriaWindow();
    }






function MapByGeoCode(Lat,Long)
{
            //var map = new GMap2(document.getElementById("map"));
            //map.addControl(new GSmallMapControl());
            //map.addControl(new GMapTypeControl());
            //map.setCenter(new GLatLng(Lat, Long), 14);
            
            // Create our "tiny" marker icon
            var icon = new GIcon();
            icon.image = "http://www.corcoran.com/gfx/Map_Icon.png";
            icon.iconSize = new GSize(12, 12);
            icon.iconAnchor = new GPoint(6, 20);
            icon.infoWindowAnchor = new GPoint(5, 1);
        
            var point = new GLatLng(Lat,Long);
		    var marker = new GMarker(point,icon);
		    
            map.addOverlay(marker);
            
}      
      






   function showAddress(address) {
     if (geocoder) {
       geocoder.getLatLng(address,
         function(point) {
           if (!point) {
             alert(address + " not found");
           } else {
	     clearMap();
             map.setCenter(point, 13);
           }
         }
       );
     }
   }









function GetXmlHttpObject()
{ 
    var objXMLHttp=null;
    if (window.XMLHttpRequest)
    {
        objXMLHttp=new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
        objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    return objXMLHttp;
}


//google map function end



//-->
