﻿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 isShortSaleSearch = false;
var isForeclosureSearch = false;
var isREOSearch = false;
var isTrends = false;

var PropMapData = null;
var PropMapSoldData = 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 = 500; // Each site could override this default value
var CurrentTab = "Map";

var SrchType = "";
var PropType = "";
var Beds = 0;
var Baths = 0;
var MinPrice = 10000;
var MaxPrice = 99999999;
var SqFtMin = 0;
var SqFtMax = 0;
var AcreMin = 0.0;
var AcreMax = 0.0;
var YrBuiltMin = 0;
var YrBuiltMax = 0;
var Pool = "";
var Garage = 0;
var Search1 = "";
var Search2 = "";
var Search3 = "";
var Search4 = "";
var Search5 = "";
var Search6 = "";
var Area = "";
var MLSArea = "";
var School = "";
var County = "";
var Address = "";
var OpenHouse = "";
var HasVirtualTour = "";
var HasPhoto = "";
var Priority = "";
var Source="";
var IDX = "";
var ShowParcels = false;
var FavType="V";

// 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 = null;
var Demographics_Type = null;
var ShowLabels = false;
var Overlays_Type = null;

var LastSearchCountTxt = "";
var LastCount = 0;
var EncryptID = null;

var Site = "";
var isDemo = false;
var isReady = false;

function Initialize(){
	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)
	{
	case "LAS":
	case "Demo":
		oContent.src =  CreateNoCookieURL("../PropMap.aspx");	
		oMenu.src = CreateNoCookieURL("SearchCriteria.aspx"); 
		break;	

	case "INR":
		oMenu.src = CreateNoCookieURL("SearchCriteria.aspx");
		if (IDX.length>0) { // IDX pages requested
			setTimeout("oContent.src = 'PropSummaryMIBOR.aspx?vidx="+$get("hEncryptedVisitorID")+"'",500) // 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 {
			oContent.src =  "PropMapMIBOR.aspx";
			setTimeout("MapLoad(39.8,-86.2,9)",50)
		}
		break;
		
		
	case "HHI" :
		oContent.src =  "PropMapHHI.aspx";	
		oMenu.src = CreateNoCookieURL("SearchCriteria.aspx"); 
		setTimeout("MapLoad(32.15,-80.8,11)",50);
	break;

	case "MFR":
	case "OKC":
	case "DFW":
		oContent.src =  CreateNoCookieURL("PropMap.aspx");
		// If user specified a area search from home page default to the list tab.		
		if (CurrentTab=="ShowList") ShowList();
		else	oMenu.src = CreateNoCookieURL(Site + "/SearchCriteria.aspx");	
		break;
	
//
	default: alert("Missing Site Code (PropertySearch.js):" + Site);
		break;
	}


	Resize();
	isReady = true;
	Search();

	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);
	oVEMap.SetCenterAndZoom(Pt,Zm);
	$get("divMap").style.display="none";
}

function Resize(){
	var h = Math.max(75,GetScreenHeight() - 75);
	var w = Math.min(GetScreenWidth()-100,350);
	var ContentWidth = GetScreenWidth()-(w+6);

	Site = $get("hSiteCode").value
	if (Site=="DFW")
	{
		h = GetScreenHeight();
		oMenu.style.top = "35px";
		oMenu.style.height = (h-35) + "px";
	}


	oContent.style.left = w + "px";	
	oContent.style.width = ContentWidth + "px";
	oContent.style.height = (h-6) + "px";

	oMenu.style.height = (h-33) + "px";
	oMenu.style.width = w + "px";

	oDetail.style.left = w + "px";	
	oDetail.style.height = (h-6) + "px";
	oDetail.style.width = ContentWidth + "px";

	var oNav = $get("divNav");
	oNav.style.width = w + "px";

	if(ContentFrame.Resize) ContentFrame.Resize(); // Trigger refresh of child frame.
	if(MenuFrame.Resize) MenuFrame.Resize(); // Trigger refresh of child frame.
	if(DetailFrame.Resize) DetailFrame.Resize(); // Trigger refresh of child frame.
	
	}

function SaveMapView(Rect, Lat, Lon, Zoom){
	MapCoord = Rect;
	MapCenterLat = Lat;
	MapCenterLon = Lon;
	MapZoom = Zoom;
	if (CurrentTab!="Favorites") Search();	
}    

