﻿var xmlUrl;
var map;
var geocoder;
var ignoreNextLoad = true;
var priceMin;
var priceMax;
var beds;
var baths;
var propType;
var markersLen = 0;
var mapMarkers;
var mapPoints;
var infoHtmls;
var loggedIn = false;
var propAddress;
var propCity;
var propState;
var propZip;
var partnerOrMember = false;
var propClass = 1; //Default to Residential
var imageServerUrl;

// Create our "tiny" marker icon
var icon = new GIcon();
icon.image = "http://labs.google.com/ridefinder/images/mm_20_blue.png";
icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
icon.iconSize = new GSize(12, 20);
icon.shadowSize = new GSize(22, 20);
icon.iconAnchor = new GPoint(6, 20);
icon.infoWindowAnchor = new GPoint(5, 1);

function load() {
	if (GBrowserIsCompatible()) {
		if ($("savedpropertysearch_id") && $F("savedpropertysearch_id") != "") {ignoreNextLoad=false};
		map = new GMap2($("GoogleMap"));
		map.enableDoubleClickZoom();
		//map.enableContinuousZoom();
		GEvent.addListener(map, "moveend", function() { newDownload() });
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		map.addControl(new GOverviewMapControl());
		geocoder = new GClientGeocoder(); 
		var newLat = $("propertysearch_MapCenterLatitude");
		var newLong = $("propertysearch_MapCenterLongitude");
		var newZoom = $("propertysearch_MapZoomLevel");
		if (newLat && newLat.value > ""){startLat=parseFloat(newLat.value)};
		if (newLong && newLong.value > ""){startLong=parseFloat(newLong.value)};
		if (newZoom && newZoom.value > ""){startZoom=parseInt(newZoom.value)};
		map.setCenter(new GLatLng(startLat, startLong), startZoom);
		setState();
		showResults();
	}
}

function loadAddress() {
	if (GBrowserIsCompatible()) {
		map = new GMap2($("GoogleMap"));
		map.enableDoubleClickZoom();
		//map.enableContinuousZoom();
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
		map.addControl(new GOverviewMapControl());
		if (propAddress || propCity || propState || propZip){
			var address = propAddress + ", " + propCity + ", " + propState + " " + propZip
			geocoder = new GClientGeocoder();
			geocoder.getLocations(address, showAddressOnMap);
		}
		switchToHybrid();
	}
}

function loadPoint() {
	if (GBrowserIsCompatible()) {
		map = new GMap2($("GoogleMap"));
		map.enableDoubleClickZoom();
		//map.enableContinuousZoom();
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
		map.addControl(new GOverviewMapControl());
		if (propLatitude > ""){startLat=parseFloat(propLatitude);};
		if (propLongitude > ""){startLong=parseFloat(propLongitude);};
		startZoom=parseInt(15);
		var point = new GLatLng(startLat, startLong);
		map.setCenter(point, startZoom);
		var marker = new GMarker(point);
		map.addOverlay(marker);
		switchToHybrid();
	}
}

function switchToHybrid(){
	var mapCenter = map.getCenter();
	try{
		map.setCenter(new GLatLng(mapCenter.lat(),mapCenter.lng()), map.getZoom(), G_HYBRID_MAP);
	} catch(e) {
		//Silent
	};
};


function createMarker(point, number, bid, mls, addr, prc, bdr, bth) {
  var marker = new GMarker(point, icon);
  GEvent.addListener(marker, "click", function() {
  var winHtml = "<table><tr><td><img width=\"85\" height=\"65\" src=\"" + imageServerUrl + "?p=1&w=85&h=65&b=" + bid + "&m=" + mls + "\"></td><td style=\"font-family: Arial; font-size: 11px;\"><b>" + addr + "</b><br />" + prc + "<br />Beds: " + bdr + "<br />Baths: " + bth + "<br /><a href=\"/RealEstate/Property/viewdetails.asp?propertyId=" + mls + "&searchType=Map\">more info</a></td></tr></table>";
    marker.openInfoWindowHtml(winHtml);
  });
  return marker;
}

