﻿var ContentFrame = null;
var oContent = null;
var MenuFrame = null;
var oMenu = null;
var DetailFrame = null;
var oDetail = null;
var oVEMap = null;

var isSearching = false;
var isDataOverflow = false;
var isRedoSearch = false; // Parameters changed during last search, redo
var isSingleStep = false; // Should DoStep continue on to process all steps?

var isActiveSearch = true;
var isSoldSearch = false;
var isOffMktSearch = false;
var isPendingSearch = false;
var isShortSaleSearch = false;
var isForeclosureSearch = false;
var isREOSearch = false;
var isTrends = false;
var DaysBackSold = 365;
var DaysBackOffMkt = 365;
//var DateSinceForSold ="";
//var DateSinceForOffMkt ="";

var LastActiveCount = "-";
var LastSoldCount = "-";
var LastOffMktCount = "-";
var LastPendingCount = "-";
var LastShortSaleCount = "-";
var LastForeclosureCount = "-";
var LastREOCount = "-";

var PropMapData = null;
var PropMapSoldData = null;
var PropMapPendingData = null;
var PropMapOffMktData = null;
var PropMapShortSaleData = null;
var PropMapForeclosureData = null;
var PropMapREOData = null;
var PropListData = null;

var PropTrendsData = null;
var SelectedProp = null; 
var MaxPropsOnMap = 50; // Max properties allowed from the search.
var MaxPropsInList = 100; // Each site could override this default value but 100 works well for ipad
var CurrentTab = "Map";
var UserHomeMLS = "";

var SourceDefault="";

var SrchType = "";
var PropType = "";
var Beds = 0;
var Baths = 0;
var BathsFull = 0;
var BathsPartial = 0;
var MinPrice = 10000;
var MaxPrice = 999999999;
var SqFtMin = 0;
var SqFtMax = 0;
var NumStories = 0;
var AcreMin = 0.0;
var AcreMax = 0.0;
var YrBuiltMin = 0;
var YrBuiltMax = 0;
var Pool = "";
var Waterfront = "";
var Waterview = "";
var ShortSaleREO = "";
var Garage = 0;
var Search1 = "";
var Search2 = "";
var Search3 = "";
var Search4 = "";
var Search5 = "";
var Search6 = "";
var Search7 = "";
var Search8 = "";
var AllRemarks = "";
var AllFeatures = "";
var RentalWeeks = "";
var Area = "";
var MLSArea = "";
var School = "";
var County = "";
var State = "";
var Address = "";
var OpenHouse = "";
var HasVirtualTour = "";
var HasPhoto = "";
var isRentalOnlySearch = ""; // Don't care; want default to not check for price>0
var Priority = "";
var ListedSinceDate = "";
var Source="";
var City = ""
var Neighborhood = ""
var Zipcode = ""

var IDX = "";
var ShowParcels = false;
var LastFavType = ""; // If a favorites search this has F for favorites only, or V for recently viewed
var LastShowMLSNumberURL = null; // Used by FCIQ & COOP to mark the MLS Detail to be displayed after the map fully loads
var LastSearchAbandoned = false; // Used when too many estimated results and user needs to revise criteria to get a timely response.

// Stats
var StatPriceCount = 0;
var StatPriceLow = "";
var StatPriceHigh = "";
var StatPriceAvg = "";
var StatPriceLabel = "";

var StatBedsCount = 0;
var StatBedsLow = "";
var StatBedsHigh = "";
var StatBedsAvg = "";
var StatBedsLabel = "";

var StatBathCount = 0;
var StatBathLow = "";
var StatBathHigh = "";
var StatBathAvg = "";
var StatBathLabel = "";

var StatSqFtCount = 0;
var StatSqFtLow = "";
var StatSqFtHigh = "";
var StatSqFtAvg = "";
var StatSqFtLabel = "";

var StatYrBuiltCount = 0;
var StatYrBuiltLow = "";
var StatYrBuiltHigh = "";
var StatYrBuiltAvg = "";
var StatYrBuiltLabel = "";

var StatLotCount = 0;
var StatLotLow = "";
var StatLotHigh = "";
var StatLotAvg = "";
var StatLotLabel = "";


// these are updated by map movement;
var MapCoord = "60,-95,20,-65";
var MapCenterLat = 0;
var MapCenterLon = 0;
var MapZoom = 0;
var MapAddr = "";
var ShowZipCodes = null;

var Boundaries_Type = null;
var POI_Type = ""; // This contains the currently selected POI_Type 
var Demographics_Type = null;
var ShowLabels = false;
var Overlays_Type = null;

var LastSearchCountTxt = "";
var LastCount = 0;
var TotalCount = 0;
var EncryptID = null;

var Site = "";
var isDemo = false;
var isReady = false;

var isListView = false;
var isDetailViewExpandable = false;
var PhotoPreview = true;
var ShowMiniMap = true;
var PropertyDetailStyle = "A";
var LanguageCode = "en-us";
var LanguageIndex  = 0
var ComputeDynamicOpt = "";

var ListCurrentPage = 1
var ListNumPropsPerPage = 5;
var SmallMapCenterLat = 0;
var SmallMapCenterLon = 0;
var SmallMapZoom = 9;

var PropSearchMsg_Searching = "Searching..."
var PropSearchMsg_Aggregating = "Aggregating..."
var PropSearchMsg_Retrieving = "Retrieving..."
var PropSearchMsg_Matches = "Matches"
var PropSearchMsg_OnMap = "on Map"
var PropSearchMsg_RetrievingMatches = "Retrieving Matches..."
var PropSearchMsg_MatchesRetrieved = "Matches Retrieved"
var PropSearchMsg_ComputingMarketTrends = "Computing Market Trends..."
var PropSearchMsg_StepCountOnMap = " on Map"
var PropSearchMsg_SearchRestarted = "Search Restarted"
var PropSearchEstimatedMsg_Matches = "First-pass Matches"


function FixAlign() {
	if (document.parentWindow)
		document.parentWindow.scroll(0, 0);
	else
		parent.scroll(0, 0);
 //When scrollintoview is used, sometimes parent frames move around. This will clean it up.
}

function SearchCriteria(Status) {
	this.Source=Source;
	this.CurrentTab=CurrentTab;
	this.EncryptID=EncryptID;
	this.iMapZoom=MakeInt(MapZoom);
	this.MapCoord=MapCoord;
	this.County=County;
	this.Address=Address;
	this.Area=Area;
	this.MLSArea=MLSArea;
	this.School=School;
	this.City=City;
	this.Neighborhood=Neighborhood;
	this.State=State;
	this.Zipcode=Zipcode;
	this.SrchType=SrchType;
	this.PropType=PropType;
	this.iMinPrice=MakeInt(MinPrice);
	this.iMaxPrice=MakeInt(MaxPrice);
	this.iBeds=MakeInt(Beds);
	this.iBaths=MakeInt(Baths);
	this.iBathsFull= MakeInt(BathsFull);;
	this.iBathsPartial= MakeInt(BathsPartial);;
	this.iNumStories = MakeInt(NumStories);;
	this.iSqFtMin = MakeInt(SqFtMin);
	this.iSqFtMax = MakeInt(SqFtMax);
	this.fAcreMin = MakeFloat(AcreMin);
	this.fAcreMax = MakeFloat(AcreMax);
	this.iYrBuiltMin = MakeInt(YrBuiltMin);
	this.iYrBuiltMax = MakeInt(YrBuiltMax);
	this.Pool=Pool;
	this.Waterfront=Waterfront;
	this.Waterview = Waterview;
	this.ShortSaleREO = ShortSaleREO;
	this.iGarage=MakeInt(Garage);;
	this.Search1=Search1;
	this.Search2=Search2;
	this.Search3=Search3;
	this.Search4=Search4;
	this.Search5=Search5;
	this.Search6=Search6;
	this.Search7=Search7;
	this.Search8=Search8;
	this.AllRemarks = AllRemarks + RentalWeeks, 
	this.AllFeatures = AllFeatures;
	this.OpenHouse  =OpenHouse,
	this.HasVirtualTour  =HasVirtualTour;
	this.HasPhoto  =HasPhoto;
	this.Status = Status;
	this.isRentalOnlySearch = isRentalOnlySearch;
	this.UserHomeMLS = UserHomeMLS;
	this.Priority = Priority;
	this.AgentID =IDX;
	this.isQuickCountable = (
	((
		this.OpenHouse +
		this.HasVirtualTour +
		this.HasPhoto +
		this.isRentalOnlySearch +
		this.AllRemarks +
		this.Address +
		this.Area +
		this.MLSArea +
		this.School +
		this.Neighborhood +
		this.Zipcode +
		this.SrchType +
		this.AllFeatures +
		this.ShortSaleREO +
		this.Waterfront +
		this.Waterview +
		this.Pool +
		this.Search1 +
		this.Search2 +
		this.Search3 +
		this.Search4 +
		this.Search5 +
		this.Search6 +
		this.Search7 + 
		this.Search8).length == 0)
	&& ((this.iNumStories + this.fAcreMin + this.fAcreMax + this.iGarage) == 0)
	)

	this.ListedSinceDate = "";
	switch (Status) {
		case "S":
			var SinceDate = new Date();
			SinceDate.setTime(SinceDate.getTime() - (DaysBackSold * 24 * 60 * 60 * 1000));
			if (DaysBackSold > 0) this.ListedSinceDate = (1 + SinceDate.getMonth()) + "/" + (SinceDate.getDate()) + "/" + SinceDate.getFullYear();
			break;
			
		case "X":
			var SinceDate = new Date();
			SinceDate.setTime(SinceDate.getTime() - (DaysBackOffMkt * 24 * 60 * 60 * 1000));
			if (DaysBackOffMkt > 0) this.ListedSinceDate = (1 + SinceDate.getMonth()) + "/" + (SinceDate.getDate()) + "/" + SinceDate.getFullYear();
			break;

		default: this.ListedSinceDate = ListedSinceDate; break;
	}


}







