//*****************************************************************************
//
// USGS Google Maps Interface Script
// Created By:  Chris Rusanowski
//
// This script is based upon scripts developed by several others.  The sources
// used are noted below:  (Also, some specific notes are in the comments)
//   John Deck http://johndeck.blogspot.com/ (Example: http://chignik.berkeley.edu/google/wmstest236.html)
//	 Mike Williams http://www.econym.demon.co.uk/googlemaps2/ V2 Reference & custommap code
//     Especially: http://www.econym.demon.co.uk/googlemaps/customtile.htm
//	 Brian Flood http://www.spatialdatalogic.com/cs/blogs/brian_flood/archive/2005/07/11/39.aspx V1 WMS code
//	 Kyle Mulka http://blog.kylemulka.com/?p=287  V1 WMS code modifications
//	 http://search.cpan.org/src/RRWO/GPS-Lowrance-0.31/lib/Geo/Coordinates/MercatorMeters.pm
//
// Future enhancement ideas:
//   - Add the google Scale tool option
//   - Make the map function more dynamic
//   - Multiple WMS layers at the same time
//   - More customizations
//
// Basic Usage/Installation:
//    This file should be included in the HEAD section of the web page where the google map will be included
//    The code snipped below shows how this may be done:
//    <script src="USGS_GMAP.js" type="text/javascript"></script>
//
//    It is strongly recommended that you also include the Style sheet used for this...  EG:
//    <link REL="stylesheet" HREF="USGS_GMAP.css" TYPE="text/css">
//
//    Next include the DIV containers that hold the USGS_GMAP and the control  You can omit the
//    USGS_GMAP_Control DIV if you do not need the ability to change layers, or map functions
//    If you change the name of the google map container from USGS_GMAP to something else
//    then you need to set the USGS_GMAP_GMap_Container_ID to the ID that you use.
//    <div id="USGS_GMAP_Control" style="width: 800px; height: 25px">
//        <script type="text/javascript">
//        //<![CDATA[
//
//          //This function call will write out the USGS_GMAP map controls
//          Write_Map_Controls(true,true);
//
//        //]]>
//        </script>
//      </form>
//    </div>
//    <div id="USGS_GMAP" style="width: 800px; height: 600px"></div>
//
//    Optionally, add some code to gracefully handle situations where the user
//    does not have JavaScript:
//    <!-- fail nicely if the browser has no Javascript -->
//    <noscript><b>JavaScript must be enabled in order for you to use Google Maps.</b> However, it seems JavaScript is either disabled or not supported by your browser. To view Google Maps, enable JavaScript by changing your browser options, and then try again.</noscript>
//
//    Finally, you need to actually start the map.  This is done by calling the
//    Create_and_Change_Map_Layer function or by adding an onload event that calls
//    the USGS_GMAP_Load function.  The Create_and_Change_Map_Layer function must be
//    called after the page has loaded all the layout, or else IE will generate an error
//    so I prefer the USGS_GMAP_Load function.  So, there are three ways to call this:
//      First, Calling the Create_and_Change_Map_Layer function:
//        <script type="text/javascript">
//          //<![CDATA[
//          //This function call initializes the map with the default values.
//          //To use a different (NLCD is default) layer then use the function below
//          //that is used when changing layers.
//          Create_and_Change_Map_Layer();
//          //]]>
//        </script>
//
//      Second, Adding an OnLoad event to the BODY tag:
//        <body onload="USGS_GMAP_Load();" onunload="GUnload();" >
//
//	Third, Adding an Onload event listener (Based upon http://www.onlinetools.org/articles/unobtrusivejavascript/chapter4.html)
//        function addEvent(obj, evType, fn){
//         if (obj.addEventListener){
//           obj.addEventListener(evType, fn, false);
//           return true;
//         } else if (obj.attachEvent){
//           var r = obj.attachEvent("on"+evType, fn);
//           return r;
//         } else {
//           return false;
//         }
//        }
//        addEvent(window, 'load', USGS_GMAP_Load);
//        addEvent(window, 'load', GUnload);
//
//    NOTE: The GUnload function is added to prevent some memory leaks on IE...  It is a google maps function - not a USGS_GMAP
//
//    Lastly, make any changes to the map desired by editing the variables used by USGS_MAP.
//    Do this anytime after the USGS_GMAP script and before the onload/init function gets
//    called.  Some examples are included below:
//
//    Changing the Map controls a little bit:  (Add this function to change map controls
//      <script type="text/javascript">
//      //<![CDATA[
//        //Change to the small map control
//        USGS_GMAP_Use_Small_Controls = true;
//        //]]>
//      </script>
//
//    Changing the map layer displayed from the default NLCD to the LANDFIRE Zones layer:
//      //A layer specifying the LANDFIRE layer with 50% transparency
//      USGS_GMAP_Default_Layer_Name[0] = 'LANDFIRE Zones Transparent';
//      USGS_GMAP_Default_Layers[0] = 'LANDFIRE.ZONES_PLANNED2,LANDFIRE.ZONES_NATIONAL2,LANDFIRE.RA_FRCC_PLYGN';
//      USGS_GMAP_Default_BGColor[0] = '0xFF0000';
//      USGS_GMAP_Default_URL[0] = 'http://imsdemo.cr.usgs.gov/wmsconnector/com.esri.wms.Esrimap/USGS_EDC_LandFire?';
//      USGS_GMAP_Default_Opacity[0] = '0.75';
//
//    Changing the Map Function
//      This is currently done by modifying the USGS_GMAP_Click function and adding
//	a new else if with the desired option.  Then set the USGS_GMAP_Click_Function
//	variable to the string you added in the new if.  Replace the USGS_GMAP_Click or
//	edit a copy of this file...
//
//	Alternatively you can overwrite the USGS_GMAP_Click object (which is a function)
//	with your own function to make the map click anything...
//        USGS_GMAP_Click = function(marker, point) {
//          Call_Map_Service1(point.x, point.y);
//        }
//*****************************************************************************