function popupHtml(marker){
	winHtml = "<table bgcolor=\"#ffffff\" width=\"240\"><tr><td><img width=\"110\" height=\"80\" src=\"" + imageServerUrl + "?p=" + marker.getAttribute("photo") + "&w=110&h=80&b=" + marker.getAttribute("bid") + "&m=" + marker.getAttribute("mls") + "\"></td><td style=\"font-family: Arial; font-size: 11px;\">"
	var addr = trim(marker.getAttribute("addr"));
	var nbhd = trim(marker.getAttribute("nbhd"));
	var city = trim(marker.getAttribute("city"));
	var rel = trim(marker.getAttribute("rel"));
	var logo = trim(marker.getAttribute("logo"));
	if (loggedIn == false && rel == "none"){
		//This is an IDX listing and user is not logged in
		if (logo.length > 0){
			winHtml += "<img src=\"" + logo + "\" height=\"14\" />";
		}
		if (nbhd.length > 0){
			winHtml += "<br />" + nbhd;
		} else {
			winHtml += "<br />" + city;
		}
	} else if (addr.length > 0){
		winHtml += "<b>"+ addr + "</b>";
		if (marker.getAttribute("unit") != ""){
			winHtml += "<br />Unit #" + marker.getAttribute("unit");
		};
		if (nbhd.length > 0) {
			winHtml += "<br />" + nbhd;
		}
	} else if (nbhd.length > 0) {
		winHtml += "<b>" + nbhd + "</b>";
	} else {
		winHtml += "<b>" + nbhd + "</b>";
	};
	winHtml +="<br />" + marker.getAttribute("prc") + "<br />" + marker.getAttribute("type")
	if (propClass == 3){
		if (marker.getAttribute("sqft") != ""){
			winHtml += "<br />Size: " + marker.getAttribute("sqft") + " SF";
		};
		if (marker.getAttribute("yr") != ""){
			winHtml += "<br />Built: " + marker.getAttribute("yr");
		};
	} else if (propClass == 4) {
		if (marker.getAttribute("acres") != ""){
			winHtml += "<br />Acres: " + marker.getAttribute("acres");
		};
		if (marker.getAttribute("lotsize") != ""){
			winHtml += "<br />Lot Size: " + marker.getAttribute("lotsize");
		};
	} else {
		winHtml += "<br />Beds: " + marker.getAttribute("bdr") + "<br />Baths: " + marker.getAttribute("bth");
	};
	winHtml += "<br /><a href=\"/RealEstate/Property/viewdetails.asp?propertyId=" + marker.getAttribute("id") + "&searchType=Map\">More Info</a>";
	// this has stopped working sometime in sept '09
	//if (loggedIn){winHtml += "&nbsp;|&nbsp;<a href=\"#\" onclick=\"Hotlist('" + marker.getAttribute("bid") + "','" + marker.getAttribute("mls") + "');return false;\">Add to Hotlist</a>"};
	winHtml += "</td></tr></table>";
	return winHtml;
};

function tooltipHtml(marker){
	tipHtml = "<table bgcolor=\"#ffffff\" style=\"border: solid 1px #333333; color: #000000;\"><tr><td nowrap style=\"font-family: Arial; font-size: 11px;\">"
	var addr = trim(marker.getAttribute("addr"));
	var nbhd = trim(marker.getAttribute("nbhd"));
	var city = trim(marker.getAttribute("city"));
	var rel = trim(marker.getAttribute("rel"));
	var logo = trim(marker.getAttribute("logo"));
	if (loggedIn == false && rel == "none"){
		//This is an IDX listing and user is not logged in
		if (logo.length > 0){
			tipHtml += "<img src=\"" + logo + "\" height=\"14\" />";
		}
		if (nbhd.length > 0){
			tipHtml += "<br />" + nbhd;
		} else {
			tipHtml += "<br />" + city;
		}
	} else if (addr.length > 0){
		tipHtml += "<b>"+ addr + "</b>";
		if (marker.getAttribute("unit") != ""){
			tipHtml += "<br />Unit #" + marker.getAttribute("unit");
		};
		if (nbhd.length > 0) {
			tipHtml += "<br />" + nbhd;
		}
	} else if (nbhd.length > 0) {
		tipHtml += "<b>" + nbhd + "</b>";
	} else {
		tipHtml += "<b>" + nbhd + "</b>";
	};
	tipHtml += "<br />" + marker.getAttribute("prc") + "<br />" + marker.getAttribute("type");
	if (propClass == 3){
			if (marker.getAttribute("sqft") != ""){
			tipHtml += "<br />Size: " + marker.getAttribute("sqft") + " SF";
		};
		if (marker.getAttribute("yr") != ""){
			tipHtml += "<br />Built: " + marker.getAttribute("yr");
		};
	} else if (propClass == 4) {
		if (marker.getAttribute("acres") != ""){
			tipHtml += "<br />Acres: " + marker.getAttribute("acres");
		};
		if (marker.getAttribute("lotsize") != ""){
			tipHtml += "<br />Lot Size: " + marker.getAttribute("lotsize");
		};
	} else {
		tipHtml += "<br />Beds: " + marker.getAttribute("bdr") + "<br />Baths: " + marker.getAttribute("bth");
	};
	tipHtml += "</td></tr></table>";
	return tipHtml;
};

