
if(GBrowserIsCompatible()) {
   // create the map
   var map = new GMap2(document.getElementById("map"));

   // load controls
   map.addControl(new GLargeMapControl());
   map.addControl(new GMapTypeControl());

   map.setCenter(new GLatLng(40.3047,-111.7529), 4);

   var overview = new GOverviewMapControl(new GSize(125,125));
   map.addControl(overview);

   // create tooltip div
   // this div is used as a tooltip for station information
   // when a user hovers over a station
   // the div will be repositioned to appear next to the station
   var globaltooltip = document.createElement("div");
   map.getPane(G_MAP_FLOAT_PANE).appendChild(globaltooltip);
   globaltooltip.style.visibility="hidden";

   //scroll wheel zoom, this is a new feature see
   //http://googlemapsapi.blogspot.com/2007/04/v278-go-ahead-scroll-your-mouse-wheels.html
   map.enableScrollWheelZoom();


   // create sidebar div
   // this div will appear when the user clicks on a station marker
   // it will provide a form for requesting a report about the station
   var formbar = $('formbar');
   var ua = navigator.userAgent.toLowerCase();
   
   // When using Safari the following line causes the lookup to be disabled.
   if ( ua.indexOf('safari/') == -1 ) {
	   map.getPane(G_MAP_FLOAT_PANE).appendChild(formbar);
   }

   // create message div
   // this div will appear when data is loading to notify the user
   var message = document.createElement("div");
   map.getPane(G_MAP_FLOAT_PANE).appendChild(message);
   message.style.visibility="hidden";
   message.innerHTML = "<div id=\"messagediv\">Stations Loading...</div>";

   // create new icons
   // this icon will appear for each active station location
   var icon = new GIcon();
   icon.image = '../img/ballon/c_orange.png';
   icon.iconSize = new GSize(12, 20);
   icon.iconAnchor = new GPoint(6, 20);
   icon.infoWindowAnchor = new GPoint(5, 1);
   // this icon will appear for each inactive station location
   var inactive_icon = new GIcon();
   inactive_icon.image = '../img/ballon/c_red.png';
   inactive_icon.iconSize = new GSize(12, 20);
   inactive_icon.iconAnchor = new GPoint(6, 20);
   inactive_icon.infoWindowAnchor = new GPoint(5, 1);
   
   // inactive icon for CRN
   var inactive_crn_icon = new GIcon();
   inactive_crn_icon.image = '../img/map/networks/crn-inactive.png';
   inactive_crn_icon.iconSize = new GSize(20, 15);
   inactive_crn_icon.iconAnchor = new GPoint(6, 20);
   inactive_crn_icon.infoWindowAnchor = new GPoint(5, 1);
   
   var icon_crn = new GIcon();
   icon_crn.image = '../img/map/networks/crn-active.png';
   icon_crn.iconSize = new GSize(20, 15);
   icon_crn.iconAnchor = new GPoint(6, 20);
   icon_crn.infoWindowAnchor = new GPoint(5, 1);

   // Create Custom Marker
   // this will allow us to store additional information
   // pertaining to a station marker
   // this is done by inheriting from the GMarker class
   // to add extra functionality
   GMarker.prototype.addStationInfo = function(id,name,por,crn_id) {
      this.stn_id = id;
      this.stn_name = name;
      this.stn_por = por;
      this.crn_id = crn_id;
   }

   // add listener for move events
   // if the map is zoomed in far enough, stations are shown
   // if the map is zoomed back out, the stations are removed to reduce clutter
   // stations are also refreshed any time the map is panned to another location
   GEvent.addListener(map, "moveend", function() {
         setMapCookie();
         if(map.getZoom() >= 10)
            loadStations();
         else
            map.clearOverlays();
         /*var bounds = map.getBounds();
           var sw = bounds.getSouthWest();
           var ne = bounds.getNorthEast();
           document.getElementById('message').innerHTML = sw + '...' + ne;*/
      });

   // this function is called each time a station marker is added
   // it formats the station's tooltip and adds event listeners
   // for click, hover, etc.
   function formatMarker(station)
   {
      var id = station.stn_id;
      var name = station.stn_name;
      var div_width = (7.9 * name.length) + 48;
      if(div_width < 110) div_width = 110;
      var por = station.stn_por;
      var crn_id = station.crn_id;
      if ( crn_id.length >= 4 ) {
      	station.tooltip = "<div id=\"tooltip\" style=\"width:" + div_width + "px\">CRN ID: "+id+' - ( '+crn_id+' ) <br/>Name: ' + name + '<br/>Period: ' + por + '</div>';
      } else {
      	station.tooltip = "<div id=\"tooltip\" style=\"width:" + div_width + "px\">ID: "+id+'<br/>Name: ' + name + '<br/>Period: ' + por + '</div>';
      }
      // add listener for marker click events
      // if a station icon is clicked, its corresponding id is displayed
      GEvent.addListener(station, "click", function() {
            showFormBar(station);
         });

      // add listener for marker hover events
      // if the user hovers over a station icon,
      // information about the station is displayed
      GEvent.addListener(station,"mouseover", function() {
            showTooltip(station);
         });
      GEvent.addListener(station,"mouseout", function() {
            globaltooltip.style.visibility="hidden";
         });
      return station;
   }

   // this function is called when the user hovers over a station marker
   // the tooltip div is repositioned near the marker
   // and becomes visible
   function showTooltip(station)
   {
      globaltooltip.innerHTML = station.tooltip;
      globaltooltip.style.width = $("tooltip").style.width;
      var point = map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
      var offset = map.getCurrentMapType().getProjection().fromLatLngToPixel(station.getPoint(),map.getZoom());
      var anchor = station.getIcon().iconAnchor;
      var width = station.getIcon().iconSize.width;
      var height = globaltooltip.clientHeight;
      var x = offset.x - point.x - anchor.x + width;
      var y = offset.y - point.y - anchor.y - height;
      var centerPoint = map.getCurrentMapType().getProjection().fromLatLngToPixel(map.getCenter(),map.getZoom());
      var mapWidth = map.getSize().width;
      var mapHeight = map.getSize().height;
      var ttWidthDOM = $("tooltip").style.width;
      var tooltipWidth = Math.floor(ttWidthDOM.substr(0,ttWidthDOM.length-2));
      if (offset.y - height - anchor.y < centerPoint.y - mapHeight/2 )
         y = y + height + anchor.y;
      if (offset.x + tooltipWidth - anchor.x + width > centerPoint.x + mapWidth/2)
         x = x - tooltipWidth - width; 
      var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(x,y));
      pos.apply(globaltooltip);
      globaltooltip.style.visibility = "visible";
   }

   var lastDate;  // keep track of the last date the user used
   function parseDates()
   {
      var month = document.choosereport.mon.selectedIndex;
      var yearIdx = document.choosereport.year.selectedIndex;
      var year = document.choosereport.year.options[yearIdx].value;
      lastDate = month + ':' + year;
      setMapCookie();
   }
   
   // this function is called when a user clicks on a station marker
   // a form is opened where the user can choose what they would like to see
   function showFormBar(station)
   {
      var formtext = "<div align='left'><b><u>ID:</u></b> " + station.stn_id;
      formtext += "<br/><b><u>Name:</u></b> " + station.stn_name;
      formtext += "<br/><b><u>Period:</u></b>" + station.stn_por +"</div>";
      $('formstninfo').innerHTML = formtext;
      document.choosereport.stn.value = station.stn_id;

      if(lastDate) {
         var dates = lastDate.split(':');
         document.choosereport.mon.selectedIndex = dates[0]; // select most recently chosen month
      }
      var years = station.stn_por.split('-');
      var i=0;
      for(var year=years[0]; year<=years[1]; year++) {
         if(lastDate && year == dates[1]) // select most recently chosen year
            document.choosereport.year[i] = new Option(year, year,true);
         else
            document.choosereport.year[i] = new Option(year, year);
         i++;
      }

      var ua = navigator.userAgent.toLowerCase();
      
      var point = map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
      var offset = map.getCurrentMapType().getProjection().fromLatLngToPixel(map.getCenter(),map.getZoom());
      var pos;
      if ( ua.indexOf('safari/') == -1 ) {
    	     pos = new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(offset.x - point.x + 55,offset.y - point.y - 210));
      } else {
    	  	 pos = new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(offset.x - point.x + 300,offset.y - point.y - 10));
      }
      
      pos.apply(formbar);

      //disable dragging and show formbar
      map.disableDragging();
      formbar.style.display = "block";
   }

   function changeDiv(on)
   {
   	switch (on)
   		{
   			case 'month':
   				on='mondiv';
     			break; 			
			case 'por':
   				on='pordiv';
   				break;			
			case 'pcpn':
   				on='pcpndiv';
   				break;			
			case 'tmean':
   				on='tmeandiv';
   				break;
			case 'et0':
   				on='et0div';
   				break;
			case 'indices':
   				on='indicesdiv';
   				break;
   	    }
      var divs = new Array('mondiv','pordiv','pcpndiv','tmeandiv','et0div','indicesdiv');
      // turn everything off
      for(var i=0;i<divs.length;i++) {
         $(divs[i]).style.display = "none";
      }
      // turn on specified div

   $(on).style.display = "block";
      //document.getElementById(on).style.display;
      //document.getElementById('mon').focus();
      //document.getElementById('year').focus();
   }

   // AJAX call for loading station icons
   // getStationXml.php queries the database for all stations
   // within the current map bounds
   // the results are sent back to the parseXml function as XML
   function loadStations()
   {
      map.clearOverlays();

      // show "Loading Stations" message
      var point = map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
      var offset = map.getCurrentMapType().getProjection().fromLatLngToPixel(map.getCenter(),map.getZoom());
      var pos = new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(offset.x - point.x - 95,offset.y - point.y - 25));
      pos.apply(message);
      message.style.visibility="visible";

      // prepare request
      var active= (document.report.inactive.checked) ? "n" : "y";

      var bounds = map.getBounds();
      var sw = bounds.getSouthWest();
      var ne = bounds.getNorthEast();
      var url = "getStationXml.php";
      var pars = 'ne=' + ne.toUrlValue() + '&sw=' + sw.toUrlValue() + '&active=' + active;

      var myAjax = new Ajax.Request(
            url,
            {
               method: 'post',
               parameters: pars,
               onComplete: parseXml
            });
   }

   // receives the XML results of the loadStations() AJAX call
   // These results are parsed and used to create icons for the stations
   // on the map
   function parseXml(request)
   {
      var responseData = request.responseXML;
      markers = responseData.getElementsByTagName("marker");

      for(var i=0; i<markers.length; i++) {
         var loc = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
               parseFloat(markers[i].getAttribute("lon")));
         var id = markers[i].getAttribute("id");
         var name = trim(markers[i].getAttribute("name"));
         var por = markers[i].getAttribute("por");
         var crn_id = markers[i].getAttribute("crn_id");
         var icontype = (markers[i].getAttribute("active") == 't') ? icon : inactive_icon;
         if ( crn_id.length >= 4 ) {
         	icontype = (markers[i].getAttribute("active") == 't') ? icon_crn : inactive_crn_icon;
         }
         var station = new GMarker(loc,icontype);
         station.addStationInfo(id,name,por,crn_id);
         map.addOverlay(formatMarker(station));
      }
      message.style.visibility="hidden";
   }

   // calls the loadStations function when the user clicks on the "inactive" checkbox
   function toggleInactive()
   {
      setMapCookie();
      if(map.getZoom() >= 10)
         loadStations();
   }
   
   // returns the index of the current map type in the MapTypes array
   function currentMapTypeNumber()
   {
      var type=0;
      for(var i=0; i < map.getMapTypes().length; i++) {
         if(map.getMapTypes()[i] == map.getCurrentMapType())
            type = i;
      }
      return type;
   }

   // called whenever a change in the map requires that the cookie be reset
   function setMapCookie()
   {
      var level = map.getZoom();
      var center = map.getCenter();
      var act = (document.report.inactive.checked) ? 'y' : 'n';
      var maptype = currentMapTypeNumber();
      var cookieString = center.lat() + ',' + center.lng() + ',';
      cookieString += level + ',' + act + ',' + maptype + ',' + lastDate;
      deleteCookie('map');
      setCookie('map', cookieString, 365);
   }
   
   function resetMap()
   {
      map.setCenter(new GLatLng(40.3047,-111.7529), 4);
      setMapCookie();
   }
   
   // load cookie if available, otherwise load default
   var cookieString = getCookie('map');
   if(cookieString) {
      var cook = cookieString.split(',');
      lastDate = cook[5];
      map.setCenter(new GLatLng(cook[0],cook[1]), Number(cook[2]));
      map.setMapType(map.getMapTypes()[cook[4]]);
      // see if inactive stations should be loaded
      if(cook[3] == 'y')
         document.report.inactive.checked = true;
      // load stations if zoomed in enough
      if(cook[2] >= 10)
         loadStations();
   }

} else {
   alert("Sorry, your browser does not support the Google Maps API.  Upgrade your browser.");
}

