// ----------------------------------------------------------------------------
// Copyright - J. C. Parker 2009
// ----------------------------------------------------------------------------

var map = null;

// ----------------------------------------------------------------------------

var routeList = [];
var oldRoute = null;

var mapCenterLat = -38.089784;  // set the default to the center of the bay
var mapCenterLng = 144.802706;  // set the default to the center of the bay
var mapZoom      = 10;
var mapType      = G_NORMAL_MAP;
var mapTypeText  = "m";

var pullDownListIdx = 0;  // default to first route on the list

// ----------------------------------------------------------------------------
// Count down the days to the event
// ----------------------------------------------------------------------------

function daysTo(futureDay)
{
   var currentDate, currentDatems, futureDate, futureDatems;

   currentDate   = new Date();
   currentDatems = currentDate.getTime();

   futureDate    = new Date(futureDay);
   futureDatems  = futureDate.getTime();

   var daysRemaining = Math.ceil((futureDatems - currentDatems) / 86400000.0);

   return daysRemaining;
}

// ----------------------------------------------------------------------------
// Build a permanent URL link to the current view
// ----------------------------------------------------------------------------

function updatePermaLink()
{
   // triggers whenever the map is moved or zoomed. Also manually
   // invoked when the feed is first created to initially populate the feed
   // make a link to the current view and display it

   // get the URL and attempt to split it
   var urlParms = window.location.href.toLowerCase();
   urlParms = urlParms.split("?");
   //GLog.write('URL  = '+ urlParms);

   if (urlParms.length >= 1)
   {
      document.getElementById("linkToThisView").innerHTML = '<a href="' + urlParms[0]
         + '?ll='    + mapCenterLat +','+ mapCenterLng
         + '&z='     + mapZoom
         + '&t='     + mapTypeText
         + '&slct1=' + pullDownListIdx
         + '">Permalink to this view</a>';

      //GLog.write('PermaLink = '+ document.getElementById("linkToThisView").innerHTML);
   }
}

// ----------------------------------------------------------------------------
// Extract the parms from the URL
// ----------------------------------------------------------------------------

function parseParms()
{
   // get the URL and attempt to split it
   var urlParms = window.location.href.toLowerCase();
   urlParms = urlParms.split("?");

   // did the URL contain any parameters?
   if (urlParms.length > 1)
   {
      // get the parm(s) and attempt to split them
      var parms = urlParms[1].split("&");

      // for all the key value pairs
      for (var i=0; i<parms.length; i++)
      {
         // get the key value pairs and attempt to split them up
         var keyValue = parms[i].split("=");

         // the parms must come in key value pairs else the url is malformed
         if (keyValue.length != 2)
            break;

         // is this the lat/lng parameter?
         if (keyValue[0] == 'll')
         {
            // break up the value into lat and lng
            var latLng = keyValue[1].split(",");

            // the lat/lng must come as a pair else the url is malformed
            if (latLng.length != 2)
               break;

            mapCenterLat = parseFloat(latLng[0]);
            mapCenterLng = parseFloat(latLng[1]);
         }

         // is this the zoom parameter?
         if (keyValue[0] == 'z')
            mapZoom = parseInt(keyValue[1],10);

         // is this the map type parameter?
         if (keyValue[0] == 't')
         {
            mapTypeText = keyValue[1];
            if      (mapTypeText == "p") { mapType = G_PHYSICAL_MAP;  }
            else if (mapTypeText == "k") { mapType = G_SATELLITE_MAP; }
            else if (mapTypeText == "h") { mapType = G_HYBRID_MAP;    }
            else                         { mapType = G_NORMAL_MAP; mapTypeText = "m"; }
         }

         // is this the selection parameter? The selection
         // parameter determines which route is displayed
         // Note this uses slct1 as other similar code uses sclt2
         if (keyValue[0] == 'slct1')
            pullDownListIdx = keyValue[1];
      }
   }
}

// ----------------------------------------------------------------------------
// Focus on the route selected in the pulldown list
// ----------------------------------------------------------------------------

