﻿
var _trace ="";

var isDev = (document.domain.indexOf("localhost")>-1)||(document.domain.indexOf("edmyersxp")>-1)
if (document.domain.indexOf("centris.ca")>-1) document.domain="centris.ca";


//  Capture any JS errors that occur and try to log them.
function LogError(message, url, line) 
{
		onerror=null; // Keep from an endless loop:

		var msg = message + '\n' + url + "::" + line;    
		if (isDev) alert('JS: ' + msg );
	 
		// Send Entry to error log. (If error occurs on page load MyAjaxService might not be available
		// ToggleDisplay capture this we need different approach
		msg +=  "\n" + window.navigator.userAgent + "\n" + _trace;
		if ((!isDev) && url.indexOf("gooogle-analytics.com") > -1) return false; // Don't log errors caused by a trogan that changes www.google-analytics to gooogle-analytics
		if ((!isDev) && url.indexOf("ecn.dev.virtualearth.net/mapcontrol") > -1) return false; // Don't log these errors
		if ((!isDev) && url.indexOf("dev.virtualearth.net/services/") > -1) return false; // Don't log these errors
		if ((!isDev) && url.indexOf("dev.virtualearth.net/webservices/") > -1) return false; // Don't log these errors
		if ((!isDev) && (line == 0) && (message == "Script error.") && (url.length == 0)) return false; // Don't log these empty generic "Script error." messages
		if ((!isDev) && (message.indexOf("'console'") > -1)) return false; // Don't log this junk
		if ((!isDev) && (message.indexOf("cloudfront.net") > -1)) return false; // Don't log this junk
		if ((!isDev) && (message.indexOf("(NS_ERROR_") > -1)) return false; // Don't log this junk

		try 
		{
			var oVisitorID =  document.getElementById("hEncryptedVisitorID")
			var oVersion = document.getElementById("hSiteVersion")
			if (oVersion) msg = msg + " [Ver=" + oVersion.value + "]";
			if (oVisitorID) MyAjaxService.LogJSErrorEx("JS Error: " + msg, oVisitorID.value);
			else MyAjaxService.LogJSError("JS Error: " + msg +  " (No VisitorID)");
			// Record version number to explain errors caused by old offline or cached versions of the aspx code 
				
		} catch (e) {return true;} // since we can't log error, allow browser to show it
		return false;
		
}
if (!isDev) onerror=LogError;

function bmi_load() { }


function Protocol() {
	ohSSL = document.getElementById("hSSL");
	if (!ohSSL) return "http://"
	if (ohSSL.value.toUpperCase() == "Y") return "https://";
	return "http://";
}

function GoogleAnalytics(Tag)
{
	// wait until the page loads and all the other initialization occur before 
	// wasting resources on Google.
	setTimeout("GoogleAnalyticsDoIt('" + Tag + "')",5000);
}

function GoogleAnalyticsDoIt(Tag) {
	try {
		var pageTracker = _gat._getTracker($get("hGoogleAnalyticsKey").value);
		pageTracker._initData();
		var PageName = document.location.href.replace(document.domain, "");
		PageName = PageName.replace("http://", "").replace("https://", "");
		if (Tag) PageName += "/" + Tag
		pageTracker._trackPageview(PageName);
	} catch (e) {
	if (isDev) window.status = "## GoogleAnalytics Failed-->" + e.toString();
		//alert("GoogleAnalytics Failed: \n" + document.location.href + '\n' + e.toString());
	}

}

function $getvar(name) {
	try {
		return eval(name)
	} catch (e) { }
	return ""
}

function $getval(name)
{
	var oFld = $get(name);
	if (!oFld) return "";
	else return oFld.value;
}
function $setval(name,value)
{
	var oFld = $get(name);
	if (!oFld) return "";
	oFld.value = value;
}
function $getint(name)
{
	var oFld = $get(name);
	if (!oFld) return "";
	return MakeInt(oFld.value);
	
}
function $getfloat(name)
{
	var oFld = $get(name);
	if (!oFld) return "";
	return MakeFloat(oFld.value);
}
function $setstyle(name,parm,val)
{
	var oFld = $get(name);
	if (!oFld) return;
	if(oFld.style) oFld.style[parm]= val; 
	
}


function isFrameReady(Function)
{
// Test if a child frame has loaded and is ready to execute a function 
// try Catch needed for Firefox 2.6 and the centris domain because until the page loads and sets the document.domain 
// they are in different domains which causes a cross-brower permission error
// e.g. isFrameReady("ContentFrame.DataClear") 
	try
	{		
		if (eval(Function)) return true;
		return false;
	} catch(e) {
		//alert(e.toString());
	}
	return false;
}

function RedirectToHomePage(bAfterLogout)
{
	// ... Redirecting to home page
	var Site = $get("hSiteCode").value;
	var URL="";
	switch(Site)
	{
		case "INR": URL="HomePageMibor.aspx"; break;
		default: URL="HomePage" + Site + ".aspx"; break;
	}
	URL = FullURL(URL);
	if (bAfterLogout) URL = URL.replace("vidx=","vidxremoved="); // prevent auto login
	document.location.href=URL;
}



function Translate(English,French)
{
	var  oCtrl = $get("hLanguageCode");
	var isFrench = false;
	if (oCtrl && (oCtrl.value.length>1)) isFrench = "fr"==oCtrl.value.substring(0,2);
	else 
	{
		if ((document.domain.indexOf("localhost")>-1) || (document.domain.indexOf("edmyersxp")>-1))	alert("Missing hLanguageCode");
	}
	return (isFrench)? French : English;
}


function FixNoCookieLinks()
{
	for (var i=0; i<document.links.length; i++)
	{
		var oLink = document.links[i]
		oLink.href = CreateNoCookieURL(oLink.href);
	}
}

