google.load("maps", "2", { "other_params": "sensor=false" });
var map;
var icon;
var markerArray = new Array();
var mapInited = false;
var bounds;

function initMapResults() {

	// unload the map on page unload
	$(window).unload(function() {
		GUnload(); 
	});
	
	map = new google.maps.Map2(document.getElementById("listingsMap"), { size:new GSize(600,500) });
	//map.setCenter(new google.maps.LatLng(37.4419, -122.1419), 13);
	map.setUIToDefault();
	map.disableScrollWheelZoom();
	//var point = new GLatLng(39.579674226527565, -105.94170391559601);
	//map.setCenter(point, 10);
	
	// get the data
	//GDownloadUrl('/maps/getPropertiesForMap2010.cfm?ids=' + propIds, buildMap);
	GDownloadUrl('/maps/getPropertiesForMap2010.cfm', buildMap, 'ids=' + propIds);
	mapInited = true;
}
//google.setOnLoadCallback(initialize);

function buildMap(data, responseCode) {
	$('#listingsMapPleaseWait').show();
	var xml = GXml.parse(data);

	var docRootNode = xml.documentElement;

	map.setMapType(G_NORMAL_MAP);
			
	var props = docRootNode.getElementsByTagName("Prop");
	for (p = 0; p < props.length; p++) {
		var thisProp = props[p];
		
		var marker = {
			address: trim(GXml.value(thisProp.getElementsByTagName("Address")[0])),
			address2: trim(GXml.value(thisProp.getElementsByTagName("Address2")[0])),
			latitude: thisProp.getAttribute("latitude"),
			longitude: thisProp.getAttribute("longitude"),
			point: new GLatLng(parseFloat(thisProp.getAttribute("latitude")), parseFloat(thisProp.getAttribute("longitude"))),
			showDrivingDirections: true,
			price: trim(GXml.value(thisProp.getElementsByTagName("Price")[0])),
			age: trim(GXml.value(thisProp.getElementsByTagName("Age")[0])),
			sqft: trim(GXml.value(thisProp.getElementsByTagName("Sqft")[0])),
			bedrooms: trim(GXml.value(thisProp.getElementsByTagName("Bedrooms")[0])),
			bathrooms: trim(GXml.value(thisProp.getElementsByTagName("Bathrooms")[0])),
			soldDate: trim(GXml.value(thisProp.getElementsByTagName("SoldDate")[0])),
			soldPrice: trim(GXml.value(thisProp.getElementsByTagName("SoldPrice")[0])),
			image: trim(GXml.value(thisProp.getElementsByTagName("Img")[0])),
			url: trim(GXml.value(thisProp.getElementsByTagName("Url")[0])),
			mls: trim(GXml.value(thisProp.getElementsByTagName("Mls")[0])),
			photoCount: trim(GXml.value(thisProp.getElementsByTagName("PhotoCount")[0]))
		};
		
		var markerImage = "";
		var age = parseInt(trim(GXml.value(thisProp.getElementsByTagName("Age")[0])));
		
		if (marker.soldDate != '') {
			markerImage = "/maps/images/mm_20_black.png";
		}
		else if (age <= 3) {
			markerImage = "/maps/images/mm_20_green.png";
		}
		else if (age <= 7) {
			markerImage = "/maps/images/mm_20_blue.png";
		}
		else {
			markerImage = "/maps/images/mm_20_red.png";
		}
		var icon = buildIcon(markerImage);
		
		var markerOptions = { icon: icon };
		var mapMarker = new GMarker(marker.point, markerOptions);
		
		marker.infoWindowHtml = createInfoWindow(marker);

		var tab1 = new GInfoWindowTab("Details", marker.infoWindowHtml);
		var tab2 = new GInfoWindowTab("Directions", buildDirectionsTab(marker)); 
		var arrTabs = new Array();
		arrTabs.push(tab1);
		arrTabs.push(tab2);			
		mapMarker.bindInfoWindowTabsHtml(arrTabs);
		marker.hasTabs = true;
		marker.infoWindowTabs = arrTabs;
		
		marker.mapMarker = mapMarker;
		
		markerArray.push(marker);
		
		map.addOverlay(mapMarker);
	}
	showAll();
	map.checkResize();
	var zoom = map.getBoundsZoomLevel(bounds);
	if (markerArray.length == 1) {
		zoom = 14;
		markerArray[0].mapMarker.openInfoWindowTabsHtml(marker.infoWindowTabs);
	}
	map.setCenter(bounds.getCenter(), zoom);
	map.checkResize();
	$('#listingsMapPleaseWait').hide();
	//showAll();
}

