/// <reference path="MicrosoftAjax.js"/>
// From Page header control
var gdays_isNew    = 7;
var gArrMlsDbList = new Array("100", "110", "12", "101", "102", "201", "202", "203", "204", "210", "300", "310", "205", "701", "402", "401", "403", "421", "411", "412", "413", "414", "206", "104", "431", "432", "433", "491", "471", "461", "472", "481", "482", "451", "441", "511", "521", "522", "531", "541", "551", "561", "571", "572", "573", "581", "591", "601", "611", "651", "811", "812", "821", "841");
var gArrMetroAreaList = new Array("1", "20", "30", "31", "32", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "65", "66", "67", "68", "69", "70", "71", "72", "73", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "91");
var gisUseNewADBanner = false;
var gListingTypeForMap= 0;
var gCtlIdPrefix = {MainContent:"ctl_main_", PageHeader:"ctl_pHeader_", LeftNav:"ctl_leftNav_", MlsCopyRight:"ctl_additional_mlsCopyRight_", ucCustomSearch: "ctl_main_USC_", AgentNav:"ctl_AgentNav1_",Master:"ctl_"};
var gCtlNamePrefix = {MainContent:"ctl$main$", ucCustomSearch:"ctl$main$USC$"};
var gWebPath = "http://www.movoto.com/";
if(document.getElementById(gCtlIdPrefix.PageHeader + "hdRPath"))
{
    gWebPath = document.getElementById(gCtlIdPrefix.PageHeader + "hdRPath").value;
}
/* ************************************
 * Array "arrMlsLogos" contains the logo note and logo image file path for covered mls systems.
 * For "logoImagePath": if the logo images location is "images/logo_" + MlsDb value + ".gif", 
 *   you can set the value to blank, because the "GetMLSLogosImgPath_Pri" method will auto return the path for this case;
 *   otherwise, you should provide the actual image location here.
 * For "logoNote": You can see the "GetMLSLogosNote_Pri" for detail.
 * ************************************/
var gArrMlsLogos = new Array();
gArrMlsLogos["100"] = {logoNote:"",logoImagePath:"images/lo_ble_logo_100.gif"};
gArrMlsLogos["110"] = {logoNote:"San Francisco"};
gArrMlsLogos["12"] = {logoNote:"Paragon"};
gArrMlsLogos["101"] = {logoNote:"NORCAL"};
gArrMlsLogos["102"] = {logoNote:"MetroList"};
gArrMlsLogos["201"] = {logoNote:"Greater South Bay"};
gArrMlsLogos["202"] = {logoNote:"MRMLS"};
gArrMlsLogos["203"] = {logoNote:"SoCAL"};
gArrMlsLogos["204"] = {logoNote:"CLAW"};
gArrMlsLogos["210"] = {logoNote:"Sandicor"};
gArrMlsLogos["300"] = {logoNote:"H3MLS"};
gArrMlsLogos["310"] = {logoNote:"MRIS"};
gArrMlsLogos["205"] = {logoNote:"i-Tech"};
gArrMlsLogos["701"] = {logoNote:"NewHomeSource"};
gArrMlsLogos["402"] = {logoNote:"NTREIS"};
gArrMlsLogos["401"] = {logoNote:"SABOR"};
gArrMlsLogos["403"] = {logoNote:"HARCOM"};
gArrMlsLogos["421"] = {logoNote:"Georgia"};
gArrMlsLogos["411"] = {logoNote:"Charlotte"};
gArrMlsLogos["412"] = {logoNote:"Triad"};
gArrMlsLogos["413"] = {logoNote:"Triangle"};
gArrMlsLogos["414"] = {logoNote:"Asheville"};
gArrMlsLogos["206"] = {logoNote:"DesertArea"};
gArrMlsLogos["104"] = {logoNote:"Fresno"};
gArrMlsLogos["431"] = {logoNote:"Mid-Florida Regional"};
gArrMlsLogos["432"] = {logoNote:"SouthEast-Florida Regional"};
gArrMlsLogos["433"] = {logoNote:"NorthEast-Florida Regional"};
gArrMlsLogos["491"] = {logoNote:"Oregon"};
gArrMlsLogos["471"] = {logoNote:"Arizona"};
gArrMlsLogos["461"] = {logoNote:"Illinois"};
gArrMlsLogos["472"] = {logoNote:"Tucson"};
gArrMlsLogos["481"] = {logoNote:"Westchester New York"};
gArrMlsLogos["482"] = { logoNote: "Long Island" };
gArrMlsLogos["571"] = {logoNote:"Realtracs"};
gArrMlsLogos["572"] = {logoNote:"Knoxville Area Association of Realtors"};
gArrMlsLogos["573"] = {logoNote:"Memphis Area Association of Realtors"};
gArrMlsLogos["441"] = {logoNote:"Trend"};
gArrMlsLogos["451"] = { logoNote: "Garden State MLS" };
gArrMlsLogos["522"] = { logoNote: "Information and Real Estate Services, LLC" };
gArrMlsLogos["521"] = { logoNote: "Metrolist" };
gArrMlsLogos["651"] = { logoNote: "North Star" };
var cookieKeys = {MainSearchExpander:"MainSearchExpander", Subarea:1, ZipCode:2};
/***************************************************************************************************************
 * Issue A, Metro Area Adjustment when new metro area added.
 * We need adjust code for the new Metro Area
 * 	1) in Common/StatisticFunction.cs: public enum MetroArea{1,20...}
 *	2) in index.js: 
 *		a) var gmetroAreaList = "1,20,21"; 
 *		b) GetCurrentMetroAreaName(MetroAreaCode){case 1:...}
 *	3) in city link list pages:  cityLinkListToOpenHouse.ascx; Add a new open house link page for new Metro Area.
 * --------------------------------------------------------------------------------------------------------------------
 * Issue B, MLS logo Adjustment when new database added
 * We need adjust code: 
 *	1) add a new mls logo for the new db.
 *	2) in index.js:
 *		a) var gArrMlsDbList = new Array("100",.."
 *		b) gArrMlsLogos["401"] = {logoImagePath:"",logoNote:"San Antonio"}. Sometimes need change copyright text or display style.
 ****************************************************************************************************************/

//GetMLSLogosNote_Pri: Need modify code for new mls_db.  Marked by Joe, 5 23th, 2007
function GetMLSLogosNote_Pri(mlsDB)
{
	mlsDB = mlsDB.toString();
	var logo_Note = " comes from the IDX program of the "
	var logo_Note_end = " Multiple Listing Service<sup>TM</sup> system.";
	
	if(gArrMlsLogos[mlsDB]!=null)
	{
		// Add by MLian for bug 3876 05/06/08
		switch(mlsDB)
		{
			case "100":
				logo_Note = " comes from";
				logo_Note_end = " the Broker Listing Exchange program of the REInfoLink<sup>TM</sup> MLS system. Copyright (C) 2007, RE InfoLink, Inc. - All rights reserved.";
				break;
			case "102":
				logo_Note += gArrMlsLogos[mlsDB].logoNote;
				logo_Note_end += " Information deemed reliable, but not verified or guaranteed. Users are responsible for checking the accuracy, completeness, currency, and status of all information. All measurements and all calculations of area (i.e., Sq Ft and Acreage) are approximate. Broker has represented to MetroList that Broker has a valid listing signed by seller authorizing placement in the MLS. Above information is provided by Seller and/or other sources and has not been verified by Broker. Some properties that appear for sale on this web site may subsequently have been sold and may no longer be available. Copyright 2007 MetroList Services, Inc."
				logo_Note_end += "&nbsp;<a style='cursor:pointer;' onclick=\"javascript:showMetroListTermsOfUse()\">Metrolist Terms of Use</a>";
				break;
			case "203":
				logo_Note += gArrMlsLogos[mlsDB].logoNote;
				logo_Note_end += "&nbsp;<a style='cursor:pointer;' onclick=\"javascript:ShowSocalDisclaimer()\">Disclaimer</a>";
				break;
			default:
				logo_Note += gArrMlsLogos[mlsDB].logoNote;
				break;
		}
	}
	
	return logo_Note + logo_Note_end; 
}

// Add by MLian for bug 3876 05/06/08
function ShowSocalDisclaimer()
{
	var windowTitle = "Disclaimer";
	var metrolistTermsContent =  "<p>If a listing displays \"Short Sale/Subj to Lender Approval**\" then that listing has been identified by the seller and the listing broker as a \"short sale\".  This means that, at the listed price, the proceeds from the sale may not be adequate to pay all liens and costs of sale.  Any offer made that does not fully cover the existing amount(s) owed to the lienholders(s) plus the costs of sale could be subject to lienholder approval, which approval may be exercised at the sole and exclusive discretion of the lienholder(s).</p>"
	                        + "<p>The information being provided is for the consumer's personal, non-commercial use and may not be used for any purpose other than to identify prospective properties consumer may be interested in purchasing.</p>"
							+ "<p>Any information relating to real estate for sale referenced on this web site comes from the Internet Data Exchange (IDX) program of the SoCalMLS and/or CRISNet Regional MLS. This web site may reference real estate listing(s) held by a brokerage firm other than the broker and/or agent who owns this web site.</p>"
							+ "<p>The accuracy of all information, regardless of source, including but not limited to square footages and lot sizes, is deemed reliable but not guaranteed and should be personally verified through personal inspection by and/or with the appropriate professionals.</p>"
							+ "<p>Copyright, SoCalMLS&reg;<br>Copyright, CRISNet Regional MLS&reg;</p>";
	var popMetroList = new popUpWindow();
	popMetroList.width = "640";
	popMetroList.height = "250";
	popMetroList.borderColor = "#000000";
	popMetroList.titleBar.foreColor = "#000000";
	popMetroList.titleBar.fontSize = "14";
	popMetroList.titleBar.backgroundColor = "#F4EFC4";
	popMetroList.titleBar.innerHTML = windowTitle;
	popMetroList.bodyContainerType = "content";
	popMetroList.bodyContainerTypeValue = metrolistTermsContent;
	popMetroList.show();
}

function goToPage(pageUrlPart1, pageUrlPart2)
{
	var pageUrl = "http://" + pageUrlPart1;
	if(pageUrlPart2 != null)
		pageUrl = pageUrl + pageUrlPart2;
	window.open(pageUrl);
}

function goToPageForNewhomesource(pageUrlPart1, pageUrlPart2) {
    var pageUrl = "http://" + pageUrlPart1;
    if (pageUrlPart2 != null)
        pageUrl = pageUrl + pageUrlPart2;
    window.open(pageUrl, '_blank', 'width=810,menubar=no,location=no,scrollbars=yes,resizable=yes');
}

// Show/hide popup window background cover layer.
// Created by Andy Wan, Sep 21, 2006.
function showPopupWindowCover(isShow)
{			
	var divbg = document.getElementById("divbg");
	if(isShow)
	{
		var appUrl = GetRelativePath2();
		divbg.src = appUrl + "blank.html";
		divbg.style.width = screen.availWidth;
		var curHeight = document.body.scrollHeight;
		if(curHeight >= availHeight)
			divbg.style.height = curHeight;
		else
			divbg.style.height = availHeight;
	}
	else
	{
		divbg.style.width = 0;
		divbg.style.height = 0;
	}
}

var ifmWidth = 393;
var ifmHeight = 460;
var DNum = 30;
var divideWidth = ifmWidth / DNum;
var divideHeight = ifmHeight / DNum;
var ifmcover = null;
var gi = 0;
function WinSize(AppURL)
{
	var divbg = document.getElementById("divbg");
	divbg.src = AppURL + "blank.html";
	divbg.style.width = gavailWidth;
	divbg.style.height = availHeight;
}
function DropDown(AppURL)
{
	WinSize(AppURL);
	ifmcover = document.getElementById("ifmcover");
	ifmcover.width = 0;
	ifmcover.height = 0;
	SmallTOBig();
}
function SmallTOBig()
{
	if(gi < DNum)
	{
		ifmcover.width = eval(ifmcover.width) + divideWidth;
		ifmcover.height = eval(ifmcover.height) + divideHeight;
		gi++;
		setTimeout("SmallTOBig()",0);
	}
	else
	{
		ifmcover.width = ifmWidth;
		ifmcover.height = ifmHeight;
	}
}

// Check browser type.
// Added by Andy Wan, Jan 5, 2007.
function browserType()
{	
	this.isIE = false;
	this.isIE7 = false;
	this.isIE6 = false;
	this.isFireFox = false;
	this.isSafari = false;
	var uAgent = window.navigator.userAgent;
	this.userAgent = uAgent;	
	if(uAgent.indexOf("MSIE") != -1)
	{
		this.isIE = true;
		if(uAgent.indexOf("MSIE 7") != -1)
			this.isIE7 = true;
		else if(uAgent.indexOf("MSIE 6") != -1)
			this.isIE6 = true;
	}
	if(uAgent.indexOf("Firefox") != -1 || uAgent.indexOf("Netscape") != -1)
		this.isFireFox = true;
	if(uAgent.indexOf("Safari") != -1)
		this.isSafari = true;
}
var clientBrowser = new browserType();

// Get current mouse's coordinate.
// Added by Andy Wan, Dec 11, 2006.
function mouseCoords(e){
	e = e || window.event;
	if(e.pageX || e.pageY){
		return {x:e.pageX, y:e.pageY};
	}
	return {
		x:e.clientX + document.body.scrollLeft - document.body.clientLeft,
		y:e.clientY + document.body.scrollTop  - document.body.clientTop
	};
}

// Get the offset between target control and mouse position.
// Added by Andy Wan, Dec 11, 2006.
function getMouseOffset(target, e){
	e = e || window.event;

	var docPos    = getPosition(target);
	var mousePos  = mouseCoords(e);
	return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
}

// Get the position of appointed control.
// Added by Andy Wan, Dec 11, 2006.
function getPosition(e){
	var left = 0;
	var top  = 0;
	while (e.offsetParent){
		left += e.offsetLeft + (e.currentStyle?(parseInt(e.currentStyle.borderLeftWidth)).NaN0():0);
		top  += e.offsetTop  + (e.currentStyle?(parseInt(e.currentStyle.borderTopWidth)).NaN0():0);
		e = e.offsetParent;
	}	
	left += e.offsetLeft + (e.currentStyle?(parseInt(e.currentStyle.borderLeftWidth)).NaN0():0);
	top  += e.offsetTop  + (e.currentStyle?(parseInt(e.currentStyle.borderTopWidth)).NaN0():0);
	return {x:left, y:top};
}

/*
==================================================================
MM_openBrWindow(theURL,winName,width, height):Open a new window
==================================================================
*/
function MM_openBrWindow(theURL,winName,width, height) 
{
	var top = (screen.height - height)/2;
	var left = (screen.width - width)/2;
	var features = 'width=' + width + ',height=' + height + ',top=' + top + ',left=' + left + ',scrollbars=yes';
	if(theURL.indexOf('GeneralMap.aspx') != -1)
	{
		theURL = theURL + "M";
	}
	var newwindow = window.open(theURL, winName, features);
	newwindow.focus();
}

//add by MLian for popwin
function openWEB(width,height,url,divid,frmid,divWaiting)
{
	var div = window.document.getElementById(divid);
	var frm = window.document.getElementById(frmid);
	//Show 'Loading...' before page loaded.Juana.Dec.12,2006
	var divWait = window.document.getElementById(divWaiting);
	if(divWait!=null)
		divWait.style.display = 'block';
	
	if(div!=null && frm != null)
	{	
		    div.style.width=width;
			div.style.height = height;
			div.style.display='block';
			moveToaCenter(divid);
			targetUrl = GetRelativePath2() + url;
			frm.src=targetUrl;
	}
}
		function moveToaCenter( divName )
		{
			//window.document.getElementById( 'divPop' ).style.display = 'none';
			//window.document.getElementById( 'divDoc' ).style.display = 'none';
			window.document.getElementById( divName ).style.display = 'block';
			
			var uAgent = window.navigator.userAgent;
			var mydiv = document.getElementById( divName );
			// Modified by Andy Wan, Jan 11, 2006. / Adjust the display in Safari.
			if(uAgent.indexOf("Firefox") != -1 || uAgent.indexOf("Netscape") != -1 || uAgent.indexOf("Safari") != -1)
			{
				mydiv.style.left = document.body.scrollLeft+(document.body.clientWidth-mydiv.offsetWidth)/2 +'px';
				if(uAgent.indexOf("Safari") != -1)
					mydiv.style.top = document.body.scrollTop+(innerHeight-mydiv.offsetHeight)/2 +'px';
				else
					mydiv.style.top = document.body.scrollTop+(document.body.clientHeight-mydiv.offsetHeight)/2 +'px';			
			}
			else
			{
				window.document.getElementById( divName ).style.posTop = document.body.scrollTop+(document.body.clientHeight-document.getElementById( divName ).offsetHeight)/2;
				window.document.getElementById( divName ).style.posLeft = document.body.scrollLeft+(document.body.clientWidth-document.getElementById( divName ).offsetWidth)/2;				
				
			}		
			
			//Modified by Joe, Jan 12, 2006.	
			var top =mydiv.style.top.replace('px','');
			if(top < 0)
				mydiv.style.top = '0px';
		}

/*
==================================================================
LTrim(string):remove the left blank
==================================================================
*/
function LTrim(str)
{
    var whitespace = new String(" \tĦĦ");
    var ss = new String(str);
    if (whitespace.indexOf(ss.charAt(0)) != -1)
    {
        var j=0, i = ss.length;
        while (j < i && whitespace.indexOf(ss.charAt(j)) != -1)
        {
            j++;
        }
        ss = ss.substring(j, i);
    }
    return ss;
}

/*
==================================================================
RTrim(string):remove the right blank
==================================================================
*/

function RTrim(str)
{
    var whitespace = new String(" \tĦĦ");
    var ss = new String(str);
    if (whitespace.indexOf(ss.charAt(ss.length-1)) != -1)
    {
        var i = ss.length - 1;
        while (i >= 0 && whitespace.indexOf(ss.charAt(i)) != -1)
        {
            i--;
        }
        ss = ss.substring(0, i+1);
    }
    return ss;
}

/*
==================================================================
Trim(string):remove the left and right blank of the string
==================================================================
*/
function Trim(str)
{
    return RTrim(LTrim(str));
}

/*
==================================================================
isFigure(string):If the string is figure
==================================================================
*/

function isFigure(str)
{
    var isfigure = true;
    
   	if(Trim(str) != "")
	{
		var figure = "0123456789";	
		var elem;
		
		for(var k =0;k<str.length;k++)
		{
			elem = str.substring(k,k+1);
			if(figure.indexOf(elem)==-1)
			{
			return false;
			}
		}				
	}
	
	return isfigure;
}

/*
==================================================================
GetRelativePath():Get Relative Path
Modified by Andy Wan, Dec 15, 2005. / Add folder "real-estate".
==================================================================
*/
function GetRelativePath()
{		
	var rPath = "";	
	var url = location.href.toLowerCase();	
	if(url.indexOf('/agent/')!=-1||url.indexOf('/mappage/')!=-1||url.indexOf('/specialtools/')!=-1)
		rPath = "../";
	if(url.indexOf('/real-estate/')!=-1)
		rPath = "";
	return rPath;	
}
// Get path from the control of pageHeader.
// Created by Andy Wan, Feb 14, 2006.
function GetRelativePath2()
{
	return GetAppURL();
}
function GetAppURL()
{
	if ( document.getElementById(gCtlIdPrefix.PageHeader + "hdRPath") != null )
		return document.getElementById(gCtlIdPrefix.PageHeader + "hdRPath").value;
	else if(document.getElementById(gCtlIdPrefix.LeftNav + "hdRPath") != null )
		return document.getElementById(gCtlIdPrefix.LeftNav + "hdRPath").value;
	else
	   return "";
}

/*
==================================================================
ChangeCss(id,cssname):set css for html control
==================================================================
*/
function ChangeCss(id,cssname)
{
	if(document.getElementById(id)!=null)
	document.getElementById(id).className =cssname;
}

/*
==================================================================
TabCss(id):set tab css
==================================================================
*/
function TabCss(tabControlId)
{
	if(document.getElementById(tabControlId)!=null)
	{
		document.getElementById(tabControlId).style.cssText = "color:#FFF;background-image:url(" + gWebPath + "images/homepage/menu_background_blue.jpg);background-repeat:repeat-x;";	
	}
}

/*
==================================================================
GetValidatePrice(id):get a validate price value;
Add by Joe 11.28,2005	
==================================================================
*/
function GetValidatePrice(pricediv)
{
	var priceValue = GetValidatePriceValue(Trim(pricediv.value));
	pricediv.value = priceValue;					
}
function GetValidatePriceValue(priceValue)
{
	var dotL = -1;
	
	if(priceValue!="")
	{
		priceValue=priceValue.replace(/\$|\e|\,/g,"");
		if(isNaN(priceValue))
		{						
			priceValue="";
		}
		else 
		{
			if(priceValue.length>9)
				priceValue=priceValue.substring(0,9);											
			dotL = priceValue.indexOf('.');				
			if(dotL != -1)
				priceValue = priceValue.substring(0,dotL);	
				
			for (var i = 0; i < Math.floor((priceValue.length-(1+i))/3); i++)
			priceValue = priceValue.substring(0,priceValue.length-(4*i+3))+','+priceValue.substring(priceValue.length-(4*i+3));	
			priceValue = '$' + priceValue;											
		}					
	}
	
	return priceValue;					
}

function ForValidatePriceValue(priceValue)
{
	if(priceValue != "")
	{
		priceValue = priceValue.replace(/\$|\e|\,/g,"");
		if(isNaN(priceValue) || priceValue.length > 9)
			return false;
		else
			return true;
	}
	else
		return true;
}

//When a client has entered any of the items that are in thousands, a comma separator should appear 
//when the client has moved on to another box, i.e., $100,000, not $100000. 
function formatNum(num) 
{
	var uAgent = window.navigator.userAgent;
	if(uAgent.indexOf("Safari") == -1)
	{
		if(!/^(\+|-)?(\d+)(\.\d+)?$/.test(num)){ return num;}
		var a = RegExp.$1, b = RegExp.$2, c = RegExp.$3;
		var re = new RegExp().compile("(\\d)(\\d{3})(,|$)");
		while(re.test(b)) b = b.replace(re, "$1,$2$3");
		return a +""+ b +""+ c;
	}
	else
	{
		return num;// We will not format the number in Safari.
	}
}

//Remove comma separator of number
function removeFormatNum(num)
{
	//num = num.split(",").join("");
	num = (""+num).replace(/,/g,"");
	
	if(num == "&nbsp;")
		num = 0;
	
	return num;
}


//Added by juana,Jan.3,2006
function btnFocus(e,tbx,btnID)
{
	var btnID=document.getElementById(btnID);
	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"))
	{
		btnID.focus();
		btnID.click();
	}
}


/*
-------------------------------------------------------------------------------------------
From JS\pageHeader. 3 . 1.js  //To avoid replacing,add some space between number and point.
-------------------------------------------------------------------------------------------
*/

// JS code for pageHeader.