// Change the List Tab to a Map tab and replace the big map with a site-specific property summary page 
function ChangeContentView()
{
	ContentFrame = window.frames["Content"] 
	Site = $get("hSiteCode").value
	if (isListView)	
	{
			oContent.src =  CreateNoCookieURL(Site + "/PropSummary" + Site + ".aspx");
			$get("ListTab").src=$get("ListTab").src.replace("_List2-","_Map-");
	}	else {
			oContent.src = CreateNoCookieURL("PropMap.aspx")
			$get("ListTab").src=$get("ListTab").src.replace("_Map-","_List2-");
	}
}

function SetParentCookie(Val)
{
	if (Val=="")parent.creerCookie("PROVPROVQC");
	else 
	{
		Val = Val.replace(/%/gi,"");
		parent.creerCookie(Val.substring(0,2) + Val);
	}
}

function SetLanguage()
{
	var oLanguageCode = $get("hLanguageCode")
	if (!oLanguageCode) return;
	
	LanguageIndex = 0;
	if ("en-ca"==$get("hLanguageCode").value) LanguageIndex=1;
	if ("fr-ca"==$get("hLanguageCode").value) LanguageIndex=2;

	PropSearchMsg_Searching = "Searching...|Searching...|Recherche...".split("|")[LanguageIndex];
	PropSearchMsg_Aggregating = "Aggregating...|Aggregating...|Consolidation...".split("|")[LanguageIndex];
	PropSearchMsg_Retrieving = "Retrieving...|Retrieving...|Extraction...".split("|")[LanguageIndex];
	PropSearchMsg_Matches = "Matches|Matches|résultats".split("|")[LanguageIndex];
	PropSearchMsg_OnMap = "on Map|on Map|sur la carte".split("|")[LanguageIndex];
	PropSearchMsg_RetrievingMatches = "Retrieving Matches...|Retrieving Matches...|Extraction des Résultats...".split("|")[LanguageIndex];
	PropSearchMsg_MatchesRetrieved = "Matches Retrieved|Matches Retrieved|résultats".split("|")[LanguageIndex];
	PropSearchMsg_ComputingMarketTrends = "Computing Market Trends...|Computing Market Trends...|Calcul des tendances du marché...".split("|")[LanguageIndex];
	PropSearchMsg_StepCountOnMap = " on Map| on Map| sur la carte".split("|")[LanguageIndex];
	PropSearchMsg_SearchRestarted = "Search Restarted|Search Restarted|Recherche à Nouveau".split("|")[LanguageIndex];

	// Fixme: need french translations
	UtilsMsg_NoWaterMarkHandler = "No Watermark Handler: ";
	UtilsMsg_ListingNotFound = "Listing Not Found: ";
	UtilsMsg_NotFound = "Not Found: ";
	UtilsMsg_MultiplePossibilities = "Mutiple possibilities...be more specific\n ";
	UtilsMsg_CantComputeLink = "Can't compute link for ";
	//PropSearchEstimatedMsg_Matches
}


function Initialize(){

	SetLanguage();
	
	ContentFrame = window.frames["Content"] 
	MenuFrame = window.frames["Menu"];
	DetailFrame = window.frames["Detail"];
	oContent = $get("Content")
	oDetail = $get("Detail")
	oMenu = $get("Menu");
	
	EncryptID = $get("hEncryptedVisitorID").value
	Site = $get("hSiteCode").value
	isDemo = (Site=="Demo");

	eval($get("hInitCode").value); // load values into JS variables
	
	var aMap = MapCoord.split(",")
	MapCenterLat = .5 * (MakeFloat(aMap[0]) + MakeFloat(aMap[2]));
	MapCenterLon = .5 * (MakeFloat(aMap[1]) + MakeFloat(aMap[3]));
	
	// Map Address passed in	
	var Addr = $get("hAddress").value;
	var CityStZip = $get("hCityStZip").value;
	if ((Addr+CityStZip).length>0){
		MapZoom = 0;
		MapAddr = Addr + Glue(",",CityStZip,"");
	
	//Fix links throughout the page by adding vidx to them
	FixNoCookieLinks();
	
	}	

	switch (Site)
	{
	
		
	//to make the tab switching work with the options tab
	case "NYS":
	case "COOP":
	case "LAS":
		MenuFrame.location.replace(CreateNoCookieURL(Site+"/SearchCriteria.aspx")); 
		if (isListView) ContentFrame.location.replace(CreateNoCookieURL(Site+"/PropSummary" + Site + ".aspx"));
		else ContentFrame.location.replace(CreateNoCookieURL("PropMap.aspx"));
		break;

	case "INR":
		oMenu.src = CreateNoCookieURL("SearchCriteria.aspx"); 
		if (IDX.length>0) { // IDX pages requested
			setTimeout("oContent.src='PropSummaryMIBOR.aspx?vidx="+$get("hEncryptedVisitorID").value+"'",50) // Need to have site cookies set before page loads to prevent "Page cannot be framed or bookmarked" ;
			setTimeout("MapLoad(39.8,-86.2,9);$get('divMap').style.display='block';",50) // Need to override 
		}	else {
			setTimeout("oContent.src='PropMapMIBOR.aspx'",50);
			setTimeout("MapLoad(39.8,-86.2,9)",50)
		}
		break;
	
	case "HHI" :
		MenuFrame.location.replace(CreateNoCookieURL(Site + "/SearchCriteria.aspx"));
		//if (isListView) ContentFrame.location.replace(CreateNoCookieURL(Site + "/PropMap" + Site + ".aspx"));
		//else ContentFrame.location.replace(CreateNoCookieURL("PropMap.aspx"));
		ContentFrame.location.replace(CreateNoCookieURL("PropMap.aspx"));
	break;

	case "FCIQ":
		oContent.style.display = "block"; // Need to keep map visible so it displays properly, but hidden by the spash screen
		oDetail.style.display = "block";
		DetailFrame.location.replace("FCIQ/MapLoading.aspx");	
		ContentFrame.location.replace(CreateNoCookieURL("PropMap.aspx"));
		MenuFrame.location.replace(CreateNoCookieURL(Site+"/SearchCriteria.aspx")); 
		break;
	
	
	case "Demo":
	case "MFR":
	case "OKC":
	case "NYS":
	case "DFW":
	case "SND":
		//oContent.src = CreateNoCookieURL("PropMap.aspx");
		ContentFrame.location.replace(CreateNoCookieURL("PropMap.aspx"));
		
		// If user specified a area search from home page default to the list tab.		
		if (CurrentTab=="ShowList") ShowList();
		else	MenuFrame.location.replace(CreateNoCookieURL(Site+"/SearchCriteria.aspx")); 
		//oMenu.src = CreateNoCookieURL(Site + "/SearchCriteria.aspx");	
		break;
	
	default: alert("Missing Site Code (PropertySearch.js):" + Site);
	
		break;
	}


	Resize();
	isReady = true;
	PropSearch();

	iPad_Lock();
	window.onresize = Resize;
	
}

