// Declare variables for later use
var map;
var geoXml;
var geocoder;
var startMarker;
var data = new Array();
var markers = new Array();
var clicked;
var current;

  // Initialize the geocoder object
  geocoder = new GClientGeocoder();

function loadMap()
{

  // loadMap: initialize the API and load the map onto the page

  // Get the map container div
  var mapDiv = document.getElementById('map');

  // Confirm browser compatibility with the Maps API
  if (!GBrowserIsCompatible())
    mapDiv.innerHTML = 'Sorry, your browser isn\'t compatible with Google Maps.';
  else
  {
    // Initialize the core map object
    map = new GMap2(mapDiv,
      {mapTypes: [G_NORMAL_MAP, G_SATELLITE_MAP, G_HYBRID_MAP, G_PHYSICAL_MAP]});

    // Set the starting map viewport
    var coordinates1 = new GLatLng(33.702846,-117.760835);
    map.setCenter(coordinates1, 10, G_PHYSICAL_MAP);

    // Add the standard map controls
    map.addControl(new GLargeMapControl());
    map.addControl(new GScaleControl());
    map.addControl(new GOverviewMapControl());
    map.addControl(new GMapTypeControl());

    // Load the initial map before accepting user input
    geoXml = new GGeoXml('OCFireStations.kml');
    //map.addOverlay(geoXml);
    function xmlLoaded()
    {
        geoXml.gotoDefaultViewport(map);
    };

    // Initialize the KML processor
    var url = 'OCFireStations.kml';
    var options = {createmarker: addDataPoint, nozoom: true};
    geoXml = new EGeoXml(map, url, options);

    // Attach an event handler for after the KML is processed
    GEvent.addListener(geoXml, 'parsed', xmlParsed);

    // Load the KML
    geoXml.parse();

    // Attach an event to refresh the marker display whenever the map moves
    GEvent.addListener(map, 'moveend',         mapMoveEnd);
    GEvent.addListener(map, 'infowindowopen',  mapInfoWindowOpen);
    GEvent.addListener(map, 'infowindowclose', mapInfoWindowClose);
  }
};

function addDataPoint(coordinates, name, description)
{
  // addDataPoint: save the data for a placemark found by the KML processor 
  var d = data.length;
  data[d] = {coords: coordinates, title: name, details: description};
};

function xmlParsed()
{
  // xmlParsed: after KML processing, initialize the marker display
  mapMoveEnd();
};

function mapMoveEnd()
{
  //  mapMoveEnd: get the new map boundary coordinates for use in marker display
  GAsync(map, 'getBounds', afterGetBounds);
};

function afterGetBounds(mapBounds)
{
  //  afterGetBounds: refresh the marker display 
  
  // Don't refresh if the currently-selected marker is still in view
  if (current != null)
  {
    if (mapBounds.contains(current))
      return;
    else
      map.closeInfoWindow();
  }

  // Prepare to build new sidebar content by starting with a clean slate
  var sidebarContent = '<HR SIZE=2 NOSHADE><u>The closest fire stations are:</u><p>';
  
  // Remove previous set of markers from the map and the array
  for (var m = markers.length - 1; m >= 0; m--)
  {
    map.removeOverlay(markers[m]);
    markers.splice(m, 1);
  }

  // Create a base icon
  var numberIcon = new GIcon(G_DEFAULT_ICON);

  // Look for data in the new map area
  for (var d = 0; d < data.length; d++)
  {
    if (mapBounds.contains(data[d].coords))
    {
      // Map does contain this data point; create a marker and add it to the map
      var fd = data[d].title.substring(1,4);
	var fsnpos = parseInt(data[d].title.indexOf('#'));
	var fsn = data[d].title.substring(fsnpos + 1);
	var fsnumb = parseInt(fsn);
	if (fsnumb > 100)
	  fsnumb = fsnumb - 190;
	m = markers.length;
	if (fd == 'CFA')
	  numberIcon.image = 
          'http://gmaps-samples.googlecode.com/svn/trunk/markers/orange/marker' + 
          (fsnumb) + '.png';
	else
	  numberIcon.image = 
          'http://gmaps-samples.googlecode.com/svn/trunk/markers/green/marker' + 
          (fsnumb) + '.png';
        markers[m] = new GMarker(data[d].coords, {icon: numberIcon});
        markers[m].data = data[d];
        map.addOverlay(markers[m]);

      // Also attach an event handler to show infowindow when marker is clicked
      GEvent.addListener(markers[m], 'click', 
        new Function('showDetail(' + m + ')'));
      
      // Create sidebar content for this data point, including click event handler
	if (document.getElementById('start').value == '')
	  sidebarContent = sidebarContent + 
          '<li><a href="#" onclick="showDetail(' + m + '); return false">' + 
          data[d].title + '</a></li>';
	else
	  {
	  var pos = parseInt(document.cookie.indexOf(')'));
	  var pos1 = 1;
	  var pos4 = pos - 1;
	  var pos2 = pos4 / 2 -1;
	  var pos3 = pos2 + 2;
	  var x = parseFloat(document.cookie.substring(pos1,pos2));
	  var y = parseFloat(document.cookie.substring(pos3,pos4));
	  var coordinates1 = new GLatLng(x, y);
	  var distance = coordinates1.distanceFrom(data[d].coords);
	  sidebarContent = sidebarContent + 
          '<dt><a href="#" onclick="showDetail(' + m + '); return false">' + 
          data[d].title + '</a><dd><font size="-2"> ' + Math.round(distance.toFixed(0) / 16.09344) /100 + 
		   ' miles</font>';
	  }
    }
  }
  
  if (markers.length == 0)
    // No data points found in map boundaries
    sidebarContent = '<li style="list-style: none">No results found in map area. ' +
        'Try zooming out or moving the map.</li>';
    // Move the new content into the sidebar
    if (document.getElementById('start').value != '')
      document.getElementById('list').innerHTML = sidebarContent;

};

function showDetail(m)
{
  // showDetail: open the infowindow for the given map marker
  current = clicked = markers[m].data.coords;
  markers[m].openInfoWindow(
    '<h4 style="margin: 0; font-size=120%">' + markers[m].data.title + '</h3>' +
    '<p style="margin: 0; font-size=90%">' + markers[m].data.details + '</p>');
};

function mapInfoWindowOpen()
{
  // mapInfoWindowOpen: set the variable that keeps track of the selected coords
  current = clicked;
};

function mapInfoWindowClose()
{
  // mapInfoWindowClose: clear the variable that keeps track of the selected coords
  current = null;
};

// Call the Google geocoder with the address supplied by the user
function geocode()
{
	var address = document.getElementById('start').value;
	geocoder.getLatLng(address, afterGeocode);
};

function afterGeocode(coordinates)
{

	// set a cookie with these coordinates for distance calculations
	  document.cookie = coordcookie=coordinates;

	// afterGeocode: Callback function for the geocoder, showing the coords on the map
	if (coordinates == null)
		alert('Address not found. Please try again.');
	else if (!map.getBounds().contains(coordinates))
		alert('Address not found in map area. Please try again.');
	else
	{
		// Address was found
		if (startMarker == null)
		{
			// This is the first time we've geocoded an address, so create the marker
			startMarker = new GMarker(coordinates);
			map.addOverlay(startMarker);
			map.setCenter(coordinates, 14, G_PHYSICAL_MAP);
		}
		else
		{
			// The marker already exists; just move it to the new coordinates
			startMarker.setPoint(coordinates);
			map.setCenter(coordinates, 14, G_PHYSICAL_MAP);
		}
	}
};