var infowindow = null;
var pick = null;;
var pick_coord = null;

// Callback function when user clicks on the map.
//
function handlePick(event)
{
  var map = window.MapObj;
  var latlng = event.latLng;

  // I also want to get the address associated with the click,
  // so do a reverse geocode.
  if (! GeoCoder) {
    var GeoCoder = new google.maps.Geocoder();
  }

  // Reverse geocode the pick.
  if (latlng) {
    GeoCoder.geocode({'latLng': latlng}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (results[1]) {
          // Get the formatted address so we can display it to the user.
          // Strip off the country and zip.
          var addr = results[0].formatted_address;
          addr = addr.substr(0, addr.lastIndexOf(','));
          if (isNumeric(addr.substr((addr.length-1), 1))) {
            addr = addr.substr(0, addr.lastIndexOf(' '));
          }

          // Put a marker at the user's pick.
          // We need this to create the info window.
          var marker = new google.maps.Marker({
              position: latlng,
              map: map});

          // If I have an existing marker, remove it.
          // Store the new marker.
          if (pick) {
            pick.setMap(null);
          }
          pick = marker;
          pick_coord = latlng;

          // Open the info window from which the user chooses the
          // RE Professional type.  Insert the user selected address.
          document.getElementById('pick_addr').innerHTML = 'You selected:<br><span class="pick_addr">' + addr + '</span>';
          var content = '<div class="info">' + document.getElementById('pick_div').innerHTML + '</div>';
          var infowindow = new google.maps.InfoWindow({
//            disableAutoPan: true,
            content: content});

          infowindow.open(map, marker);
        } else {
          alert("We couldn't find an address associated with your pick.");
        }
      } else {
        alert("Geocoder failed due to: " + status);
      }
    })
  }
}

// Callback function when user selects a RE Professional type in the
// info window.  This opens the Partners page.
//
function openPartners(type)
{
  window.open("/cgi-bin/Partners.pl?lat=" + pick_coord.lat() + "&lng=" + pick_coord.lng() + "&type=" + type, '_self');
}

// Callback function when the user wants to cancel the choice.
//
function cancelPartners()
{
  infowindow.close(window.MapObj, pick);
}