function MapLoad(Lat,Lon,Zm){
	oVEMap = new VEMap('divMap');
	oVEMap.SetDashboardSize(VEDashboardSize.Tiny); // Small, Tiny
	
	oVEMap.LoadMap(null,15,"s",false,1,true);
	oVEMap.HideMiniMap();
	//var Pt=	new VELatLong(Lat,Lon);
	//VEMap.SetCenterAndZoom(Pt,Zm);
	setTimeout("oVEMap.SetCenterAndZoom(new VELatLong(" + Lat + "," + Lon + ")," + Zm +")",100);
	$get("divMap").style.display="none";
}

function Resize(){
	var h = Math.max(75,GetScreenHeight() - 79);
	var w = Math.min(GetScreenWidth()-100,350);
	var ContentWidth = GetScreenWidth()-(w+5);

	var hTop =33;
	
	// See Site-specific PriopertySearchXXX.css file for an over-ride on the default layout
	Site = $get("hSiteCode").value
	switch (Site)
	{
	case "COOP":
	case "SND":
	case "DFW":	h = GetScreenHeight();
							oMenu.style.top = "35px";
							//oMenu.style.height = (h-35) + "px";
							break;
	
	case "FCIQ": h = GetScreenHeight();
							w -= 25;
							ContentWidth += 25; 
							h -= 54;
							hTop = 10;
							break;
	default: break;
	}

	// Photo Preview
	var oImg = $get("imgPopup");
	if (oImg) oImg.style.top = oMenu.style.top;
	
	oContent.style.left = w + "px";	
	oContent.style.width = ContentWidth + "px";
	oContent.style.height = (h-4) + "px";

	oMenu.style.height = (h-hTop) + "px";
	oMenu.style.width = w + "px";

	if (oDetail) {
		oDetail.style.left = w + "px";
		oDetail.style.width = ContentWidth + "px";
		oDetail.style.height = (h - 4) + "px";
	}


	// If Data Coop, reclaim as much of the left search panel as possible to get complete columns	
				
	if (ContentWidth<925) { // try overlapping seach screen to get 3 full columns 
		var NewContentWidth = Math.max(325,ContentWidth); // Only 1 column possible
		if (ContentWidth>325) NewContentWidth = Math.max(625,ContentWidth); // 2 columns possible
		if ((!isiPad) && ContentWidth>625) NewContentWidth = Math.min(925,ContentWidth); // 3 columns possible

		if (Site != 'COOP' && (ContentWidth > 625)) NewContentWidth = ContentWidth; // If Consumer view overlap left panel..ignore column widths since we don't have any.
			
		var adj = Math.min(325,NewContentWidth-ContentWidth); // Move screen left this amount (no more than 325 pixels overlapping)
		oDetail.style.width = (ContentWidth+adj)+ "px" 		
		oDetail.style.left = (w-adj) + "px";
}



	var oNav = $get("divNav");
	if (oNav) oNav.style.width = w + "px";

	if(isFrameReady("ContentFrame.Resize")) ContentFrame.Resize(); // Trigger refresh of child frame.
	if(isFrameReady("MenuFrame.Resize")) MenuFrame.Resize(); // Trigger refresh of child frame.
	if(isFrameReady("DetailFrame.Resize")) DetailFrame.Resize(); // Trigger refresh of child frame.
	
	}

function SaveMapView(Rect, Lat, Lon, Zoom){
	MapCoord = Rect;
	MapCenterLat = Lat;
	MapCenterLon = Lon;
	MapZoom = Zoom;
	PropSearch();	
}    

function SetShowParcels(bool){
	ShowParcels = bool;
	// reload Map to initiate change (if it is visible)
	if (bool)	MapZoom=18;
	ContentFrame.location.replace(ContentFrame.location.href); 
}

function Reload()
{
	document.location.replace(document.location.href); 
}

function ShowListFromChild()
{
	setTimeout("ShowList()",50);
}

function ShowList(){
	CurrentTab = "List"
	LastFavType="";
	HideDetailFrame()
	switch (Site){
	//to make this work with options tab
	case "NYS":
	case "COOP":	if (isListView) MenuFrame.location.href = CreateNoCookieURL(FullURL("SiteContent/PropMapSummary.aspx"));
							else MenuFrame.location.href = CreateNoCookieURL("PropPageList.aspx");
							break;
	 
	case "LAS" : MenuFrame.location.href = CreateNoCookieURL("../PropPageList.aspx"); break;

	// MFR, OKC, DFW, Demo
	default: MenuFrame.location.href = CreateNoCookieURL("PropPageList.aspx");	break;
	}
	//Account for each one of two stages the button could be in
	var oImg1 = $get("SearchTab");	oImg1.src = oImg1.src.replace("-selected", "-default").replace("-over", "-default");
	var oImg2 = $get("ListTab");		oImg2.src = oImg2.src.replace("-default", "-selected").replace("-over", "-selected");
	var oImg3 = $get("OptionsTab");		if (oImg3) oImg3.src = oImg3.src.replace("-selected", "-default").replace("-over","-default");
	var oImg4 = $get("FavoritesTab");	if (oImg4) oImg4.src = oImg4.src.replace("-selected", "-default").replace("-over","-default");

	PropSearch();
}

function PropFavRefresh()
{
	// FavoriteSearch ... need to force a refresh
	if (LastFavType=="")
	{
		PropSearch();
	} else {
		var Favtype = LastFavType;
		LastFavType = "";
		FavoriteSearch(Favtype); 
	}
}

function PropSearch(){
		if (LastFavType!="") 
		{
			FavoriteSearch(LastFavType);
			return;
		}
		if (isListView)	SimpleSearch();
		else Search();
}

function ShowFavorites(){
	CurrentTab = "Favorites"
	HideDetailFrame()
	// Do Favorites Search
		
	/// Show the PropPageList
	// Load Favorites Options into Detail frame.

	switch (Site){
	case "LAS" : 
		ContentFrame.location.href = CreateNoCookieURL("../PropMap.aspx"); 
		MenuFrame.location.href =  CreateNoCookieURL("SearchCriteria.aspx");	
		break;
		//to make this work with new options tab
		case "NYS":
			if (isListView) 
			{
				ContentFrame.location.href = CreateNoCookieURL("NYS/PropSummaryNYS.aspx");
				MenuFrame.location.href =  CreateNoCookieURL("MyFavorites.aspx");	
				
			}	else {
				ShowDetailFrame(CreateNoCookieURL("MyFavorites.aspx"));
				MenuFrame.location.href =  CreateNoCookieURL("PropPageList.aspx");	
				
			}
			break;
		//to make this work with new options tab
		case "COOP" : 
			if (isListView) 
			{
				ContentFrame.location.href = CreateNoCookieURL("COOP/PropSummaryCOOP.aspx");
				MenuFrame.location.href =  CreateNoCookieURL("MyFavorites.aspx");	
				
			}	else {
				ShowDetailFrame(CreateNoCookieURL("MyFavorites.aspx"));
				MenuFrame.location.href =  CreateNoCookieURL("PropPageList.aspx");	
				
			}
			break;
		case "FCIQ" : 
				ContentFrame.location.href=CreateNoCookieURL("PropMap.aspx");
				MenuFrame.location.href=CreateNoCookieURL("PropPageList.aspx");	
				setTimeout("DoStep('Recenter')",1000);
			break;
						
	default: // MFR,OKC,DFW,Demo
		MenuFrame.location.href = CreateNoCookieURL("PropPageList.aspx");
		ShowDetailFrame(CreateNoCookieURL("MyFavorites.aspx"));
		break;		
	}



	var oImg1 = $get("SearchTab");	oImg1.src = oImg1.src.replace("-selected", "-default").replace("-over", "-default");
	var oImg2 = $get("ListTab");		oImg2.src = oImg2.src.replace("-selected", "-default").replace("-over", "-default");
	var oImg3 = $get("OptionsTab");		if (oImg3) oImg3.src = oImg3.src.replace("-selected", "-default").replace("-over","-default");
	var oImg4 = $get("FavoritesTab");	if (oImg4) oImg4.src = oImg4.src.replace("-default", "-selected").replace("-over","-selected");
		
	FavoriteSearch("F");
}

function ShowOptions(){
	CurrentTab = "Options"
	HideDetailFrame()
	MenuFrame.location.href =  CreateNoCookieURL("SearchOptions.aspx");	
	
	//Account for each one of two stages the button could be in
	var oImg1 = $get("SearchTab");	oImg1.src = oImg1.src.replace("-selected", "-default").replace("-over", "-default");
	var oImg2 = $get("ListTab");		oImg2.src = oImg2.src.replace("-selected", "-default").replace("-over", "-default");
	var oImg3 = $get("OptionsTab");		if (oImg3) oImg3.src = oImg3.src.replace("-default", "-selected").replace("-over","-selected");
	var oImg4 = $get("FavoritesTab");	if (oImg4) oImg4.src = oImg4.src.replace("-selected", "-default").replace("-over","-default");
}