function CreateNoCookieURL(URL)
{
	ohSSL = document.getElementById("hSSL");
	if (ohSSL && (ohSSL.value.toUpperCase() == "Y")) URL += ((-1 == URL.indexOf("?")) ? "?" : "&") + "ssl=y";
	if (document.cookie.indexOf("VisitorID")>-1) return URL; // Have cookies, no need to pass visitorid
	if (URL.toLowerCase().indexOf("javascript:")>-1) return URL; // Local function needs to do the FixNoCookie
	if (URL.toLowerCase().indexOf(".html")>-1) return URL; // Loading.html does not need the cookie
	URL += (-1==URL.indexOf("?")) ? "?" : "&";
	var ohEncrypted = document.getElementById("hEncryptedVisitorID");
	if (ohEncrypted) URL += "vidx=" + ohEncrypted.value;
	var ohTS = document.getElementById("hTS");
	if (ohTS) URL += "&t=" + document.getElementById("hTS").value; // ExpireDate
	return URL;
}

function GetScreenHeight()
{
	if (window.innerHeight) return parseInt(window.innerHeight,10); // Netscape
	if (document.documentElement && document.documentElement.clientHeight) return parseInt(document.documentElement.clientHeight,10);
	if (document.body) return parseInt(document.body.clientHeight,10);
	return 500;
}

function toProperCase(str) {
		return str.replace(/\w\S*/g, function(txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); });
}

function GoToHomePage(Site){
	
	var url= "HomePage" + Site + ".aspx"; 
	if (Site=="") url = "index.aspx"
	if (Site=="Demo") url = "HomePage.aspx"; 
	document.location.href=FullURL(url);
}

function GetScreenWidth()
{
	if (window.innerWidth) return parseInt(window.innerWidth,10); // Netscape
	if (document.documentElement && document.documentElement.clientWidth) return parseInt(document.documentElement.clientWidth,10);
	if (document.body) return parseInt(document.body.clientWidth,10)-5;
	return 500;
}

//  Display any errors that occur
function FailedCallback(error, userContext, methodName) {
	//stop here and get error before it proceeds and loses orig message
		
		var message = error.get_message() + '\n' + document.location.href + "::" + methodName + 
		'\nContext:' + userContext + "\n" + window.navigator.userAgent + "\n" + _trace;

		var oVersion = document.getElementById("hSiteVersion")
		if (oVersion) message = "[Ver=" + oVersion.value + "] " + message;
		
		
		if (isDev) 
		{
			alert('Failed Callback: ' + message);
			return;			
		}

		if (userContext == null) return; // Skip this, likely caused by switching pages in the middle of a call.

		// Send Entry to error log.
		var oVisitorID =  document.getElementById("hEncryptedVisitorID")
		if (oVisitorID) MyAjaxService.LogJSErrorEx("Failed Callback: " + message, oVisitorID.value);	
		else	MyAjaxService.LogJSErrorEx("Failed Callback: " + message + " (No VisitorId)" );		
		
}		
function DoNothing() {}


function ShapeInfo(Data){
	var Info =(Data+",,,").split(",");
	this.PropNum = parseInt(Info[0],10);
	this.Source = Info[1];
	this.SysID = parseInt(Info[2]);
	// if PropNum is empty then the data values are Lat Lon 
	this.Lat = parseFloat(Info[1]);
	this.Lon = parseFloat(Info[2]);
	// If PropNum is -1 then the data is Source,SysID,Address,Zipcode,Lat,Lon
	this.Address = Info[3];
	this.Zipcode = Info[4];
	if (this.PropNum == -1) {
		this.Lat = parseFloat(Info[5]);
		this.Lon = parseFloat(Info[6]);
	}
	
}

function PropInfo(PropData,Num){
	var Prop = (PropData[Num]+"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n").split("\n");
	this.Lat = parseFloat(Prop[0]);
	this.Lon = parseFloat(Prop[1]);
	this.Source = Prop[2];	
	this.SysID = Prop[3]; 
	this.PhotoURL = GetPhotoPath(Prop[4]);
	this.Address = Prop[5];
	this.LP = Prop[6];
	this.MLNum = Prop[7];
	this.Beds = Prop[8];
	this.Bath = Prop[9];
	this.SqFt = Prop[10];
	this.Lot =  Prop[11];
	this.YrBuilt = Prop[12];
	this.PriceK = Prop[13];	
	this.BathsFull = Prop[14];	
	this.BathsPartial = Prop[15];	
	this.GarageSpaces = Prop[16];	
	this.HOAFeeMo = Prop[17];	
	this.TaxesMo = Prop[18];	
	this.AssessedValue = Prop[19];	
	this.CDOM = Prop[20];	
	this.PropTypeDesc = Prop[21];
	this.Pool = Prop[22];
	this.City = Prop[23];
	this.Zipcode = Prop[24];
	this.County = Prop[25];
	this.Neighborhood = Prop[26];
	this.ElemSchool = Prop[27];
	this.MiddleSchool = Prop[28];
	this.HighSchool = Prop[29];
	this.Feature1 = Prop[30];
	this.Feature2 = Prop[31];
	this.Feature3 = Prop[32];
	this.Feature4 = Prop[33];
	this.Feature5 = Prop[34];
	this.Feature6 = Prop[35];
	this.Feature7 = Prop[36];
	this.Feature8 = Prop[37];
	this.Feature9 = Prop[38];
	this.Feature10 = Prop[39];
	this.Feature11 = Prop[40];
	this.Feature12 = Prop[41];
	this.Feature13 = Prop[42];
	this.Feature14 = Prop[43];
	this.Feature15 = Prop[44];
	this.Feature16 = Prop[45];
	this.Feature17 = Prop[46];
	this.Feature18 = Prop[47];
	this.Feature19 = Prop[48];
	this.Feature20 = Prop[49];
	this.Feature21 = Prop[50];
	this.Feature22 = Prop[51];
	this.Feature23 = Prop[52];
	this.Feature24 = Prop[53];
	this.Feature25 = Prop[54];
	this.Feature26 = Prop[55];
	this.Feature27 = Prop[56];
	this.Feature28 = Prop[57];
	this.Feature29 = Prop[58];
	this.Feature30 = Prop[59];
	this.Feature31 = Prop[60];
	this.Search1 = Prop[61];
	this.Search2 = Prop[62];
	this.Search3 = Prop[63];
	this.Search4 = Prop[64];
	this.Search5 = Prop[65];
	this.Search6 = Prop[66];
	this.Search7 = Prop[67];
	this.Search8 = Prop[68];
	this.BrokerName = Prop[69];
	this.FavID = MakeInt(Prop[70]);
	this.OpenHouse = Prop[71];
	this.SoldDate = Prop[72];
	this.ListDate = Prop[73];
	this.RentPrice = Prop[74];
	this.PriceSF = Prop[75];
	this.DisplaySource = Prop[76];
	this.Status = Prop[77];
	this.SoldPrice = Prop[78];
	this.ListPriceLow = Prop[79];

	
	this.isValid= (!isNaN(this.Lat)) && (!isNaN(this.Lon)); // bad lat/long values (probably empty)
	this.Desc = this.Address + " (" + this.PriceK ;
	if (this.RentPrice.length>0) this.Desc += ";" + this.RentPrice;
	this.Desc += ")";

	this.isAggregate = "AGGREGATE"==this.Source;
	this.Area = Prop[5];
	this.Qty = (Prop[3]>999)? (parseInt(Prop[3]/1000)+"K") : Prop[3];	

	this.Baths = "";
	var fBaths = MakeInt(this.BathsFull,10);
	var hBaths = MakeInt(this.BathsPartial,10);
	if (isNaN(fBaths)&& isNaN(hBaths)) this.Baths="";
	else if (isNaN(fBaths)) this.Baths=this.BathsPartial; 
		else if (isNaN(hBaths)) this.Baths = this.BathsFull;
		else this.Baths = (hBaths + fBaths) + "";

}

