var gdir = '';
function initialize() 
{
  if (GBrowserIsCompatible()) 
  {
	map = new GMap2(document.getElementById("map_canvas"));
	// alert(map.getCenter().lat);
	map.setCenter(new GLatLng(44.08758502824516, -97.734375), 3);
	map.addControl(new GSmallMapControl());
	
	gdir=new GDirections(map, document.getElementById("directions"));

	// === Array for decoding the failure codes ===
	var reasons=[];
	reasons[G_GEO_SUCCESS]            = "Success";
	reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
	reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
	reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
	reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
	reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
	reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
	reasons[G_GEO_BAD_REQUEST]        = "A directions request could not be successfully parsed.";
	reasons[G_GEO_MISSING_QUERY]      = "No query was specified in the input.";
	reasons[G_GEO_UNKNOWN_DIRECTIONS] = "The GDirections object could not compute directions between the points.";
	
	// === catch Directions errors ===
	GEvent.addListener(gdir, "error", function() {
	var code = gdir.getStatus().code;
	var reason="Code "+code;
	if (reasons[code]) {
	  reason = reasons[code]
	}
	
	alert("Failed to obtain directions, "+reason);
	});

    
    GDownloadUrl("/pages/dealers_xml.php", function(data) {
    	
    	//var sidebar = document.getElementById('sidebar');
		//sidebar.innerHTML = '';
		var xml = GXml.parse(data);
		var markers = xml.documentElement.getElementsByTagName("marker");
		for (var i = 0; i < markers.length; i++) {
		var name = markers[i].getAttribute("name");
		var address = markers[i].getAttribute("address");
		var city = markers[i].getAttribute("city");
		var state = markers[i].getAttribute("state");
		var zip = markers[i].getAttribute("zip");
		var url = markers[i].getAttribute("url");
		var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
								parseFloat(markers[i].getAttribute("lng")));
		var marker = createMarker(point, name, address, city, state, zip, url);
		map.addOverlay(marker);
		//var sidebarEntry = createSidebarEntry(marker, name, address, city, state, zip);
        //sidebar.appendChild(sidebarEntry);
	  }
	});
  }
}
var i = 0;
var gmarkers = [];
var htmls = [];
// arrays to hold variants of the info window html with get direction forms open
var to_htmls = [];
var from_htmls = [];
function createMarker(point, name, address, city, state, zip, url) 
{
	var marker = new GMarker(point);
		var html = "<b>" + name + "</b> <br/>" + address + "<br>" + city + ", " + state + " " + zip + '<br /><a href="http://' + url + '">' + url + '</a><br>';
		GEvent.addListener(marker, 'mouseover', function() { marker.openInfoWindowHtml(html); });
		GEvent.addListener(marker, 'click', function() { marker.openInfoWindowHtml(html); });
		
		// The info window version with the "to here" form open
    to_htmls[i] = html + '<br>Directions: <b>To here</b> - <a href="javascript:fromhere(' + i + ')">From here</a>' +
       '<div style="width:250px;height:90px;text-align:center;"><span style="float:left;">Start address:</span>' + 
       '<form action="javascript:getDirections()">' +
       '<input type="text" size="30" name="saddr" id="saddr" value="" style="border:1px solid #000;padding:5px;font-size:11px;margin:0px;"/><br>' +
       '<input value="Get Directions" TYPE="SUBMIT" style="margin-top:3px;border:2px solid #841D18;padding:5px;">' +
       '<input type="hidden" id="daddr" value="'+name+"@"+ point.lat() + ',' + point.lng() + '"/>' +
       '</div>';
    // The info window version with the "from here" form open
    from_htmls[i] = html + '<br>Directions: <a href="javascript:tohere(' + i + ')">To here</a> - <b>From here</b>' +
       '<div style="width:250px;height:90px;text-align:center;"><span style="float:left;">From address:<span>' + 
       '<form action="javascript:getDirections()">' +
       '<input type="text" size="30" name="daddr" id="daddr" value="" style="border:1px solid #000;padding:5px;font-size:11px;margin:0px;"/><br>' +
       '<INPUT value="Get Directions" TYPE="SUBMIT" style="margin-top:3px;border:2px solid #841D18;padding:5px;">' +
       '<input type="hidden" id="saddr" value="'+name+"@"+ point.lat() + ',' + point.lng() +'"/>' +
       '</div>';
    // The inactive version of the direction info
    html = html + '<br>Directions: <a href="javascript:tohere('+i+')">To here</a> - <a href="javascript:fromhere('+i+')">From here</a>';
	gmarkers[i] = marker;
    htmls[i] = html;

	i++;

		return marker;
}
function createSidebarEntry(marker, name, address, city, state, zip) 
{
      var div = document.createElement('div');
      var html = '<b>' + name + '</b><br/>' + address + "<br>" + city + ", " + state + " " + zip + "<br><br>";
      div.innerHTML = html;
      div.style.cursor = 'pointer';
      div.style.marginBottom = '5px'; 
      GEvent.addDomListener(div, 'click', function() {
        GEvent.trigger(marker, 'click');
      });
      GEvent.addDomListener(div, 'mouseover', function() {
        div.style.backgroundColor = '#C1B79C';
      });
      GEvent.addDomListener(div, 'mouseout', function() {
        div.style.backgroundColor = '';
      });
      return div;
  }
 
  function tohere(i) 
  {
    gmarkers[i].openInfoWindowHtml(to_htmls[i]);
  }
  function fromhere(i) 
  {
    gmarkers[i].openInfoWindowHtml(from_htmls[i]);
  }
  function getDirections() 
  {
    var saddr = document.getElementById("saddr").value
    var daddr = document.getElementById("daddr").value
    gdir.load("from: "+saddr+" to: "+daddr);
  }