/**
 * setCookie()
 * --> set a javascript cookie
 * @param cookieName [string]: name of the cookie
 * @param value [string]: content of cookie
 * @param expiredays [int]: number of days before expiration
 */
function setCookie(cookieName, value, expiredays)
{
   var ExpireDate = new Date();
   ExpireDate.setTime(ExpireDate.getTime() + (expiredays*24*3600*1000));

   document.cookie = cookieName + "=" + escape(value) + ((expiredays == -1) ? "" : "; expires=" +
         ExpireDate.toGMTString()) + ";path=/";
}

/**
 * deleteCookie()
 * --> delete a cookie
 * @param name [string]: name of cookie to delete
 */
function deleteCookie(name)
{
   setCookie(name,"",-1);
}

/**
 * getCookie()
 * --> retrieve cookie information
 * @param cookieName [string]: name of cookie to retrieve
 * @return [string]: if cookie exists, its value is returned
 *			   otherwise null is returned
 */
function getCookie(cookieName)
{
   if(document.cookie.length > 0)
   {
      begin = document.cookie.indexOf(cookieName+"=");

      if(begin != -1)
      {
         begin += cookieName.length+1;
         end = document.cookie.indexOf(";", begin);
         if( end == -1 ) end = document.cookie.length;
         return unescape(document.cookie.substring(begin, end));
      }
   }
   return null;
}

/**
 * trim()
 * --> remove leading and trailing whitespace from a string
 * @param inString [string]: name of the string to trim
 * @return [string]: trimmed version of inString
 */
function trim(inString)
{
   inString = inString.replace(/^\s+/g, "" ); // strip leading
   return inString.replace(/\s+$/g, "" ); // strip trailing
}