//*****************************************************************************
// START - Global Variables
//*****************************************************************************
  //Create a global object that will be the reference to the map object
  var USGS_GMAP_Google_Map_Object ='';
  //Specify the Google maps API version here, so it is easier to change later
  var USGS_GMAP_API_VERSION = 2.81;
  //Create some global variables used to control how the map looks/acts
  var USGS_GMAP_Include_Reference = false;
  var USGS_GMAP_GMap_Container_ID = 'USGS_GMAP';
  var USGS_GMAP_Display_Only_Custom_Layer = true;
  var USGS_GMAP_Display_Map_Controls = true;
  var USGS_GMAP_Display_Layer_Controls = false;
  var USGS_GMAP_Use_Small_Controls = false;
  var USGS_GMAP_Custom_Min_Scale = 0;
  var USGS_GMAP_Custom_Max_Scale = 17;
  var USGS_GMAP_Center_X = -96.0;
  var USGS_GMAP_Center_Y = 39.0;
  var USGS_GMAP_Zoom_Level = 3;

  //The following variable is used to determine the map interaction
  //  ALERT = Popup an alert with the X, Y coordinates
  //  SDDS = Open a window on SDDS with the USGS_GMAP_SDDS_Layers and the current extent
  //  TILED = Open a window on Tiled SDDS witht he USGS_GMAP_SDDS_Layers and the current Extent
  //  URL = Open a window with the URL specified in USGS_GMAP_Click_URL, passing X, Y, of the click and current Extent
  //        It does this by replacing [X}, [Y], and [EXTENT] with the values in the URL
  var USGS_GMAP_Click_Function = 'URL';
  var USGS_GMAP_SDDS_Layers = 'L9201TZ';
  var USGS_GMAP_Click_URL = 'http://gisdata.usgs.gov/XMLWebServices/USNG.asmx/Get_USNG?X_Value=[X]&Y_Value=[Y]';
//*****************************************************************************
// END - Global Variables
//*****************************************************************************

//*****************************************************************************
// START - Default WMS and Custom Tiling Parameters
//   These are used for the pre-defining the layers
//*****************************************************************************
  var USGS_GMAP_Default_Layer_Name = new Array();
  var USGS_GMAP_Default_Mecator_Zoom_Level = new Array();
  var USGS_GMAP_Default_Format = new Array();
  var USGS_GMAP_Default_Layers = new Array();
  var USGS_GMAP_Default_Version = new Array();
  var USGS_GMAP_Default_Styles = new Array();
  var USGS_GMAP_Default_BGColor = new Array();
  var USGS_GMAP_Default_Transparent = new Array();
  var USGS_GMAP_Default_URL = new Array();
  var USGS_GMAP_Default_Opacity = new Array();
//*****************************************************************************
// END - Default WMS and Custom Tiling Parameters
//*****************************************************************************

//*****************************************************************************
// START - Pre-defined layers
//*****************************************************************************
  //A layer specifying the US NLCD 1992 layer with 50% transparency
  USGS_GMAP_Default_Layer_Name[0] = 'US_NLCD Transparent';
  USGS_GMAP_Default_Mecator_Zoom_Level[0] = 5;
  USGS_GMAP_Default_Format[0] = 'image/gif';
  USGS_GMAP_Default_Layers[0] = 'US_NLCD,CONUS_NLCD16,CONUS_NLCD32,CONUS_NLCD64,CONUS_NLCD128,CONUS_NLCD256';
  USGS_GMAP_Default_Version[0] = '1.1.1';
  USGS_GMAP_Default_Styles[0] = '';
  USGS_GMAP_Default_BGColor[0] = '0x000000';
  USGS_GMAP_Default_Transparent[0] = 'TRUE';
  USGS_GMAP_Default_URL[0] = 'http://imsdemo.cr.usgs.gov/wmsconnector/com.esri.wms.Esrimap/USGS_EDC_LandCover_NLCD?';
  USGS_GMAP_Default_Opacity[0] = '0.5';

  //Same as default (0) layer but no transparency
  USGS_GMAP_Default_Layer_Name[1] = 'US_NLCD Solid';
  USGS_GMAP_Default_Mecator_Zoom_Level[1] = 5;
  USGS_GMAP_Default_Format[1] = 'image/gif';
  USGS_GMAP_Default_Layers[1] = 'US_NLCD,CONUS_NLCD16,CONUS_NLCD32,CONUS_NLCD64,CONUS_NLCD128,CONUS_NLCD256';
  USGS_GMAP_Default_Version[1] = '1.1.1';
  USGS_GMAP_Default_Styles[1] = '';
  USGS_GMAP_Default_BGColor[1] = '0x000000';
  USGS_GMAP_Default_Transparent[1] = 'TRUE';
  USGS_GMAP_Default_URL[1] = 'http://imsdemo.cr.usgs.gov/wmsconnector/com.esri.wms.Esrimap/USGS_EDC_LandCover_NLCD?';
  USGS_GMAP_Default_Opacity[1] = '1.0';
//*****************************************************************************
// END - Pre-defined layers
//*****************************************************************************

//*****************************************************************************
// START - Convert to Mercator functionality
// This section comes directly from
//   John Deck http://johndeck.blogspot.com/ (Example: http://chignik.berkeley.edu/google/wmstest236.html)
//*****************************************************************************
  //Variables used by the convert to Mercator functions
  var MAGIC_NUMBER=6356752.3142;
  var DEG2RAD=0.0174532922519943;
  var PI=3.14159267;

  function dd2MercMetersLng(p_lng) {
    return MAGIC_NUMBER*(p_lng*DEG2RAD);
  }

  function dd2MercMetersLat(p_lat) {
    if (p_lat >= 85) p_lat=85;
    if (p_lat <= -85) p_lat=-85;
    return MAGIC_NUMBER*Math.log(Math.tan(((p_lat*DEG2RAD)+(PI/2)) /2));
  }
//*****************************************************************************
// END - Convert to Mercator functionality
//*****************************************************************************

