// ----------------------------------------------------------------------------
// Copyright - J. C. Parker 2008
// ----------------------------------------------------------------------------

var map = null;

// ----------------------------------------------------------------------------

var routeList = [];
var oldRoute = null;

// ----------------------------------------------------------------------------
// 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;
}

// ----------------------------------------------------------------------------
// Focus on the route selected in the pulldown list
// ----------------------------------------------------------------------------

function jumpToRoute()
{
   var routeOptions = document.getElementById("routeOptions");

   var route = routeList[routeOptions.selectedIndex];

   // 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();
}

// ----------------------------------------------------------------------------
// Extract the parms from the URL
// ----------------------------------------------------------------------------

function parseParms(resultParms)
{
   // set the zoom and map defaults
   resultParms[0] = 10;
   resultParms[1] = G_NORMAL_MAP;
   resultParms[2] = null;

   // set the default to the center of the bay
   var mapCenter = new GLatLng(-38.089784, 144.802706);

   // 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;

            // you can't update a GLatLng object - you have to make a new one!
            delete mapCenter;
            var mapCenter = new GLatLng(parseFloat(latLng[0]), parseFloat(latLng[1]));
         }

         // is this the zoom parameter?
         if (keyValue[0] == 'z')
            resultParms[0] = keyValue[1];

         // is this the map type parameter?
         if (keyValue[0] == 't')
         {
            if (keyValue[1] == "m") { resultParms[1] = G_NORMAL_MAP;    }
            if (keyValue[1] == "k") { resultParms[1] = G_SATELLITE_MAP; }
            if (keyValue[1] == "h") { resultParms[1] = G_HYBRID_MAP;    }
         }

         // 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')
            resultParms[2] = keyValue[1];
      }
   }
   return mapCenter;
}

// ----------------------------------------------------------------------------
// 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
   var latLngStr = map.getCenter().toUrlValue();
   document.getElementById("linkToThisView").innerHTML = '<a href="http://www.bv.com.au/map/gmap/atb2008gmap.html'
       + '?ll='    + latLngStr
       + '&z='     + map.getZoom()
       + '&t='     + map.getCurrentMapType().getUrlArg()
       + '&slct1=' + document.getElementById("routeOptions").selectedIndex
       + '">Permalink to this view</a>';
}

// ----------------------------------------------------------------------------
// Don't name this 'onload' as it's a reserved word in Firefox
// ----------------------------------------------------------------------------

function load()
{
   // select an option in the pulldown list
   document.getElementById("routeOptions").selectedIndex = 0;

   if (GBrowserIsCompatible())
   {
      map = new GMap2(document.getElementById("mapDiv"));

      // use an array, as objects are passed by reference to a function
      // ugly but I'm not sure how to do this properly
      var prms  = [];
      var theCenter = parseParms(prms);

      // got the center and zoom level so set it
      map.setCenter(theCenter, parseInt(prms[0]), prms[1]);

      map.addControl(new GMapTypeControl());
      map.addControl(new GLargeMapControl());
      map.enableScrollWheelZoom();
      map.enableDoubleClickZoom();

      map.addMapType(G_SATELLITE_3D_MAP);

      GEvent.addListener(map, "moveend", updatePermaLink);

      GEvent.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();
      });

      GEvent.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 GGeoXml("http://www.bv.com.au/map/kml/ATB2008iconsgmap.kmz");
      map.addOverlay(iconOverlay);

      // get the routes
      routeList[0] = new GGeoXml("http://www.bv.com.au/map/kml/ATB2008km250gmap.kmz");
      routeList[1] = new GGeoXml("http://www.bv.com.au/map/kml/ATB2008km210ClkWgmap.kmz");
      routeList[2] = new GGeoXml("http://www.bv.com.au/map/kml/ATB2008km210AClkWgmap.kmz");
      routeList[3] = new GGeoXml("http://www.bv.com.au/map/kml/ATB2008km210SRetgmap.kmz");
      routeList[4] = new GGeoXml("http://www.bv.com.au/map/kml/ATB2008km210QRetgmap.kmz");
      routeList[5] = new GGeoXml("http://www.bv.com.au/map/kml/ATB2008km100gmap.kmz");
      routeList[6] = new GGeoXml("http://www.bv.com.au/map/kml/ATB2008km80gmap.kmz");
      routeList[7] = new GGeoXml("http://www.bv.com.au/map/kml/ATB2008km50gmap.kmz");

      // was a selection passed in the URL?
      if (prms[2] !== null)
         document.getElementById("routeOptions").selectedIndex = prms[2];

      jumpToRoute();

      var daysRemaining = daysTo('Oct 19, 2008');
      if (daysRemaining > 0)
         document.getElementById("daysToGo").innerHTML = daysRemaining + ' days to go. ';
   }
   else
      alert("Sorry, the Google Maps API is not compatible with this browser");
}

// ----------------------------------------------------------------------------