// Load the default content for top-right panel.
function LoadDefaultUserPanel()
{
	var urlHeader = GetRelativePath2();
	var userPanel = document.getElementById(gCtlIdPrefix.PageHeader + "userPanel");
	var userPanelContent = "<div class='linksOntopright'><a id=\"linkLogin\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" onclick=\"showLoginPopUp();\" rel=\"nofollow\">Sign In</a> | <A href=\"javascript:showContactUsPopUp('emailinfo')\" id=\"emLink\" rel=\"nofollow\">info@movoto.com</A>";
	userPanelContent += " | <span id='metroLink'>";
	userPanelContent += "</span></div>";
	userPanelContent += "<div class=\"UserPanelPhoneText\">Call us toll-free: <b>(888) 766-8686</b></div>";
	userPanel.innerHTML = userPanelContent;
//	SetCurrentMetroAreaName();	
}

// Check if current user is logged in.
function checkUserIsLoggedIn() {
    var hidUlStatus = $get(gCtlIdPrefix.PageHeader + "hidUlStatus");
	if(hidUlStatus == null)
		hidUlStatus = parent.document.getElementById(gCtlIdPrefix.PageHeader + "hidUlStatus");

	if(hidUlStatus.value == "1")
		return true;
	else
		return false;
}

//Added by Ballian for bug#4139:listingUpdates pop up Sept 6,2008
//cityCode is necessary,when other parameter is not.
//isNotSearch needs bool variable containing(true, false);if true,hide the search criteria,if false display the search criteria.
//the other parameters are search option of listing, get values from search details of other pages.
function ListingUpdates(cityCode,isNotSearch,listingType,propertyType,bedrooms,bathrooms,minPrice,maxPrice)
{
	var popListingUpdates = new popUpWindow('divListingUpdates');
	popListingUpdates.width = "510";
	
	if(!isNotSearch)
		popListingUpdates.height = "400";
	else
		popListingUpdates.height = "315";
	
	popListingUpdates.titleBar.innerHTML = "Sign Up for Listing Updates";
	popListingUpdates.bodyContainerTypeValue = gWebPath + "ListingUpdates.aspx?cityCode=" + cityCode + "&isNotSearch=" + isNotSearch + "&listingType=" + listingType + "&propertyType=" + propertyType + "&bedrooms=" + bedrooms + "&bathrooms=" + bathrooms + "&minPrice=" + minPrice + "&maxPrice=" + maxPrice;
	popListingUpdates.body.pageIframeScrolling = "auto";
	popListingUpdates.show();
}	


// Check if current user is logged in.
// If has logged in and targetURL is not blank, go to the target url.
// If has logged in and targetURL is blank, return true.
// If has not logged in, popup register or login window.
// Created by Andy Wan, Aug 1, 2006. 
function checkLoginPop(targetURL,registerType)
{
	iGen.WebServices.Common.CheckUserIsLoggedIn(onCheckLoginPopSucceeded,null,{"targetURL":targetURL,"registerType":registerType});
}
function onCheckLoginPopSucceeded(result,userContext)
{
    var urlHeader = GetRelativePath2();
    if(!result)
	{
		var cookieSavedMail = GetCookie("lastLogedMail");
		if(cookieSavedMail == null || cookieSavedMail == "")
			showRegisterPopUp(userContext.registerType);
		else
			showLoginPopUp(userContext.registerType);
	}
	else
	{			
		if(userContext.targetURL == "" && userContext.registerType == null)
			return true;
		else
			window.location.href = urlHeader + userContext.targetURL;			
	}
}

// Show the pop up window of the login page.
function showLoginPopUp(registerType)
{
	//var loginWindowName = "LoginPage";
	var loginPageUrl = gWebPath + "loginpage.aspx";
	if(registerType != null && registerType != "")
	{
		//loginWindowName += "_" + registerType;
		loginPageUrl += "?type=" + registerType;
	}	
	var popLoginPage = new popUpWindow();
	popLoginPage.width = "420";
	popLoginPage.height = "220";
	popLoginPage.titleBarFontSize = "18px";
	popLoginPage.titleBar.textAlign = "center";
	popLoginPage.titleBar.innerHTML = "Login or Register";
	popLoginPage.bodyContainerTypeValue = loginPageUrl;
	popLoginPage.show();
}



// Show the pop up window of the register page.
function showRegisterPopUp(registerType,activeId)
{
	//var loginWindowName = "RegisterPage";
	var loginPageUrl = gWebPath + "registration1.aspx";
	if(registerType != null && registerType != "")
	{
		//loginWindowName += "_" + registerType;
		loginPageUrl += "?type=" + registerType;
	}
	if(activeId != null && activeId != "")
	{
		//loginWindowName += "_Active";
		loginPageUrl += "?ActiveID=" + activeId;
	}
	var popLoginPage = new popUpWindow();
	popLoginPage.width = "640";
	popLoginPage.height = "530";
	popLoginPage.titleBar.fontSize = "15";
	popLoginPage.titleBar.textAlign = "left";
	popLoginPage.titleBar.innerHTML = "<FONT color=white>NEW USER?</FONT> <SPAN style='font-size:13px'>Register now for the most complete home search tools available.</SPAN>";
	popLoginPage.bodyContainerTypeValue = loginPageUrl;
	popLoginPage.show();
}


// Pop-up a register window.
// Created by Andy Wan, Jan 12, 2006.
function PopupRegisterWindow(str)
{
	showRegisterPopUp();
}

// Get current user id.
// Created by Andy Wan, Jan 16, 2005.
function GetCurrentUserID()
{
	var txtUserID = document.getElementById(gCtlIdPrefix.PageHeader + "txtUserID");

	if(txtUserID !=null && txtUserID.value != null &&  txtUserID.value != "")
		return txtUserID.value;
	else
	{
	    iGen.WebServices.Common.GetCurrentUserID(onGetCurrentUserIDSucceeded);
	}

}
function onGetCurrentUserIDSucceeded(result)
{
    var userID = "";
	var sessionUserID = result;
	var txtUserID = document.getElementById(gCtlIdPrefix.PageHeader + "txtUserID");
	if(sessionUserID != null)
	{
	    userID = sessionUserID;
	    if(txtUserID != null)
			txtUserID.value = userID;			
	}
}

/*
-----------------------------------------------------------------------------------------
From JS\leftNav. 3 . 1 .js  //To avoid replacing,add some space between number and point.
-----------------------------------------------------------------------------------------
*/
	
	function GetCookie(sName)
	{
		var aCookie = document.cookie.split("; ");
		for (var i=0; i < aCookie.length; i++)
		{
			var aCrumb = aCookie[i].split("=");
			if (sName == aCrumb[0]) 
			{
				// Modified by Andy Wan, Mar 2, 2006.
				// If the cookie value is null, return "" value. The original code will return "undefined".
				if(aCrumb.length > 1)
					return unescape(aCrumb[1]);
				else
					return "";
			}
		}

		return null;
	}
	
	// Create a cookie with the specified name and value.
	function SetCookie(sName, sValue)
	{
		date = new Date('1/1/2100');
		document.cookie = sName + "=" + escape(sValue) + "; expires=" + date.toGMTString() + "; path=/";
	}
	
	
	
	// Load both auto saved and user saved search.
	// Created by Andy Wan, Apr 7, 2006.
	function LoadAllSavedSearch()
	{
		// Modified by Andy Wan, May 9, 2006.
		// For unregistered user, will not load the save searches, this will reduce one connection to server, and some database connections.
		if(document.getElementById(gCtlIdPrefix.LeftNav + "divLeftNav").className != "sidenav_none")
		{
			var urlHeader = GetRelativePath2();
			var tbCurSearchID = document.getElementById(gCtlIdPrefix.LeftNav + "tbCurSearchID");
			var divMySavedSearch = document.getElementById(gCtlIdPrefix.LeftNav + "divMySavedSearch");
			divMySavedSearch.innerHTML = "Loading...";
			
			iGen.WebServices.Common.ShowUserSearchesList(tbCurSearchID.value, urlHeader, onShowUserSearchesListSucceeded);
		}
	}
	function onShowUserSearchesListSucceeded(result)
	{
	    var divMySavedSearch = document.getElementById(gCtlIdPrefix.LeftNav + "divMySavedSearch");
	    if(result == "" || result == null)
		{
			divMySavedSearch.innerHTML = "";
		}
		else
		{
			divMySavedSearch.innerHTML = result[0];
		}
	}
	
	// Delete saved search.
	// Created by Andy Wan, Nov 21, 2005.
	function DelSavedSearch(searchid,isAutoSaved)
	{
		// Check login status and try to auto login.
		// Added by Andy Wan, Dec 23, 2005.
		iGen.WebServices.Common.CheckAndTryAutoLogin(onDelSavedSearchSucceeded,null,{"searchid":searchid});
	}
	function onDelSavedSearchSucceeded(result,userContext)
	{
		if(result == null || result == "")
		{
			// If return false, return to home page to login.
			// Added by Andy Wan, Dec 23, 2005.
			window.location.href = GetHomePageLink(true);
		}
		else
		{
			if(result == true)
			{
			    iGen.WebServices.Common.DeleteSavedSearch(userContext.searchid);
			    LoadAllSavedSearch();
			}
			else
			{
				// If return false, return to home page to login.
				// Added by Andy Wan, Dec 23, 2005.
				window.location.href = GetHomePageLink(true);
			}
		}
	}

	// Load user panels (left nav + top-right user panel).
	function LoadUserPanelsContent()
	{
		var tbCurSearchID = document.getElementById(gCtlIdPrefix.LeftNav + "tbCurSearchID");
		var currentSearchId = null;
		if(tbCurSearchID)
		{
		    currentSearchId = tbCurSearchID.value;
		}
		var cachebox = document.getElementById(gCtlIdPrefix.LeftNav + "cachebox");
		var cacheboxValue = null;
		if(cachebox)
		{
		    cacheboxValue = cachebox.value;
		}

		var divMySavedSearch = document.getElementById(gCtlIdPrefix.LeftNav + "divMySavedSearch");
		var userPanel = document.getElementById(gCtlIdPrefix.PageHeader + "userPanel");
				
	    if(divMySavedSearch)
	    {			
		    divMySavedSearch.innerHTML = "Loading...";
		}
		userPanel.innerHTML = "Loading...";

		var savedSearchID = document.getElementById(gCtlIdPrefix.MainContent + "tbHiddenEditSearchID");
        if(savedSearchID != null && savedSearchID.value != null)
            savedSearchID.value = "";
        		
		iGen.WebServices.Common.LoadUserPanels(currentSearchId,cacheboxValue, onLoadUserPanelsSucceeded, onLoadUserPanelsFailed);
	}
	
	function onLoadUserPanelsSucceeded(result)
	{
	    var divLogin = document.getElementById(gCtlIdPrefix.LeftNav + "divLogin");
	    var divLeftNav = document.getElementById(gCtlIdPrefix.LeftNav + "divLeftNav");
	    var divMlsSearch = document.getElementById(gCtlIdPrefix.LeftNav + "divMlsSearch");
	    var hidUlStatus = $get(gCtlIdPrefix.PageHeader + "hidUlStatus");
	    if(result.isCurrentUserLoggedIn == true)
	    {
	        if(divLogin)
	        {
	            divLogin.className = "sidenav_none";
	        }
	        if(divLeftNav)
	        {
		        divLeftNav.className = "sidenav_block";
		    }
		    if(divMlsSearch)
		    {
		        divMlsSearch.className = "sidenav_block";
		    }
	        var divMySavedSearch = document.getElementById(gCtlIdPrefix.LeftNav + "divMySavedSearch");
	        if(divMySavedSearch)
	        {
	            divMySavedSearch.innerHTML = result.htmlMySavedSearch;
	        }
	    }
        if(hidUlStatus)
        {
            if(result.isCurrentUserLoggedIn == true)
            {
                hidUlStatus.value = "1";
            }
            else
            {
                hidUlStatus.value = "0";
            }
        }
	    var userPanel = document.getElementById(gCtlIdPrefix.PageHeader + "userPanel");
	 
		userPanel.innerHTML = result.htmlTopHeader;
	//	SetCurrentMetroAreaName();
		// Update the page saved info when login from unregistered to registered.
		if(typeof(window.top.PageUpdateForLogin)=='function')
			void(window.top.setTimeout("PageUpdateForLogin()",300));
		if(typeof(window.top.closePopUpWindow)=='function')
		    void (window.top.closePopUpWindow());
		loadMultiLanguages();
	}
	
	function onLoadUserPanelsFailed(error)
	{
	    if(divLogin)
	    {
	        divLogin.className = "sidenav_block";
	    }
		if(divLeftNav)
	    {
	        divLeftNav.className = "sidenav_none";
		}
		if(divMlsSearch)
		{
	        divMlsSearch.className = "sidenav_none";
		}
		if(hidUlStatus)
		{
		    hidUlStatus.value = "0";
		}
	    var divMySavedSearch = document.getElementById(gCtlIdPrefix.LeftNav + "divMySavedSearch");
	    if(divMySavedSearch)
	    {
	        divMySavedSearch.innerHTML = "";
	    }
	    LoadDefaultUserPanel();
	}
	
	function  GetHomePageLink(isTimeOut)
	{	
		var strHomePage = GetRelativePath2() + "default.aspx";

		if(isTimeOut != null && isTimeOut)
			strHomePage += "?ErrorType=timeout";

		return strHomePage;
	}	
	
	//Modify By MLian for bug 2198
	function GetLast2(igenKey)
	{
		return  "0" + igenKey.substring(igenKey.length - 2,igenKey.length);
	}
	function GetLast3(igenKey) 
	{
	    return "0" + igenKey.substring(igenKey.length - 3, igenKey.length);
	}	
	function GetSmallImage(mlsnum,mlsdb)
	{
		var hdImagePath = document.getElementById( gCtlIdPrefix.PageHeader + "hdImagePath");	
		
		if(hdImagePath!=null)
		{
			if(hdImagePath.value!=null && hdImagePath.value!= "" && mlsnum != null && mlsnum != "" && mlsdb != null && mlsdb != "")
		    {
		        if (mlsdb == 8)
		            return hdImagePath.value.replace("%category%", mlsdb) + GetLast3(mlsnum) + "/tn/" + mlsnum + "_0.jpg";
		        else
		            return hdImagePath.value.replace("%category%", mlsdb) + GetLast2(mlsnum) + "/tn/" + mlsnum + "_0.jpg";
		    }
							
		}
					
		return "http://dev.igenhome.com/MLSImages/tn/";	
	}	
	function GetBigImage(mlsnum,mlsdb,photoNum,imagePath)
	{
		var hdImagePath = imagePath;	
		if(imagePath == "")		
			hdImagePath = document.getElementById( gCtlIdPrefix.PageHeader + "hdImagePath" ).value;				
		
		//Modify By MLian for bug 2198
		if(hdImagePath!=null)
		{
			if(hdImagePath != null && hdImagePath != "" && mlsnum != null && mlsnum != "" && mlsdb != null && mlsdb != "")				
		    {
		        if (mlsdb == 8)
		            return hdImagePath.replace("%category%", mlsdb) + GetLast3(mlsnum) + "/" + mlsnum + "_" + photoNum + ".jpg";
		        else
		            return hdImagePath.replace("%category%", mlsdb) + GetLast2(mlsnum) + "/" + mlsnum + "_" + photoNum + ".jpg";
		    }	
		}
			
		return "http://dev.igenhome.com/MLSImages/";	
	}

//Added by Juana at Sept.22,2006
//Show Notes when mouse over

function Show_Notes(noteId, noteContent, width)
{
	var ID = document.getElementById(noteId);
	ID.className = "notesStyle_new";
	ID.innerHTML = noteContent;
	ID.style.width = width;
}

//Hide Notes when mouse out
function Hidden_Notes(noteId)
{
	var ID=document.getElementById(noteId);
	ID.className="notesStyleHidden";
}
//end

// Fly an element to a new position.
function ObjectFly(elementId, endPositionTop, endPositionLeft)
{
    endPositionTop = parseFloat(endPositionTop);
    endPositionLeft = parseFloat(endPositionLeft);
    var flyObject = document.getElementById(elementId);
    if(flyObject)
    {
        var currentPostion = GetObjectPosition(elementId);
        if(currentPostion.Top != endPositionTop || currentPostion.Left != endPositionLeft)
        {
            var stepValue =  10;
            currentPostion.Top =  GetSteppedValue(currentPostion.Top, endPositionTop, stepValue);
            currentPostion.Left = GetSteppedValue(currentPostion.Left, endPositionLeft, stepValue);
	        MoveObjectToPosition(elementId, currentPostion.Top, currentPostion.Left);
            setTimeout("ObjectFly('" + elementId + "', '" + endPositionTop + "', '" + endPositionLeft + "')", 30);
        }
    }
}

function GetSteppedValue(currentValue, targetValue, stepValue)
{
    if(currentValue < targetValue)
    {
        if(currentValue + stepValue <= targetValue)
        {
            return currentValue + stepValue;
        }
    }
    if(currentValue > targetValue)
    {
        if(currentValue - stepValue >= targetValue)
        {
            return currentValue - stepValue;
        }
    }
    return targetValue;
}

// Get the position of an element.
function GetObjectPosition(elementId)
{
    var myObject = document.getElementById(elementId);
    if(myObject)
    {
        var objectPosition = {Top: 0, Left: 0};
        if(clientBrowser.isFireFox || clientBrowser.isSafari)
	    {
		    objectPosition.Left =  parseFloat(myObject.style.left.replace('px',''));
		    objectPosition.Top = parseFloat(myObject.style.top.replace('px',''));		
	    }
	    else
	    {
		    objectPosition.Top = myObject.style.posTop;
		    objectPosition.Left = myObject.style.posLeft;
	    }
	    return objectPosition;
	}
	return null;
}

// Move an element to a position.
function MoveObjectToPosition(elementId, top, left)
{
    var myObject = document.getElementById(elementId);
    if(myObject)
    {
        if(clientBrowser.isFireFox || clientBrowser.isSafari)
        {
            myObject.style.left = left;
            myObject.style.top = top;		
        }
        else
        {
            myObject.style.posLeft = left;
            myObject.style.posTop = top;			
        }
    }
}

// ********************************** Begin Pop Up Window ********************************** //
// Related bug #2323.
// Created by Andy Wan, Jan 10, 2007.

//var popWinMaskZIndex = 10005;
var popWinZIndex = 10006;
var popWinClientIdPrefix = "popWin_";
var popWinMaskShow = false;
var popWinDragWindow = null;
var popWinMouseOffset = null;
var popWinActiveWindowName = null;
var popWinArrWindowNames = new Array();
// Total count of unnamed pop up windows, 
// the new unnamed pop up window name will based on this value.
var popWinUnnamedWindowCount = 0;
var popWinIsDragWork = false;

var PopUpFlyDirections = {None: 0, LeftToCenter: 1, TopToCenter: 2};

// Default values for pop up window.
function popUpWindowDefaultValues()
{
	this.height = 200;
	this.width = 500;
	this.alignCenter = true; // if it is true, the "left" and "top" will be ignored.
	this.left = 0;
	this.top = 0;
	this.hasBorder = true;
	this.borderThick = 1; // the thick of the pop up window border.
	this.borderColor = "#000000"; // the color of the pop up window border.
	this.ie6DropdownCompatible = true;
	// Show a mask to make parent window can't be click.
	this.hasMask = false;
	// Transparent the background.
	// Note: 1. if you set both "hasMask" and "transparent" to true, the transparent will not work.
	//       2. for transparent, the "body.backgroundColor" will not work.
	this.transparent = false;
	// Drag the title bar of the pop up window.
	this.allowDrag = false;
	this.flyDirection = PopUpFlyDirections.None;
	
	// If no title bar for pop up window, you can set "hasTitleBar" to false.
	this.hasTitleBar = true;
	this.titleBarHeight = 22;
	this.titleBarBackgroundColor = "#19378E";
	this.titleBarForeColor = "#FFFFFF";
	this.titleBarInnerHTML = "";
	this.titleBarFontBold = true;
	this.titleBarFontSize = "14";
	this.titleBarTextAlign = "center";
	this.titleBarCloseButtonImageUrl = "images/closewindowbtn2.png";
	
	// Pop up body container types: content(html content), element(basic elements) and page(page url, use an iframe to contain it).
	this.bodyContainerType = "page"; 
	// for different container types:
	// - content: set html content to this value.
	// - element: set element id to this value.
	// - page: set page url to this value.
	this.bodyContainerTypeValue = "";
	this.bodyContainerIframeSrc = "";
	//this.body.innerHTML = "";
	this.bodyBackgroundColor = "#FFFFFF";
}
var popUpWinDefault = new popUpWindowDefaultValues();

function popUpWindow(windowName)
{
	// If no window name, add a temp window name.
	if(windowName == null)
	{
		// Record the new unnamed windows count.
		popWinUnnamedWindowCount += 1;
		// Add a name for current new unnamed window.
		windowName = "Temp" + popWinUnnamedWindowCount;
	}
	this.name = windowName; // the name of the object.
	this.clientId = popWinClientIdPrefix + windowName;// the id of the pop up div element.
	this.height = popUpWinDefault.height;
	this.width = popUpWinDefault.width;
	this.alignCenter = popUpWinDefault.alignCenter; // if it is true, the "left" and "top" will be ignored.
	this.left = popUpWinDefault.left;
	this.top = popUpWinDefault.top;
	this.hasBorder = popUpWinDefault.hasBorder;
	this.borderThick = popUpWinDefault.borderThick; // the thick of the pop up window border.
	this.borderColor = popUpWinDefault.borderColor; // the color of the pop up window border.
	this.ie6DropdownCompatible = popUpWinDefault.ie6DropdownCompatible;
	// Show a mask to make parent window can't be click.
	this.hasMask = popUpWinDefault.hasMask;
	// Transparent the background.
	// Note: 1. if you set both "hasMask" and "transparent" to true, the transparent will not work.
	//       2. for transparent, the "body.backgroundColor" will not work.
	this.transparent = popUpWinDefault.transparent;
	// Drag the title bar of the pop up window.
	this.allowDrag = popUpWinDefault.allowDrag;
	
	this.flyDirection = popUpWinDefault.flyDirection;
	
	// If no title bar for pop up window, you can set "hasTitleBar" to false.
	this.hasTitleBar = popUpWinDefault.hasTitleBar;
	this.titleBar = new Object();
	this.titleBar.height = popUpWinDefault.titleBarHeight;
	this.titleBar.backgroundColor = popUpWinDefault.titleBarBackgroundColor;
	this.titleBar.foreColor = popUpWinDefault.titleBarForeColor;
	this.titleBar.fontSize = popUpWinDefault.titleBarFontSize;
	this.titleBar.innerHTML = popUpWinDefault.titleBarInnerHTML;
	this.titleBar.fontBold = popUpWinDefault.titleBarFontBold;
	this.titleBar.textAlign = popUpWinDefault.titleBarTextAlign;
	this.titleBar.closeButtonImageUrl = popUpWinDefault.titleBarCloseButtonImageUrl;
	
	// Pop up body container types: content(html content), element(basic elements) and page(page url, use an iframe to contain it).
	this.bodyContainerType = popUpWinDefault.bodyContainerType; 
	// for different container types:
	// - content: set html content to this value.
	// - element: set element id to this value.
	// - page: set page url to this value.
	this.bodyContainerTypeValue = popUpWinDefault.bodyContainerTypeValue;	
	this.bodyContainerIframeSrc = popUpWinDefault.bodyContainerIframeSrc;
	this.body = new Object();
	//this.body.innerHTML = "";
	this.body.backgroundColor = popUpWinDefault.bodyBackgroundColor;	
	// If set "bodyContainerType" to "page", "pageIframeScrolling" will control the scroll bar of the iframe.
	// Values for "pageIframeScrolling": "auto", "yes" and "no". Default is "no".
	this.body.pageIframeScrolling = "no";
	//this.buttonRowHeight = 30; // the hight of the buttons bar.
	//this.buttonRowHTML = ""; // the html content of the button row.	
}
/*popUpWindow.prototype.close = function()
{
	var divPopWin = document.getElementById(this.clientId);
	if(divPopWin)
		document.removeChild(divPopWin);
}*/

