/*************************** JS TO SUPPORT MAP IN DETAILS PAGE ****************/

var _focusPoint = null;
var _focusLabel = null;
var _controllerBaseURL = null;

// init map for details page
function mapOnLoad( x, y, z, mt, label, ajaxBaseURL, controllerBaseURL ) {
  log('mapOnLoad');
  _ajaxBaseURL = ajaxBaseURL;
  _controllerBaseURL = controllerBaseURL;
  if (GBrowserIsCompatible()) {
   _focusPoint = new GLatLng( x, y );
   _focusLabel = label;
   _map = new GMap2(document.getElementById('poi'));
   _map.addControl(new GSmallMapControl());
   _map.addControl(new GMapTypeControl());
   _map.addControl(new GScaleControl());
   _map.setCenter( _focusPoint, z );
   // can only do this after setting centre, which is a bit odd if you ask me
   _map.setMapType( stringToMapType( mt ) );
   GEvent.addListener( _map, "moveend", mapUpdate );
   mapUpdate();
  }
  else {
    alert("Your browser does not appear to support Google Maps");
  }
}

function mapUpdate() {
  var x = _map.getBounds().getSouthWest().lat() + "," + _map.getBounds().getSouthWest().lng() + "," + _map.getBounds().getNorthEast().lat() + "," + _map.getBounds().getNorthEast().lng();
  log("mapUpdate: " + x);
  downloadUrl( 'mapUpdate', getLocalContentURL( _map,ALL_MY_PLACEMARKS ), function(doc) {
    log("mapUpdate.callback");
    var jsonData = eval('(' + doc + ')');
    _map.clearOverlays();
    plotPlacesDetails(jsonData);
    // reinstate original marker
    _map.addOverlay( new GMarker( _focusPoint, { icon: createIcon(), title: _focusLabel } ) );
  } );
}

function plotPlacesDetails( jsonData ) {
    log("plotPlacesDetails");
    if (jsonData == null || jsonData.places == null) return;
    for (var i=0; i<jsonData.places.length; i++) {
        var pd = new PlacemarxDetails(jsonData.places[i], _controllerBaseURL, "allp" );
        var point = new GLatLng(pd.lat, pd.lng);
        if ( point.distanceFrom( _focusPoint ) > 150 || pd.title.toLowerCase() != _focusLabel.toLowerCase() ) {
            var marker = createMarkerDetails(point,pd);
            _map.addOverlay( marker );
        }
    }
}

// Create marker for details page
function createMarkerDetails(point,pd) {
      var icon = createOtherIcon();
      var marker = new GMarker(point, {icon: icon, title: pd.title});
      GEvent.addListener(marker, "click", function() {
        document.location=_controllerBaseURL + "op=sd" +
          "&lbl=" + encodeURIComponent(pd.title) +
          "&ll=" + pd.encodedLL +
          "&z=" + _map.getZoom() +
          "&mt=" + mapTypeToString( _map.getCurrentMapType() );
      });
      return marker;
}