//*****************************************************************************
// START - Custom Tile functionality
// This section is a modified version of the CustomGetTileURL function from
//   John Deck http://johndeck.blogspot.com/ (Example: http://chignik.berkeley.edu/google/wmstest236.html)
//*****************************************************************************
  USGS_Get_WMS_Tile = function (a,b,c) {
    //Make sure the Object has been initialized
    if (typeof(window['this.USGS_GMAP_Layer_Name'])=="undefined") { Initialize_Custom_Layer_Properties(this); }

    //Calculate the BBOX and determine the SRS
    // This section comes directly from
    //   John Deck http://johndeck.blogspot.com/ (Example: http://chignik.berkeley.edu/google/wmstest236.html)
    var lULP = new GPoint(a.x*256,(a.y+1)*256);
    var lLRP = new GPoint((a.x+1)*256,a.y*256);
    var lUL = G_NORMAL_MAP.getProjection().fromPixelToLatLng(lULP,b,c);
    var lLR = G_NORMAL_MAP.getProjection().fromPixelToLatLng(lLRP,b,c);
    // switch between Mercator and DD if merczoomlevel is set
    if (this.USGS_GMAP_Mecator_Zoom_Level!=0 && USGS_GMAP_Google_Map_Object.getZoom() < this.USGS_GMAP_Mecator_Zoom_Level) {
        var lBbox=dd2MercMetersLng(lUL.x)+","+dd2MercMetersLat(lUL.y)+","+dd2MercMetersLng(lLR.x)+","+dd2MercMetersLat(lLR.y);
        var lSRS="EPSG:54004";
    } else {
        var lBbox=lUL.x+","+lUL.y+","+lLR.x+","+lLR.y;
        var lSRS="EPSG:4326";
    }

    //Now Build the Custom Tile URL
    var Custom_Tile_URL=this.USGS_GMAP_URL;
    Custom_Tile_URL+="&REQUEST=GetMap";
    Custom_Tile_URL+="&SERVICE=WMS";
    Custom_Tile_URL+="&VERSION="+this.USGS_GMAP_Version;
    Custom_Tile_URL+="&LAYERS="+this.USGS_GMAP_Layers;
    Custom_Tile_URL+="&STYLES="+this.USGS_GMAP_Styles;
    Custom_Tile_URL+="&FORMAT="+this.USGS_GMAP_Format;
    Custom_Tile_URL+="&BGCOLOR="+this.USGS_GMAP_BGColor;
    Custom_Tile_URL+="&TRANSPARENT="+this.USGS_GMAP_Transparent;
    Custom_Tile_URL+="&SRS="+lSRS;
    Custom_Tile_URL+="&BBOX="+lBbox;
    Custom_Tile_URL+="&WIDTH=256";
    Custom_Tile_URL+="&HEIGHT=256";
    Custom_Tile_URL+="&reaspect=false";

    //Finally Return the URL
    return Custom_Tile_URL;
  }
//*****************************************************************************
// END - Custom Tile functionality
//*****************************************************************************

//*****************************************************************************
// START - Custom Copyright functionality
//*****************************************************************************
  USGS_Get_WMS_Copyright = function (a,b) {
    //Make sure the Object has been initialized
    if (typeof(window['this.USGS_GMAP_Layer_Name'])=="undefined") { Initialize_Custom_Layer_Properties(this); }

    //Return the Layer name prefixed by USGS_GMAP:
    return {prefix:"USGS_GMAP: ",copyrightTexts:[this.USGS_GMAP_Layer_Name]};
  }
//*****************************************************************************
// END - Custom Copyright functionality
//*****************************************************************************

//*****************************************************************************
// START - Custom Opacity functionality
//*****************************************************************************
  USGS_Get_WMS_Opacity = function (a,b) {
    //Make sure the Object has been initialized
    if (typeof(window['this.USGS_GMAP_Layer_Name'])=="undefined") { Initialize_Custom_Layer_Properties(this); }

    //Return the Opacity from tile object
    return this.USGS_GMAP_Opacity;
  }
//*****************************************************************************
// END - Custom Opacity functionality
//*****************************************************************************

//*****************************************************************************
// START - Initialize Custom Layer Properties Object
// Description:
//    The custom functions that get assigned to the Custom Layers Object
//    all make references to some special properties that define the Custom
//    WMS layer.  This function makes sure that the Object has all those
//    properties and sets them to the default values if they do not exist.
//*****************************************************************************
  function Initialize_Custom_Layer_Properties(Custom_Layer_Object) {
    if (typeof(Custom_Layer_Object.USGS_GMAP_Layer_Name)=="undefined") { Custom_Layer_Object.USGS_GMAP_Layer_Name=USGS_GMAP_Default_Layer_Name[0]; }
    if (typeof(Custom_Layer_Object.USGS_GMAP_Opacity)=="undefined") { Custom_Layer_Object.USGS_GMAP_Opacity=USGS_GMAP_Default_Opacity[0]; }
    if (typeof(Custom_Layer_Object.USGS_GMAP_Mecator_Zoom_Level)=="undefined") { Custom_Layer_Object.USGS_GMAP_Mecator_Zoom_Level=USGS_GMAP_Default_Mecator_Zoom_Level[0]; }
    if (typeof(Custom_Layer_Object.USGS_GMAP_Format)=="undefined") { Custom_Layer_Object.USGS_GMAP_Format=USGS_GMAP_Default_Format[0]; }
    if (typeof(Custom_Layer_Object.USGS_GMAP_Layers)=="undefined") { Custom_Layer_Object.USGS_GMAP_Layers=USGS_GMAP_Default_Layers[0]; }
    if (typeof(Custom_Layer_Object.USGS_GMAP_Version)=="undefined") { Custom_Layer_Object.USGS_GMAP_Version=USGS_GMAP_Default_Version[0]; }
    if (typeof(Custom_Layer_Object.USGS_GMAP_Styles)=="undefined") { Custom_Layer_Object.USGS_GMAP_Styles=USGS_GMAP_Default_Styles[0]; }
    if (typeof(Custom_Layer_Object.USGS_GMAP_BGColor)=="undefined") { Custom_Layer_Object.USGS_GMAP_BGColor=USGS_GMAP_Default_BGColor[0]; }
    if (typeof(Custom_Layer_Object.USGS_GMAP_Transparent)=="undefined") { Custom_Layer_Object.USGS_GMAP_Transparent=USGS_GMAP_Default_Transparent[0]; }
    if (typeof(Custom_Layer_Object.USGS_GMAP_URL)=="undefined") { Custom_Layer_Object.USGS_GMAP_URL=USGS_GMAP_Default_URL[0]; }
  }