function buildIcon(markerImage) {
	icon = new GIcon();
	icon.shadow = "/maps/images/shadow50.png";
	icon.shadowSize = new GSize(22, 20);
	icon.iconAnchor = new GPoint(6, 20);
	icon.infoWindowAnchor = new GPoint(6, 2);
	icon.infoShadowAnchor = new GPoint(22, 8);
	if (markerImage != "") {
		icon.image = markerImage;
	}
	else {
		icon.image = "/maps/images/mm_20_red.png";
	}
	icon.iconSize = new GSize(12, 20);
	return icon;
}

function createInfoWindow(marker) {
	var theHtml = "<div class='popup'>";
	
	theHtml += "<div class='photo'><div><a href='" + marker.url + "' target='_blank'><img src='" + marker.image + "' border='0' /></a></div>";
	if (parseInt(marker.photoCount) > 0) {
		theHtml += "<div class='photoCount'><a href='" + marker.url + "' target='_blank'>" + marker.photoCount + " Additional Photo";
		if (parseInt(marker.photoCount) != 1) {
			theHtml += "s";
		}
		theHtml += "</a></div>";
	}
	theHtml += "</div>";
	theHtml += "<div class='description'>";
	
	if (marker.soldDate != "") {
		theHtml += "<div class='price'><span class='priceSold'>$" + marker.price + "</span>";
		theHtml += "<span class='sold'>SOLD!</span>";
	}
	else {
		theHtml += "<div class='price'>$" + marker.price;
	}
	theHtml += "</div>";
	theHtml += "<div class='address'>" + marker.address + "</div><div>" + marker.address2 + "</div>";
	theHtml += "<div class='info'>";
	theHtml += "<div class='brba'>" + marker.bedrooms + " BR/" + marker.bathrooms + " BA</div>";
	theHtml += "<div class='sqft'>" + marker.sqft + " SqFt</div>";
	theHtml += "<div class='mls'>MLS# " + marker.mls + "</div>";
	theHtml += "<div class='moreinfo'><a href='" + marker.url + "' target='_blank'>More Info &raquo;</a></div>";
	theHtml += "</div>"; // end info
	theHtml += "</div>"; // end description
	theHtml += "</div>"; // end popup
	return theHtml;
}