function PropInfoShort2(Num){
	var Prop = (PropListData[Num]+"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n").split("\n");
	this.Lat = parseFloat(Prop[0]);
	this.Lon = parseFloat(Prop[1]);
	this.Source = Prop[2];
	this.SysID = Prop[3];
	this.PhotoURL = GetPhotoPath(Prop[4]);
	this.Address = Prop[5];
	this.LP = Prop[6];
	//this.MLNum = Prop[7];
	this.Beds = Prop[8];
	this.Bath = Prop[9];
	this.SqFt = Prop[10];
	this.Lot =  Prop[11];
	this.YrBuilt = Prop[12];
	this.isValid= (!isNaN(this.Lat)) && (!isNaN(this.Lon)) // bad lat/long values (probably empty)
} 

function PropInfoShort(Data,Num){
	var Prop = (Data[Num]+"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n").split("\n");
	this.Lat = parseFloat(Prop[0]);
	this.Lon = parseFloat(Prop[1]);
	this.Source = Prop[2];
	this.SysID = Prop[3];
	this.PhotoURL = GetPhotoPath(Prop[4]);
	this.Address = Prop[5];
	this.LP = Prop[6];
	//this.MLNum = Prop[7];
	this.Beds = Prop[8];
	this.Bath = Prop[9];
	this.SqFt = Prop[10];
	this.Lot =  Prop[11];
	this.YrBuilt = Prop[12];
	this.PriceK = Prop[13];	
	this.PropTypeDesc = Prop[21];
	this.Zipcode = Prop[24];
	this.OpenHouse = Prop[71];
	this.SoldDate = Prop[72];
	this.RentPrice = Prop[74];
	this.DisplaySource = Prop[76];
	this.Status = Prop[77];
	this.isValid= (!isNaN(this.Lat)) && (!isNaN(this.Lon)) // bad lat/long values (probably empty)
	this.Desc = this.Address + " (" + this.LP 
	if (this.RentPrice.length>0) this.Desc += ";" + this.RentPrice;
	this.Desc += ")"
	
	if (this.Source=="FCIQ") 
	{
		this.Desc = this.Address + "</a>"
		var isFrench = false;
		var oLng = $get("hLanguageCode")
		if (oLng) isFrench = oLng.value.indexOf("fr")>-1;
		if (isFrench) this.Desc+=Glue("<br>",Prop[30],"")+Glue("<br>",Prop[32],"");
		else this.Desc +=Glue("<br>",Prop[31],"")+Glue("<br>",Prop[33],"");		
		this.Desc += "<a>"
	}
	
	this.isAggregate = "AGGREGATE"==this.Source;
	this.Area = Prop[5];
	this.Qty = (Prop[3]>999)? (parseInt(Prop[3]/1000)+"K") : Prop[3];	
		
} 	
function PropInfoValueYourHome(Num){
	var Prop = (PropMapData[Num]+"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n").split("\n");
	this.Lat = parseFloat(Prop[0]);
	this.Lon = parseFloat(Prop[1]);
	this.Source = Prop[2];
	this.SysID = Prop[3];
	this.PropType = Prop[4];
	this.PropStatus = Prop[5];
	this.ClosedDate = Prop[6];
	this.PhotoURL = GetPhotoPath(Prop[7]);
	this.Address = Prop[8];
	this.Price = Prop[9];
	this.MLNum = Prop[10];
	this.Beds = MakeInt(Prop[11]);
	this.BathsFull = MakeInt(Prop[12]);
	this.BathsPartial = MakeInt(Prop[13]);
	this.SqFt = MakeInt(Prop[14]);
	this.YrBuilt = Prop[15];
	this.DOM = MakeInt(Prop[16]);
	this.PriceK = Prop[17];	
	this.LP = MakeInt(Prop[18]);	

	this.isValid= (!isNaN(this.Lat)) && (!isNaN(this.Lon)) // bad lat/long values (probably empty)
	this.Desc = this.Address + " (" + this.PriceK + ")"

	this.isAggregate = "AGGREGATE"==this.Source;
	this.Area = Prop[8];
	this.Qty = (Prop[3]>999)? (parseInt(Prop[3]/1000)+"K") : Prop[3];	
}

