// An instance of GClientGeocoder
var g_geocoder;
var g_goldMemberIcon;
var g_silverMemberIcon;

var g_site_base_path = location.protocol + "//" + location.host + "/";
//g_site_base_path += "chn/"; // TODO: Remove once the site is live

function onclick_handler_for_marker(html_to_show)
{
	this.openInfoWindowHtml(html_to_show);
}

function calc_custom_zindex(the_marker, unknown)
{
	/*
	$("debug").appendChild(document.createTextNode(
		the_marker.getPoint().lat() + " = " + GOverlay.getZIndex(the_marker.getPoint().lat()) + "\n"
	));
	*/
	if (the_marker.membership >= 2) {
		return (the_marker.membership - 3);
	} else {
		return GOverlay.getZIndex(the_marker.getPoint().lat());
	}
}

function create_marker_with_html(map_in, point_in, membership, html_in)
{
	membership = parseInt(membership);
	
	// Create the marker
	var markerOptions = {
		zIndexProcess:calc_custom_zindex
	};
	var marker = null;
	switch (membership) {
		case 2: // Silver
			markerOptions.icon = g_silverMemberIcon;
			//marker = new GMarker(point_in, {icon:g_silverMemberIcon});
			break;
			
		case 3: // Gold
			markerOptions.icon = g_goldMemberIcon;
			//marker = new GMarker(point_in, {icon:g_goldMemberIcon});
			break;
		
		default:
			//marker = new GMarker(point_in);
	}
	marker = new GMarker(point_in, markerOptions);
	if (marker) {
		// Specify the membership value of this marker
		marker.membership = membership;
			
		// Give the marker an on-click event
		if (html_in != undefined) {
			GEvent.addListener(marker, "click", onclick_handler_for_marker.bind(marker, html_in));
		}
		
		// Add the marker to the map
		map_in.addOverlay(marker);
		
		// Return a reference to the created marker (just to be nice).
		return marker;
	} else {
		return null;
	}
}

function generate_html_for_listing(listing_in)
{
	var str = "";
	str += "<div style=\"width: 250px;\">";
	str += "<h2><span><a href=\"property?id=" + listing_in.id + "\">" + listing_in.name + "</a></span></h2>";
	str += "<div class=\"popup_content\">";
		str += "<span class=\"street_address\">";
			str += listing_in.address;
			if (listing_in.address2) {
				str += ", <span class=\"address2\">" + listing_in.address2 + "</span>";
			}
		str += "</span>";
		str += "<span class=\"location\">" + listing_in.city + ", " + listing_in.state + " " + listing_in.zip + "</span>";
		str += "<a href=\"property?id=" + listing_in.id + "\">View this property</a>";
	str += "</div>";
	str += "</div>";
	
	return str;
}

function add_random_markers(map_in)
{
	var bounds = map_in.getBounds();
	var southWest = bounds.getSouthWest();
	var northEast = bounds.getNorthEast();
	var lngSpan = northEast.lng() - southWest.lng();
	var latSpan = northEast.lat() - southWest.lat();
	for (var i = 0; i < g_listings_js.length; i++) {
		// Generate a fake location until one can be derived from a street address
		var point = new GLatLng(
			southWest.lat() + latSpan * Math.random(),
			southWest.lng() + lngSpan * Math.random()
		);
		//map_in.addOverlay(new GMarker(point));
		
		var html = generate_html_for_listing(g_listings_js[i]);
		create_marker_with_html(map_in, point, 0, html);
	}
}

/* start_geocode_request() exists to allow for closures. The three arguments
	(map_in, address, listing_index) are needed inside the anonymous function
	but can't be passed into the source of the callback (getLatLng).  Prototype
	could have been used, but it's just doing the same thing behind the scenes.
*/
function start_geocode_request(map_in, address, listing_index)
{
	g_geocoder.getLatLng(
		address,
		function(point) {
			// Global: g_listings_js
			// Inherited: map_in, listing_index
			if (point) {
				var html = generate_html_for_listing(g_listings_js[listing_index]);
				create_marker_with_html(map_in, point, g_listings_js[listing_index].membership, html);
				
				// TODO: Throw off an AJAX request to update the database with these lat/lon coordinates.
			} else {
				//alert("failed geocode: " + point);
			}
		}
	);
}