function jumpToRoute()
{
   pullDownListIdx = document.getElementById("routeOptions").selectedIndex;

   var route = routeList[pullDownListIdx];

   // the overlay must already exist if you try to remove it, else it's an error
   if (oldRoute !== null)
      map.removeOverlay(oldRoute);

   map.addOverlay(route);
   oldRoute = route;
   updatePermaLink();
}

// ----------------------------------------------------------------------------
// Don't name this 'onload' as it's a reserved word in Firefox
// ----------------------------------------------------------------------------

function load()
{
   // parameters in the URL will override all
   parseParms();

   // was a selection passed in the URL? else the first on the list is used
   document.getElementById("routeOptions").selectedIndex = pullDownListIdx;

   if (GBrowserIsCompatible())
   {
      map = new google.maps.Map2(document.getElementById("mapDiv"));

      // ready map center
      var mapCenter = new google.maps.LatLng(mapCenterLat,mapCenterLng);

      // got the center and zoom level so set it
      map.setCenter(mapCenter, mapZoom, mapType);

      // set up the UI controls on the map
      map.setUIToDefault();
      map.addMapType(G_SATELLITE_3D_MAP);

      google.maps.Event.addListener(map, "moveend", function()
      {
         // the map center changed - save it
         var latLngStr = map.getCenter().toUrlValue();
         var latLng    = latLngStr.split(",");
         mapCenterLat  = parseFloat(latLng[0]);
         mapCenterLng  = parseFloat(latLng[1]);

         updatePermaLink();
      });

      google.maps.Event.addListener(map, "zoomend", function(oldLevel, newLevel)
      {
         // the zoom level changed - save it
         mapZoom = newLevel;
         updatePermaLink();
      });

      google.maps.Event.addListener(map, "maptypechanged", function()
      {
         // the map type changed - save it
         mapType     = map.getCurrentMapType();
         mapTypeText = mapType.getUrlArg();
         updatePermaLink();
      });

      google.maps.Event.addListener(map, "infowindowopen", function()
      {
         // the map moves when the infowindow opens - later
         // on we'll stick it back to where it came from
         map.savePosition();
      });

      google.maps.Event.addListener(map, "infowindowclose", function()
      {
         // the map moves when the infowindow opens
         // we'll stick it back to where it came from
         map.returnToSavedPosition();

         // at this point the 'moveend' event is fired
      });

      // get the icons
      var iconOverlay = new google.maps.GeoXml("http://www.bv.com.au/map/kml/ATB2009iconsgmap.kml?5");
      map.addOverlay(iconOverlay);

      // get the routes
      routeList[0] = new google.maps.GeoXml("http://www.bv.com.au/map/kml/ATB2009km250gmap.kmz");
      routeList[1] = new google.maps.GeoXml("http://www.bv.com.au/map/kml/ATB2009km210ClkWgmap.kmz");
      routeList[2] = new google.maps.GeoXml("http://www.bv.com.au/map/kml/ATB2009km210AClkWgmap.kmz");
      routeList[3] = new google.maps.GeoXml("http://www.bv.com.au/map/kml/ATB2009km210SRetgmap.kmz");
      routeList[4] = new google.maps.GeoXml("http://www.bv.com.au/map/kml/ATB2009km210QRetgmap.kmz");
      routeList[5] = new google.maps.GeoXml("http://www.bv.com.au/map/kml/ATB2009km100gmap.kmz");
      routeList[6] = new google.maps.GeoXml("http://www.bv.com.au/map/kml/ATB2009km80gmap.kmz");
      routeList[7] = new google.maps.GeoXml("http://www.bv.com.au/map/kml/ATB2009km50gmap.kmz");

      jumpToRoute();

      var daysRemaining = daysTo('Oct 18, 2009');
      if (daysRemaining > 0)
         document.getElementById("daysToGo").innerHTML = daysRemaining + ' days to go. ';
   }
   else
      alert("Sorry, the Google Maps API is not compatible with this browser");
}

// ----------------------------------------------------------------------------