function MemberInfo(DataMap,Num){
	var Data = (DataMap[Num]+"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n").split("\n");
	this.Lat = parseFloat(Data[0]);
	this.Lon = parseFloat(Data[1]);
	this.Source = Data[2];
	this.SysOfficeID = Data[3];
	this.SysUserID = Data[4];
	//this.OfficeCode = Data[5];
	this.AgentFirstName = Data[6];
	this.AgentLastName = Data[7];
	this.AgentName = Data[8];
	this.OfficeName = Data[9];
	this.Address1 = Data[10];
	//this.Address2 = Data[11];
	//this.Address3 = Data[12];
	//this.City = Data[13];
	//this.State = Data[14];
	this.Zipcode = Data[15];
	this.Phone = Data[16];
	//this.FaxPhone = Data[17];	
	this.URL = Data[18];	
	this.EmailAddress = Data[19];	
	this.Photo = "";
	if (0 < Data[20].length) this.Photo = "http://" + Data[20];
	this.TagLine = Data[21]; 
	
	this.isValid = (!isNaN(this.Lat)) && (!isNaN(this.Lon)); // bad lat/long values (probably empty)
} 	



function ToggleDisplay(CtrlID){
	var oCtrl = $get(CtrlID)
	if (oCtrl) oCtrl.style.display = (oCtrl.style.display=="block") ? "none" :  "block"
}


function GetPhotoPath(URL){
	if (0<URL.length) return URL;
	return FullURL("Icons/NoPhoto_147.jpg").replace("http://","").replace("https://","");
	//var Path = location.pathname
	//Path = Path.substring(0,Path.lastIndexOf("/"))
	//return location.host + Path + "/../Icons/NoPhoto_147.jpg" 
}

function Expand(evt,id){
	// Browser independent
	var oTbl = $get(id+"Detail");
	var oImg = $get(id+"Image");
	var myEvent = null;
	var oTR = $get(id);
	
	if (window.event) {
		myEvent = window.event; 
	} else {
		myEvent = evt; 
	} 
		
	switch (myEvent.type){
		case "mouseover": oTR.style.color = "Navy";	oTR.style.fontWeight="bold"; break;
		case "mouseout": oTR.style.color = "black";		oTR.style.fontWeight="normal"; break;
		case "click": var Open = oImg.src.indexOf("_Up")>0;
				if (Open){ // close
					oImg.src = oImg.src.replace("_Up","_Dn"); 
					oTbl.style.display = "none";
				
				} else { // open
					oImg.src = oImg.src.replace("_Dn","_Up"); 
					oTbl.style.display = "";
					oTbl.scrollIntoView(false);
				}
				break;
				
		default: alert("Missing EventType Arg to Expand: " + myEvent.type);
	}
}


function Tab(evt){
	// Browser independent
	var oImg = null;
	var myEvent = null;
	
	if (window.event) {
		myEvent = window.event; 
		oImg = myEvent.srcElement;
	} else {
		myEvent = evt; 
		oImg = evt.target; 
	} 

	if (!oImg) return;
	if(!oImg.src) return;
	var src = oImg.src;
	switch (myEvent.type){
		case "mouseover": src = src.replace("-default","-over"); break;
		case "mouseout": src = src.replace("-over","-default"); src=src.replace("-down","-default"); break;
		case "mousedown": src = src.replace("-default","-down"); src=src.replace("-over","-down");break;
		default: alert("Missing EventType Arg to Tab: " + myEvent.type);
	}
	oImg.src=src;
}


// for Netscape 6/Mozilla by Thor Larholm me@jscript.dk
if(typeof HTMLElement!="undefined" && !HTMLElement.prototype.insertAdjacentElement)
{
	HTMLElement.prototype.insertAdjacentElement = function(where,parsedNode)
	{
		switch (where){
		case 'beforeBegin':
			this.parentNode.insertBefore(parsedNode,this)
			break;
		case 'afterBegin':
			this.insertBefore(parsedNode,this.firstChild);
			break;
		case 'beforeEnd':
			this.appendChild(parsedNode);
			break;
		case 'afterEnd':
			if (this.nextSibling) this.parentNode.insertBefore(parsedNode,this.nextSibling);
			else this.parentNode.appendChild(parsedNode);
			break;
		}
	}

	HTMLElement.prototype.insertAdjacentHTML = function(where,htmlStr)
	{
		var r = this.ownerDocument.createRange();
		r.setStartBefore(this);
		var parsedHTML = r.createContextualFragment(htmlStr);
		this.insertAdjacentElement(where,parsedHTML)
	}


	HTMLElement.prototype.insertAdjacentText = function(where,txtStr)
	{
		var parsedText = document.createTextNode(txtStr)
		this.insertAdjacentElement(where,parsedText)
	}
	
}

if (!document.all) {
	HTMLElement.prototype.__defineGetter__("innerText", 
							function () { return(this.textContent); });
	HTMLElement.prototype.__defineSetter__("innerText", 
							function (txt) { this.textContent = txt; });
}



function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function deleteCookie(name)
{
	document.cookie = name + '=; expires=Thu, 01-Jan-90 00:00:01 GMT;';
}

function MakeInt(Val){
	Val = (Val+"").replace("$","").replace(/,/g,"");
	var iVal = parseInt(Val,10)
	if(isNaN(iVal)) return 0;
	return Math.min(2147483646,iVal); // already a number
}