//*****************************************************************************
// END - Initialize Custom Layer Properties Object
//*****************************************************************************

//*****************************************************************************
// START - Create Custom MapType Object
// Description:
//    Create a Custom MapType object from the Custom Tile Object by creating
//    a Map Layer and then assigning it to a new MapType Object and returning
//    that.  Include_Reference is a true/false (or 0/1) boolean that tells
//    this function to create a new layer with, or without reference data
//*****************************************************************************
  function Create_Custom_MapType(Custom_Tile_Object,Include_Reference) {
    //Make sure the Object has been initialized
    if (typeof(Custom_Tile_Object.USGS_GMAP_Layer_Name)=="undefined") { Initialize_Custom_Layer_Properties(Custom_Tile_Object); }

    //Check if the new layer should include the Google Reference Data (Mostly Roads)
    if ((typeof(Include_Reference)=="undefined") || (Include_Reference.toUpperCase=="TRUE" || Include_Reference=="1")) {
      var Custom_Map_Layer = [G_SATELLITE_MAP.getTileLayers()[0],Custom_Tile_Object,G_HYBRID_MAP.getTileLayers()[1]];
    } else {
      var Custom_Map_Layer = [G_SATELLITE_MAP.getTileLayers()[0],Custom_Tile_Object];
    }

    //Now build the Custom MapType
    var Custom_Map = new GMapType(Custom_Map_Layer, G_SATELLITE_MAP.getProjection(), Custom_Tile_Object.USGS_GMAP_Layer_Name, {errorMessage: "Unable to retrieve WMS Tile"});

    //Return the final MapType
    return Custom_Map;
  }
//*****************************************************************************
// END - Create Custom MapType Object
//*****************************************************************************

//*****************************************************************************
// START - Create Custom Tile Object
// Description:
//    Create a Custom MapType object from the Custom Tile Object by creating
//    a Map Layer and then assigning it to a new MapType Object and returning
//    that.  Include_Reference is a true/false (or 0/1) boolean that tells
//    this function to create a new layer with, or without reference data
//
//    NOTE:  Currently the scale parameters do not seem to have an effect...
//*****************************************************************************
  function Create_Custom_Tile(Custom_Min_Scale, Custom_Max_Scale) {
    //Check for Scale parameters and set to maximum values if not present
    if (typeof(Custom_Min_Scale)=="undefined") { Custom_Min_Scale=USGS_GMAP_Custom_Min_Scale; }
    if (typeof(Custom_Max_Scale)=="undefined") { Custom_Max_Scale=USGS_GMAP_Custom_Max_Scale; }

    //Now create the Custom Tile Object
    var Custom_Tile_Object=new GTileLayer(new GCopyrightCollection("USGS_GMAP"), Custom_Min_Scale, Custom_Max_Scale);

    //Assign the custom functions used for getting the WMS tiles
    Custom_Tile_Object.getTileUrl=USGS_Get_WMS_Tile;
    Custom_Tile_Object.getCopyright=USGS_Get_WMS_Copyright;
    Custom_Tile_Object.getOpacity=USGS_Get_WMS_Opacity;

    //return the Custom Tile Object
    return Custom_Tile_Object;
  }
//*****************************************************************************
// END - Create Custom Tile Object
//*****************************************************************************

