   
   var map;
   var iwindow = new google.maps.InfoWindow({maxWidth:237});
   var myGeoXml;
   var myMaps
   var directionsDisplay;
   var directionsService = new google.maps.DirectionsService();
/*
   var map_styles = [
      {
           featureType: "all",
           elementType: "all",
           stylers: [
               { visibility:"off" }
           ]
       },
      {
           featureType: "landscape.natural",
           elementType: "all",
           stylers: [
              { visibility: "on"},
              { hue: "#d1def1" },
              { saturation: -47 },
              { lightness: 57 }
           ]

       },
   {
           featureType: "water",
           elementType: "all",
           stylers: [
              { visibility: "on"},
               { hue: "#89d3dc" },
               { saturation: 52 },
               { lightness: 10 }
           ]
       },
      {
           featureType: "road.highway",
           elementType: "all",
           stylers: [
              { visibility: "on"},
              { hue: "#d1def1" },
              { saturation: -47 },
              { lightness: 5 }
           ]
       },
      {
           featureType: "road.arterial",
           elementType: "all",
           stylers: [
              { visibility: "on"},
               { hue: "#d1def1" },
               { saturation: -47 },
               { lightness: 17 }
           ]
       },
        {
       featureType: "administrative.locality",
       elementType: "all",
       stylers: [
         { visibility: "off" }
       ]
     },
     {
           featureType: "poi.park",
           elementType: "all",
           stylers: [
               {visibility: "off"},
               { hue: "#8696a5" },
               { saturation: -60 },
               { lightness: -19 }
           ]
       }

   ];
*/

