var LocalMap = Behavior.create({

  initialize : function(options) {
    if (GBrowserIsCompatible()) {
      var view = options.startingView;
      this.map = new GMap2(this.element);
      this.map.setCenter( new GLatLng(view.lat, view.lon), view.zoom );
      this.map.addControl( new GSmallMapControl() );
      this.fixTeleAtlasOverlay();
      LocalMap.PropertyMarker.clickable = view.options.clickable ? true : false;
      var properties = options.properties;
      if (properties.length) this.addProperties(properties);
    }
  },

  addProperties : function(properties) {
    this.propertyMarkers = $A(properties).map( function(p) {
      return new LocalMap.PropertyMarker(p);
    });
    if (this.propertyMarkers.length > 0) {
      this.markerManager = new GMarkerManager(this.map);
      this.markerManager.addMarkers( this.propertyMarkers, 11 );
      this.markerManager.refresh();
    }
  },

  fixTeleAtlasOverlay : function() {
    var customTiles = new GTileLayerOverlay(
      new GTileLayer(null, null, null, {
        tileUrlTemplate: 'http://maps.ontrackmedia.ca/{Z}/{X}-{Y}.png',
        isPng:false
      })
    );
    this.map.addOverlay( customTiles );
  }

});


LocalMap.PropertyIcon = {
  image:  "/images/map/house.png",
  iconSize : new GSize(38,29),
  iconAnchor : new GPoint(12,28)
};
Object.extend( LocalMap.PropertyIcon, GIcon );

LocalMap.PropertyMarker = function(listing) {
    this.latlng = new GLatLng(parseFloat(listing.lat), parseFloat(listing.lon));
    this.listing = listing;
    GMarker.apply(this, [this.latlng, {icon: LocalMap.PropertyIcon} ] );
};
LocalMap.PropertyMarker.prototype = new GMarker( new GLatLng(0,0) );

LocalMap.PropertyMarker.prototype.initialize = function(map) {
  GMarker.prototype.initialize.call(this, map);
  if ( LocalMap.PropertyMarker.clickable ) {
    GEvent.addListener( this, 'click', function() {
      var mapinfo = document.createElement('div');
      mapinfo.className = 'mapinfo';
      map.openInfoWindowHtml( this.latlng, this.infoWindowContent() );
    });
  }
};

LocalMap.PropertyMarker.prototype.infoWindowContent = function() {
  var mapinfo = document.createElement('div');
  mapinfo.className = 'mapinfo';
  var addressLink = this.listing.address.link('/listings/'+this.listing.id);
  var imgLink = ('<img height="60" width="80" src="'+this.listing.photo+'" alt="" />').link('/listings/'+this.listing.id);
  mapinfo.innerHTML += imgLink;
  mapinfo.innerHTML += '<h4>' + addressLink + '</h4>';
  return mapinfo;
}

Event.observe(window, 'unload', GUnload );
