//This function saves the search criteria to the database
//pstrFunction =	'search': go to search results
//					'count' : update listing count 
//					URL     : go to a specific url
//					blank   : if nothing is passed in, then just update database
function updateSearchCriteriaCache(pstrFunction, pstrSessionId, pintCompanyId, pstrSiteDir, pstrSelected, pAccID){
//alert(pstrFunction+'\n'+pstrSessionId+'\n'+pintCompanyId+'\n'+pstrSiteDir+'\n'+pstrSelected);
	//var blnHasProptype = true;	
	/*for(var i=0;i<document.getElementsByName('groupproptype').length;i++){
		if (document.getElementsByName('groupproptype')[i].checked == true){
//			alert(document.getElementsByName('groupproptype')[i].id);
			blnHasProptype = true
		}
	}*/
	var criteria=mySearchCriteria.getCriteria(true);
	//var criteria='mlsnumber=513077'
	if (criteria.length > 0){
		var request=new HttpRequest();
		//prompt('ff'+criteria,'/modules/internet/global/ajax/updatesearchcriteriacache.asp?debug=true&sessionid='+pstrSessionId+'&companyid='+pintCompanyId+'&'+criteria);
		request.open('POST', '/'+pstrSiteDir+'/modules/internet/global/ajax/updatesearchcriteriacache.asp',true);
		request.setRequestHeader('Content-type','application/x-www-form-urlencoded');
		request.onreadystatechange=function(){
				//alert(request.readyState+'\n'+request.statusText+'\n'+request.responseText)
				//if (request.readyState==4) {
				//	alert(request.responseText);
				//}
				
				// The check for request.statusText=='OK' was removed because safari always 
				// returned 'undefined' and therefore it would never do anything.
				//if(request.readyState==4&&request.statusText=='OK'){
				//alert(request.readyState + ' '   + ' ' + criteria);
				//if(request.readyState==1 || request.readyState==4){
				//alert('check readystate' + pstrSessionId);
				if(request.readyState==4){
				//	alert('ready state 4 -   pstrfunction: ' + pstrSelected);
					if (pstrFunction == 'results') {
						gotoResults(pstrSelected, pstrSiteDir, pAccID);
					}else if (pstrFunction == 'count') {
						document.getElementById('listingCount').innerHTML = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="16" height="16" style="float:left;margin-left:12px;" ID="Shockwaveflash1" VIEWASTEXT>\n\
								<param name="movie" value="http://media.reliancenetwork.com/media/intranet/loading.swf?setbasecolor=b6b6b6&setforecolor=7f7f7f">\n\
								<param name="quality" value="high"/>\n\
								<param name="wmode" value="transparent">\n\
								<param name="menu" value="false">\n\
								<embed src="http://media.reliancenetwork.com/media/intranet/loading.swf?setbasecolor=b6b6b6&setforecolor=7f7f7f" quality="high" wmode="transparent" width="16" height="16" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"/>\n\
							</object>\
							<div> Matches</div>\n';
						getCount(pstrSessionId, pstrSiteDir);
					}else if (pstrFunction.length > 0) {
						if (pstrFunction.indexOf("eval?") == 0) { eval(pstrFunction.substr(5)); }
						else {document.location = pstrFunction; }
					}
				}
			};
		//alert('send request');
		request.send('sessionid='+pstrSessionId+'&companyid='+pintCompanyId+'&'+criteria);
		//alert('Ready state: ' + request.readyState + ' criteria: ' + criteria);
	}else{
		if(pstrFunction == 'count'){
			alert('You must first select search criteria in order to get a result count.');
		}else{
			alert('You must first select search criteria in order to continue to search results.');
		}
	}
}

function gotoResults(pstrSelected, pstrSiteDir, pAccID){
	var pathArr = location.pathname.split('/')
	var pathElements = pathArr.length;
	var pageName = pathArr[pathElements-1];
	var accInfo = pAccID > 0 ? '&acc=' + pAccID : '';
	
	if (pageName == 'agent.asp' || pageName == 'office.asp' || pageName == 'team.asp'  || pageName == 'officegroup.asp') { 
		document.location = location.pathname+'?p=findahome.asp&results=true&selected='+pstrSelected;
	}else{
		if (accInfo.length > 0) {
			accInfo = '&acc='+pAccID;
		}else{
			accInfo = '';
		}
		document.location = '/'+pstrSiteDir+'/index.asp?p=findahome.asp&results=true&selected='+pstrSelected+accInfo;
	}
}

