var map = null;
var gdir = null;
var gmarkers = [];
var htmls = [];
var i = 0;
// arrays to hold variants of the info window html with get direction forms open
var to_htmls = [];
var from_htmls = [];

// functions that open the directions forms
function tohere(i) {
  	gmarkers[i].openInfoWindowHtml(to_htmls[i]);
}

function fromhere(i) {
  	gmarkers[i].openInfoWindowHtml(from_htmls[i]);
}

// ===== request the directions =====
function getDirections(i) {
	var saddr = document.getElementById("saddr").value
	var daddr = document.getElementById("daddr").value
	GEvent.clearListeners(gdir, "load");
	GEvent.addListener(gdir, "load", function() {
		// console.log(code);
		if (gdir.getStatus().code == G_GEO_SUCCESS) {
			gmarkers[i].closeInfoWindow();
			gmarkers[i].hide();		
		}		
		});
	
	gdir.load("from: "+saddr+" to: "+daddr);
}

function mapInit() {

    if (GBrowserIsCompatible()) {

      // A function to create the marker and set up the event window
      function createMarker(point,html) {
        var marker = new GMarker(point);

        // The info window version with the "to here" form open
        to_htmls[i] = html + '<p class="js">Get directions: <b>To here<\/b> | <a href="javascript:fromhere(' + i + ')">From here<\/a>' +
           '<span class="js2">Start address:<\/span><form action="javascript:getDirections(' + i + ')">' +
           '<input type="text" SIZE=40 MAXLENGTH=80 name="saddr" id="saddr" value="" /> ' +
           '<INPUT value="GO" type="submit" class="js3">' +
           '<input type="hidden" id="daddr" name="daddr" value="'+name+"@"+ point.lat() + ',' + point.lng() + '"/><\/p>';

        // The info window version with the "from here" form open
        from_htmls[i] = html + '<p class="js">Get directions: <a href="javascript:tohere(' + i + ')">To here<\/a> | <b>From here<\/b>' +
           '<span class="js2">End address:<\/span><form action="javascript:getDirections(' + i + ')">' +
           '<input type="text" SIZE=40 MAXLENGTH=80 name="daddr" id="daddr" value="" /> ' +
           '<INPUT value="GO" type="submit" class="js3">' +
                     '<input type="hidden" id="saddr" name="saddr" value="'+name+"@"+ point.lat() + ',' + point.lng() + '"/><\/p>';



               // The inactive version of the direction info
        html = html + '<p class="js">Get directions: <a href="javascript:tohere('+i+')">To here<\/a> | <a href="javascript:fromhere('+i+')">From here<\/a><\/p>';

        GEvent.addListener(marker, "click", function() {
          	marker.openInfoWindowHtml(html);
        });
        gmarkers[i] = marker;
        htmls[i] = html;
        i++;
        return marker;
      }

      // create the map
      map = new GMap2(document.getElementById("map"));
      map.addControl(new GLargeMapControl());
      map.addControl(new GMapTypeControl());
      map.setCenter(new GLatLng(40.827344,-74.216015), 14);

      // === create a GDirections Object ===
      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);
      });

      // Set up marker with info window 

      var point = new GLatLng(40.818344,-74.216015);
      var marker = createMarker(point,"<div id='balloon'><h1>Meislik Family Law<\/h1><img src='http://www.meislik.com/images/meislik_bldg.jpg' alt='Law offices of Meislik Family Law' width='110' height='89' /><br /><p>66 Park Street<br />Montclair, NJ 07042<\/p><p>Tel: 973-783-3000<br />Fax: 973-744-5757<\/p><\/div>")
      map.addOverlay(marker);
   		GEvent.trigger(marker, "click");
    }

    else {
      alert("Sorry, the Google Maps API is not compatible with this browser");
    }
}