google.load("maps", "2");
google.load("visualization", "1", {packages:["table"]});


function Map() {
  var map      = this;
  this.map_div = document.getElementById('map');
  
  this.disable_camera_updates = false;
  
  // // Setup the map.
  this.google_map = new GMap2(this.map_div);
  this.google_map.addControl(new GMapTypeControl());
  this.google_map.addMapType(G_PHYSICAL_MAP);
  this.google_map.setMapType(G_PHYSICAL_MAP);
  this.google_map.setCenter(new GLatLng(0, 0), 1);
  this.google_map.addControl(new GLargeMapControl());
  this.google_map.addControl(new GHierarchicalMapTypeControl());
  this.google_map.enableContinuousZoom();
  this.google_map.enableScrollWheelZoom();
   
  var bounds = new GLatLngBounds();
  bounds.extend(new GLatLng(20, -150));
  bounds.extend(new GLatLng(50, -40));
  this.google_map.setCenter(bounds.getCenter(), this.google_map.getBoundsZoomLevel(bounds));
  
  GEvent.addListener(this.google_map, "zoomend", function() {
    if(map.google_map.getZoom() > 14) {
      map.google_map.setMapType(G_NORMAL_MAP);
    } else {
      map.google_map.setMapType(G_PHYSICAL_MAP);
    }
  } );
  GEvent.addListener(this.google_map, "moveend", function() { map.update_cameras(); } );
  
  this.update_cameras = function() {
    if(this.disable_camera_updates == false) {
      minimum_x = this.google_map.getBounds().getSouthWest().lng();
      minimum_y = this.google_map.getBounds().getSouthWest().lat();
      maximum_x = this.google_map.getBounds().getNorthEast().lng();
      maximum_y = this.google_map.getBounds().getNorthEast().lat();
      if(minimum_x > maximum_x) minimum_x = minimum_x * -1; // No idea why this is necessary
      new Ajax.Request('/cameras.js',
                       { asynchronous: true,
                         evalScripts: true,
                         method: 'get',
                         parameters: "minimum_x="  + minimum_x.toString() +
                                     "&minimum_y=" + minimum_y.toString() +
                                     "&maximum_x=" + maximum_x.toString() +
                                     "&maximum_y=" + maximum_y.toString() })
    }
  }
  
  this.clear = function() {
    this.google_map.clearOverlays();
  }
}
