$(function() {
   var map, directions, showDir = false;
   
   $(window).unload(GUnload); //Bind unload event for google map
   
   //Empty the map div
   var mapDiv = $('#mapDiv');
   mapDiv.empty();
   
   //If browser isn't compatible, then use static map
   if (!GBrowserIsCompatible())
      mapDiv.append($("<img id='map' src='http://maps.google.com/maps/api/staticmap?center=1463+County+Road+P,Rudolph,WI&markers=color:blue|1463+County+Road+P,Rudolph,WI&zoom=13&size=768x512&maptype=roadmap&sensor=false&key=ABQIAAAA5DYIBF6LUJZh5yK01o7GzhTKZrt6RXpBKFGbFNYju2ij3dDM1xRp_gaJKjb7HRIr5oAwVGDUfVp0Yw'>"));
      
   else {   //Browser is compatible, so set up dynamic map
      mapDiv.addClass('gMap');
      createMap(true);
      
      //Create div for entering directions
      $('#dirDiv').append($("<div id='directions'>" +
                              "Get Directions From: <input id='dirInput'>" +
                              "<a href='#' class='button'>Go</a>" +
                            "</div>"));
                      
      //Click event for directions 'Go' button
      $('#directions a').click(function(event) {
         event.preventDefault();
      
         var dirText = $("#dirInput").val();
         if (dirText == '')
            return;
      
         if (!showDir) {   //Do first-time setup for directions
            showDir = true;

            mapDiv.css('width', '43%');   //Shrink map to make room for directions
            createMap();                  //Re-load map in shrunken view
            
            //Add div to hold directions
            var stepsDiv = $("<div id='steps'></div>");
            $('#outerMap').append(stepsDiv);
            
            directions = new GDirections(map, stepsDiv.get(0));    //Create directions object
         }

         //Load directions
         directions.load("from:" + dirText + " to: 1463 Highway 66, Rudolph, WI 54475");
      });
      
      //Hitting enter in directions input is same as clicking 'Go' button
      $('#dirInput').keydown(function(event) {
         if (event.which == 13)
            $('#directions a').click();
      });
   }
   
   function createMap(setMark) {
      //Set up map centered on our building
      map = new GMap2(mapDiv.get(0));
      var latLng = new GLatLng(44.434408, -89.805272);
      map.setCenter(latLng, 13);
      map.setUIToDefault();
      
      //Mark our building
      if (setMark) {
         var marker = new GMarker(latLng);
         map.addOverlay(marker);
         marker.show();
      }
   }
});