﻿var oVEMap = null;
var oVEMapLayer = null;
var oVEMap_BoundariesLayer = null;
var oVEMap_MarkerLayer = null;

var oMap = null;
var oDetail = null;
var PropData = null;
var SoldPrices = new Array();
var ActivePrices = new Array();
var isSearching = false;
var MapCoord = "";
var wasWarned = false;

function Initialize(){
	oMap = $get("divMap");
	oDetail = $get("Detail");
	Resize();
	window.onresize = Resize; 
	setTimeout("LoadMap()",200);
}

function LoadMap(){

	oVEMap = new VEMap("divMap");
	oVEMapLayer=new VEShapeLayer();
	oVEMap_BoundariesLayer=new VEShapeLayer();
	oVEMap_MarkerLayer=new VEShapeLayer();

	oVEMap.LoadMap(null,19,"s",false,1,true);
	oVEMap.SetDashboardSize(VEDashboardSize.Small); // Small, Tiny
	if ((GetScreenWidth()>900) && (GetScreenHeight()>600)) oVEMap.ShowMiniMap();
	else oVEMap.HideMiniMap();
	oVEMap.AddShapeLayer(oVEMapLayer);
	oVEMap.AddShapeLayer(oVEMap_MarkerLayer);

	// Return user to same place on the map as last time
	MapZoom = parseInt($get("hMapZoom").value);
	MapCoord = $get("hMapCoord").value;
	var aMap = MapCoord.split(",")
	MapCenterLat = .5 * (MakeFloat(aMap[0]) + MakeFloat(aMap[2]));
	MapCenterLon = .5 * (MakeFloat(aMap[1]) + MakeFloat(aMap[3]));
	if (MapZoom > 0) {
			if (parent.MapCenterLat) MapCenterLat = parent.MapCenterLat;
			if (parent.MapCenterLon) MapCenterLon = parent.MapCenterLon;
			LastCenter = new VELatLong(MapCenterLat, MapCenterLon);
			oVEMap.SetCenterAndZoom(LastCenter,MapZoom);
	} 
	oVEMap.AttachEvent("onchangeview", UpdateView);
	oVEMap.AttachEvent("onclick", ShowPropDetail);
	oVEMap.HideMiniMap();
	DoCMA();	
}

function UpdateView() {
	var View = oVEMap.GetMapView();
	MapCoord = View.TopLeftLatLong +","+View.BottomRightLatLong
	Search();
}

function Resize(){
	
	var W = (GetScreenWidth() - 205);
	var H = GetScreenHeight() - 80;
	oMap.style.width = W + "px";
	oMap.style.height = H + "px";

	var imgHouse = $get("bgHouse")
	if (imgHouse)imgHouse.style.top = (H-126) + "px";

	oDetail.style.width = (W-3) + "px";
	oDetail.style.height = (H-3) + "px";
	

	var oMenu = $get("Menu");
	oMenu.style.height = H + "px";
	
	if (oVEMap != null)  Search();
}