function HighlightPin(N)
{
	if (isFrameReady("MenuFrame.HighlightPin")) MenuFrame.HighlightPin(N);
}

function RefreshDropDowns()
{
	if (isFrameReady("MenuFrame.RefreshDropDowns")) MenuFrame.RefreshDropDowns();
}

function ShowSearch(){
	CurrentTab = "Search"
	HideDetailFrame();
	
	switch (Site){
	case "LAS" : 
		ContentFrame.location.href = CreateNoCookieURL("../PropMap.aspx"); 
		MenuFrame.location.href =  CreateNoCookieURL("SearchCriteria.aspx");	
		break;
		//to make this work with new options tab
		case "NYS":
			if (isListView) ContentFrame.location.href = CreateNoCookieURL("NYS/PropSummaryNYS.aspx");
			else ContentFrame.location.href = CreateNoCookieURL("PropMap.aspx");
			MenuFrame.location.href =  CreateNoCookieURL("NYS/SearchCriteria.aspx");	
			break;
		//to make this work with new options tab
		case "COOP" : 
			if (isListView) ContentFrame.location.href = CreateNoCookieURL("COOP/PropSummaryCOOP.aspx");
			else ContentFrame.location.href = CreateNoCookieURL("PropMap.aspx");
			MenuFrame.location.href =  CreateNoCookieURL("COOP/SearchCriteria.aspx");	
			break;
			
	default: // MFR,OKC,DFW,Demo
		ContentFrame.location.href = CreateNoCookieURL("PropMap.aspx"); 
		MenuFrame.location.href = CreateNoCookieURL(Site + "/SearchCriteria.aspx");
		break;		
	}
	//Account for each one of two stages the button could be in
	var oImg1 = $get("SearchTab");	oImg1.src = oImg1.src.replace("-default", "-selected").replace("-over", "-selected");
	var oImg2 = $get("ListTab");		oImg2.src = oImg2.src.replace("-selected", "-default").replace("-over", "-default");
	var oImg3 = $get("OptionsTab");		if (oImg3) oImg3.src = oImg3.src.replace("-selected", "-default").replace("-over","-default");
	var oImg4 = $get("FavoritesTab");	if (oImg4) oImg4.src = oImg4.src.replace("-selected", "-default").replace("-over","-default");
	
	if (LastFavType!='') 
	{ 
		LastFavType=""; 
		PropSearch(); 
	}

	
}


function Search() {
	if (!isReady) return;
	if (isSearching){
		isRedoSearch = true;
		return; // don't jam up with multiple searches at once.
	}
	isSearching = true;
	LastFavType="";
	
// Clear map and counts
	PropListData = null;
	PropMapData = null;
	PropMapSoldData = null;
	PropMapOffMktData = null;
	PropMapPendingData = null;
	PropMapShortSaleData = null;
	PropMapForeclosureData = null;
	PropMapREOData = null;
	DisplayStepCount("ActiveCount","");			
	DisplayStepCount("SoldCount","");				
	DisplayStepCount("OffMktCount","");				
	DisplayStepCount("PendingCount","");				
	DisplayStepCount("ShortSaleCount","");	
	DisplayStepCount("ForeclosureCount","");
	DisplayStepCount("REOCount","");				


	DisplayMsg("");
	isSingleStep = false; 
	if(isFrameReady("ContentFrame.DataRefresh"))ContentFrame.DataRefresh('All');
	if (Site=='COOP') setTimeout("DoStep('CountQuick')", 50);
	else setTimeout("DoStep('Count')", 50);
}


/* Loop through the steps in sequence, skipping those that are not needed and quitting if search has restarted.


Step Name				Ajax Method Call						CallBack to...						Next Step	
==========			=====================				===================				===========
Recenter				PropertySearchRegion				RecenterMapCallBack					None
CountQuick			PropertySearchCount					StepCountQuickCallBack			Count
Count						PropertySearchCount					StepCountCallBack						Active
Active					PropertySearchAggregate			StepActiveAggCallBack				Pending
Pending					PropertySearchAggregate			StepPendingAggCallBack			Sold
Sold						PropertySearchAggregate			StepSoldAggCallBack					OffMkt	
OffMkt					PropertySearchAggregate			StepSoldAggCallBack					ShortSale	
ShortSale				ForeclosureSearchAggregate	StepShortSaleCallBack				Foreclosure
Foreclosure			ForeclosureSearchAggregate	StepForeclosureCallBack			REO
REO							ForeclosureSearchAggregate	StepREOCallBack							GetActiveList
GetActiveList		PropertySearch							StepGetActiveListCallBack		GetPendingList
GetPendingList	PropertySearch							StepGetPendingListCallBack	GetSoldList
GetSoldList			PropertySearch							StepGetSoldListCallBack			GetOffMktList
GetOffMktList		PropertySearch							StepGetOffMktListCallBack		SummarizeList	
SummarizeList																														Trends
Trends					PropertyTrends							MarketTrendsCallBack				none

*/