function gridHeadHtml(){
	headHtml = "<table align=\"center\" width=\"99%\" bgcolor=\"#ffffff\"><tr class=\"headRow\"><td>ID #</td><td>Address</td>"
	if (propClass != 4){
		headHtml += "<td>Unit #</td>";
	};
	headHtml += "<td>Price</td>";
	if (propClass == 3){
		headHtml += "<td>Size (SF)</td><td>Year</td>";
	} else if (propClass == 4){
		headHtml += "<td>Acres</td>";
	} else {
		headHtml += "<td>Beds</td><td>Baths</td>";
	};
	headHtml += "</tr>";
	return headHtml;
};

function gridRowHtml(marker, rowNum){
	rowHtml = "<tr onmouseover=\"hl(this," + rowNum + ")\" onmouseout=\"dl(this," + rowNum + ")\" onclick=\"parent.mapOpener(" + rowNum + ")\">";
	rowHtml += "<td>" + marker.getAttribute("mls") + "</td><td>"
	var rel = trim(marker.getAttribute("rel"));
	var logo = trim(marker.getAttribute("logo"));
	var addr = trim(marker.getAttribute("addr"));
	var nbhd = trim(marker.getAttribute("nbhd"));
	var city = trim(marker.getAttribute("city"));
	if (loggedIn == false && rel == "none"){
		//This is an IDX listing and user is not logged in
		if (logo.length > 0){
			rowHtml += "<img src=\"" + logo + "\" height=\"14\" />";
		}
		if (nbhd.length > 0){
			rowHtml += " " + nbhd;
		} else {
			rowHtml += " " + city;
		}
	} else if (addr.length > 0 && (loggedIn || rel != "none")){
		rowHtml += addr;
	} else if (nbhd.length > 0) {
		rowHtml += nbhd;
	} else {
		rowHtml += city;
	};
	if (propClass != 4){
		rowHtml += "</td><td>" + marker.getAttribute("unit");
	};
	rowHtml += "</td><td>" + marker.getAttribute("prc") + "</td>";
	if (propClass == 3){
		rowHtml += "<td>" + marker.getAttribute("sqft") + "</td><td>" + marker.getAttribute("yr") + "</td>";
	} else if (propClass == 4){
		rowHtml += "<td>" + marker.getAttribute("acres") + "</td>";
	} else {
		rowHtml += "<td>" + marker.getAttribute("bdr") + "</td><td>" + marker.getAttribute("bth") + "</td>";
	};
	rowHtml += "</tr>";
	return rowHtml;
};

function newDownload(){
    if (map && !ignoreNextLoad){
        showLoading();
        setTimeout("doDownload()",100);
    } else {
		ignoreNextLoad = false; 
	 };
};


