﻿var GoogleMap = Class.create({
	initialize: function (options) {
		$H({
			mapId: 'map_canvas',
			directionsId: 'directions',
			directionsFormId: 'directions_form',
			displayDirections: true,
			showInfoWindow: true
		}).merge(options).each(function (option) {
			this[option.key] = option.value;
		}, this);

		this.points = [];
		this.map = new GMap2($(this.mapId));
		this.geocoder = new GClientGeocoder();

		if (this.displayDirections) {
			this.initializeDirections();
		}

		if (typeof this.address == 'string') {
			this.showAddress(this.address);
		} else if (this.address.constructor == Array) {
			var test = [];
			var that = this;

			this.address.each(function (a, i) {
				(function (a, i) {
					test[i] = setTimeout(function () {
						that.showAddress(a);
					}, i * 225);
				})(a, i);

			} .bind(this));
		}

		this.map.setUIToDefault();
		this.registerEventHandlers();
	},
	registerEventHandlers: function () {
		// Prevent memory leaks by calling GUnload when the user leaves the page
		document.observe('unload', GUnload);
	},
	showAddress: function (address) {
		this.geocoder.getLatLng(
			address,
			function (point) {
				if (!point) { } else {
					var icon = new GIcon(G_DEFAULT_ICON);

					with (icon) {
						iconSize = new GSize(32, 32);
						shadowSize = new GSize(59, 32);
						// TODO: make this dynamic
						image = absoluteRoot + '/_ui/img/google_map_marker.png';
						shadow = absoluteRoot + '/_ui/img/google_map_shadow.png';
					}

					this.map.setCenter(point, 15);
					this.marker = new GMarker(point, {
						icon: icon
					});

					this.map.addOverlay(this.marker);
					if (this.showInfoWindow) {
						this.marker.openInfoWindowHtml(address);
					}

					this.points.push(point);
					this.centerOnAllPoints();
				}
			} .bind(this)
		);
	},
	centerOnAllPoints: function () {
		var bounds = new GLatLngBounds;

		this.points.each(function (currentPoint) {
			bounds.extend(currentPoint);
		});

		if (this.address.length == this.points.length) {
			this.map.setZoom(this.map.getBoundsZoomLevel(bounds) - 1);
		}
		//this.map.setZoom(15);
		this.map.setCenter(bounds.getCenter());

	},
	initializeDirections: function () {
		this.directionsWrapper = $(this.directionsId);
		this.directionsForm = $(this.directionsFormId);
		this.directions = new GDirections(this.map, this.directionsWrapper);

		$(this.directionsForm).observe('submit', function (e) {
			e.stop();
			this.showDirections($('starting_address').value);
		} .bind(this));
	},
	showDirections: function (startingLocation) {
		this.map.removeOverlay(this.marker);
		this.directions.load('from: ' + startingLocation + ' to: ' + this.address);
	}
});  				    
			    
// Sample instantiation:
//
//	new GoogleMap({
//		'address': 'Seattle, WA'
//	});