// Init the mask layer for pop up window.
function initPopUpMask()
{
	var popMask = document.createElement("iframe");
	popMask.setAttribute("id","iframePopUpMask");
	popMask.setAttribute("scrolling","no");
	popMask.setAttribute("frameborder","0");
	popMask.className = "divbg";
	var popWinsContainer = getPopUpWindowsContainer();
	popWinsContainer.appendChild(popMask);
}

// Get the center postion of the current popup window, the postion is the top-left corner of the popup window.
popUpWindow.prototype.GetCenterPosition = function()
{
    var mydiv = document.getElementById(this.clientId);
    var centerPostion = {Top:0, Left: 0};
	if(clientBrowser.isFireFox || clientBrowser.isSafari)
	{
		centerPostion.Left = document.body.scrollLeft+(document.body.clientWidth-mydiv.offsetWidth)/2;
		if(clientBrowser.isSafari)
			centerPostion.Top = document.body.scrollTop+(innerHeight-mydiv.offsetHeight)/2;
		else
			centerPostion.Top = document.body.scrollTop+(document.body.clientHeight-mydiv.offsetHeight)/2;			
	}
	else
	{
		centerPostion.Top = document.body.scrollTop+(document.body.clientHeight-mydiv.offsetHeight)/2;
		centerPostion.Left = document.body.scrollLeft+(document.body.clientWidth-mydiv.offsetWidth)/2;
	}
    return centerPostion;
}

// Move the pop up window to browser center.
// Added by Andy Wan, Jan 11, 2007.
popUpWindow.prototype.moveToCenter = function()
{
	window.document.getElementById(this.clientId).style.display = 'block';
	var mydiv = document.getElementById(this.clientId);
	var centerPostion = this.GetCenterPosition();
	if(clientBrowser.isFireFox || clientBrowser.isSafari)
	{
		mydiv.style.left = centerPostion.Left;
		mydiv.style.top = centerPostion.Top;		
	}
	else
	{
		mydiv.style.posTop = centerPostion.Top;
		mydiv.style.posLeft = centerPostion.Left;			
	}	
	var top =mydiv.style.top.replace('px','');
	if(top < 0)
		mydiv.style.top = '0px';
}
// Get the container for pop up windows.
function getPopUpWindowsContainer()
{
	var popWinsContainer = document.getElementById("popWinsContainer"); 
	if(popWinsContainer == null)
	{
		popWinsContainer = document.createElement("div");
		popWinsContainer.setAttribute("id","popWinsContainer");
		document.body.appendChild(popWinsContainer);
	}
	return popWinsContainer;
}

// Show/hide the mask for pop up window.
// Note: this function need to use "INCLUDE/pageHeader.ascx" user control.
// Added by Andy Wan, Jan 11, 2007.
function popWinShowMask(isShow)
{
	var divbg = document.getElementById("iframePopUpMask");
	if(divbg == null)
	{
		initPopUpMask();
		divbg = document.getElementById("iframePopUpMask");
	}
	if(isShow)
	{
		try
		{
			var appUrl = GetRelativePath2();
			divbg.src = appUrl + "blank.html";
		}
		catch(e)
		{
			divbg.src = "blank.html";
		}
		var availHeight1 = document.body.scrollHeight;
		divbg.style.width = screen.availWidth;
		var curHeight = document.body.scrollHeight;
		if(curHeight >= availHeight1)
			divbg.style.height = curHeight;
		else
			divbg.style.height = availHeight1;
		popWinMaskShow = true;
	}
	else
	{
		divbg.style.width = 0;
		divbg.style.height = 0;
		popWinMaskShow = false;
	}
}
Number.prototype.NaN0=function(){return isNaN(this)?0:this;}
// Show the pop up window.
popUpWindow.prototype.show = function()
{
	var popWinsContainer = getPopUpWindowsContainer();
	var topPopWinObject = this;
	var popupTop;
	// Check if the pop up is exist, if it exists, do nothing.
	// If the pop up exists and it is hidden, re-show it.
	var tmpPopWin = document.getElementById(this.clientId)
	if(tmpPopWin != null)
	{
		if(tmpPopWin.style.display == "none")
			tmpPopWin.style.display = "block";
		return;
	}
	//let top of iframe below the banner if it is not.
	popupTop = document.body.scrollTop + document.body.clientHeight/2 - parseInt(this.height)/2;
	if(popupTop < 135 && this.alignCenter == true)
	{
		this.alignCenter = false;
		this.top = 155;
		this.left = document.body.scrollLeft+(document.body.clientWidth - this.width)/2;
	}

	// Close all opening pop up windows.
	clearPopUpWindows();
	// Add window name to window names list.
	popWinArrWindowNames[popWinArrWindowNames.length] = this.name;
	
	// Create a new div element.
	var popWin = document.createElement('div');
	// Set the id value for the div element.
	popWin.setAttribute("id",this.clientId);
	popWin.className = "popWin";
	// Set the style of the pop up window.
	popWinZIndex = popWinZIndex + 1;
	popWin.style.zIndex = popWinZIndex;	
	popWin.style.display = "block";
	popWin.style.left = this.left;
	popWin.style.top = this.top;
	popWin.style.width = this.width;
	popWin.style.height = this.height;
	if(this.hasBorder)
	{
	    popWin.style.border = this.borderThick + "px solid " + this.borderColor;
	}
	popWin.style.position = "absolute";
	popWin.onmousedown=function()
	{
		// If multiple pop up windows are showing, click any one window will put it to the front.
		popWinZIndex = popWinZIndex + 1;
		popWin.style.zIndex = popWinZIndex;
		// Set this pop up's window name as the current active window name.
		popWinActiveWindowName = topPopWinObject.name;
	}
	
	// Calculate the pop up window body height.
	var contentHeight = this.height;// - this.buttonRowHeight;
	if(this.hasTitleBar)
	{
		contentHeight = this.height - this.titleBar.height;
		if(clientBrowser.isFireFox)
			contentHeight = contentHeight - 3 - this.borderThick;
		/*if(clientBrowser.isFireFox)
			contentHeight = contentHeight - 17;*/
	}
	/*else
	{
		if(clientBrowser.isFireFox)
			contentHeight = contentHeight - 10;
	}*/
	// If current page has mouse move or mouse up event, disable the drag function for pop up window.
	if(popWinIsDragWork == false)
	{
		if(document.onmousemove || document.onmouseup)
		{
			this.allowDrag = false;
		}
		else
		{
			popWinIsDragWork = true;
		}
	}
		
	// Title bar.
	if(this.hasTitleBar)
	{
		var popWinTitleBar = document.createElement("div");
		popWinTitleBar.style.backgroundColor = this.titleBar.backgroundColor;
		popWinTitleBar.style.color = this.titleBar.foreColor;
		popWinTitleBar.style.fontSize = this.titleBar.fontSize + "px";
		popWinTitleBar.style.height = this.titleBar.height;
		popWinTitleBar.style.textAlign = this.titleBar.textAlign;
		popWinTitleBar.style.paddingTop = "3px";
		popWinTitleBar.style.paddingBottom = "3px";
		popWinTitleBar.id="popWinTitle_" + this.name;
		if(this.titleBar.fontBold)
			popWinTitleBar.style.fontWeight="bold";
		if(this.allowDrag)
		{
			popWinTitleBar.style.cursor = "move";
			document.onmousemove = dragMouseMove;
			document.onmouseup   = dragMouseUp;
		}
		var arrPopWinTitleBarContent = [];
		arrPopWinTitleBarContent.push("<span class=\"popWinTitleBar_CloseButton\"><IMG class=\"cursorPointer\" onclick=\"");
		arrPopWinTitleBarContent.push("closePopUpWindow();");
		arrPopWinTitleBarContent.push("\" alt=\"Close\" src=\"");
		arrPopWinTitleBarContent.push(GetRelativePath2());
		arrPopWinTitleBarContent.push(this.titleBar.closeButtonImageUrl);
		arrPopWinTitleBarContent.push("\"></span>");
		arrPopWinTitleBarContent.push("<div class=\"popWinTitleBar_Content\">");
		arrPopWinTitleBarContent.push(this.titleBar.innerHTML);
		arrPopWinTitleBarContent.push("</div><div class=\"clearFloat\"></div>");
		popWinTitleBar.innerHTML = arrPopWinTitleBarContent.join('');
		if(this.allowDrag)
		{			
			popWinTitleBar.onmousedown = function(e)
			{
				e = e || window.event;
				popWinDragWindow = document.getElementById(topPopWinObject.clientId);			
				popWinMouseOffset = getMouseOffset(popWinDragWindow, e);
			}
		}
		popWin.appendChild(popWinTitleBar);
	}
	// Body.
	var popWinBody = document.createElement("div");
	popWinBody.style.height = contentHeight;
	// If current pop up window has title bar, show the separator between title bar and body.
	if(this.hasTitleBar)
		popWinBody.style.borderTop = this.borderThick + "px solid " + this.borderColor;	
	if(!this.transparent)
		popWinBody.style.backgroundColor = this.body.backgroundColor;
	//else
	//{
		// For transparent window, if the browser is not IE 6, we shouldn't set the background color for pop up window body.
		// if it is IE 6, set the background color to white to make the transparent looks better.
		//if(clientBrowser.isIE6)
		//	popWinBody.style.backgroundColor = "#FFFFFF";
	//}
	switch(this.bodyContainerType)
	{
		case "content":
			// if the body container is content, show the html content.
			popWinBody.style.padding = "5px";
			popWinBody.innerHTML = this.bodyContainerTypeValue;
			break;
		case "element":
			// if the body container is an element, move the element here and display it.
			popWinBody.style.padding = "5px";
			var popWinBodyElement = document.getElementById(this.bodyContainerTypeValue);
			if(popWinBodyElement)
				popWinBody.appendChild(popWinBodyElement);
			break;
		case "object":
			popWinBody.appendChild(this.bodyContainerTypeValue);
			break;
		case "page":
			// if the body container is a page, add a iframe to contain the page url.
			//popWinBody.innerHTML = "<iframe frameBorder=\"0\" width=\"100%\" allowTransparency=\"true\" scrolling=\"" + this.body.pageIframeScrolling + "\" height=\"" + contentHeight + "\" src=\"" + this.bodyContainerTypeValue + "\"></iframe>";
			var bodyContainerIframe;
			if(this.bodyContainerIframeSrc == null || this.bodyContainerIframeSrc == "")
				bodyContainerIframe = document.createElement("iframe");
			else
				bodyContainerIframe = document.getElementById(this.bodyContainerIframeSrc);
			bodyContainerIframe.setAttribute("frameBorder","0");
			bodyContainerIframe.setAttribute("width","100%");
			bodyContainerIframe.setAttribute("allowTransparency","true");
			bodyContainerIframe.setAttribute("scrolling",this.body.pageIframeScrolling);
			bodyContainerIframe.setAttribute("height",contentHeight);
			bodyContainerIframe.setAttribute("src",this.bodyContainerTypeValue);
			popWinBody.appendChild(bodyContainerIframe);
			break;
	}
	popWin.appendChild(popWinBody);
	
	// In IE 6, the dropdown list and list box control can display over the popup layer, add an iframe here to avoid this display issue.
	if(this.ie6DropdownCompatible && clientBrowser.isIE6)
	{
		var popWinFocusInput = document.getElementById("popWinFocusInput");
		if(popWinFocusInput == null)
		{
			popWinFocusInput = document.createElement("<input type='text'>");
			popWinFocusInput.setAttribute("id","popWinFocusInput");
			popWinFocusInput.style.width="0";
			popWinFocusInput.style.height="0";		
			var tdLogoArea = document.getElementById("tdLogoArea");
			if(tdLogoArea)
			{
				tdLogoArea.appendChild(popWinFocusInput);
			}
		}
		var popWinIe6Iframe = document.createElement("div");
		popWinIe6Iframe.innerHTML = "<iframe id=\"popWinIframe\" frameBorder=0 style=\"position:absolute; visibility:inherit; top:0px; left:1px; width:99%;height:" + this.height +"px;z-index:-1; filter='progid: DXImageTransform.Microsoft.Alpha(style=0,opacity=0)';\"></iframe>";
		popWin.appendChild(popWinIe6Iframe);
	}
	popWinsContainer.appendChild(popWin);
	
	
	// If need to transparent the background of the pop up window, transparent it.
//	if(this.transparent)
//	{
//		if(clientBrowser.isIE && !clientBrowser.isIE7)
//			popWin.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=80)";
//		else
//			popWin.style.backgroundColor = 'transparent';		
//		popWin.style.backgroundImage='url(images/transBg.png)';	
//	}
	
	// If need to show mask, show it.
	if(this.hasMask)
		popWinShowMask(true);
	
	if(this.flyDirection == PopUpFlyDirections.None)
	{
	    // If alignCenter is true, move the pop up window to the browser center.
	    if(this.alignCenter)
	    {
		    this.moveToCenter();
	    }
	}
	else
	{
	    var initPostion = this.GetCenterPosition()
        var endPostion = this.GetCenterPosition()
        var mydiv = document.getElementById(this.clientId);
        switch(this.flyDirection)
        {
            case PopUpFlyDirections.LeftToCenter:
                initPostion.Top = endPostion.Top;
                initPostion.Left = 0 - mydiv.offsetWidth;
                MoveObjectToPosition(this.clientId, initPostion.Top, initPostion.Left);
                break;
            case PopUpFlyDirections.TopToCenter:
                initPostion.Top = 0 - mydiv.offsetHeight;
                initPostion.Left = endPostion.Left;
                MoveObjectToPosition(this.clientId, initPostion.Top, initPostion.Left);
                break;
        }
        // Wait 12 seconds to start fly so that the iframe can be loaded first.
        setTimeout("ObjectFly('" + this.clientId + "', '" + endPostion.Top + "', '" + endPostion.Left + "')", 7000);
	}
	// Set current pop up window as the active window.
	popWinActiveWindowName = this.name;
}

// Close/hide a pop up window.
function closePopUpWindow(isFullyClose)
{
	// Close/hide the current active window.
	windowName = popWinActiveWindowName;
	if(document.getElementById("popWinFocusInput"))
	{
		document.getElementById("popWinFocusInput").focus();
	}
	closeSpecifiedPopUpWindow(windowName, isFullyClose)
}
// Close/hide a pop up window with a specified window name.
function closeSpecifiedPopUpWindow(windowName, isFullyClose)
{
	var divPopWin = document.getElementById(popWinClientIdPrefix + windowName);
	// Set current active window name to null.
	popWinActiveWindowName = null;
	
	if(isFullyClose != null && isFullyClose == false)
	{
		// Hide the pop up window.
		if(divPopWin)
			divPopWin.style.display = "none";		
	}
	else
	{
		// Fully remove the pop up window from page elements list.
		removePopUpWindowNamesFromArray(windowName);
		if(divPopWin)
		{
			var popWinsContainer = getPopUpWindowsContainer();
			popWinsContainer.removeChild(divPopWin);
		}
		// if the pop up window mask is shown, close it.
		if(popWinMaskShow)
			popWinShowMask(false);
	}
}
// Re-show a hidden pop up window.
function reshowHiddenPopUpWindow(windowName)
{
	var divPopWin = document.getElementById(popWinClientIdPrefix + windowName);
	if(divPopWin)
		divPopWin.style.display = "block";
}

// Remove pop up window name from window names array list (popWinArrWindowNames).
function removePopUpWindowNamesFromArray(windowName)
{
	for(var i = 0; i < popWinArrWindowNames.length; i ++)
	{
		if(popWinArrWindowNames[i] == windowName)
		{
			// Delete the window name from the list.
			popWinArrWindowNames.splice(i,1);
			// The window names can't be repeated, when the window name for delete is found, stop the loop and return.
			return;
		}
	}
}
// Close all pop up windows in current page.
function clearPopUpWindows()
{
	for(var i = popWinArrWindowNames.length - 1; i >= 0; i --)
	{
		closeSpecifiedPopUpWindow(popWinArrWindowNames[i]);
	}
}
// Quick open an iframe pop up window with a default style.
function popUpWindowQuickOpen(title,windowWidth, windowHeight,url, windowName)
{
	var myPopUp = new popUpWindow(windowName);
	myPopUp.width = windowWidth;
	myPopUp.height = windowHeight;
	myPopUp.titleBar.innerHTML = title;
	myPopUp.bodyContainerTypeValue = url;
	myPopUp.show();
}

function dragMouseMove(e)
{
	if(popWinDragWindow)
	{
		e = e || window.event;
		var target = e.target || e.srcElement;
		//var mouseOffset = getMouseOffset(popWinDragWindow,e);
		var mousePos = mouseCoords(e);
		popWinDragWindow.style.position = 'absolute';
		popWinDragWindow.style.top = mousePos.y - popWinMouseOffset.y;
		popWinDragWindow.style.left = mousePos.x - popWinMouseOffset.x;
	}
	if(popWinDragWindow)
		return false;
}

function dragMouseUp(e)
{
	if(popWinDragWindow)
		popWinDragWindow = null;
}
// ********************************** End Pop Up Window ********************************** //

/* Metro Area Begin*/
function GetCurrentMetroAreaCode()
{
	var cMetroAreaCode = -1;
	
	var metroAreaCodeEle = document.getElementById(gCtlIdPrefix.PageHeader + "ph_pub_MetroAreaCode");
	if(metroAreaCodeEle == null)
		metroAreaCodeEle = window.top.document.getElementById(gCtlIdPrefix.PageHeader + "ph_pub_MetroAreaCode");
	
	if(metroAreaCodeEle != null)
		cMetroAreaCode = parseInt(metroAreaCodeEle.value);
		
	if(cMetroAreaCode == -1)
	{ 
		var cMetroAreaCodeCookie = GetCookie("MetroAreaCode");
		// If metro area can't get from the control in pageheader, then get from cookies. Such as html page.
		// If can't get from all the way, then return to home page.
		if(cMetroAreaCodeCookie!=null)
			cMetroAreaCode = cMetroAreaCodeCookie;
		else if(GetCookie("lastMapSearch")!=null)
			cMetroAreaCode = 1;
		else 
		{
			var curURL = window.location.href.toLowerCase();
			if(IsValidPageForMetroArea(curURL) == false)
			{
				if(curURL.indexOf("activeid=") != -1)
				{
					var defaultMetroAreaCode = 1;
					SetCurrentMetroAreaCode(defaultMetroAreaCode); 				 
					if(document.getElementById(gCtlIdPrefix.MainContent + "currentSearchMetroAreaCode") != null)
					{
					    document.getElementById(gCtlIdPrefix.MainContent + "currentSearchMetroAreaCode").value = defaultMetroAreaCode;
					}
					SetCurrentMetroAreaName();
				}
				else
				{
					window.location.href = GetRelativePath2();
				}
			}
		}
	}
		
	return parseInt(cMetroAreaCode);	
}
function SetCurrentMetroAreaCode( cMetroAreaCode )
{
	var MetroAreaCodeCookieName = "MetroAreaCode"; 
	
	var metroAreaCode; 
	var IsSuccess = true;	
	 
	if(cMetroAreaCode != null)
	{
	    metroAreaCode = parseInt(cMetroAreaCode);
	    if(document.getElementById(gCtlIdPrefix.PageHeader + "ph_pub_MetroAreaCode")!=null)
		    document.getElementById(gCtlIdPrefix.PageHeader + "ph_pub_MetroAreaCode").value = metroAreaCode;
	    iGen.WebServices.Common.SetCurrentMetroAreaCode(metroAreaCode,onSetCurrentMetroAreaCodeSucceeded,null,{"MetroAreaCodeCookieName":MetroAreaCodeCookieName,"metroAreaCode":metroAreaCode});				
	}
	else
	{
	    var metroAreaCodeEle = document.getElementById(gCtlIdPrefix.MainContent + "currentSearchMetroAreaCode");
			if(metroAreaCodeEle == null)
			    metroAreaCodeEle = document.getElementById(gCtlIdPrefix.ucCustomSearch + "currentSearchMetroAreaCode");
					
			if(metroAreaCodeEle != null && metroAreaCodeEle.value != null && metroAreaCodeEle.value != "") 
				metroAreaCode = metroAreaCodeEle.value;
			else
			{
				if(metroAreaCodeEle != null)
					metroAreaCodeEle.value = GetCurrentMetroAreaCode();	
					
				return 	IsSuccess;
			}			
			SetCookie( MetroAreaCodeCookieName, metroAreaCode);
			if(document.getElementById(gCtlIdPrefix.PageHeader + "ph_pub_MetroAreaCode")!=null)
		        document.getElementById(gCtlIdPrefix.PageHeader + "ph_pub_MetroAreaCode").value = metroAreaCode;
	}
		
	return 	IsSuccess;
}
function onSetCurrentMetroAreaCodeSucceeded(result,userContext)
{
	var cMetroAreaCodeAJAX = result;			
	if(cMetroAreaCodeAJAX != null && parseInt(cMetroAreaCodeAJAX) == userContext.metroAreaCode )		
		SetCookie( userContext.MetroAreaCodeCookieName, userContext.metroAreaCode);
}

function GetCurrentMetroAreaName(MetroAreaCode)
{
	var MeName = "";
	switch(eval(MetroAreaCode)) 
	{
        case 1: 
            MeName = "Northern California";
            break;
        case 20:
            MeName = "Southern California";//Los Angeles Area
            break;
        case 30:
            MeName = "Massachusetts";
            break;
        case 31:
            MeName = "DC/Maryland/Virginia";//District Of Columbia
            break;
        case 32:
            MeName = "Nevada";
            break;
        case 40:
            MeName = "Texas";
            break;		
        case 41:
            MeName = "North Carolina";
            break;
        case 42:
            MeName = "Georgia";
            break;	
        case 43:
            MeName = "Florida";
            break;
		case 44:
		    MeName = "Pennsylvania";
		    break;
		case 45:
		    MeName = "New Jersey";
		    break;
		case 46:
		    MeName = "Illinois";
		    break;
		case 47:
		    MeName = "Arizona";
		    break;
		case 48:
		    MeName = "New York";
		    break;
		case 49:
		    MeName = "Oregon";
		    break;
		case 50:
		    MeName = "Washington";
		    break;
		case 51:
		    MeName = "Utah";
		    break;
		case 52:
		    MeName = "Colorado";
		    break;
		case 53:
		    MeName = "Alabama";
		    break;
		case 54:
		    MeName = "Ohio";
		    break;
		case 55:
		    MeName = "Michigan";
		    break;
		case 56:
		    MeName = "Nevada";
		    break;
		case 57:
		    MeName = "Tennessee";
		    break;
		case 58:
		    MeName = "South Carolina";
		    break;
		case 59:
		    MeName = "Rhode Island";
		    break;
		case 60:
		    MeName = "Delaware";
		    break;
		case 61:
		    MeName = "Kansas";
		    break;
		case 65:
		    MeName = "Minnesota";
		    break;
		case 66:
		    MeName = "Wisconsin";
		    break;
		case 67:
		    MeName = "Iowa";
		    break;
		case 68:
		    MeName = "Nebraska";
		    break;
		case 69:
		    MeName = "Missouri";
		    break;
		case 70:
		    MeName = "Oklahoma";
		    break;
		case 71:
		    MeName = "Arkansas";
		    break;
		case 72:
		    MeName = "Louisiana";
		    break;
		case 73:
		    MeName = "Mississippi";
		    break;
		case 81:
		    MeName = "SouthCarolina";
		    break;
		case 82:
		    MeName = "RhodeIsland";
		    break;
		case 83:
		    MeName = "Ohio";
		    break;
		case 84:
		    MeName = "Michigan";
		    break;
		case 85:
		    MeName = "Indiana";
		    break;
		case 86:
		    MeName = "Kentucky";
		    break;
		case 87:
		    MeName = "WestVirginia";
		    break;
		case 88:
		    MeName = "Vermont";
		    break;
		case 89:
		    MeName = "Maine";
		    break;
		case 90:
		    MeName = "NewHampshire";
		    break;
		case 91:
		    MeName = "Connecticut";
		    break;
		default:
			break;
	}
	return MeName;
}
function SetCurrentMetroAreaName()
{
    var cMetroAreaCode = GetCurrentMetroAreaCode();

	if( window.top.document.getElementById("metroLink")!=null && eval(cMetroAreaCode)!= -1 ) // If user not select metro area then	not show the metro area string.
	{
		if(cMetroAreaCode == 31)
		{
            window.top.document.getElementById("metroLink").innerHTML = "";
            return;
		}
		window.top.document.getElementById("metroLink").innerHTML = GetCurrentMetroAreaName(cMetroAreaCode) + " | <a class=\"cursorPointer\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" onclick=\"showMetroAreaSelectWindow('change');\" rel=\"nofollow\">Change Area</a>";
	}
}