function DoCMA(){

	oVEMap.DeleteAllShapes();
	oVEMapLayer.DeleteAllShapes();
	var Address = $get("txtSubjAddress").value;
	var CityState = $get("txtSubjCity").value;
	var Zipcode = $get("txtSubjZipcode").value;
	var CurrentAddr = Address + " " + CityState + " " + Zipcode
	// If Address provide, center on coordinates, zoom to level 17 and then call property search. 
	var Type = null;
	var index = 0;
	var NumPts = 20;
	if ((Address+CityState+Zipcode).length==0) Search();
	else	oVEMap.Find("", CurrentAddr, Type, null, index, NumPts, true, true, true, null, AddAddrPushPinCallBack);
}	
	
	
function AddAddrPushPinCallBack(oVEShapeLayer, oVEFindResult, oVEPlace, bHasMore, e){
	if(null==oVEPlace) return;
	if (0==oVEPlace.length) return;
			
	var Lat = oVEPlace[0].LatLong.Latitude;
	var Lon = oVEPlace[0].LatLong.Longitude;
	var Point = new VELatLong(Lat,Lon);
			
	var shape = new VEShape(VEShapeType.Pushpin, Point)
	shape.SetCustomIcon("<img src='../Icons/Pin_Red_Small.gif' />");
	var Addr=oVEPlace[0].Name; 
	shape.SetTitle("<div><B>" + Addr + "</B></div>");	
	oVEMap.AddShape(shape);
	oVEMap.SetCenter(Point);
	Search();	
}	
	
	
function Search(){

	// Put up aggregate pushpins for up to 50 points closest to center of matching solds and actives
	// 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.
	if (isSearching) return; // don't jam up with multiple searches at once.
	isSearching = true;

	var Max = 50;
	var PropType = $get("ddlType").value;
 	var Beds = $get("ddlBeds").selectedIndex;
	var BathsF = $get("ddlFullBaths").selectedIndex;
	var BathsP = $get("ddlPBaths").selectedIndex;
	var SqFt = GetIntField($get("txtSqFt"));
	var VisitorID = $get("hEncryptedVisitorID").value
	var Address = $get("txtSubjAddress").value;
	var CityState = $get("txtSubjCity").value;
	var Zipcode = $get("txtSubjZipcode").value;
	MyAjaxService.PropertySearchValueYourHomeAggregate(
				Max,
				'S',
				VisitorID,
				MapCoord,
				PropType,
				Address,
				CityState,
				Zipcode, 
				Beds, 
				BathsF, 
				BathsP, 
				SqFt, 
				SoldCallBack, 
				FailedCallback
		); 					
	
	}

		
