google.load("maps", "2.x");
var spotmap = null;
var geocoder = null;

function initialize_spotmap() {
  if (GBrowserIsCompatible()) {
	opts = new Object();
	opts.backgroundColor="#ddd";
	spotmap = new GMap2(document.getElementById("map"), opts);
	geocoder = new GClientGeocoder();
  }
}

function populate_address(latlng) {
  geocoder.getLocations(latlng, 
						function(r) {
						  if(r.Status && r.Status.code == 200 && (r.Placemark.length > 0)) {
							$('#id_address').val(r.Placemark[0].address);
						  }
						}
						);
}

function setupDoubleClickListener() {
	GEvent.addListener(spotmap, "dblclick",
	                   function(overlay, latlng ) {
						 markSpot(latlng);
						 document.newspot.coordinates.value = latlng.lat()+","+latlng.lng();
						 populate_address(latlng);
	                   }
					   );
}


function marker_url(color) {
  return("/static/markers/"+color+"_marker.png");
}


function markSpot(point) {
  var marker = new GMarker(point);
  spotmap.clearOverlays();
  spotmap.addOverlay(marker);
}

function centerOnAddress(address, zoomlevel) {
  if(spotmap == null) { initialize_spotmap(); }
  if(!zoomlevel) {
    zoomlevel = 14;
  }
  if (geocoder) {
	geocoder.getLatLng(
					   address,
					   function(point) {
						 if (!point) {
						   alert("Address " + address + " not found");
						 } else {
						   spotmap.setCenter(point, zoomlevel);
						 }
					   }
					   );
  }
}

function showAddress(label, address) {
  if (geocoder) {
	geocoder.getLatLng(
					   address,
					   function(point) {
						 if (!point) {
						   alert(address + " not found");
						 } else {
						   spotmap.setCenter(point, 13);
						   var marker = new GMarker(point);
						   spotmap.addOverlay(marker);
						   alert(spotmap.getCenter());
						   //marker.openInfoWindowHtml("<div id='mapmarker'><b>"+
						   //                         label+"</b><br>"+address+"</div>");
						 }
					   }
					   );
  }
}

function fitMap( map, points, minimum_zoom ) {
   var bounds = new GLatLngBounds();
   if(!minimum_zoom) {
	 minimum_zoom = 99;
   }
   for (var i=0; i< points.length; i++) {
      bounds.extend(points[i]);
   }
   var bounds_zoom = map.getBoundsZoomLevel(bounds)
	 map.setZoom(bounds_zoom < minimum_zoom ? bounds_zoom : minimum_zoom);
   map.setCenter(bounds.getCenter());
}