function CheckMetroArea( pageUrl )
{
	if( GetCurrentMetroAreaCode() == -1 )
	{
	    showMetroAreaSelectWindow("select");
		document.getElementById(gCtlIdPrefix.Master + "metroAreaSelection").setAttribute("pageUrl",pageUrl);
	//	document.getElementById("metroAreaSelection").getAttribute("pageUrl");
	}
	else
		window.location.href = GetRelativePath2() + pageUrl;
}
// Show metro area select window.
function showMetroAreaSelectWindow(popUpType)
{
	var metroAreaSelection = document.getElementById(gCtlIdPrefix.Master + "metroAreaSelection");
	var metroAreaSelectionHTML = metroAreaSelection.innerHTML;
    var strReg = /ChangeMetroArea/g;
    var metroAreaCount = metroAreaSelectionHTML.match(strReg); //metro area count for getting DIV' height.

	var metroAreaWindowTitle = "Select a Metro Area";
	if(popUpType == "change")
		metroAreaWindowTitle = "Change Metro Area";
	var popSelectMetroArea = new popUpWindow();
	popSelectMetroArea.width = "412";
	popSelectMetroArea.height = 100 + 16 * eval(metroAreaCount.length/2+1);//Automatically get the DIV's height.
	popSelectMetroArea.borderColor = "#000000";
	popSelectMetroArea.titleBar.fontSize = "14";
	popSelectMetroArea.titleBar.innerHTML = metroAreaWindowTitle;
	popSelectMetroArea.bodyContainerType = "content";
	popSelectMetroArea.bodyContainerTypeValue = metroAreaSelectionHTML;
	popSelectMetroArea.show();
}

function IsValidPageForMetroArea(pageUrl)
{
    var isValid = true;
    if(pageUrl.indexOf("mapsearch.aspx") != -1)
		isValid = false;
    else if(pageUrl.indexOf("propertysearch.aspx") != -1)
		isValid = false;
    else if(pageUrl.indexOf("openhouse.aspx") != -1)
		isValid = false;
    else if(pageUrl.indexOf("market-statistics.aspx") != -1)
		isValid = false;
    else if(pageUrl.indexOf("schools.aspx") != -1)
		isValid = false;
	else if(pageUrl.indexOf("/propertysearch") != -1)
		isValid = false;
	else if(pageUrl.indexOf("/real-estate-map-search") != -1)
		isValid = false;		
		
	return isValid;    	
}
function ChangeMetroArea( metroCode)
{
	if(parseInt(metroCode) == GetCurrentMetroAreaCode())
		closePopUpWindow();	
	else
	{
	    metroAreaCode = parseInt(metroCode);
	    iGen.WebServices.Common.SetCurrentMetroAreaCode(metroAreaCode,onChangeMetroAreaSucceeded,null,{"metroCode":metroCode,"metroAreaCode":metroAreaCode});
	}
	
}
function onChangeMetroAreaSucceeded( result,userContext )
{
	var MetroAreaCodeCookieName = "MetroAreaCode"; 
	var metroAreaCode = userContext.metroAreaCode; 
	var IsSuccess = true;
    var cMetroAreaCodeAJAX = result;			
	if(cMetroAreaCodeAJAX != null && parseInt(cMetroAreaCodeAJAX) == metroAreaCode )		
		SetCookie( MetroAreaCodeCookieName, metroAreaCode);
	else
	    IsSuccess = false;
	if(document.getElementById(gCtlIdPrefix.PageHeader + "ph_pub_MetroAreaCode")!=null)
		document.getElementById(gCtlIdPrefix.PageHeader + "ph_pub_MetroAreaCode").value = metroAreaCode;
	
	if(IsSuccess)
	    setTimeout('RefreshPageForChangeMetroArea('+userContext.metroCode+')',1000);
}