function add_markers(map_in)
{
	if (g_listings_js) {
		// Loop through all the listings supplied by a global array
		for (var i = 0; i < g_listings_js.length; i++) {
			var the_listing = g_listings_js[i];
	
			// Generate the merged address string
			var address = the_listing.address;
			if (the_listing.address2) { if (the_listing.address2.length > 0) {
				address += ", " + the_listing.address2;
			}}
			address += ", " + the_listing.city;
			if (the_listing.country == "United States of America") {
				address += ", " + the_listing.state;
			}
			if (the_listing.zip) { if (the_listing.zip.length > 0) {
				address += " " + the_listing.zip;
			}}
			address += ", " + the_listing.country;
			
			if (the_listing.lat == "" && the_listing.lon == "") {
				//alert("Starting a geocode request for " + address);
				
				// Start a request for lat/long coordinates
				start_geocode_request(map_in, address, i);
			} else {
				// Create a lat/lon object from the .lat and .lon properties
				var point = new GLatLng(the_listing.lat, the_listing.lon);
	
				//alert("No geocode, using coordinates " + the_listing.lat + ", " + the_listing.lon);
				
				// Create the marker
				var html = generate_html_for_listing(the_listing);
				create_marker_with_html(map_in, point, the_listing.membership, html);
			}
		}
	}
}

//function start_map_center_request(map, state, city)
function start_map_center_request(map, params)
{
	var zoom_level = 4; // "National"
	var address = false;
	
	if (params.country) {
		address = params.country;
		
		if (params.state_fullname || params.state) {
			zoom_level = 6; // "State"
			
			if (params.state_fullname) {
				address = params.state_fullname + ", " + address;
			} else {
				address = params.state + ", " + address;
			}
			
			if (params.city) {
				zoom_level = 9; // "City"
				
				address = params.city + ", " + address;
			}
		}
	}
	
	if (address) {
		//alert("map center address: " + address);
		g_geocoder.getLatLng(
			address,
			function(point) {
				if (point) {
					map.setCenter(point, zoom_level);
				}
			}
		);
	}
}

function search_results_init()
{
	// Will Google Maps work?
	if (GBrowserIsCompatible()) {
		// Does the map container exist?
		//var objMap = document.getElementById("search_results_map");
		var objMap = $("search_results_map");
		
		if (!objMap) {
			//alert("Cannot find the map container.");
		} else {
			objMap.addClassName("scripted");
			
			// Create the map
			var map = new GMap2(objMap);
			
			// Add a pan/zoom control
			map.addControl(new GSmallMapControl());
			//map.addControl(new GLargeMapControl());
			
			// Center it (on Palo Alto, apparently)
			//map.setCenter(new GLatLng(37.4419, -122.1419), 13);
			
			// Center the map on America, zoomed out
			map.setCenter(new GLatLng(37.0625, -95.677068), 4);
			
			// Create our "tiny" marker icon
			g_goldMemberIcon = new GIcon(G_DEFAULT_ICON);
			g_goldMemberIcon.image = g_site_base_path + "images/_google_maps/goldpin.png";
			g_goldMemberIcon.iconSize = new GSize(20, 34);

			g_silverMemberIcon = new GIcon(G_DEFAULT_ICON);
			g_silverMemberIcon.image = g_site_base_path + "images/_google_maps/silverpin.png";
			g_silverMemberIcon.iconSize = new GSize(20, 34);
			
			g_geocoder = new GClientGeocoder();
	
			// Start a request for the location of the search city/state
			//start_map_center_request(map, g_state, g_city);
			var map_center_params = new Object();
			if (typeof g_country != "undefined") { map_center_params.country = g_country; }
			if (typeof g_state != "undefined") { map_center_params.state = g_state; }
			if (typeof g_state_fullname != "undefined") { map_center_params.state_fullname = g_state_fullname; }
			if (typeof g_city != "undefined") { map_center_params.city = g_city; }
			start_map_center_request(map, map_center_params);
			
			// Add some markers to the map
			//add_random_markers(map);
			add_markers(map);
		}
	} else {
		alert("Your browser is incompatible with Google Maps.");
	}
	
	// Activate H3's in the amenities search form
	var amenities_form_container = $("amenities_search_form_container");
	if (amenities_form_container) {
		amenities_form_container.addClassName("scripted");
		
		var h3s = amenities_form_container.select("h3.collapsable");
		
		for (var i = 0; i < h3s.length; i++) {
			// Set the onclick handler
			h3s[i].observe("click", handle_h3_click);
		}
	}
}

function handle_h3_click()
{
	var next_sib = this.next("ul.checkboxgroup");
	
	if (this.hasClassName("show")) {
		this.removeClassName("show");
		next_sib.removeClassName("show");
	} else {
		this.addClassName("show");
		next_sib.addClassName("show");
	}
}

// Require that Prototype is available
if (typeof Prototype == "undefined") {
	alert("The Google Maps on this page require that Javascript is enabled.");
} else {
	//alert("Setting up on-DOM-loaded event");
	document.observe("dom:loaded", search_results_init);
}

