//
// A class which displays a Directory Listing location.
// Requires the MooTools 1.2 javascript framework and the Google Javascript API loader.
// Created by Aaron Neugebauer
// January 6, 2009
//

var DirectoryListingMap = new Class(
{
	// constructor
	initialize: function(id, lat, lng, address, region)
	{
		this._id = id; 			// id of the element to contain the map
		this._lat = lat; 		// latitude of the map location
		this._lng = lng; 		// longitude of the map location
		this._address = address; // address of the map location
		this._region = region; 	// region of the map location
		this._zoomLevel = 13; 	// level to zoom into the map
		this._countryCode = 'NZ'; // the country code to use when loading addresses
		this._map = null;
		// load the Google maps API
		google.load('maps', '2.x');
		google.setOnLoadCallback(this._onMapsLoaded.bind(this));
	},

	// Sets the center position of the map.
	_setCenter: function(point)
	{
		// center the map on the location and add a marker at the location
		this._map.setCenter(point, this._zoomLevel);
		this._map.addOverlay(new GMarker(point));
	},

	// Event handler - Google maps API has been loaded.
	_onMapsLoaded: function()
	{
		// initialize the map
		this._map = new google.maps.Map2(document.getElementById(this._id));
		this._map.addControl(new google.maps.SmallMapControl());
		if (this._lat && this._lng)
		{
			// center the map on the coordinates
			this._setCenter(new google.maps.LatLng(this._lat, this._lng), this._zoomLevel);
		}
		else
		{
			// coordinates not set - load the address
			this._geocoder = new google.maps.ClientGeocoder();
			this._geocoder.setBaseCountryCode(this._countryCode);
			this._geocoder.getLatLng(this._address, this._onAddressLoaded.bind(this));
		}
	},

	// Event handler - an address has been loaded.
	_onAddressLoaded: function(point)
	{
		if (point)
		{
			// address located - center the map on its location
			this._setCenter(point, this._zoomLevel);
		}
		else
		{
			// address not found - try locating the region
			this._geocoder.getLatLng(this._region, this._onRegionLoaded.bind(this));
		}
	},

	// Event handler - a region has been loaded.
	_onRegionLoaded: function(point)
	{
		if (point)
		{
			// region located - center the map on its location
			this._setCenter(point, this._zoomLevel);
		}
		else
		{
			// region not found - give up and hide the map
			document.getElementById(this._id).style.display = 'none';
		}
	}
});