function buildDirectionsTab(marker) {
	var addr = xreplace(trim(marker.address), "<br />", ", ");
	addr = xreplace(addr, "<br>", ", ");
	addr = xreplace(addr, "<br/>", ", ");

	var retHtml = "";
	//var retHtml = "<form action='#' onsubmit=''>";
	retHtml += "<div class='directionsContainer'>";
	retHtml += "<div class='dirHeader'>Get Directions ";
	retHtml += "<a id='dirTo' href='javascript:setDirectionsTo()'>To</a>";
	retHtml += "<span id='spnDirTo' class='dirSel'>To</span>";
	retHtml += " | ";
	retHtml += "<a id='dirFrom' href='javascript:setDirectionsFrom()'>From</a>";
	retHtml += "<span id='spnDirFrom' class='dirSel'>From</span>";
	retHtml += "&nbsp;&nbsp;" + marker.address + "</div>";
	retHtml += "<br class='clear' />";
	retHtml += "<div class='dirLabel'>From:</div>";
	retHtml += "<div class='dirInput' id='dirInputFromForm'><input type='text' class='directions' id='fromAddress' name='from' /></div>";
	retHtml += "<div class='dirInput' id='dirInputFromLabel'>" + marker.address + "</div>";
	retHtml += "<br class='clear'/>";
	retHtml += "<div class='dirLabel'>To:</div>";
	retHtml += "<div class='dirInput' id='dirInputToForm'><input type='text' class='directions' id='toAddress' name='to' /></div>";
	//retHtml += "<div class='dirInput'><input type='text' class='directions' id='toAddress' name='to' value='" + merchant.latitude + ", " + merchant.longitude + "'></div>";
	retHtml += "<div class='dirInput' id='dirInputToLabel'>" + marker.address + "</div>";
	retHtml += "<br class='clear' />";
	//retHtml += "<input type='submit' value='Get Directions'>";
	retHtml += "<input type='hidden' id='direction' value='To' />";
	//retHtml += "<input type='hidden' id='merchantGeocode' value='" + merchant.latitude + ", " + merchant.longitude + "' />";
	//710 N Summit Blvd # 101, Frisco, CO (Starbucks) @39.576783,-106.092512
	retHtml += "<input type='hidden' id='markerGeocode' value='";
	retHtml += xreplace(marker.address, "<br />", ", ");
	//retHtml += " (" + marker.address + ") @" + marker.latitude + "," + marker.longitude + "' />";
	retHtml += " @" + marker.latitude + "," + marker.longitude + "' />";
	retHtml += "<br style='clear:both' />";
	retHtml += "<a href='javascript:setDirections()' style='margin:10px 0px;'>Get Directions</a>";
	retHtml += "</div>";
	return retHtml;
}
function setDirectionsTo() {
	document.getElementById("dirTo").style.display = "none";
	document.getElementById("dirFrom").style.display = "inline";
	document.getElementById("spnDirTo").style.display = "inline";
	document.getElementById("spnDirFrom").style.display = "none";
	document.getElementById("direction").value = "To";
	document.getElementById("dirInputFromForm").style.display = "block";
	document.getElementById("dirInputToForm").style.display = "none";
	document.getElementById("dirInputFromLabel").style.display = "none";
	document.getElementById("dirInputToLabel").style.display = "block";
}
function setDirectionsFrom() {
	document.getElementById("dirTo").style.display = "inline";
	document.getElementById("dirFrom").style.display = "none";
	document.getElementById("spnDirTo").style.display = "none";
	document.getElementById("spnDirFrom").style.display = "inline";
	document.getElementById("direction").value = "From";
	document.getElementById("dirInputFromForm").style.display = "none";
	document.getElementById("dirInputToForm").style.display = "block";
	document.getElementById("dirInputFromLabel").style.display = "block";
	document.getElementById("dirInputToLabel").style.display = "none";
}

function setDirections() {
	var from;
	var to;
	if (document.getElementById("direction").value == "To") {
		to = document.getElementById("markerGeocode").value;
		from = document.getElementById("fromAddress").value;
	}
	else {
		from = document.getElementById("markerGeocode").value;
		to = document.getElementById("toAddress").value;
	}
	window.open('http://maps.google.com/maps?f=q&source=s_q&hl=en&q=' + from + '+to+' + to);
}

function showAll() {
	bounds = new GLatLngBounds();
	for (i = 0; i < markerArray.length; i++) {
		bounds.extend(markerArray[i].point);
	}
	//map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
}

function trim(str) {
	if (str != "") {
		return str.replace(/^\s*|\s*$/g, "");
	}
	else {
		return "";
	}
}
function xreplace(checkMe, toberep, repwith) {
	var temp = checkMe;
	var i = temp.indexOf(toberep);
	while (i > -1) {
		temp = temp.replace(toberep, repwith);
		i = temp.indexOf(toberep, i + repwith.length + 1);
	}
	return temp;
}