function DoStep(Name)
{

	var iMapZoom = MakeInt(MapZoom);
	var iGarage = MakeInt(Garage);
	var iMinPrice = MakeInt(MinPrice);
	var iMaxPrice = MakeInt(MaxPrice);
	var iBeds = MakeInt(Beds);
	var iBaths = MakeInt(Baths);
	var iBathsFull = MakeInt(BathsFull);
	var iBathsPartial = MakeInt(BathsPartial);
	var iNumStories = MakeInt(NumStories);
	var iSqFtMin = MakeInt(SqFtMin);
	var iSqFtMax = MakeInt(SqFtMax);
	var fAcreMin = MakeFloat(AcreMin);
	var fAcreMax = MakeFloat(AcreMax);
	var iYrBuiltMin = MakeInt(YrBuiltMin);
	var iYrBuiltMax = MakeInt(YrBuiltMax);
	

	// Don't need to retriev data for List view this time?
	var CanSkipListRetrieveal = (Site == 'COOP') && ((CurrentTab == 'Map') || (CurrentTab == 'Search') || (CurrentTab == 'Options'))

	if (EncryptID == null) {
		if (isDev) alert("Dev Only: Missing visitor record...system unable to perform search.\nTry reloading page.");
		return;
	}
	 
	switch(Name) {
	case "Recenter":
		MyAjaxService.PropertySearchRegion(new SearchCriteria('A'), RecenterMapCallBack, FailedCallback);
			break;
		
				// if we have a potentially slow search criteria (mostly a Co-op DEMO problem) 
				// do a quick count with the criteria that will be fast
				// (cause it will use the propertyaggreate table) and determine 
				// if the search is sufficiently narrow that performance won't suck. 
				// Otherwise alert user to add more criteria restrictions

	case "CountQuick":
			DisplayStatus(PropSearchMsg_Searching);
			if (isFrameReady("MenuFrame.DataClear")) MenuFrame.DataClear(); // Clear list
			
			
			var oSearchCriteria = new SearchCriteria('A');
			oSearchCriteria.isQuickCountable = true; // Get a quick count of the maximum possible matches by ignoring the criteria not in the PropertyAgg table 
			MyAjaxService.PropertySearchCount(oSearchCriteria, false, StepCountQuickCallBack, FailedCallback);
			break;

	case "Count":
			DisplayStatus(PropSearchMsg_Searching);
			if (isFrameReady("MenuFrame.DataClear")) MenuFrame.DataClear(); // Clear list
			MyAjaxService.PropertySearchCount(new SearchCriteria('A'), false,  StepCountCallBack, FailedCallback);
			break;


	case "Active":
		if (isActiveSearch) {
			DisplayStatus(PropSearchMsg_Aggregating);

			//////////////if (LastCount>MaxPropsOnMap){ // Aggregate data
			// put up aggregate pushpins for up to 250 points closest to center
			// The aggregation unit are square lat/lon boxes of whatever size needed to get the data down to < Max points
			// Trial and error is used to determine lat/lon box size.
			LastCount = MakeInt(LastCount);
			MyAjaxService.PropertySearchAggregate(LastCount, MaxPropsOnMap, new SearchCriteria('A'), StepActiveAggCallBack, FailedCallback);
		} else {
			DisplayStepCount("ActiveCount", "-");
			if (isSingleStep) DoStep('Done');
			else setTimeout("DoStep('Pending')", 50);
		}
		break;


	case "Pending":
		if (isPendingSearch) {
			DisplayStatus("Aggregating Pending...");
			MyAjaxService.PropertySearchAggregate(0, MaxPropsOnMap, new SearchCriteria('U'), StepPendingAggCallBack, FailedCallback);
		} else {
			DisplayStepCount("PendingCount", "-");
			if (isSingleStep) DoStep('Done');
			else setTimeout("DoStep('Sold')", 50);
		}
		break;


	case "Sold":
			if (isSoldSearch) {
				DisplayStatus("Aggregating Solds...");
				MyAjaxService.PropertySearchAggregate(0, MaxPropsOnMap, new SearchCriteria('S'), StepSoldAggCallBack, FailedCallback);
			} else {
				DisplayStepCount("SoldCount", "-");
				if (isSingleStep) DoStep('Done');
				else setTimeout("DoStep('OffMkt')", 50);
			}
			break;

	case "OffMkt":
			if (isOffMktSearch) {
				DisplayStatus("Aggregating Off-Market...");
				MyAjaxService.PropertySearchAggregate(0, MaxPropsOnMap, new SearchCriteria('X'), StepOffMktAggCallBack, FailedCallback);
			} else {
				DisplayStepCount("OffMktCount", "-");
				if (isSingleStep) DoStep('Done');
				else setTimeout("DoStep('ShortSale')", 50);
			}
			break;
					
	// Mortgage Default
		 case "ShortSale":
			if (isShortSaleSearch) {
				DisplayStatus("Searching Defaults...");
				MyAjaxService.ForeclosureSearchAggregate(
					MaxPropsOnMap,
					iMapZoom,
					MapCoord,
					PropType,
					Area,
					City,
					Neighborhood,
					State,
					Zipcode,
					iMinPrice,
					iMaxPrice,
					iBeds,
					iBaths,
					iNumStories,
					iSqFtMin,
					iSqFtMax,
					fAcreMin,
					fAcreMax,
					iYrBuiltMin,
					iYrBuiltMax,
					"D",
					StepShortSaleCallBack, FailedCallback);
			} else {
				DisplayStepCount("ShortSaleCount", "-");
				if (isSingleStep) DoStep('Done');
				else setTimeout("DoStep('Foreclosure')", 50);
			}
			break;

	// Auction
		 case "Foreclosure":
			if (isForeclosureSearch) {
				DisplayStatus("Searching Auctions...");
				MyAjaxService.ForeclosureSearchAggregate(
					MaxPropsOnMap,
					iMapZoom,
					MapCoord,
					PropType,
					Area,
					City,
					Neighborhood,
					State,
					Zipcode,
					iMinPrice,
					iMaxPrice,
					iBeds,
					iBaths,
					iNumStories,
					iSqFtMin,
					iSqFtMax,
					fAcreMin,
					fAcreMax,
					iYrBuiltMin,
					iYrBuiltMax,
					"A",
					StepForeclosureCallBack, FailedCallback);

			} else {
				DisplayStepCount("ForeclosureCount", "-");
				if (isSingleStep) DoStep('Done');
				else setTimeout("DoStep('REO')", 50);
			}
			break;

	// REO
		 case "REO":
			if (isREOSearch) {
				DisplayStatus("Searching Bank/REO...");
				MyAjaxService.ForeclosureSearchAggregate(
					MaxPropsOnMap,
					iMapZoom,
					MapCoord,
					PropType,
					Area,
					City,
					Neighborhood,
					State,
					Zipcode,
					iMinPrice,
					iMaxPrice,
					iBeds,
					iBaths,
					iNumStories,
					iSqFtMin,
					iSqFtMax,
					fAcreMin,
					fAcreMax,
					iYrBuiltMin,
					iYrBuiltMax,
					"R",
					StepREOCallBack, FailedCallback);
			} else {
				DisplayStepCount("REOCount", "-");
				DoStep('GetActiveList')
			}
			break;

	// Get the list of property that should be displayed in the list view.
		case "GetActiveList":
			if (isActiveSearch && !CanSkipListRetrieveal) {
				DisplayStatus(PropSearchMsg_Retrieving);
				var N = MaxPropsInList;
				MyAjaxService.PropertySearch(N, new SearchCriteria('A'), false, StepGetActiveListCallBack, FailedCallback);
			} else {
				if (isSingleStep) DoStep('Done');
				else setTimeout("DoStep('GetPendingList')", 50);
			}
			break;


	// Get the list of property that should be displayed in the list view. 
	case "GetPendingList":
		if (isPendingSearch && !CanSkipListRetrieveal)
				{ 					
					DisplayStatus(PropSearchMsg_Retrieving);
					var N = MaxPropsInList;
					MyAjaxService.PropertySearch(N, new SearchCriteria('U'), false, StepGetPendingListCallBack, FailedCallback);
				} else {
					if (isSingleStep) DoStep('Done');
					else setTimeout("DoStep('GetSoldList')",50);				
				}
				break;


	// Get the list of property that should be displayed in the list view. 
	case "GetSoldList":
		if (isSoldSearch && !CanSkipListRetrieveal)
				{ 					
					DisplayStatus(PropSearchMsg_Retrieving);
					var N = MaxPropsInList;
					MyAjaxService.PropertySearch(N, new SearchCriteria('S'), false, StepGetSoldListCallBack, FailedCallback);
				} else {
					if (isSingleStep) DoStep('Done');
					else setTimeout("DoStep('GetOffMktList')",50);				
				}
				break;

	// Get the list of property that should be displayed in the list view. 
	case "GetOffMktList":
		if (isOffMktSearch && !CanSkipListRetrieveal)
				{ 					
					DisplayStatus(PropSearchMsg_Retrieving);
					var N = MaxPropsInList;
					MyAjaxService.PropertySearch(N, new SearchCriteria('X'), false, StepGetOffMktListCallBack, FailedCallback);
				} else {
					if (isSingleStep) DoStep('Done');
					else setTimeout("DoStep('SummarizeList')",50);				
				}
				break;


			case "SummarizeList":

				if (hasSearchRestarted()) return;
				if (!CanSkipListRetrieveal) {
					var PropCount = 0; if (PropListData) PropCount = PropListData.length;

					// Compute Summary Statistics
					StatPriceCount = 0; StatPriceLabel = ""; StatPriceLow = 999999999; StatPriceHigh = 0; StatPriceAvg = 0;
					StatBedsCount = 0; StatBedsLabel = ""; StatBedsLow = 999; StatBedsHigh = 0; StatBedsAvg = 0;
					StatBathCount = 0; StatBathLabel = ""; StatBathLow = 999; StatBathHigh = 0; StatBathAvg = 0;
					StatSqFtCount = 0; StatSqFtLabel = ""; StatSqFtLow = 9999999; StatSqFtHigh = 0; StatSqFtAvg = 0;
					StatYrBuiltCount = 0; StatYrBuiltLabel = ""; StatYrBuiltLow = 9999; StatYrBuiltHigh = 0; StatYrBuiltAvg = 0;
					StatLotCount = 0; StatLotLabel = ""; StatLotLow = 999999; StatLotHigh = 0; StatLotAvg = 0;

					for (var Num = 0; Num < PropCount; Num++) {
						var NewProp = new PropInfoShort2(Num);
						var New_Price = MakeInt(NewProp.LP);
						var New_SqFt = MakeInt(NewProp.SqFt);
						var New_Beds = MakeInt(NewProp.Beds);
						var New_Bath = MakeInt(NewProp.Bath);
						var New_Lot = MakeFloat(NewProp.Lot);
						var New_Yr = MakeInt(NewProp.YrBuilt);
						if (New_Price > 0) { StatPriceCount++; StatPriceAvg += New_Price; StatPriceLow = Math.min(StatPriceLow, New_Price); StatPriceHigh = Math.max(StatPriceHigh, New_Price); }
						if (New_SqFt > 0) { StatSqFtCount++; StatSqFtAvg += New_SqFt; StatSqFtLow = Math.min(StatSqFtLow, New_SqFt); StatSqFtHigh = Math.max(StatSqFtHigh, New_SqFt); }
						if (New_Beds > 0) { StatBedsCount++; StatBedsAvg += New_Beds; StatBedsLow = Math.min(StatBedsLow, New_Beds); StatBedsHigh = Math.max(StatBedsHigh, New_Beds); }
						if (New_Bath > 0) { StatBathCount++; StatBathAvg += New_Bath; StatBathLow = Math.min(StatBathLow, New_Bath); StatBathHigh = Math.max(StatBathHigh, New_Bath); }
						if (New_Yr > 0) { StatYrBuiltCount++; StatYrBuiltAvg += New_Yr; StatYrBuiltLow = Math.min(StatYrBuiltLow, New_Yr); StatYrBuiltHigh = Math.max(StatYrBuiltHigh, New_Yr); }
						if (New_Lot > 0) { StatLotCount++; StatLotAvg += New_Lot; StatLotLow = Math.min(StatLotLow, New_Lot); StatLotHigh = Math.max(StatLotHigh, New_Lot); }
					}

					if (StatPriceCount > 0) { StatPriceLow = "$" + CommaFmt(StatPriceLow); StatPriceHigh = "$" + CommaFmt(StatPriceHigh); StatPriceAvg = "$" + CommaFmt(Math.round(StatPriceAvg / StatPriceCount)); }
					if (StatSqFtCount > 0) { StatSqFtAvg = CommaFmt(Math.round(StatSqFtAvg / StatSqFtCount)); }
					if (StatBedsCount > 0) { StatBedsAvg = Math.round(10 * StatBedsAvg / StatBedsCount) / 10.0; }
					if (StatBathCount > 0) { StatBathAvg = Math.round(10 * StatBathAvg / StatBathCount) / 10.0; }
					if (StatYrBuiltCount > 0) { StatYrBuiltAvg = Math.round(StatYrBuiltAvg / StatYrBuiltCount); }
					if (StatLotCount > 0) { StatLotAvg = Math.round(100 * StatLotAvg / StatLotCount) / 100.0; }
					if (hasSearchRestarted()) return;
				}
				if (isFrameReady("MenuFrame.DataRefresh")) setTimeout("MenuFrame.DataRefresh()", 50);
				if (!isSingleStep) DoStep("Trends");
				else DoStep('Done');



	case "Trends":
					DisplayStatus(PropSearchMsg_ComputingMarketTrends);
					if (isTrends) MyAjaxService.PropertyTrends(
					Source,
					MapCoord,
					Area,
					MLSArea,
					School,
					City,
					Neighborhood,
					State,
					Zipcode,
					County,
					Address,
					SrchType,
					PropType,
					iMinPrice,
					iMaxPrice,
					iBeds,
					iBaths,
					iBathsFull,
					iBathsPartial,
					iNumStories,
					iSqFtMin,
					iSqFtMax,
					fAcreMin,
					fAcreMax,
					iYrBuiltMin,
					iYrBuiltMax,
					Pool,
					Waterfront,
					Waterview,
					iGarage,
					Search1, Search2, Search3, Search4, Search5, Search6, Search7, Search8,
					AllRemarks + RentalWeeks,
					AllFeatures,
					"",
					HasVirtualTour,
					HasPhoto,
					"X",
					ListedSinceDate,
					isRentalOnlySearch,
					Priority,
					MarketTrendsCallBack,FailedCallback); 		
					DoStep('Done')
					break;



				case "Done": isSearching = false; // Done
					DisplayStatus("");
					if (Site == "FCIQ") break;
					break;
	
	default: alert("Missing Step Handler: " + Name); break;			
	}
}


