﻿var oVECompsMap = null;
var oVECompsMap_PropCompsLayer = null;
var oPanel = null;
var oIPanel = null;
var Source = null;
var Site = null;
var iSysID = 0;
var Address = null;
var PostalCode = null;
var oDrivingDir = null;
var isPrinting = false;
var PropMapData = null;
var oOutput = null;
var N = 0;
var Start = 0;
var CurrentPage = 0;

//Set default language and change error messages accordingly
var LanguageIndex  = 0

//var PropSearchMsg_Searching = "|Searching...|Searching...|Recherche...".split("|")[LanguageIndex];
var ZoomedInPropMapTitle = "|Subject Property|Subject Property|{french}".split("|")[LanguageIndex];
var ZoomedInPropMapIcon = "|Click icon for more property info.|Click icon for more property info.|{french}".split("|")[LanguageIndex];
var CompsCallBackTitle = "|Market<br>Comparison|Market<br>Comparison|{french}".split("|")[LanguageIndex];


function Initialize() {
	var startDate = $get("hDateStart").value;
	var endDate = $get("hDateEnd").value;
	var weeksAvailable = $get("hWeeks").value;

	var rentaldiv = $get("ShortTermRental");
	if (rentaldiv != null) {
		//call to SiteContent/CalendarWeekly.js
		rentaldiv.innerHTML = WriteCalendars(weeksAvailable, startDate, endDate);
	}
		
		// Are we undocked?
		var isUndock = false
		try { isUndock = parent.isDetailViewExpandable } catch (e){}
		if (isUndock) 
		{
			UndockPropertyDetailAndExpandView();
			return;
		}

		var oBackBut = $get("btnBack");


		// Are we part of a popup?
		if (window.opener) 
		{
			if (oBackBut) oBackBut.style.display="none";
		}
		
		GoogleAnalytics()
		
		var isCurrentTab = false;
		try { isCurrentTab = parent.CurrentTab } catch(e){}
		
		// If we aren't in a prop search situation replace the "Back to Map" with a Return button
		if (isCurrentTab) 
		{
					if (oBackBut)
					{
						if (parent.isListView) oBackBut.src = oBackBut.src.replace("Return", "ReturnToList");
						else oBackBut.src = oBackBut.src.replace("Return", "ReturnToMap");
					}
				if ($get("butSave2ShoppingCart")) $get("butSave2ShoppingCart").style.display = "block";
		}

		if ((!$get("chkSend2Friend")) && ($get("btnFriend"))) $get("btnFriend").style.display = "none";

		isPrinting = (0 < $getval("hPrinting").length);
		Source = $getval("hSource");
		Site = $getval("hSiteCode");
		iSysID = $getint("hSysID");
		oDrivingDir = new DrivingDir();
		DataClear();
		Resize();
		Compute();

		if (!isPrinting) GetAuxPhotos();
				
		// No suggested props for MIBOR or Agent Search Links
		var isPropListData = false;
		try { isPropListData = (null != parent.PropListData )} catch (e) { }
		if ((Site!="INR") && isPropListData) GetSuggestedProps();
		if ((Site=="INR") && (!isPrinting)) 
		{
			$get('chkContactAnAgent').checked=true;
			ToggleView('chkContactAnAgent', 'divContactAnAgent'); // Agent Info Open by default
		}
		 
		if ($get("CMA"))
		{         
			if (Site == 'DFW') $get("CMA").style.display = "none";
			if (Site == 'INR') $get("CMA").style.display = "none";
		}
		
		// If this is a print window, do some reformatting
		if (isPrinting) {
				
				ToggleView('chkLoanCalc', 'divLoanCalc'); // Calculator on;
				ToggleView('chkContactAnAgent', 'divContactAnAgent'); // Agent Info
				$get("tblContactForm").style.display = "none";
				$get("Send2Friend").style.display = "none";
				$get("tblContactAnAgent").style.display = "none";
				
				var oWin = window.opener;
				if (oWin) {	
						
						if (oWin.document.getElementById("bShowDir").checked) {
								$get("tblDrivingDirections").style.display = "none";
								$get("divDirections").innerText = oWin.document.getElementById("divDirections").innerText;
						} else {
								$get("DrivingDirections").style.display = "none";
						}

						if (oWin.document.getElementById("chkLoanCalc").checked) {
								$get("tblLoanCalc").style.display = "none";
						} else {
								$get("LoanCalc").style.display = "none";
						}

				} else {
						$get("DrivingDirections").style.display = "none";
						$get("LoanCalc").style.display = "none";
				}
				if ($getval("hSiteCode") == 'INR') {
					//Setup print flyer
					//Copy existing tables into the print flyer tables in the arranged order
					var feattable = document.getElementById("tblFeatureList1");
					document.getElementById("printFeatureList1").appendChild(feattable);
					
					var printheader = $getval("hPrintHeader");
					
					var headertable = document.getElementById("tblPropDetailHdr");
					document.getElementById("printHeader").appendChild(headertable);
					
					var detailstable1 = document.getElementById("tblFeatureList1");
					document.getElementById("printFeatureList1").appendChild(detailstable1);
					
					var detailstable2 = document.getElementById("tblFeatureList2");
					document.getElementById("printFeatureList2").appendChild(detailstable2);
					
					var detailstable3 = document.getElementById("tblFeatureList3");
					document.getElementById("printFeatureList3").appendChild(detailstable3);
					
					var detailstable4 = document.getElementById("tblFeatureList4");
					document.getElementById("printFeatureList4").appendChild(detailstable4);
					
					var remarkstable = document.getElementById("agentRemarks");
					document.getElementById("printAgentRemarks").appendChild(remarkstable);
					
					var agentstable = document.getElementById("agentInformation");
					document.getElementById("printAgentContact").appendChild(agentstable);
					
					var copyrighttable = document.getElementById("copyright");
					document.getElementById("printCopyrightInfo").appendChild(copyrighttable);
					
					$get("propPhoto").src = $getval("hPrimaryPhotoURL");

					//Turn off the display of the normal page elements
					$setstyle("propPhotos", "display", "none");
					$setstyle("AgentComments", "display", "none");
					$setstyle("PropertyFeatures", "display", "none");
					$setstyle("DrivingDirections", "display", "none");
					$setstyle("ContactAnAgent", "display", "none");
					$setstyle("Send2Friend", "display", "none");
					$setstyle("LoanCalc", "display", "none");
					$setstyle("divPropSuggest", "display", "none");
					$setstyle("copyright", "display", "none");
					
					//$get("MIBORHdr").style.display = "none"; - hiding this makes it not print

					$setstyle("Map", "display", "none");
					$setstyle("PhotoXTitle", "display", "none");
					$setstyle("linkVTX", "display", "none");
					$setstyle("divPrintReport", "display", "block");
				}
				if ($getval("hSiteCode") == 'MFR') {
						if (oWin.document.getElementById("chkPropComps").checked) {
								$get("tblAVM").style.display = "none";
								$get("divPropComps").style.display = "block";
								divPropCompsTable.innerHTML = oWin.document.getElementById("divPropCompsTable").innerHTML;
						} else {
								$get("CMA").style.display = "none";
						}
				}
			 Print2();
		} else setTimeout("SlideShow()",3000); // slideshow unless we are printing
		
		//Get data and length for the prev-next buttons
		try {PropMapData = parent.PropListData;} catch(e) {PropMapData=null;}
	 
		var ddlPg = $get("PageNum")
		var NPages=0;
		if (!PropMapData) ddlPg = null;
		else  NPages = PropMapData.length 
		
		if (ddlPg) {
				while (ddlPg.options.length) ddlPg.remove(0);
				for (var i = 1; i <= NPages; i++) {
						ddlPg.options.add(new Option(i,i));
				}
				if (ddlPg.options.length > 0) {
						ddlPg.options[Math.min(ddlPg.options.length, Math.max(0, CurrentPage))].selected = true;
				} else { CurrentPage = 0; }
				if (parent.SelectedProp) $get("ckSelect").checked=parent.SelectedProp[CurrentPage];
		}
		
		//Find property on mini-map
		var isListView = false
		try { isListView = parent.isListView;} catch(e) {}
		
		if (isListView)
		{
			var Lat = parseFloat($getval("hLatitude"));
			var Lon = parseFloat($getval("hLongitude"));
			var Title = $getval("hAddress");
			if (parent.FindOnMapSearch) {
					parent.FindOnMapSearch(Lat, Lon, Title); // HHI & MIBOR Style
			}
		}
		
		// Show expander icon only if we are inside a frame.
		if (window.top.location != self.location)
		{
			var oImg = $get("btnBack"); if (oImg) oImg.style.visibility="visible";	
		} else {
			var oImg = $get("imgExpand");
			if (oImg){
				oImg.src=oImg.src.replace("HandleGripUp.gif","HandleGripDown.gif");
				oImg.title="Close window and dock detail to map frame"					
			}
		}
		var oBtn = $get("btnBack"); if (oBtn) oBtn.style.visibility="visible";	
		var oImg = $get("imgExpand"); if (oImg) oImg.style.visibility="visible";

		iPad_PageScroll($get('divDetailsPanel'));

		window.onresize = Resize;
}