function doDownload(){
    if (map){
        var bounds = map.getBounds();
        var southWest = bounds.getSouthWest();
        var northEast = bounds.getNorthEast();
        xmlUrl = "/RealEstate/PropertySearchMap/Search.asp?"
        var mapCenter = map.getCenter();
        
        $("propertysearch_MapCenterLatitude").value = mapCenter.lat();
        $("propertysearch_MapCenterLongitude").value = mapCenter.lng();
        $("propertysearch_MapZoomLevel").value = map.getZoom();
        $("propertysearch_LatitudeMin").value = southWest.lat();
        $("propertysearch_LatitudeMax").value = northEast.lat();
        $("propertysearch_LongitudeMin").value = southWest.lng();
        $("propertysearch_LongitudeMax").value = northEast.lng();
        
        propClass = $("propertysearch_PropertyClass").value;
        
        xmlUrl += Form.serialize('searchform');
        if (window.location.toString().toLowerCase().indexOf("debug=true") > -1){ window.open(xmlUrl); }
        GDownloadUrl(xmlUrl, function(data) {
          map.clearOverlays();
          if (map.getZoom() > 5) {
							//alert(data);
              var xml = GXml.parse(data);
              var markers = xml.documentElement.getElementsByTagName("marker");
              markersLen = markers.length;
              if (markersLen){
                  mapPoints = new Array(markersLen); 
                  mapMarkers = new Array(markersLen); 
                  infoHtmls = new Array(markersLen); 
              
                  var propTable = gridHeadHtml();
                  for (var i = 0; i < markersLen; i++) {
                    if (parseFloat(markers[i].getAttribute("lat")) && parseFloat(markers[i].getAttribute("lng"))){
                    mapPoints[i] = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
                                            parseFloat(markers[i].getAttribute("lng")));

                    mapMarkers[i] = new PdMarker(mapPoints[i],icon);
                    mapMarkers[i].setTooltip(tooltipHtml(markers[i]));
                    mapMarkers[i].setHoverImage("http://labs.google.com/ridefinder/images/mm_20_red.png");
                    
                    infoHtmls[i] = popupHtml(markers[i]);

                    GEvent.addListener(mapMarkers[i],'click',makeOpenerCaller(i)); 
                     
                    map.addOverlay(mapMarkers[i]);
                    
                    propTable += gridRowHtml(markers[i], i);
                    }
                  }
                  propTable += "</table>";
                  
                  resultsFrame=$("MapResults");
                  resultsFrame.contentWindow.document.body.innerHTML=propTable;
                  if (markersLen == 50) {
							showStatus("Over 50 matches found.  To refine your search, please double click the map to zoom in.");
                  } else {
							if (markersLen == 1){
								showStatus(markersLen + " property matched your criteria.  Displaying all matches.");
							} else {
								showStatus(markersLen + " properties matched your criteria.  Displaying all matches.");
							};
                  };
                  showResults();
              } else {
                  resultsFrame=$("MapResults");
                  resultsFrame.contentWindow.document.body.innerHTML=""; 
                  hideResults();
                  showStatus("No properties matched.  Please change your criteria or try a different location.");      
              };
          } else {
            hideResults();
           showStatus("You are zoomed out too far.  Please zoom in to see properties"); 
          };
          hideLoading();
        });
    };
};

function makeOpenerCaller(i) { 
        return function() { mapOpener(i); }; 
};


function mapOpener(i) { 
        ignoreNextLoad = true;
        mapMarkers[i].openInfoWindowHtml(infoHtmls[i]);
        mapMarkers[i].showTooltip();
} ;

function showResults(){
    $('MapResultsDiv').style.display = '';
};

function hideResults(){
    $('MapResultsDiv').style.display = 'none';
};

function showLoading(){
    if (document.all){
        divLeft = (document.body.clientWidth / 2) - 100;
    } else {
        divLeft = (window.innerWidth / 2) - 100;
    };
    $('LoadingDiv').style.left = divLeft + "px";
    $('LoadingDiv').style.display = '';
};

function hideLoading(){
    $('LoadingDiv').style.display = 'none';
};

function Hotlist(MLSBoardID,PropertyID){
    // PopupAddToHotlist.aspx is not in HIS code repository. Was it served from a Visient machine?
    // Visient sites appear broken as well.
	winHotlist = window.open('PopupAddToHotlist.aspx?MLSBoardID='+MLSBoardID+'&PropertyID='+PropertyID,'AddToHotlist','width=300,height=120,left=200,top=200'); 
	if (winHotlist){
	    winHotlist.focus();
	} else {
	    alert("Your popup blocker has prevented the Hotlist window from appearing.\nPlease disable your popup blocker.");
	};
};

