/* ==================================================== Standard JavaScript Components [BEGIN] ==================================================== */
/* ---------------------------------------------------- Neighborhoods Selector [BEGIN] ---------------------------------------------------- */
// NeighborhoodsSelector component creates a list box to list the neighborhoods of specific cities for users to select.
function NeighborhoodsSelector(myCityList)
{
	// Basic attributes with default values for the neighborhoods selector.
	// NOTE: If you need to change these attributes values, please set the new values after you created a new instance of the NeighborhoodsSelector.
	this.alignCenter = false;
	this.fixedHeight = 526;
	this.top = 205;
	this.left = 805;
	this.title = "Select Neighborhoods";
	this.cityCodeList = myCityList;
	this.selectItemHeight = 18;
	this.selectItemWidth = 180;
	//this.maxColumnCount = 1;
	//this.itemsCountPerColumn = 22;
	this.actualColumnCount = 1;
	//this.totalItemsCount = 0;
	// The window name of NeighborhoodsSelector for the standard Movoto popUpWindow component.
	this.popupWindowName = "NeighborhoodsSelector";	
}
// Check whether a city is the the NeighborhoodsSelector display list or not.
NeighborhoodsSelector.prototype.isCityInList = function(cityCode)
{
	if(cityCode == null || cityCode == "" || this.cityCodeList == null || this.cityCodeList == "")
	{
		return false;
	}
	var arrCityList = this.cityCodeList.split(',');
	for(var i = 0; i < arrCityList.length; i ++)
	{
		if(arrCityList[i] == cityCode)
		{
			return true;
		}
	}
	return false;
}
// After setup the attributes values, call this function to show the NeighborhoodsSelector to the UI.
NeighborhoodsSelector.prototype.show = function()
{
	// If current instance of NeighborhoodsSelector component has already been displayed, close it first, so that it can be refreshed to apply some new changes.
	this.close();
	// Generate controls in the selector.
	var tmpNeighborhoodsSelector = this;
	if(neighborhoodsDataList.lists.length == 0)
	{
		alert("No neighborhoods found.");
		return;
	}
	// Add neighborhoods to the selector.
	//this.totalItemsCount = res.value.Tables[1].Rows[0].Count;
	this.neighborhoodsContainer = document.createElement("div");
	this.neighborhoodsContainer.className = "NeighborhoodSelectorSubContainer";
	var arrCityList = this.cityCodeList.split(',');
	var arrNeighborhoodsData = neighborhoodsDataList.getNeighborhoodsDataByCities(arrCityList);
	for(var k = 0; k < arrNeighborhoodsData.length; k ++)
	{		
		// Add city item.
		var cityCode = arrNeighborhoodsData[k].CityCode;
		var cityName = arrNeighborhoodsData[k].CityName;
		var singleSelectItemCity = document.createElement("div");
		singleSelectItemCity.innerHTML = cityName.toUpperCase();
		singleSelectItemCity.className = "NeighborhoodSelectorCityItem";
		singleSelectItemCity.style.height = this.selectItemHeight;
		this.neighborhoodsContainer.appendChild(singleSelectItemCity);
		
		if(arrNeighborhoodsData[k].Status == neighborhoodsDataListStatus.Pending)
		{
			var singleSelectItemLoading = document.createElement("div");
			singleSelectItemLoading.innerHTML = "Loading...";
			singleSelectItemLoading.className = "NeighborhoodSelectorLoading";
			singleSelectItemLoading.style.height = this.selectItemHeight;
			this.neighborhoodsContainer.appendChild(singleSelectItemLoading);
		}
		else
		{		
			// Add subarea items for current loop city.
			for(var i = 0; i < arrNeighborhoodsData[k].NeighborhoodsData.Rows.length; i ++)
			{
				var neighborhoodCode = arrNeighborhoodsData[k].NeighborhoodsData.Rows[i].AreaCode;
				var neighborhoodName = arrNeighborhoodsData[k].NeighborhoodsData.Rows[i].AreaName;
				neighborhoodName = neighborhoodName.replace(/'/g,"\'");
				var neighborhoodNameDisplay = neighborhoodName;
				var neighborhoodNLength = neighborhoodName.length;
				// If the neighborhood name is too long, its name will be truncated,
				// display the hint when user hover the mouse on the name.
				var neighborhoodLongHint = ""; 
				if(neighborhoodNLength > 20)
				{
					neighborhoodLongHint = " title=\"" + neighborhoodNameDisplay + "\"";
					neighborhoodNameDisplay = neighborhoodNameDisplay.substring(0,20) + "...";
				}
				var areaName = neighborhoodNameDisplay;
				var displayName = neighborhoodName;
				var singleSelectItem = document.createElement("div");
				singleSelectItem.innerHTML = areaName;
				// Save area information to "areaInfo" attribute so that we can get them when we need them.
				var minLat = arrNeighborhoodsData[k].NeighborhoodsData.Rows[i].MinLat;
				var maxLat = arrNeighborhoodsData[k].NeighborhoodsData.Rows[i].MaxLat;
				var minLong = arrNeighborhoodsData[k].NeighborhoodsData.Rows[i].MinLong;
				var maxLong = arrNeighborhoodsData[k].NeighborhoodsData.Rows[i].MaxLong;
				if(minLat == null)
					minLat = 0;
				if(maxLat == null)
					maxLat = 0;
				if(minLong == null)
					minLong = 0;
				if(maxLong == null)
					maxLong = 0;
				var curAreaType = arrNeighborhoodsData[k].NeighborhoodsData.Rows[i].AreaType;
				singleSelectItem.setAttribute("areaInfo",neighborhoodCode + "_" + displayName + "_" + minLat + "_" + maxLat + "_" + minLong + "_" + maxLong + "_" + cityCode + "_" + cityName + "_" + curAreaType);
				singleSelectItem.className = "NeighborhoodSelectorItemMouseOut";
				singleSelectItem.style.height = this.selectItemHeight;
				singleSelectItem.onmouseover = function(){
					if(this.className != "NeighborhoodSelectorItemSelected")
					{
						this.className="NeighborhoodSelectorItemMouseOver";
					}
				}
				singleSelectItem.onmouseout =  function(){
					if(this.className != "NeighborhoodSelectorItemSelected")
					{
						this.className="NeighborhoodSelectorItemMouseOut";
					}
				}
				singleSelectItem.onclick = function(){
					var tempSubareaInfo = this.getAttribute("areaInfo");
					var arrTempSubareaInfo = tempSubareaInfo.split("_");
					var objCitySubarea = new CitySubareaObject();
					objCitySubarea.areaCode = arrTempSubareaInfo[0];
					objCitySubarea.areaName = arrTempSubareaInfo[1];
					objCitySubarea.minLat = arrTempSubareaInfo[2];
					objCitySubarea.maxLat = arrTempSubareaInfo[3];
					objCitySubarea.minLong = arrTempSubareaInfo[4];
					objCitySubarea.maxLong = arrTempSubareaInfo[5];
					objCitySubarea.cityCode = arrTempSubareaInfo[6];
					objCitySubarea.cityName = arrTempSubareaInfo[7];
					objCitySubarea.areaType = arrTempSubareaInfo[8];
					if(this.className == "NeighborhoodSelectorItemSelected")
					{
						this.className="NeighborhoodSelectorItemMouseOut";
						removeACitySubareaItem(objCitySubarea.areaCode, objCitySubarea.cityCode, objCitySubarea.areaType);
					}
					else
					{
						this.className="NeighborhoodSelectorItemSelected";
						addACitySubareaItem(objCitySubarea);
					}
				}
				this.neighborhoodsContainer.appendChild(singleSelectItem);
			}
		}
	}
	// Create a new instance of standard Movoto popUpWindow component to show the neighborhoods.
	var popupNeighborhoodsSelector = new popUpWindow(this.popupWindowName);
	popupNeighborhoodsSelector.width = this.selectItemWidth * this.actualColumnCount;
	popupNeighborhoodsSelector.height = this.fixedHeight;
	popupNeighborhoodsSelector.top = this.top;
	popupNeighborhoodsSelector.left = this.left;
	popupNeighborhoodsSelector.alignCenter = this.alignCenter;
	popupNeighborhoodsSelector.titleBar.fontSize = "12";
	popupNeighborhoodsSelector.titleBar.innerHTML = this.title;
	popupNeighborhoodsSelector.bodyContainerType = "object";
	popupNeighborhoodsSelector.bodyContainerTypeValue = this.neighborhoodsContainer;
	popupNeighborhoodsSelector.show();
	// Refresh to highlight the selected neighborhoods.
	this.refreshHighlightItems();
}
// Close the neighborhoods selector window.
NeighborhoodsSelector.prototype.close = function()
{
	closeSpecifiedPopUpWindow(this.popupWindowName, true);
}
// Highlight the selected neighborhoods, read these selected neiborhoods from the citySubareaZipcodeList.
NeighborhoodsSelector.prototype.refreshHighlightItems = function()
{
	var neighborhoodsElements = this.neighborhoodsContainer.getElementsByTagName("div");
	var neighborhoodsElementsCount = neighborhoodsElements.length;
	for(var k = 0; k < neighborhoodsElementsCount; k ++)
	{
		var neighborhoodsElement = neighborhoodsElements[k];
		var tempSubareaInfo = neighborhoodsElement.getAttribute("areaInfo");
		if(tempSubareaInfo)
		{
			var arrTempSubareaInfo = tempSubareaInfo.split("_");
			var areaCode = arrTempSubareaInfo[0];
			if(areaCode != "null")
			{
				var areaCityCode = arrTempSubareaInfo[6];
				var areaType = arrTempSubareaInfo[8];
				if(citySubareaZipcodeList.isAreaSelected(areaCode, areaCityCode, areaType) == true)
				{
					if(neighborhoodsElement.className != "NeighborhoodSelectorItemSelected")
					{
						neighborhoodsElement.className="NeighborhoodSelectorItemSelected";
					}
				}
				else
				{
					if(neighborhoodsElement.className != "NeighborhoodSelectorItemMouseOut")
					{
						neighborhoodsElement.className="NeighborhoodSelectorItemMouseOut";
					}
				}
			}
		}
	}
}
/* ---------------------------------------------------- Neighborhoods Selector [END] ---------------------------------------------------- */
/* ---------------------------------------------------- CitySubareaZipcodeList Selector [BEGIN] ---------------------------------------------------- */
function insertItemToArray(arrObj, index, value)
{
	var part1 = arrObj.slice(0, index);
	var part2 = arrObj.slice(index);
	part1.push(value);
	return(part1.concat(part2));
}
// CitySubareaObject contains the basic city/subarea/zipcode information.
function CitySubareaObject()
{
	this.areaCode = "";
	this.areaName = "";
	this.minLat = "";
	this.maxLat = "";
	this.minLong = "";
	this.maxLong = "";
	this.cityName = "";
	this.cityCode = "";
	this.state = "";
	this.areaType = citySubareaType.City;
}
// CitySubareaZipCodeList contains city/subarea/zipcode list, and provide some functions to add/remove these areas.
function CitySubareaZipcodeList()
{
	this.lists = new Array();
}
// Get the city code list from the CitySubareaZipcodeList object, return an Array with city codes.
CitySubareaZipcodeList.prototype.getCityCodeList = function()
{
	var arrCityList = new Array();
	for(var i = 0; i < this.lists.length; i ++)
	{
		var tempCitySubareaObject = this.lists[i];
		if(tempCitySubareaObject.areaType == citySubareaType.City)
		{
			arrCityList.push(tempCitySubareaObject.areaCode);
		}
	}
	return arrCityList;
}
// Get the city name list from the CitySubareaZipcodeList object, return an Array with city names.
CitySubareaZipcodeList.prototype.getCityNameList = function()
{
	var arrCityList = new Array();
	for(var i = 0; i < this.lists.length; i ++)
	{
		var tempCitySubareaObject = this.lists[i];
		if(tempCitySubareaObject.areaType == citySubareaType.City)
		{
			arrCityList.push(tempCitySubareaObject.areaName);
		}
	}
	return arrCityList;
}
// Return the first city's name in the CitySubareaZipcodeList object.
CitySubareaZipcodeList.prototype.getFirstCityName = function()
{
	var firstCityName = null;
	if(this.lists.length > 0)
	{
		firstCityName = this.lists[0].areaName;
	}
	return firstCityName;
}
// Get the city/subarea/zipcode string list for property search.
// Return value format: "CityCode1:SubareaCode1,SubareaCode2;CityCode2:SubareaCode3;CityCode3".
CitySubareaZipcodeList.prototype.getCitySubareaZipcodeStringList = function()
{    
	var arrCitySubareaCodeStringList = new Array();
	var isFirstCity = true;
	var isFirstSubarea = true;
	var isFirstZipCode = true;
	for(var i = 0; i < this.lists.length; i ++)
	{		
		var tempCitySubareaObject = this.lists[i];
		if(tempCitySubareaObject.areaType == citySubareaType.City)
		{
			if(isFirstCity)
			{
				isFirstCity = false;
			}
			else
			{
				arrCitySubareaCodeStringList.push(";");
			}
			isFirstSubarea = true;
			isFirstZipCode = true;
		}
		else if(tempCitySubareaObject.areaType == citySubareaType.Subarea)
		{
			if(isFirstSubarea)
			{
				 isFirstSubarea = false;
				 arrCitySubareaCodeStringList.push(":");
			}
			else
			{
				arrCitySubareaCodeStringList.push(",");
			}
		}
		else if(tempCitySubareaObject.areaType == citySubareaType.ZipCode)
		{
		    if(isFirstZipCode)
			{
				 isFirstZipCode = false;
				 arrCitySubareaCodeStringList.push("#");
			}
			else
			{
				arrCitySubareaCodeStringList.push(",");
			}
		}
		arrCitySubareaCodeStringList.push(tempCitySubareaObject.areaCode);
	}
	
	var cityString=arrCitySubareaCodeStringList.join('');
	
	var cityList=cityString.split(";");            
    var cityListSort=cityList.sort();
    
    for(var cityIndex=0;cityIndex<cityListSort.length;cityIndex++)
    {
        citySubareaZipcodeString=cityListSort[cityIndex];
    
        var zipcodeStartIndex=citySubareaZipcodeString.indexOf('#');
        var subareaStartIndex=citySubareaZipcodeString.indexOf(':');
        var containsZipcode=zipcodeStartIndex!=-1;
        var containsSubarea=subareaStartIndex!=-1;
        
        var cityCodeString='';
        var zipCodeString='';
        var subareaString='';
        
        if(containsZipcode&&containsSubarea)
        {
            cityCodeString=citySubareaZipcodeString.substring(0,zipcodeStartIndex);
            zipCodeString=citySubareaZipcodeString.substring(zipcodeStartIndex+1,subareaStartIndex);
            subareaString=citySubareaZipcodeString.substring(subareaStartIndex+1);
            
            if(zipCodeString.indexOf(',')!=-1)
            {
                zipCodeString=zipCodeString.split(",").sort().join(',');
            }
            if(subareaString.indexOf(',')!=-1)
            {
                subareaString=subareaString.split(",").sort().join(',');
            }
            
            cityListSort[cityIndex]=cityCodeString+'#'+zipCodeString+':'+subareaString;
        }else if(containsZipcode&&!containsSubarea)
        {
            cityCodeString=citySubareaZipcodeString.substring(0,zipcodeStartIndex);
            zipCodeString=citySubareaZipcodeString.substring(zipcodeStartIndex+1);
            
            if(zipCodeString.indexOf(',')!=-1)
            {
                zipCodeString=zipCodeString.split(",").sort().join(',');
            }
        
            cityListSort[cityIndex]=cityCodeString+'#'+zipCodeString;
        }else if(!containsZipcode&&containsSubarea)
        {
            cityCodeString=citySubareaZipcodeString.substring(0,subareaStartIndex);
            subareaString=citySubareaZipcodeString.substring(subareaStartIndex+1);
            
            if(subareaString.indexOf(',')!=-1)
            {
                subareaString=subareaString.split(",").sort().join(',');
            }
            
            cityListSort[cityIndex]=cityCodeString+':'+subareaString;
        }
        else
        {
            cityListSort[cityIndex]=citySubareaZipcodeString;
        }                
    }
    
    return cityListSort.join(';');    
}
CitySubareaZipcodeList.prototype.getCitySubareaNameStringList = function()
{
	var arrCitySubareaCodeStringList = new Array();
	var isFirstCity = true;
	var isFirstSubarea = true;
	var isFirstZipCode = true;
	for(var i = 0; i < this.lists.length; i ++)
	{		
		var tempCitySubareaObject = this.lists[i];
		if(tempCitySubareaObject.areaType == citySubareaType.City)
		{
			if(isFirstCity)
			{
				isFirstCity = false;
			}
			else
			{
				arrCitySubareaCodeStringList.push("; ");
			}
			isFirstSubarea = true;
			isFirstZipCode = true;
		}
		else if(tempCitySubareaObject.areaType == citySubareaType.Subarea)
		{
			if(isFirstSubarea)
			{
				 isFirstSubarea = false;
				 arrCitySubareaCodeStringList.push(": ");
			}
			else
			{
				arrCitySubareaCodeStringList.push(", ");
			}
		}
		else if(tempCitySubareaObject.areaType == citySubareaType.ZipCode)
		{
		    if(isFirstZipCode)
			{
				 isFirstZipCode = false;
				 arrCitySubareaCodeStringList.push("#");
			}
			else
			{
				arrCitySubareaCodeStringList.push(",");
			}
		}
		arrCitySubareaCodeStringList.push(tempCitySubareaObject.areaName);
	}
	return arrCitySubareaCodeStringList.join('');
}
// Add a CitySubareaObject to CitySubareaZipcodeList object.
CitySubareaZipcodeList.prototype.addCitySubarea = function(citySubareaObject)
{
	if(citySubareaObject.areaType == citySubareaType.City)
	{
		this.lists.push(citySubareaObject);
	}
	else
	{
		// When adding a subarea, and if there are no items in the list, do not add this subarea.
		if(this.lists.length == 0)
		{
			return;
		}
		
		for(var i = 0; i < this.lists.length; i ++)
		{
			var tempCitySubareaObject = this.lists[i];
			if(tempCitySubareaObject.areaType == citySubareaType.City && tempCitySubareaObject.areaCode == citySubareaObject.cityCode)
			{
		        if(i == this.lists.length - 1)
		        {
		            this.lists = insertItemToArray(this.lists, i + 1, citySubareaObject);
		            return;
		        }
		        else
		        {
			        if(citySubareaObject.areaType == citySubareaType.ZipCode)
			        {
			            // Zipcode is always added to the 1st node of the city.
			            this.lists = insertItemToArray(this.lists, i + 1, citySubareaObject);
			            return;
			        }
			        else if(citySubareaObject.areaType == citySubareaType.Subarea)
			        {    			        
			            var nextCitySubareaObject = this.lists[i+1];
			            if(nextCitySubareaObject.areaType == citySubareaType.City || nextCitySubareaObject.areaType == citySubareaType.Subarea)
			            {
			                this.lists = insertItemToArray(this.lists, i + 1, citySubareaObject);
			                return;
			            }
			        }	
			    }			
			}
			else
			{
			    if(tempCitySubareaObject.areaType == citySubareaType.ZipCode && tempCitySubareaObject.cityCode == citySubareaObject.cityCode)
			    {
			        if(i == this.lists.length - 1)
		            {
		                this.lists = insertItemToArray(this.lists, i + 1, citySubareaObject);
		                return;
		            }
			        var nextCitySubareaObject = this.lists[i+1];
			        if(nextCitySubareaObject.areaType != citySubareaType.ZipCode)
		            {
		                this.lists = insertItemToArray(this.lists, i + 1, citySubareaObject);
		                return;
		            }
			    }
			}
		}
	}
}
// Check if a city/subarea/zipcode is in the CitySubareaZipcodeList.
// NOTE: For a subarea or a zipcode, the code maybe exists in multiple cities, so we need to provide its city code not only the area code.
CitySubareaZipcodeList.prototype.isAreaSelected = function(areaCode, areaCityCode, areaType)
{
	if(this.lists.length == 0)
	{
		return false;
	}
	for(var i = 0; i < this.lists.length; i ++)
	{
		if(areaCode == this.lists[i].areaCode && areaCityCode == this.lists[i].cityCode && parseInt(areaType) == this.lists[i].areaType)
		{
			return true;
		}
	}
	return false;
}
// Remove a CitySubareaObject from CitySubareaZipcodeList object.
// NOTE: For a subarea or a zipcode, the code maybe exists in multiple cities, so we need to provide its city code not only the area code.
CitySubareaZipcodeList.prototype.removeCitySubarea = function(areaCode, areaCityCode, areaType)
{
	if(this.lists.length == 0)
	{
		return;
	}
	for(var i = this.lists.length - 1; i >= 0; i --)
	{
		var tempCitySubareaObject = this.lists[i];
		// If the area to be removed is a city, remove the city and also its subareas/zipcodes.
		if(parseInt(areaType) == citySubareaType.City)
		{
			if(areaCode == tempCitySubareaObject.cityCode)
			{
				this.lists.splice(i, 1);
			}
		}
		else
		{
			// If the area to be removed is not a city, only remove this area.
			if(areaCode == tempCitySubareaObject.areaCode)
			{
				this.lists.splice(i, 1);
				return;
			}
		}
	}
}
// Clear all the CitySubareaObjects from the CitySubareaZipcodeList object.
CitySubareaZipcodeList.prototype.clear = function()
{
	this.lists = new Array();
}
/* ---------------------------------------------------- CitySubareaZipcodeList [END] ---------------------------------------------------- */
/* ---------------------------------------------------- CitySubarea Selector [BEGIN] ---------------------------------------------------- */
// CitySubareaSelector component creates a UI container, in this container, we can add or remove cities/subareas/zipcodes to it.
// "selectorContainerId" parameter is the id of the element which is used to include a CitySubarea selector.
function CitySubareaSelector(selectorContainerId)
{
	this.isCitySubareaClickable = false;
	this.containerElement = document.getElementById(selectorContainerId);
	this.subContainerElement = document.createElement("div");
	this.subContainerElement.className = "CitySubareaSelectorSubContainer";
	if(this.containerElement)
	{
		this.containerElement.className = "CitySubareaSelectorContainer";
		this.containerElement.appendChild(this.subContainerElement);
	}
}
// Clear all the city/subarea/zipcode items in the CitySubarea selector.
CitySubareaSelector.prototype.clearItems = function()
{
	if ( this.subContainerElement.hasChildNodes() )
	{
		while ( this.subContainerElement.childNodes.length >= 1 )
		{
			this.subContainerElement.removeChild( this.subContainerElement.firstChild );       
		} 
	}	
}
// Reload all the items in the CitySubarea selector.
CitySubareaSelector.prototype.reloadItems = function()
{
	// Clear the existing items first.
	this.clearItems();
	
	// Add the items from the citySubareaZipcodeList.
	if(citySubareaZipcodeList.lists.length > 0)
	{
		var myCitySubareaContainer = this;
		for(var i = 0; i < citySubareaZipcodeList.lists.length; i ++)
		{
			var objCitySubarea = citySubareaZipcodeList.lists[i];
			var citySubareaItem = document.createElement("div");
			
			var citySubareaNameDiv = document.createElement("div");
			
			if(objCitySubarea.areaType == citySubareaType.City)
			{
				citySubareaNameDiv.innerHTML = objCitySubarea.areaName + ", " + objCitySubarea.state;
				// Set the style for city item.
				citySubareaNameDiv.className = "CitySubareaSelectorItem";
			}
			else
			{
				var subareaNameDisplayText = objCitySubarea.areaName;
				if(subareaNameDisplayText.length > 18)
				{
					subareaNameDisplayText = subareaNameDisplayText.substring(0,18) + "...";
				}
				citySubareaNameDiv.innerHTML = subareaNameDisplayText;
				// Set the style for subarea/zipcode item.
				if(i == citySubareaZipcodeList.lists.length - 1 || (i != citySubareaZipcodeList.lists.length - 1 && citySubareaZipcodeList.lists[i+1].areaType == citySubareaType.City))
				{
					// if the item is the last item in the list, or it is not the last item in the list but the next item is a city, 
					// so it is the last subarea/zipcode for its city, set the special style for it.
					citySubareaNameDiv.className = "CitySubareaSelectorSubareaLastItem";
				}
				else
				{
					// Set the basic subarea/zipcode item style.
					citySubareaNameDiv.className = "CitySubareaSelectorSubareaItem";
				}
			}
			citySubareaItem.appendChild(citySubareaNameDiv);
			
			// If current area to be added is a city, add preview button for it, click the button will load neighborhoods list in a popup window.
			if(objCitySubarea.areaType == citySubareaType.City)
			{
				
				var citySubareaItemPreviewButton = document.createElement("div");
				citySubareaItemPreviewButton.className = "CitySubareaSelectorPreviewButton";
				citySubareaItemPreviewButton.setAttribute("title", "Select neighborhoods of this city");
				citySubareaItemPreviewButton.setAttribute("areaCode", objCitySubarea.areaCode);
				citySubareaItemPreviewButton.onclick = function()
				{
					// If user clicks the preview button, create a new instance of NeighborhoodsSelector component to show the neighborhoods list.
					neighborhoodsSelector = new NeighborhoodsSelector(this.getAttribute("areaCode"));
					neighborhoodsSelector.top = 205;
					if(isAgentSendEmailPage)
					{
						neighborhoodsSelector.top = "585";
					}
					neighborhoodsSelector.show();
				}
				citySubareaItem.appendChild(citySubareaItemPreviewButton);
			}
			
			// Add delete button.
			var citySubareaItemDeleteButton = document.createElement("div");
			citySubareaItemDeleteButton.className = "CitySubareaSelectorDeleteButton";
			citySubareaItemDeleteButton.setAttribute("id","delNeighborhood_" + objCitySubarea.areaCode);
			citySubareaItemDeleteButton.setAttribute("title", "Remove");
			citySubareaItemDeleteButton.setAttribute("areaCode", objCitySubarea.areaCode);
			citySubareaItemDeleteButton.setAttribute("areaCityCode", objCitySubarea.cityCode);
			citySubareaItemDeleteButton.setAttribute("areaType", objCitySubarea.areaType);
			
			citySubareaItemDeleteButton.onclick = function()
			{
				removeACitySubareaItem(this.getAttribute("areaCode"), this.getAttribute("areaCityCode"), this.getAttribute("areaType"));
			}
			citySubareaItem.appendChild(citySubareaItemDeleteButton);
			
			// Add a blank DIV to clear the float for a city/subarea item.
			var citySubareaItemClearFloatDiv = document.createElement("div");
			citySubareaItemClearFloatDiv.className = "clearFloat";
			citySubareaItem.appendChild(citySubareaItemClearFloatDiv);
			
			this.subContainerElement.appendChild(citySubareaItem);
		}		
	}	
}
/* ---------------------------------------------------- CitySubarea Selector [END] ---------------------------------------------------- */
/* ---------------------------------------------------- NeighborhoodsDataList [BEGIN] ---------------------------------------------------- */
var neighborhoodsDataListStatus = {Pending: 0, Done: 1, Failed: -1};
function NeighborhoodsDataList()
{
	this.lists = new Array();
}
NeighborhoodsDataList.prototype.appendCity = function(cityCode, cityName)
{
	if(this.isCityNeighborhoodsDataIncluded(cityCode))
	{
		return;
	}
	var neighborhoodsDataItem = {CityCode: cityCode, CityName: cityName, Status: neighborhoodsDataListStatus.Pending, NeighborhoodsData: null};
	this.lists.push(neighborhoodsDataItem);
	this.reloadNeighborhoodsDataByCity(cityCode);
}
NeighborhoodsDataList.prototype.addNeighborhoodsData = function(cityCode, neighborhoodsDataTable)
{
	if(this.lists.length == 0)
	{
		return;
	}
	for(var i = 0; i < this.lists.length; i ++)
	{
		if(cityCode == this.lists[i].CityCode)
		{
			this.lists[i].NeighborhoodsData = neighborhoodsDataTable;
			this.lists[i].Status = neighborhoodsDataListStatus.Done;
			// Re-show the neighborhoods selector to update the list in the UI.
			if(neighborhoodsSelector != null && popWinActiveWindowName == neighborhoodsSelector.popupWindowName)
			{
				if(neighborhoodsSelector.isCityInList(cityCode) == true)
				{
					neighborhoodsSelector.show();
				}
			}
			break;
		}
	}
	
}
NeighborhoodsDataList.prototype.reloadNeighborhoodsDataByCity = function(cityCode)
{
	iGen.WebServices.Common.GetSubareaListByCityList(cityCode, onGetSubareaListByCityListSuccessed);
}
function onGetSubareaListByCityListSuccessed(result)
{
	if(result == null || result.Tables == 0 || result.Tables.length < 2)
	{
		return;
	}
	var returnedCityCode = result.Tables[0].Rows[0].CityCode;
	neighborhoodsDataList.addNeighborhoodsData(returnedCityCode, result.Tables[1]);
}
NeighborhoodsDataList.prototype.removeNeighborhoodsData  = function(cityCode)
{
	for(var i = this.lists.length - 1; i >= 0; i --)
	{
		if(cityCode == this.lists[i].CityCode)
		{
			this.lists.splice(i, 1);
			return;
		}
	}
}
NeighborhoodsDataList.prototype.isCityNeighborhoodsDataIncluded = function(cityCode)
{
	if(this.lists.length == 0)
	{
		return false;
	}
	for(var i = 0; i < this.lists.length; i ++)
	{
		if(cityCode == this.lists[i].CityCode)
		{
			return true;
		}
	}
	return false;
}
NeighborhoodsDataList.prototype.getNeighborhoodsData = function(cityCode)
{
	if(this.isCityNeighborhoodsDataIncluded(cityCode))
	{
		for(var i = 0; i < this.lists.length; i ++)
		{
			if(cityCode == this.lists[i].CityCode)
			{
				return this.lists[i];
			}
		}
	}
	else
	{
		return null;
	}
}
NeighborhoodsDataList.prototype.getNeighborhoodsDataByCities = function(arrCityCode)
{
	if(arrCityCode == null || arrCityCode.length == 0)
	{
		return null;
	}
	var arrNeighborhoodsData = new Array();
	for(var i = 0; i < arrCityCode.length; i ++)
	{
		var tempCityCode = arrCityCode[i];
		for(var i = 0; i < this.lists.length; i ++)
		{
			if(tempCityCode == this.lists[i].CityCode)
			{
				arrNeighborhoodsData.push(this.lists[i]);
				break;
			}
		}
	}
	return arrNeighborhoodsData;
}
NeighborhoodsDataList.prototype.clear = function()
{
	this.lists = new Array();
}
var neighborhoodsDataList = new NeighborhoodsDataList();
/* ---------------------------------------------------- NeighborhoodsDataList [END] ---------------------------------------------------- */
/* ==================================================== Standard JavaScript Components [END] ==================================================== */
/* ==================================================== Global Variables [BEGIN] ==================================================== */
var gChangeCityListNumber	= 0;
var gCallDistrictAjaxNumber = 0;
var propertySearchCurrentMetroArea = GetCurrentMetroAreaCode();
// Area types list.
var citySubareaType = {City:0, Subarea:1, ZipCode:2};
var citySubareaZipcodeList = new CitySubareaZipcodeList();
var neighborhoodsSelector;
/* ==================================================== Global Variables [END] ==================================================== */
/* ==================================================== DOM manipulation [BEGIN] ==================================================== */
// Validate all inputs values for important controls.
function validateAllInputsValues()
{	
	// Check the selected cities and subareas.
	if(citySubareaZipcodeList.lists.length == 0)
	{
		alert("Please select at least one city.");
		return false;
	}
	
	// Check save search inputs.
	var isSearchNeedSave = false;
	var ckbIsEmailUpdates = ChangeElement("ckbIsEmailUpdates");
	var ckbIsAutoSaveSearch = ChangeElement("ckbIsAutoSaveSearch");
	var tbxSearchName = ChangeElement("tbxSearchName");
	if(ckbIsEmailUpdates.checked || ckbIsAutoSaveSearch.checked)
	{
		isSearchNeedSave = true;
	}
	if(ckbIsEmailUpdates.checked)
	{
		if(tbxSearchName.value == "")
		{
			alert("Please input the search name to save.");
			tbxSearchName.focus();
			return false;
		}
		TrackPSListingUpdates();
	}
	if(tbxSearchName.value != "" && !ckbIsAutoSaveSearch.checked)
	{
		alert("You need to check the checkbox of \"Save this Search\" to save.");
		return false;
	}
	// Check the email address.
	if(isSearchNeedSave == true)
	{
		var tbxEmail = ChangeElement("tbxEmail");
		if(tbxEmail.style.display != "none")
		{
			if(tbxEmail.value == "")
			{
				alert("Please input you email address.");
				tbxEmail.focus();
				return false;
			}
			else
			{
				if(validateEmailAddress(tbxEmail.value))
				{
					if(!ckbIsEmailUpdates.checked)
					{
						alert("Please check the \"Send Me Email Updates\" checkbox to receive email updates.");
						return false;
					}
				}
				else
				{
					alert("Your email address is incorrect.");
					tbxEmail.focus();
					return false;
				}
			}
		}
	}
	return true;
}
function TrackPSListingUpdates()
{
	var ckbIsEmailUpdates = ChangeElement("ckbIsEmailUpdates");
	if(ckbIsEmailUpdates.checked)
	{
	    var ele = ChangeElement("ddlEmailUpdatesFrequency");
	    var v   = ele.options[ele.selectedIndex].value;
	    var frequency;
	    if(v == "2")
	        frequency = "Daily ";
	    else if(v == "3")
	        frequency = "Weekly ";
	    else
	        frequency = "Realtime";
	    
	    TrackGoogleAnalytics('PropertySearch - '+ frequency +'Listing Updates');
	}
}

// Check user input values.
function checkRealTimeInputValues(checkControl, e)
{	
	var key;	
	if (window.event)
	{ 
		//for IE
		key = event.keyCode;
	} 
	else if (e)
	{ 
		//for Firefox
 		key = e.which;
	}
	else
	{
		return;
	}
	switch(checkControl.id)
	{
		// Save search name input box, auto check the check box when user inputs some values.
		case "USC_tbxSearchName":
			var ckbIsAutoSaveSearch = ChangeElement("ckbIsAutoSaveSearch");
			if(ckbIsAutoSaveSearch)
			{
				ckbIsAutoSaveSearch.checked = (checkControl.value.length > 0);
			}
			break;
		// Auto check the check box when user change the email update type.
		case "USC_ddlEmailUpdatesFrequency":
			var ckbIsEmailUpdates = ChangeElement("ckbIsEmailUpdates");
			if(ckbIsEmailUpdates)
			{
				ckbIsEmailUpdates.checked = true;
			}
			break;
		case "USC_tbxEmail":
			var ckbIsEmailUpdates = ChangeElement("ckbIsEmailUpdates");
			if(ckbIsEmailUpdates && checkControl.value.length > 0)
			{
				ckbIsEmailUpdates.checked = true;
			}
			break;
		case "USC_tbxMinSquareFeet":
		case "USC_tbxMinLotSize":
		case "USC_tbxDaysOnMarketMin":
		case "USC_tbxDaysOnMarketMax":
		case "USC_tbxYearBuiltMin":
		case "USC_tbxYearBuiltMax":
			// Only allow input numbers for these input boxes.
			if(key != 8)
			{
				if(key < 48 || key > 57)
				{
					if(window.event)
					{
						event.returnValue = false;
					}
					else if(e)
					{
						e.preventDefault();
					}
				}
			}
			break;
		case "USC_tbxMinPrice":
		case "USC_tbxMaxPrice":
			// Only allow input numbers, dollar($), comma(,), dot(.) for these input boxes.
			if(key != 8 && key != 44 && key != 46 && key != 36)
			{
				if(key < 48 || key > 57)
				{
					if(window.event)
					{
						event.returnValue = false;
					}
					else if(e)
					{
						e.preventDefault();
					}
				}
			}
			break;
	}
}

//Control save logic.
function AutoCheck(eleid,chbxid)
{			
	if(ChangeElement("btnSave")==null)	return;				
	if(chbxid==null)
	{							
		if(!ChangeElement('chbxSaveAs').checked)	
		{			
			ChangeElement("btnSave").disabled=true;
		}
		else 
			ChangeElement("btnSave").disabled=false;					
	}
	else
	{
		var touchEle = ChangeElement(eleid);
		if(touchEle!=null&&Trim(touchEle.value)!="")	
		{		
			if(ChangeElement(chbxid)!=null)
			{
				ChangeElement(chbxid).checked = true;
				ChangeElement('chbxSaveAs').checked = true;
			}	
				
			if(eleid == "tbxSaveAs"&&ChangeElement("btnSave")!=null)				
				ChangeElement("btnSave").disabled=false;							
					
		}
		else if(ChangeElement(chbxid)!=null)
		{
			ChangeElement(chbxid).checked = false;
			if(eleid == "tbxSaveAs"&&ChangeElement("btnSave")!=null)				
				ChangeElement("btnSave").disabled=true;	
		}
	}
}

//Created by Joe, Get element on user control.								
function ChangeElement(eleID)
{			    
	var uc_name = "USC_";	
	if(document.getElementById(uc_name+eleID)==null)
	{
		if(document.getElementById(eleID)==null)
		{
			alert(eleID);
			return null;
		}
		else
			return document.getElementById(eleID);	
	}
	return document.getElementById(uc_name+eleID);
}

//add subarea to the list box			
function addsubitem()
{
	var list=ChangeElement("lbxCityList");	
	if(list.selectedIndex!=-1)
	{
		var cityListItemText = list.options[list.selectedIndex].text;
		var cityname=cityListItemText.substring(0, cityListItemText.length - 4);
		var stateCode = cityListItemText.substring(cityListItemText.length - 2, cityListItemText.length);
		var citycode=list.options[list.selectedIndex].value;
		var objCitySubarea = new CitySubareaObject();
		objCitySubarea.areaCode = objCitySubarea.cityCode = citycode;
		objCitySubarea.areaName = objCitySubarea.cityName = cityname;
		objCitySubarea.state = stateCode;
		objCitySubarea.minLat = objCitySubarea.maxLat = objCitySubarea.minLong = objCitySubarea.maxLong = "";
		objCitySubarea.areaType = citySubareaType.City;
		addACitySubareaItem(objCitySubarea);
	}		
}

/* Add a city/subarea to selected areas container:
 If adding a city, it will:
   1. Remove the city from left city list box.
   2. Update "citySubareaZipcodeList" object.
   3. Add the city to the right city/subarea container.
 If adding a subarea, it will:
   1. Highlight the subarea in the popup neighborhoods selector.
   2. Update "citySubareaZipcodeList" object.
   3. Add the subarea to the right city/subarea container.
*/
function addACitySubareaItem(objCitySubarea)
{
	
	// 2. Add the city to the right city/subarea container.
	citySubareaZipcodeList.addCitySubarea(objCitySubarea);
	// 3. Add the city to the right city/subarea container.
	citySubareaSelector.reloadItems();
	
	if(objCitySubarea.areaType == citySubareaType.City)
	{
		loadCityNeighborhoodsList(objCitySubarea.areaCode,objCitySubarea.areaName);
		// 1. Remove the city from left city list box.
		var list=ChangeElement("lbxCityList");
		for(var i = 0; i < list.options.length; i ++)
		{
			if(objCitySubarea.areaCode ==list.options[i].value)
			{
				list.remove(i);
				break;
			}
		}
		// Refresh school districts list for selected cities.
		SetUpdateSchoolDistrictTrue();
	}
}

// Add multiple city/subarea items.
// objCitySubareaList: array collection of CitySubareaObject.
function addCitySubareaItems(objCitySubareaList)
{
	for(var i = 0; i < objCitySubareaList.length; i ++)
	{
		citySubareaZipcodeList.addCitySubarea(objCitySubareaList[i]);
		if(objCitySubareaList[i].areaType == citySubareaType.City)
		{
			loadCityNeighborhoodsList(objCitySubareaList[i].areaCode,objCitySubareaList[i].areaName);
		}
	}
	citySubareaSelector.reloadItems();
	SetUpdateSchoolDistrictTrue();
	iGen.WebServices.Common.BindCity("", eval(propertySearchCurrentMetroArea),onBindCitySuccessed);
}
// Load saved cities and subareas, and add them to the city/subarea selector.
function loadSavedCitiesAndSubareas(citiesSubareasString)
{
	iGen.WebServices.Common.GetSavedSubAreaList(citiesSubareasString, onGetSavedSubAreaListSuccessed);
}
function onGetSavedSubAreaListSuccessed(result)
{
	if(result != null && result.Tables != 0)
	{
		var arrCitySubareaObj = new Array();
		for(var i = 0; i < result.Tables[0].Rows.length; i ++)
		{
			var citySubareaObj = new CitySubareaObject();
			citySubareaObj.areaCode = result.Tables[0].Rows[i].AreaCode;
			citySubareaObj.areaName = result.Tables[0].Rows[i].AreaName;
			citySubareaObj.cityCode = result.Tables[0].Rows[i].CityCode;
			citySubareaObj.cityName = result.Tables[0].Rows[i].CityName;
			citySubareaObj.state = result.Tables[0].Rows[i].State;
			citySubareaObj.areaType = parseInt(result.Tables[0].Rows[i].AreaType);
			arrCitySubareaObj.push(citySubareaObj);
		}
		addCitySubareaItems(arrCitySubareaObj);
	}
}

/* Remove a city/subarea from selected areas container:
 If removing a city, it will:
   1. Update "citySubareaZipcodeList" object.
   2. Remove the city from the right city/subarea container.
   3. Add the city to left city list box.
 If removing a subarea, it will:
   1. Unhighlight the subarea in the popup neighborhoods selector.
   2. Update "citySubareaZipcodeList" object.
   3. Remove the subarea from the right city/subarea container.
*/
function removeACitySubareaItem(areaCode, areaCityCode, areaType)
{
	// 1. Update "citySubareaZipcodeList" object.
	citySubareaZipcodeList.removeCitySubarea(areaCode, areaCityCode, areaType);		
	// 2. Remove the city from the right city/subarea container.
	citySubareaSelector.reloadItems();
	if(areaType == citySubareaType.City)
	{	
		// Close neighborhoods selector if the deleted city is in its list
		if(neighborhoodsSelector && neighborhoodsSelector.isCityInList(areaCode) == true)
		{
			neighborhoodsSelector.close();
		}
		// Remove the city's neighborhoods data in the neighborhoodsDataList.
		neighborhoodsDataList.removeNeighborhoodsData(areaCode);
		// 3. Add the city to left city list box.
		iGen.WebServices.Common.BindCity("", eval(propertySearchCurrentMetroArea),onBindCitySuccessed);
		// Refresh school districts list for selected cities.
		SetUpdateSchoolDistrictTrue();
	}
	else
	{
		if(neighborhoodsSelector)
		{
			neighborhoodsSelector.refreshHighlightItems();
		}
	}
	
}
// Clear all selected cities and subareas.
function clearAllCitySubareaItems()
{
	// Clear all objects in the citySubareaZipcodeList.
	citySubareaZipcodeList.clear();
	// Clear all items in the city/subarea selector.
	citySubareaSelector.clearItems();
	// Refresh school districts list for selected cities.
	SetUpdateSchoolDistrictTrue();
	// Refresh the city select box.
	iGen.WebServices.Common.BindCity("", eval(propertySearchCurrentMetroArea),onBindCitySuccessed);
	// Close neighborhoods selector.
	if(neighborhoodsSelector)
	{
		neighborhoodsSelector.close();
	}
	// Clear neighborhoods data in the neighborhoodsDataList.
	neighborhoodsDataList.clear();
}

function onBindCitySuccessed(result)
{
	if(result != null && result.Tables != 0 && result.Tables.length == 1)
	{		
		var list=ChangeElement("lbxCityList");		
		//clear items			
		while(list.options.length>0)
		{
			list.remove(0);					
		}
		var arrSelectedCities = citySubareaZipcodeList.getCityCodeList();
		var flag=false;
		for(var i = 0; i < result.Tables[0].Rows.length; i ++)
		{
			flag = false;
			var oOption = document.createElement("OPTION");			
			//find the selected city.If one item has been selected then don't add it anymore
			for(var k = 0; k < arrSelectedCities.length; k ++)
			{
				if(result.Tables[0].Rows[i].city_code==arrSelectedCities[k])
				{
					flag = true;
					break;
				}
			}		
			if(flag == false)		
			{
				var uAgent = window.navigator.userAgent;
				if(uAgent.indexOf("Firefox") != -1 || uAgent.indexOf("Netscape") != -1)//for FireFox and Netscape
					list.options.add(oOption);
				else
					list.add(oOption);
				oOption.value = result.Tables[0].Rows[i].city_code;
				oOption.innerHTML = result.Tables[0].Rows[i].city_name + ", " + result.Tables[0].Rows[i].stateCode;	
			}
		}
	}
}
// Show or hide the save search section content for main search.
function showHideSaveSearchSection()
{
	var linkShowHideSaveSearch = document.getElementById("linkShowHideSaveSearch");
	var divSaveSearchContainer = document.getElementById("divSaveSearchContainer");
	var divExpanderSaveSearch = document.getElementById("divExpanderSaveSearch");
	if(divSaveSearchContainer)
	{
		if(divSaveSearchContainer.style.display == "none")
		{
			divSaveSearchContainer.style.display = "";
			linkShowHideSaveSearch.innerHTML = "(Click to Hide)";
			divExpanderSaveSearch.className = "PropertySearchSectionExpanderOpen";
		}
		else
		{
			divSaveSearchContainer.style.display = "none";
			linkShowHideSaveSearch.innerHTML = "(Click to Show)";
			divExpanderSaveSearch.className = "PropertySearchSectionExpanderClose";
		}
	}
}
// Show or hide the advanced criteria section content for main search.
function showHideAdvancedCriteriaSection(isShow)
{
	var linkShowHideAdvancedCriteria = document.getElementById("linkShowHideAdvancedCriteria");
	var divAdvancedCriteriaContainer = document.getElementById("divAdvancedCriteriaContainer");
	var divExpanderAdvancedCriteria = document.getElementById("divExpanderAdvancedCriteria");
	if(divAdvancedCriteriaContainer)
	{
		if(isShow != true && isShow != false)
		{
			if(divAdvancedCriteriaContainer.style.display == "none")
			{
				 isShow = true;
			}
			else
			{
				isShow = false;
			}
		}
		var divMustHaveTitle = document.getElementById("divMustHaveTitle");
		var divNiceHaveTitle = document.getElementById("divNiceHaveTitle");
		if(isShow == true)
		{
			divAdvancedCriteriaContainer.style.display = "";
			linkShowHideAdvancedCriteria.innerHTML = "(Click to Hide)";
			divExpanderAdvancedCriteria.className = "PropertySearchSectionExpanderOpen";
			divMustHaveTitle.className = "PropertySearchMustHaveTitle";
			divNiceHaveTitle.className = "PropertySearchNiceHaveTitle";
			SetCookie(cookieKeys.MainSearchExpander, "1");
		}
		else
		{
			divAdvancedCriteriaContainer.style.display = "none";
			linkShowHideAdvancedCriteria.innerHTML = "(Click to Show)";
			divExpanderAdvancedCriteria.className = "PropertySearchSectionExpanderClose";
			divMustHaveTitle.className = "hideElement";
			divNiceHaveTitle.className = "hideElement";
			SetCookie(cookieKeys.MainSearchExpander, "0");
		}
	}
}
// Generate a property search name from the property search UI.
function GeneratePropertySearchNameFromUI()
{
	var selectedFirstCityName = citySubareaZipcodeList.getFirstCityName();
	var minBedrooms = properySearchUiParameterList.MinBedrooms;
	var minBathrooms = properySearchUiParameterList.MinBathrooms;
	var minPrice = properySearchUiParameterList.MinPrice;
	var maxPrice = properySearchUiParameterList.MaxPrice;
	return GeneratePropertySearchName(selectedFirstCityName, minBedrooms, minBathrooms, minPrice, maxPrice);
}
// Generate a property search name for save.
function GeneratePropertySearchName(selectedFirstCityName, minBedrooms, minBathrooms, minPrice, maxPrice)
{
	var searchName = "";
	if(eval(minBathrooms) > 4) 
	{
		minBathrooms = eval(minBathrooms) - 3.5;
	}
	if(minBathrooms == "4")
	{
		minBathrooms = "4+";
	}
	searchName = selectedFirstCityName + ", " + minBedrooms + "+Bed, " + minBathrooms + "+Bath";
	if(minPrice != "" || maxPrice != "")
	{
		searchName += ", " + minPrice + "-" + maxPrice;
	}
	return searchName;
}

// Get search criteria for display in email.
function getSearchCriteriaTextFromUI()
{
	var minBedrooms = properySearchUiParameterList.MinBedrooms;
	var minBathrooms = properySearchUiParameterList.MinBathrooms;
	var minPrice = properySearchUiParameterList.MinPrice;
	var maxPrice = properySearchUiParameterList.MaxPrice;
	
	var searchCriteria = "";	
	// Get selected city and subareas.
	searchCriteria += citySubareaZipcodeList.getCitySubareaNameStringList();
	searchCriteria += ". ";
	if(eval(minBathrooms) > 4) 
		minBathrooms = eval(minBathrooms) - 3.5;
	if(minBathrooms == "4")
		minBathrooms = "4+";
	searchCriteria += minBedrooms+"+Bedrooms, "+minBathrooms+"+Bathrooms, ";
	if( minPrice != "" || maxPrice != "")
	{
		searchCriteria += minPrice + "-" + maxPrice;
	}
	return searchCriteria;
}

function GetCity()//created by Sky Liu 2005-05-22. Modified by Joe, 11/12/2005. When user type in the top text box the listbox will get the city automatcily
{				
	var tb=ChangeElement("tbxcity");
	if(tb==null)
	{
		return;
	}				
	var list1=ChangeElement("lbxCityList");	
	var city=tb.value;
	var i;
	for(i=0;i<list1.options.length;i++)
	{
		var str=list1.options[i].text;
		if(str.substring(0,city.length).toLowerCase()==city.toLowerCase())
		{
			list1.selectedIndex=i;
			return;
		}
	}								
}

function GetSearchID(eID)
{
	var bsearchId = "";
	var eleId = "ucSearchID";
	if(eID != null)
		eleId = eID;
	if(ChangeElement(eleId)!=null && ChangeElement(eleId).innerHTML!="")
	{					
		bsearchId = ChangeElement(eleId).innerHTML;
	}				
	return bsearchId;
}

//auto check the mail notification preference when user select 
function AutoCheckPre()
{
	var cb=ChangeElement("chbxEmailUpdates");
	cb.checked=true;
}

// Receive enter key when user types into "City Selection" box.
// If one city is highlighted, and then user presses the enter key, the selected city will be added to the right box.
// Created by Andy Wan, Dec 5, 2005.
function citySelectEnter(e)
{
	var target;
	var key;
	
	if (window.event)
	{ 
		//for IE
		target = window.event.srcElement; 
		key = event.keyCode;
	} 
	else if (e)
	{ 
		//for Firefox
 		target = e.target; 
 		key = e.which;
	}
	else
	{
		return;
	}
	if(key==13&&(target.type== "text"||target.type =="password"))
	{
		//document.getElementById("btnFortbxcity").focus();
		addsubitem();
	}
}

// Update property search page after user logged in.
function PageUpdateForLogin()
{
	var divQuickRegisterInfo = ChangeElement("divQuickRegisterInfo");
	if(divQuickRegisterInfo)
	{
		divQuickRegisterInfo.style.display = "none";
	}
	var divQuickRegisterEmailContainer = ChangeElement("divQuickRegisterEmailContainer");
	if(divQuickRegisterEmailContainer)
	{
		divQuickRegisterEmailContainer.style.display = "none";
	}
	var tbxEmail = ChangeElement("tbxEmail");
	if(tbxEmail)
	{
		tbxEmail.style.display = "none";
	}
}
/* ---------------------------------------------------- For Refresh School District [BEGIN] ---------------------------------------------------- */
//For performance, I add two global variables "gCallDistrictAjaxNumber", "gChangeCityListNumber" to delay the ajax call.
//In this situation, the ajax call will be reduce to once per time section(1500 now).
function SetUpdateSchoolDistrictTrue()
{
	gChangeCityListNumber += 1;
	var tempNum = gChangeCityListNumber;
	window.setTimeout(function(){SetTimeoutUpdateSchoolDistrict(tempNum);}, 1500);
}

function SetTimeoutUpdateSchoolDistrict(changeCityListNumber)
{
	if(gCallDistrictAjaxNumber < changeCityListNumber)
	{
		gCallDistrictAjaxNumber = gChangeCityListNumber;
		var cityList = citySubareaZipcodeList.getCityCodeList().join(",");
		iGen.WebServices.schools.GetElementaryHighSchoolDistrictsByCities(cityList, onGetElementaryHighSchoolDistrictsByCitiesSuccessed);
	}
}

function onGetElementaryHighSchoolDistrictsByCitiesSuccessed(result,userContext,methodName)
{
	if(result != null && result.Tables.length >0)
	{
		RefreshDistrictsByAjaxReturn(result.Tables[0], 'ddlElementaryDistrict', 'Elementary', 'hdnElementarySchoolDistricts');
		RefreshDistrictsByAjaxReturn(result.Tables[1], 'ddlHighSchoolDistrict', 'High', 'hdnHighSchoolDistricts');		
	}
	else
	{
		RefreshDistrictsByAjaxReturn(null, 'ddlElementaryDistrict', 'Elementary', 'hdnElementarySchoolDistricts');
		RefreshDistrictsByAjaxReturn(null, 'ddlHighSchoolDistrict', 'High', 'hdnHighSchoolDistricts');		
	}
}

function RefreshDistrictsByAjaxReturn(resValue, districtContainerId, schoolType, hdnSelectedDistrictValueContainerId)
{
	var listD = ChangeElement(districtContainerId);
	var i = 0;
	while( listD.options.length > 0 )
	{
		listD.remove(0); //remove items first.
	}
	var titleOption = document.createElement("OPTION");
	var uAgent = window.navigator.userAgent;
	//Add default selected item first. No selection is all selected,
	if( uAgent.indexOf("Firefox") != -1 || uAgent.indexOf("Netscape") != -1 )
		listD.options.add( titleOption );
	else
		listD.add( titleOption );
	titleOption.value = "All";
		
	if(resValue != null &&  resValue.Rows.length >0)
	{
		titleOption.value = "All";
		titleOption.innerHTML = "All " + schoolType + " School Districts";	
		for( i = 0; i < resValue.Rows.length; i++ )
		{
			var oOption = document.createElement("OPTION");
			if( uAgent.indexOf("Firefox") != -1 || uAgent.indexOf("Netscape") != -1 )
				listD.options.add( oOption );
			else
				listD.add( oOption );
			oOption.value = resValue.Rows[i].dist_code;
			oOption.innerHTML = resValue.Rows[i].dist_name;//district name
		}
		
		//Check is revise or not. Revise selected school districts if it is.
		var selectedDistrictsValue = GetSelectedDistrictsValue(hdnSelectedDistrictValueContainerId);
		if(selectedDistrictsValue != null)
			ReviseSchoolDistricts(selectedDistrictsValue, districtContainerId);
	}
	else
		titleOption.innerHTML = "No " + schoolType + " School Districts";
}

function GetSelectedDistrictsValue(hdnSelectedDistrictValueContainerId)
{
	var hdnSelectedDistricts = ChangeElement(hdnSelectedDistrictValueContainerId);
	if(hdnSelectedDistricts != null && hdnSelectedDistricts.value != null && hdnSelectedDistricts.value !="" && Trim(hdnSelectedDistricts.value) != "")
	{
		var selectedDistricts = hdnSelectedDistricts.value;
		//Clear the selected school district value after revise.
		hdnSelectedDistricts.value = "";
		return selectedDistricts;
	}
	else
		return null;
}

function ReviseSchoolDistricts(selectedDistrictsValue, districtContainerId)
{
	var ddlDistrict = ChangeElement(districtContainerId);
	for(var i=0; i<ddlDistrict.options.length; i++)
	{
		if(selectedDistrictsValue == ddlDistrict.options[i].value)
		{
			ddlDistrict.selectedIndex = i;
			break;
		}
	}
}

//Save selected school districts in html hidden controls before search
function SetSelectedSchoolDistrict()
{
	var hdnElementaryDistrict = ChangeElement("hdnElementarySchoolDistricts");
	var hdnHighSchoolDistrict = ChangeElement("hdnHighSchoolDistricts");
	
	var ddlElementaryDistrict = ChangeElement("ddlElementaryDistrict");
	var ddlHighSchoolDistrict = ChangeElement("ddlHighSchoolDistrict");
	if(hdnElementaryDistrict != null && ddlElementaryDistrict != null)
		hdnElementaryDistrict.value = ddlElementaryDistrict.options[ddlElementaryDistrict.selectedIndex].value;
	if(hdnHighSchoolDistrict != null && ddlHighSchoolDistrict != null)
		hdnHighSchoolDistrict.value = ddlHighSchoolDistrict.options[ddlHighSchoolDistrict.selectedIndex].value;
}
/* ---------------------------------------------------- For Refresh School District [END] ---------------------------------------------------- */
/* ---------------------------------------------------- For PropertySearch [BEGIN] ---------------------------------------------------- */
function GetElementId(eleId)
{			   
	return  "USC_"+eleId;	
}

function GetElementName(eleId)
{			   
	return  "USC$"+eleId;	
}

function GetEditSearchId()
{
    var hdnAlreadySavedSearchId = ChangeElement("hdnAlreadySavedSearchId");
    if(hdnAlreadySavedSearchId)
    {
        return hdnAlreadySavedSearchId.value;
    }
    else
    {
        return null;
    }
}

function GetPriceString(controlId)
{
    return document.getElementById(controlId).value.replace(/\$|\,/g, '');
}

function GetPropertyTypeValue()
{
    var singleFamilyHouse=document.getElementById(GetElementId("ckblPropertyType_0"));
    var condoOrTownhouse=document.getElementById(GetElementId("ckblPropertyType_1"));
    
    if((singleFamilyHouse.checked&&condoOrTownhouse.checked)||(!singleFamilyHouse.checked&&!condoOrTownhouse.checked))
    {
        return "0";
    }else if(singleFamilyHouse.checked)
    {
        return "1";
    }else(condoOrTownhouse.checked)
    {
        return "2";   
    }
}

function GetSearchName()
{
    var isAutoSaveSearch=document.getElementById(GetElementId("ckbIsAutoSaveSearch")).checked?false:true;
    var searchName=document.getElementById(GetElementId("tbxSearchName")).value;
    
    if(isAutoSaveSearch || searchName==EmptyString.Value)
    {
        return GeneratePropertySearchNameFromUI();
    }
    else
    {
        return searchName;
    }
}

function TextBoxParameter(controlId,key,mustOrNiceToHaveRadioButtonName)
{
    this.controlId=controlId;
    this.key=key;
    this.mustOrNiceToHaveRadioButtonName=mustOrNiceToHaveRadioButtonName;
    
    if(typeof TextBoxParameter._initialized=="undefined")
    {        
        TextBoxParameter.prototype.GetXMLString=function ()
        {
            var inputValue=document.getElementById(this.controlId).value;
            if(inputValue=="") return inputValue;            
            
            if(this.mustOrNiceToHaveRadioButtonName==null ||this.mustOrNiceToHaveRadioButtonName==undefined)
            {
                return GetParameterXMLItemString(this.key,inputValue);
            }
            else
            {
                var mustHaveValue=this.GetMustOrNiceToHaveValue();
                return GetParameterXMLItemString(this.key,inputValue,mustHaveValue);
			}
        };
        
        TextBoxParameter.prototype.GetMustOrNiceToHaveValue=function ()
        {
            var mustOrNiceToHaveRadioButtons=document.getElementsByName(this.mustOrNiceToHaveRadioButtonName);
            return mustOrNiceToHaveRadioButtons[0].checked;
        };
        
        TextBoxParameter.prototype.GetValue=function ()
        {
			return document.getElementById(this.controlId).value;
        };
        
        TextBoxParameter._initialized=true;
    }
}

function RadioButtonParameter(controlName,key,mustOrNiceToHaveRadioButtonName,firstItemAavailable)
{
    this.controlName=controlName;
    this.key=key;
    this.mustOrNiceToHaveRadioButtonName=mustOrNiceToHaveRadioButtonName;
    this.firstItemAavailable=firstItemAavailable;

    if(typeof RadioButtonParameter._initialized=="undefined")
    {        
        RadioButtonParameter.prototype.GetXMLString=function ()
        {
            var inputValue=EmptyString.Value;
            var radioButtonList=document.getElementsByName(this.controlName);
            if(radioButtonList[0].checked && !this.firstItemAavailable) return EmptyString.Value;
            
            for(var index=0;index<radioButtonList.length;index++)
            {
                if(radioButtonList[index].checked)
                {
                    inputValue=radioButtonList[index].value;
                    break;
                }
            }

            if(this.mustOrNiceToHaveRadioButtonName==null ||this.mustOrNiceToHaveRadioButtonName==undefined)
            {
                return GetStringParameterXMLItemString(this.key,inputValue);
            }
            else
            {
                var mustHaveValue=this.GetMustOrNiceToHaveValue();
                return GetParameterXMLItemString(this.key,inputValue,mustHaveValue);
            }                    
        };
        
        RadioButtonParameter.prototype.GetMustOrNiceToHaveValue=function ()
        {
            var mustOrNiceToHaveRadioButtons=document.getElementsByName(this.mustOrNiceToHaveRadioButtonName);
            return mustOrNiceToHaveRadioButtons[0].checked;
        };
        
        RadioButtonParameter.prototype.GetValue=function ()
        {			
			var radioButtonList=document.getElementsByName(this.controlName);              
			for(var index=0;index<radioButtonList.length;index++)
			{
				if(radioButtonList[index].checked)
				{
					return radioButtonList[index].value;
				}
			}        
        };
        
        RadioButtonParameter._initialized=true;
    }
}

function CheckBoxParameter(controlId,key,mustOrNiceToHaveRadioButtonName)
{
    this.controlId=controlId;
    this.key=key;
    this.mustOrNiceToHaveRadioButtonName=mustOrNiceToHaveRadioButtonName;
    
    if(typeof CheckBoxParameter._initialized=="undefined")
    {        
        CheckBoxParameter.prototype.GetXMLString=function ()
        {
            var inputValue=document.getElementById(this.controlId).checked?true:false;
            if(!inputValue) return EmptyString.Value;

            if(this.mustOrNiceToHaveRadioButtonName==null ||this.mustOrNiceToHaveRadioButtonName==undefined)
            {
                return GetParameterXMLItemString(this.key,inputValue,this.parameterType);
            }
            else
            {
                var mustHaveValue=this.GetMustOrNiceToHaveValue();
                return GetParameterXMLItemString(this.key,inputValue,mustHaveValue);
            }                    
        };
        
        CheckBoxParameter.prototype.GetMustOrNiceToHaveValue=function ()
        {
            var mustOrNiceToHaveRadioButtons=document.getElementsByName(this.mustOrNiceToHaveRadioButtonName);
            return mustOrNiceToHaveRadioButtons[0].checked;
        };
        
        CheckBoxParameter.prototype.GetValue=function ()
        {			
			return document.getElementById(this.controlId).value=='on'?true:false;
        };
        
        CheckBoxParameter._initialized=true;
    }
}

function ProperySearchUiParameterList()
{
    SelectParameterList.call(this);
}
ProperySearchUiParameterList.prototype = new SelectParameterList();
ProperySearchUiParameterList.prototype.Update = function()
{
    this.PropertyParameters = new Array();                              
    this.UserParameters = new Array();
    /*********************************** House Search Parameter Start*******************************************/
    
    this.UserParameters["userID"] = new StringParameter(GetUserID(),"userID");
    this.UserID=this.UserParameters["userID"].GetValue();					
	
    this.UserParameters["searchId"] = new StringParameter(GetEditSearchId(),"searchId");
    this.searchId=this.UserParameters["searchId"].GetValue();								
	
    this.PropertyParameters["citySubAreaZipcodeString"] = new StringParameter(citySubareaZipcodeList.getCitySubareaZipcodeStringList(),"citySubAreaZipcodeString");
    this.CitySubAreaZipcodeString=this.PropertyParameters["citySubAreaZipcodeString"].GetValue();                            

    this.PropertyParameters["listingType"] = new RadioButtonParameter(GetElementName("rdblListingType"),"listingType",null,true);
    this.ListingType=this.PropertyParameters["listingType"].GetValue(); 
	
    this.PropertyParameters["propertyType"] = new StringParameter(GetPropertyTypeValue(),"propertyType");
    this.PropertyType=this.PropertyParameters["propertyType"].GetValue();
    
    this.PropertyParameters["minBedrooms"] = new RadioButtonParameter(GetElementName("rdblBedrooms"),"minBedrooms",null,false);
    this.MinBedrooms=this.PropertyParameters["minBedrooms"].GetValue();
    
    this.PropertyParameters["minBathrooms"] = new RadioButtonParameter(GetElementName("rdblBathrooms"),"minBathrooms",null,true);
    this.MinBathrooms=this.PropertyParameters["minBathrooms"].GetValue();
    
    this.PropertyParameters["minPrice"] = new StringParameter(GetPriceString(GetElementId("tbxMinPrice")),"minPrice");
    this.MinPrice=this.PropertyParameters["minPrice"].GetValue();
    
    this.PropertyParameters["maxPrice"] = new StringParameter(GetPriceString(GetElementId("tbxMaxPrice")),"maxPrice");
    this.MaxPrice=this.PropertyParameters["maxPrice"].GetValue();
    
    /*********************************** House Search Parameter End*******************************************/        


    /*********************************** Save Parameter Start*******************************************/
    
    this.UserParameters["isAutoSaveSearch"] = new StringParameter(document.getElementById(GetElementId("ckbIsAutoSaveSearch")).checked?'false':'true',"isAutoSaveSearch");  
    this.IsAutoSaveSearch=this.UserParameters["isAutoSaveSearch"].GetValue();
    
    this.UserParameters["searchName"] = new StringParameter(GetSearchName(),"searchName");   
    this.SearchName=this.UserParameters["searchName"].GetValue();
    
    this.UserParameters["isEmailUpdates"] = new StringParameter(document.getElementById(GetElementId("ckbIsEmailUpdates")).checked?'true':'false',"isEmailUpdates"); 
    this.IsEmailUpdates=this.UserParameters["isEmailUpdates"].GetValue();
    
    this.UserParameters["emailUpdatesFrequency"] = new DropDownListParameter(GetElementId("ddlEmailUpdatesFrequency"),"emailUpdatesFrequency",null,true);  
    this.EmailUpdatesFrequency=this.UserParameters["emailUpdatesFrequency"].GetValue();
    
    /*********************************** Save Parameter End*******************************************/
    
    
    
    /*********************************** Advanced Parameter Start*******************************************/
    
    this.PropertyParameters["minSquareFeet"] = new TextBoxParameter(GetElementId("tbxMinSquareFeet"),"minSquareFeet",GetElementName("rdblMinSquareFeetMustOrNiceHave"));
    this.MinSquareFeet=this.PropertyParameters["minSquareFeet"].GetValue();
    
    this.PropertyParameters["minLotSize"] = new TextBoxParameter(GetElementId("tbxMinLotSize"),"minLotSize",GetElementName("rdblMinLotSizeMustOrNiceHave"));
    this.MinLotSize=this.PropertyParameters["minLotSize"].GetValue();
    
    this.PropertyParameters["numberOfStories"] = new DropDownListParameter(GetElementId("ddlStoriesNumber"),"numberOfStories",GetElementName("rdblNumberOfStoriesMustOrNiceHave"),false);
    this.NumberOfStories=this.PropertyParameters["numberOfStories"].GetValue();
    
    this.PropertyParameters["minDaysOnMarket"] = new TextBoxParameter(GetElementId("tbxDaysOnMarketMin"),"minDaysOnMarket",GetElementName("rdblDaysOnMarketMustOrNiceHave"));
    this.MinDaysOnMarket=this.PropertyParameters["minDaysOnMarket"].GetValue();
    
    this.PropertyParameters["maxDaysOnMarket"] = new TextBoxParameter(GetElementId("tbxDaysOnMarketMax"),"maxDaysOnMarket",GetElementName("rdblDaysOnMarketMustOrNiceHave"));
    this.MaxDaysOnMarket=this.PropertyParameters["maxDaysOnMarket"].GetValue();
    
    this.PropertyParameters["minYearBuilt"] = new TextBoxParameter(GetElementId("tbxYearBuiltMin"),"minYearBuilt",GetElementName("rdblYearBuiltMustOrNiceHave"));
    this.MinYearBuilt=this.PropertyParameters["minYearBuilt"].GetValue();
    
    this.PropertyParameters["maxYearBuilt"] = new TextBoxParameter(GetElementId("tbxYearBuiltMax"),"maxYearBuilt",GetElementName("rdblYearBuiltMustOrNiceHave"));
    this.MaxYearBuilt=this.PropertyParameters["maxYearBuilt"].GetValue();
        
    this.PropertyParameters["elementaryDistrict"] = new DropDownListParameter(GetElementId("ddlElementaryDistrict"),"elementaryDistrict",GetElementName("rdblElementaryDistrictMustOrNiceHave"),false);
    this.ElementaryDistrict=this.PropertyParameters["elementaryDistrict"].GetValue();
    
    this.PropertyParameters["highSchoolDistrict"] = new DropDownListParameter(GetElementId("ddlHighSchoolDistrict"),"highSchoolDistrict",GetElementName("rdblHighSchoolDistrictMustOrNiceHave"),false);
    this.HighSchoolDistrict=this.PropertyParameters["highSchoolDistrict"].GetValue();
    
    this.PropertyParameters["garage"] = new RadioButtonParameter(GetElementName("rdblGarage"),"garage",GetElementName("rdblGarageMustOrNiceHave"),false);
    this.Garage=this.PropertyParameters["garage"].GetValue();
    
    this.PropertyParameters["hasPhotos"] = new CheckBoxParameter(GetElementId("ckbHavePhotos"),"hasPhotos",GetElementName("rdblPhotoMustOrNiceHave")); 
    this.HasPhotos=this.PropertyParameters["hasPhotos"].GetValue();
    
    /*********************************** Advanced Parameter End*******************************************/
    
    /*********************************** Room Option Start*******************************************/
    
    this.PropertyParameters["separateFamilyRoom"] = new CheckBoxParameter(GetElementId("ckblRoomOptions_0"),"separateFamilyRoom",GetElementName("rdblRoomOptionsMustOrNiceHave"));
    this.SeparateFamilyRoom=this.PropertyParameters["separateFamilyRoom"].GetValue();
    
    this.PropertyParameters["formalDiningRoom"] = new CheckBoxParameter(GetElementId("ckblRoomOptions_1"),"formalDiningRoom",GetElementName("rdblRoomOptionsMustOrNiceHave"));
    this.FormalDiningRoom=this.PropertyParameters["formalDiningRoom"].GetValue();
    
    this.PropertyParameters["library"] = new CheckBoxParameter(GetElementId("ckblRoomOptions_2"),"library",GetElementName("rdblRoomOptionsMustOrNiceHave"));
    this.Library=this.PropertyParameters["library"].GetValue();
    
    this.PropertyParameters["denOrStudy"] = new CheckBoxParameter(GetElementId("ckblRoomOptions_3"),"denOrStudy",GetElementName("rdblRoomOptionsMustOrNiceHave"));
    this.DenOrStudy=this.PropertyParameters["denOrStudy"].GetValue();
    
    this.PropertyParameters["fullBasement"] = new CheckBoxParameter(GetElementId("ckblRoomOptions_4"),"fullBasement",GetElementName("rdblRoomOptionsMustOrNiceHave"));
    this.FullBasement=this.PropertyParameters["fullBasement"].GetValue();
    
    this.PropertyParameters["separateLivingUnit"] = new CheckBoxParameter(GetElementId("ckblRoomOptions_5"),"separateLivingUnit",GetElementName("rdblRoomOptionsMustOrNiceHave"));
	this.SeparateLivingUnit=this.PropertyParameters["separateLivingUnit"].GetValue();
    
    /*********************************** Room Option End*******************************************/
    
    /*********************************** Style Option Start*******************************************/
    
    this.PropertyParameters["cabin"] = new CheckBoxParameter(GetElementId("ckblStyleOptions_0"),"cabin",GetElementName("rdblStyleOptionsMustOrNiceHave"));
    this.Cabin=this.PropertyParameters["cabin"].GetValue();
    
    this.PropertyParameters["capeCod"] = new CheckBoxParameter(GetElementId("ckblStyleOptions_1"),"capeCod",GetElementName("rdblStyleOptionsMustOrNiceHave"));
    this.CapeCod=this.PropertyParameters["capeCod"].GetValue();
    
    this.PropertyParameters["colonial"] = new CheckBoxParameter(GetElementId("ckblStyleOptions_2"),"colonial",GetElementName("rdblStyleOptionsMustOrNiceHave"));
    this.Colonial=this.PropertyParameters["colonial"].GetValue();
    
    this.PropertyParameters["contemporary"] = new CheckBoxParameter(GetElementId("ckblStyleOptions_3"),"contemporary",GetElementName("rdblStyleOptionsMustOrNiceHave"));
    this.Contemporary=this.PropertyParameters["contemporary"].GetValue();                                
    
    this.PropertyParameters["cottageOrBungalow"] = new CheckBoxParameter(GetElementId("ckblStyleOptions_4"),"cottageOrBungalow",GetElementName("rdblStyleOptionsMustOrNiceHave"));
    this.CottageOrBungalow=this.PropertyParameters["cottageOrBungalow"].GetValue();
    
    this.PropertyParameters["ranch"] = new CheckBoxParameter(GetElementId("ckblStyleOptions_5"),"ranch",GetElementName("rdblStyleOptionsMustOrNiceHave"));
    this.Ranch=this.PropertyParameters["ranch"].GetValue();
    
    this.PropertyParameters["spanish"] = new CheckBoxParameter(GetElementId("ckblStyleOptions_6"),"spanish",GetElementName("rdblStyleOptionsMustOrNiceHave"));
    this.Spanish=this.PropertyParameters["spanish"].GetValue();
    
    this.PropertyParameters["traditional"] = new CheckBoxParameter(GetElementId("ckblStyleOptions_7"),"traditional",GetElementName("rdblStyleOptionsMustOrNiceHave"));
    this.Traditional=this.PropertyParameters["traditional"].GetValue();
    
    this.PropertyParameters["tudor"] = new CheckBoxParameter(GetElementId("ckblStyleOptions_8"),"tudor",GetElementName("rdblStyleOptionsMustOrNiceHave"));
    this.Tudor=this.PropertyParameters["tudor"].GetValue();
    
    this.PropertyParameters["victorian"] = new CheckBoxParameter(GetElementId("ckblStyleOptions_9"),"victorian",GetElementName("rdblStyleOptionsMustOrNiceHave"));
	this.Victorian=this.PropertyParameters["victorian"].GetValue();
    
    /*********************************** Style Option End*******************************************/
}

function DoSearch()
{
	if(validateAllInputsValues())
	{
		divSearchCount.innerHTML='Loading';
		var divLoadingIcon = document.getElementById("divLoadingIcon");
		divLoadingIcon.className = "SearchMatchLoadingShow";
		SetFinalSearchArea();
		SetSelectedSchoolDistrict();
		var objEmail = ChangeElement("tbxEmail");		
		var xmlParameter=properySearchUiParameterList.GetXMLString();
		iGen.WebServices.Common.DoSearch(xmlParameter,objEmail.value,onDoSearchSuccessed);		
	}
}

function onDoSearchSuccessed(result)
{
	if(result != null&& Trim(result) != "")
	{
		ShowSearchResult(result);
	}
}

var callGetMatchedCountMethodCount=0;

function GetMatchedCount()
{	
	var xmlParameter=properySearchUiParameterList.GetXMLString();		
	if(lastSelectXmlParameterString==xmlParameter)return;	
	if(properySearchUiParameterList.CitySubAreaZipcodeString==EmptyString.Value)
	{
		onGetMatchedCountSuccessed();
		return;
	}

	callGetMatchedCountMethodCount+=1;
	if(callGetMatchedCountMethodCount!=1 && callGetMatchedCountMethodCount<5)return;	
	callGetMatchedCountMethodCount=1;
	lastSelectXmlParameterString=xmlParameter;
	divSearchCount.innerHTML='Calculating';
	var divLoadingIcon = document.getElementById("divLoadingIcon");
	divLoadingIcon.className = "SearchMatchLoadingShow";
	iGen.WebServices.Common.GetMatchedCount(xmlParameter,onGetMatchedCountSuccessed);	
}

function onGetMatchedCountSuccessed(result)
{
	var searchCount = 0;
	if(result!=null)
	{
		searchCount = result;
	}	
	var divSearchCount=document.getElementById('divSearchCount')
	divSearchCount.innerHTML=searchCount + ' Matches';
	var divLoadingIcon = document.getElementById("divLoadingIcon");
	divLoadingIcon.className = "SearchMatchLoadingHide";
	
	callGetMatchedCountMethodCount=0;
}

function TurnToSearchResultPage(searchIDString)
{
	var url="";
	var relativePath = GetRelativePath2();
	url = relativePath + "customsearchresults.aspx?searchid=" +searchIDString;
	if(window.location.href.getQueryString("userid")!=null)
	{
		url += "&userid=" + window.location.href.getQueryString("userid");
	}
	url += "&logPage=CUSTOM_SEARCH_RESULT&logSearch=custom";
	url+=GetIsSavedUrlString();
	url+=GetEmailFrequentlyUrlString();
	url += "&highPref=1";
	window.location.href = url;
}

function ShowSearchResult(emailStatusAndSearchID)
{
	//user not need updates emails.
	if(emailStatusAndSearchID.indexOf(':') <= 0)
	{
		TurnToSearchResultPage(emailStatusAndSearchID);
		return true;
	}
	
	//user wants updates emails.	
	var emailStatus = emailStatusAndSearchID.substring(0, emailStatusAndSearchID.indexOf(':'));
	var returnedSearchId = emailStatusAndSearchID.substring(emailStatusAndSearchID.indexOf(':')+1, emailStatusAndSearchID.length);
	if(returnedSearchId == undefined || returnedSearchId == null)
		return false;
		
	switch(emailStatus)
	{
		case "EmailWrongFormat": 
			alert('Your E-mail Address is Invalid. Please re-enter.');
			return false;
		case "InvalidEmail": 
			alert('This email address you entered is not receiving emails. Please re-enter.');
			return false;
		case "RegisterFailed":
			alert('Regist failed!');
			return false;
			
		case "LoggedIn":
			alert("Your search is saved, and you will receive periodic property updates.");
			TurnToSearchResultPage(returnedSearchId);
			break;				
		case "RegisteredNotLoggedIn":
			alert("Your search is saved, and you will receive periodic property updates.");
			TurnToSearchResultPage(returnedSearchId);
			break;	
		case "NeedActive":
			alert("You are now signed up to receive email updates for this search.");
			TurnToSearchResultPage(returnedSearchId);
			return;
		case "NewlyRegister":
			alert("Thanks for signing up. Please click the activation link in the email that we just sent to the email address you provided.");
			TurnToSearchResultPage(returnedSearchId);
			return;
			
		default:
			alert('Failed. Please retry.');
			return false;
	}
}


function GetIsSavedUrlString()
{
	var isSaved=document.getElementById(GetElementId("ckbIsAutoSaveSearch")).checked
	if(isSaved)
	{
		return "&isSaved=1";
	}
	return EmptyString.Value;
}

function GetEmailFrequentlyUrlString()
{
	var isSaved=document.getElementById(GetElementId("ckbIsAutoSaveSearch")).checked
	if(isSaved)
	{
		var emailFrequently=document.getElementById(GetElementId("ddlEmailUpdatesFrequency"))
		var emailFrequentlyValueString=emailFrequently.options[emailFrequently.selectedIndex].value
		return "&emailFreq=" + emailFrequentlyValueString;
	}
	return EmptyString.Value;
}

/* ---------------------------------------------------- For PropertySearch [END] ---------------------------------------------------- */
// Show neighorhoods popup for all selected cities.
function showNeighborhoodsForAllSelectedCities()
{
	// Check the selected cities.
	if(citySubareaZipcodeList.lists.length == 0)
	{
		alert("Please select at least one city.");
		return;
	}
	var selectedCities = citySubareaZipcodeList.getCityCodeList().join(',');
	neighborhoodsSelector = new NeighborhoodsSelector(selectedCities);
	neighborhoodsSelector.top = 205;
	if(isAgentSendEmailPage)
	{
		neighborhoodsSelector.top = "585";
	}
	neighborhoodsSelector.show();
}

function showNearbyCities()
{
	var arrayCityCodeList = citySubareaZipcodeList.getCityCodeList();
	if(arrayCityCodeList != null && arrayCityCodeList.length > 0)
		ShowNearbyCitiesPopup(arrayCityCodeList);
	else
		alert("Please select at least one city.");
}

function ShowNearbyCitiesPopup(arrayCityCodeList)
{
	var cityCodes = arrayCityCodeList.join(',');
	
	var popShowNearbyCities = new popUpWindow();
	popShowNearbyCities.width = "430";
	popShowNearbyCities.height = "415";
	popShowNearbyCities.titleBar.foreColor = "#ffffff";
	popShowNearbyCities.titleBar.backgroundColor = "#2A4597";
	popShowNearbyCities.titleBar.innerHTML = "Nearby Cities";
	popShowNearbyCities.bodyContainerTypeValue = gWebPath + "showNearbyCities.aspx?cityCodes=" + cityCodes;
	popShowNearbyCities.body.pageIframeScrolling = "auto";
	popShowNearbyCities.show();
}		

function SetFinalSearchArea()
{

	var objFinalCitySubAreaZipcodeString = ChangeElement("hdnFinalCitySubareaString");
	if(objFinalCitySubAreaZipcodeString != undefined && objFinalCitySubAreaZipcodeString != null)
		objFinalCitySubAreaZipcodeString.value = citySubareaZipcodeList.getCitySubareaZipcodeStringList();
}
function loadCityNeighborhoodsList(cityCode,cityName)
{
	if(neighborhoodsDataList.lists.length > 16)
	{
		return;
	}
	if(neighborhoodsDataList.isCityNeighborhoodsDataIncluded(cityCode))
	{
		return;
	}
	neighborhoodsDataList.appendCity(cityCode, cityName);
}

function GetUserID()
{
	var userid = "";
	//when manager or management or agent view and change his client's search, Juana
	var hdnUserID = ChangeElement("hdnUserID");
	if(hdnUserID !=null && hdnUserID.value != "")
		userid = hdnUserID.value;
	else
	{
		// The userid is now saved at pageheader user control.
		// Modified by Andy Wan, Jan 17, 2006.
		// Modified by Joe, Jan 19, 2006. Note: Id is pHeader_txtUserID, not pHeader:txtUserID.
		if(document.getElementById("pHeader_txtUserID") != null)
			userid = document.getElementById("pHeader_txtUserID").value;
	}
	return userid;
}
/* ==================================================== DOM manipulation [BEGIN] ==================================================== */

function docSearchx()
{
	var latitude = document.getElementById("uhdLatitude").value;
	var longitude = document.getElementById("uhdLongitude").value;	
	var RBAddress = "";
	if( document.getElementById("RBAddress8").checked )
		RBAddress = "0.00180923/0.002296";
	if( document.getElementById("RBAddress4").checked )
		RBAddress = "0.00361847/0.0045919";
	if( document.getElementById("RBAddress2").checked )
		RBAddress = "0.00723694/0.0091838";
	if( document.getElementById("RBAddress1").checked )
		RBAddress = "0.01447388/0.0091838";		
		
    iGen.WebServices.PropertySearch.DoAddressSearch(latitude, longitude, RBAddress,onDoAddressSearchSuccessed);
}

function onDoAddressSearchSuccessed(result,userContext,methodName)
{
    var r = result;
	if( r == null || r == "0" )
	{
		alert( "Sorry, no houses match the address you entered.  Please change the address and try again." );
		return false;
	}
	if( r.length > 6 )
	{
		window.location.href = "search_detail.aspx?igen_key="+ r;
		return false;
	}
	if( r == "s" )
	{
		window.location.href = "searchresults.aspx?addressSearch=1";
		return false;
	}
}

// Define property search types.
var PropertySearchType = {MainSearch: 0, MlsNumberSearch: 1, AddressSearch: 2};
// Set the property search type of property search page, and save it to a hidden control "hdnLastPropertySearchType".
function SetPropertySearchType(propertySearchType)
{
    var hdnLastPropertySearchType = document.getElementById("hdnLastPropertySearchType");
    if(hdnLastPropertySearchType)
    {
        hdnLastPropertySearchType.value = propertySearchType;
    }
}
// Get the property search type of property search page, which is saved into a hidden control "hdnLastPropertySearchType".
function GetPropertySearchType()
{
    var hdnLastPropertySearchType = document.getElementById("hdnLastPropertySearchType");
    if(hdnLastPropertySearchType)
    {
        return hdnLastPropertySearchType.value;
    }    
}