var SlideNum = 0;
var isSlideShowRunning = true;

function SlideShow() {
		if (isSlideShowRunning) {
				// change Image
				var oImg = $get("Photo" + SlideNum);
				if (!oImg) oImg = $get("PhotoXH" + SlideNum);
				if (!oImg) oImg = $get("PhotoXV" + SlideNum);
				
				if ((!oImg) || (0 < oImg.src.indexOf("NoPhoto"))) 
				{
						SlideNum = 0;
				} else {
					var oTitle = $get("PhotoXTitle")
					SwitchPhoto($get("PhotoX"), oImg, oTitle);
					SlideNum++;
				}
		}
		setTimeout("SlideShow()", 5000);
}

function SwitchPhoto (oPhoto, oImg, oTitle)
{
	if (!oPhoto) return;
	var Title = GetAttrStr(oImg, "alt", "");
	oTitle.innerText = Title;
	var oTitleSpace = $get("imgTitleSpace");
	if (oTitleSpace && (Title.length > 0)) $get("imgTitleSpace").style.height = "48px"; // Latches the title height if there are any titles at all. Keeps slide show from bouncing screen up and down.
	var NumFilters = 4
	var id = Math.floor(NumFilters * Math.random());
	try {
		var canFilter = oPhoto.filters && oPhoto.filters(id)
		if (canFilter) oPhoto.filters(id).Apply();
		oPhoto.src = oImg.src;
		if (canFilter) oPhoto.filters(id).Play();
	} catch (e) { }
}


function DataClear() {
		CurrentPage = $getint("hN");
}

function Next(Dir) {
		CurrentPage = Math.min(Math.max(0, CurrentPage+Dir), PropMapData.length-1);
		var Prop = new PropInfo(PropMapData, CurrentPage); //PropMapData has a zero-based index
		var SysID = Prop.SysID;
		Source = Prop.Source;
		ShowPropDetail(CurrentPage, Source, SysID);
		if ((Site == "HHI") || (Site == "INR")) {  //Find property on mini-map (redundant??)
			 var Lat = parseFloat($getval("hLatitude"));
			 if (parent.FindOnMapSearch) parent.FindOnMapSearch(Prop.Lat, Prop.Lon, Prop.Address); // HHI & MIBOR Style
		}
}

function Move(pg) {
		if (pg < 0) return;
		CurrentPage = pg;
		setTimeout("Next(0)", 1000);
}


function $SetWidth(id, width) {
		var element = $get(id);
		if (element) element.style.width = width;
}

function $SetHeight(id, height) {
		var element = $get(id);
		if (element) element.style.height = height;
}

function Resize() {
		// If the user resizes the window this will resize all the layers

		var Height = Math.max(200, GetScreenHeight());
		var Width = Math.max(200, GetScreenWidth());
		var Edge = Math.max(300, Width - 35);

	var oHdr = $get("tblPropDetailHdr");
	if (oHdr) oHdr.style.width = (Width - 20) + "px";

		oPanel = $get("divDetailsPanel");
		if (oPanel) {

				switch (Site) {
		 
						//Style B (HHI) Sites have a smaller height value 
						case "HHI":
						case "INR":
								oPanel.style.width = (Width) + "px";
								oPanel.style.height = (Height - 32) + "px";
								break;
								
						default: // Default Style
								oPanel.style.height = (Height - 35) + "px";
				oPanel.style.width = Width + "px";
				break;
				}
	}



	var NumPhotos = $getint("hNumPhotos");

	// Resize Aux Photo Display so their are 6 per line on the bottom and 6 per column on the right
	var oPhoto = $get("PhotoX");
	if (oPhoto){
		var H1 = Height-75;
		var W1 = Math.min(Width-25, 520);
			
		oPhoto.height = Math.round(Math.min(H1, W1 / 1.3));
		oPhoto.width = Math.round(Math.min(W1, H1 * 1.3));
		var tnW = Math.max(10,Math.round(oPhoto.width / 6.0)-4);
		var tnH = Math.max(10,Math.round(oPhoto.height / 6.0)-4);
		for (var i=0; i<30; i++)
		{
			var oTNv = $get("PhotoXV" + i);
			var oTNh = $get("PhotoXH" + i);
			if (oTNv) { oTNv.style.height = tnH + "px" ; oTNv.style.width=tnW + "px" ;}
			if (oTNh) { oTNh.style.width = tnW + "px" ;	oTNh.style.height=tnH + "px" ;}
		}
		$SetWidth("PhotoSpacer1", tnW + "px");
		$SetWidth("PhotoSpacer2", tnW + "px");
		$SetWidth("PhotoSpacer3", tnW + "px");
		$SetWidth("PhotoSpacer4", tnW + "px");
		$SetWidth("PhotoSpacer5", tnW + "px");
		$SetWidth("PhotoSpacer6", tnW + "px");

		FitPhotoX(Width-25,oPhoto.width, tnW, NumPhotos);

		$SetHeight("PhotoSpacerV1", tnH + "px");
		$SetHeight("PhotoSpacerV2", tnH + "px");
		$SetHeight("PhotoSpacerV3", tnH + "px");
		$SetHeight("PhotoSpacerV4", tnH + "px");
		$SetHeight("PhotoSpacerV5", tnH + "px");
		$SetHeight("PhotoSpacerV6", tnH + "px");
	}

	$SetWidth("divPropCompsMap", Edge + "px");
	$SetWidth("divPropCompsTable", (Edge - 20) + "px");
	$SetWidth("divIDXCourtesy", Edge + "px");

	// Narrow screen, make single column
	if (Edge < 600) {
		var oOverflow = $get("tdOverflow");
		var oFeatureList2 = $get("tblFeatureList2");
		var oFeatureList3 = $get("tblFeatureList3");
		var oFeatureList4 = $get("tblFeatureList4");
		if (oOverflow && oFeatureList2) 
		{
			// 
			var HTML = oFeatureList2.outerHTML + "<hr>" + oFeatureList3.outerHTML + oFeatureList4.outerHTML;
			// You have to clear the existing tables before adding the HTML to the overflow since the HTML you are 
			// adding has the same ID and you clear them afterwards you either end up clearing the both 
			// or it throws a NO_MODIFICATION_ALLOWED_ERR: DOM Exception 7 error
			oFeatureList2.outerHTML = "";
			if (oFeatureList3) oFeatureList3.outerHTML = "";
			if (oFeatureList4) oFeatureList4.outerHTML = "";
			oOverflow.innerHTML = HTML;

			$get("tdDivider").style.display = "none";
		} // else already a narrow screen
	}
}