//*****************************************************************************
// START - Create and Change Map Layer Function
// Description:
//    This is the code that normally gets included in the html to setup
//    a google map with WMS using this script.  It has been merged into
//    a function to make it easier to call and change layers on the fly
//    from a drop down list or other page object.
//*****************************************************************************
  function Create_and_Change_Map_Layer(Custom_Min_Scale, Custom_Max_Scale, USGS_GMAP_Layer_Name, USGS_GMAP_Mecator_Zoom_Level, USGS_GMAP_Format, USGS_GMAP_Layers, USGS_GMAP_Version, USGS_GMAP_Styles, USGS_GMAP_BGColor, USGS_GMAP_Transparent, USGS_GMAP_URL, USGS_GMAP_Opacity, Include_Reference, GMap_Container_ID, Display_Only_Custom_Layer, Display_Map_Controls, Display_Layer_Controls, Center_X, Center_Y, Zoom_Level) {
    //Set the input values to default parameters if they were not passed in
    if (typeof(USGS_GMAP_Layer_Name)=="undefined") {
      Custom_Min_Scale = USGS_GMAP_Custom_Min_Scale;
      Custom_Max_Scale = USGS_GMAP_Custom_Max_Scale;
      Include_Reference = USGS_GMAP_Include_Reference;
      GMap_Container_ID = USGS_GMAP_GMap_Container_ID;
      Display_Only_Custom_Layer = USGS_GMAP_Display_Only_Custom_Layer;
      Display_Map_Controls = USGS_GMAP_Display_Map_Controls;
      Display_Layer_Controls = USGS_GMAP_Display_Layer_Controls;
      Center_X = USGS_GMAP_Center_X;
      Center_Y = USGS_GMAP_Center_Y;
      Zoom_Level = USGS_GMAP_Zoom_Level;
    }

    //Check the browser compatibility with the Google Maps Library
    if (GBrowserIsCompatible()) {
      //It is compatible, so now make the New Custom Tile Object
      var New_Custom_Tile_Object=Create_Custom_Tile(Custom_Min_Scale,Custom_Max_Scale);

      //Now set the parameters that define the WMS Layer (Otherwise it will default to NLCD on imsdemo)
      if (typeof(USGS_GMAP_Layer_Name)!="undefined") { New_Custom_Tile_Object.USGS_GMAP_Layer_Name = USGS_GMAP_Layer_Name; }
      if (typeof(USGS_GMAP_Mecator_Zoom_Level)!="undefined") { New_Custom_Tile_Object.USGS_GMAP_Mecator_Zoom_Level = USGS_GMAP_Mecator_Zoom_Level; }
      if (typeof(USGS_GMAP_Format)!="undefined") { New_Custom_Tile_Object.USGS_GMAP_Format = USGS_GMAP_Format; }
      if (typeof(USGS_GMAP_Layers)!="undefined") { New_Custom_Tile_Object.USGS_GMAP_Layers = USGS_GMAP_Layers; }
      if (typeof(USGS_GMAP_Version)!="undefined") { New_Custom_Tile_Object.USGS_GMAP_Version = USGS_GMAP_Version; }
      if (typeof(USGS_GMAP_Styles)!="undefined") { New_Custom_Tile_Object.USGS_GMAP_Styles = USGS_GMAP_Styles; }
      if (typeof(USGS_GMAP_BGColor)!="undefined") { New_Custom_Tile_Object.USGS_GMAP_BGColor = USGS_GMAP_BGColor; }
      if (typeof(USGS_GMAP_Transparent)!="undefined") { New_Custom_Tile_Object.USGS_GMAP_Transparent = USGS_GMAP_Transparent; }
      if (typeof(USGS_GMAP_URL)!="undefined") { New_Custom_Tile_Object.USGS_GMAP_URL = USGS_GMAP_URL; }
      if (typeof(USGS_GMAP_Opacity)!="undefined") { New_Custom_Tile_Object.USGS_GMAP_Opacity = USGS_GMAP_Opacity; }

      //Create a custom map from the custom tile object
      var New_Custom_Map = Create_Custom_MapType(New_Custom_Tile_Object, Include_Reference);

      //Now create the Google Map Object
      USGS_GMAP_Google_Map_Object = new GMap(document.getElementById(GMap_Container_ID));

      //Set the Map Types array length to 0, so that only layers added below will display
      if (Display_Only_Custom_Layer.toUpperCase=="TRUE" || Display_Only_Custom_Layer=="1") { USGS_GMAP_Google_Map_Object.getMapTypes().length=0; }

      //Add the New_Custom_Map to the Map Object
      USGS_GMAP_Google_Map_Object.addMapType(New_Custom_Map);

      //Add a map control for zoom/pan
      if (Display_Map_Controls.toUpperCase=="TRUE" || Display_Map_Controls=="1") {
        if (USGS_GMAP_Use_Small_Controls) {
          USGS_GMAP_Google_Map_Object.addControl(new GSmallMapControl());
        } else {
          USGS_GMAP_Google_Map_Object.addControl(new GLargeMapControl());
        }
      }

      //Show the buttons that select the different map layers
      if (Display_Layer_Controls.toUpperCase=="TRUE" || Display_Layer_Controls=="1") { USGS_GMAP_Google_Map_Object.addControl(new GMapTypeControl()); }

      //Set the starting Position and Zoom level
      USGS_GMAP_Google_Map_Object.setCenter(new GLatLng(Center_Y, Center_X), Zoom_Level);

      //Setup the Click Functionality
      GEvent.addListener(USGS_GMAP_Google_Map_Object, "click", USGS_GMAP_Click);

    } else {
      //Display a warning that the map is unable to load
      alert("Sorry, the Google Maps API which is used by USGS_GMAP is not compatible with this browser");
    }
  }
//*****************************************************************************
// END - Create and Change Map Layer Function
//*****************************************************************************

//*****************************************************************************
// START - Custom Click functionality
//*****************************************************************************
  USGS_GMAP_Click = function(marker, point) {
    //  ALERT = Popup an alert with the X, Y coordinates
    //  SDDS = Open a window on SDDS with the USGS_GMAP_SDDS_Layers and the current extent
    //  TILED = Open a window on Tiled SDDS witht he USGS_GMAP_SDDS_Layers and the current Extent
    //  URL = Open a window with the URL specified in USGS_GMAP_Click_URL, passing X, Y, of the click and current Extent
    var temp_Bounds = USGS_GMAP_Google_Map_Object.getBounds();
    var temp_minx = temp_Bounds.getSouthWest().x;
    var temp_miny = temp_Bounds.getSouthWest().y;
    var temp_maxx = temp_Bounds.getNorthEast().x;
    var temp_maxy = temp_Bounds.getNorthEast().y;
    if (USGS_GMAP_Click_Function=='ALERT') {
      alert("You Clicked " + point.x + "," + point.y);
    } else if (USGS_GMAP_Click_Function=='TILED') {
      window.open("http://extract.cr.usgs.gov/tddsRequest/tddsFrameset.jsp?VI=afghan&AL=" + temp_maxy + "," + temp_miny + "," + temp_maxx + "," + temp_minx + "&VI=" + USGS_GMAP_SDDS_Layers,"","height=480,width=600,status=0,toolbar=0");
    } else if (USGS_GMAP_Click_Function=='SDDS') {
      window.open("http://extract.cr.usgs.gov/Website/distreq/RequestSummary.jsp?AL=" + temp_maxy + "," + temp_miny + "," + temp_maxx + "," + temp_minx + "&PL=" + USGS_GMAP_SDDS_Layers,"","height=480,width=600,status=0,toolbar=0");
    } else if (USGS_GMAP_Click_Function=='URL') {
      window.open(USGS_GMAP_Click_URL.replace("[X]",point.x).replace("[Y]",point.y).replace("[EXTENT]",temp_maxy + "," + temp_miny + "," + temp_maxx + "," + temp_minx),"","height=200,width=400,status=0,toolbar=0");
    }
  }
//*****************************************************************************
// END - Custom Click functionality
//*****************************************************************************