function SetShowParcels(bool){
	ShowParcels = bool;
	if (bool)	ContentFrame.oVEMap.SetZoomLevel(18);
}

function ShowList(){
	CurrentTab = "List"
	HideDetailFrame()
	switch (Site){
	case "LAS" : 
	case "Demo": MenuFrame.location.href = CreateNoCookieURL("../PropPageList.aspx"); break; 
	// MFR, OKC, DFW
	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");
	var oImg1 = $get("SearchTab"); oImg1.src = oImg1.src.replace("-over", "-default");
	var oImg2 = $get("ListTab"); oImg2.src = oImg2.src.replace("-over", "-selected");
	var oImg3 = $get("FavoritesTab"); if (oImg3) oImg3.src = oImg3.src.replace("-over", "-default");
	var oImg3 = $get("FavoritesTab"); if (oImg3) oImg3.src = oImg3.src.replace("-selected", "-default");
	Search();
}

function ShowFavorites(){
	CurrentTab = "Favorites"
	// Do Favorites Search
	/// Show the PropPageList
	// Load Favorites Options into Detail frame.

	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("FavoritesTab");	if (oImg3) oImg3.src = oImg3.src.replace("-default", "-selected").replace("-over","-selected");
	MenuFrame.location.href = CreateNoCookieURL("PropPageList.aspx");

	//switch (Site){
	//case "DFW" : 
	//default: // MFR, OKC 
	//}
	ShowDetailFrame(CreateNoCookieURL("MyFavorites.aspx"));
	FavoriteSearch("V");

}

function ShowSearch(){
	CurrentTab = "Search"
	HideDetailFrame()
	switch (Site){
	case "LAS" : 
	case "Demo": 
		ContentFrame.location.href = CreateNoCookieURL("../PropMap.aspx"); 
		MenuFrame.location.href =  CreateNoCookieURL("SearchCriteria.aspx");	
		break;
		
	default: // MFR,OKC,DFW
		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("-over","-selected");
	var oImg1 = $get("SearchTab"); oImg1.src = oImg1.src.replace("-default","-selected");
	var oImg2 = $get("ListTab"); oImg2.src = oImg2.src.replace("-over","-default");
	var oImg2 = $get("ListTab"); oImg2.src = oImg2.src.replace("-selected","-default");
	var oImg3 = $get("FavoritesTab"); if (oImg3) oImg3.src = oImg3.src.replace("-over", "-default");
	var oImg3 = $get("FavoritesTab"); if (oImg3) oImg3.src = oImg3.src.replace("-selected", "-default");
}
 
    
function Search(){
	if (!isReady) return;
	if (isSearching){
		isRedoSearch = true;
		return; // don't jam up with multiple searches at once.
	}
	isSearching=true;
	
// Clear map and counts
	PropListData = null;
	PropMapData = null;
	PropMapSoldData = null;
	PropMapShortSaleData = null;
	PropMapForeclosureData = null;
	PropMapREOData = null;

	DisplayStepCount("ActiveCount","");			
	DisplayStepCount("SoldCount","");				
	DisplayStepCount("ShortSaleCount","");	
	DisplayStepCount("ForeclosureCount","");
	DisplayStepCount("REOCount","");				

	DisplayMsg("");
	isSingleStep = false; 
	if(ContentFrame && ContentFrame.DataRefresh)ContentFrame.DataRefresh('All');
	setTimeout("DoStep('Count')",50);
}



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 iSqFtMin = MakeInt(SqFtMin);
	var iSqFtMax = MakeInt(SqFtMax);
	var fAcreMin = MakeFloat(AcreMin);
	var fAcreMax = MakeFloat(AcreMax);
	var iYrBuiltMin = MakeInt(YrBuiltMin);
	var iYrBuiltMax = MakeInt(YrBuiltMax);
	
	
	switch(Name) {
	case "Recenter":
					MyAjaxService.PropertySearchRegion(Source,County,Address,Area,MLSArea,School,SrchType,PropType,iMinPrice,iMaxPrice,iBeds,iBaths,iSqFtMin,iSqFtMax,fAcreMin,fAcreMax,iYrBuiltMin,iYrBuiltMax,Pool,iGarage,Search1,Search2,Search3,Search4,Search5,Search6,OpenHouse,HasVirtualTour,HasPhoto,RecenterMapCallBack,FailedCallback); 					
					break;
	
	case "Count":	
					DisplayStatus("Searching...");
					//if (ContentFrame && ContentFrame.oVEMap_PropertyLayer) ContentFrame.oVEMap_PropertyLayer.DeleteAllShapes();
					if (MenuFrame && MenuFrame.DataClear) MenuFrame.DataClear(); // Clear list
					MyAjaxService.PropertySearchCount(EncryptID,MapCoord,iMapZoom,Source,County,Address,Area,MLSArea,School,SrchType,PropType,iMinPrice,iMaxPrice,iBeds,iBaths,iSqFtMin,iSqFtMax,fAcreMin,fAcreMax,iYrBuiltMin,iYrBuiltMax,Pool,iGarage,Search1,Search2,Search3,Search4,Search5,Search6,OpenHouse,HasVirtualTour,HasPhoto,"",StepCountCallBack,FailedCallback); 		
					break;
	
	
	case "Active":	
					DisplayStatus("Aggregating...");
					if (isActiveSearch)	{
										
					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.
						MyAjaxService.PropertySearchAggregate(LastCount,MaxPropsOnMap,CurrentTab,EncryptID,iMapZoom,MapCoord,Area,MLSArea,School,County,Address,SrchType,PropType,iMinPrice,iMaxPrice,iBeds,iBaths,iSqFtMin,iSqFtMax,fAcreMin,fAcreMax,iYrBuiltMin,iYrBuiltMax,Pool,Search1,Search2,Search3,Search4,Search5,Search6,OpenHouse,HasVirtualTour,HasPhoto,"A",Priority,StepActiveAggCallBack,FailedCallback);
					} else { // Get Actual Data
						// Do real search; and display list of property. Cut off list at 999 properties to save bandwidth 
						var N = Math.min(500,LastCount);
						MyAjaxService.PropertySearch(N,Source,CurrentTab,EncryptID,iMapZoom,MapCoord,County,Address,Area,MLSArea,School,SrchType,PropType,iMinPrice,iMaxPrice,iBeds,iBaths,iSqFtMin,iSqFtMax,fAcreMin,fAcreMax,iYrBuiltMin,iYrBuiltMax,Pool,iGarage,Search1,Search2,Search3,Search4,Search5,Search6,OpenHouse,HasVirtualTour,HasPhoto,"A",Priority,"",StepActiveCallBack,FailedCallback); 					
					}
					break;
					
					
					} else {
						DisplayStepCount("ActiveCount","-");
						if (isSingleStep) DoStep('Done');
						else setTimeout("DoStep('Sold')",50);
					}
					
					
	case "GetActiveList": 
					DisplayStatus("Retrieving...");
					var N = Math.min(MaxPropsInList,LastCount);
					MyAjaxService.PropertySearch(N,Source,CurrentTab,EncryptID,iMapZoom,MapCoord,County,Address,Area,MLSArea,School,SrchType,PropType,iMinPrice,iMaxPrice,iBeds,iBaths,iSqFtMin,iSqFtMax,fAcreMin,fAcreMax,iYrBuiltMin,iYrBuiltMax,Pool,iGarage,Search1,Search2,Search3,Search4,Search5,Search6,OpenHouse,HasVirtualTour,HasPhoto,"A",Priority,IDX,StepGetActiveListCallBack,FailedCallback); 	
					break;
	
	// Use same LastCount for active properties as an estimate for sold ones. 
	case "Sold":	
					DisplayStatus("Aggregating Solds...");
					if (isSoldSearch) {
					
//						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.
							MyAjaxService.PropertySearchAggregate(LastCount,MaxPropsOnMap,CurrentTab,EncryptID,iMapZoom,MapCoord,Area,MLSArea,School,County,Address,SrchType,PropType,iMinPrice,iMaxPrice,iBeds,iBaths,iSqFtMin,iSqFtMax,fAcreMin,fAcreMax,iYrBuiltMin,iYrBuiltMax,Pool,Search1,Search2,Search3,Search4,Search5,Search6,"",HasVirtualTour,HasPhoto,"S",Priority,StepSoldAggCallBack,FailedCallback);
//						} else { // Get Actual Data
							// Do real search; and display list of property. Cut off list at 999 properties to save bandwidth 
//							var N = Math.min(500,LastCount);
//							MyAjaxService.PropertySearch(N,Source,CurrentTab,EncryptID,iMapZoom,MapCoord,County,Address,Area,MLSArea,School,SrchType,PropType,iMinPrice,iMaxPrice,iBeds,iBaths,iSqFtMin,iSqFtMax,fAcreMin,fAcreMax,iYrBuiltMin,iYrBuiltMax,Pool,iGarage,Search1,Search2,Search3,Search4,Search5,Search6,"","",HasPhoto,"S",Priority,"",StepSoldCallBack,FailedCallback); 					
//						}
					}	else {
						DisplayStepCount("SoldCount","-");						
						if (isSingleStep) DoStep('Done');
						else setTimeout("DoStep('ShortSale')",50);
					}
					break;
					
	// Foreclosures
 	case "ShortSale":	
 					DisplayStatus("Searching Defaults...");
 					if (isShortSaleSearch) MyAjaxService.ForeclosureSearchAggregate(MaxPropsOnMap,iMapZoom,MapCoord,PropType,Area,iMinPrice,iMaxPrice,iBeds,iBaths,iSqFtMin,iSqFtMax,fAcreMin,fAcreMax,iYrBuiltMin,iYrBuiltMax,"D",StepShortSaleCallBack,FailedCallback);
					else {
						DisplayStepCount("ShortSaleCount","-");						
						if (isSingleStep) DoStep('Done');
						else setTimeout("DoStep('Foreclosure')",50);
					}
					break;

	// REO
 	case "Foreclosure":	
 					DisplayStatus("Searching Auctions...");
 					if (isForeclosureSearch) MyAjaxService.ForeclosureSearchAggregate(MaxPropsOnMap,iMapZoom,MapCoord,PropType,Area,iMinPrice,iMaxPrice,iBeds,iBaths,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":	
 					DisplayStatus("Searching Bank/REO...");
 					if (isREOSearch) MyAjaxService.ForeclosureSearchAggregate(MaxPropsOnMap,iMapZoom,MapCoord,PropType,Area,iMinPrice,iMaxPrice,iBeds,iBaths,iSqFtMin,iSqFtMax,fAcreMin,fAcreMax,iYrBuiltMin,iYrBuiltMax,"R",StepREOCallBack,FailedCallback);
					else  {
						DisplayStepCount("REOCount","-");						
						DoStep('Trends')
					}
					break;

	case "Trends":
 					DisplayStatus("Computing Market Trends...");
 					if (isTrends) MyAjaxService.PropertyTrends(MapCoord,Area,MLSArea,County,SrchType,PropType,MakeInt(MinPrice),MakeInt(MaxPrice),MakeInt(Beds),MakeInt(Baths),MakeInt(SqFt),MakeFloat(Acre),MakeInt(YrBuilt),Pool,Search1,Search2,Search3,Search4,Search5,Search6,OpenHouse,Priority,MarketTrendsCallBack,FailedCallback); 		
 					DoStep('Done')
					break;
	
	case "Done":	isSearching = false; // Done
					DisplayStatus("");
					break;
	
	default: alert("Missing Step Handler: " + Name); break;			
	}
}

function StepCountCallBack(Data)
{	// SearchCount Callback
	LastSearchCountTxt = Data;
	var aCount = (Data+".").split(".");
	var MapCount = CommaFmt(parseInt(aCount[0]));
	LastCount = parseInt(aCount[0]);
	var TotalCount = CommaFmt(parseInt(aCount[1]));
	DisplayMsg( TotalCount + " Matches; " + MapCount + " on Map");
	isDataOverflow = (LastCount>MaxPropsInList);
	DisplayStepCount("ActiveCount",MapCount);

	DisplayStatus("");
	
	if (hasSearchRestarted()) return; //Abort;
	if(!isSingleStep) DoStep("Active"); // Continue to next step
	else DoStep('Done');
}

function StepActiveAggCallBack(Data)
{ // SearchAggregate Callback
	PropMapData = Data;
	if (hasSearchRestarted()) return;
	if(!isSingleStep) DoStep("GetActiveList"); // Continue to next step
	else DoStep('Done');
}

function StepSoldAggCallBack(Data)
{ // SearchAggregate Callback
	PropMapSoldData = Data;
	DisplayStepCount("SoldCount",CountProps(Data));
	if (hasSearchRestarted()) return;
	if(!isSingleStep) DoStep("ShortSale"); // 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); // Skip Aggregation Step
}

function StepGetActiveListCallBack(Data)
{
  PropListData = Data;
	if (hasSearchRestarted()) return;

	// Compute Summary Statistics
	StatPriceCount = 0; StatPriceLabel=""; StatPriceLow = 99999999; 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<PropListData.length; 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(MenuFrame.DataRefresh) setTimeout("MenuFrame.DataRefresh()",50);
	if(!isSingleStep) DoStep("Sold");
	else DoStep('Done');
}

function StepSoldCallBack(Data)
{
	PropMapSoldData = Data;
	DisplayStepCount("SoldCount",CountProps(Data));
	if (hasSearchRestarted()) return;
	if(!isSingleStep) DoStep("ShortSale");
	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 (MenuFrame.DisplayStepCount) MenuFrame.DisplayStepCount(id,N);
}

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;
	DoStep("Done");
}