function FitPhotoX(ScreenWidth,MainPhotoWidth,ThumbnailWidth, NumPhotos)
{
	// Arrange thubnails to maximize usage of horizontal space

	// Turn on both Horizonal and vertical photos in case they were previously hidden due to resize. 
	for (var i = 0; i < 30; i++) {
		var oPhotoV = $get("PhotoXV" + i)
		var oPhotoH = $get("PhotoXH" + i)
		if (oPhotoV && oPhotoH)
		{
			if (oPhotoV.style.display == "block") oPhotoH.style.display = "block";
			if (oPhotoH.style.display == "block") oPhotoV.style.display = "block";
		}
	}


	if (MovePhotos(1, NumPhotos, ScreenWidth, MainPhotoWidth, ThumbnailWidth)) return;
	if (MovePhotos(2, NumPhotos, ScreenWidth, MainPhotoWidth, ThumbnailWidth)) return;
	if (MovePhotos(3, NumPhotos, ScreenWidth, MainPhotoWidth, ThumbnailWidth)) return;
	if (MovePhotos(4, NumPhotos, ScreenWidth, MainPhotoWidth, ThumbnailWidth)) return;
	if (MovePhotos(5, NumPhotos, ScreenWidth, MainPhotoWidth, ThumbnailWidth)) return;

}

function MovePhotos(Row, NumPhotos, ScreenWidth, MainPhotoWidth, ThumbnailWidth) {
	var oAdvSpace = $get("imgAdvSpace")
	var AdvSpaceWidth = 0;
	if (oAdvSpace) AdvSpaceWidth = 160;
	if (oAdvSpace) oAdvSpace.width = Math.max(1, ScreenWidth - (MainPhotoWidth + ((Row-1) * (ThumbnailWidth + 3)) + AdvSpaceWidth));

	var First = 6 * (Row - 1);
	var Last = 6 * Row;

	if ((NumPhotos>=First) && (ScreenWidth > MainPhotoWidth + Row * (ThumbnailWidth + 3) + AdvSpaceWidth))
	{
		for (var i = First; i < Last; i++) HidePhotoX("H", i);
		return false; // May be more to do
	} else {
		for (var i = First; i < 30; i++) HidePhotoX("V", i);
		return true; // Yes, no more photos
	}
}

function HidePhotoX(Type,N)
{
	var oPhoto = $get("PhotoX" + Type + N)
	if (!oPhoto) return;
	oPhoto.style.display = "none";	
}


function ShowPhoto(evt) {
		var oIng = null;
		var eType = null;

		if (window.event) {
				oImg = window.event.srcElement;
				eType = window.event.type;
		} else {
				oImg = evt.target;
				eType = evt.type;
		}

		switch (eType) {
			case "mouseover":
			case "click":
				var oPhoto = $get("Photo"); if (oPhoto) oPhoto.src = oImg.src;
				var oPhoto = $get("PhotoX"); if (oPhoto) oPhoto.src = oImg.src;
				var oTitle = $get("PhotoXTitle");
				var Title = GetAttrStr(oImg, "alt", "");
				var oTitleSpace = $get("imgTitleSpace");
				if (oTitleSpace && (Title.length > 0)) oTitleSpace.style.height = "48px"; // Latches the title height if there are any titles at all. Keeps slide show from bouncing screen up and down.
				if (oTitle) oTitle.innerText = Title;
				SlideNum = parseInt(oImg.id.substr(5));
				isSlideShowRunning = false;
				break;
			case "mouseout":
				isSlideShowRunning = true;
				break;
			default:
		}
}


function UpdateNotesCallBack(Msg) {
		$get("tdFavoriteMsg").innerText = Msg;

}

function UpdateNotes() {
		var VisitorID = $getval("hEncryptedVisitorID");
		var NewText = $getval("txtNotes");
		var SysPropertyID = $getval("hSysID");
		var Source = $getval("hSource");
		MyAjaxService.UpdateNotes(VisitorID, Source, SysPropertyID, NewText, UpdateNotesCallBack, FailedCallback)
}

function ToggleView(ImgID, DivID) {
		var oImg = $get(ImgID);
		if (oImg && "_Up.gif" == oImg.src.substr(oImg.src.length - 7)) {
				$setstyle(DivID,"display","none");
				oImg.src = oImg.src.substr(0, oImg.src.length - 7) + "_Dn.gif";
				return;
		}
		$setstyle(DivID,"display","block");
		oImg.src = oImg.src.substr(0, oImg.src.length - 7) + "_Up.gif";
		var VisitorID = $getval("hEncryptedVisitorID");
		var Lat = $getfloat("hLatitude"); if (0.0==Lat) Lat = 40;
		var Lon = $getfloat("hLongitude"); if (0.0==Lon) Lon = -80;

		switch (DivID) {
				case "divCommunity":
						//GeoNamesService.FindNearbyWikipedia(Lat, Lon, WikiCallBack, FailedCallback)
						//GeoNamesService.FindNearbyWeather(Lat, Lon, WeatherCallBack, FailedCallback)
						break;

				case "divPropComps":
						var sysId = $getval("hSysID");
						var myMls = $getval("hMyMLS");
						$get("divPropCompsTable").innerText = Translate("Loading... please wait.", "Téléchargement... veuillez patienter");
						MyAjaxService.GetCompTable(9, "S", sysId, myMls, this.CompsCallBackString, FailedCallback);
						break;

				case "divLoanCalc": Compute(); break;

				case "divContactAnAgent": break;
				case "divSend2Friend": break; // nothing to do.

				case "divPublicRecords": break;
				case "divSchools": break;
				case "divEstablishments": break;

		case "divMapContainer":
				// No longer used
				break;
				
				default: alert("Missing ToggleView handler: " + DivID); break;
		}
}

function CompsCallBackString(tables) {
		$get("divPropCompsTable").innerHTML = tables;
}