function getCount(pstrSessionId, pstrSiteDir){
	var request=new HttpRequest();
	var numListings = 0;
	var strText = '&nbsp;Matches'
	
	//prompt('stuff','/'+pstrSiteDir+'/modules/internet/search/ajax/getListingCount.asp?sessionid='+pstrSessionId);
	request.open('POST', '/'+pstrSiteDir+'/modules/internet/search/ajax/getListingCount.asp',true);
	request.setRequestHeader('Content-type','application/x-www-form-urlencoded');
	request.onreadystatechange=function(){
			//if(request.readyState==4){
			//	prompt('',request.responseText);
			//}
			if(request.readyState==4&&request.statusText.toUpperCase( ) == 'OK'){
				numListings = eval(request.responseText);
				numListings = CommaFormatted(numListings);
				//alert(numListings);
				if (numListings == 1){
					strText = '&nbsp;Match';
				}
				document.getElementById('listingCount').innerHTML = '<span class="newsearchresultcount">'+numListings+strText+'</span>';
				if (document.getElementById("listingcountadvancedcriteria")) { document.getElementById("listingcountadvancedcriteria").innerHTML = numListings+strText; }
			}else if(request.readyState==4){
				//alert(request.responseText)
			}
		};
	request.send('sessionid='+pstrSessionId);
}

function CommaFormatted(pamount)
{
	var delimiter = ","; // replace comma if desired
	//var a = amount.split('.',2)
	//var d = a[1];
	var i = parseInt(pamount);
	if(isNaN(i)) { return ''; }
	var n = new String(i);
	var a = [];
	while(n.length > 3)
	{
		var nn = n.substr(n.length-3);
		a.unshift(nn);
		n = n.substr(0,n.length-3);
	}
	if(n.length > 0) { a.unshift(n); }
	n = a.join(delimiter);
	amount = n;
	return amount;
}

// uses the SearchCriteria object
function populate_mysearch ( )
{
	var strDisplayName = "";
	var strDisplayValue = "";
	
	if (arguments[4]) { strDisplayName = arguments[4]; }
	if (arguments[5]) { strDisplayValue = arguments[5]; }
	
	mySearchCriteria.update({object:arguments[0], multiple:arguments[1], key:arguments[2], value:arguments[3], displayName:strDisplayName, displayValue:strDisplayValue});
	/*if(pDisplayName == null || pDisplayName.length == 0 || pDisplayValue == null || pDisplayValue.length == 0) {
		mySearchCriteria.update({object:pObj, multiple:pMultiple, key:pKey, value:pValue});
	} else {
		mySearchCriteria.update({object:pObj, multiple:pMultiple, key:pKey, value:pValue, displayName:pDisplayName, displayValue:pDisplayValue});
	}*/
}

/* This function was deprecated for the following reasons:
1. Not all browsers (Safari in this case) support custom attributes such as "_inprocess", so it won't work in these browsers.
2. Ajax is asyncronous, meaning it can run multiple calls at the same time, so theres no need to see if a call is currently "in process".
// checkes to see if there's already an existing ajax call being executed
function validrequest (pThisID, pThatID)
{
	var blnReturn = false;
	var objButtonLinkThis = document.getElementById(pThisID);
	var objButtonLinkThat = document.getElementById(pThatID);
	
	if (objButtonLinkThis.getAttribute("_inprocess") == "true" || objButtonLinkThat.getAttribute("_inprocess") == "true")
	{
		alert("Please wait for your previous request to complete before making this request.");
		blnReturn = false;s
	}
	else
	{
		objButtonLinkThis.setAttribute("_inprocess", "true");
		setTimeout("updatebuttonlinkstatus( )", 1000);
		blnReturn = true;
	}
	return blnReturn;
}
*/

// if an ajax call is done executed, update the object that triggered the call to indicate that it's done processing
function updatebuttonlinkstatus ( )
{
	if (document.getElementById("listingCount").innerHTML.indexOf("<object") < 0 && document.getElementById("listingCount").innerHTML.indexOf("</object>") < 0)
	{
		document.getElementById("buttonlinksearchresults").setAttribute("_inprocess", "false");
		document.getElementById("buttonlinkgetcount").setAttribute("_inprocess", "false");
	}
	else { setTimeout("updatebuttonlinkstatus( )", 1000); }
}