function MakeSmallInt(Val){
	return Math.min(32766,MakeInt(Val)); 
}

function MakeTinyInt(Val){
	return Math.min(127,MakeInt(Val)); 
}

function MakeFloat(Val){
	var fVal = parseFloat(Val);
	if (isNaN(fVal)) return 0.0;
	return fVal;
}

function CommaFmt(Num) {
	// Add commas to large numbers
	var Result = "";
	//remove any existing commas from Num so we don't duplicate commas
	Num = Num.toString().replace(/,/g, "")
	var IX=Num.indexOf('.',0);
	if (IX<0) {
	IX=Num.length
	} else {
	Num=Num+"00"	
	}	
	if ((Num.length-IX)>3) Num=Num.substring(0,IX+3) // only 2 decimal places past .
	if (IX<=4) return Num; // too short for commas
	Result=Num.substring(IX,Num.length)
	Num=Num.substring(0,IX)
	while (Num.length > 3) {
		Result = "," + Num.substring(Num.length-3,Num.length)+ Result;
		Num = Num.substring(0,Num.length-3)
	}
	Result = Num + Result;
	return Result;
}

function GetWatermarkFldValue(FldName)
{
	var oFld = $get(FldName)
	return (oFld.value!=GetAttr(oFld, "title",""))? oFld.value : "";
}

function Watermark(evt){
	// Browser independent
	var oCtrl = null;
	var myEvent = null;
	
	if (window.event) {
		myEvent = window.event; 
		oCtrl = myEvent.srcElement;
	} else {
		myEvent = evt; 
		oCtrl = evt.target; 
	} 

	switch (myEvent.type){
		case "blur":
			var Val = oCtrl.value.replace(/ /gi,"");
			if (Val.length==0) {
				oCtrl.value=oCtrl.title;
				oCtrl.style.color="gray";
			} 
			break;
			
		case "focus":
			if ((!oCtrl.title) || (oCtrl.title==oCtrl.value)) {
				oCtrl.title=oCtrl.value; // Save the watermark
				oCtrl.value="";
				oCtrl.style.color = "black";
			}
			break;
		
		case "load":
				oCtrl.value=oCtrl.title;
				oCtrl.style.color="gray";
				
		default: 
		alert("No Watermark Handler: " + myEvent.type);
		myEvent.cancelBubble = true;
		break;
	}
	

}

function Glue(a, Data, b){
	if (!Data) return "";
	if (0==Data.length) return ""
	return a + Data + b;
}

function GlueNum(a, Data, b){
	if (!Data) return "";
	if (isNaN(Data)) return ""
	if (0==Data) return ""
	if (999999999==Data) return "";
	return a + Data + b;

}

// For sorting arrays in numeric order e.g. Arrray.sort[numOrdA]
function numOrdA(a, b){ return (a-b); }


function SetCriteria(Field,Value){
	// make the correct radio button checked
	var oCtrl = document.forms[0][Field]
	var oCtrlY = document.forms[0][Field+"Y"]
	var oCtrlN = document.forms[0][Field+"N"]
	if (oCtrlY) oCtrl = oCtrlY
	if (!oCtrl) return;

	switch (""+oCtrl.type){
	case "select-one": 
		for(var i=0;i<oCtrl.length;i++){
			if (oCtrl[i].value!=Value) continue;
				oCtrl.selectedIndex = i;
				return;
			}
			// If not found maybe because this is a dynamic dropdown
			if (oCtrl.options.length>1)
			{
			oCtrl.selectedIndex = 1;
			oCtrl[1].value=Value;
			oCtrl[1].text=Value;
			}
			break;

	case "select-multiple":
		var Values=Value.split(",");
		var isNoneSelected = true;
		for(var i=0;i<oCtrl.length;i++){
			var isFound = false;
			for(var j=0;j<Values.length;j++){
				if ((oCtrl[i].value.length>0)&&(oCtrl[i].value==Values[j])) 
				{
					isFound=true;				
					isNoneSelected=false;
				}
			}
			oCtrl[i].selected = isFound;
		}
		if (oCtrl[0].value.length==0) oCtrl[0].selected = isNoneSelected; // Select "All Areas" if nothing is selected
		break;
		
	
	case "radio":
			for (var i=0;  i<oCtrl.length; i++){
				if (oCtrl[i].value==Value) {
					oCtrl[i].checked=true;	
					CriteriaChange(oCtrl[i]);			
				}
			}

		case "checkbox":
			if (oCtrl) oCtrl.checked = (Value != "")
			if (oCtrlN) oCtrlN.checked = oCtrlN.value == Value;
			if (oCtrlY) oCtrlY.checked = oCtrlY.value == Value;

			if (oCtrlY || oCtrlN) break;

			// If Multiple selection checkboxes
			var oCtrls = document.forms[0].elements[Field];
			if (!oCtrls) break;

			//if (Values.length > 0) oCtrl.checked = false;
			//alert("Multi:" + oCtrls.length + ", " + oCtrls.id + ":" + Value + "=" + oCtrls.value + " - " + (("," + Value).indexOf("," + oCtrls.value) > -1));
			oCtrls.checked = ("," + Value).indexOf("," + oCtrls.value) > -1
			break;	
	
	case "text": 
		if ((Value=="") || (Value=="0") || (Value=="999999999"))
		{
		 oCtrl.value = oCtrl.title;
		 oCtrl.style.color = "gray";
		}
		else 
		{
			oCtrl.style.color = "black";
			oCtrl.value=Value;
			var Fmt = ""+oCtrl.getAttribute("fmt");
			if ((0<parseInt(Value)) && (Fmt.indexOf(",")>-1))	oCtrl.value = CommaFmt(Value);
		}
		break;

	case "undefined":
		for (var i = 0; i < oCtrl.length; i++) {
			SetCriteria(oCtrl[i].id, Value); // Multi-checkbox case
		}
		break;
	
	default: alert("Missing SetCriteria Handler for Field=" + Field + "; " + oCtrl.type); break;
	}
	
}

