var LocationMap = Class.create({

	initialize: function(div){
		
		if (!GBrowserIsCompatible()) { return; }
		// Store instance of class
		div.mgr = this;
		this.map = new GMap2(div);
		this.map.addControl(new GScaleControl());
		this.map.addControl(new GSmallZoomControl3D());
		this.markers = $A();
		this.active_marker = null;
		this.pano = new GStreetviewPanorama($('pano_canvas')); 
		this.pano_client = new GStreetviewClient();
		this.geocoder = new GClientGeocoder();
		this.center = new GLatLng(origin['lat'], origin['lng']);
		this.bounds = new GLatLngBounds();
		this.bounds.extend(this.center);
		this.locations = locations;
		this.base_icon = new GIcon(G_DEFAULT_ICON);
	    this.base_icon.iconSize = new GSize(40, 40);
	    this.base_icon.iconAnchor = new GPoint(20, 20);
	    this.base_icon.infoWindowAnchor = new GPoint(9, 2);
		// Show Origin
		this.origin_marker = new GMarker(this.center);
		this.map.addOverlay(this.origin_marker);
		this.locations.each(function(location, index) {
			var letter = String.fromCharCode("A".charCodeAt(0) + index);
			var lettered_icon = new GIcon(this.base_icon);
			lettered_icon.image = 'http://assets0.whitecastle.com/images/icons/locator_' + letter.toLowerCase() + '.png';
			var marker_options = { icon:lettered_icon }
			var point = new GLatLng(location['lat'], location['lng']);
			point.letter = letter;
			point.id = location['id'];
			point.yaw = location['yaw'];
			var marker = new GMarker(point, marker_options);
			this.markers[point.id] = marker;
			this.map.addOverlay(marker);
			this.bounds.extend(point);
			GEvent.addListener(marker, 'click', this.manage_point.bind(this));
			// Hilight the first result
			if (index == 0) {
				this.manage_point(point);	
			}
		}, this);
		this.set_center();
		GEvent.addListener(this.pano, 'error', this.no_flash.bind(this)); 
	},
	
	set_center: function(){
		this.map.setCenter(this.bounds.getCenter());
		this.map.setZoom(this.map.getBoundsZoomLevel(this.bounds));
	},
	
	manage_point: function(point){
		// Short circuit already-selected markers
		if (point.id == this.active_marker) { return; }
		this.active_marker = point.id;
		$('location_' + point.id).simulate('click');
		this.pano_client.getNearestPanorama(point, this.show_pano.bind(this));
	},
	
	show_pano: function(pano_data){
		if (pano_data.code != 200) {
			this.pano.hide();
			//console.log('showPanoData: Server rejected with code: ' + pano_data.code);
			return;
		}
		var yaw = this.markers[this.active_marker].getLatLng().yaw;
		this.pano.setLocationAndPOV(pano_data.location.latlng, { yaw:yaw, pitch:0 });
	},
	
	no_flash: function(e){
		if (e == 603) {
			//alert("Error: Flash doesn't appear to be supported by your browser");
			// TODO: should we hide the pano?
			return;
		}
	}
	
});

Event.observe(window, 'load', function() { 
	new LocationMap($('map_canvas'));
});