/* Redline Software Inc. 2007 */

MapFrame = Class.create();

MapFrame.prototype = {
  initialize: function(options) {
    this.window = window; //frames[name].window;
    this.map = this.window.map;
    this.newIcon = new this.window.GIcon(this.window.G_DEFAULT_ICON, "/images/marker_new.png");

    this.options = options || {};
    this.defaultZoom = this.options['zoom'] || 14;
    this.coordinateField = this.options['coordinateField']; 
    this.map.savePosition();
  },

  getMarker: function(marker_var) {
    return this.window.markers[marker_var];
  },

  position: function() {
    var latlng = this.map.getCenter();
    return [latlng.lat(), latlng.lng(), this.map.getZoom()].join(',');
  },

  reset: function() {
    this.map.closeInfoWindow();
    this.map.returnToSavedPosition();
  },

  zoom: function(marker_var, zoom) {
    zoom = zoom || this.defaultZoom;

    if (this.map.getZoom() != zoom)
      this.map.setZoom(zoom);

    this.map.closeInfoWindow();

    var marker = this.getMarker(marker_var);
    if (marker) {
      this.map.panTo(marker.getPoint());
      if (marker.showInfoWindow)
        marker.showInfoWindow();
    }
  },

  setPosition: function(position) {
    if (this.coordinateField) $(this.coordinateField).value = [position.lat(), position.lng()].join(',');
  },

  placeMarker: function(lat, long) {
    if (this.window.new_location) {
      this.map.removeOverlay(this.window.new_location);
    }

    var uselatlong = !(lat == null && long == null);
    var position = uselatlong ? new this.window.GLatLng(lat,long) : this.map.getCenter(); 

    this.window.new_location = new this.window.GMarker(position, {draggable:true, bouncy:true, icon:this.newIcon});
    this.window.GEvent.addListener(this.window.new_location, 'dragend', function() { this.setPosition(this.window.new_location.getPoint()) }.bind(this));

    this.setPosition(position);

    this.map.addOverlay(this.window.new_location);
    if (uselatlong) this.map.setCenter(this.window.new_location.getPoint(), 14);
  },

  removeMarker: function(marker_var) {
    var marker = this.getMarker(marker_var);

    this.map.closeInfoWindow();
    this.map.removeOverlay(marker);
    delete this.window.markers[marker_var];
  },

  showMarkers: function(show) {
    this.reset();
    for (name in this.window.markers) {
      var marker = this.window.markers[name];
      show ? marker.show() : marker.hide();
    }
  }
}
