var SearchMapClusterController = Class.create(MapController, {

  setLayer: function(options) {
    this.zoomMin = options.zoom;
    this.zoomMax = options.stopAreasZoomThresholdMax-1;
    this.zoomCurrent = this.mapView.getZoom();

    this.mapView.addLayer("cluster",
        new LayerClusterProperties(
            options.zoom,
            options.stopAreasZoomThresholdMax-1));
    this.loadClusters();
  },

  displayClusters: function(transport) {
    if (transport.responseText) {
      var overlayItems = $A( eval(transport.responseText));
      var id = 0;

      overlayItems.each(function(overlayItem){
        var location = new Location(overlayItem.coordinates.lat,overlayItem.coordinates.lng,
                                    id, overlayItem.name, overlayItem.icon_path, "cluster");

      console.log( "displayClusters "+overlayItem.name);
        this.displayLocation(location);
        id = id + 1;
      }.bind(this.mapView));
    }
  },

  onZoomChanged: function() {
    console.log( "SearchMapClusterController.onZoomChanged");
    if ( this.loadingRequired()) {
      this.loadClusters();
    } else if ( this.unloadingRequired()) {
      this.mapView.cleanLocations("cluster");
    }
    this.zoomCurrent = this.mapView.getZoom();
  },

  loadClusters: function() {
    new Ajax.Request(options.overlayMarkersPath,
      {method: 'get', onSuccess: this.displayClusters.bind(this)});
  },
  // -----------------------------------------------------
  // private methods
  // -----------------------------------------------------

  zoomCompliant: function(zoom) {
    return this.zoomMin <= zoom && zoom <= this.zoomMax;
  },

  loadingRequired: function() {
    return !this.zoomCompliant( this.zoomCurrent) &&
            this.zoomCompliant( this.mapView.getZoom());
  },

  unloadingRequired: function() {
    return this.zoomCompliant( this.zoomCurrent) &&
          !this.zoomCompliant( this.mapView.getZoom());
  }
});

SearchMapClusterController.addMethods({
  setMapView: function($super,mapView) {
    $super(mapView);
    google.maps.event.addListener(mapView.map, "zoom_changed", this.onZoomChanged.bindAsEventListener(this));
  }
});