// addAddressToMap() is called when the geocoder returns an
// answer.  It adds a marker to the map with an open info window
// showing the nicely formatted version of the address.
function addAddressToMap(response, showPoint, openWindow, considerAutosearch) {
	if (!response || response.Status.code != 200) {
		alert("Sorry, we were unable to geocode that address");
	} else {
		place = response.Placemark[0];
		point = new GLatLng(place.Point.coordinates[1],
                        place.Point.coordinates[0]);
       if (considerAutosearch && $F('autosearch') == 'True' && $F('explicitZoomLevel') != "0"){
           //Use explicit zoom level if needed during autosearch 
           map.setCenter(point, $F('explicitZoomLevel'));      
       } else {
           //Lookup zoom level by geocode accuracy 
           map.setCenter(point, getZoomByAccuracy(place.AddressDetails.Accuracy));
       }   
		 if (showPoint && place.AddressDetails.Accuracy == 8){
			marker = new GMarker(point);
			map.addOverlay(marker);
			if (openWindow && (loggedIn || partnerOrMember)){
				var area = place.AddressDetails.Country.AdministrativeArea;
				var winHtml = area.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName + "<br />" + area.SubAdministrativeArea.Locality.LocalityName + ", " + area.AdministrativeAreaName + " " + area.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber;
				GEvent.addListener(marker, "click", function() {
					marker.openInfoWindowHtml(winHtml);
				});
				marker.openInfoWindowHtml(winHtml); 
			};
		};
	};
	//Turn off autosearch since find has been executed
	if (considerAutosearch){
		$('autosearch').value = 'False';
	};
};

//Centers map on address (no marker added).
//Used by map search.
function showAddress(response){
	addAddressToMap(response, false, false, true);
};

//Centers map on address and displays marker.
//Used by property detail (ignore autosearch).
function showAddressOnMap(response, considerAutosearch){
	addAddressToMap(response, true, true, false);
};

//Finds geocode for an address.
//Used by map search.
function showLocation(address) {
  geocoder.getLocations(address, showAddress);
}

function findLocation(){
	var state="";
	if ($("propertysearch_state").selectedIndex != 0) { 
		state=$("propertysearch_state")[$("propertysearch_state").selectedIndex].text; 
	}
	var county="";
	if ($("County").selectedIndex != 0) { 
		county=$("County")[$("County").selectedIndex].text; 
	}
    showLocation($F("Street") + ", " + $F("City") + ", " + county + ", " + state + " " +$F("Zip"));
};

function startSearch()
{
	if ($F('autosearch') == 'True')
	{
		findLocation();
	} else {
		newDownload();
	};
};

function setState()
{
		if ($("propertysearch_state").selectedIndex == 0){
			state = $("propertysearch_state");
			 for (var i = 0; i < state.options.length; i++){
				state[i].selected = (state[i].text == startState);
			};
		};
};

function showStatus(msg){
	$("MapStatusDiv").innerHTML = msg;
}

function getZoomByAccuracy(acc){
	//Accuracy Reference:
	//0 Unknown location.
	//1 Country level accuracy.
	//2 Region (state, province, prefecture, etc.) level accuracy.
	//3 Sub-region (county, municipality, etc.) level accuracy.
	//4 Town (city, village) level accuracy.
	//5 Post code (zip code) level accuracy.
	//6 Street level accuracy.
	//7 Intersection level accuracy.
	//8 Address level accuracy.
	switch (acc){
		case 1: 
			return 7;
			break;
		case 2: 
			return 8;
			break;
		case 3: 
			return 9;
			break;
		case 4: 
			return 10;
			break;
		case 5: 
			return 13;
			break;
		case 6: 
			return 14;
			break;
		case 7: 
			return 15;
			break;
		case 8: 
			return 16;
			break;
		default :
			return 5;
	}
};

function trim(str) {
	str = str.replace(/^\s+/, '');
	for (var i = str.length - 1; i > 0; i--) {
		if (/\S/.test(str.charAt(i))) {
			str = str.substring(0, i + 1);
			break;
		}
	}
	return str;
}