function ShowCountSummary() {
	// Display additional count stats.

	if (LastSearchAbandoned) {
		var CurrentMsg = "Too many properties selected."
		CurrentMsg += "!Searches are limited to 20,000 matches. This search"
		CurrentMsg += "!could potentially return up to " + CommaFmt(1000*Math.round(LastCount/1000.0)) + " matches."
		CurrentMsg += "!!Please add or revise criteria to narrow your search."
		CurrentMsg += "!Focus on adding narrower limits to these fields: "
		CurrentMsg += "!!Type, Price, Yr Blt, SqFt, Beds, Baths, State and County."
		CurrentMsg += "!!Clearing the criteria from all fields other than those!fields listed above will allow unlimited matches."

	} else {
		var CurrentMsg = "The status line show counts for active property only.!See below for additional counts!!"
		if (isActiveSearch) CurrentMsg += "Active matches visible on map..." + LastActiveCount + "!"
		if (!isNaN(parseInt(TotalCount))) CurrentMsg += "Active matches (including off map)..." + TotalCount + "!"
		else CurrentMsg += "!Note: System unable to count off-map matches.!Fix this by providing narrower location criteria !(e.g. State, County, Zipcode) in Advance Search!!"

		if (!isActiveSearch) CurrentMsg += "Active matches on map (but hidden)..." + CommaFmt(LastCount) + "!"

		if (isSoldSearch) CurrentMsg += "Sold matches visible on map..." + LastSoldCount + "!"
		if (isPendingSearch) CurrentMsg += "Under Contract matches visible on map..." + LastPendingCount + "!"
		if (isOffMktSearch) CurrentMsg += "Off-market matches visible on map..." + LastOffMktCount + "!"
		if (isShortSaleSearch) CurrentMsg += "Pre-Default matches visible on map..." + LastShortSaleCount + "!"
		if (isForeclosureSearch) CurrentMsg += "Auction matches visible on map..." + LastForeclosureCount + "!"
		if (isREOSearch) CurrentMsg += "REO/Bank Owned matches visible on map..." + LastREOCount + "!"

	}
	
	
	
	if (isSearching) CurrentMsg += LastREOCount + "!==Warning== still searching, results are not complete!"

	
	CurrentMsg = CurrentMsg.replace(/!/g, "\n");
	alert(CurrentMsg)

}


function FrenchFmt(LanguageIndex,Num)
{
	var Result = CommaFmt(parseInt(Num));
	if (LanguageIndex!=2) return Result;
	return Result.replace(","," ");
}

function StepCountQuickCallBack(Data) {
	LastSearchCountTxt = Data;
		var aCount = (Data + ".").split(".");
		LastCount = parseInt(aCount[0]);
		var MapCount = FrenchFmt(LanguageIndex, aCount[0]);
		TotalCount = FrenchFmt(LanguageIndex, aCount[1]);
		DisplayMsg(LastCount + " " + PropSearchEstimatedMsg_Matches);
		DisplayStepCount("ActiveCount", CommaFmt(LastCount));
		DisplayStatus("");
		LastSearchAbandoned = false;
		if (hasSearchRestarted()) return; //Abort;

		// If the quickcount is accurate, then skip the full count and go right to pin retrieval
		if (new SearchCriteria('A').isQuickCountable)
		{
			StepCountCallBack(Data);
			return;
		}

	
		// If the quickcount's maximum estimate is less than 20,000 we can complete the search
		if (LastCount<20000) {
			DoStep("Count");
			return;
		}

		// The search will take too long to run; abandon it and have user revise criteria
		isSearching = false; // Done
		LastSearchAbandoned = true;
		
		PropListData = null;
		if (isFrameReady("MenuFrame.DataRefresh")) setTimeout("MenuFrame.DataRefresh()", 50);
		if (isFrameReady("ContentFrame.DataRefresh")) setTimeout("ContentFrame.DataRefresh()", 50);
		DisplayStatus("<b style='color:red'>Revise Criteria</b>");
		DisplayMsg("<b style='color:red'>Click ? for details</b>");
		return;
	}

function StepCountCallBack(Data) {	// SearchCount Callback
	LastSearchCountTxt = Data;
	var aCount = (Data+".").split(".");
	LastCount = parseInt(aCount[0]);
	var MapCount = FrenchFmt(LanguageIndex,aCount[0]);
	TotalCount = FrenchFmt(LanguageIndex, aCount[1]);
	DisplayMsg(MapCount + " " + Translate("Matches on map","résultats sur la carte"))

	if ((!isNaN(TotalCount)) && (TotalCount<1000)) DisplayMsg(TotalCount + Translate(" Matches "," résultats ") + MapCount + Translate(" on map"," sur la carte"));
	
	isDataOverflow = (LastCount > MaxPropsInList);
	DisplayStepCount("ActiveCount",CommaFmt(LastCount));

	DisplayStatus("");
	
	if (hasSearchRestarted()) return; //Abort;
	if(!isSingleStep) DoStep("Active"); // Continue to next step
	else DoStep('Done');
}

function StepActiveAggCallBack(Data)
{ // SearchAggregate Callback
	if (hasSearchRestarted()) return;
	PropMapData = Data;
	if(!isSingleStep) DoStep("Pending"); // Continue to next step
	else DoStep('Done');
}

function StepSoldAggCallBack(Data)
{ // SearchAggregate Callback
	if (hasSearchRestarted()) return;
	PropMapSoldData = Data;
	DisplayStepCount("SoldCount",CountProps(Data));
	if(!isSingleStep) DoStep("OffMkt"); // Continue to next step
	else DoStep('Done');
}