function TRIM(Str)
{
	if (null==Str) return "";
	return Str.replace(/^\s+|\s+$/g, '');
}


function GetAttr(Obj, Field, DefVal){
	if (!Obj) return DefVal;
	if (!Obj.getAttribute) return DefVal;
	var Val = Obj.getAttribute(Field);
	if (!isFinite(DefVal)) return parseInt(Val,10);
	Val = parseInt(Val,10);
	if (isNaN(Val)) return DefVal;
	return Val;
}

function GetAttrStr(Obj, Field, DefVal){
	if (!Obj) return DefVal;
	if (!Obj.getAttribute) return DefVal;
	var Val = Obj.getAttribute(Field);
	if (!Val) return DefVal;
	if (0<Val.length) return Val;
	return DefVal;
}

function RememberChanges(oFld,FldName)
{
	if (!oFld) return;
	MyAjaxService.RememberSetting(FldName,oFld.value,$getval("hEncryptedVisitorID"))		
}

function FullURL(URL){
// Expand relative URL to a full URL
	if (document.location.href.toLowerCase().indexOf("proto")>0) URL = "Proto/" + URL;
	var domain = document.domain.toLowerCase();
	if (document.location.href.indexOf("search.centris.ca")>-1) domain = "search.centris.ca";
	if (document.location.href.indexOf("betasearch.centris.ca")>-1) domain = "betasearch.centris.ca";
	if (document.location.href.indexOf("testsearch.centris.ca")>-1) domain = "testsearch.centris.ca";
	if (document.location.href.indexOf("stagesearch.centris.ca")>-1) domain = "stagesearch.centris.ca";

	var http = document.location.protocol // might be http: or https:

	if (URL.indexOf("vidx")>0){
			URL = http + "//" + domain + "/" + URL;
		} else {
			URL = CreateNoCookieURL(http + "//" + domain + "/" + URL);
		}
	return (URL);
}

function WatchForCR(evt){
	// onKeydown event handler to make CR=keypress
	var event = (window.event)? window.event : evt;
	var oCtrl = (window.event)? window.event.srcElement : evt.target;
	var isShift = event.shiftKey;
	var kCode = event.which || event.keyCode;
	if (kCode!=13) return true;
	
	var code=oCtrl.getAttribute("onenter");
	if (!code) return true;
	try {eval(code)} catch (e) {}
	return false;  //  CR
}

function NumbersOnly(evt){
	// onKeydown event handler to accept only numbers and make CR = tab
	var event = (window.event)? window.event : evt;
	var oCtrl = (window.event)? window.event.srcElement : evt.target;
	var isShift = event.shiftKey;
	var kCode = event.which || event.keyCode;
	if ((kCode>=48) && (kCode <58))  return true;
	if ((kCode>=96) && (kCode <106)) return true;
	if(kCode==8) return true;
	if(kCode==9) return true;
	if(kCode==46) return true; //Delete 
	if (kCode!=13) return false;
	return false;
}

var LastKeycode = "";
function Lookup(evt){
	// Browser independent
	var event = (window.event)? window.event : evt;
	var oCtrl = (window.event)? window.event.srcElement : evt.target;
	var isShift = event.shiftKey;
	var kCode = event.which || event.keyCode;
	
	//var text = oCtrl.options[oCtrl.selectedIndex].text + String.fromCharCode(kCode);
	var WatermarkText = oCtrl.title;
	var Entry = oCtrl.options[0].text.replace(WatermarkText,""); 
	
	if(kCode==27) alert(LastKeycode);
	LastKeycode = kCode;

	switch (kCode)
	{
	case 8: Entry = Entry.substring(0,Math.max(0,Entry.length-1)); break; // BS
	
	case 13: var code=oCtrl.getAttribute("onenter");
		eval(code);
		return true;  //  CR

	
	case 9:  // Tab
	case 16: 
	case 33: // PgUp
	case 34: // PgDn
	case 35: //End
	case 36: // Home
	case 37: // Left 
	case 38: 
	case 39:  // Right
	case 40: 
	case 45: // Insert
	case 46: // Delete
	
	case 106: // Big *
	case 107: // Big +
	case 109: // Big -
	case 110: // Del - .
	case 111: // Big /
	case 112: // F1
	case 113: // F2
	case 114: // F3
	case 115: // F4
	case 116: // F5
	case 117: // F6
	case 118: // F7
	case 119: // F8
	case 120: // F9
	case 121: // F10
	case 122: // F11
	case 123: // F12	
	case 144: // NumLock
		return true; // Key is ignored
	
	
	case 96: kCode=48; break; // Insert - 0
	case 97: kCode=49; break; // End - 1
	case 98: kCode=50; break; // Dn - 2
	case 99: kCode=51; break; //PgDn - 3
	case 100: kCode=52; break; // Left - 4
	case 101: kCode=53; break; // Center - 5
	case 102: kCode=54; break; // Right - 6
	case 103: kCode=55; break; // Home - 7
	case 104: kCode=56; break; // Up - 8
	case 105: kCode=57; break; // PgUp - 9

	case 48: if (event.shiftKey) kCode = 41; break;  // 0 or )
	case 49: if (event.shiftKey) kCode = 33; break;  // 1 or !
	case 50: if (event.shiftKey) kCode = 64; break;  // 2 or @
	case 51: if (event.shiftKey) kCode = 35; break;  // 3 or #
	case 52: if (event.shiftKey) kCode = 36; break;  // 4 or $
	case 53: if (event.shiftKey) kCode = 37; break;  // 5 or %
	case 54: if (event.shiftKey) kCode = 94; break;  // 6 or ^
	case 55: if (event.shiftKey) kCode = 38; break;  // 7 or &
	case 56: if (event.shiftKey) kCode = 42; break;  // 8 or *
	case 57: if (event.shiftKey) kCode = 40; break;  // 9 or (
	case 186: if (event.shiftKey) kCode = 58; else kCode=59; break; // ; :
	case 187: if (event.shiftKey) kCode = 43; else kCode=61; break; // = +
	case 188: if (event.shiftKey) kCode = 60; else kCode=44; break; // , <
	case 189: if (event.shiftKey) kCode = 95; else kCode=45; break; // - _
	case 190: if (event.shiftKey) kCode = 62; else kCode=46; break; // . >
	case 191: if (event.shiftKey) kCode = 63; else kCode=47; break; // / ?
	case 192: if (event.shiftKey) kCode = 126; else kCode=96; break; // ` ~
	case 219: if (event.shiftKey) kCode = 123; else kCode=91; break; // [ {
	case 220: if (event.shiftKey) kCode = 124; else kCode=92; break; // \ |
	case 221: if (event.shiftKey) kCode = 125; else kCode=93; break; // ] }
	case 222: if (event.shiftKey) kCode = 34; else kCode=39; break; // ] }
	
	 
	default: 
		if ((kCode>64) && (kCode<91) && (!event.shiftKey)) kCode +=32 //lc letters
	}
	if (kCode>31) Entry += String.fromCharCode(kCode); 	
	//LastKeyCode = kCode;
	oCtrl.options[0].text  = Entry;
	oCtrl.options[0].value  = Entry;
	oCtrl.options[0].selected = true; 

	event.cancelBubble = true;  
	if (event.returnValue) event.returnValue = false;  
	if (event.stopPropagation) event.stopPropagation();
	var fields = oCtrl.getAttribute("fields")
	MyAjaxService.Lookup(25, oCtrl.id, fields, Entry, LookupCallback, FailedCallback)
	return false
}