function CompsCallBack(CompProp) {

		var N = CompProp.N;
		var Tbl = new Sys.StringBuilder("<table width='100%' cellspacing='0' cellpadding='2' border='1' id='CompGrid'>");

		Tbl.append("<tr><td valign='bottom'><b><i>Market<br>Comparison</i></b></td>");
		Tbl.append("<td><img src='" + $get("PhotoX").src + "' width='100'/></td>");

		for (i = 1; i < N; i++) {
			var URL = "http://" + CompProp.PhotoPaths[i];
			if (!CompProp.PhotoPaths[i]) URL = "../Icons/NoPhoto_147.jpg"
			Tbl.append("<td><img src='" + URL + "' width='100'/></td>");
		}
		Tbl.append("</tr>");
		Tbl.append("<tr><td valign='bottom'>Property</td><td align='center' class='SubjHighlight'>Subject</td>");
		for (i = 1; i < N; i++) Tbl.append("<td align='center'>" + i + "</td>");
		Tbl.append("</tr>");

		Tbl.append(AddRow(N, "Rank", CompProp.Rank));
		Tbl.append(AddRow(N, "MLNumber", CompProp.MLNumber));
		Tbl.append(AddRow(N, "City", CompProp.City));
		Tbl.append(AddRow(N, "Bedrooms", CompProp.Bedrooms));
		Tbl.append(AddRow(N, "Full Baths", CompProp.BathsFull));
		Tbl.append(AddRow(N, "Partial Baths", CompProp.BathsPartial));
		Tbl.append(AddRow(N, "Size (SqFt)", CompProp.SqFt));
		Tbl.append(AddRow(N, "Garage", CompProp.GarageSpaces));
		Tbl.append(AddRow(N, "Acres", CompProp.LotAcres));
		Tbl.append(AddRow(N, "Year Built", CompProp.YrBuilt));
		Tbl.append(AddRow(N, "HOA", CompProp.HOAFeeMo));
		Tbl.append(AddRow(N, "Taxes", CompProp.TaxesAnn));
		Tbl.append(AddRow(N, "Tax Value", CompProp.AssessedValue));
		Tbl.append(AddRow(N, "Price", CompProp.Price));
		if ($getval("hSiteCode") == "LAS") Tbl.append(AddRow(N, "Price/SqFt", CompProp.PriceSqFt));
		Tbl.append(AddRow(N, "Date Sold", CompProp.ClosedDate));
		Tbl.append("<tr><td valign='bottom'>Include?</td>");
		for (i = 0; i < N; i++) {
				Tbl.append("<td align='center' ");
				if (0 == i) Tbl.append("class='SubjHighlight' ");
				Tbl.append("><input type='checkbox' checked='checked' id='Incl" + i + "' ");
				Tbl.append("AssessedValue='" + CompProp.iAssessedValue + "' ");
				Tbl.append("Price='" + CompProp.iPrice[i] + "' ");
				Tbl.append("SqFt='" + CompProp.iSqFt[i] + "' ");
				Tbl.append("DOM='" + CompProp.DOM[i] + "' onclick='fnRecalc()' ");

				if (i == 0) Tbl.append("disabled=1");
				Tbl.append("></td>");
		}
		Tbl.append("</tr>");
		Tbl.append("<tr><td valign='top' class='SubjHighlight'><b>Price<br>Analysis</b></td>")
		Tbl.append("<td valign='top'>based on <span id='NumComps'>?</span> selected properties</td>");
		Tbl.append("<td colspan='" + N + "' id='EstSP'></td></tr>");
		Tbl.append("</table>");

		$get("divPropCompsTable").innerHTML = Tbl.toString();
		fnRecalc();

		if (oVECompsMap_PropCompsLayer) { // Skip map update if the map is closed or not ready

			for (var i = 1; i < N; i++) {
				var Point = new VELatLong(CompProp.Latitude[i], CompProp.Longitude[i]);
				var PushPin = new VEShape(VEShapeType.Pushpin, Point);
				PushPin.SetTitle("Comp #" + i);
				PushPin.SetCustomIcon("<img src='../Icons/Pin_blue.gif' />");
				var PhotoURL = "http://" + CompProp.PhotoPaths[i];
				if (!CompProp.PhotoPaths[i]) PhotoURL = "../Icons/NoPhoto_147.jpg"
				PushPin.SetDescription("<div><img src='" + PhotoURL + "' alt='Click icon for more property info' width='100'></div>")
				oVECompsMap_PropCompsLayer.AddShape(PushPin);
			}

			// Adjust the map view so all property is visible
			rect = oVECompsMap_PropCompsLayer.GetBoundingRectangle();
			oVECompsMap.SetMapView(rect);
			oVECompsMap.SetMapStyle(VEMapStyle.Shaded);
			oVECompsMap.ZoomOut();
		} 
}

function fnRecalc() {
		var Price = 0;
		var nPrice = 0;
		var n = 0;
		var Answ = "";
		var DOM = 0;
		var nDOM = 0;
		var SubjSqFt = GetAttr($get("Incl0"), "SqFt");
		var SubjAssessedValue = GetAttr($get("Incl0"), "AssessedValue");
		//var PriceLow = 100000000;
		//var PriceHigh = 0;
		var n = 0;
		var PriceSum = 0;
		var Prices = new Array();
		var PricePerSqFtSum = 0;
		var nPricePerSqFt = 0;
		var PricePerAssSum = 0;
		var nPricePerAssess = 0;

		for (i = 1; i < 50; i++) {
				var oCtrl = $get("Incl" + i);
				if (oCtrl && oCtrl.checked) {
						var a_val = GetAttr(oCtrl, "AssessedValue");
						var p_val = GetAttr(oCtrl, "Price");
						var s_val = GetAttr(oCtrl, "SqFt");
						if (p_val > 100) {
								Prices.push(p_val);
								PriceSum += p_val;
								n++;
						}
						if ((s_val > 0) && (SubjSqFt > 0)) {
								PricePerSqFtSum += p_val / s_val;
								nPricePerSqFt++;
						}

						if ((a_val > 0) && (SubjAssessedValue > 0)) {
								PricePerAssSum += p_val / a_val;
								nPricePerAssess++;
						}
				}
		}
		Prices = Prices.sort(numOrdA);

		Answ = "<table>"
		if (n > 0) {
				Answ += "<tr><td align=right>Price Range:</td><td>$" + Math.round(Prices[0] / 1000) + "K</td><td align='center'>&nbsp;to&nbsp;</td><td>$" + Math.round(Prices[Prices.length - 1] / 1000) + "K</td></tr>";
				Answ += "<tr><td align=right>Average Price:</td><td>$" + Math.round(.001 * PriceSum / n) + "K</td><td>&nbsp;Median:</td><td>$" + Math.round(.001 * (Prices[Math.ceil(n / 2) - 1] + Prices[Math.ceil((n + 1) / 2) - 1]) / 2.0) + "K</td></tr>"

		}

		Answ += "</td></tr></table>";

		$get("EstSP").innerHTML = Answ;
		$get("NumComps").innerText = n;
}

function AddRow(N, Title, oProp) {
		var isData = false;
		var HTML = new Sys.StringBuilder("<tr><td>" + Title + "</td>");
		HTML.append("<td align='center' class='SubjHighlight'>");
		if (oProp[0]) { HTML.append(oProp[0]); isData = true; }
		else HTML.append("&nbsp;");
		HTML.append("</td>");

		for (i = 1; i < N; i++) {
				HTML.append("<td align='center'>");
				if (oProp[i]) { HTML.append(oProp[i]); isData = true; }
				else HTML.append("&nbsp;");
				HTML.append("</td>");
		}
		HTML.append("</tr>");
		if (!isData) return ""; // Skip this row, nothing there
		return HTML.toString();
}

function PopupGoogleMap() {
		var URL = "http://maps.google.com/maps?z=19&layer=tc&t=h&btnG=New+Address&cbp=1,0,1,0,0&cbll="
		URL += "&cbll=" + $getval("D_Lat")
		URL += "," + $getval("D_Lon")
		URL += "&q=" + escape(Address + "," + PostalCode + " USA")

		window.open(URL, "Map", "menubar=no,statusbar=no")
}

function PopupNeighborhoodBrowser() {
		var URL = "http://www.onboardnavigator.com/webcontent/OBWC_results.aspx?&AID=537-692f83792537&Datatype=4&Searchtype=2"
		URL += "&State=" //+ State;
		URL += "&Zip=" + PostalCode;
		URL += "&Address=" + Address;
		URL += "&City="// + City;
		window.open(URL, "Info", "menubar=no,statusbar=no")
		//	GeoNamesService.PostalCodeLookup(PostalCode, LinksCallBack, FailedCallback);

}

function MarkVisitor(Type) {

		var VisitorID = $getval("hEncryptedVisitorID");
		var Source = $getval("hSource");
		var SysPropID = $getval("hSysID");
		MyAjaxService.AddFavorite(VisitorID, Source, SysPropID, Type, DoNothing, DoNothing);
}