function RefreshPageForChangeMetroArea(metroCode)
{
	var Url = window.location.href.toLowerCase();		
	if(Url.indexOf('?')!=-1)
	{
        if(Url.indexOf('searchid')!= -1)
        {
			if(Url.indexOf('customsearchresults.aspx')!=-1)
				Url =GetRelativePath2()+"propertysearch.aspx";	
			else if(Url.indexOf('propertysearch.aspx')!=-1)
				Url =GetRelativePath2()+"propertysearch.aspx";					
			else if(Url.indexOf('openhousesresults.aspx')!=-1)
				Url =GetRelativePath2()+"openhouse.aspx";
		}
		
		if(Url.indexOf('mapsearch.aspx')!=-1)
			Url =GetRelativePath2()+"mapsearch.aspx";				
	}
	if(Url.indexOf('?')!=-1 && Url.indexOf('searchresults.aspx')!= -1)
		Url =GetRelativePath2()+"propertysearch.aspx";
	
	if(Url.indexOf('homes-for-sale-near/schools') != -1)
		Url = GetRelativePath2() + "propertysearch.aspx";
				
	if(Url.indexOf('/real-estate-map-search/')!=-1)
		Url =GetRelativePath2()+"mapsearch.aspx";
		
	if(Url.indexOf('/propertysearch/')!=-1 || Url.indexOf('/homesearch/')!=-1)
		Url =GetRelativePath2()+"propertysearch.aspx";

    if (document.getElementById(gCtlIdPrefix.Master + "metroAreaSelection").getAttribute("pageUrl") != null && document.getElementById(gCtlIdPrefix.Master + "metroAreaSelection").getAttribute("pageUrl") != "")
		Url =GetRelativePath2()+document.getElementById(gCtlIdPrefix.Master + "metroAreaSelection").getAttribute("pageUrl");				

	window.location.href = Url.replace(/\#/g,'');
}
/* Metro Area End */

function pHeaderForSEO()
{
	var btnFcs = document.getElementById(gCtlIdPrefix.PageHeader + "btnFcs");
	if( btnFcs != null )
		btnFcs.disabled = true;
	if(clientBrowser.isFireFox || clientBrowser.isIE6 || clientBrowser.isSafari)
	{
		if( document.getElementById("divMenuBar") != null )
			document.getElementById("divMenuBar").style.marginTop = "0px";
	}
	loadMultiLanguages();
	TrackYahooCampaign();
}

function loadMultiLanguages() {
    if (window.location.href.indexOf("/agent") > 0)
        return;
    var divMultiLanguages = document.getElementById("divMultiLanguages");
    var englishVersion = "<div class=\"switcherAassemble switchOnEN\"></div>";
    var spanishVersion = "<div class=\"switcherAassemble switchOffES\" onclick=\"setMultiLanguages('es')\"></div>";
    var chineseVersion = "<div class=\"switcherAassemble switchOffCN\" onclick=\"setMultiLanguages('zh-CN')\"></div>";
    var language = GetCookie("language");
    if (language != "" && language != null) {
        switch (language) {
            case "en":
                //use default
                break;
            case "es":
                englishVersion = "<div class=\"switcherAassemble switchOffEN\" onclick=\"setMultiLanguages('en')\"></div>";
                spanishVersion = "<div class=\"switcherAassemble switchOnES\"></div>";
                chineseVersion = "<div class=\"switcherAassemble switchOffCN\" onclick=\"setMultiLanguages('zh-CN')\"></div>";
                break;
            case "zh-CN":
                englishVersion = "<div class=\"switcherAassemble switchOffEN\" onclick=\"setMultiLanguages('en')\"></div>";
                spanishVersion = "<div class=\"switcherAassemble switchOffES\" onclick=\"setMultiLanguages('es')\"></div>";
                chineseVersion = "<div class=\"switcherAassemble switchOnCN\"></div>";
                break;
        }
    }
    divMultiLanguages.innerHTML = englishVersion + spanishVersion + chineseVersion;
}

function setMultiLanguages(language) {
    SetCookie("language", language);
    TrackGoogleAnalytics("Language-" + language);
    window.location.href = window.location.href.replace(/\#/g, '');
}

function TrackYahooCampaign()
{
	//Track yahoo campaign
	var hdCampValue		   = document.getElementById(gCtlIdPrefix.PageHeader + "hdCampValue");
	var hdOVKEYValue	   = document.getElementById(gCtlIdPrefix.PageHeader + "hdOVKEYValue");
	var ggAnalyticsAccount = document.getElementById(gCtlIdPrefix.PageHeader + "ggAnalyticsAccount");
	if((hdCampValue!=null && hdCampValue.value!="") 
		&& (hdOVKEYValue!=null && hdOVKEYValue.value!="") && ggAnalyticsAccount!=null)
	{
		_uacct = ggAnalyticsAccount.value;
		_uccn  = hdCampValue.value;
		_ucsr  = "YAHOO";
		_ucmd  = "PPC";
		_uctr  = hdOVKEYValue.value;
		_ucct  = "1";
		urchinTracker();
	}
}

/********************************** Tab Pages Control [BEGIN] **********************************/
/* Created by Andy Wan, May 15, 2007. */
function mTabPages(divContainerId, tabPagesWidth, tabTheme)
{
	// Setup tab theme.
	if(tabTheme == null || tabTheme == "")
	{
		tabTheme = "";
	}
	else
	{
		tabTheme = "_" + tabTheme;
	}
	this.themeStyle = new Object();
	this.themeStyle.tabsDiv = "divTabs" + tabTheme;
	this.themeStyle.tabsContainer = "tabContainer" + tabTheme;
	this.themeStyle.tabsFirstSeparator = "tabsFirstSeparator" + tabTheme;
	this.themeStyle.tabPage = "tabPage" + tabTheme;	
	this.themeStyle.tabPageCommon = "tabPageCommon" + tabTheme;
	this.themeStyle.tabPageCommonHover = "tabPageCommonHover" + tabTheme;
	this.themeStyle.tabPageSelected = "tabPageSelected" + tabTheme;
	this.themeStyle.tabSeparator = "tabSeparator" + tabTheme;
	this.themeStyle.tabContent = "tabContent" + tabTheme;
	
	this.tabPagesContainerId = divContainerId;
	this.TabItems = new Array();
	this.divTabPagesContainer = document.getElementById(divContainerId);
	if(this.divTabPagesContainer != null)
	{
		this.divTabs = document.createElement("div");
		this.divTabs.id = this.tabPagesContainerId + "_Tabs";
		this.divTabs.className = this.themeStyle.tabsDiv;
		this.divTabs.style.width = tabPagesWidth;
		this.divTabPagesContainer.style.width = tabPagesWidth;
		this.divTabPagesContainer.appendChild(this.divTabs);
		
		this.divTabsContainer = document.createElement("ul");
		this.divTabsContainer.className = this.themeStyle.tabsContainer;
		// Add first separator for all tabs.
		var myTabsFirstSeparator = document.createElement("li");
		myTabsFirstSeparator.className = this.themeStyle.tabsFirstSeparator;
		this.divTabsContainer.appendChild(myTabsFirstSeparator);		
		this.divTabs.appendChild(this.divTabsContainer);
		
		this.divTabContent = document.createElement("div");
		this.divTabContent.id = this.tabPagesContainerId + "_TabContent";
		this.divTabContent.className = this.themeStyle.tabContent;
		this.divTabContent.style.width = tabPagesWidth;
		this.divTabPagesContainer.appendChild(this.divTabContent);
	}
}
function mTabItem()
{
	this.tabName = null;
	this.tabTitle = null;
	this.tabPageDivId = null;
	this.tabRelateFunctionName = null;
	this.selected = false;
}
// Unselect all tabs.
mTabPages.prototype.unselectAllTabs = function()
{
	for(var i = 0; i < this.TabItems.length; i ++)
	{
		if(this.TabItems[i].selected == true)
		{
			var unselectTab = document.getElementById(this.tabPagesContainerId + "_Tab" + i);
			if(unselectTab != null)
			{
				unselectTab.className = this.themeStyle.tabPage + " " + this.themeStyle.tabPageCommon;
				this.TabItems[i].selected = false;
				var unselectTabPageDiv = document.getElementById(this.TabItems[i].tabPageDivId);
				if(unselectTabPageDiv != null)
					unselectTabPageDiv.style.display = "none";				
			}
			return;
		}
	}
}
// Show a tab by the tab index.
mTabPages.prototype.showTabByIndex = function(tabIndex)
{
	this.unselectAllTabs();
	var myTab = document.getElementById(this.tabPagesContainerId + "_Tab" + tabIndex);
	myTab.className = this.themeStyle.tabPage + " " + this.themeStyle.tabPageSelected;
	this.TabItems[tabIndex].selected = true;
	var tabPageDiv = document.getElementById(this.TabItems[tabIndex].tabPageDivId);
	if(tabPageDiv != null)
		tabPageDiv.style.display = 'block';
	var tabRelateFunction = this.TabItems[tabIndex].tabRelateFunctionName;
	if(tabRelateFunction != null && tabRelateFunction != "")
		setTimeout(tabRelateFunction, 0);
}
// Show a tab by the tab name.
mTabPages.prototype.showTabByTabName = function(tabName)
{
	for(var i = 0; i < this.TabItems.length; i ++)
	{
		if(this.TabItems[i].tabName == tabName)
		{
			this.showTabByIndex(i);
			return;
		}
	}	
}
// Add a new tab to tab pages.
// Parameters:
// tabTitle: The tab title for display.
// tabPageDivId: The div id of this tab for display when clicking the tab.
// tabRelateFunctionName: The function name to call when clicking the tab.
mTabPages.prototype.addTab = function(tabName, tabTitle, tabPageDivId, tabRelateFunctionName)
{
	if(this.divTabsContainer != null)
	{
		var tabItem = new mTabItem();
		tabItem.tabName = tabName;
		tabItem.tabTitle = tabTitle;
		tabItem.tabPageDivId = tabPageDivId;
		tabItem.tabRelateFunctionName = tabRelateFunctionName;
		var tabItemIndex = this.TabItems.length;
		this.TabItems[tabItemIndex] = tabItem;
		// Add the tab.
		var myTab = document.createElement("li");
		//myTab.innerHTML = tabTitle;
		myTab.className = this.themeStyle.tabPage + " " +  this.themeStyle.tabPageCommon;
		myTab.id = this.tabPagesContainerId + "_Tab" + tabItemIndex;
		var mySpan = document.createElement("span");
		mySpan.innerHTML = tabTitle;
		myTab.appendChild(mySpan);
		
		var curTabPageDiv = document.getElementById(tabPageDivId);
		if(curTabPageDiv != null)
		{
			this.divTabContent.appendChild(curTabPageDiv);
		}	

		var iTabPagesObj = this;
		// Click event for this tab.
		myTab.onclick = function()
		{
			iTabPagesObj.unselectAllTabs();
			myTab.className = iTabPagesObj.themeStyle.tabPage + " " + iTabPagesObj.themeStyle.tabPageSelected;
			iTabPagesObj.TabItems[tabItemIndex].selected = true;
			if(tabPageDivId != null && tabPageDivId != "")
			{
				var tabPageDiv = document.getElementById(tabPageDivId);
				if(tabPageDiv != null)
					tabPageDiv.style.display = 'block';
					
				//added by Jane Jan. 4 2008 for bug 4589	
			    if(tabPageDivId == "divMainSearchContainer")
			    {
			        TrackGoogleAnalytics("Property Search UI - Main Search");
			    }
			    else if(tabPageDivId == "divMlsNumberSearchContainer")
			    {
			        TrackGoogleAnalytics("Property Search UI - MLS# Search");
			    }	
			}
			if(tabRelateFunctionName != null && tabRelateFunctionName != "")
				setTimeout(tabRelateFunctionName, 0);
		}
		// Mouse over event for this tab.
		myTab.onmouseover = function()
		{
			if(myTab.className == iTabPagesObj.themeStyle.tabPage + " " +  iTabPagesObj.themeStyle.tabPageCommon)
				myTab.className = iTabPagesObj.themeStyle.tabPage + " " +  iTabPagesObj.themeStyle.tabPageCommonHover;
		}
		// Mouse out event for this tab.
		myTab.onmouseout = function()
		{
			if(myTab.className == iTabPagesObj.themeStyle.tabPage + " " +  iTabPagesObj.themeStyle.tabPageCommonHover)
				myTab.className = iTabPagesObj.themeStyle.tabPage + " " +  iTabPagesObj.themeStyle.tabPageCommon;
		}
		this.divTabsContainer.appendChild(myTab);
		// Add a tab separator after this tab.
		var myTabSeparator = document.createElement("li");
		myTabSeparator.className = this.themeStyle.tabSeparator;
		this.divTabsContainer.appendChild(myTabSeparator);
	}
}
/********************************** Tab Pages Control [END] **********************************/
/********************************** Input Validation [BEGIN] **********************************/
// Validate phone number.
function validatePhoneNumber(phoneNO)
{
	var re = /^(1-)?[\(| ]?\d{3}[\)| |-|.]?[ |-]?\d{3}[-| |)|.]?\d{4}[ ]?(ext\.)?[-|x|X| |#]?\d{0,6}$/;
	var wholeNum = "0000000000,1111111111,2222222222,3333333333,4444444444,5555555555,6666666666,7777777777,8888888888,9999999999,1231231234,6503211133,8887668686";
	if(phoneNO.search(re) != -1)
	{
		if(wholeNum.indexOf(phoneNO) != -1 || phoneNO.substring(0,3) == "911" || phoneNO.substring(0,3) == "800" || phoneNO.substring(0,1) == "0" || phoneNO.indexOf("1111111",3,7) != -1 
		)
			return false;
		else
			return true;
	}
	else
		return false;
}


//  Validate user id
function validateIntegerNumber(intNumber)
{
	var re = "^[0-9]{1,}$";
	return (intNumber.search(re) != -1) ;	
}

// Validate email address.
function validateEmailAddress(emailAddr)
{
	var regu="^(([0-9a-zA-Z]+)|([0-9a-zA-Z]+[_.0-9a-zA-Z-]*[_.0-9a-zA-Z]+))@([a-zA-Z0-9-]+[.])+([a-zA-Z]{2}|net|NET|com|COM|gov|GOV|mil|MIL|org|ORG|edu|EDU|int|INT|cn|CN|nu|NU|de|DE|biz|BIZ)$";  
	var re = new RegExp(regu);	
	return (emailAddr.search(re) != -1);
}
/********************************** Input Validation [END] **********************************/
function doHelpMeSell()
{
	PopUpLeadPage(10);
}
// common function for pop up Lead page: View it / Buy it / Ask a Q
// Juana, May 22, 2007
function GetLeadURL(i, pic, price, address, mls, mlsDb, bed, bath, igen_key, city_code)
{
	if(city_code == null)
		city_code = "";
	var pageUrl = "customresponseemail.aspx";
	if(i+"" == "10")
	{
		pageUrl = "helpmesell.aspx";
	}
	else if(i+"" == "11")
		pageUrl = "FindForeclosure.aspx";
		
	var url = GetRelativePath2() + pageUrl + '?rtype='+ i;
	if(pic != null && price != null && address != null && mls != null  
	&& mlsDb != null && bed != null && bath != null && igen_key != null)
	{	  
		url += "&address="
			+ escape(address) +"&mls="+ mls +"&mlsDb=" + mlsDb + "&pic="+ pic +"&bed=" 
			+ bed.toString().replace("+","*") +"&bath=" + bath.replace("&","_") + "&igen_key="+ igen_key +"&price="+ price +"&city_code="+city_code;
	}
	return url;
}

//Pop Up
function PopUpLeadPage( i, pic, price, address, mls, mlsDb, bed, bath, igen_key, city_code )
{	
    iGen.WebServices.Common.CheckAndTryAutoLogin(onPopUpLeadPageSucceeded,null,{"i":i,"pic":pic,"price":price,"address":address,"mls":mls,"mlsDb":mlsDb, "bed":bed, "bath":bath, "igen_key":igen_key, "city_code":city_code});
}
function onPopUpLeadPageSucceeded(result,userContext)
{
    var i = userContext.i;
    var pic = userContext.pic;
    var price = userContext.price;
    var address = userContext.address;
    var mls = userContext.mls;
    var mlsDb = userContext.mlsDb;
    var bed = userContext.bed;
    var bath = userContext.bath;
    var igen_key = userContext.igen_key;
    var city_code = userContext.city_code;
    
	if(result == true)
	{
		if(address != null)
			address = address.replace(' - Click to see details','');
		var popUpHeight = 300;
		var popUpTitle = "";
		if( i+"" == "1"  || i+"" == "3")
			if(clientBrowser.isIE)
				popUpHeight = 480;
			else
				popUpHeight = 490;
		else if( i+"" == "10")
		{
			if(clientBrowser.isIE)
				popUpHeight = 445;//395;
			else
				popUpHeight = 445;
			popUpTitle = "Help me sell my home";
		}
		else if( i+"" == "11")
		{
			if(clientBrowser.isIE)
				popUpHeight = 400;//395;
			else
				popUpHeight = 400;
			popUpTitle = "Foreclosures and Bank Owned Homes";
		}
		else
			if(clientBrowser.isIE)
				popUpHeight = 480;
			else
				popUpHeight = 490;
		var popUpPageUrl = GetLeadURL(  i, pic, price, address, mls, mlsDb, bed, bath, igen_key, city_code );

		if(i == 10 || i == 11)
		{
			var leadPagePopUp = new popUpWindow();//'leadPage' + i);
			leadPagePopUp.height = popUpHeight;
			leadPagePopUp.width = "500";
			leadPagePopUp.bodyContainerTypeValue = popUpPageUrl;
			leadPagePopUp.hasTitleBar = true;
			leadPagePopUp.titleBar.innerHTML = popUpTitle;
			leadPagePopUp.titleBar.fontSize = "14";
			leadPagePopUp.titleBar.foreColor = "#FFFFFF";
			leadPagePopUp.titleBar.backgroundColor = "#0A2986";
			leadPagePopUp.show();
		}
		else
		{
			var popCustomResponse = new popUpWindow();//"customResponse_" + i + "_" + igen_key);
			var popTitle = "";
			popCustomResponse.height = popUpHeight;
			switch(i)
			{
				case 0:
				    popTitle = multiLanguagesText.hotLeadTitleViewIt;
					break;
				case 1:
					popTitle = "Ask a Question";
					break;
				case 3:
				    popTitle = multiLanguagesText.hotLeadTitleBuyIt;
					break;
			}
			popCustomResponse.titleBar.innerHTML = popTitle;
			popCustomResponse.bodyContainerTypeValue = popUpPageUrl;
			popCustomResponse.show();
		}
		ClearTrackGoogleAdWordsAndOverture();
	}
	else
	{
		window.location.href = GetHomePageLink(true);
	}
}

//MLS LOGOS in property page, property result pages and site map pages.
//Use in INCLUDE/MLSCopyRight.ascx control.
//Get MLS Logos by Mls DB.
function GetMLSLogosImgPath_Pri(mlsDB)
{
	mlsDB = mlsDB.toString();
	var imgPath = "";
	if(gArrMlsLogos[mlsDB]!=null)
	{
		if(gArrMlsLogos[mlsDB].logoImagePath == null || gArrMlsLogos[mlsDB].logoImagePath == "")
		{   
			imgPath = "images/logo_" + mlsDB + ".gif";
		}
		else
		{
			imgPath = gArrMlsLogos[mlsDB].logoImagePath;
		}
	}
	return imgPath;
}
function GetMLSDB_Pri(mlsLogoName)
{
    var mlsDB = -1;
	var sL = mlsLogoName.indexOf("logo_")+5;	
	if( sL > 0 )
	{
	    var eL = mlsLogoName.indexOf(".gif");
	    mlsDB = mlsLogoName.substring(sL,eL);	
	}
	return mlsDB;
}

function GetMLSLogosByMlsDb( mlsDB )
{
	var imgSrc = GetMLSLogosImgPath_Pri(mlsDB);
	var img = "";
	if( imgSrc != "" )	
		img = "<img src=\""+GetRelativePath2()+imgSrc+"\">";
	return img;
}
function GetMLSLogos_Pri(mlsDB)
{
	var logo = "";		

	var logo_head = "<span class=\"footFont\">The real estate listing data marked with this icon ";

	if( mlsDB != null && eval(mlsDB) > 0 )
		{
			//added by Jane Oct,13 for bug 4308
		    if (mlsDB == "421") {
		        logo = "<div class=\"footFont\">" + GetMLSLogosByMlsDb(eval(mlsDB)) + "The data relating to real estate for sale on this web site comes in part from the Internet Data Exchange/ Broker Reciprocity Program of Georgia "
				    + "MLS. Real estate listings held by brokerage firms other than this one are marked with the Internet Data Exchange/Broker Reciprocity logo and detailed "
					+ "information about them includes the name of the listing brokers. The broker providing this data believes it to be correct, but advises interested parties "
					+ "to confirm them before relying on them in a purchase decision. IDX information is provided exclusively for consumers' personal, non-commercial use and may not "
					+ "be used for any purpose other than to identify prospective properties consumers may be interested in purchasing. Copyright 2008 Georgia MLS. All rights reserved.</div>";
		    }
		    else if (mlsDB == "411") {
		        logo = "<div class=\"footFont\">" + GetMLSLogosByMlsDb(eval(mlsDB)) + "Copyright 2008 Carolina Multiple Listing Services, Inc.</div>"
					+ "<div class=\"footFont\">The data relating to real estate on this Web site derive in part from the Carolina Multiple Listing Services, Inc. IDX program. Brokers make an effort to "
					+ "deliver accurate information, but buyers should independently verify any information on which they will rely in a transaction. All properties are "
					+ "subject to prior sale, change or withdrawal. Neither Movoto nor any listing broker shall be responsible for any typographical errors, misinformation, or "
					+ "misprints, and they shall be held totally harmless from any damages arising from reliance upon this data. This data is provided exclusively for "
					+ "consumers'personal, non-commercial use and may not be used for any purpose other than to identify prospective properties they may be interested in "
					+ "purchasing. &copy; 2009 Carolina Multiple Listing Services, Inc.</div>";
		    }
		    else if (mlsDB == "412") {
		        logo = "<div class=\"footFont\">" + GetMLSLogosByMlsDb(eval(mlsDB)) + "The data relating to real estate for sale on this web site comes in part from the Internet Data Exchange (IDX) Program of the Triad MLS, Inc. of High Point, NC. "
				    + "Real estate listings held by brokerage firms other than the firm which owns this website are marked with the Internet Data Exchange logo or the Internet Data Exchange (IDX) thumbnail logo (the TRIAD MLS logo) and detailed information about them includes the name of the listing brokers. "
					+ "Information Deemed Reliable But Not Guaranteed. The broker providing this data believes it to be correct, but advises interested parties to confirm the data before relying on it in a purchase decision. The information being provided is for "
					+ "consumers' personal, non-commercial use and may not be used for any purpose other than to identify perspective properties consumers may be interested in purchasing. "
					+ "Any use of search facilities of data on the site, other than by potential buyers and sellers is prohibited. &copy; 2008 Triad MLS, Inc. of North Carolina. All rights reserved.</div>";
		    }
		    else if (mlsDB == "461") {
		        logo = logo_head + "<img src=\"" + GetRelativePath2() + "" + "images/logo_461_large.gif\">" + GetMLSLogosNote_Pri(eval(mlsDB)) + "</span>";
		    }
		    else
		        logo = logo_head + GetMLSLogosByMlsDb(eval(mlsDB)) + GetMLSLogosNote_Pri(eval(mlsDB)) + "</span>";
		}	
		
		
	if(mlsDB == 102)
		logo = logo.replace("<span","<div").replace("</span>","</div>");

	// Add more text for MA.
	if(mlsDB == "300")
	{
		logo += "<div class=\"footFont\">The property listing data and information set forth herein were provided to MLS Property Information Network, Inc. from third party sources, "
			+ "including sellers, lessors, and public records, and were compiled by MLS Property Information Network, Inc. "
			+ "The property listing data and information are for the personal, non commercial use of consumers having a good faith in interest "
			+ "in purchasing or leasing listed properties of the type displayed to them and may not be used for any purpose other than to identify "
			+ "prospective properties which such consumers may have a good faith interest in purchasing or leasing.  MLS Property Information Network, Inc. "
			+ "and its subscribers disclaim any and all representations and warranties as to the accuracy of the property listing data and information set forth herein.</div>";
	}
	
	//Add by Jane Feb, 11 2009 for bug 4674
	//added more text for FL
	if(mlsDB == "432")
	{
		var pageType = document.getElementById(gCtlIdPrefix.PageHeader + "iptPageType");
		var listingAgentName = document.getElementById(gCtlIdPrefix.PageHeader + "listingAgentName");
		var listingAgent ="";
		var listingOfficeName = document.getElementById(gCtlIdPrefix.PageHeader + "listingOfficeName");
		var listingOffice ="";
		if(listingAgentName != null && listingAgentName.value != null && listingAgentName.value != "" )
			listingAgent = listingAgentName.value;
		if(listingOfficeName != null && listingOfficeName.value != null && listingOfficeName.value != "" )
			listingOffice =listingOfficeName.value;
		if(pageType != null && pageType.value != null && (pageType.value == "DPP" || pageType.value == "DPP2"))
		{
			logo += "<div class=\"footFont\">The Realtor&reg; Associations (Miami-Dade County, Greater Ft. Lauderdale, Greater Miami and the Beaches, Northwestern Dade, South Broward Board) are not "
				+ "responsible for the accuracy of the information listed above. The data relating to real estate for sale or lease on this web site comes in part from the "
				+ "Internet Data Exchange Program (IDX) and the South East Florida Regional MLS and is provided here for consumer's personal, non-commercial use. It may not be "
				+ "used for any purpose other than to identify prospective properties consumers may be interested in purchasing or leasing. Real Estate listings held in "
				+ "brokerage firms other than the office owning this web site are marked with the IDX Logo on the short inquiry and detailed information about the listing "
				+ "includes the name of the listing Broker's Company. Data provided is deemed reliable but not guaranteed. This information is protected by copyright and all "
				+ "rights are reserved. This property is shown courtesy of "
				+ listingAgent + " Company Name "+ listingOffice +".</div>";
		}
		else
		{
			logo += "<div class=\"footFont\">The data relating to real estate for sale/lease on this web site comes from a cooperative data exchange program of the Multiple Listing Service (MLS) in "
				+ "which these Brokers participate (Realtor&reg; Association of Miami-Dade County, Realtor&reg; Association of Greater Ft. Lauderdale, Realtor&reg; Association of "
				+ "Greater Miami and the Beaches, Northwestern Dade Association of Realtors&reg;, South Broward Board of Realtors&reg;). The properties displayed may not be all of "
				+ "the properties in the MLS database, or all of the properties listed with Brokers participating in the cooperative data exchange program. Properties "
				+ "listed by Brokers other than this Broker are marked with the IDX Symbol, indicating an agreement to exchange property information. Detailed information "
				+ "about such properties includes the name of the listing Broker's Company. Information provided is thought to be reliable but is not guaranteed to be "
				+ "accurate. You are advised to verify facts that are important to you. No warranties, expressed or implied, are provided for the data herein, or for "
				+ "their use or interpretation by the user. This information is protected from unlawful duplication by copyright. Federal law prohibits discrimination on the "
				+ "basis of race, color, religion, sex, handicap, familial status or national origin in the sale, rental or financing of housing.</div>";
		}	
	}
	
	//Added by Jane Apr 14, 2009 for bug 4830, added more text for OR/WA
	if(mlsDB == "491")
	{
	    var listingOfficeName = document.getElementById(gCtlIdPrefix.PageHeader + "listingOfficeName");
		var listingOffice ="";
		if(listingOfficeName != null && listingOfficeName.value != null && listingOfficeName.value != "" )
			listingOffice =listingOfficeName.value;
	
	    logo += "<div class=\"footFont\">The content relating to real estate for sale on this web site comes in part from the IDX program of the RMLS<sup>TM</sup> of Portland, Oregon. Real estate listings "
            +"held by brokerage firms other than "+listingOffice+" are marked with the RMLS<sup>TM</sup> logo, and detailed information about these properties includes the names of the "
            +"listing brokers. Listing content is copyright &copy; 2009 RMLS<sup>TM</sup>, Portland, Oregon.</div>";
	}

	//Added more text for Trend(Delaware and Pennsylvania)
	if (mlsDB == "441")
	{
	    logo += "<div class=\"footFont\">The data relating to real estate for sale on this website is provided in part by TReND Broker Reciprocity Program, a voluntary cooperative exchange of "
            + "property listing data between licensed real estate brokerage firms in which our firm participates, and is provided by TReND through a licensing agreement. The information provided "
            + "by this website is for the personal, non-commercial use of consumers and may not be used for any purpose other than to identify prospective properties consumers may be interested "
            + "in purchasing. Information deemed reliable but is not guaranteed. Some properties which appear for sale on this website may no longer be available because they are under contract, "
            + "have sold or are no longer being offered for sale. &copy; 2009 TReND. All Rights Reserved.</div>";
	}

	if (mlsDB == "482") {
	    logo += "<div class=\"footFont\">The data relating to real estate for sale on this web site comes in part from the Broker Reciprocity Program of the Multiple Listing Service of Long Island, Inc."
            + " Real Estate listings held by brokerage firms other than Movoto, Inc. are marked with the Broker Reciprocity logo and detailed information about them includes the name of the listing brokers."
            + " The source of the displayed data is either the property owner or public record provided by non-governmental third parties. It is believed to be reliable but not guaranteed."
            + " Information Copyright 2008, Multiple Listing Service of Long Island, Inc.</div>";
	}

	if (mlsDB == "651") {
	    logo += "<div class=\"footFont\">Information Deemed Reliable But Not Guaranteed.<br />Copyright 2010 Regional Multiple Listing Service of Minnesota, Inc.</div>";
	}
	return logo;
}

function GetMLSDBArrayByMetroArea(metroArea)
{
    var arrMlsDbListByMetroArea = new Array();    
    if( eval(metroArea)>0 )
    { 
		var maLength = 1; //match the first number.
		if(eval(metroArea)>=10 && eval(metroArea)<100)
		{
			maLength  = 2;			
			if(eval(metroArea)==20)
				arrMlsDbListByMetroArea.push("210");
			else if(eval(metroArea) == 50)
		        arrMlsDbListByMetroArea.push("491");
		    else if(eval(metroArea) == 60)
		        arrMlsDbListByMetroArea.push("441");
		    else if (eval(metroArea) == 31)
		        arrMlsDbListByMetroArea.push("441");
		    else if (eval(metroArea) == 45)
		        arrMlsDbListByMetroArea.push("441");
		    else if (eval(metroArea) == 66)
		        arrMlsDbListByMetroArea.push("651");
		}		
		for(var i=0;i<gArrMlsDbList.length;i++)
		{
			if(gArrMlsDbList[i].substring(0,maLength) == metroArea)
				arrMlsDbListByMetroArea.push(gArrMlsDbList[i]);
		}
    }
    if(arrMlsDbListByMetroArea.length == 0)
    {         	
        var mlsDBList = "";	
        var ImgEleS = document.getElementsByTagName( "img" );
		for(var i=0; i<ImgEleS.length;i++)
		{
		    if ( ImgEleS[i].src.indexOf("images/logo_" ) > -1)
		    {
		        var mlsDB = GetMLSDB_Pri(ImgEleS[i].src);
		        if(mlsDBList.indexOf(mlsDB) == -1)
		        {	
		            mlsDBList += mlsDB;	    
			        arrMlsDbListByMetroArea.push(mlsDB);
			    }	
			}		 
		}
				  
		return arrMlsDbListByMetroArea;//all MLS
	}	
    else
		return arrMlsDbListByMetroArea;
}

//ShowMLSLogos: Need modify code for new mls_db.  Marked by Joe, 5 23th, 2007
function ShowMLSLogos()
{
	var mlsLogos = $get(gCtlIdPrefix.MlsCopyRight + "mlsLogos");
	if(mlsLogos!=null && mlsLogos.innerHTML == "")
	{	
		var mlsDB    = -1;
		var iptMLSDB = $get(gCtlIdPrefix.MlsCopyRight + "iptMLSDB");		
		if( iptMLSDB != null && iptMLSDB.value != "")
			mlsDB = eval(iptMLSDB.value);

		if(mlsDB == 701)
		{
			return;
		}
		
		var metroAreaCode    = -1;	
		var iptMetroAreaCode = $get(gCtlIdPrefix.MlsCopyRight + "iptMetroAreaCode");
		if( iptMetroAreaCode != null && iptMetroAreaCode.value != "" )
		    metroAreaCode = eval(iptMetroAreaCode.value)
		    
		var str = GetMLSLogos_Pri(mlsDB);		
		if( str == "" )
		{
		    var mlsdbArray;		   
		    if(metroAreaCode<0)
		    {		        
		       	var ImgEleS = document.getElementsByTagName( "img" );								
				for(var i=0; i<ImgEleS.length;i++)
				{
				    for (var m = 0; m < gArrMetroAreaList.length; m++)
					{
					    mlsdbArray = GetMLSDBArrayByMetroArea(gArrMetroAreaList[m]);
	
						for(var j=0; j<mlsdbArray.length;j++)
						{ 
							if ( ImgEleS[i].src.indexOf( GetMLSLogosImgPath_Pri(mlsdbArray[j]) ) > -1)
							{
								metroAreaCode = gArrMetroAreaList[m];
								break;
							}					
						}
					}
					
					if(metroAreaCode>0)
						break;
				}
			}			
			// Show LOGOs			
			if(metroAreaCode>0)
			{
			    var mlsdbArray = GetMLSDBArrayByMetroArea(metroAreaCode);		  		   
				for(var k=0; k<mlsdbArray.length;k++)
				{	
				    if(mlsdbArray[k] != '701' && GetMLSLogosNote_Pri(mlsdbArray[k])!="")			
						str += GetMLSLogos_Pri( mlsdbArray[k])+ "<br>";
				}			
			}
		}
		
		mlsLogos.innerHTML = str.replace(/<\/div><br>/g,"</div>");		
	}
	
	if(window.location.href.indexOf("/ma/") > 0 && $get(gCtlIdPrefix.MlsCopyRight + "mlsLogos") == null)
	{
	    document.getElementById("forMAInfo").innerHTML = GetMLSLogos_Pri(300);
	}
}

function LeftOnLoadFunc()
{
	//add by MLian for bug #1555
	var divbg = document.getElementById("divbg");
	divbg.style.height = document.body.scrollHeight;

	var pageUrl = window.location.href.toLowerCase();
	if(pageUrl.indexOf(".html") != -1)
	{
		// This is a static page, try to auto login.
		iGen.WebServices.Common.LoadUserPanelsForStaticPages(onLoadUserPanelsForStaticPagesSucceeded)
	}	
}
function onLoadUserPanelsForStaticPagesSucceeded(result)
{
    var userPanel = document.getElementById(gCtlIdPrefix.PageHeader + "userPanel");
	if(result.isCurrentUserLoggedIn == true)	
	{
		document.getElementById(gCtlIdPrefix.LeftNav + "divLogin").className = "sidenav_none";
		document.getElementById(gCtlIdPrefix.LeftNav + "divLeftNav").className = "sidenav_block";
		document.getElementById(gCtlIdPrefix.LeftNav + "divMlsSearch").className = "sidenav_block";
		var divMySavedSearch = document.getElementById(gCtlIdPrefix.LeftNav + "divMySavedSearch");
        divMySavedSearch.innerHTML = result.htmlMySavedSearch;
	}
	else
	{
		document.getElementById(gCtlIdPrefix.LeftNav + "divLogin").className = "sidenav_block";
		document.getElementById(gCtlIdPrefix.LeftNav + "divLeftNav").className = "sidenav_none";
		document.getElementById(gCtlIdPrefix.LeftNav + "divMlsSearch").className = "sidenav_none";
	}
	userPanel.innerHTML = result.htmlTopHeader;
//	SetCurrentMetroAreaName();
		
	// Update saved userid in pageHeader user control.
	// Added by Andy Wan, Feb 21, 2006.
	GetCurrentUserID();	
}

//add by MLian
function showIndL(VSPid,type)
{
	var ID = document.getElementById(VSPid);
	ID.className = "notesStyle";			
	ID.style.margin = "20px 0px 0 0";			
	if(type == "edit")
	{
	    ID.style.width = "120px";
		ID.innerHTML = "<p align=left>Edit Saved Search</p>";
	}
	else
	{
	    ID.style.width = "135px";
		ID.innerHTML = "<p align=left>Delete Saved Search</p>";
	}
}
function HiddenIndL(VSPid)
{
	var ID=document.getElementById(VSPid);
	ID.className="notesStyleHidden";
}
/*********************** JavaScript code for propertySearchForm.ascx [BEGIN] ***********************/
function clickSearchBtn(e,txtMLSNumId,errorMessageId)
{
	if(txtMLSNumId == null || txtMLSNumId == "undefined")
		return;
	var key;
					
	if (window.event) 
	{ 
		//for IE
		key = event.keyCode;
		if(key==13)
		{
			var btnFcs = document.getElementById(gCtlIdPrefix.PageHeader + "btnFcs");
			btnFcs.disabled = true;
			MlsNOSearch(txtMLSNumId,errorMessageId);
		}
	} 
	else if (e) 
	{ 
		//for Firefox
 		key = e.which;
 		if(key==13)
			MlsNOSearch(txtMLSNumId,errorMessageId);	
	}
	
}
//3.only for the propertySearchForm.ascx
function MlsNOSearch(textid,errorMessageId)
{
	if(textid == null || textid == "undefined" || errorMessageId == null || errorMessageId == "undefined")
		return;
	//To distinguish where MLS search comes from, property search or left navigation.
	//gTxtErrorMLSMsg is a global variable from property search page. Added by Ballian on 11/14/2008 new property search.
	if(typeof(gTxtErrorMLSMsg) != "undefined" && gTxtErrorMLSMsg != null)
		gTxtErrorMLSMsg = errorMessageId;

	if(document.getElementById(textid)==null || document.getElementById(textid)=="undefined") 
		return;	
	var strMlsNum = Trim(document.getElementById(textid).value);
	var strMLSMsg = "";
	if(strMlsNum !="")
	{
		iGen.WebServices.Common.ValidNumber(strMlsNum, "url", "#HTML_URL#", eval(GetCurrentMetroAreaCode()), onValidNumberSuccessed);
		TrackGoogleAnalytics("Property Search - MLS# Search");
		return;
	}
	else
	{ 
		strMLSMsg = "Enter MLS Number";
	}	
	if(	strMLSMsg != "" && document.getElementById(errorMessageId)!=null)	
		document.getElementById(errorMessageId).innerHTML = strMLSMsg;	
		return;
}

function onValidNumberSuccessed(mlsnum)
{	    
	var rpath = GetRelativePath2();	   
	if(mlsnum != null && mlsnum != "")
	{
		if(mlsnum.substr(0, 4) == "URL:")
		{
			window.location.href = rpath + mlsnum.substr(4, mlsnum.length);
		}
		else
		{
			// Clear the original error message.
			document.getElementById('ErrorMessage').innerHTML = "";
			// Show popup window.
			var popDivNoFrame = document.getElementById('popDivNoFrame');
			popDivNoFrame.style.display = "block";
			popDivNoFrame.innerHTML = mlsnum;
			moveToaCenter('popDivNoFrame');
		}
	}
	else
	{ 
		if(typeof(gTxtErrorMLSMsg) != "undefined" && gTxtErrorMLSMsg != null)
			document.getElementById(gTxtErrorMLSMsg).innerHTML = "MLS number unavailable";			
		else if(document.getElementById('ErrorMessage')!=null && document.getElementById('ErrorMessage')!="undefined")
			document.getElementById('ErrorMessage').innerHTML = "MLS number unavailable";	
	}
}
// Hide the div of mls_num search results.
// Created by Andy Wan, Apr 2, 2006.
function HideMLSSearchDiv()
{
	var popDivNoFrame = document.getElementById('popDivNoFrame');
	popDivNoFrame.style.display = "none";
	popDivNoFrame.innerHTML = ""; // Clear the div content.
}
//ChangeCss(id,cssname):set css for html control
function ChangeCss(id,cssname)
{
	if(document.getElementById(id)!=null)
	document.getElementById(id).className =cssname;
}

/*********************** JavaScript code for propertySearchForm.ascx [END] ***********************/
// Check user account info, if user password is null then pop up register page.
function checkUserAccountInfo()
{
	var tbActiveFlag = document.getElementById(gCtlIdPrefix.LeftNav + "tbActiveFlag");
	if( tbActiveFlag != null && tbActiveFlag.value.indexOf("active_") != -1)
	{
		var activeID = tbActiveFlag.value.substring(tbActiveFlag.value.indexOf('_')+1);
		showRegisterPopUp(null,activeID);
	}	
}

/*********************** JavaScript code for homepage.aspx ***********************/
//Add bu MLian for bug 3068
function DoPopUpForHomePage()
{
	if(window.location.href.getQueryString("dopopup") == "true")
		doHelpMeSell();
}

function homepageOnLoadEvent()
{	

	var homepageSellersFormRightBorder = document.getElementById("homepageSellersFormRightBorder");
	if(homepageSellersFormRightBorder != null && clientBrowser.isIE6 == true)
	{
		homepageSellersFormRightBorder.className = "homepageSellersFormBorderRightForIE6";
	}
	// When the page is loaded, default focus to search input bar.
	var buyersContainer = document.getElementById("buyersContainer");
	if(buyersContainer.style.display != "none")
	{
	    var tbInputLetters = document.getElementById(gCtlIdPrefix.MainContent + "tbInputLetters");
		tbInputLetters.focus();
	}
	// SetCurrentMetroAreaName();  
	// If user resize the browser window, we should refresh the dropdown div's position.
	window.onresize = refreshDropdownDivPosition;
	//take a test if the page name tracked into gg analytics
	TrackGoogleAnalytics("Home Page");
}


//Get Search Page Name for google analytics tracking by search type.
//Juana, Dec.18,2006
function GetSearchPageName(searchType)
{
	var pageName = "";
	switch(searchType)
	{
		case "m0":case "m1":default:
			pageName = "Map Search";
			break;
		case "pb0":
			pageName = "Property Search - Basic";
			break;
		case "pc0":
			pageName = "Property Search - Custom";
			break;
		case "pa0":
			pageName = "Property Search - Address";
			break;
		case "ps0":
			pageName = "Property Search - School District";
			break;
		case "pb1":case "pc1":case "ps1": case "pa1": case "psc1"://Basic/Custom/School District Search Result
			pageName = "Property Search Result";
			break;
		case "o0":
			pageName = "Open Houses";
			break;
		case "o1":
			pageName = "Open Houses Result";
			break;
		case "hp0":
			pageName = "Home Page";
			break;			
	}
	return pageName;
}
		
//Google Analytics Tracking
function TrackGoogleAnalytics(pageName, isTrackSpecial)
{
	var uacctValue = "";
	var accountControlName = gCtlIdPrefix.PageHeader + "ggAnalyticsAccount";
	if(isTrackSpecial!=null && isTrackSpecial == true)
		accountControlName = gCtlIdPrefix.PageHeader + "ggAnalyticsAccountForAdBanner";
	
	var analyticsAccount = document.getElementById(accountControlName);	
	if(analyticsAccount == null)
		analyticsAccount = window.top.document.getElementById(accountControlName);		
	if(analyticsAccount == null)
		analyticsAccount = document.getElementById("ggAnalyticsAccount");
		
	if(analyticsAccount != null && analyticsAccount.value != null && analyticsAccount.value != "")
		uacctValue = analyticsAccount.value;
	_uacct = uacctValue;
	_udn = window.location.hostname; 
	urchinTracker(pageName);
}
//End of Google Analytics Tracking

//Added by Jane sept 18,2008 for bug 4127
//New Google Analytics Tracking
//modified by Jane Nov,11 2008
function TrackGoogleAnalyticsNew() {
    var uacctValue = "";
    var accountControlName = gCtlIdPrefix.PageHeader + "ggAnalyticsAccountNew";
    var analyticsAccountNew = document.getElementById(accountControlName);
    if (analyticsAccountNew == null)
        analyticsAccountNew = window.top.document.getElementById(accountControlName);

    if (analyticsAccountNew != null && analyticsAccountNew.value != null && analyticsAccountNew.value != "")
        uacctValue = analyticsAccountNew.value;
    _uacct = uacctValue;
    _udn = window.location.hostname; 

    //get analyticsAccountNew.value from ads control
    var GetCityZipForAd_Value = "";
    var GetCityZipForAd = document.getElementById(gCtlIdPrefix.PageHeader + "GetCityZipForAd");
    if (GetCityZipForAd != null && GetCityZipForAd.value != "") 
    {
        GetCityZipForAd_Value = GetCityZipForAd.value.replace(/ /g, "_");
        //capture the first cityname info and send it to new google analytics in map search and property seach pages
        var GetCityZipForAd_ValueArray = GetCityZipForAd_Value.split(',');
        GetCityZipForAd_Value = GetCityZipForAd_ValueArray[0];
    }

    //if GetCityZipForAd_Value is null ,GoogleAnalytics track name may be url
    if (GetCityZipForAd_Value != null && GetCityZipForAd_Value != "") {
        // 5443, Support price range tracking in Analytics.
        var prefix = GetCityZipForAd_Value.substr(0, 3);
        if (prefix == "MSR") {
            var priceRange = GetCityZipListWithPriceRange(maxPrice, minPrice);
            prefix = GetCityZipForAd_Value.substr(0, 4);
            if (prefix == "MSR-")
                GetCityZipForAd_Value = GetCityZipForAd_Value.substr(0, 4) + priceRange + GetCityZipForAd_Value.substr(3);
            prefix = GetCityZipForAd_Value.substr(0, 6);
            if (prefix == "MSR_NH")
                GetCityZipForAd_Value = GetCityZipForAd_Value.substr(0, 7) + priceRange + GetCityZipForAd_Value.substr(6);
        }

        urchinTracker(GetCityZipForAd_Value);
    }
}
//End of New Google Analytics Tracking

//Google AdWords and Yahoo/Overture Tracking
//We need add following script referer after call this function to track Google AdWords.
//<script language="JavaScript" src="http://www.googleadservices.com/pagead/conversion.js"></script>
//<noscript>(show in search_detail.aspx page)..can be ignored for hot lead pages.
function TrackGoogleAdWordsAndOverture(adWordsType,isOnlyGoogleAdWords)
{
	// Google Code for Lead Conversion Page
	//Method 1. The method 1 maybe is wrong.
	//var google_conversion_id = 1068047522;
	//var google_conversion_language = "en_US";
	//var google_conversion_format   = "1";
	//var google_conversion_color    = "FFFF99";
	//var google_conversion_value    = 1;
	//var google_conversion_label    = "Lead";	
	//google_handle_conversion();
	
    var google_conversion_id          = 'traceGoogleADWords';
	var google_conversion_imageObject = parent.document.getElementById(google_conversion_id);
	var google_conversion_imageUrl    = "http://www.googleadservices.com/pagead/conversion/1068047522/?value=1&label=Lead&script=0";
	var google_conversion_imageUrl2   = "http://www.googleadservices.com/pagead/conversion/1068047522/?value=1&script=0&label=Lead";
	
	if(adWordsType != null && adWordsType == 2)
	{
		//var google_conversion_type = 'landing';
		google_conversion_imageUrl  = "http://www.googleadservices.com/pagead/conversion/1068047522/extclk?script=0";
		google_conversion_imageUrl2 = "";
	}	
		
	if(google_conversion_imageObject.src != google_conversion_imageUrl)
		google_conversion_imageObject.src = google_conversion_imageUrl; 
	else
		google_conversion_imageObject.src = google_conversion_imageUrl2; 

	//Overture Services Inc. 07/15/2003
	if(isOnlyGoogleAdWords == null)
	{
		var cc_tagVersion = "1.0";
		var cc_accountID = "1774926527 ";
		var cc_marketID =  "0";
		var cc_protocol="http";
		var cc_subdomain = "convctr";
		if(location.protocol == "https:")
		{
			cc_protocol="https";
			cc_subdomain="convctrs";
		}
		var cc_queryStr = "?" + "ver=" + cc_tagVersion + "&aID=" + cc_accountID + "&mkt=" + cc_marketID +"&ref=" + escape(document.referrer); 
		var cc_imageUrl = cc_protocol + "://" + cc_subdomain + ".overture.com/images/cc/cc.gif" + cc_queryStr; 	
		var cc_imageObject = parent.document.getElementById('traceYahooOverture');	//cc_imageObject = new Image(1, 1);
		cc_imageObject.src = cc_imageUrl; 
	}
	

}
function ClearTrackGoogleAdWordsAndOverture()
{
	var google_conversion_imageObject = parent.document.getElementById('traceGoogleADWords');
	if(google_conversion_imageObject != null)
		google_conversion_imageObject.src = "";
	
	var cc_imageObject = parent.document.getElementById('traceYahooOverture');
	if(cc_imageObject != null)
		cc_imageObject.src = "";
}

// Get the query string of the request url.
String.prototype.getQueryString = function(name)
{
  var reg = new RegExp("(^|&|\\?)"+ name +"=([^&]*)(&|$)");
  var r = this.match(reg);
  if (r!=null) return unescape(r[2]); return null;
}

//this function is for dpp
function getCurrentPropertyObject()
{
	var pWindow   = window.parent;
    this.mlsnum   = "";
    this.igenkey  = "";
    this.price    = "";
    this.address  = "";
    this.cityCode = "";
    this.isMatch  = false;

    var pcMLSNUM  = pWindow.document.getElementById(gCtlIdPrefix.MainContent + "tbCurMlsNum");
    var pcIGenKey = pWindow.document.getElementById(gCtlIdPrefix.MainContent + "tbIGEN_KEY");
	var pcPrice   = pWindow.document.getElementById(gCtlIdPrefix.MainContent + 'TDListPrice' );
	var pcAddr    = pWindow.document.getElementById(gCtlIdPrefix.MainContent + 'hidPropertyAddress');
	var pcCity    = pWindow.document.getElementById(gCtlIdPrefix.MainContent + 'iptCity' );
	
	if(pcIGenKey == null && pcMLSNUM == null)
	{
	    pcMLSNUM  = document.getElementById("tbCurMlsNum");
	    pcIGenKey = document.getElementById("tbIGEN_KEY");
	    pcPrice   = document.getElementById('hdPrice');
	    pcAddr    = document.getElementById('hdAddress');	
		pcCity    = document.getElementById('iptCity' );
	}
	
	if(pcMLSNUM != null && pcIGenKey != null && pcPrice != null && pcAddr != null)
	{
		this.mlsnum   = pcMLSNUM.value;
		this.igenkey  = pcIGenKey.value;
		this.price    = pcPrice.innerHTML.replace("From ","");
		this.address  = pcAddr.value;
		this.isMatch  = true;
		
		if(pcCity != null)
			this.cityCode = pcCity.value;
		if( price == "")	
			this.price    = pcPrice.value;		
	}
	else
	  return null;
		
	return this;
}

//this function is for offmarket
function getCurrentPropertyObjectForOffMarket() {
    var pWindow = window.parent;
    this.mlsnum = "";
    this.igenkey = "";
    this.price = "";
    this.address = "";
    this.cityCode = "";
    this.isMatch = false;

    var pcMLSNUM = pWindow.document.getElementById(gCtlIdPrefix.MainContent + "assistantMlsNum");
    var pcIGenKey = pWindow.document.getElementById(gCtlIdPrefix.MainContent + "tbIGEN_KEY");
    var pcPrice = pWindow.document.getElementById(gCtlIdPrefix.MainContent + 'assistantPrice');
    var pcAddr = pWindow.document.getElementById(gCtlIdPrefix.MainContent + 'assistantFullAddress');
    var pcCity = pWindow.document.getElementById(gCtlIdPrefix.MainContent + 'assistantCityCode');
    
    if (pcIGenKey == null && pcMLSNUM == null) {
        pcMLSNUM = document.getElementById(gCtlIdPrefix.MainContent + "assistantMlsNum");
        pcIGenKey = document.getElementById(gCtlIdPrefix.MainContent + "tbIGEN_KEY");
        pcPrice = document.getElementById(gCtlIdPrefix.MainContent + 'assistantPrice');
        pcAddr = document.getElementById(gCtlIdPrefix.MainContent + 'assistantFullAddress');
        pcCity = document.getElementById(gCtlIdPrefix.MainContent + 'assistantCityCode');
    }

    if (pcMLSNUM != null && pcIGenKey != null && pcPrice != null && pcAddr != null) {
        this.mlsnum = pcMLSNUM.value;
        this.igenkey = pcIGenKey.value;
        this.price = pcPrice.innerHTML.replace("From ", "");
        this.address = pcAddr.value;
        this.isMatch = true;

        if (pcCity != null)
            this.cityCode = pcCity.value;
        if (price == "")
            this.price = pcPrice.value;
    }
    else
        return null;

    return this;
}

function HotLeadConfirmationPopUp()
{
	alert("Thank you!  We will contact you shortly.");
}
// Show pop up window for contact us.
function showContactUsPopUp(tagName)
{
	var popContactUs = new popUpWindow();//"contact_" + tagName);
	popContactUs.height = "372";
	if(tagName == "meetagent")
		popContactUs.titleBar.innerHTML = "Meet a Movoto real estate professional";
	else
		popContactUs.titleBar.innerHTML = "Contact Us";
	popContactUs.bodyContainerTypeValue = GetRelativePath2() + "contactus.aspx?tag=" + tagName;
	popContactUs.show();
} 		

function FormatPhoneNumber(phone)
{	
	var phoneNumber = phone.replace(/-/g,"").replace(/ /g,"").replace("(","").replace(")","").replace(/\./g,"");
	var phoneLength = phoneNumber.length;

	if(phoneLength == 10)
	{
		return phoneNumber.substring(0,3) + "-" + phoneNumber.substring(3,6) + "-" + phoneNumber.substring(6,10);
	}

	if(phoneLength > 10 && phoneNumber.substring(0,1) == '1')
	{
		return phoneNumber.substring(0,1) + "-" + phoneNumber.substring(1,4) + "-" + phoneNumber.substring(4,7) + "-" + phoneNumber.substring(7,phoneLength);
	}

	return phone;
}

function ValidatePhoneNO(phoneNO)
{
	var regu=/^(1-)?[\(| ]?\d{3}[\)| |-|.]?[ |-]?\d{3}[-| |)|.]?\d{4}[ ]?(ext\.)?[-|x|X| |#]?\d{0,6}$/;
	var re = new RegExp(regu);
	
	var wholeNum = "0000000000,1111111111,2222222222,3333333333,4444444444,5555555555,6666666666,7777777777,8888888888,9999999999,1231231234,6503211133,8887668686";
	if(phoneNO.search(re) != -1)
	{
		if(wholeNum.indexOf(phoneNO) != -1 || phoneNO.substring(0,3) == "911" || phoneNO.substring(0,1) == "0" || phoneNO.indexOf("1111111",3,7) != -1 )
		{
			return false;
		}
		else
			return true;
	}
	else
		return false;
}

function showMetroListTermsOfUse()
{
	var windowTitle = "Terms of Use";
	var metrolistTermsContent = "<p>1. The following are terms of a legal agreement between you, the person viewing and/or using this Internet site (\"User\") and the operator of this Internet site (\"Provider.\") By accessing, browsing and/or using this Internet site (\"Site\"), User acknowledges that User has read, understood, and agrees to be bound by these terms and to comply with all applicable laws and regulations, including but not limited to U.S. export and re-export control laws and regulations. If User does not agree to these terms, User is not authorized to use this Site. The material provided on this Site is protected by law, including, but not limited to, United States Copyright law and international treaties."
	+"<p>2. User must be a prospective purchaser or seller of real estate with a bona fide interest in the purchase or sale of such real estate."
	+"<p>3. All real estate data provided on this Site is strictly for the personal, private, non-commercial use of User and is not made available for redistribution, retransmission, reformatting, modification or copying. User may not sell or use any of the real estate data on this Site for any purpose other than attempting to evaluate houses or properties for sale or purchase by User. User acknowledges that the real estate data on this Site is provided by MetroList Services, Inc., a California corporation (\"MetroList\"), and User acknowledges the validity of MetroList's copyright as to such data. User expressly acknowledges and agrees that MetroList is a third-party beneficiary of these Terms of Use, and that MetroList will be entitled to enforce these Terms of Use against User."
	+"<p>4. To the fullest extent permitted by law, the data on this Site is provided \"as is,\" without warranty or representation of any kind, either express or implied, as to the nature, quality, characteristics or value of any property or information to which the data pertains. NEITHER PROVIDER NOR METROLIST MAKES ANY WARRANTIES, EXPRESS OR IMPLIED, REGARDING THE DATA DISPLAYED ON THIS SITE, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, OR AS TO THE TIMELINESS, ACCURACY AND/OR COMPLETENESS OF THE DATA."
	+"<p>5. NEITHER PROVIDER NOR METROLIST SHALL BE LIABLE FOR ANY INCIDENTAL, SPECIAL, CONSEQUENTIAL, INDIRECT, SPECIAL, PUNITIVE OR EXEMPLARY DAMAGES WHATSOEVER (INCLUDING WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS INFORMATION, LOSS OF DATA, LOST PROFITS, LOSS OF CUSTOMERS OR OTHER PECUNIARY LOSS), ARISING OUT OF THE USE OR INABILITY TO USE THE DATA DISPLAYED ON THIS SITE, WHETHER THE CLAIM OR CAUSE OF ACTION ARISES IN TORT, CONTRACT, NEGLIGENCE, STRICT LIABILITY OR UNDER ANY OTHER LEGAL THEORY."
	+"<p>6. User agrees that the prevailing party or parties in any action brought to enforce or for breach of these Terms of Use shall be entitled to recover, in addition to any other relief, that party's or those parties' reasonable attorney's fees and court costs incurred in such action from the non-prevailing party or parties.<br>&nbsp;</p>";
	var popMetroList = new popUpWindow();
	popMetroList.width = "640";
	popMetroList.height = "548";
	popMetroList.borderColor = "#000000";
	popMetroList.titleBar.foreColor = "#000000";
	popMetroList.titleBar.fontSize = "14";
	popMetroList.titleBar.backgroundColor = "#F4EFC4";
	popMetroList.titleBar.innerHTML = windowTitle;
	popMetroList.bodyContainerType = "content";
	popMetroList.bodyContainerTypeValue = metrolistTermsContent;
	popMetroList.show();
}

/* ---------------------------------------------------- firstreleasehomes.com banner [BEGIN] ---------------------------------------------------- */
var cityCodeList = null;
var date = new Date();
//for pv parameter in ads code.
var currentDateTime = date.getFullYear().toString()+date.getMonth().toString()+date.getDate().toString()
+date.getHours().toString()+date.getMinutes().toString()+date.getSeconds().toString()
+date.getMilliseconds().toString();
/* ---------------------------------------------------- firstreleasehomes.com banner [END] ---------------------------------------------------- */

//added by Jane Apr 22, 2009 for bug 4786
//load ads in agent page when the user are agents or co-broker agents 
function LoadLeaderboardAdsForAgent()
{
    var isNewAgentMonitorPage=window.location.toString().indexOf("NewAgentMonitor")>-1;
    if(!isNewAgentMonitorPage)
    {
        iGen.WebServices.Common.GetCurrentUserRole(onGetCurrentUserRoleSucceeded);
    }
}
function onGetCurrentUserRoleSucceeded(result)
{
    var userRole = result;
    var ifmLeaderboardAds = document.getElementById("leaderboardAds");
    if(ifmLeaderboardAds != null)
    {
	    if(userRole != null && (userRole=="1" || userRole=="4"))
	    {	    
	        ifmLeaderboardAds.style.width = "750px";
	        ifmLeaderboardAds.style.height = "90px";
		    ifmLeaderboardAds.src = GetRelativePath2() + "LeaderboardAd.aspx?adSpotName=AgentPageLeaderboard";
        }
    }
}

function ShowAgentPhoto(action)
{
	popWinZIndex = popWinZIndex + 1;
	var divAgentPhoto = document.getElementById("divAgentPhoto");
	divAgentPhoto.style.zIndex = popWinZIndex;	
	if(action)
		divAgentPhoto.style.display = '';
	else
		divAgentPhoto.style.display = 'none';
}


/*******************************************************************StringBuilder Start************************************/

function StringBuilder()
{
    this.stringSet=new Array();
    
    if(typeof StringBuilder._initialized =="undefined")
    {
        StringBuilder.prototype.Append=function(aString)
                                                {
                                                    this.stringSet.push(aString);
                                                    return this;
                                                };
        StringBuilder.prototype.ToString=function(aString)
                                                {
                                                    return this.stringSet.join("");
                                                };
        StringBuilder._initialized=true;
    }
}

/*******************************************************************StringBuilder end************************************/

// Parse XML content.
function parseXmlContent(xmlContent)
{    
    // create appropiate XML document
    if (window.ActiveXObject) {
        // IE 6 (and 7)
        doc = new ActiveXObject("Microsoft.XMLDOM");
        if (!doc.loadXML(xmlContent)){
            // handle parse error
            throw doc.parseError.reason;
        }
    }
    else {
        // Firefox and others
        var parser = new DOMParser();
        doc = parser.parseFromString(xmlContent, "text/xml");
    }
    return doc;
}

//Get template for showing listing info.
function GetListingBoxTemplate(templateType,MLSDB)
{
    var template = "";
    switch(templateType)
    {
        case "Result":
        case "Fav":
        case "Open":
            template = GetListingBoxTemplate_Result(MLSDB);break;
        case "Comps":
            template = GetListingBoxTemplate_Comps(MLSDB);break;
        default://"Map"
            template = GetListingBoxTemplate_Map(MLSDB);break;
    }
    
    return template;
}

function GetStatus(statusNum)
{
    var status = 0;
    if(statusNum != undefined && statusNum != null)
        status = parseInt(statusNum);
    var strStatus;
	switch(status)
	{
		case 1:
			strStatus="Active";
			break;
		case 2:
			strStatus="Pending Release";
			break;
		case 3:
			strStatus="Pending Show";
			break;
		case 4:
			strStatus="Pending";
			break;
		case 5:
			strStatus="Sold";
			break;
		case 6:
			strStatus="Expired";
			break;
		case 7:
			strStatus="Cancel";
			break;
		case 8:
			strStatus="Withdrawn";
			break;
		case 9:
			strStatus="Active Cont.";
			break;
		default:
		    strStatus="";
			break;
	}
	
	return strStatus;
}
function GetStatusDESC(statusDESCNum)
{
    var descNum = 0;
    if(statusDESCNum != undefined && statusDESCNum != null)
        descNum = parseInt(statusDESCNum);
    var statusDESC = "";
    switch(descNum)
    {
        case 1:
            statusDESC = "Notice of Default"; break;
        case 2:
            statusDESC = "Lis Pendens"; break;
        case 3:
            statusDESC = "Notice of Trustee Sale"; break;
        case 4:
            statusDESC = "Notice of Foreclosure Sale"; break;
        case 5:
            statusDESC = "Real Estate Owned"; break;
    }
    
    return statusDESC;
}

function HouseBox(type)
{
    //Include four type for four pages:
    //1."Map" for MapSearch;    2."Comps" for Comps;    3."Result" for SearchResult;    4."Fav" for Favorite;   5."Open" for Open house
    if(type != undefined && type != null)
        this.BoxType = type;
    else
        this.BoxType = "Map";
    
    this.Address		      =	null;
    this.bathroomText         =	null;
    this.bedroomText          =	null;
    this.DaysOnMkt            =	null;
    this.Favorite             =	null;
    this.HouseScore           =	null;
    this.iGen_Key             =	null;
    this.list_price           =	null;
    this.listingType          =	null;
    this.ln_list_agents_name  =	null;
    this.lo_listing_office    =	null;
    this.lot_size             =	null;
    this.lotsize_desc         =	null;
    this.mls_db               =	null;
    this.mls_num              =	null;
    this.num_photos_dl        =	null;
    this.openHouseText        =	null;
    this.planName             =	null;
    this.priceChange          =	null;
    this.salePrice            = null;
    this.saleDate             = null;
    this.square_feet          =	null;
    this.ss_status            =	null;
    this.ss_status_desc       = null;
    this.StaticURL            =	null;
    this.vs_flag              =	null;
    this.zipcode              =	null;
    this.cityCode             =	null;
    this.flag_display         = null;
    this.state_code           = null;
}
HouseBox.prototype.GetValidValue = function(value)
{
    if(value == undefined || value == null)
        value = "";
    return value;
}
/***************************************************** For Common Keys [START] *************************************************/
HouseBox.prototype.GetPrice = function()
{
    var price;   
    if(this.BoxType == "Result" || this.BoxType == "Fav" || this.BoxType == "Open")
    {
        var iconForPrice = "";					
        if(this.priceChange == "1")
	        iconForPrice = "&nbsp;<IMG alt='price_up' src='images/up_arrow.gif' border=0>";
        else if(this.priceChange == "2")
	        iconForPrice = "&nbsp;<IMG alt='price_down' src='images/down_arrow.gif' border=0>";
        
        var list_price;
        if(this.BoxType == "Result")
            list_price = GetValidatePriceValue(this.list_price.toString()).substring(1);
        else
            list_price = this.list_price;
        
        price = list_price + iconForPrice;
    }
    else
        price = this.list_price;
    
    return price;    
}
HouseBox.prototype.GetSQFeet = function()
{
	var SQFeet = this.square_feet;
    if(SQFeet == "")
        SQFeet = 0;
    
    return SQFeet;
}
HouseBox.prototype.GetLotSizeDesc = function()
{
    var Lotsize_desc = this.lotsize_desc;
    if(Lotsize_desc =="")
        Lotsize_desc = "0";
    
    return Lotsize_desc;
}

HouseBox.prototype.GetLotSize = function()
{
    return getLotSize(this.lot_size,this.lotsize_desc,this.mls_db);
}
HouseBox.prototype.GetDaysOnMkt = function()
{
    var daysOnMkt;
    if(this.BoxType == "Result" || this.BoxType == "Open")
    {
	    var iconForDOM = "";
	    if(this.DaysOnMkt <= gdays_isNew)
	        iconForDOM = "&nbsp;<font color=\"#008303\"><b>NEW</b></font>";
        daysOnMkt = this.DaysOnMkt + iconForDOM;
    }
    else if(this.BoxType == "Fav" && parseInt(this.ss_status) > 4)
        daysOnMkt = "";
    else
        daysOnMkt = this.DaysOnMkt;
        
    return daysOnMkt;
}
HouseBox.prototype.GetStatus = function()
{
    return GetStatus(this.ss_status);
}
HouseBox.prototype.GetStatusDESC = function()
{
    return GetStatusDESC(this.ss_status_desc);
}
HouseBox.prototype.GetMLSLogo = function()
{
    return GetMLSLogosByMlsDb( eval(this.mls_db) );
}
HouseBox.prototype.GetHouseImg = function() {
    var img = "";
    if (this.num_photos_dl > 0)
        img = "<IMG alt=\"" + this.Address + ", " + this.state_code + "\" title=\"Click for House Detail\" src=\"" + GetSmallImage(this.mls_num, this.mls_db) + "\" border=0>";
    else 
    {
        //When a listing has no photo, display default images in the place.
        img = "<img alt=\"" + this.Address + ", " + this.state_code + "\" class=\"noPhoto\" src =\"" + GetRelativePath2() + "" + "images/nophoto_small.gif\">";
    }

    return img;
}
/***************************************************** For Common Keys [END] *************************************************/
HouseBox.prototype.GetOfficeFor431 = function()
{
	var officeFor431;
	if(this.lo_listing_office != null && this.lo_listing_office !='')
		officeFor431 = "Listing Information Courtesy Of " + this.lo_listing_office;
    else
        officeFor431 = "";
    
    return officeFor431;
}
HouseBox.prototype.GetNewRowForOffice = function()
{
	var newRowOffice;
	if(this.lo_listing_office != null && this.lo_listing_office !='')
		newRowOffice = "<br>";
    else
        newRowOffice = "";
    
    return newRowOffice;   
}
HouseBox.prototype.GetNewRowForAgent = function()
{
	var newRowAgent;
	if(this.ln_list_agents_name != null && this.ln_list_agents_name !='')
		newRowAgent = "<br>";
    else
        newRowAgent = "";
    
    return newRowAgent;   
}
HouseBox.prototype.GetSoldInfo = function()
{
	var soldInfo = "";
	if(this.salePrice && this.ss_status != 1)
	{
		if(this.ss_status == 4 && (this.salePrice == "" || this.salePrice == "&nbsp;"))
			soldInfo = "<br> Sold Price: N/A";
		else
			soldInfo = "<br> Sold Price: $" + this.salePrice;
	}
	if(this.saleDate && this.ss_status != 1)
	{
		soldInfo = "<br> Sold Date: " + this.saleDate;
	}

    return soldInfo;
}
HouseBox.prototype.GetStatusOnMkt = function()
{
    var statusOnMkt;
    if( this.BoxType == "Fav" && this.ss_status != null && parseInt(this.ss_status) > 4)
	    statusOnMkt = "<font color=red>" + GetStatus(this.ss_status) + "</font>";
	else
	    statusOnMkt = "";
	
	return statusOnMkt;
}
HouseBox.prototype.GetValueSpotImg = function()
{
    var vsImg = "";
    var extraFlag = GetExtraFlag(this.flag_display, 4);
    if(this.BoxType == "Map")
    {
        var spot = false;
        if(!extraFlag && this.vs_flag == 1)
            spot = true;
        vsImg  = GetValuesSpot(this.iGen_Key,spot,"");
    }
    else if(this.BoxType == "Result" || this.BoxType == "Fav" || this.BoxType == "Open")
    {        
	    if(!extraFlag && this.vs_flag == 1)
		    vsImg = "<div style='width:100%' align=right><a class='cursorPointer' onmouseover=\"showInd('VSP_"+ this.iGen_Key +"')\" onmouseout=\"HiddenInd('VSP_"+ this.iGen_Key +"')\"><img src='images/icon_dollar_sign.gif' border=0></a><span id=\"VSP_"+ this.iGen_Key +"\"></span></div>";
	    else
		    vsImg = "<br>";
    }
    
    return vsImg;
}
HouseBox.prototype.GetMoreInfoLink = function()
{
	var moreInfoLink = "";
	if(this.BoxType == "Map")
//	    moreInfoLink = GetHouseAddress(igenkey,"<b>More Info</b>",1,"");
        moreInfoLink = GetALink("<b>More Info</b>", this.StaticURL);
	
	return moreInfoLink;
}
HouseBox.prototype.GetHotleadParameter = function()
{
	var numPic = 0;
	if(this.num_photos_dl > 0)
		numPic = 1;
	var address = this.Address.replace(/\"|\'/g,"");
	
    var arr = new Array();
    arr.push(numPic);
    arr.push(",\"");
    arr.push(this.list_price);
    arr.push("\",\"");
    arr.push(address);
    arr.push(" ");
    arr.push(this.zipcode);
    arr.push("\",\"");
    arr.push(this.mls_num);
    arr.push("\",");
    arr.push(this.mls_db);
    arr.push(",\"");
    arr.push(this.bedroomText);
    arr.push("\",\"");
    arr.push(this.bathroomText);
    arr.push("\",");
    arr.push(this.iGen_Key);
    arr.push(",\"");
    arr.push(this.cityCode);
    arr.push("\"");
    
    return arr.join("");
}
HouseBox.prototype.GetOpenText = function()
{
	var openText = "";
	if ( this.openHouseText && this.openHouseText!="&nbsp;" )
			openText = "<br>" + this.openHouseText;
    return openText;
}
HouseBox.prototype.GetFavorite = function()
{
	var fv;
	var curIsCheck = "";
	if(this.Favorite == 1)
	{
		curIsCheck = "checked";
		fv = "<span id=\"fv_" + this.iGen_Key + "\"><img src=\"images/favorite.gif\" style=\"alpha:100%;vertical-align:bottom;\" height=\"17\" width=\"63\"></span>";
	}
	else
	{
	    fv = "<span id=\"fv_" + this.iGen_Key + "\"><img src=\"images/favorite_2.gif\" style=\"alpha:100%;vertical-align:bottom;\" height=\"17\" width=\"63\"></span>";
	}

	var favorite;
	if(this.BoxType == "Result")					
		favorite = "<div style='margin-left:-3px'><table width=100% border=0 cellpadding=0 cellspacing=0><tr><td><input id=\"check_" + this.iGen_Key + "\" type=\"checkbox\" "+curIsCheck+" onclick=\"UpdateSavedHouse('check_"+this.iGen_Key+"')\"/>"+fv+"</td><td align=right style='vertical-align:middle;'><strong>"+this.HouseScore+"%</strong> Matched</td></tr></table></div>";
	else
		favorite = "<div style='margin-left:-3px'><input id=\"check_" + this.iGen_Key + "\" type=\"checkbox\" "+curIsCheck+" onclick=\"UpdateSavedHouse('check_"+this.iGen_Key+"')\"/>"+fv+"</div>";

    return favorite;
}
/*Flow to handle new special MLSDB arrival:
1. Find the function GetListingBoxTemplate_(*) which manage the template for special MLSDB.
2. Check the difference notes to look for the same special template.
    if(HasTheSame) {   
        Add "case MLSDB" in GetListingBoxTemplate_(*).
        eg. if current MLS(1000) shows "Days on Movoto" instead of "Days on Market", we've had template "templateMLS_DaysOnMovoto" yet.
        Just add "case 1000:" in the GetListingBoxTemplate_(*).
    }
    else {
        Flow to Add new special template:
        1). Copy a new template_MLS template, name it and add its difference note.
        2). Modify the template.
            if(difference is static HTML)
            {
                Edit the HTML in template. eg. Change the "Days on Market" with "Days on Movoto".
            }
            else
            {
                1]. Add a (key,value) in the belowing switch.
                    eg. case "StaticURL": value = res.value.Tables[0].Rows[i].StaticURL;break;
                    key is "StaticURL". value is res.value.Tables[0].Rows[i].StaticURL.
                2]. Find position and Add the key into template. The key should be added in format like ~key~, eg. ~StaticURL~
            }
        3). Add MLSDB in judgement sentence of GetListingBoxTemplate_(*). 
            eg. case 300: template = templateMLS_NoDOM;break;
   }
*/					
HouseBox.prototype.GetHouse = function()
{
    var currentBoxHTML = GetListingBoxTemplate(this.BoxType,this.mls_db);
    var reg = /~(\w+?)~/g;
    var replaceList = currentBoxHTML.match(reg);
    for(var k=0; k<replaceList.length; k++)
    {
        var re = new RegExp(replaceList[k],"g");
        var value = "";
        var key = replaceList[k].substring(1,replaceList[k].length-1);
        switch(key)
        {
            //Common info
            case "StaticURL":           value = this.StaticURL;break;
            case "Address":             value = this.Address;break;
            case "ZipCode":             value = this.zipcode;break;
            case "IGenKey":             value = this.iGen_Key;break;
            case "Bed":                 value = this.bedroomText;break;	                        
            case "Bath":                value = this.bathroomText;break;
            case "MLSNum":              value = this.mls_num;break;
            case "MLSImg":              value = this.GetMLSLogo();break;
            case "HouseImg":            value = this.GetHouseImg();break;
            case "Price":               value = this.GetPrice();break;
            case "SQFeet":              value = this.GetSQFeet();break;
            case "LotSize":             value = this.GetLotSize();break;
            case "DaysOnMkt":           value = this.GetDaysOnMkt();break;
           
            //Special info. Use this.GetValidValue(value) to get value if no special function to get.
            //eg. value = this.GetValidValue(this.lo_listing_office);
            case "Status":              value = this.GetStatus();break;
            case "StatusDESC":          value = this.GetStatusDESC();break;//For MLS801:Foreclosure
            case "Office":              value = this.GetValidValue(this.lo_listing_office); break;
            case "OfficeFor431":        value = this.GetOfficeFor431(); break;
            case "newRowOffice":        value = this.GetNewRowForOffice();break;	                        
            case "Agent":               value = this.GetValidValue(this.ln_list_agents_name);break;
            case "newRowAgent":         value = this.GetNewRowForAgent(); break;
            case "ValueSpotImg":        value = this.GetValueSpotImg();break;
            case "Lotsize_desc":        value = this.GetLotSizeDesc();break;
            
            //Map
            case "MoreInfo":            value = this.GetMoreInfoLink(); break;  
            
            //Comps
            case "DaysOnMkt_comps":     value = this.GetDaysOnMkt();break;
            case "SoldInfo":	        value = this.GetSoldInfo();break;
            
            //Favorite
            case "StatusOnMkt":         value = this.GetStatusOnMkt();break;
            
            //Result
            case "HotleadParameters":   value = this.GetHotleadParameter();break;
            case "Open":                value = this.GetOpenText();break;
            case "StrFavorite":         value = this.GetFavorite();break;
            
            default: break;
        }
        
        currentBoxHTML = currentBoxHTML.replace(re, value);
    }
    
    return currentBoxHTML;
}

function getLotSize(lotSize, lotSize_desc, MlsDB)
{
    var lot_size ="N/A";
    if(MlsDB == 411)
    {
        if(lotSize !='' && lotSize !='0')
            lot_size = lotSize; 
    }
    else
    {
        if(lotSize !='' && lotSize !='0')
            lot_size = lotSize;  
        else if (lotSize_desc != undefined && lotSize_desc != null && lotSize_desc !='Not Available')
            lot_size = lotSize_desc.length<=3 ? "N/A" : lotSize_desc;
    }
    return(lot_size);
}

var callBackHotleadType = "";
function SendCallBackHotlead(hotleadType)
{	
    //debugger;
    callBackHotleadType = hotleadType;
	
    //0.txtMessage, 1.txtName, 2.txtMail, 3.txtPhone, 4.txtTime1, 5.txtTime2,
    //6.tbCurMlsNum, 7.tbIGEN_KEY, 8.hdAddress, 9.hdPrice, 10.pageURL, 11.Hidden1
    var tMsg = "";
    var tNm = document.getElementById(gCtlIdPrefix.MainContent + "txtName").value;
    tNm = tNm.replace(/&/g," ").replace(/'/g,"");
    var tMl = document.getElementById(gCtlIdPrefix.MainContent + "txtMail" ).value;
    var tPh = FormatPhoneNumber(document.getElementById(gCtlIdPrefix.MainContent + "txtPhone").value);

    if (document.getElementById(gCtlIdPrefix.MainContent + "tbMessage") != null)
        tMsg = document.getElementById(gCtlIdPrefix.MainContent + "tbMessage").value;
    else if (document.getElementById("tbMessage") != null)
        tMsg = document.getElementById("tbMessage").value;

    var cityName = "";
    var cityInfo = "";
    if (hotleadType == "7")
        cityInfo = parent.document.getElementById(gCtlIdPrefix.PageHeader + "GetCityZipForAd").value;
    else
        cityInfo = document.getElementById(gCtlIdPrefix.PageHeader + "GetCityZipForAd").value;
    if(cityInfo != "")
        cityName = cityInfo.split('-')[2];
    
    if(tNm == "" || tMl == "" || tPh == "" || tNm == "Name" || tMl == "Email Addres" || tPh == "Phone Number" )
    {
        alert("Please complete all the required fields.");
        return;
    }
    
    if(!validateEmailAddress(tMl))
    {
        alert("Your email address does not appear to be valid. Please try again.");
        return;
    }
    
    if(!validatePhoneNumber(tPh))
    {
        alert("Your phone number does not appear to be valid. Please try again.");
        return;
    }
				
    var tTm1 = "";
    var tTm2 = "";
	
    var tUrl = window.location.href;			
    var strInput = tNm + "&" + tMl + "&" + tPh + "&" + tTm1 + "&" + tTm2;

    var cProperty = null;
    if (hotleadType == 8)
        cProperty = getCurrentPropertyObjectForOffMarket();
    else
        cProperty = getCurrentPropertyObject();
    var cPropertyInstance  = "";
    if(cProperty != null && cProperty.isMatch == true)
        cPropertyInstance = cProperty.mlsnum + "&" + cProperty.igenkey + "&" + cProperty.price + "&" + cProperty.address + "&" + cProperty.cityCode;
    else if (hotleadType == 9)
        cPropertyInstance = "&&&&" + document.getElementById(gCtlIdPrefix.MainContent + "iptCity").value;
    else if(cityName != "")
        cPropertyInstance = "&&&&" + cityName;
    else
        cPropertyInstance = "";

    if (document.getElementById(gCtlIdPrefix.MainContent + "txtName") != null)
        document.getElementById(gCtlIdPrefix.MainContent + "txtName").value = "";

    if (document.getElementById("txtName") != null)
        document.getElementById("txtName").value = "";

    if (document.getElementById(gCtlIdPrefix.MainContent + "txtMail") != null)
        document.getElementById(gCtlIdPrefix.MainContent + "txtMail").value = ""

    if (document.getElementById("txtMail") != null)
        document.getElementById("txtMail").value = "";

    if (document.getElementById(gCtlIdPrefix.MainContent + "txtPhone") != null)
        document.getElementById(gCtlIdPrefix.MainContent + "txtPhone").value = "";

    if (document.getElementById("txtPhone") != null)
        document.getElementById("txtPhone").value = "";

    if (document.getElementById(gCtlIdPrefix.MainContent + "tbMessage") != null)
        document.getElementById(gCtlIdPrefix.MainContent + "tbMessage").value = "";

    if (document.getElementById("tbMessage") != null)
        document.getElementById("tbMessage").value = "";
    
    iGen.WebServices.Common.ClickSendButton(tMsg, strInput, cPropertyInstance, tUrl, callBackHotleadType,onSendHotleadsSucceed);
}

function SendCallBackHotleadDPPRight(hotleadType) {
    //debugger;
    callBackHotleadType = hotleadType;

    //0.txtMessage, 1.txtName, 2.txtMail, 3.txtPhone, 4.txtTime1, 5.txtTime2,
    //6.tbCurMlsNum, 7.tbIGEN_KEY, 8.hdAddress, 9.hdPrice, 10.pageURL, 11.Hidden1

    var tNm = document.getElementById(gCtlIdPrefix.MainContent + "txtNameDPPRight").value;
    tNm = tNm.replace(/&/g, " ").replace(/'/g, "");
    var tMl = document.getElementById(gCtlIdPrefix.MainContent + "txtMailDPPRight").value;
    var tPh = FormatPhoneNumber(document.getElementById(gCtlIdPrefix.MainContent + "txtPhoneDPPRight").value);
    var tMsg = document.getElementById(gCtlIdPrefix.MainContent + "tbMessageDPPRight").value;

    var cityName = "";
    var cityInfo = "";
    if (hotleadType == "7")
        cityInfo = parent.document.getElementById(gCtlIdPrefix.PageHeader + "GetCityZipForAd").value;
    else
        cityInfo = document.getElementById(gCtlIdPrefix.PageHeader + "GetCityZipForAd").value;
    if (cityInfo != "")
        cityName = cityInfo.split('-')[2];

    if (tNm == "" || tMl == "" || tPh == "" || tNm == "Name" || tMl == "Email Addres" || tPh == "Phone Number") {
        alert("Please complete all the required fields.");
        return;
    }

    if (!validateEmailAddress(tMl)) {
        alert("Your email address does not appear to be valid. Please try again.");
        return;
    }

    if (!validatePhoneNumber(tPh)) {
        alert("Your phone number does not appear to be valid. Please try again.");
        return;
    }

    var tTm1 = "";
    var tTm2 = "";

    var tUrl = window.location.href;
    var strInput = tNm + "&" + tMl + "&" + tPh + "&" + tTm1 + "&" + tTm2;

    var cProperty = null;
    if (hotleadType == 8)
        cProperty = getCurrentPropertyObjectForOffMarket();
    else
        cProperty = getCurrentPropertyObject();
    var cPropertyInstance = "";
    if (cProperty != null && cProperty.isMatch == true)
        cPropertyInstance = cProperty.mlsnum + "&" + cProperty.igenkey + "&" + cProperty.price + "&" + cProperty.address + "&" + cProperty.cityCode;
    else if (hotleadType == 9)
        cPropertyInstance = "&&&&" + document.getElementById(gCtlIdPrefix.MainContent + "iptCity").value;
    else if (cityName != "")
        cPropertyInstance = "&&&&" + cityName;
    else
        cPropertyInstance = "";

    if (document.getElementById(gCtlIdPrefix.MainContent + "txtNameDPPRight") != null)
        document.getElementById(gCtlIdPrefix.MainContent + "txtNameDPPRight").value = "";

    if (document.getElementById(gCtlIdPrefix.MainContent + "txtPhoneDPPRight") != null)
        document.getElementById(gCtlIdPrefix.MainContent + "txtPhoneDPPRight").value = "";

    if (document.getElementById(gCtlIdPrefix.MainContent + "tbMessageDPPRight") != null)
        document.getElementById(gCtlIdPrefix.MainContent + "tbMessageDPPRight").value = "";

    if (document.getElementById(gCtlIdPrefix.MainContent + "txtMailDPPRight") != null)
        document.getElementById(gCtlIdPrefix.MainContent + "txtMailDPPRight").value = ""

    iGen.WebServices.Common.ClickSendButton(tMsg, strInput, cPropertyInstance, tUrl, callBackHotleadType, onSendHotleadsSucceed);
}

function onSendHotleadsSucceed(res)
{
    if(res == "fail")
    {
        alert("Failed to send email.");
    }
    else {
        var pageType = window.top.document.getElementById(gCtlIdPrefix.PageHeader + "iptPageType");
        
        switch (callBackHotleadType) {
            case "4":
                if (pageType != null && pageType.value == "DPP2")
                    TrackGoogleAnalytics("LeadConfirmation_DppCallBack Six");
                else
                    TrackGoogleAnalytics("LeadConfirmation_DppCallBack");
                break;
            case "5":
                TrackGoogleAnalytics("LeadConfirmation_PropSearchCallBack");
                break;
            case "6":
                TrackGoogleAnalytics("LeadConfirmation_MapSearchCallBack");
                break;
            case "7":
                if (pageType != null && pageType.value == "DPP2")
                    TrackGoogleAnalytics("LeadConfirmation_DppPopup Six");
                else
                    TrackGoogleAnalytics("LeadConfirmation_DppPopup");
                break;
            case "8":
                TrackGoogleAnalytics("LeadConfirmation_OffMktCallBack");
                break;
            case "9":
                TrackGoogleAnalytics("LeadConfirmation_MktInfo");
                break;
        }

        alert("Thank you! We will contact you shortly.");
        if (callBackHotleadType == "7")
            void (parent.closePopUpWindow());
    }
    return;
}

var callBackInputLettersName = "Name";
var callBackInputLettersEmail = "Email Address";
var callBackInputLettersPhone = "Phone Number";

function ClearNote(textbox,note)
{
    if(textbox.value == note)
        textbox.value = '';
    textbox.className = '';
}
function AddNote(textbox,note)
{
    if(textbox.value == '')
    {
        textbox.value = note;
        textbox.className = 'textboxNote';
    }
}
function MLSWithNoListDate(mlsDB)
{
    var isDaysOnMovoto = false;
    switch(eval(mlsDB))
    {//	402,401,411,412,431,432,433,491,471,441
        case 401:
        case 402:
        case 411:
        case 412:
        case 431:
        case 432:
        case 433:
        case 491:
        case 471:
        case 441:
            isDaysOnMovoto = true;
            break;            
    }
    return isDaysOnMovoto;
}

// Get a DataTable from AJAX results.
function GetDataTable(tableName,res)
{
    for(var i=0; i<res.Tables.length; i++)
    {
        if(res.Tables[i].Name == tableName)
            return res.Tables[i];
    }
    return null;
}

function RefreshCityTextParagraphForCityInfo()
{
    var divCityTextParagraph = document.getElementById(gCtlIdPrefix.MainContent + "divCityTextParagraph");
    var divFooterCityTextParagraph = document.getElementById("divFooterCityTextParagraph");
    if(divCityTextParagraph && divFooterCityTextParagraph)
    {
        divFooterCityTextParagraph.innerHTML = divCityTextParagraph.innerHTML;
        divCityTextParagraph.innerHTML = "";
    }
}

function GetExtraFlag(flagDisplay, compareValue)
{
    var extraFlag = false;
    if (flagDisplay >= 4 && flagDisplay <= 11)
    {
        extraFlag = ((flagDisplay - 4) & compareValue) == 0 ? true : false;
    }

    return extraFlag;
}

function showTestScoreNotes(noteId, type)
{
	//default MCAS notes
	var note = "";
	switch(noteId.toLowerCase())
	{
		case "solnotes":
			note="<p>Virginia Standards of Learning (SOL) test scores are displayed as three percentages which represent the following criteria:<br><br>"
			+"English/Math/Science<br><br>Each number refers to the percentage of students passing the test school-wide.</p>";
			break;
		case "msanotes":
			note = "<p>Maryland School Assessment (MSA) test scores are displayed as two percentages which represent the following criteria:<br><br>"
				+"English/Math<br><br>Each number refers to the percentage of students scoring proficient or better<br>school-wide.</p>";
			break;
		case "solnotes_en":
		case "solnotes_mth":
			note = "<p>Movoto calculates Virginia high school performance by averaging the school-wide Standards of Learning (SOL) results from various subjects into three separate categories."
			+"<p>The English score is an average of the percentages of students who passed the SOL Reading and SOL Writing tests.<br>The Math score is an average of the percentages of students who passed the SOL Algebra 1, SOL Algebra 2, and SOL Geomerty tests.<br>The Science score is an average of the percentages of students who passed the SOL Chemistry, SOL Biology, and SOL Earth Science tests.</p>";
			break;
		case "aypnotes":
			note = "<p>Washington DC schools are measured with DC-CAS tests. These scores are displayed as two percentages which represent the following criteria:<br><br>"
				+"Reading/Math<br><br>Each number refers to the percentage of students scoring proficient or betterschool-wide.</p>";
			break;
		case "dcnotes":
			note = "<p>The schools in the DC/Maryland/Virginia area are scored in the following ways:</p>"
				+"<p><b>Washington DC</b>: Comprehensive Assessment System (DC-CAS).  The two numbers displayed for DC schools represent the percentages of students passing at or above the proficient level in the subjects of reading and math.</p>" 
				+"<p><b>Maryland</b>: Maryland School Assessment (MSA).  The two numbers displayed for Maryland schools represent the percentages of students scoring proficient or better in the subjects of English and math.</p>" 
				+"<p><b>Virginia</b>: Virginia Standards of Learning (SOL).  The three numbers displayed for Virginia schools represent the percentages of students passing in the subjects of English, math, and science.</p>";
			break;
		case "taksnotes":
			note = "<p>In the state of Texas, school performance is scored by the Texas Assessment of "
				+"Knowledge and Skills (TAKS) tests.  The values below represent the percentage "
				+"of students who met or exceeded the standards in the all the TAKS tests</p>";
			break;
		case "ganotes":
			note = "<p>The number in the test score column represents the average (mean) value of "
						+"students passing the following tests.  To see each subject individually, click "
						+"on the school name to see a detailed report on the school.<BR><BR> "

						+"Elementary Schools: Grade 5 English language arts, reading, math, science, and "
						+"social studies CRCT tests.<BR><BR> "

						+"Middle Schools: Grade 8 English language arts, reading, math, science, and "
						+"social studies CRCT tests.<BR><BR> "

						+"High Schools: Grade 11 English language arts, math, science, and social studies "
						+"EOCT tests.</p>";
			break;			
		//added by Jane Oct,28 2008 
		case "ncnotes":
			note = "<p>Elementary and middle school students in North Carolina are tested with the "
						+"End-of-Grade (EOG) tests in the subjects of reading and math. Movoto shows the percentage of students per "
						+"school who scored at or above the proficient level in each subject.<BR><BR> "
						
						+"High school students are tested with End-of-Course (EOC) tests in the "
						+"subjects algebra 1, algebra 2, English 1, biology, United States "
						+"history, geometry, chemistry, physical science, physics, and ELPS. Movoto "
						+"shows the percentage of students per school who scored at or above the proficient level in each subject.</p>";							
			break;
		//added by Jane Dec, 16 2008 for bug 4524
		case "fcatnotes":
			note = "<p>The three scores below represent the Florida Comprehensive Achievement Test "
						+"(FCAT) results for the highest available grade level in the school. The scores "
						+"are Reading/Math/Science respectively.</p>";
			break;
		case"oaksnotes":
			note ="<p>The four scores represent the Oregon Assessment of Knowledge and Skills (OAKS) "
                        +"scores for the highest available grade level in the school. The scores are "
                        +"Reading/Math/Science/Writing respectively.<br><br>*95% is the highest possible score, and 5% is the lowest possible score.</p>";
			break;
        case"waslnotes":
            note = "<p>The four scores represent the Washington Assessment of Student Learning (WASL) "
                      +"scores for the highest available grade level in the school. The scores are "
                      +"Reading/Math/Science/Writing respectively.</p>";
            break;
        case"aimsnotes":
			note ="<p>The four scores represent the Arizona Instrument to Measure Standards (AIMS) "
                    +"results for the highest available grade level in the school. The scores are Reading/Math/Science/Writing respectively.</p>";
			break;
        case"isatnotes":
            note = "<p>The number for each school is a percentage that represents the performance of "
                    +"students in the school on the ISAT test for elementary/middle schools, or the "
                    +"PSAE test for high schools. This score is provided by the Illinois State Board "
                    +"of Education.</p>";
            break;
        case"pssanotes":
            note = "<p>The four numbers represent the Pennsylvania System of State Assessments (PSSA) "
                    +"scores for the highest available grade level in the school. The scores are "
                    +"Reading/Math/Science/Writing respectively.</p>";
            break;
        case"nysanotes":
            note = "<p>The value represents a composite score of the performance of the school.  For "
                    +"elementary and middle schools, the value is an average (mean value) of the Math and English New York State Assessment (NYSA) tests.  For high schools, the "
                    +"value is an average of the 10 subjects of the NYSA Regents Examinations.  These subjects include Math A, Math B, English, Living Environment, Physics, "
                    +"Chemistry, Earth Science, Integrated Algebra, Global History/Geography, and U.S. History/Government.</p>";
            break;
        case "tcapnotes":
            note = "<p>The two scores below represent the Tennessee Comprehensive Assessment Program "
                    + "(TCAP) results for the highest available grade level in the school. The scores "
                    + "are displayed as Math/Reading respectively.</p>";
            break;
        case "dstpnotes":
            note = "<p>The three scores below represent the Delaware Student Testing Program (DSTP) results "
                    +"for the highest available grade level in the school. The scores are displayed as "
                    +"Math/Reading/Writing respectively</p>";
            break;
        case "nj_asknotes":
            note = "<p>For high schools, the two numbers represent the High School Proficiency Assessment "
            +"(HSPA) test results in the subjects of math and language arts respectively.  For elementary "
            +"and middle schools, the three numbers represent the New Jersey Assessment of Skills and Knowledge "
            +"(NJ ASK) test results in the subjects of math, language arts, and science respectively.</p>";
            break;
        case "csapnotes":
            note = "<p>In the State of Colorado, school performance is scored using the Colorado Student "
            + "Assessment Program (CSAP) tests.  Students are tested in the subjects of reading, writing, "
            + "and math in grades 3 through 10, and science in grades 5, 8, and 10.  The numbers displayed "
            + "below represent percentage of students who passed the test at a proficient level or above. "
            + "The four values represent the scores for the highest grade in the school in the subjects of "
            + "reading, math, writing, and science respectively.</p>";
            break;
        case "mca_iinotes":
            note = "<p>In Minnesota, the Minnesota Comprehensive Assessment-II (MCA-II) is used to score "
            + "school performance. The values represent the percentage of students who met or exceeded "
            + "the test standards for the MCA-II tests in Math, Reading, and Science respectively.</p>";
            break;
        case "wkcenotes":
            note = "<p>In the state of Wisconsin, the school performance is scored using the Wisconsin Knowledge "
            + "and Concepts Examination (WKCE). The scores displayed represent the percentage of students who scored in the proficient and "
            + "advanced levels of the WKCE tests  in Language Arts, Math, Reading, Science, and Social studies respectively.</p>";
            break;
		default:
			note="<p>MCAS test scores are displayed as three percentages <br>which represent the following criteria:<br><br>"
				+ "<b>Elementary Schools</b> - 5<sup>th</sup> Grade English/Math/Science<br><b>Middle Schools</b> - 8<sup>th</sup> Grade English/Math/Science<br><b>High Schools</b> - 10<sup>th</sup> Grade English/Math<br><br>"
				+ "Each number refers to the percentage of students<br>scoring at/above the proficient level.</p>";
			break;
	}
	var ID=document.getElementById(noteId);
	if(type == "dpp")
	    ID = document.getElementById("schoolNotes");
	else
	{
	    noteId = noteId + type;
	    ID=document.getElementById(noteId);
	}
	if(ID != null)
	{
        ID.className="notesStyle";
        ID.innerHTML=note;
    }
}

function HiddenTestScoreNotes(noteId, type)
{
	var ID=document.getElementById(noteId);
	if(type == "dpp")
	    ID = document.getElementById("schoolNotes");
	else
	{
	    noteId = noteId + type;
	    ID=document.getElementById(noteId);
	}
	if(ID != null)
	    ID.className="notesStyleHidden";
}

function showPopupNotes(noteId, noteContent)
{
    var ID=document.getElementById(noteId);
	ID.className="notesStyle";
	ID.innerHTML=noteContent;
}

function HiddenPopupNotes(noteId)
{
	var ID=document.getElementById(noteId);
	ID.className="notesStyleHidden";
}
/********************************** Homepage Slide Panel **********************************/
var Extend = function(destination, source) {
    for (var property in source) {
        destination[property] = source[property];
    }
    return destination;
}

var CurrentStyle = function(element) {
    return element.currentStyle || document.defaultView.getComputedStyle(element, null);
}

var Bind = function(object, fun) {
    var args = Array.prototype.slice.call(arguments).slice(2);
    return function() {
        return fun.apply(object, args.concat(Array.prototype.slice.call(arguments)));
    }
}

var Tween = {
    Quart: {
        easeOut: function(t, b, c, d) {
            return -c * ((t = t / d - 1) * t * t * t - 1) + b;
        }
    },
    Back: {
        easeOut: function(t, b, c, d, s) {
            if (s == undefined) s = 1.70158;
            return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
        }
    },
    Bounce: {
        easeOut: function(t, b, c, d) {
            if ((t /= d) < (1 / 2.75)) {
                return c * (7.5625 * t * t) + b;
            } else if (t < (2 / 2.75)) {
                return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b;
            } else if (t < (2.5 / 2.75)) {
                return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b;
            } else {
                return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b;
            }

        }
    }
}
var SlideTrans = function(container, slider, options) {
    this._slider = $get(slider);
    this._container = $get(container); 
    this._timer = null; 
    this._count = Math.abs(5);
    this._target = 0;
    this._t = this._b = this._c = 0;
    this.Index = 0;
    this.SetOptions(options);

    this.Auto = !!this.options.Auto;
    this.Duration = Math.abs(this.options.Duration);
    this.Time = Math.abs(this.options.Time);
    this.Pause = Math.abs(this.options.Pause);
    this.Tween = this.options.Tween;

    var bVertical = !!this.options.Vertical;
    this._css = bVertical ? "left" : "left";

    var p = CurrentStyle(this._container).position;
    p == "relative" || p == "absolute" || (this._container.style.position = "relative");
    this._container.style.overflow = "hidden";
    this._slider.style.position = "absolute";

    this.Change = this.options.Change ? this.options.Change :
            this._slider[bVertical ? "offsetHeight" : "offsetWidth"] / this._count;
};
SlideTrans.prototype = {
    SetOptions: function(options) {
        this.options = {
            Vertical: true,
            Auto: true,
            Change: 0,
            Duration: 100,
            Time: 10,
            Pause: 11000,
            Tween: Tween.Quart.easeOut
        };
        Extend(this.options, options || {});
    },
    
    Run: function(index) {
        index == undefined && (index = this.Index);
        index < 0 && (index = this._count - 1) || index >= this._count && (index = 0);
        this._target = -Math.abs(this.Change) * (this.Index = index);
        this._t = 0;
        this._b = parseInt(CurrentStyle(this._slider)[this.options.Vertical ? "top" : "left"]);
        this._c = this._target - this._b;
        this.Move();
    },
    Move: function() {
        clearTimeout(this._timer);
        if (this._c && this._t < this.Duration) {
            var moveToPosition = Math.round(this.Tween(this._t++, this._b, this._c, this.Duration));
            this.MoveTo(moveToPosition);
            this._timer = setTimeout(Bind(this, this.Move), this.Time);
        } else {
            this.MoveTo(this._target);
            this.Auto && (this._timer = setTimeout(Bind(this, this.Next), this.Pause));
        }
    },
    MoveTo: function(i) {
        this._slider.style[this._css] = i + "px";
    },
    Next: function() {
        if(this.Index > 0)
        {
            if(this._slider.rows[0].cells[0])
            {
                this._slider.rows[0].appendChild(this._slider.rows[0].cells[0].cloneNode(true));
                this._slider.rows[0].deleteCell(0);
                if(clientBrowser.isFireFox || clientBrowser.isSafari)
                {
                    this._slider.style.left = (parseInt(CurrentStyle(this._slider)[this.options.Vertical ? "top" : "left"]) + Math.abs(this.Change)) + "px";
                }
                else
                {
                    this._slider.style.posLeft = parseInt(CurrentStyle(this._slider)[this.options.Vertical ? "top" : "left"]) + Math.abs(this.Change);
                }
            }
            this.Run(this.Index);
        }
        else
        {
            this.Run(++this.Index);
        }
    },
    Previous: function() {
        this.Run(--this.Index);
    },
    Stop: function() {
        clearTimeout(this._timer); this.MoveTo(this._target);
    }
};

var forEach = function(array, callback, thisObject) {
    if (array.forEach) {
        array.forEach(callback, thisObject);
    } else {
        for (var i = 0, len = array.length; i < len; i++) { callback.call(thisObject, array[i], i, array); }
    }
}


/********************************** Trace Window Control **********************************/
function TraceWindow(left, top)
{
    this.traceWindowId = "divTraceWindow";
    var popTraceWindow = new popUpWindow();
	popTraceWindow.width = "350";
	popTraceWindow.height = "350";
	popTraceWindow.alignCenter = false;
	popTraceWindow.left = left;
	popTraceWindow.top = top;
	popTraceWindow.titleBar.innerHTML = "Trace Window";
	popTraceWindow.allowDrag = true;
	popTraceWindow.bodyContainerType = "content";
	popTraceWindow.bodyContainerTypeValue = "<div id=\"" + this.traceWindowId + "\"></div>";
	popTraceWindow.show();  
}

TraceWindow.prototype.Print = function(content)
{
    var traceWindow = $get(this.traceWindowId);
    if(traceWindow)
    {
        traceWindow.innerHTML += content;
        traceWindow.innerHTML += "<br/>";
    }
}


/********************************** AD Coding Start **********************************/
function LoadTopAds() {
    var url = location.href.toLowerCase();
    var inWhichPage = document.getElementById(gCtlIdPrefix.PageHeader + "GetCityZipForAd");
    if (url.indexOf("/specialtools/") == -1) {
        if (url.indexOf("/agent/") > -1)
            LoadLeaderboardAdsForAgent();
        else {
            if (inWhichPage != null && inWhichPage.value.indexOf("MSR") != -1) {
                var spotName = document.getElementById(gCtlIdPrefix.PageHeader + "adSpotName");
                if (spotName != null)
                    spotName.value = "mapsearch";
            }
            LoadLeaderboardAds(); //default load for Leaderboard_targeted ads.
        }
    }
}

function ControlADs() {
    var pageType = document.getElementById(gCtlIdPrefix.PageHeader + "iptPageType");
    if (pageType != null && pageType.value != "mapsearch") {
        LoadTopAds();

        if (pageType.value == "DPP2")
            LoadLeaderboardAds("Rectangle_DPP_2010_Targeted");
        else
            LoadLeaderboardAds("SkyscraperLeftBar");
    }
}
// Load Bankrate Widget ad in the left nav bar.
function loadBankrate() {
    var adBankrate = document.getElementById("adBankrate");
    if(adBankrate)
    {
        adBankrate.contentWindow.location.replace(GetRelativePath2() + "external/partner/ad-bankrate.html");
    }
}

function LoadLeaderboardAds(adSpotName, ctZipList, pvValue) {
    
    if (pvValue != null) {
        currentDateTime = pvValue;
    }
    if (adSpotName == null) {
        var spotName = document.getElementById(gCtlIdPrefix.PageHeader + "adSpotName");
        if (spotName != null)
            adSpotName = spotName.value;
    }
    if (ctZipList == null) {
        var GetCityZip = document.getElementById(gCtlIdPrefix.PageHeader + "GetCityZipForAd");
        if (GetCityZip == null) {
            GetCityZip = window.top.document.getElementById(gCtlIdPrefix.PageHeader + "GetCityZipForAd");
        }
        if (GetCityZip != null) {
            ctZipList = GetCityZip.value.replace(/MapSearchPage/, "").replace(/ /g, "_");

            var prefix = ctZipList.substr(0, 3);
            if (prefix == "PSR")
                ctZipList = ctZipList.substr(0, 4) + ctZipList.substr(8);

            prefix = ctZipList.substr(0, 5);
            if (prefix == "DPP_A")
                ctZipList = ctZipList.substr(0, 6) + ctZipList.substr(10);

            prefix = ctZipList.substr(0, 6);
            if (prefix == "DPP_NH")
                ctZipList = ctZipList.substr(0, 7) + ctZipList.substr(11);
        }
    }
    if (adSpotName.toLowerCase() == "homepage" || adSpotName.toLowerCase() == "mapsearch") {
        document.getElementById("divLeadboardAd").style.display = "none";
        return;
    }
    else if (document.getElementById("divLeadboardAd") != null)
        document.getElementById("divLeadboardAd").style.display = "block";
    
    var ifmAds = null;
    var ifmWidth = "";
    var ifmHeight = "";
    var hasPV = false;
    var latitude = 0;
    var longitude = 0;
    var zoomlevel = 0;

    var urlpara;
    var pageType = document.getElementById(gCtlIdPrefix.PageHeader + "iptPageType");
    // Get parameter for Advertise.
    if (pageType!=null && (pageType.value == "mapsearch" || pageType.value == "DPP" || pageType.value == "DPP2")) {
        var latitudeForAD = document.getElementById(gCtlIdPrefix.PageHeader + "latitudeForAD");
        if (latitudeForAD != null && latitudeForAD.value != "")
            latitude = latitudeForAD.value;

        var longitudeForAD = document.getElementById(gCtlIdPrefix.PageHeader + "longitudeForAD");
        if (longitudeForAD != null && longitudeForAD.value != "")
            longitude = longitudeForAD.value;

        var zoomLevelForAD = document.getElementById(gCtlIdPrefix.PageHeader + "zoomLevelForAD");
        if (zoomLevelForAD != null && zoomLevelForAD.value != "")
            zoomlevel = zoomLevelForAD.value;
    }

    switch (adSpotName.toLowerCase()) {
        case "skyscraperleftbar":
            ifmAds = document.getElementById("SkyscraperLeftBar");
            ifmWidth = "160px";
            ifmHeight = "600px";
            hasPV = true;
            if (ctZipList.toLowerCase().indexOf("np") > -1 || ctZipList.toLowerCase().indexOf("sdp") > -1)
                adSpotName = "SkyScraper-Neighborhoods_School";
            else
                adSpotName = "Skyscraper_SiteEmbedded_LeftNav";
            break;
        case "rectangle_targeted":
            ifmAds = document.getElementById("IframeRectangle_Targeted");
            ifmWidth = "336px";
            ifmHeight = "280px";
            break;
        case "rectangle_dpp_2010_targeted":
            ifmAds = document.getElementById("ifmRectangleDPP");
            ifmWidth = "303px";
            ifmHeight = "250px";
            hasPV = true;
            break;
        default:
            ifmAds = document.getElementById("leaderboardAds");

            if (adSpotName.toLowerCase() == "leaderboard_dpp_2010_targeted")
                ifmWidth = "728px";
            else
                ifmWidth = "750px";
                
            ifmHeight = "90px";
            hasPV = true;
            if (ctZipList.toLowerCase().indexOf("np") > -1 || ctZipList.toLowerCase().indexOf("sdp") > -1)
                adSpotName = "Leaderboard-Neighborhood_School";
            break;
    }
    if (ifmAds != null) {
        ifmAds.style.width = ifmWidth;
        ifmAds.style.height = ifmHeight;
        var pvParam = "";
        if (hasPV == true)
            pvParam = "&pv=" + currentDateTime;

        if (pageType.value == "mapsearch" || pageType.value == "DPP" || pageType.value == "DPP2")
            urlpara = GetRelativePath2() + "LeaderboardAd.aspx?adSpotName=" + adSpotName + pvParam + "&cityZipList=" + ctZipList + "&lat=" + latitude + "&long=" + longitude + "&zoom=" + zoomlevel;
        else
            urlpara = GetRelativePath2() + "LeaderboardAd.aspx?adSpotName=" + adSpotName + pvParam + "&cityZipList=" + ctZipList;

        ifmAds.contentWindow.location.replace(urlpara);
    }
}

function ReloadADS() {
    //re-load leaderboard ads and left nav ads for the search changed.
    //Also refresh PV parameter's value. 
    var dateNew = new Date();
    //for pv parameter in ads code.
    var pvValue = dateNew.getFullYear().toString() + dateNew.getMonth().toString() + dateNew.getDate().toString()
    + dateNew.getHours().toString() + dateNew.getMinutes().toString() + dateNew.getSeconds().toString()
    + dateNew.getMilliseconds().toString();

    LoadLeaderboardAds("Leaderboard_Targeted", null, pvValue);
    LoadLeaderboardAds("SkyscraperLeftBar", null, pvValue);
}

/********************************** AD Coding End **********************************/

// 5443, Support price range tracking in Analytics.
function GetCityZipListWithPriceRange(maxPrice, minPrice) {

    var range = "";
    var price = 0;
    
    if (maxPrice > 0)
        price = maxPrice;
    else if (minPrice > 0)
        price = minPrice;

    if (price == 0)
        range = "P01";
    else if (price > 2000000)
        range = "P31";
    else {
        var step = 0;
        var remainder = 0;
        
        if (price > 0 && price <= 1000000) {
            step = price / 50000;
            remainder = price % 50000;
        }

        if (price >= 1000001 && price <= 2000000) {
            step = price / 100000 + 10;
            remainder = price % 100000;
        }

        step = parseInt(step);

        if (remainder > 0)
            step += 1;

        if (step < 10)
            range = "P0" + step;
        else
            range = "P" + step;
    }

    return range;
}