function LookupCallback(List)
{
	if(List.length==0) return;
	var oCtrl = $get(List[0]);
	for (var i=1; i<oCtrl.options.length; i++)
	{
		var Item;
		if (List.length>i)	Item = List[i];
		else Item = ""
		oCtrl.options[i].text = Item;
		oCtrl.options[i].value = Item;
	}
}

function LookupClear(oCtrl)
{
	oCtrl.options[0].text = ""; //oCtrl.getAttribute("defaultvalue");
	oCtrl.options[0].value = "";
	oCtrl.size=oCtrl.length;
	var action = "document.getElementById('" + oCtrl.id + "').size=" + oCtrl.length 
	setTimeout(action,100);
}
function LookupClose(oCtrl)
{
	oCtrl.size=1;
}

var GoToURL = "";


function SearchML(id){
	setTimeout("SearchML0('" + id + "')",50) // Need a breather so that selectedIndex gets set 
}

function SearchML0(id){
	var oCtrl = $get(id);
	if (!oCtrl) return;
	var ML = "";
	if (oCtrl.type=="select-one") ML = oCtrl[oCtrl.selectedIndex].text;
	if (oCtrl.type=="text") ML = oCtrl.value;
	var ML = TRIM(ML);
	LastAddress=ML // Save in case we need to just position map

	if (0==ML.length) return;
	// Was ML# included in the text
	if (ML.lastIndexOf("#:")>0)
	{ 
		ML=ML.substring(ML.lastIndexOf("#:")+2,ML.length);
		MyAjaxService.PropertyMLLookup(ML, "0,0,0,0", SearchMLCallBack, FailedCallback);		
		return;
	}
	// If a single word then assume it is an ML# unless it is a 5 digit number starting with "9" (Sandicor Zip)
	if (ML.split(" ").length==1) {
		if ((ML.length==5) && ("9"==ML.substr(0,1))) SearchAddr1(id); 	
		else 	MyAjaxService.PropertyMLLookup(ML, "0,0,0,0", SearchMLCallBack, FailedCallback);
		return;
	}
	// else look up as an address
	SearchAddr1(id);

	//var aAddr = ML.split(",");
	//var Zip="";
	//if (aAddr.length>1) Zip = TRIM(aAddr[aAddr.length-1]);
	//if (Zip.length>5) Zip=Zip.substr(Zip.length-5,5);
	//MyAjaxService.PropertyAddressLookup(TRIM(aAddr[0]),Zip,AddrCallBack, FailedCallback);
	
}

function SearchMLCallBack(Result){
	if (0 == Result.length) {
		var ML = LastAddress
		if ("0" == ML.substring(0, 1)) { // Try replacing 0 with the letter O
			LastAddress = "O" + ML.substr(1)
			MyAjaxService.PropertyMLLookup(LastAddress, "0,0,0,0", SearchMLCallBack, FailedCallback);
		} else {
			alert("Listing Not Found: " + LastAddress);	
			//maybe it is an address
			//MyAjaxService.PropertyAddressLookup(TRIM(ML),"",SearchAddrCallBack, FailedCallback)
		}
		return;
	}
	AddrCallBack(Result);	
}

