var map;

function initMap(){
  map = new GMap2(document.getElementById("googlemap"));
  map.addControl(new GLargeMapControl3D());
  map.addControl(new GMapTypeControl());
  map.setMapType(G_HYBRID_MAP);
  map.enableContinuousZoom();
  
  var allPoints = [];
  
  $.each(polygon_data, function(i, polygon){
    var path = jQuery.map(polygon.points, function(point){
      return new GLatLng(point.lat, point.lng);
    });
    var gPolygon = new GPolygon(path, polygon.stroke, 3, 1, polygon.fill, 0.5);
    GEvent.addListener(gPolygon, "click", function(latlng) {
      if (latlng) {
        $.ajax({
          url: polygon.url,
          success: function(data, status){
            map.openInfoWindow(latlng, data);
          }
        });
      }
    });
    
    map.addOverlay(gPolygon);
    if(polygon.current) allPoints = allPoints.concat(path);
  });
  
  centerAndZoomOnPoints(map, allPoints);
}

function centerAndZoomOnPoints(map, points) {
  var bounds = new GLatLngBounds(points[0], points[0]);
  for (var i=1, len = points.length ; i<len; i++) {
	  bounds.extend(points[i]);
  }

  centerAndZoomOnBounds(map, bounds);
}

function centerAndZoomOnBounds(map, bounds) {
    var center = bounds.getCenter();
    map.setCenter(center, map.getBoundsZoomLevel(bounds));
}