function SoldCallBack(Data){
	PropMapData = Data;
	oVEMapLayer.DeleteAllShapes();
	SoldPrices = new Array();
	DOM = new Array();
	for (var Num=0; Num<PropMapData.length; Num++) { 
			var NewProp = new PropInfoValueYourHome(Num);

			if (NewProp.isValid){
				var Point = new VELatLong(NewProp.Lat, NewProp.Lon);
				var PushPin = new VEShape(VEShapeType.Pushpin, Point);
				if (NewProp.isAggregate) { // zipcode aggregate marker
					var Name = NewProp.Area.replace("'","")
					Name = Name.replace("Zipcode","Zip Code")
					var MoreInfo=NewProp.Qty 
					PushPin.SetTitle(NewProp.Qty + " Recent Solds in " + Name)
					PushPin.SetCustomIcon("<div class='PushPinStyleBigRed'>" + NewProp.Qty + "</div>")
					var MoreInfo = "<div>Average price: " + NewProp.Price;
					MoreInfo += "<br>Average SqFt: " + NewProp.SqFt;
					//MoreInfo += "<br><input type='checkbox' title='Uncheck if this is not a comparable home. The Statistics will be updated.' ";
					//MoreInfo += "onclick='Recalc(this)' id='ckProp" + Num + "' count='" + NewProp.Qty + "' checked='checked' value='" ;
					//MoreInfo += NewProp.Price.replace(",","").replace("$","") ;
					//MoreInfo += "'>Include in Statistics?";
					for (var i=0; i<NewProp.Qty; i++){
						SoldPrices.push(NewProp.LP);					
						DOM.push(NewProp.DOM);
					}
					PushPin.SetDescription("<div>" + MoreInfo + "</div>")							
					PushPin.SetMoreInfoURL("NaN," + NewProp.Lat + "," + NewProp.Lon);

				} else { // Actual property
					PushPin.SetTitle(NewProp.Desc);
					var MoreInfo="Sold " + NewProp.ClosedDate + " for " + NewProp.Price 
					MoreInfo += "<br>" + NewProp.Beds + " Bedrooms, "; 
					if (NewProp.SqFt>0) MoreInfo += NewProp.SqFt + " SqFt";
					MoreInfo += "<br>" + NewProp.BathsFull + " Full";
					if (NewProp.BathsPartial>0) MoreInfo += ", " + NewProp.BathsPartial + " Partial"
					MoreInfo += " Baths"
					//MoreInfo += "<br><input type='checkbox' title='Uncheck if this is not a comparable home. The Statistics will be updated.' "
					//MoreInfo += "onclick='Recalc(this)' id='ckProp" + Num + "' count='1' checked='checked' value='" 
					//MoreInfo += NewProp.Price.replace(",","").replace("$","") 
					//MoreInfo += "'>Include in Statistics?"
					SoldPrices.push(MakeInt(NewProp.Price));
					DOM.push(NewProp.DOM);
					MoreInfo += "<br><img src='http://" + NewProp.PhotoURL + "' width='200'/>"
					PushPin.SetDescription("<div>" + MoreInfo + "</div>")
					PushPin.SetMoreInfoURL(Num + "," + NewProp.Source + "," + NewProp.SysID);
					PushPin.SetCustomIcon("<div class='PushPinStyleRed'>1</div>")
				}
				oVEMapLayer.AddShape(PushPin);	
			} //else alert("Not Valid")// skip it if it isn't valid
	}

	SoldPrices=SoldPrices.sort(numOrdA);
	DOM = DOM.sort(numOrdA);
	var N = SoldPrices.length;
	if (N>0){
		var Sum = 0;	for (var i=0; i<N; i++) {Sum+= SoldPrices[i];}
		var n1 = Math.floor(N/2.0);
		var n2 = Math.ceil((N-1)/2.0);
		$get("tdSCount").innerText = N;
		$get("tdSRangeLow").innerText = "$"+CommaFmt(SoldPrices[0]);
		$get("tdSRangeHigh").innerText = "$"+CommaFmt(SoldPrices[N-1]);
		$get("tdSMedian").innerText = "$"+CommaFmt(Math.round((SoldPrices[n1]+ SoldPrices[n2])/2.0));
		$get("tdSAverage").innerText = "$"+CommaFmt(Math.round(Sum/N));
		//$get("tdDOM").innerText = Math.round((DOM[n1]+ DOM[n2])/2.0);
	} else {
		$get("tdSCount").innerText = N;
		$get("tdSRangeLow").innerText = "";
		$get("tdSRangeHigh").innerText = "";
		$get("tdSMedian").innerText = "";
		$get("tdSAverage").innerText = "";
		//$get("tdDOM").innerText = ""	
		if (!wasWarned) {
			alert("No Sold listings found in this area that match your property. Try zooming out to search a larger area or leave your beds and baths zero so more properties match.")
			wasWarned = true;
		}

	}
		
	var Max = 25;
	var PropType = $get("ddlType").value;
 	var Beds = $get("ddlBeds").selectedIndex;
	var BathsF = $get("ddlFullBaths").selectedIndex;
	var BathsP = $get("ddlPBaths").selectedIndex;
	var SqFt = GetIntField($get("txtSqFt"));
	var VisitorID = $get("hEncryptedVisitorID").value
	var Address = $get("txtSubjAddress").value;
	var CityState = $get("txtSubjCity").value;
	var Zipcode = $get("txtSubjZipcode").value;

	MyAjaxService.PropertySearchValueYourHomeAggregate(
				Max,
				'A',
				VisitorID,
				MapCoord,
				PropType,
				Address,
				CityState,
				Zipcode, 
				Beds, 
				BathsF, 
				BathsP, 
				SqFt, 
				ActiveCallBack, 
				FailedCallback
		); 					

}