function AddrCallBack(SysPropID)
	{	
	// If this address is for an active listing, then show the detail, else just go to 
	// regular property search centered on this address
		if (SysPropID.length>0)	{
		
			var parms = (SysPropID+",,,").split(",");

			var ThisSource = parms[0];
			var ThisID = parms[1];
			var ThisLat = parms[2];
			var ThisLon = parms[3];
			var Site = parent.$get("hSiteCode").value;
		
			switch (Site){
				case "HHI":
				case "INR":
					parent.ShowDetailFrame("../PropDetail.aspx?N=0&S=" + ThisSource + "&Id=" + ThisID);
					return;

				
				case "FCIQ": 
					document.location.href = FullURL("SiteContent/PropDetail_Q.aspx?N=0&S=" + ThisSource + "&Id=" + ThisID);
					return;

				case "MFR":
				case "OKC":
				case "SND":
					document.location.href = FullURL("SiteContent/PropDetail.aspx?N=0&S=" + ThisSource + "&id=" + ThisID);
					return;
																
	
			case "Demo": document.location.href=FullURL("SiteContent/Demo/PropDetailDemo.aspx?N=0&S=" + SysPropID.replace(",","&Id="));
					return;

			case "DFW": parent.ShowDetailFrame("PropDetail.aspx?N=0&S=" + ThisSource + "&id=" + ThisID); 
					return;
												
			default:	alert("Missing AddrCallBack handler for " + parms[0]);		
				break;
			}
		

		} else parent.ContentFrame.FindAddress(LastAddress)


}







function SearchAddr(id){
	setTimeout("SearchAddr1('" + id +"')",50);
}

function SearchAddr1(id){
	// Look up an address entered from the home page
	var oCtrl = $get(id);
	var SiteCode = $get("hSiteCode").value;
	var Addr = "";
	if (oCtrl.type=="select-one") Addr = oCtrl[oCtrl.selectedIndex].text;
	if (oCtrl.type=="text") Addr = oCtrl.value;
	Addr = TRIM(Addr);
	if (0==Addr.length) return;
	var aAddr = Addr.split(",");
	var Zip="";
	if (aAddr.length>1) Zip = TRIM(aAddr[aAddr.length-1]);
	if (Zip.length>5) Zip=Zip.substr(Zip.length-5,5);

	LastAddress=Addr;
	// Incase there is no address match, prepare redirect.
	var url = "?Addr=" + escape(Addr) + "&CityStZip=" + escape(Zip)
	switch (SiteCode){
	case "DFW": GoToURL=null; if (Addr.length>0) parent.ContentFrame.FindAddress(Addr); 
							break; // No home page, move map in ajoining window.
	case "INR": GoToURL = null; break; // Stay here if not found						
	case "MFR": GoToURL = null; break; //FullURL("SiteContent/PropertySearch.aspx" + url); break;
	case "OKC": GoToURL = FullURL("SiteContent/PropertySearch.aspx" + url); break;
	case "LAS": GoToURL = FullURL("SiteContent/LAS/PropertySearchLAS.aspx" + url); break;
	case "SND": GoToURL = FullURL("SiteContent/SND/PropertySearchSND.aspx" + url); break;
	case "Demo": GoToURL = null; break; //FullURL("SiteContent/PropertySearch.aspx" + url); break;
	case "NYS": GoToURL = null; break; 
	default:alert("Missing SiteCode Handler in SearchAddr():" + SiteCode);
	}	
	
	var ML=""
	if (Addr.lastIndexOf("#:")>0)
	{ ML=Addr.substring(Addr.lastIndexOf("#:")+2,Addr.length);
		MyAjaxService.PropertyMLLookup(ML, "0,0,0,0", SearchAddrCallBack, FailedCallback);
		
	} else {
		MyAjaxService.PropertyAddressLookup(TRIM(aAddr[0]),Zip,SearchAddrCallBack, FailedCallback);
	}
}
	
function SearchAddrCallBack(SysPropID)
	{	
	// If this address is for an active listing, then show the detail, else just go to 
	// regular page centered on this address
		if (SysPropID.length==0)	{
			if (GoToURL!=null) document.location.href=GoToURL;
			else alert("Not Found: " + LastAddress);
			return;
		};
		
		var aProps = SysPropID.split(";")
		if (aProps.length>1) 
		{
			var Display = "Multiple possibilities...Enter the ML# for a specific property\n ";
			var N = aProps.length
			for (var i=0; i<N; i++)
			{
				var aText = (aProps[i]+",,").split(",")
				var Text = aText[2];
				Display += "\n" + Text;
			}
			alert(Display);
			return;
		}
		
		//var parms = SysPropID.split(",");
		//var qparms = "?N=0&S=" + SysPropID.replace(",","&Id=");
		//switch ($get("hSiteCode").value){
		//case "DFW": break;
		//case "INR": parent.ShowDetailFrame(FullURL("SiteContent/PropDetail.aspx" + qparms)); break;
		//case "DEMO": document.location.href = FullURL("SiteContent/Demo/PropDetailDemo.aspx" + qparms); break;
		//default:		document.location.href = FullURL("SiteContent/PropDetail.aspx" + qparms);
		//break;
		//}
		
		
		
		var Source=(SysPropID+",").split(",")[0];
		var SysID=(SysPropID+",").split(",")[1];
		document.location.href = ComputePropDetailURL("", 0, Source, SysID)
		
		
}

function ComputePropDetailURL(PropDetailStyle, N, Source, SysID){
	var URL="";
	Source = TRIM(Source);
	if ("G"==PropDetailStyle) return FullURL("SiteContent/Demo/PropDetailDemo.aspx?N=" + N + "&S=" + Source + "&Id=" + SysID); 
	if ("A"==PropDetailStyle) return FullURL("SiteContent/PropDetail.aspx?N=" + N + "&S=" + Source + "&Id=" + SysID);
	if ("C"==PropDetailStyle) return FullURL("SiteContent/PropDetailGadgets.aspx?N=" + N + "&S=" + Source + "&Id=" + SysID);
	if ("Q"==PropDetailStyle) return FullURL("SiteContent/FCIQ/PropDetailQ.aspx?N=" + N + "&S=" + Source + "&Id=" + SysID);
	
	// If no recognized style specified, determine one based on Source code
	if ("FCIQ"==Source) return ComputePropDetailURL("Q",N,Source,SysID);
	 //
	return ComputePropDetailURL("A",N,Source,SysID);
}