function PopupRealQuest() {
		var URL = "http://csvaluemap.facorelogic.com/ValueMap.aspx?licenseCode=10bc72a40f6446a4ba70081d2bd0ea42"
		URL += "&StreetAddress=" + escape($get('Address').innerText);
		URL += "&CityStateZip=" + $getval('hZipCode');
		window.open(URL, "Info", "menubar=no,statusbar=no")

}

// FUNCTION:  restrictNumeric
// REMARKS:   Called when the "onchange" event fires. This could have been done per 
//            keystroke but Netscape does not support "onkeypress" for input controls.
// IN:        bAllowDecimals - boolean, true allows periods to be entered, false will only allow numbers.
// RETURN:    none.
function restrictNumeric(bAllowDecimals, objInput) {
		// Loop through the string and remove any non numeric characters or decimals if flagged so.
		var sValue = objInput.value;
		var iLength = sValue.length;
		var iCharCode = null;
		var sNewString = "";
		for (var i = 0; i < iLength; i++) {
				iCharCode = sValue.charCodeAt(i);
				if ((iCharCode == 46 && bAllowDecimals) || (iCharCode >= 48 && iCharCode <= 57) || iCharCode == 8 || iCharCode == 9 || iCharCode == 127) {
						sNewString += sValue.charAt(i);
				}
		}

		// Display the newly formatted string.
		objInput.value = sNewString;
}
function ShowInquiry() {
		if (!$get("chkContactAnAgent").checked)
		{
			$get("chkContactAnAgent").checked = true;
			ToggleView('chkContactAnAgent', 'divContactAnAgent')
		}
		$get("divContactAnAgent").scrollIntoView(false);
		if (parent.FixAlign) parent.FixAlign();
		MarkVisitor("I");
	}

	function ShowOnboard(onboard) {
		var id = onboard.id;
		var checkbox = $get("chk" + id);
		
		if (!checkbox.checked) {
			checkbox.checked = true;
			ToggleView("chk" + id, "div" + id);
		}
		$get("Jump"+id).scrollIntoView(true);
		if (parent.FixAlign) parent.FixAlign();

		var iframe = $get("ifr" + id);
		iframe.src = onboard.src;
		iframe.height = onboard.height;

	}

	
function CancelInquiry() {
		$get("chkContactAnAgent").checked = false;
		ToggleView('chkContactAnAgent', 'divContactAnAgent')
}

function ShowSend2Friend() {
	var oChk = $get("chkSend2Friend")
	if (!oChk) return;
	if (!oChk.checked) {
		oChk.checked = true;
		ToggleView('chkSend2Friend', 'divSend2Friend')
	}

	var oDiv = $get("divSend2Friend")
	if (oDiv) oDiv.scrollIntoView(false);
	if (parent.FixAlign) parent.FixAlign();

}


function ShowMap() {
		//Reset top page navigation elements
		CurrentPage = 0;
		$setval("hN", '0');

		// You'll get permission errors from some browsers
		try { parent.HideDetailFrame(); return; } catch (e) { }	
		
		var RefPage = document.referrer.toLowerCase(); 
		//if ((RefPage.indexOf("propsummary.aspx") > 0) 
		//|| (RefPage.indexOf("loading.html")>0)
		//|| (RefPage.indexOf("recentprop4sale.aspx") > 0))
		if (RefPage.length>0) 
		{
				window.history.go(-1); // For agent web page usage ... site was framed, go back to propsummary rather than home page
		} 
		else {
			// Return button from detail page as standalone ... Redirecting to home page
			var Site = $getval("hSiteCode");
			switch(Site)
			{
				case "INR": // if this is a pop-up detail page we want to delay loading the home page if the frame is going to be closed anyway
				// When the home page is loaded we lose track of the favorite agent.  That's ok if we aren't a popup.  
					setTimeout("document.location.href = '../HomePageMibor.aspx'",500); 
				break;
				case "LAS": $get("btnBack").style.display = "none"; break;  // do nothing. No place to go.
				default: document.location.href = "../HomePage" + Site + ".aspx"; break;
			}
		}
}

function AddLead() {

		if ($getval("subject").length > 0) return; // Abort if a bot has filled in this hidden field.
		$get("tdStatus").innerText = "Preparing email...";
		var ToEmailAddr = $getval("LAEmail");
		var FromEmailAddr = $getval("txtEmail");

		//Required field validation
		var atpos = FromEmailAddr.indexOf("@");
		var dotpos = FromEmailAddr.lastIndexOf(".");
		if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= FromEmailAddr.length) {
				$get("tdStatus").innerText = "A valid Email address is required.";
				$get("txtEmail").focus();
				return;
		}    
		if ($getval("txtFirstName").replace(" ", "").length < 1) {
				$get("tdStatus").innerText = "A First Name is required.";
				$get("txtFirstName").focus();
				return;
		}
		if ($getval("txtLastName").replace(" ", "").length < 1) {
				$get("tdStatus").innerText = "A Last Name is required.";
				$get("txtLastName").focus();
				return;
		}

		var Subj = "Info Request from " + document.domain;
		var Msg = $getval("txtFirstName") + " " + $getval("txtLastName") + "<br>";
		Msg += Glue("", $getval("txtHomeStreet"), "<br>");
		Msg += Glue("", $getval("txtHomeCity"), ", ") + $getval("txtHomeState") + " " + $getval("txtHomeZip") + "<br>";
		Msg += Glue("<a href='mailto:", $getval("txtEmail"), "'>" + $getval("txtEmail") + "</a><br>");
		Msg += Glue("Home Phone: ", $getval("txtHomePhone"), "<br>");

		Msg += Glue("Working with agent: ", $getval("txtMyAgent"), "<br>")
		Msg += Glue("Comment: ", $getval("taComments"), "<br>")

		Msg += "<hr>The website visitor above was viewing ML# " + $getval("hMLNum")
		Msg += "<br>Address: <a href='" + document.location.href + "'>" + $getval("hAddress") + "</a>"
		Msg += "<br>when they sent this inquiry."

		var oChkSearchInfo = $get("chkSearchInfo")
		if (oChkSearchInfo && oChkSearchInfo.checked) {
				Msg += "<br>Their search criteria at the time was:<br>"
				Msg += Glue("SrchType=", $getvar("parent.SrchType"), "<br>");
				Msg += Glue("PropType=", $getvar("parent.PropType"), "<br>");
				Msg += GlueNum("Bedrooms >=", $getvar("parent.Beds"), "<br>");
				Msg += GlueNum("Baths >=", $getvar("parent.Baths"), "<br>");
				Msg += GlueNum("Price >=", $getvar("parent.MinPrice"), "<br>");
				Msg += GlueNum("Price <", $getvar("parent.MaxPrice"), "<br>");
				Msg += GlueNum("SqFt >=", $getvar("parent.SqFt"), "<br>");
				Msg += GlueNum("Lot size (Acres) >=", $getvar("parent.Acre"), "<br>");
				Msg += GlueNum("Year Built after ", $getvar("parent.YrBuilt"), "<br>");
				Msg += Glue("Pool=", $getvar("parent.Pool"), "<br>");
				Msg += Glue("County=", $getvar("parent.County"), "<br>");
				Msg += Glue("OpenHouse=", $getvar("parent.OpenHouse"), "<br>");
				Msg += GlueNum("Garage=", $getvar("parent.Garage"), "<br>");
				Msg += Glue("Area=", $getvar("parent.Area"), "<br>");
				Msg += Glue("Priority is ", $getvar("parent.Priority"), "<br>");
				//Msg += "Click to view <a href='http://" + document.domain + "/ProspectView.aspx?id=" + $get("hEncryptedVisitorID").value + "'>User's Map</a><br>"
		}
		Msg += "<br><br><b>Please reply immediately.</b><br>Thank you."


		var VisitorID = $getval("hEncryptedVisitorID");
		var Source = $getval("hSource");
		var SysPropID = $getval("hSysID");
		var SiteCode = $getval("hSiteCode");

		//Lookup CCEmail to send to the MLS (stored in the SiteInfo table)
		//var ccemail = DB.GetValue("SELECT CCEmail FROM SiteInfo WHERE " + Utils.AddString("SiteMLSCode",Source));

		//LAS wants a call to their GLVAR website to track email leads, passing variables in the URL
		//Make a request to a page they specify passing the agent code and some activity code:
		//Ex: http://www.glvar.com/WebsiteTracking.asp?activity=LeadGen&Agentid=12345

		// Some slimeball offices want the leads to go to them instead of the listing agents (XA)
		// Others just want an email copy of lead (CC)
		// Some agents don't want mail at all MLXPro Only (MX)
		switch ($getval("hOfficeSpecialAction")) {
				case "XA":
						ToEmailAddr = $getval("hOfficeEmail");
						MyAjaxService.SendLeadEmail(VisitorID, Source, SysPropID, "E", ToEmailAddr, FromEmailAddr, Subj, Msg, "en", LeadCallback, FailedCallback)
						return; // no MLXPro Leads allowed

				case "CC":
						ToEmailAddr += ";" + $getval("hOfficeEmail");
						MyAjaxService.SendLeadEmail(VisitorID, Source, SysPropID, "E", ToEmailAddr, FromEmailAddr, Subj, Msg, "en", LeadCallback, FailedCallback)
						break;

				case "MX": break; // No email, just PRO

				default:
						MyAjaxService.SendLeadEmail(VisitorID, Source, SysPropID, "E", ToEmailAddr, FromEmailAddr, Subj, Msg, "en", LeadCallback, FailedCallback)
		}

		// Send to MLX Pro if available	
		var url = $getval("MLXProLeadURL")

		var data = "listingID=" //+ $get("listingID").value
		data += "&selectedListingIDs=" + $getval("selectedListingIDs")
		data += "&radInterest=" + $getval("radInterest")
		data += "&selCriteriaBedrooms=" + $getval("selCriteriaBedrooms")
		data += "&selCriteriaBathrooms=" + $getval("selCriteriaBathrooms")
		data += "&txtCriteriaPriceMin=" + $getval("txtCriteriaPriceMin")
		data += "&txtCriteriaPriceMax=" + $getval("txtCriteriaPriceMax")
		data += "&txtCriteriaKeyFeatures="; // + $getval("txtCriteriaKeyFeatures")

		data += "&txtFirstName=" + $getval("txtFirstName");
		data += "&txtLastName=" + $getval("txtLastName");
		data += "&subject=" + $getval("subject");
		data += "&txtStreetAddress=" + $getval("txtHomeStreet");
		data += "&txtCity=" + $getval("txtHomeStreet");
		data += "&txtState=" + $getval("txtHomeState");
		data += "&txtZip=" + $getval("txtHomeZip");
		data += "&txtEmailAddress=" + $getval("txtEmail");
		data += "&txtHomePhone=" + $getval("txtHomePhone");
		data += "&txtWorkPhone="
		data += "&txtCellPhone="
		data += "&selContactMethod=Email"
		data += "&taComments=" + $getval("taComments").replace(/\n/g, " ");

		// No callback, messages added to errorlog
		if (url.length != 0) MyAjaxService.SendLead2MLX(url, data, MLXLeadCallback, FailedCallback);

}

