
// Global variables
var histogramMapOpacity = 0.80;

/*
 * Create a map type that makes the tile grid visible.
 * For debugging.
 * Borrowed from here: http://code.google.com/apis/maps/documentation/javascript/maptypes.html#CustomMapTypes
 */
function CoordMapType() {
}

CoordMapType.prototype.tileSize = new google.maps.Size(256,256);
CoordMapType.prototype.maxZoom = 19;

CoordMapType.prototype.getTile = function(coord, zoom, ownerDocument) {
  var div = ownerDocument.createElement('DIV');
  div.innerHTML = coord;
  div.style.width = this.tileSize.width + 'px';
  div.style.height = this.tileSize.height + 'px';
  div.style.fontSize = '10';
  div.style.borderStyle = 'solid';
  div.style.borderWidth = '1px';
  div.style.borderColor = '#AAAAAA';
  return div;
};

CoordMapType.prototype.name = "Tile #s";
CoordMapType.prototype.alt = "Tile Coordinate Map Type";

var coordinateMapType = new CoordMapType();


/*
 * Create a histogram map type that is a black and white.
 * This is used both as an overlay and as a standalone map.
 */
var histogramMapTypeOptions =
  { getTileUrl: function(coord, zoom) { return "http://images.wherewerun.com/map_tiles/" + zoom + "/" + coord.x + "/" + coord.y + ".png"; },
    tileSize: new google.maps.Size(256, 256),
    isPng: true,
    name: "Histogram",
    alt: "Popularity Histogram",
    opacity: histogramMapOpacity,
    maxZoom: 15,
    minZoom: 5
  };
var histogramMapType = new google.maps.ImageMapType( histogramMapTypeOptions );

/*
 * Set up the Map!
 */
var map;
var geocoder;
function initialize_histogram_overlay_id_map()
{
  var latlng = new google.maps.LatLng(36.888, -96.236);
  var zoom = 5;
  var mapTypeId = google.maps.MapTypeId.ROADMAP;

  var queryCenter = getParameterByName("center");
  if( queryCenter )
  {
    var queryLatLng = queryCenter.split(",");
    latlng = new google.maps.LatLng( parseFloat( queryLatLng[0]), parseFloat( queryLatLng[1] ) );
  }
  var queryZoom = getParameterByName("zoom");
  if( queryZoom )
  {
    zoom = parseInt( queryZoom );
  }
  var queryMapType = getParameterByName("mapType");
  if( queryMapType )
  {
    if( queryMapType == "Histogram" )
    {
      mapTypeId = queryMapType;
    }
  }
  var queryColor = getParameterByName("color");

  var mapOptions =
    { zoom: zoom,
      center: latlng,
      mapTypeId: mapTypeId,
      mapTypeControlOptions: {
	mapTypeIds: [ google.maps.MapTypeId.ROADMAP, 'Histogram' ]
      },
      disableDefaultUI: false,
      maxZoom: 15,
      minZoom: 5
    };

  map = new google.maps.Map(document.getElementById("map"), mapOptions);

  // Instead of an overlay, add the histogram as a standalone map.
  map.mapTypes.set( 'Histogram', histogramMapType );
  // An overlay on the road map, so you can see both the streets and the histogram
  map.overlayMapTypes.insertAt( 0, histogramMapType );
//  map.overlayMapTypes.insertAt( 1, coordinateMapType ); // for debugging

  google.maps.event.addListener( map, 'center_changed', update_map_link );
  google.maps.event.addListener( map, 'zoom_changed', update_map_link );
  google.maps.event.addListener( map, 'maptypeid_changed', update_map_link );
}

/*
 * Some jQuery code.
 */
function getParameterByName( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

function update_map_link()
{
  var url = "http://" + window.location.host + "/?" + "center=" + map.getCenter().toUrlValue() + "&zoom=" + map.getZoom() + "&mapType=" + map.getMapTypeId() + "&color=bw";
  $('#map-link-button-popup-input-box').val( url );
  $('#map-link-button-popup').hide();
}

function handle_geocode_result( results, status )
{
  if( status == google.maps.GeocoderStatus.OK )
  {
    map.panToBounds( results[0].geometry.viewport );
    map.fitBounds( results[0].geometry.viewport );
    map.setCenter( results[0].geometry.location );
  }
  $('#map-go-button-popup').hide('fast');
}

function search_for_address( address_str )
{
  // Call Google's geocoder service to convert the address string to a latitude and longitude
  geocoder.geocode( { 'address': address_str }, handle_geocode_result )
}

function document_is_ready()
{
  $('#map-go-button-container').click(function(event) {
    event.preventDefault();
    $('#map-link-button-popup').hide();
    $('#map-go-button-popup').toggle('fast');
  });
  $('#map-go-button-popup-button').click(function(event) {
    event.preventDefault();
    search_for_address( $('#map-go-button-popup-input-box').val() );
  });
  $('#map-go-button-popup-input-box').keypress(function(event) {
    if( event.which == 13 ) // enter key
    {
      event.preventDefault();
      search_for_address( $('#map-go-button-popup-input-box').val() );
    }
  });
  $('#map-link-button-container').click(function(event) {
    event.preventDefault();
    $('#map-go-button-popup').hide();
    $('#map-link-button-popup').toggle('fast');
  });

  geocoder = new google.maps.Geocoder();
  initialize_histogram_overlay_id_map();
  update_map_link();
//  console.log( "center is %s", getParameterByName( "center" ) );
}

$(document).ready( document_is_ready );