//*****************************************************************************
// START - USGS_GMAP_Change_Layer Function
// Description:
//    This will recreate the map with a different WMS layer from the pre-defined
//    layer list arrays
//*****************************************************************************
  function USGS_GMAP_Change_Layer(Layer_Selection) {
    //If unspecified then Layer_Selection should be 0
    if (typeof(Layer_Selection)=="undefined") { Layer_Selection=0; }

    //Generally everything below here will not change
    var USGS_GMAP_Mecator_Zoom_Level = 5;
    var Custom_Min_Scale = 0;
    var Custom_Max_Scale = 17;
    var Include_Reference = USGS_GMAP_Include_Reference;
    var GMap_Container_ID = USGS_GMAP_GMap_Container_ID;
    var Display_Only_Custom_Layer = USGS_GMAP_Display_Only_Custom_Layer;
    var Display_Map_Controls = USGS_GMAP_Display_Map_Controls;
    var Display_Layer_Controls = USGS_GMAP_Display_Layer_Controls;
    var Current_Center = USGS_GMAP_Google_Map_Object.getCenter()
    var Center_X = Current_Center.x;
    var Center_Y = Current_Center.y;
    var Zoom_Level = USGS_GMAP_Google_Map_Object.getZoom();

    //Now set the layer variables from the array
    Create_and_Change_Map_Layer(Custom_Min_Scale, Custom_Max_Scale, USGS_GMAP_Default_Layer_Name[Layer_Selection], USGS_GMAP_Default_Mecator_Zoom_Level[Layer_Selection], USGS_GMAP_Default_Format[Layer_Selection], USGS_GMAP_Default_Layers[Layer_Selection], USGS_GMAP_Default_Version[Layer_Selection], USGS_GMAP_Default_Styles[Layer_Selection], USGS_GMAP_Default_BGColor[Layer_Selection], USGS_GMAP_Default_Transparent[Layer_Selection], USGS_GMAP_Default_URL[Layer_Selection], USGS_GMAP_Default_Opacity[Layer_Selection], Include_Reference, GMap_Container_ID, Display_Only_Custom_Layer, Display_Map_Controls, Display_Layer_Controls, Center_X, Center_Y, Zoom_Level)
  }
//*****************************************************************************
// END - USGS_GMAP_Change_Layer Function
//*****************************************************************************

//*****************************************************************************
// START - USGS_GMAP_Change_Click Function
// Description:
//    Sets the Map Click Function to a string passed into it
//*****************************************************************************
  function USGS_GMAP_Change_Click(Click_Selection) {
    USGS_GMAP_Click_Function = Click_Selection;
  }
//*****************************************************************************
// END - USGS_GMAP_Change_Layer Function
//*****************************************************************************

//*****************************************************************************
// START - Write_Map_Controls Function
// Description:
//    Writes out the HTML Form for controlling the map
//*****************************************************************************
  function Write_Map_Controls(ShowLabels,ShowMapFunction) {
    document.write('<form action="">');
    if (ShowLabels) {
      document.write('<label for="USGS_GMAP_Layer_Select">Map Theme:</label>');
    }
    document.write('<select id="USGS_GMAP_Layer_Select" onchange="USGS_GMAP_Change_Layer(this.value);">');
    for (var i=0; i<USGS_GMAP_Default_Layer_Name.length; i++) {
      document.write('<option value="' + i + '">' + USGS_GMAP_Default_Layer_Name[i] + '</option>');
    }
    document.write('</select>');
    if (ShowMapFunction) {
      if (ShowLabels) {
        document.write('<label for="USGS_GMAP_Click_Select">Map Function:</label>');
      }
      document.write('<select id="USGS_GMAP_Click_Select" onchange="USGS_GMAP_Change_Click(this.value);">');
      document.write('<option value="URL">USNG Lookup</option>');
      document.write('<option value="SDDS">SDDS Download</option>');
      document.write('<option value="TILED">Tiled Download</option>');
      document.write('</select>');
    }
    document.write('</form>');
  }
//*****************************************************************************
// END - Write_Map_Controls Function
//*****************************************************************************

//*****************************************************************************
// START - USGS_GMAP_Load Function
// Description:
//    A call to this function is placed in the BODY HTML tag because IE has
//    an issue with modifying the content of some HTML elements before a
//    page is completely loaded.  If you call the Create_and_Change_Map_Layer
//    function before the page is loaded, you will get an Operation Aborted
//    error message.  If, for some reason, you cannot modify the BODY tag to
//    add a call to this function, then make sure to call this function or
//    the Create_and_Change_Map_Layer function at the end of the page.  It can
//    even be after all the tags, (</html> even)  Bad form, but browsers
//    correctly handle it.
//*****************************************************************************
function USGS_GMAP_Load() {
      //This function call initializes the map with the default values.
      //To use a different (NLCD is default) layer then use the function below
      //that is used when changing layers.
      Create_and_Change_Map_Layer();
}
//*****************************************************************************
// END - USGS_GMAP_Load Function
//*****************************************************************************


//*****************************************************************************
// START - USGS_Google Maps Key setup
//    This code could be copied to the head section of the HTML document.
//    It is included here and should not exist in both places...
//*****************************************************************************
//This is code that originally came from http://www.kokogiak.com/gmaps-transparencies.html
//This allows us to use a different Google Key for each of our domains (because the key is tied to the domain...)
//Alphabetized by domain name except for imsdemo which is the first, and the last entries