function MLXLeadCallback(Msg) {
		//alert(Msg);
}

function LeadCallback(Msg) {
		$get("tdStatus").innerText = Msg;
		alert(Msg);
}

function Print() {
		//var VisitorID = $getval("hEncryptedVisitorID");
		var SysPropID = $getval("hSysID");
		var Source = $getval("hSource");
		var AdvancedReports = $getval("hHasAdvancedReports");

		var location = document.location.href.toLowerCase();

		

		// This isn't ready.
		//For web solutions there is a pdf options for pretty reports.
		//if (AdvancedReports == "Y") {
		//		location = location.replace("propdetail.aspx", "propertyreportdesign.aspx");
		//		location = location + "&websolutions=Y";
		//		window.open(location, "printwindow", "");
		//} else {
		if (Source == 'INR') {
			window.open(self.location.href + "&prt=1", "printwindow", "width=800,height=500;");
			return;
		}

			//$get("tblPropDetailNav").style.display = "none";
		$get("divDetailsPanel").style.width = "725px";
		$get("divDetailsPanel").style.height = "100%";
		$get("divDetailsPanel").style.width = "725px";
		$get("tblPropDetailHdr").style.width = "725px";

		// Rearrange Photo display -- put small photos at the bottom.
		for (var i = 0; i < 30; i++) {
			var oPhoto = $get("PhotoXV" + i);
			if (oPhoto) {
				oPhoto.style.display = "none";
				if (oPhoto.src.indexOf("NoPhoto_147.jpg") == -1) $get("PhotoXH" + i).style.display = "block";
			}
		}
		isSlideShowRunning = false;


		var oImg = $get("PhotoXH0");
		var oPhoto = $get("Photo"); if (oPhoto) oPhoto.src = oImg.src;
		var oPhoto = $get("PhotoX"); if (oPhoto) oPhoto.src = oImg.src;
		var oTitle = $get("PhotoXTitle"); if (oTitle) oTitle.innerText = GetAttrStr(oImg, "alt", "");

		var oInfo = $get("tdOnboardLinks"); if (oInfo) oInfo.style.display = "none";
		var oCF = $get("tblContactForm"); if (oCF) oCF.style.display = "none";
		var oS2F = $get("Send2Friend"); if (oS2F) oS2F.style.display = "none";

		var oChk = $get("chkEstablishments"); if (oChk && !oChk.checked) $get("Establishments").style.display = "none";
		var oChk = $get("chkSchools"); if (oChk && !oChk.checked) $get("Schools").style.display = "none";
		var oChk = $get("chkPublicRecords"); if (oChk && !oChk.checked) $get("PublicRecords").style.display = "none";
		var oChk = $get("chkLoanCalc"); if (oChk && !oChk.checked) $get("LoanCalc").style.display = "none";
		var oChk = $get("bShowDir"); if (oChk && !oChk.checked) $get("DrivingDirections").style.display = "none";
		var oChk = $get("chkPropComps"); if (oChk && !oChk.checked) $get("CMA").style.display = "none";
		var oChk = $get("chkMap"); if (oChk && !oChk.checked) $get("Map").style.display = "none";
		var oChk = $get("divToolHelpMsg"); if (oChk) oChk.style.display = "none";
		var oChk = $get("AgentClick"); if (oChk) oChk.style.display = "none";

		window.print();
		setTimeout("Resize();", 3000);
		return;


//				
//				setTimeout("Print3()", 100);
//		}
}
function Print3() {
	window.print();

	$get("tblPropDetailNav").style.display = "block";
	for (var i = 0; i < 30; i++) {
		var oPhoto = $get("PhotoXV" + i);
		if (oPhoto.src.indexOf("NoPhoto_147.jpg") == -1) oPhoto.style.display = "block";
	}

	setTimeout("Resize();", 1000);
}

function Print2() {
	//print now that we are in the popup print window	
		oVECompsMap = null;

		setTimeout("window.print()", 1000);
		if (!isDev) setTimeout("window.close()", 1500);
}