/* original with dark blue background */
var map_styles = [
   {
		featureType: "all",
		elementType: "all",
		stylers: [
			{ visibility:"off" }
		]
	},
   /* 
     {
		featureType: "administrative.locality",
		elementType: "labels",
		stylers: [
			{ visibility:"on"},
            { invert_lightness:true}
		]
    },
   */
   {
		featureType: "landscape.natural",
		elementType: "all",
		stylers: [
		   { visibility: "on"},
			{ hue: "#1f3163" },
			{ saturation: 36 },
			{ lightness: -73 }		]
	},
{
		featureType: "water",
		elementType: "all",
		stylers: [
		   { visibility: "on"},
			{ hue: "#89d3dc" },
			{ saturation: 52 },
			{ lightness: 10 }
		]
	},
   {
		featureType: "road.highway",
		elementType: "all",
		stylers: [
		   { visibility: "on"},
			{ hue: "#d1def1" },
			{ saturation: -47 },
			{ lightness: 15 }
		]
	},
   {
		featureType: "road.arterial",
		elementType: "all",
		stylers: [
		   { visibility: "on"},
			{ hue: "#d1def1" },
			{ saturation: -47 },
			{ lightness: -37 }
		]
	}
];
/* 
,
  {
		featureType: "poi.park",
		elementType: "labels",
		stylers: [
		    {visibility: "on"},
		]
	} 
*/
   function initialize() {

      myMaps = [
         {
            title:'Apex Communities',
            kml:'apex.kml',
            hierarchical:false, // set to true if My Map is series of top-level polygons with child markers,
            markerIconSpriteOffset:['-8px','-6px'],
            markerIconSpriteSize:['12px','13px'],
            legendFunction:null
         }
      ];

      var kmlUrls = [];
      for (var i=0; i<myMaps.length; i++) {
          kmlUrls.unshift(myMaps[i].kml);
      }

      var d = new Date;
      var time = d.getTime();

      var latlng = new google.maps.LatLng(51.01, -114.08);
      var myOptions = {
        zoom: 10,
        center: latlng,
        streetViewControl: false,
        maxZoom: 14,
        minZoom: 9,
        mapTypeControlOptions: {
            mapTypeIds: ['cmlc',google.maps.MapTypeId.TERRAIN],
            style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
            backgroundColor: 'transparent'
        },
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };
      var map = new google.maps.Map(document.getElementById("map_canvas"),
          myOptions);

      var cmlcStyleOptions = {
          name: "Map"
      }
      var cmlcMapType = new google.maps.StyledMapType(map_styles, cmlcStyleOptions);
      map.mapTypes.set('cmlc', cmlcMapType);
      map.setMapTypeId('cmlc');

      //$('#map_canvas').css('opacity','0.93');


        //add directions...
        //directionsDisplay = new google.maps.DirectionsRenderer();


      myGeoXml = new geoXML3.parser({
          map: map,
          singleInfoWindow: true,
          infoWindow: iwindow,
          zoom: false,
          pmParseFn: parsePlacemark,
          afterParse: useTheData,
          polygonOptions: {clickable:false}
      });
      myGeoXml.parse(kmlUrls);

   }
   function parsePlacemark(node, placemark){
       // node = the actual KML node
       // placemark = JSON representation of the node; this gets passed into createMarker, createPolygon, etc.

      //if(!!placemark.Point) {
         //console.log(node, placemark);
      //   placemark.description += '<div class="directionsBox">Get driving directions from...<br/><i>e.g. Street Address, City, Prov/State</i><br/><input type="text" id="start" name="start" size="27" /> <a href="javascript:void" class="textLink" onclick="calcRoute(\$(\'#start\').val(),' + placemark.Point.coordinates[0].lat + ',' + placemark.Point.coordinates[0].lng + ');">Go!</a></div>';
      //}
   }
   function useTheData(ignoredocs){
       // Geodata handling goes here, using JSON properties of the doc object
       var menuHtml = '';
       var style;

       //menuHtml = '<div class="glossymenu" id="glossymenu" style="float:left;z-index:10;">';

       for(var x=0; x < myGeoXml.docs.length; x++) {
           if (myMaps[x].legendFunction) {
              menuHtml += myMaps[x].legendFunction();
           }

          var ulOpen = false;
          var regionCounter = 0;

           for (var i = 0; i < myGeoXml.docs[x].placemarks.length; i++) {
              if(myGeoXml.docs[x].placemarks[i].Point) {
                 menuHtml += '<a href="javascript:void(0);" class="marker" onclick="click_placemark('+ x + ',' + i + ')">' + myGeoXml.docs[x].placemarks[i].name + '</a>';
              }else{
                 //regionCounter++;
                 //menuHtml += '<a href="javascript:void(0);" class="menuitem submenuheader region" onclick="zoom_to_region('+ x + ',' + i + ')">' + myGeoXml.docs[x].placemarks[i].name + '</a><div class="submenu" id="menu' + regionCounter + '"><ul>';
              }
           } 
       }

       $('#map_nav').append(menuHtml);
       
       //$('#map_layer').hide();
       //$('#map_layer').css('visibility','visible');
       //$('#map_layer').css('top','121px');
       //$('#map_layer').css('left','350px');

       // GK: Let accordion init handle what menu is displayed on load/init...
       //init_accordion();
       //ddaccordion.expandone('submenuheader',0);

       //directionsDisplay.setPanel(document.getElementById("directionsPanel"));
   };
   function show_geoxml_map(i){
      // i = index of myGeoXml.docs[] array
      if(myGeoXml.docs.length > 0 && !!myGeoXml.docs[i]) {
         for(var x=0; x<myGeoXml.docs.length; x++) {
            if(x == i && !!myGeoXml.docs[x]) {
                myGeoXml.showDocument(myGeoXml.docs[x]);
               if(!!myGeoXml.docs[x].bounds) {
                  console.log(myGeoXml.docs[x].bounds);
                  map.fitBounds(myGeoXml.docs[x].bounds);
               }
            }else{
               if(!!myGeoXml.docs[x]) {
                  myGeoXml.hideDocument(myGeoXml.docs[x]);
               }
            }
         }
      }else{
         if(!myGeoXml.docs[i]) {
            //console.log('myGeoXml map ' + i + ' not parsed yet!');
         }else{
            //console.log('No maps loaded into myGeoXml.docs[] yet!');
         }
      }
   }
    function click_placemark (k, i){
        if(myGeoXml.docs[k].placemarks[i].Polygon) {
            google.maps.event.trigger(myGeoXml.docs[k].placemarks[i].polygon, "click");
        }else if(myGeoXml.docs[k].placemarks[i].Point) {
            google.maps.event.trigger(myGeoXml.docs[k].placemarks[i].marker, "click");
        }else if(myGeoXml.docs[k].placemarks[i].LineString) {
            google.maps.event.trigger(myGeoXml.docs[k].placemarks[i].polyline, "click");
        }else{
            //console.log("Unhandled placemark type!");
        }
    }
    function zoom_to_region (k, i){
        if(myGeoXml.docs[k].placemarks[i].Polygon) {
           map.fitBounds(myGeoXml.docs[k].placemarks[i].polygon.bounds);
        }
    }
    function get_hex_colour (abgr){
     //abgr should be a KML colour with Alpha first then Blue, Green and Red
     return '#' + abgr.substr(6,2) + abgr.substr(4,2) + abgr.substr(2,2);
   }

   function calcRoute(start, lat, lng) {
      var end = new google.maps.LatLng(lat, lng);
      //console.log(start, lat, lng);
      // reset panel contents...
      $('#directionsPanel').html('');
      
      var request = {
        origin:start, 
        destination:end,
        travelMode: google.maps.DirectionsTravelMode.DRIVING,
        region: 'ca'
      };
      directionsService.route(request, function(response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
               directionsDisplay.setMap(map);
               directionsDisplay.setDirections(response);
            }else if(status == google.maps.DirectionsStatus.INVALID_REQUEST || status == google.maps.DirectionsStatus.NOT_FOUND || status == google.maps.DirectionsStatus.ZERO_RESULTS){
               $('#directionsPanel').html('<div class="error">We could not find directions based on the start address you have entered.</div>');
            }else{
               $('#directionsPanel').html('<div class="error">Google Maps encountered an error.</div>');
            }

         }
      );
      $('#directionsLayer').css('display','inline-block');

   }

   function closeDirections(){
      $('#directionsLayer').css('display','none');
      $('#directionsPanel').html('');
      directionsDisplay.setMap(null);
   }

