// Карта для мест
PlaceMap = _Class.extend({
  init: function(map_id, lat, lng){
    this.pmap = new google.maps.Map2(document.getElementById(map_id));
    this.pmap.addControl(new GLargeMapControl());
    this.pmap.addControl(new GMapTypeControl());
    this.pmap.enableScrollWheelZoom()
    this.pmap.setCenter(new GLatLng(lat, lng), 15);
	  this.place_mark = false;
  },
  handle_inputs: function(){
  	jQuery("#" + this.inputs_prefix + '_lat').attr('value', this.place_mark.getLatLng().lat());
    jQuery("#" + this.inputs_prefix + '_lng').attr('value', this.place_mark.getLatLng().lng());
  },
  geocode_address: function(text){
    var geocoder = new GClientGeocoder();
    var _me = this;
    geocoder.getLocations(text, function(response){
      if (!response || response.Status.code != 200) {alert("Ничего не найдено")}
      else{
        var place = response.Placemark[0];
        var point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
        _me.pmap.setCenter(point);
        _me.move_place_marker(point);
      }
    });
  },
  move_place_marker: function(latlng){
    this.place_mark.setLatLng(latlng);
    this.handle_inputs();
  },
  set_place_marker: function(lat, lng, text, handle_inputs_prefix){
    if(!!this.place_mark){this.pmap.removeOverlay(this.place_mark);}
    this.place_text = text;
    this.point = new GLatLng(lat, lng);

    this.pmap.setCenter(this.point, 16);
    this.place_mark = new GMarker(this.point, {draggable: !!handle_inputs_prefix});
   

    // Если карта предназначена для редактирования, а не просмотра, обновляем 
    // values у инпутов с именами _lat, _lng с префиксом handle_inputs_prefix
    if (!!handle_inputs_prefix){
      this.inputs_prefix = handle_inputs_prefix;
      this.pmap.addOverlay(this.place_mark);
      this.handle_inputs();
      var _me = this;
      GEvent.addListener(this.place_mark, "dragend", function() {
        _me.handle_inputs();});
    } else {
      this.pmap.addOverlay(this.place_mark);
      this.pmap.openInfoWindowHtml(this.point, "<p class='bubble-mapbubble'>" + this.place_text + "</p>");
    }
  }
});

BubblePlaceMap = {
  load_for_bubble : function(lat, lng, title){
    google.load('maps', '2.x', {'callback' : function(){
      window.GMAPS_LOADED = true;
        BubblePlaceMap.render_bubble_map(lat, lng, title);
      }
    });
  },
  render_bubble_map: function(lat, lng, title){
    if (window.GMAPS_LOADED && window.BUBBLE_LOADED && !BubblePlaceMap.rendered){
      place_map = new PlaceMap("PlaceMapID", lat, lng);
      place_map.set_place_marker(lat, lng, title, false);
      BubblePlaceMap.rendered = true;
      setTimeout("place_map.pmap.checkResize()", 300);
    }
  }
}