function MarketTrendsCallBack(Data){
		PropTrendsData = Data;
		isSearching = false;
		if(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("Search Restarted")
	setTimeout("Search()",100);
	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 + "')",50)
}
function ShowDetailFrame2(URL)
{
			oDetail.src = URL;
			oDetail.style.display = "block";
			oContent.style.display = "none";
}

function HideDetailFrame()
{
			oDetail.style.display = "none";
			oContent.style.display = "block";
			if (-1==oDetail.src.indexOf("Loading.html"))	oDetail.src = FullURL("Loading.html");
			// if MiniMap style, (ala HHI) need to show map
			if ($get("divMap"))	$get("divMap").style.display="block";
			// refresh display so checkmarks get registered
			if (ContentFrame.DataRefresh) ContentFrame.DataRefresh(); 			
}


function DisplayMsg(Text){
	$get("tdFeedBack").innerHTML = Text;
}
function DisplayStatus(Text){
	$get("tdStatus").innerHTML = 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);
	}		
}

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(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

	DisplayMsg("");
	DisplayStatus("Searching...");
	if (oVEMap) oVEMap.DeleteAllShapes();

	if (isCountOnly) {
	    MyAjaxService.PropertySearchCount(
				EncryptID,
				"",
				MakeInt(MapZoom),
				Site,
				County,
				Address,
				Area,
				MLSArea,
				School,
				SrchType,
				PropType,
				MakeInt(MinPrice),
				MakeInt(MaxPrice),
				MakeInt(Beds),
				MakeInt(Baths),
				MakeInt(SqFtMin),
				MakeInt(SqFtMax),
				MakeFloat(AcreMin),
				MakeFloat(AcreMax),
				MakeInt(YrBuiltMin),
				MakeInt(YrBuiltMax),
				Pool,
				MakeInt(Garage),
				Search1,Search2,Search3,Search4,Search5,Search6,
				OpenHouse,
				HasVirtualTour,
				HasPhoto,
				IDX,
				SimpleSearchCountOnlyCallBack,
				FailedCallback
	        );
	} else {
	    MyAjaxService.PropertySearchCount(
				EncryptID,
				"",
				MakeInt(MapZoom),
				Site,
				County,
				Address,
				Area,
				MLSArea,
				School,
				SrchType,
				PropType,
				MakeInt(MinPrice),
				MakeInt(MaxPrice),
				MakeInt(Beds),
				MakeInt(Baths),
				MakeInt(SqFtMin),
				MakeInt(SqFtMax),
				MakeFloat(AcreMin),
				MakeFloat(AcreMax),
				MakeInt(YrBuiltMin),
				MakeInt(YrBuiltMax),
				Pool,
				MakeInt(Garage),
				Search1,Search2,Search3,Search4,Search5,Search6,
				OpenHouse,
				HasVirtualTour,
				HasPhoto,
				IDX,
				SimpleSearchCountCallBack,
				FailedCallback
	    );
	}	
}