function ActiveCallBack(Data){
	ActivePrices = new Array();
	PropMapData = Data
	for (var Num=0; Num<PropMapData.length; Num++) { 
			var NewProp = new PropInfoValueYourHome(Num);

			if (NewProp.isValid){
				var Point = new VELatLong(NewProp.Lat, NewProp.Lon);
				
				var PushPin = new VEShape(VEShapeType.Pushpin, Point);
				if (NewProp.isAggregate) { // zipcode aggregate marker
					for (var i=0; i<NewProp.Qty; i++)ActivePrices.push(NewProp.LP);					
					var Name = NewProp.Area.replace("'","")
					Name = Name.replace("Zipcode","Zip Code")
					var MoreInfo=NewProp.Qty 
					var T =NewProp.Qty + " Properties for Sale in " + Name;
					if (NewProp.Qty==1) T.replace("Properties","Property"); 
					PushPin.SetTitle(T);
					PushPin.SetCustomIcon("<div class='PushPinStyleBig'>" + NewProp.Qty + "</div>")
					PushPin.SetDescription("<div>Average Price: " + NewProp.Price 
					+ "<br>Average Size: " + NewProp.SqFt + " sqft" 
					+ "<br>Average Bedrooms: " + NewProp.Beds 
					+ "<br>Average Full Baths: " + NewProp.BathsFull 
					+ "<br>Average Partial Baths: " + NewProp.BathsPartial 
					+ "</div>");					
					
					PushPin.SetMoreInfoURL("NaN," + NewProp.Lat + "," + NewProp.Lon);

							
				} else { // Actual property
					ActivePrices.push(MakeInt(NewProp.Price));	
					PushPin.SetTitle(NewProp.Desc);
					var MoreInfo="" //"For Sale since " + NewProp.ClosedDate; 
					MoreInfo += "For sale at " + NewProp.Price;
					var Style="PushPinStyleRed";
					MoreInfo += "<br>" + NewProp.Beds + " Bedrooms, "; 
					if (NewProp.SqFt>0) MoreInfo += NewProp.SqFt + " SqFt";
					MoreInfo += "<br>" + NewProp.BathsFull + " Full";
					if (NewProp.BathsPartial>0) MoreInfo += ", " + NewProp.BathsPartial + " Partial"
					MoreInfo += " Baths"
					PushPin.SetDescription("<div>" + MoreInfo + "<br><img src='http://" + NewProp.PhotoURL + "' width='200'/></div>")
					PushPin.SetCustomIcon("<div class='PushPinStyle'>1</div>")
					PushPin.SetMoreInfoURL(Num + "," + NewProp.Source + "," + NewProp.SysID);
				}
				
								
				oVEMapLayer.AddShape(PushPin);	
			} // skip it if it isn't valid
	}
	
	ActivePrices=ActivePrices.sort(numOrdA);	
	var N = ActivePrices.length;
	if (N>0){
		var Sum = 0;	for (var i=0; i<N; i++) {Sum+= ActivePrices[i];}
		var n1 = Math.floor(N/2.0);
		var n2 = Math.ceil((N-1)/2.0);
		$get("tdACount").innerText = N;
		$get("tdARangeLow").innerText = "$"+CommaFmt(ActivePrices[0]);
		$get("tdARangeHigh").innerText = "$"+CommaFmt(ActivePrices[N-1]);
		$get("tdAMedian").innerText = "$"+CommaFmt(Math.round((ActivePrices[n1]+ ActivePrices[n2])/2.0));
		$get("tdAAverage").innerText = "$"+CommaFmt(Math.round(Sum/N));
	} else {
		$get("tdACount").innerText = N;
		$get("tdARangeLow").innerText = "";
		$get("tdARangeHigh").innerText = "";
		$get("tdAMedian").innerText = "";
		$get("tdAAverage").innerText = "";
	}
	
isSearching = false;
}



function GetIntField(oFld){
	var Value = parseInt(oFld.value,10); 
	return  isNaN(Value)? 0 : Value;
}





