﻿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) {
			this.address.each(function(a) {
				this.showAddress(a);
			}.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) {
					//alert(address + " not found");
				} 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, 12);
					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(){
		if((this.points.length == this.address.length) && this.address.length != 1){
			var bounds = new GLatLngBounds;
			this.points.each(function(currentPoint){
				bounds.extend(currentPoint);
			});
			this.map.setZoom(this.map.getBoundsZoomLevel(bounds));
			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'
//				});