if (document.domain=="imsdemo.cr.usgs.gov") {
  document.write('<scr' + 'ipt src="http://maps.google.com/maps?file=api&v=' + USGS_GMAP_API_VERSION + '&key=ABQIAAAA5Kjj2tQ6wC-ZtsJm-iE-exQFpH8TzvGHnAz-cMiw-0p1tBgqxhT7AwlEqtK8g-cZSHCe-CCgcwLNeQ" type="text/javascript"></scr' + 'ipt>')
} else if (document.domain=="afghanistan.cr.usgs.gov") {
  document.write('<scr' + 'ipt src="http://maps.google.com/maps?file=api&v=' + USGS_GMAP_API_VERSION + '&key=ABQIAAAA5Kjj2tQ6wC-ZtsJm-iE-exQEa8RqL9f8wlJnxUXVM85uOp2GzxRkdkHC8JH1M0VoEzmIt3YmioLLAA" type="text/javascript"></scr' + 'ipt>')
} else if (document.domain=="earlywarning.usgs.gov") {
  document.write('<scr' + 'ipt src="http://maps.google.com/maps?file=api&v=' + USGS_GMAP_API_VERSION + '&key=ABQIAAAA5Kjj2tQ6wC-ZtsJm-iE-exTb02RHWHQhw_M9EZkEYIuiOh5QIBS2U6tRkAz0lq3TdduKn1ncjHgxfg" type="text/javascript"></scr' + 'ipt>')
} else if (document.domain=="edna.usgs.gov") {
  document.write('<scr' + 'ipt src="http://maps.google.com/maps?file=api&v=' + USGS_GMAP_API_VERSION + '&key=ABQIAAAA5Kjj2tQ6wC-ZtsJm-iE-exTCvZgDVCZfEBtUlfE6Kl216UjTkRTH-L8IJnqimbUJtW51vm-r1krJJg" type="text/javascript"></scr' + 'ipt>')
} else if (document.domain=="extract.cr.usgs.gov") {
  document.write('<scr' + 'ipt src="http://maps.google.com/maps?file=api&v=' + USGS_GMAP_API_VERSION + '&key=ABQIAAAA5Kjj2tQ6wC-ZtsJm-iE-exT7mmmPnd9P5CLCtAH6FdlBqKf0iBQfRd19vi-v54vtFB2YtS8PiEU1Hw" type="text/javascript"></scr' + 'ipt>')
} else if (document.domain=="gisdata.usgs.gov") {
  document.write('<scr' + 'ipt src="http://maps.google.com/maps?file=api&v=' + USGS_GMAP_API_VERSION + '&key=ABQIAAAA5Kjj2tQ6wC-ZtsJm-iE-exQS7Ln6mIPHJ7hU2TuRix2YuOohdRQq8I5up_mY8eW9E0Og-8jsJLcDCg" type="text/javascript"></scr' + 'ipt>')
} else if (document.domain=="gisdata.usgs.net") {
  document.write('<scr' + 'ipt src="http://maps.google.com/maps?file=api&v=' + USGS_GMAP_API_VERSION + '&key=ABQIAAAA5Kjj2tQ6wC-ZtsJm-iE-exRs3-CtZYUdscmXM1cddDMa5fxdzBTu3kJUHcpDExkUH5d5JLix5CxqIQ" type="text/javascript"></scr' + 'ipt>')
} else if (document.domain=="hydrosheds.cr.usgs.gov") {
  document.write('<scr' + 'ipt src="http://maps.google.com/maps?file=api&v=' + USGS_GMAP_API_VERSION + '&key=ABQIAAAA5Kjj2tQ6wC-ZtsJm-iE-exQjIMQ4ZxMWB1x-iQd5baAwh3RTERQKZcC1SwV54Te9U_3UD5mDrEleqQ" type="text/javascript"></scr' + 'ipt>')
} else if (document.domain=="igskmncngs042.cr.usgs.gov") {
  document.write('<scr' + 'ipt src="http://maps.google.com/maps?file=api&v=' + USGS_GMAP_API_VERSION + '&key=ABQIAAAA5Kjj2tQ6wC-ZtsJm-iE-exQtoViElq458otXxjLn6wO9tKqDZRRv-QsVyhqc1hHqeg-0SGSuVG83hg" type="text/javascript"></scr' + 'ipt>')
} else if (document.domain=="igskmncngs043.cr.usgs.gov") {
  document.write('<scr' + 'ipt src="http://maps.google.com/maps?file=api&v=' + USGS_GMAP_API_VERSION + '&key=ABQIAAAA5Kjj2tQ6wC-ZtsJm-iE-exRxKKknkqqQNNidalD1U5CcBuZVrxQtjPxuZBimpypZYq8_aPPSPO9z0w" type="text/javascript"></scr' + 'ipt>')
} else if (document.domain=="igskmncngs045.cr.usgs.gov") {
  document.write('<scr' + 'ipt src="http://maps.google.com/maps?file=api&v=' + USGS_GMAP_API_VERSION + '&key=ABQIAAAA5Kjj2tQ6wC-ZtsJm-iE-exSW0S9Q8QC3gSDMdsitXbxGwm9g2hRdKxonE8fl0jka32hWzFrFppmacQ" type="text/javascript"></scr' + 'ipt>')
} else if (document.domain=="igskmncngs046.cr.usgs.gov") {
  document.write('<scr' + 'ipt src="http://maps.google.com/maps?file=api&v=' + USGS_GMAP_API_VERSION + '&key=ABQIAAAA5Kjj2tQ6wC-ZtsJm-iE-exSYVqMr9UtXh_n2jmJwD3TVzykDsRRNdQhL4dx5moxUBhEeFG793vMxWA" type="text/javascript"></scr' + 'ipt>')
} else if (document.domain=="igskmncnwb010.cr.usgs.gov") {
  document.write('<scr' + 'ipt src="http://maps.google.com/maps?file=api&v=' + USGS_GMAP_API_VERSION + '&key=ABQIAAAA5Kjj2tQ6wC-ZtsJm-iE-exT2X8tambOToQKGpn67MRKwffUhAxSs54Fi5dh98Ho3O1LwYLuTOYJMIQ" type="text/javascript"></scr' + 'ipt>')
} else if (document.domain=="igskmncnwb010a.cr.usgs.gov") {
  document.write('<scr' + 'ipt src="http://maps.google.com/maps?file=api&v=' + USGS_GMAP_API_VERSION + '&key=ABQIAAAA5Kjj2tQ6wC-ZtsJm-iE-exQNgJtG08UtC4-We_mFsiVwXETSsRRkQSpbMJsSna6Cl3XP1PiGVvmPIg" type="text/javascript"></scr' + 'ipt>')
} else if (document.domain=="igskmncnwb015.cr.usgs.gov") {
  document.write('<scr' + 'ipt src="http://maps.google.com/maps?file=api&v=' + USGS_GMAP_API_VERSION + '&key=ABQIAAAA5Kjj2tQ6wC-ZtsJm-iE-exSZZNO0tKk1p2RtMxervScDJKavwxT-bHLi10Z7uaiqaMzHm631fmrA3g" type="text/javascript"></scr' + 'ipt>')
} else if (document.domain=="ims.cr.usgs.gov") {
  document.write('<scr' + 'ipt src="http://maps.google.com/maps?file=api&v=' + USGS_GMAP_API_VERSION + '&key=ABQIAAAA5Kjj2tQ6wC-ZtsJm-iE-exTYfLCbGPWLWRbh57P6hoGVFx_GMhQI8n96ZyG8SaQUF6UuWEQXb-AU8A" type="text/javascript"></scr' + 'ipt>')
} else if (document.domain=="landcover.usgs.gov") {
  document.write('<scr' + 'ipt src="http://maps.google.com/maps?file=api&v=' + USGS_GMAP_API_VERSION + '&key=ABQIAAAA5Kjj2tQ6wC-ZtsJm-iE-exRPo8qucu_X-h6JRQvL956AIDkF1hQOb_De00bjWegPvy59jekjLyWUyw" type="text/javascript"></scr' + 'ipt>')
} else if (document.domain=="lidar.cr.usgs.gov") {
  document.write('<scr' + 'ipt src="http://maps.google.com/maps?file=api&v=' + USGS_GMAP_API_VERSION + '&key=ABQIAAAA5Kjj2tQ6wC-ZtsJm-iE-exTjIwkaagUTt9F3x5Kb_6THkOj65RTAxn7rfTuuFc1bFxk3-sUHLbz2_A" type="text/javascript"></scr' + 'ipt>')
} else if (document.domain=="mopex.cr.usgs.gov") {
  document.write('<scr' + 'ipt src="http://maps.google.com/maps?file=api&v=' + USGS_GMAP_API_VERSION + '&key=ABQIAAAA5Kjj2tQ6wC-ZtsJm-iE-exR63phdVexyLiFBmoYeqQzq8f6qBRRFoa9n2_beJQq0HcuRS3wQAqbUIw" type="text/javascript"></scr' + 'ipt>')
} else if (document.domain=="ned.usgs.gov") {
  document.write('<scr' + 'ipt src="http://maps.google.com/maps?file=api&v=' + USGS_GMAP_API_VERSION + '&key=ABQIAAAA5Kjj2tQ6wC-ZtsJm-iE-exQSAjlBOom2j5vRiZ8gL9SZeq1wMRTZQdsJutJMxMkHxYXCO5mZH5LssQ" type="text/javascript"></scr' + 'ipt>')
} else if (document.domain=="ortho.cr.usgs.gov") {
  document.write('<scr' + 'ipt src="http://maps.google.com/maps?file=api&v=' + USGS_GMAP_API_VERSION + '&key=ABQIAAAA5Kjj2tQ6wC-ZtsJm-iE-exSehoDcQYPRFx_KVkmm829G0Ko6iRTvRleHUbgYSBuf3Yb7LXkZkkb84Q" type="text/javascript"></scr' + 'ipt>')
} else if (document.domain=="orthoimagery.cr.usgs.gov") {
  document.write('<scr' + 'ipt src="http://maps.google.com/maps?file=api&v=' + USGS_GMAP_API_VERSION + '&key=ABQIAAAA5Kjj2tQ6wC-ZtsJm-iE-exTsHdYChGyTHgk7NroEruoyRUJV4RQ8PvRdIweZAF9iSb59tEc5METz9w" type="text/javascript"></scr' + 'ipt>')
} else if (document.domain=="seamless.usgs.gov") {
  document.write('<scr' + 'ipt src="http://maps.google.com/maps?file=api&v=' + USGS_GMAP_API_VERSION + '&key=ABQIAAAA5Kjj2tQ6wC-ZtsJm-iE-exT28XBhMKpaXmIAOl4-9bfcrRPpXRQB_GE4cTQUDtAU10IpWWYFAsM7dw" type="text/javascript"></scr' + 'ipt>')
} else if (document.domain=="service.cr.usgs.gov") {
  document.write('<scr' + 'ipt src="http://maps.google.com/maps?file=api&v=' + USGS_GMAP_API_VERSION + '&key=ABQIAAAA5Kjj2tQ6wC-ZtsJm-iE-exReGTfbk7w2hB8YgRXOFv0oOcFAdxQMVPbBox8twnfbUlUv5kW3BuG1Tg" type="text/javascript"></scr' + 'ipt>')
} else if (document.domain=="landfire.cr.usgs.gov") {
  document.write('<scr' + 'ipt src="http://maps.google.com/maps?file=api&v=' + USGS_GMAP_API_VERSION + '&key=ABQIAAAA5Kjj2tQ6wC-ZtsJm-iE-exQBs0vm0vWfOEJm4lEf264nAb-rIBRT79Qdh2PPkw5-KtTSqhSfx89B3Q" type="text/javascript"></scr' + 'ipt>')
} else if (document.domain=="landfiredev.cr.usgs.gov") {
  document.write('<scr' + 'ipt src="http://maps.google.com/maps?file=api&v=' + USGS_GMAP_API_VERSION + '&key=ABQIAAAAAMydqm2BtWtmhqRRf4NNsRQd04Bsp87SwrqOCvH3sgOsJB_yDhRwSRsGIi96_v8_TisMof2dO7_23g" type="text/javascript"></scr' + 'ipt>')
  //Adding localhost for testing
} else if (document.domain=="localhost") {
  document.write('<scr' + 'ipt src="http://maps.google.com/maps?file=api&v=' + USGS_GMAP_API_VERSION + '&key=ABQIAAAA5Kjj2tQ6wC-ZtsJm-iE-exT2yXp_ZAY8_ufC3CFXhHIE1NvwkxQOBthPyV93GBeSrmD2hgIBPOYoaA" type="text/javascript"></scr' + 'ipt>')
} else {
  //igskmncngs086.cr.usgs.gov is the default
  document.write('<scr' + 'ipt src="http://maps.google.com/maps?file=api&v=' + USGS_GMAP_API_VERSION + '&key=ABQIAAAA5Kjj2tQ6wC-ZtsJm-iE-exSQxbUonuCu4IiMXu-iEIiO-Ib2DhQVnTQEI7NDOTS6WK6s2ApaMdGjgw" type="text/javascript"></scr' + 'ipt>')
}
//*****************************************************************************
// END - USGS_Google Maps Key setup
//*****************************************************************************

