// Declare variables for later use
var recentMap;
var searchMap;
var geoXml;
var clearedAddress = false;

// Attach handlers for window events
addEventHandler(window, 'load',   loadPage);
addEventHandler(window, 'unload', unloadPage);

function loadPage()
{
  // loadPage: initialize the API and load the maps onto the page

  // Get the recent-entries map container div
  var mapDiv = document.getElementById('recent_map');

  // Confirm browser compatibility with the Maps API
  if (!GBrowserIsCompatible())
  {
    if (mapDiv == null)
      mapDiv = document.getElementById('no_recent');

    mapDiv.innerHTML = '<strong>Important note</strong>: this site requires ' +
        'Google Maps, which appear to be incompatible with your browser. ' +
        'May we suggest <a href="http://getfirefox.com">Firefox</a>?';
  }
  else
  {
    if (mapDiv != null)
    {
      // Initialize the recent-entries map object
      var options = {backgroundColor: '#D7D5E3', mapTypes: [G_PHYSICAL_MAP]};
      recentMap = new GMap2(mapDiv, options);
      recentMap.setCenter(new GLatLng(39.8, -98.5), 3, G_PHYSICAL_MAP);
      recentMap.enableContinuousZoom();
  
      // Limit the minimum zoom for the terrain map type
      G_PHYSICAL_MAP.getMinimumResolution  = function () {return 3};
  
      // Add a couple of standard map controls
      recentMap.addControl(new GSmallMapControl());
      recentMap.addControl(new GScaleControl());
  
      // Initialize the KML processor
      var options = {createmarker: addDataPoint};
      geoXml = new EGeoXml(recentMap, 'services/recent_campgrounds.php?type=kml', options);
      geoXml.parse();
    }

    // Also initialize the small click-to-search map
    var options = {backgroundColor: '#D7D5E3', mapTypes: [G_NORMAL_MAP]};
    searchMap = new GMap2(document.getElementById('search_map'), options);
    searchMap.setCenter(new GLatLng(40, -96), 2);
    searchMap.disableDragging();
    GEvent.addListener(searchMap, 'click', searchMapClick);
  }
};

function searchMapClick(overlay, coordinates)
{
  // searchMapClick: load the search page with the clicked coordinates
  document.location = 'search/#' + coordinates.toUrlValue() + ',8';
};

function searchSubmit()
{
  var address = document.getElementById('address').value.replace('"', '\"');
  
  if (address == '')
    alert('Please enter a place name or zip code to search near.');
  else
    location = '/search#address:' + encodeURIComponent(address);
};

function getAnchor(iconUrl)
{
  // getAnchor: return the infoWindowAnchor property for the given icon image URL
  if (iconUrl.indexOf('bus') > -1)
    return new GPoint(16, 0);
  else if (iconUrl.indexOf('trailer') > -1)
    return new GPoint(19, 10);
  else
    return new GPoint(16, 6);
};

function addDataPoint(coordinates, name, description, style)
{
  // addDataPoint: display a recent-entry placemark found by the KML processor 

  // Create and initialize the icon from the style in the KML
  var myIcon = new GIcon();
  myIcon.image      = geoXml.styles[style].image;
  myIcon.iconSize   = new GSize(32, 32);
  myIcon.shadow     = geoXml.styles[style].shadow;
  myIcon.shadowSize = new GSize(59, 32);
  myIcon.iconAnchor = new GPoint(16, 28);
  myIcon.infoWindowAnchor = getAnchor(myIcon.image);

  // Create a marker for this data point
  var options = {icon: myIcon, title: name};
  var thisMarker = new GMarker(coordinates, options);

  // Attach infowindow to the marker with content from the KML
  options = {maxWidth: 250};
  thisMarker.bindInfoWindowHtml('<div id="infowindow"><h3>' + name + '</h3>' + 
    description + '</div>', options);

  // Add the marker to the recent-entries map 
  recentMap.addOverlay(thisMarker);

  // Also create a list entry (alongside the map) with the icon & name
  var recentRow = document.createElement('li');
  recentRow.innerHTML = 
    '<img width="32" height="32" src="' + myIcon.image + '" />' + name;
  document.getElementById('recent_list').appendChild(recentRow);

  recentRow.onclick = 
    function ()
    {
      // A click on the list entry triggers a click on its associated marker
      GEvent.trigger(thisMarker, "click")
    };
};

function unloadPage()
{
  // unloadPage: finalize the Maps API
  if (searchMap != null)
    GUnload();
};

function clearAddress()
{
  if (!clearedAddress)
  {
    // The first time the user clicks in the address box, clear the instructions
    document.getElementById('address').value = '';
    clearedAddress = true;
  }
};