function SimpleSearchCountOnlyCallBack(result) {
    LastSearchCountTxt = result
    var aCount = (result + ".").split(".");
    var MapCount = CommaFmt(parseInt(aCount[0]));
    var Count = parseInt(aCount[0]);
    var TotalCount = CommaFmt(parseInt(aCount[1]));
    DisplayMsg(TotalCount + " Matches ");
    isSearching = false;
    DisplayStatus("");
}




function SimpleSearchCountCallBack(result){
	LastSearchCountTxt = result 
	var aCount = (result+".").split(".");
	var MapCount = CommaFmt(parseInt(aCount[0]));
	var Count = parseInt(aCount[0]);
	var TotalCount = CommaFmt(parseInt(aCount[1]));
	DisplayMsg( TotalCount + " Matches ");
	DisplayStatus("Retrieving Matches...");
	
	// Abort and start over
	if (isRedoSearch) {
		isRedoSearch = false;
		isSearching= false;
		Search();
	}
	
	// Do real search; and display list of property. If too many property 
	
	isDataOverflow = (Count>MaxPropsInList)
	var N = Math.min(MaxPropsInList,Count);
	MyAjaxService.PropertySearch(
				N,
				Site,
				"List",
				EncryptID,
				MakeInt(MapZoom),				
				"",
				County,
				Address,
				Area,
				MLSArea,
				School,
				SrchType,
				PropType, 
				MakeInt(MinPrice), 
				MakeInt(MaxPrice), 
				MakeInt(Beds), 
				MakeInt(Baths), 
				MakeInt(SqFtMin), 
				MakeInt(SqFtMax), 
				MakeFloat(AcreMin), 
				MakeFloat(AcreMax), 
				MakeInt(YrBuiltMin), 
				MakeInt(YrBuiltMax), 
				Pool,
				MakeInt(Garage),
				Search1,Search2,Search3,Search4,Search5,Search6,
				OpenHouse,
				HasVirtualTour,
				HasPhoto,
				"A", 
				Priority,
				IDX,
				SimpleSearchCallBack, 
				FailedCallback
		); 					
				
}


		
function SimpleSearchCallBack(Data){
	PropListData = Data;
	SelectedProp = new Array();
	for (i=0; i<Data.length; i++) SelectedProp[i] = false;
	if(MenuFrame.DataRefresh) setTimeout("MenuFrame.DataRefresh()",50);
	if(ContentFrame.DataRefresh) setTimeout("ContentFrame.DataRefresh()",50);
	DisplayStatus("");
	isSearching=false;
}

