var data;
var satellitePhysicalZoomThreshold = 6;
document.observe("dom:loaded", function() {
  try { var hasMap = document.getElementById('map_canvas') } catch(e) { var hasMap = false };
  if (GBrowserIsCompatible() && hasMap) {
    // Create a new google map
    var map = new GMap2(document.getElementById('map_canvas'));
    
    // Center on the world
    map.setCenter(new GLatLng(25, 0), 1);
    
    // Add controls
    map.addControl(new GSmallZoomControl());
    map.addMapType(G_PHYSICAL_MAP);
    map.setMapType(G_PHYSICAL_MAP);
    
    
    GEvent.addListener(map, "zoomend", function(oldLevel, newLevel) {
      if (newLevel < satellitePhysicalZoomThreshold && map.getCurrentMapType() != G_PHYSICAL_MAP)
      {
        map.setMapType(G_PHYSICAL_MAP);
      }
      else if (map.getCurrentMapType() != G_SATELLITE_MAP && newLevel > satellitePhysicalZoomThreshold)
      {
        map.setMapType(G_HYBRID_MAP);
      }
    });
    
    
    setTimeout(function() {
      var maptimizeMap = new Maptimize.Map(map, {
        onMarkerClicked: function(marker) {
          var url = "/"+currentLocale+"/courses/"+marker.getId()+".js"
          new Ajax.Request(url, {
            method: 'get',
            onSuccess: function(transport) {
              var course = transport.responseText.evalJSON();
              if (course.name == course.club.name)
                var name = course.name
              else
                var name = course.club.name + "<br />" + course.name
              var content = "<a href=\"/"+currentLocale+"/courses/"+course.id+"\">"+name+"</a>"
              marker.getGMarker().openInfoWindowHtml(content);
            }
          });
        },
        onClusterClicked: function(cluster) {
          if (cluster.canExpandOnMap()) {
            cluster.expandOnMap();
          }
          else {
            cluster.requestIds(function(ids) {
              var url = "/"+currentLocale+"/courses/"+ids.join('__')+".js"
              //console.log(url);
              new Ajax.Request(url, {
                method: 'get',
                onSuccess: function(transport) {
                  var courses = transport.responseText.evalJSON();
                  var content = ["<ol>"]
                  courses.each(function(course, course_index) {
                    course = course.evalJSON();
                    if (course.name == course.club.name)
                      var name = course.name;
                    else
                      var name = course.club.name + " — " + course.name;
                    content.push("<li><a href=\"/"+currentLocale+"/courses/"+course.id+"\">"+name+"</a></li>");
                  })
                  content.push("</ol>");
                  cluster.getGMarker().openInfoWindowHtml(content.join(''));
                }
              });
            });
          }
        }
      });
      maptimizeMap.refresh();
    }, 500);
  }

  window.onunload = GUnload;
});