var map = null;
var cluster = null;
var markers = [];
var search = '';

Event.observe(window, 'load', function() {
	
	if(GBrowserIsCompatible()) {	
		var mapbox = $('mapbox');

		map = new GMap2(mapbox);
		map.setCenter(new GLatLng(37, -118), 5);
		map.addControl(new GSmallZoomControl3D());
		map.addControl(new GHierarchicalMapTypeControl());
		map.addMapType(G_PHYSICAL_MAP);
		map.enableScrollWheelZoom();
		
		/*var icon = new GIcon({
			'image': '/images/icon.png',
			'size': new GSize(30, 33),
			'iconAnchor': new GPoint(17, 33),
			'infoWindowAnchor': new GPoint(17, 33)
		});*/
		
		new Ajax.Request('/map?q=markers&search='+search, {
			method: 'get',
			onSuccess: function(transport){
				var response = transport.responseText.strip();
				
				if(response.substr(0, 1) == '[') {
					var points = response.evalJSON(true);
					
					points.each(function(p, i) {
						markers[i] = new GMarker(new GLatLng(p.lat, p.lon), {/*icon: icon,*/ draggable: false});
						
						markers[i].data = {id: p.id, lat: p.lat, lon: p.lon};
						GEvent.addListener(markers[i], 'click', marker_clicked);
						markers[i].disableDragging();
						
						//map.addOverlay(markers[i]); // or cluster below
					});
		
					cluster = new MarkerClusterer(map, markers, {gridSize: 40, styles: [
						{width: 32, height: 32, url: '/images/book.png', opt_anchor: [6, 14], opt_textColor : 'white'},
						{width: 32, height: 32, url: '/images/book.png', opt_anchor: [6, 11], opt_textColor : 'white'},
						{width: 32, height: 32, url: '/images/book.png', opt_anchor: [6, 8], opt_textColor : 'white'},
						{width: 32, height: 32, url: '/images/book.png', opt_anchor: [6, 3], opt_textColor : 'white'}
					]});
					
				} else alert(transport.responseText);
			}
		});
	}
});

function marker_clicked(i){
	new Ajax.Request('/map?q=bubble&id='+this.data.id, {
		method: 'get',
		onSuccess: (function(transport){
			this.openInfoWindowHtml(transport.responseText);
		}).bind(this)
	});
}