function StepSoldCallBack(Data)
{
	if (hasSearchRestarted()) return;
	PropMapSoldData = Data;
	DisplayStepCount("SoldCount",CountProps(Data));
	if(!isSingleStep) DoStep("OffMkt");
	else DoStep('Done');
}	

function StepOffMktAggCallBack(Data)
{ // SearchAggregate Callback
	if (hasSearchRestarted()) return;
	PropMapOffMktData = Data;
	DisplayStepCount("OffMktCount",CountProps(Data));
	if(!isSingleStep) DoStep("ShortSale"); // Continue to next step
	else DoStep('Done');
}

function StepPendingAggCallBack(Data)
{ // SearchAggregate Callback
	if (hasSearchRestarted()) return;
	PropMapPendingData = Data;
	DisplayStepCount("PendingCount",CountProps(Data));
	if(!isSingleStep) DoStep("Sold"); // Continue to next step
	else DoStep('Done');
}
/*
function StepActiveCallBack(Data)
{
		PropMapData = Data;
		//Added from HHI to create the SelectedProp Array
		SelectedProp = new Array();
		for (i = 0; i < Data.length; i++) SelectedProp[i] = false;
		
	DisplayStepCount("ActiveCount",CountProps(Data));
	StepGetActiveListCallBack(Data); 
}
*/

function StepGetActiveListCallBack(Data)
{ // SearchProperty Callback
	if (hasSearchRestarted()) return;
	PropListData = Data;
	if(!isSingleStep) DoStep("GetPendingList"); // Continue to next step
	else DoStep('Done');
}
function StepGetPendingListCallBack(Data)
{ // SearchProperty Callback
	if (hasSearchRestarted()) return;
	if (PropListData) PropListData = PropListData.concat(Data);	else PropListData = Data;
	if(!isSingleStep) DoStep("GetSoldList"); // Continue to next step
	else DoStep('Done');
}
function StepGetSoldListCallBack(Data)
{ // SearchProperty Callback
	if (hasSearchRestarted()) return;
	if (PropListData) PropListData = PropListData.concat(Data);	else PropListData = Data;
	if(!isSingleStep) DoStep("GetOffMktList"); // Continue to next step
	else DoStep('Done');
}
function StepGetOffMktListCallBack(Data)
{ // SearchProperty Callback
	if (hasSearchRestarted()) return;
//	PropListOffMktData = Data;
	if (PropListData) PropListData = PropListData.concat(Data);	else PropListData = Data;

	if(!isSingleStep) DoStep("SummarizeList"); // Continue to next step
	else DoStep('Done');
}



function CountProps(Data){
	// return the number of property in aggregate pins
	var Count = 0;
	for(var i=0; i<Data.length; i++){
		var Prop = (Data[i]+"\n\n\n").split("\n");
		var Type=Prop[2];	
		var N = 1;
		if("AGGREGATE"==Type) N=parseInt(Prop[3],10); 
		Count +=N;
	}
	return CommaFmt(Count);
}

function DisplayStepCount(id,N){
	if (isFrameReady("MenuFrame.DisplayStepCount")) { MenuFrame.DisplayStepCount(id, N) };
	var NewVal = "" + N;
	NewVal = CommaFmt(NewVal.replace(",", ""));
	eval("Last" + id + "='" + NewVal + "'");
}

function StepShortSaleCallBack(Data)
{
	PropMapShortSaleData = Data;
	DisplayStepCount("ShortSaleCount",CountProps(Data));
	if (hasSearchRestarted()) return;
	if(!isSingleStep) DoStep("Foreclosure");
	else DoStep('Done');
}
function StepForeclosureCallBack(Data)
{
	PropMapForeclosureData = Data;
	DisplayStepCount("ForeclosureCount",CountProps(Data));
	if (hasSearchRestarted()) return;
	if(!isSingleStep) DoStep("REO");
	else DoStep('Done');
}

function StepREOCallBack(Data)
{
	PropMapREOData = Data;
	DisplayStepCount("REOCount",CountProps(Data));
	if (hasSearchRestarted()) return;
	if(!isSingleStep) DoStep('GetActiveList');
	DoStep("Done");
}


function MarketTrendsCallBack(Data){
		PropTrendsData = Data;
		isSearching = false;
		if(isFrameReady("MenuFrame.DataRefresh")) setTimeout("MenuFrame.DataRefresh()",50);
		DisplayStatus("");
}


function hasSearchRestarted(){
	// if the search has been aborted and restarted (Criteria changed in middle) then return true and queue up a restart
	if (!isRedoSearch) return false
	isRedoSearch = false;
	isSearching= false;
	DisplayStatus(PropSearchMsg_SearchRestarted)
	setTimeout("PropSearch()",200);
	return true
}


function ShowDetailFrame(URL)
{
	// Have to wait for the unload event to finish (The unload is needed so that the back button works)
	HideDetailFrame()
	setTimeout("ShowDetailFrame2('" + URL + "')",100)
}

function ShowDetailFrame2(URL) {
	if (!oContent) {
		var whnd = window.open(URL);
		return; // SND community pages
	}
	oContent.style.display = "none";
	oDetail.style.display = "block";
	// The .replace version means the back button goes back to the home page instead of the list
	//DetailFrame.location.replace(URL);
	DetailFrame.location.href=URL;
}

function HideDetailFrame()
{
	if(!oDetail) return;
	oDetail.style.display = "none";
	if (!oContent) return;
	oContent.style.display = "block";
	//if (-1==DetailFrame.location.href.indexOf("Loading.html"))	
	DetailFrame.location.replace(FullURL("Loading.html"));

	var obtnBack = $get("btnBack"); if (obtnBack) obtnBack.style.display="none";
	// if MiniMap style, (ala HHI) need to show map
	if ($get("divMap"))	$get("divMap").style.display="block";
	// refresh display so checkmarks get registered
	if (isFrameReady("ContentFrame.DataRefresh")) ContentFrame.DataRefresh();
}


function DisplayMsg(Text){
	var oTD = $get("tdFeedBack")
	if (oTD) oTD.innerHTML = Text;
	var oTD =  $get("tdFeedBackFCIQ")
	if (oTD) oTD.innerHTML = Text+ "&nbsp;";
	
}
function DisplayStatus(Text){
	var oFld = $get("tdStatus")
	if (oFld) oFld.innerHTML = Text;
	var oTD =  $get("tdStatusFCIQ")
	if (oTD) oTD.innerHTML = Text + "&nbsp;";
}

function DisplayPOIStatus(text)
{
		if (isFrameReady("MenuFrame.DisplayPOIMsg")) MenuFrame.DisplayPOIMsg(text);
		
}
				

function PrintDetail(){
	ContentFrame.print();
}

function Overlay(Name,Value){
	switch(Name){
	case "POI":	POI_Type = Value;	break;
	case "Boundaries": Boundaries_Type = Value; break;
	case "Demographics": Demographics_Type=Value; 
				$get("PropMarketLegend").style.display="none";
				$get("DemographicsLegend").style.display="none";

				switch(Value){
				case "": break;
				case "PROP": $get("PropMarketLegend").style.display="block"; break;
				default: $get("DemographicsLegend").style.display="block"; break;
				}
	
	break;
	default: alert("Missing Overlay handler: " + Name); return;
	}	
	if(isFrameReady("ContentFrame.POIUpdate"))ContentFrame.POIUpdate();
	
}

function Toggle(oThis){
	var ID = oThis.id;
	var oCtrl = $get(ID + "Detail")
	var oImg = $get(ID + "Image")
	var oTxt = $get(ID + "Text")
	if (0 < oImg.src.indexOf("_Dn.gif")){
		oImg.src = oImg.src.replace("Dn.gif","Up.gif")
		oCtrl.style.display = "block" 
		//oTxt.innerText = oTxt.innerText.replace("Show", "Hide");
	} else {
		oImg.src = oImg.src.replace("Up.gif","Dn.gif")
		oCtrl.style.display = "none" 
		//oTxt.innerText = oTxt.innerText.replace("Hide", "Show");
	}
}


function RecenterMap(){
	// Figure out how to Pan and Zoom Map so that all existing points from the property list are visible
	DoStep("Recenter");
}

function RecenterMapCallBack(Res){
		if(!Res.isValid) return;
		if(isFrameReady("ContentFrame.CenterOnRegion"))	
		{
			ContentFrame.CenterOnRegion(Res.Lat,Res.Lon,Res.MaxLat,Res.MinLon,Res.MinLat,Res.MaxLon);
		}
}