// handle event of a search criteria selection  that involves highlighting the selected value
function genericinputcriteriaselect (pObj, pMultiple, pKey, pValue, pDisplayName, pDisplayValue)
{
	if (pObj.checked) { pObj.parentNode.style.backgroundColor = "#f1f1f1"; }
	else { pObj.parentNode.style.backgroundColor = ""; }
	
	populate_mysearch(pObj,pMultiple,pKey,pValue,pDisplayName,pDisplayValue);
}

function clearselectall (pObj)
{
	pObj.checked = false;
	pObj.parentNode.style.backgroundColor = "";
}

function inputselectall (pObj, pArrInput, pKey, pDisplayName)
{
	if (pObj.checked)
	{
		for (var i=0; i<pArrInput.length; i++)
		{
			if (pArrInput[i].checked)
			{
				pArrInput[i].checked = false;
				pArrInput[i].parentNode.style.backgroundColor = "";
				populate_mysearch({checked:false}, true, pKey, pArrInput[i].value, pDisplayName, pArrInput[i].getAttribute("_displayvalue"));
			}
		}
		pObj.parentNode.style.backgroundColor = "#f1f1f1";
	}
	else { pObj.parentNode.style.backgroundColor = ""; }
}

// makes an ajax call to a page given by pURL and then sets the content of the element given by the id with the result of the call
function ajaxgetpage (pURL, pContainerID, pData, pExecute)
{
	var request = new HttpRequest( );
	
	request.open("POST", pURL, true);
	request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	request.onreadystatechange = function ( ) {
		if (request.readyState == 4 || request.readyState == "complete") 
		{
			if (document.getElementById(pContainerID)) { document.getElementById(pContainerID).innerHTML = request.responseText; }
			else { eval(pContainerID+"="+request.responseText); }
			if (pExecute.length > 0) { eval(pExecute); }
		}
	}
	request.send(pData);
}

// traverses a two-column table and check the items that exist in the search cache (uses for things like the schools and school districts search)
function checkCriteriaTableFormat (pContainer, pArrSearchCache)
{
	var objTable;
	var arrSearchCache = null;

	if (pArrSearchCache)
	{
		if (typeof(pArrSearchCache.value) == "string") { arrSearchCache = [pArrSearchCache.value]; }
		else { arrSearchCache = pArrSearchCache.value; }
	}
	
	if (arrSearchCache != null && pContainer.hasChildNodes( ))
	{
		for (var i=0; i<pContainer.childNodes.length; i++)
		{
			if (pContainer.childNodes[i].nodeType == 1 && pContainer.childNodes[i].tagName.toLowerCase( ) == "table")
			{
				objTable = pContainer.childNodes[i];
				for (var iRow=0; iRow<objTable.rows.length; iRow++)
				{
					for (var iCell=0; iCell<objTable.rows[iRow].cells.length; iCell++)
					{
						if (objTable.rows[iRow].cells[iCell].hasChildNodes( ))
						{
							for (var j=0; j<objTable.rows[iRow].cells[iCell].childNodes.length; j++)
							{
								if (objTable.rows[iRow].cells[iCell].childNodes[j].nodeType == 1 && objTable.rows[iRow].cells[iCell].childNodes[j].tagName.toLowerCase( ) == "input")
								{
									for (var x=0; x<arrSearchCache.length; x++)
									{
										if (arrSearchCache[x] == objTable.rows[iRow].cells[iCell].childNodes[j].value)
										{
											objTable.rows[iRow].cells[iCell].childNodes[j].checked = true;
											objTable.rows[iRow].cells[iCell].style.backgroundColor = "#f1f1f1";
											x = arrSearchCache.length + 1;
										}
									}
								}
							}
						}
					}
				}
			}
		}
	}
}

// Called by the "Search Results" and "Get Count" buttons
function getResults(returnCountOnly, sessionId, companyId, siteDirectory, selected) {
	var mode = returnCountOnly ? 'count' : 'results', validRequestArg1 = returnCountOnly ? 'buttonlinksearchresults' : 'buttonlinkgetcount', validRequestArg2 = returnCountOnly ? 'buttonlinkgetcount' : 'buttonlinksearchresults';
	if (returnCountOnly) {
		updateSearchCriteriaCache(mode, sessionId, companyId, siteDirectory);
	} else {
		updateSearchCriteriaCache(mode, sessionId, companyId, siteDirectory, selected);			
	}
}