function Send2Friend() {
		var Source = $getval("hSource");
		var ToEmailAddr = $getval("emailto")
		if (0 == ToEmailAddr.length) {
				alert(Translate("Please enter an email address","S'il vous plaît entrer une adresse e-mail"));
				return;
		}
		var oButton = $get("btnSend2Friend");
		if (oButton) oButton.disabled = true;
		$get("tdS2FMsg").innerHTML="<img src='../icons/wait16trans.gif'/>";
				
		var FromEmailAddr = $getval("EmailFrom")
		if (0 == FromEmailAddr.length) return;
		RememberChanges($get("EmailFrom"), 'EmailAddr');
		createCookie("VisitorEmail", FromEmailAddr, 60); // Keep track of this person.

		
		var url = FullURL("prop/" + $getval("hLanguageCode") + "/"+  $getval("hSource").toLowerCase() + "/" + $getval("hMLNum"));

		var domain = $getval("Domain");
		if (domain == "") domain = document.domain;

		var Subj = Translate("Invitation to view a property on ","Invitation à consulter cette propriété sur ") + domain + " (" + $getval("hAddress") + ")";
		var Msg = $getval("EmailMessage")
		Msg += "<br>--" + $getval("MyFirstName") + " " + $getval("MyLastName") + "<br>";
		
		//Customize email message for different languages
		Msg += "<br><a href='" + url + "'><img alt='" + Translate("Click for Details","Cliquer pour les détails") +
						"' src='" + $getval("hPrimaryPhotoURL") + "'></a>"
		Msg += "<br>" + Translate("Address: ","Adresse : ") + " <a href='" + url + "'>" + $getval("hAddress") + "</a>"
		var Label ="City: "; if (Source=="FCIQ") Label="Municipality: ";		
		Msg += Glue("<br>" + Translate(Label,"Municipalité : "), $getval("hCity"), "");
		
		//var Label = "County: "; if (Site="FCIQ") Label="Region: ";
		//Msg += Glue("<br>" + Translate(Label,"Région : "), $get("hCounty").value, "");
		//Msg += Glue("<br>" + Translate("Neighborhood: ","Neighborhood : "), $get("hNeighborhood").value, "");
		if (Source=="FCIQ")	Msg += "<br>" + Translate("Price: ","Prix : ") + $getval("hListPrice") 
		else Msg += "<br>Price: " +  $getval("hListPrice");
		
		//Msg += "<br>" + Translate("Bedrooms: ","Chambres : ") + $get("hBeds").value
		//Msg += "<br>" + Translate("Bathrooms: ","Salles de bains : ") + $get("hBathsF").value + Translate(" full","")
		//Msg + GlueNum(Translate(", ","Salles d'eau :"), $get("hBathsP").value, Translate(" partial",""));
		//Msg += GlueNum("<br>" + Translate("Living Area: ","habitale pieds carrés : "), $get("hSqFt").value, Translate(" sqft"," pc"));
		//Msg += GlueNum("<br>" + Translate("Lot: ","Superficie du terrain : "), $get("hLotSize").value, Translate(" acres","pc et"));
		//Msg += GlueNum("<br>" + Translate("Year Built: ","Année de construction"), $get("hYrBuilt").value, "");
		//Msg += GlueNum("<br>" + Translate("Garage: ","Garage : "), $get("hGarageSpaces").value, " spaces");
		//Msg += Glue("<br>" + Translate("Pool: ","Piscine : "), $get("hPoolType").value, "");
		
		Msg += "<br><br>URL: <a href='" + url + "'>" + url + "</a>"
		
		if (Source=="FCIQ") Msg += "<br><br><a href='www.centris.ca'><img src='" + FullURL("SiteContent/FCIQ/images/logo.jpg") + "' width='154' alt='centris.CA logo' border='0'/></a>";

		var VisitorID = $getval("hEncryptedVisitorID");
		var SysPropID = $getval("hSysID");
		var LanguageCode = $getval("hLanguageCode");
		MyAjaxService.SendLeadEmail(VisitorID, Source, SysPropID, "S", ToEmailAddr, FromEmailAddr, Subj, Msg, LanguageCode, Send2FriendCallback, FailedCallback)
}

function Send2FriendCallback(Msg) {
		var oButton = $get("btnSend2Friend");
		if (oButton) oButton.disabled = false;
		$get("tdS2FMsg").innerHTML = "";
		alert(Msg);
}

function getFormValues(obj) {
		var queryStr = "";
		for (i = 0; i < obj.elements.length; i++) {
				var VarName = "&" + obj.elements[i].name + "="
				if (obj.elements[i].name.length == 0) continue;
				if (VarName.substr(1, 2) == "__") continue;
				switch (obj.elements[i].type) {
						case "text":
						case "submit":
						case "button":
						case "textarea":
						case "hidden": queryStr += VarName + obj.elements[i].value.replace(/\n/g, " "); break;

						case "radio":
						case "checkbox": if (obj.elements[i].checked) queryStr += VarName + obj.elements[i].value; break;

						case "select-one":
								var sel = obj.elements[i];
								queryStr += VarName + sel.options[sel.selectedIndex].value;
								break;
						default: alert("Missing getFormValues Handler for " + obj.elements[i].type);
				}
		}
		queryStr = queryStr.substr(1, (queryStr.length - 1));
		return queryStr;
}

function WikiCallBack(e) {
		var Data = Sys.Serialization.JavaScriptSerializer.deserialize(e, true);
		var HTML = new Sys.StringBuilder("");
		if ((e != null) && (Data.geonames != null)) {
				for (var i = 0; i < Data.geonames.length; i++) {
						HTML.append("<p><big><a href='http://" + Data.geonames[i].wikipediaUrl + "' target='_new'>")
						HTML.append(Data.geonames[i].title + "</a></big>&nbsp;" + Data.geonames[i].summary + "</P>")
				}
		} else {
				HTML.append("No results found")
		}
		$get("tdWiki").innerHTML = HTML.toString()
		$get("tabExternalLink").innerHTML = "";
}

function WeatherCallBack(e) {
		var Data = Sys.Serialization.JavaScriptSerializer.deserialize(e, true);
		var HTML = new Sys.StringBuilder("");
		if ((e != null) && (Data.weatherObservation != null)) {
				HTML.append("Observation Station: " + Data.weatherObservation.stationName);
				HTML.append("<br>Time of Observation: " + Data.weatherObservation.datetime);
				HTML.append("<br>Obervation Elevation: " + Data.weatherObservation.elevation);
				HTML.append("<br>Weather Conditions: " + Data.weatherObservation.weatherCondition);
				HTML.append("<br>Clouds: " + Data.weatherObservation.clouds);
				HTML.append("<br>Temperature: " + Data.weatherObservation.temperature);
				HTML.append("<br>Wind Speed: " + Data.weatherObservation.windSpeed);
				HTML.append("<br>Wind Direction: " + Data.weatherObservation.windDirection);
				HTML.append("<br>Dew Point: " + Data.weatherObservation.dewPoint);
				HTML.append("<br>Humidity: " + Data.weatherObservation.humidity);
		} else {
				HTML.append("No results found");
		}
		$get("tdWeather").innerHTML = HTML.toString()
}

function HelpSwitch() {
		$get('tdHelp').style.display = 'block';
		$get('linkClick').innerText = "";
}


function GetInput(FldName) {
		var oCtrl = $get(FldName)
		if (!oCtrl) alert(FldName + " is not an object");
		return MakeInt(oCtrl.value.replace(/\,/g, ""));
}