function SimpleSearch(isCountOnly){
	if (isSearching){
		isRedoSearch = true;
		return; // don't jam up with multiple searches at once.
	}
	isSearching=true;
	PropMapData = null;
	PropListData = null;
	LastFavType="";

	DisplayMsg("");
	DisplayStatus(PropSearchMsg_Searching);
	if (oVEMap) oVEMap.DeleteAllShapes();

	MapCoord = 89,-180,-89,180
	MapZoom = 0

	if (isCountOnly) {
		MyAjaxService.PropertySearchCount(new SearchCriteria('A'), false, SimpleSearchCountOnlyCallBack, FailedCallback); 			
	} else {
		MyAjaxService.PropertySearchCount(new SearchCriteria('A'), false, SimpleSearchCountCallBack, FailedCallback);
	}	
}

function SimpleSearchCountOnlyCallBack(result) {
	LastSearchCountTxt = result
		var aCount = (result + ".").split(".");
		var MapCount = CommaFmt(parseInt(aCount[0]));
		var Count = parseInt(aCount[0]);
		TotalCount = CommaFmt(parseInt(aCount[1]));
		DisplayMsg(TotalCount + " " + PropSearchMsg_Matches + " ");
		isSearching = false;
		DisplayStatus("");
}


function SimpleSearchCountCallBack(result){
	LastSearchCountTxt = result 
	var aCount = (result+".").split(".");
	var MapCount = CommaFmt(parseInt(aCount[0]));
	var Count = parseInt(aCount[0]);
	if (isNaN(Count)) Count = MaxPropsInList;
	TotalCount = CommaFmt(aCount[1]);
	DisplayMsg( TotalCount + " " + PropSearchMsg_Matches + " ");
	DisplayStatus(PropSearchMsg_RetrievingMatches);
	
	// Abort and start over
	if (isRedoSearch) {
		isRedoSearch = false;
		isSearching= false;
		PropSearch();
	}
	
	// Do real search; and display list of property. If too many property 
	
	isDataOverflow = (Count>MaxPropsInList)
	var N = Math.min(MaxPropsInList,Count);

	MyAjaxService.PropertySearch(N, new SearchCriteria('A'), false, SimpleSearchCallBack, FailedCallback);
				
}

		
function SimpleSearchCallBack(Data){
	PropListData = Data;

	SelectedProp = new Array();
	for (i=0; i<Data.length; i++) SelectedProp[i] = false;
	if(isFrameReady("MenuFrame.DataRefresh")) setTimeout("MenuFrame.DataRefresh()",50);
	if (isFrameReady("ContentFrame.DataRefresh")) setTimeout("ContentFrame.DataRefresh()", 50);
	DisplayStatus("");
	isSearching = false;

	// If we didn't know the actual count (Because of a text search), we need to 
	// Update the status display ..but only if the count is known becuase it is less than MaxPropsInList
	var oTD = $get("tdFeedBack")
	if (!oTD) return;
	if (-1==oTD.innerText.indexOf ("??")) return;
	if (MaxPropsInList == Data.length) return;
	DisplayMsg(Data.length + " " + PropSearchMsg_Matches + " ");
	
}


function FindOnMapSearch(Lat, Lon, Title)
{

	var Latitude = parseFloat(Lat);
	var Longitude = parseFloat(Lon);
	
	if (isNaN(Latitude)) return;
	if (isNaN(Longitude)) return;	


		// If we have a little VE map, add a pushpin for the current location. (HHI & MIBOR)
		if (oVEMap)
		{
			oVEMap.DeleteAllShapes();
			var Point = new VELatLong(Latitude, Longitude);
			var PushPin = new VEShape(VEShapeType.Pushpin, Point);
			PushPin.SetTitle(Title);
			PushPin.SetCustomIcon("<img src='../../Icons/Pin_Red_Small.gif' border='0' />");
			oVEMap.AddShape(PushPin);
			oVEMap.SetCenter(Point);
			return;
		}		


	if (isFrameReady("MenuFrame.CenterSmallMap"))
	{
		MenuFrame.CenterSmallMap(Latitude,Longitude)		
		return;
	}
	if (isListView) return; // No map
	
	
	if (isFrameReady("ContentFrame.FindLocation")) // DFW, for example
	{
		HideDetailFrame();
		isMapMoveable = (CurrentTab=="Favorites");
		ContentFrame.FindLocation(Title,Latitude,Longitude,isMapMoveable);
		return;	
	}
			
	if (isFrameReady("ContentFrame.FindLocation"))
	{ // MFR & LAS style
		if (parent.HideDetailFrame)	parent.HideDetailFrame(); 
		isMapMoveable = (parent.IgnoreMapView)? true: false;
		parent.ContentFrame.FindLocation(Title,Latitude,Longitude,isMapMoveable);
		return;
	}
	ContentFrame.location.href=CreateNoCookieURL("propmap.aspx");	
	
}

function GoBackToMap()
{
	HideDetailFrame();
}

function ShowBackToMap()
{
	$get("btnBack").style.display="block";
}

function ShowMap(){
	// Show Big map not little VE map
	HideDetailFrame();
	
	switch (Site){
	case "INR" : oContent.src=CreateNoCookieURL("PropMapMIBOR.aspx"); break;
	case "HHI": if (isListView) oContent.src = CreateNoCookieURL("PropMapHHI.aspx");
		else oContent.src = CreateNoCookieURL("PropMap.aspx");
		break;
	default: oContent.src=CreateNoCookieURL("PropMap.aspx");	
	break;
	}

	$get("divMap").style.display="none";
}


function FavoriteSearch(FavType){
	if (isSearching) {
			setTimeout("FavoriteSearch('" + FavType + "')",1000);
			return; // don't jam up with multiple searches at once.
	}
	if (LastFavType == FavType) return;	

	PropData = null;
	PropMapData = null;
	
	SelectedProp=null;
	isDataOverflow=false;
	LastFavType = FavType;	
	isSearching=true;

	if (isFrameReady("MenuFrame.DataClear")) MenuFrame.DataClear();
	if (isFrameReady("ContentFrame.DataClear")) ContentFrame.DataClear();
	DisplayStatus(Translate("Seaching Favorites...","Recherche des favoris..."));
		
	if (FavType=="F") DisplayMsg(Translate("Displaying Favorites","Affichage des Favoris"));
	if (FavType=="V") DisplayMsg(Translate("Displaying Recently Viewed","Affichage des Inscriptions Récemment Consultées"));
		
	var Max = 100;
	var EncryptID = $get("hEncryptedVisitorID").value
	MyAjaxService.MyFavoritesSearch(
			Max,
			EncryptID, 
			FavType,
			Priority,
			FavoriteSearchCallBack, 
			FailedCallback
	);
			
}

function FavoriteSearchCallBack(Data){
	PropListData = Data;
	PropMapData = Data;
	SelectedProp = new Array();
	for (i=0; i<Data.length; i++) SelectedProp[i] = false;
	
	LastSearchCountTxt = Data.length + "." + Data.length;
	DisplayStatus(Data.length + " " + PropSearchMsg_MatchesRetrieved + " ");
	if (Data.length == 0) DisplayMsg(Translate("No Matches Found","Aucun résultat"));

	if(isFrameReady("MenuFrame.DataRefresh")) setTimeout("MenuFrame.DataRefresh()",50);
	if(isFrameReady("ContentFrame.DataRefresh")) setTimeout("ContentFrame.DataRefresh()",50);
	isSearching=false;
	
}

function ShowInitMLSNum(Source,MLNum,SysID,Lat,Lon) {

	// Override the last map setting so that when the user returns to the map they are in the same neighborhood as this property
	var Rect = (parseFloat(Lat) + .004) + "," + (parseFloat(Lon) - .004) + "," + (parseFloat(Lat) - .004) + "," + (parseFloat(Lon) + .004)
	setTimeout("SaveMapView('" + Rect + "'," + Lat + "," + Lon + ",17)", 100); // Because ShowInitMLSNum executes before the default assignments.

	switch (Source) {
		case "FCIQ":
			LastShowMLSNumberURL = ComputePropDetailURL('Q', 0, 'FCIQ', SysID);
			break;
		case "COOP":
			LastShowMLSNumberURL = ComputePropDetailURL('C', 0, 'COOP', SysID);
			break;
		default: LastShowMLSNumberURL = ComputePropDetailURL('A', 0, Source, SysID);
			break;
		//setTimeout("ShowDetailFrame(ComputePropDetailURL('A', 0, Source, " + SysID + "))", 2000); break;
	}
}











		



