
var map_with_points = Class.create({
	iconPath: '/_site/images/',
	mapContainer: null,
	points: {},
	map: null,
	mgr: null,
	markers:[],
	markerfinder:[],
	mother:{},
	afterInit:function(){},
	
  initialize: function(container, points, afterInit_callback) {
    this.mapContainer = $(container);
    this.points = points;
    if (afterInit_callback)
      this.afterInit = afterInit_callback;
    Event.observe(window,'load',this.init.bind(this));
    return this;
  },
	init: function() {
	  this.map = new GMap2(this.mapContainer);

	  this.points.mother.coord = new GLatLng(this.points.mother.lat, this.points.mother.lng);
	  this.map.setCenter(this.points.mother.coord, 14);
	  this.map.addControl(new GSmallMapControl());
	  this.map.setMapType(G_NORMAL_MAP);

	  window.setTimeout(function(){
			this.mother = this.addPoint(this.points.mother);

		  $H(this.points).each(function(pair){
				if (pair.key != 'mother') {
					for (var i=0;i<pair.value.length;i++) {
					  this.points[pair.key][i].coord = new GLatLng(this.points[pair.key][i].lat, this.points[pair.key][i].lng);
					  this.points[pair.key][i].distance = this.points[pair.key][i].coord.distanceFrom(this.points.mother.coord);
						this.addPoint(this.points[pair.key][i]);
					}
				}
			}.bind(this));

			this.mgr = new MarkerManager(this.map, { borderPadding: 50, maxZoom: 15, trackMarkers: false });
			this.mgr.addMarkers(this.markers, 1);
			this.mgr.refresh();

			new MarkerTracker(this.mother, this.map, { weight: 10, color: '#f90', iconScale: 1 });
			this.mother.openInfoWindowHtml(this.mother.html);
			
			this.afterInit(this);
		}.bind(this));
	},
	addPoint: function (point) {
	  if (point.icon){
		  var ico = new GIcon();
		  ico.image = this.iconPath+point.icon;
//		  ico.shadow = this.iconPath+'shadow.png';
		  ico.iconSize = new GSize(20, 20);
//		  ico.shadowSize = new GSize(45, 32);
		  ico.iconAnchor = new GPoint(10,10);
		  ico.infoWindowAnchor = new GPoint(10, 10);
		} else ico = null;

		var marker = new GMarker(point.coord, {icon:ico});
		if (point.html)
		  marker.html = point.html;
		else marker.html = '<strong style="display: block; border-bottom: 1px solid #aaa;">'+point.name+'</strong>'+point.street+'<br />'+point.zip+' '+point.city;

	  marker.openInfo = function () {
			this.openInfoWindowHtml(this.html);
		}

	  GEvent.addListener(marker, 'click', marker.openInfo.bind(marker));

	  this.markers.push(marker);
	  this.markerfinder.push(point.lat+','+point.lng);

	  return marker;
	},
	showMarker: function (lat,lng) {
		var marker = this.markers[this.markerfinder.indexOf(lat+','+lng)];
		marker.openInfoWindowHtml(marker.html);
	}

});