function fnRecalc(){
	var Price = 0;
	var nPrice = 0;
	var n = 0;
	var Answ = "";
	var DOM = 0;
	var nDOM = 0; 

	var SubjSqFt = parseInt(document.all.Incl0.SqFt);
	var SubjAssessedValue = parseInt(document.all.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 = parseInt(oCtrl.AssessedValue); 
			var p_val = parseInt(oCtrl.Price);
			var s_val = parseInt(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)) {
				PricesPerAssSum += p_val /a_val;
				nPricePerAssess++;
			}
		}
	}
	Prices = Prices.sort();
	
	Answ="<table>"
	if (n>0) {
		Answ += "<tr><td align=right>Lowest Price:</td><td>$" + Math.round(Prices[0]/1000) + "K</td></tr>"
		Answ += "<tr><td align=right>Highest Price:</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></tr>" ;
		Answ += "<tr><td align=right>Median Price:</td><td>$" + Math.round(.001*(Prices[Math.ceil(n/2)-1] + Prices[Math.ceil((n+1)/2)-1])/2.0) + "K</td></tr>"
	}
	if (nPricePerSqFt>0) Answ += "<tr><td align=right>Price based on SqFt:</td><td>$" + Math.round(SubjSqFt * PricePerSqFtSum / (nPricePerSqFt*1000)) + "K</td></tr>"
	if (nPricePerAssess>0) Answ += "<tr><td align=right>Price based on Assessment:</td><td>$" + Math.round(SubjAssessedValue * PricesPerAssSum / (nPricePerAssess*1000)) + "K</td></tr>";
	
								
	document.all.EstSP.innerHTML=Answ + "</table>";
	document.all.NumComps.innerText = n;
}
	
	
function ShowPropDetail(e) {
	if (e.elementID)
	{
		var shape = oVEMap.GetShapeByID(e.elementID);
		if (shape)
		{
			var Info =new ShapeInfo(shape.GetMoreInfoURL());
			if (!isNaN(Info.PropNum)) {
				ShowDetailFrame(ComputePropDetailURL("A", Info.PropNum, Info.Source, Info.SysID));
				return;
			}
			// Aggregate button; zoom in
			if (isNaN(Info.Lat) || isNaN(Info.Lon) ) return;
			var Point = new VELatLong(Info.Lat, Info.Lon);
			var Zoom = Math.min(19,2 + oVEMap.GetZoomLevel());
			
			LastZoom = Zoom;
			parent.MapZoom = Zoom;
			
			oVEMap.SetCenterAndZoom(Point,Zoom);
			
		}
	} else {
		// right Click on map ... convert to Lat, Lon and retrieve parcel information 
		if (e.rightMouseButton){
			if (document.location.href.indexOf("Proto")>0){
			var x = e.mapX;
			var y = e.mapY;
			var Pt = oVEMap.PixelToLatLong(new VEPixel(x, y));
			if ((!e.shiftKey)&&(!e.ctrlKey)&&(!e.altKey)) oVEMap_BoundariesLayer.DeleteAllShapes(); // Single parcel shown unless holding the shift when clicking
			
			shape = new VEShape(VEShapeType.Pushpin, Pt);
			shape.SetTitle("Loading...Please wait");
			shape.SetCustomIcon("<img src='../Icons/Pin_Red_Small.gif' style='position:relative;left:10px;top:0px;' />");	
			oVEMap_MarkerLayer.AddShape(shape);
				
			MyAjaxService.GetParcelInfo(Pt.Latitude, Pt.Longitude, "", "", GetGeomCallBack, FailedCallback);  					
		}
		}
	} 
	return false; // Disable event
}		

function GetGeomCallBack(e){
			oVEMap_MarkerLayer.DeleteAllShapes();
			if (!e.isValid) return;
			
			var veLatLon = [];
			var Geometry = e.Geometry.replace("MULTIPOLYGON(((","").replace(")))","").split(",")
			for (var i=0; i<Geometry.length; i++){
				var point = Geometry[i].split(" ");
				veLatLon.push(new VELatLong(parseFloat(point[1]), parseFloat(point[0])));			
			}
			
			var CenterPoint = new VELatLong(e.Latitude, e.Longitude) // Centroid
						
			shape = new VEShape(VEShapeType.Polygon, veLatLon);
			shape.SetLineWidth(2);
			shape.SetLineColor(new VEColor(255,0,0,.8));
			shape.SetFillColor(new VEColor(255,0,0,.15));
			shape.SetTitle(e.Address);
			shape.SetDescription(e.Description);
      shape.SetIconAnchor(CenterPoint);   
			shape.SetCustomIcon("<img src='../Icons/Pin_Blue_Small.gif' style='position:relative;left:10px;top:0px;' />");
			oVEMap_MarkerLayer.AddShape(shape);	
}

 
 function ShowDetailFrame(URL)
{
			oDetail.src = URL;
			oDetail.style.display = "block";
			oDetail.style.zIndex = 10;
			//oContent.style.display = "none";
}
function HideDetailFrame()
{
			oDetail.style.display = "none";
			oDetail.src = FullURL("loading.html");
}