function Compute() {
	if (!$get("divLoanCalc")) return;
		var Price = GetInput("SalesPrice");
		var DownPay = GetInput("DownPay");
		var Taxes = GetInput("Taxes");
		var Insurance = GetInput("Insurance");
		var HOA = GetInput("HOA")
		var Mortgage = Price - DownPay;
		var Closing = GetInput("Closing")
		if (Closing == 0) Closing = .03 * Price;
		var Cash = DownPay + Closing
		var IR = $get("Rate")[$get("Rate").selectedIndex].value / 1200.
		var Pay = Math.round(Mortgage * ((IR * Math.pow(1 + IR, 30 * 12)) / ((Math.pow(1 + IR, 30 * 12)) - 1)));

		$setval("SalesPrice", CommaFmt(Price));
		$setval("DownPay", CommaFmt(DownPay));
		$setval("Mortgage", CommaFmt(Mortgage));
		$setval("Closing", CommaFmt(Closing));
		$setval("Cash",CommaFmt(Cash));
		$setval("Pay", CommaFmt(Pay));
		$setval("Taxes",CommaFmt(Taxes));
		$setval("Insurance", CommaFmt(Insurance));
		$setval("HOA",CommaFmt(HOA));
		$setval("MoTotal", CommaFmt(Math.round(Pay + Insurance + HOA + Taxes)));
		$setval("Income", CommaFmt(Math.round((12 * (Pay + Taxes + Insurance)) / .28)));
}

function GetAuxPhotos() {
		var Source = $getval("hSource");
		var SysID = $getval("hSysID");
		
		MyAjaxService.GetAuxPhotos(Source, SysID, GetAuxPhotosCallBack, FailedCallback);
}

function GetAuxPhotosCallBack(ImgList) {
		// Show photo list
		for (var i = 0; i < ImgList.length; i++) {
				var Photo = (ImgList[i]+';').split(';');
				var PhotoPath = Photo[0];
				var Alt = Photo[1];
				var oPhotoH = $get("Photo" + i);
				var oPhotoV = $get("PhotoB" + i);
				var oPhotoXH = $get("PhotoXH" + i);
				var oPhotoXV = $get("PhotoXV" + i);
				if (oPhotoH) {oPhotoH.src = "http://" + PhotoPath; oPhotoH.style.display = "block"; oPhotoH.setAttribute("alt",Alt);}
				if (oPhotoV) {oPhotoV.src = "http://" + PhotoPath; oPhotoV.style.display = "block";  oPhotoV.setAttribute("alt",Alt);}
				if (oPhotoXH) {oPhotoXH.src = "http://" + PhotoPath; oPhotoXH.style.display = "block";  oPhotoXH.setAttribute("alt",Alt);}
				if (oPhotoXV) {oPhotoXV.src = "http://" + PhotoPath; oPhotoXV.style.display = "block";  oPhotoXV.setAttribute("alt",Alt);}
				
	 }
		$setval("hNumPhotos", ImgList.length);
		Resize();
}


function GetSuggestedProps() {
		if (!$get("divPropSuggest")) return;
		var sysId = $getval("hSysID");
		var address = $getval("hAddress");
		var source = $getval("hSource");
		var zip = $getval("hZipcode");
		var visitor = $getval("hEncryptedVisitorID");
		
		MyAjaxService.GetCompGrid(5, "A", sysId, address, source, zip, visitor,
		this.PropsSuggestedJSONCallBack, FailedCallback);
}

function PropsSuggestedJSONCallBack(value) {
		var json = eval("(" + value + ")");

		var Source = $getval("hSource");
		var Tbl = new Sys.StringBuilder("<p class=\"suggestedPropsHeaderBold\">Below are comparable properties that you might be interested in viewing.</p>");
		Tbl.append("<table class='SuggestedPropsTable' cellspacing=\"0\" cellpadding=\"0\">");
		Tbl.append("<tr>");
		for (var i = 0; i < json.length; i++) {
			Tbl.append("<td class=\"suggestedPropsPrice\">$" + CommaFmt(json[i].ListPrice) + "</td>");
		}
		Tbl.append("</tr>");
		Tbl.append("<tr>");
		for (var i = 0; i < json.length; i++) {
			var URL = "http://" + json[i].Photo;
			var DetailURL = "Javascript:ShowPropDetail(" + i + ",'" + Source + "','" + json[i].SysPropertyId + "')";
			if (!json[i].Photo) URL = "../Icons/NoPhoto_147.jpg";
			Tbl.append("<td><a href=\"" + DetailURL + "\" class=\"suggestedPropsLink\"><img src='" + URL + "' alt='" + json[i].Address + "' /></a></td>");
		}
		Tbl.append("</tr>");
		Tbl.append("<tr>");
		for (var i = 0; i < json.length; i++) {
			var DetailURL = "Javascript:ShowPropDetail(" + i + ",'" + Source + "','" + json[i].SysPropertyId + "')";
			Tbl.append("<td><a href=\"" + DetailURL + "\" class=\"suggestedPropsLink\">" + json[i].Address + "</a></td>");
		}
		Tbl.append("</tr>");
		Tbl.append("</table>");

		$get("divPropSuggest").innerHTML = Tbl.toString();
		$get("divPropSuggest").style.display = "block";
}


function ShowPropDetail(N, Source, SysID) {
		var URL=ComputePropDetailURL(parent.PropertyDetailStyle, N, Source, SysID);
		if (parent.ShowDetailFrame) parent.ShowDetailFrame(URL);
		else document.location.href = URL;        
}

function SetSelection(){
	parent.SelectedProp[CurrentPage]=$get("ckSelect").checked;
}

function AutoClickInteractiveMap() {
	var oChk = $get('interactiveMapCheckbox')
	if (!oChk) return;
	oChk.click();
}
function ToggleDynamicMap(checkbox) {
	if (checkbox.checked) {
		ShowDynamicMap($get("hLatitude").value, $get("hLongitude").value, $get("hAddress").value, $get("hZipcode").value);
	} else {
		$get("divMapDynamic").style["display"] = "none";
		$get("divMap").style["display"] = "block";
	}
}
function ShowDynamicMap(Lat, Lng, Addr, Zip) {
	var div = $get("divMapDynamic");
	if (div.innerHTML == "") {
		div.innerHTML = "<iframe src='Gadgets/BirdseyeImageExpanded.aspx?Lat=" + Lat + "&Lon=" + Lng + "&Addr=" + Addr + "&Zip=" + Zip + "' width='600px' height='400px'/>";
	}
	div.style["display"] = "block";
	$get("divMap").style["display"] = "none";
	$get("interactiveMapCheckbox").checked = true;
}
function GetWeeksAvailable() {
	var weeks = $get("hWeeks");
	if (weeks != null) {
		var pattern = /;week:[0-9]{1,2}/g;
		var matches = weeks.value.match(pattern);
		if (matches != null) {
			for (var i = 0; i < matches.length; i++) {
				Weeks.Selected += matches[i].substring(6).replace(" ", "") + ",";
			}
		}
	}
}

function SetiFrameSize(obj) {
	if (obj.contentDocument == null) {
		setTimeout(SetiFrameSize(obj), 500);
		return;
	}
	var content = obj.contentDocument;
	if (content.document) content = content.document;

	var size = { height: content.body.clientHeight, width: content.body.clientWidth };
	//var width = content.body.clientWidth;

	obj.height = size.height;
	obj.width = size.width;
}

function FindMyAgent() {
	

	//Clear existing favorite agent
	// load find and agent at top level

	switch ($getval("hSiteCode")) {
		case "MFR": var oBtn = parent.$get("TopBannerMFR_Tab1_FindAgent")
			if (!oBtn) oBtn = parent.$get("TopBannerMFR_FavAgent_Tab1_FindAgent")
			if (oBtn) oBtn.click();
			break;

		case "SND": top.window.location = "snd/findanagent.aspx";
			break;

		case "OKC": top.window.location = "okc/MemberSearchOKC.aspx";
			break;

		

		default: alert("Not Supported");
			MyAjaxService.LogJSError("JS Error: FindMyAgent() not supported in PropDetail");
			break;
	}
}