function FindOnMapSearch(Lat, Lon, Title)
{

	var Latitude = parseFloat(Lat);
	var Longitude = parseFloat(Lon);
	
	if (isNaN(Latitude)) return;
	if (isNaN(Longitude)) return;	

	switch (Site){
	case "HHI":
	case "INR" : 
		// If we have a little VE map, add a pushpin for the current location. 
		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);
		break;		

	default: 
			if (ContentFrame.FindLocation) // DFW, for example
			{
				HideDetailFrame();
				isMapMoveable = (CurrentTab=="Favorites");
				ContentFrame.FindLocation(Title,Latitude,Longitude,isMapMoveable);
				return false;	
			}
			
			
			if (parent.ContentFrame.FindLocation) 
			{ // MFR & LAS style
				if (parent.HideDetailFrame)	parent.HideDetailFrame(); 
				isMapMoveable = (parent.IgnoreMapView)? true: false;
				parent.ContentFrame.FindLocation(Title,Latitude,Longitude,isMapMoveable);
				return false;
			}
			parent.ContentFrame.location.href=CreateNoCookieURL("propmap.aspx");	
		break;		
	}

}

function ShowMap(){
	// Show Big map not little VE map
	HideDetailFrame();
	
	switch (Site){
	case "INR" : oContent.src=CreateNoCookieURL("PropMapMIBOR.aspx"); break;
	case "HHI" : oContent.src=CreateNoCookieURL("PropMapHHI.aspx"); break;
	default: oContent.src=CreateNoCookieURL("PropMap.aspx");	break;
	}

	$get("divMap").style.display="none";
}




function FavoriteSearch(FavType){
	PropData = null;
	SelectedProp=null;	
	if (isSearching) return; // don't jam up with multiple searches at once.

	if (MenuFrame && MenuFrame.DataClear) MenuFrame.DataClear();
	if (ContentFrame && ContentFrame.DataClear) ContentFrame.DataClear();
	DisplayStatus("Searching Favorites...");
	if (FavType=="F") DisplayMsg("Displaying Favorites");
	if (FavType=="V") DisplayMsg("Displaying Recently Viewed");
	
	var Max = 100;
	var EncryptID = $get("hEncryptedVisitorID").value
	isSearching=true;
	MyAjaxService.MyFavoritesSearch(
			Max,
			EncryptID, 
			FavType,
			SimpleSearchCallBack, 
			FailedCallback
	);
			
}












		


