//*********************************************************************
//
// USGS OGC Backgrounds Code additions 
// Created By:  Chris Rusanowski
// Installation:
//   -Copy USGS_OGC.js and USGS_OGC_Layers.js into the javascript 
//    directory of the HTML Viewer
//   -Include both in MapFrame.htm 
//   -Add var USGS_OGC_Loaded=false; to mapframe.htm before the load of this file
//   -Add code to MapFrame.htm to draw layers, and refresh them
//   -Modify Pan functions in aimsnavigation.js to drag map [Optional]
//   -Modify toolbar.htm to use OGCLayerMetadata function [Optional]
//   -Modify the Identify(e) and IdentifyAll(e) in aimsIdentify.js
//    to use the IdentifyAllWindow(e) for identifying OGC layers
//   -Include calls to GetOGCTOC or SimpleTOC to draw the layer list
//    in the toc.htm (or replace toc.htm with page that does this)
//   -set the mapTransparent = true in arcimsparams.js
//   -Modify the Legend button to set the legend classification var
//   -This uses the USGS Scale Tool to control scale ranges and layer
//    display, so that must be installed also.
//   -If the USGS Group Layers is installed, comment out the USGS_Group_Loaded variable
//
//*********************************************************************
//Define all the variables used to include OGC Layers in the map
//USGS_OGC_Loaded is used to check if the extension is loaded and if
//it should be used.  Set this to false if you do not want any OGC
//background layers to show up at all.
//It comes from the mapframe.htm because it is needed there to avoid 
//any error messages, if there is a problem loading this file.
//mapTransparent must be set to true to show the backgrounds under the map.

USGS_OGC_Loaded=false;
if (USGS_OGC_Loaded) { mapTransparent=true; }

//If the USGS_Group_Loaded variable is not defined - USGS_Group_Layers.js is not loaded
//then uncomment the line below to avoid error messages...
//var USGS_Group_Loaded = false;

//Display_Only_OGC is used by the TOC to show only OGC layers, and no
//layers from the overlying map service.
Display_Only_OGC=false;

//OGC_Low_Bandwidth is used to set how the OGC images are handled.  If this is set to true
//then only the images that are visible are set.  The rest point to pixel.gif.  While this 
//causes layers to appear more slowly when turned on/off, it will not download the images  
//until they are turned visible.
var OGC_Low_Bandwidth = true;

//Maximum number of layers - This is how many DHTML Layers are created
var Number_OGC_Layers = 15;

//A variable used to check if the OGC WMS strings/map requests need to be refreshed
var CheckForExtentChange = '';

//Display Layer Classification (Or Legend...)
var Display_Layer_Classification = false;

//Include Layers that are out of scale for the current view in the layer list
//This is also used for Bad Extent - Layers that are outside the current view extent
var Include_Bad_Scale = false;

//Show_TOC_Title determines if the Layer Title is displayed when drawing the TOC
var Show_TOC_Title = true;

//The Panning_Moves_OGC_Background determines if the OGC images are dragged with the mouse
//when using the pan map tool.  This will slow down panning refreshes on slower clients, so 
//set this to false if the interface is responding too slowly.
var Panning_Moves_OGC_Background = true;

//TOC_Hash is used to set an HREF Anchor to move to in the TOC.  This way when expanding/collapsing
//categories, we can move the user to the closest position to where they were before...
var TOC_Hash ='';

//Update_Images is used to see if we have to create the Images in the appropriate layers
var Update_Images = '';

//Working_Category is the currently selected category when doing things like remove layer, etc.
var Working_Category = -1;

//This is the Category listing in order of display in TOC (Reverse drawing Order)
var Category_Order = new Array();

//This is the Layer listing in order of display in TOC (Reverse drawing Order)
//Each entry must use split to parse out the array of layers, because they 
//are stored here as a comma-delimited string.
var Category_Layer_Order = new Array();

//This matches the layer listing with a true/false for each layer to 
//show if it is visible or not.
var Category_Layer_Visibility = new Array();

//Whether a category twist-tie is expanded or collapsed (true = expanded)
var Category_Expanded = new Array();

//Images to use for Category Expanded and Collapsed...
var Category_Expanded_Image = '/website/ImageArchive/secondary/category_expanded.gif';
var Category_Collapsed_Image = '/website/ImageArchive/secondary/category_collapsed.gif';

//SRC_Layer arrays define the possible values of OGC backgrounds
//that may be specified in the Category layers above.  The category layers
//just specify a array number and then these arrays are referenced for the
//specifics for that layer.
//URL is the WMS url for the map image without the Height/Width/and BBOX (Those will be added)
//Name is the name that is shown in the TOC
//Icon_URL is the url to a small 16 pixels or less image for the legend
//Documentation_URL is the url to any home pages describing this dataset
//Metadata_URL is the url to the capabilities or Metadata description of this dataset
//Max_Scale is the maximum number of square degrees ABOVE which this layer is NOT shown
//Min_Scale is the maximum number of square degrees BELOW which this layer is NOT shown
//Category is the name of the category this layer may belong to
//IDLayers is the layer list that is passed to this layer in Identify requests
//Extent* are used to determine if the layer should be displayed in the current window extent
//Download_URL is a reference to a URL that can download the data used in the map.  This URL will 
//be evaluated (JavaScript Eval) so it can include things like the current coordinates, by including them
//as variables.  IE:  to define an areaList with current coordinates use a string like:  (Note the ' and ")
//  '"[rest of URL]areaList="+eTop+","+eBottom+","+eRight+","+eLeft+"[rest of URL]"'
var SRC_Layer_URL = new Array();
var SRC_Layer_Name = new Array();
var SRC_Layer_Icon_URL = new Array();
var SRC_Layer_Documentation_URL = new Array();
var SRC_Layer_Metadata_URL = new Array();
var SRC_Layer_Max_Scale = new Array();
var SRC_Layer_Min_Scale = new Array();
var SRC_Layer_Category = new Array();
var SRC_Layer_IDLayers = new Array();
var SRC_Layer_Description = new Array();
var SRC_Layer_Extent_Left = new Array();
var SRC_Layer_Extent_Right = new Array();
var SRC_Layer_Extent_Bottom = new Array();
var SRC_Layer_Extent_Top = new Array();
var SRC_Layer_Download_URL = new Array();
	
//*****************************************************************************
// Function AddUSGSOGCLayers
// This function creates a new layer with the USGS Logo
// Made to be called from the MapFrame.htm eg: "AddUSGSLogoLayer(mWidth, mHeight, sWidth, sHeight);"
// Place the call to this before the "map image" layer so that it appears beneath 
// any map service stuff, like the scale bar, north arrow, acetate layers...
// This will also set the Number_OGC_Layers to the a count of the currently 
// defined layers.
//*****************************************************************************
function AddUSGSOGCLayers(mWidth, mHeight, sWidth, sHeight) {
  //set Number_OGC_Layers to total count of Layers defined.
  Number_OGC_Layers = SRC_Layer_URL.length;
  for (var i=0;i<Number_OGC_Layers;i++) {
		var content = '<img name="BackgroundMap' + i + '" alt="Background Map ' + i + '" onload="FinishedLoading();" src="/website/ImageArchive/secondary/pixel.gif" hspace="0" vspace="0" border="0" width="' + mWidth + '" height="' + mHeight + '"> ';
		createLayer("theBackground" + i,0,0,sWidth,sHeight,false,content);
  }
}

//*****************************************************************************
// Function DrawOGCLayers
// This function updates the OGC Layers that are under the map image with 
// images that are OGC WMS requests.  This is map to be called from the
// afterMapRefresh() function in the MapFrame.htm.  The Scale call needs
// the USGS Scale Bar Tool loaded to get the current scale.
//*****************************************************************************
function DrawOGCLayers(mWidth, mHeight, eLeft, eBottom, eRight, eTop) {
  //Start the Status Indicator
  //ADDED .parent FOR CHANGE FOR OGC BUSY ERROR and capitalized the L on DownLoading
  parent.OGCDownLoading_Count = 0;
 // alert ("from draw" + parent.OGCDownLoading_Count + "," +OGCDownLoading_Count +"," +top.OGCDownLoading_Count + "," +document.OGCDownLoading_Count );
   if (USGS_Group_Loaded) { IVM_OGC_Update_Layer(); }
  //Check if we need to update the WMS requests
  localCheck = false;
  if ( (CheckForExtentChange != '&WIDTH=' + mWidth + '&HEIGHT=' + mHeight + '&BBOX=' + eLeft + ',' + eBottom + ',' + eRight + ',' + eTop) || OGC_Low_Bandwidth ) {
    //Extent has changed, so update the Extent Check, and recreate all the layers...
    CheckForExtentChange = '&WIDTH=' + mWidth + '&HEIGHT=' + mHeight + '&BBOX=' + eLeft + ',' + eBottom + ',' + eRight + ',' + eTop;
    localCheck = true;
  }
  //Get the Current Scale from USGS Scale Tool
  var CenterAdjust = Math.abs(eRight - eLeft);
  var CurrentMapScale = HaversineScale((eLeft + CenterAdjust), eBottom, (eLeft + CenterAdjust), eTop, mHeight, ScaleToolDPI);
  //Hide all the layers so the user does not see garbage or out-of-scale images  (Doesn't work?????)
	/*for (var i=0;i<Number_OGC_Layers;i++) {
    hideLayer('theBackground' + i);
    TempString2 = 'document.BackgroundMap' + i + '.src = "images/pixel.gif"';
    eval(TempString2);
  }*/
  //Counter used to determine which background OGC layer to update
  Background_Image_Counter = 0;
  //Cycle through the Categories from the Category_Order array
	for (var i=Category_Order.length-1;i>=0;i--) {
    if (Category_Layer_Order[i].length>0) {
      //For each category, get the Layer_Order and Layer_Visibility and split into some temp arrays.
      TempArray = Category_Layer_Order[i].split(',');
      TempArray2 = Category_Layer_Visibility[i].split(',');
      //Cycle through the layers for this current category in Layer_Order
	    for (var j=TempArray.length-1;j>=0;j--) {
        //Check the layer's scale factor and extent to see if we should display it
        if (Check_Layer_Extent_and_Scale(TempArray[j], eLeft, eBottom, eRight, eTop, CurrentMapScale)) {
          //Passes Extent/Scale check, so display the layer 
          //if we need to rebuild the request (extent change) then do that before drawing the layer
          if (localCheck) {
            //Build the OGC WMS request string
            /*if (SRC_Layer_URL[TempArray[j]].indexOf('terraservice')>0) {
              TempString = SRC_Layer_URL[TempArray[j]] + CheckForExtentChange + '&REQUEST=GetMap';
            } else {*/
              TempString = SRC_Layer_URL[TempArray[j]] + CheckForExtentChange + '&REQUEST=GetMap&EXCEPTIONS=se_blank';
            //}
            if ((OGC_Low_Bandwidth && TempArray2[j]=='true') || !OGC_Low_Bandwidth){
			  //Downloading_Count++;
			  parent.OGCDownLoading_Count++;
              //Create a string with JavaScript to update a Background Layer, using the Backgroung_Image_Counter setting it to the string above
              TempString2 = 'document.BackgroundMap' + Background_Image_Counter + '.src = "' + TempString + '"';
              //Evaluate that string (execute the JavaScript)
              eval(TempString2);
              //Create a string with JavaScript to update a Background Layer, using the Backgroung_Image_Counter setting the name to reflect the layer
              TempString2 = 'document.BackgroundMap' + Background_Image_Counter + '.alt = "' + SRC_Layer_Name[TempArray[j]] + '"';
              //Evaluate that string (execute the JavaScript)
              eval(TempString2);
            }
          }
          //Now hide or show that layer based upon the visibility array 
          if (TempArray2[j]=='true') {
            showLayer('theBackground' + Background_Image_Counter);
          } else {
            hideLayer('theBackground' + Background_Image_Counter);
          }
        } else {
          //Layer is out of scale, so hide it if it is showing...
          hideLayer('theBackground' + Background_Image_Counter);
        }
        Background_Image_Counter++;
      }
    }
  }
  //Start the Update Status Indicator Process
  setTimeout('parent.CheckDownloadStatus()',1000);
}

//*****************************************************************************
// Function getOGCTOC
// This function will generate HTML code to draw the OGC layer list with the
// categories expanded/collapsed and the Layer classification, if shown.
// It returns the code as an HTML table to do indenting properly.  The 
// Category expand/collapse functions, do reload the window in order to 
// get the client to call this function again and redraw the window.
// page2Load is used for the expanding/collapsing of categories.  It must 
// specify the page that called the function.  This can be done by passing
// window.location.pathname in the call to this function.  
//*****************************************************************************
function getOGCTOC(page2Load) {
  
  //Initialize the String to return with the table header
  var LocalString = '';
  if (Show_TOC_Title) {
    LocalString += ('<div align="left" class="title_label">&nbsp;Layers</div>');
  }
  LocalString += '<form name="OGCLayerlist"><table border="0" cellpadding="0" cellspacing="0" summary="Categorized Layer list of OGC layers">';
  //Get the Current Scale from USGS Scale Tool
  var CenterAdjust = Math.abs(eRight - eLeft);
  var CurrentMapScale = HaversineScale((eLeft + CenterAdjust), eBottom, (eLeft + CenterAdjust), eTop, mHeight, ScaleToolDPI);
  //Cycle through the Categories array
	for (var i=0;i<Category_Order.length;i++) {
    //First show the Category Expanded/Collapsed Icon
    LocalString += ('<tr><td valign=top align=right><a name="C' + i + '"></a><a href="' + page2Load + '"');
    if (Category_Expanded[i]) {
      LocalString += (' onclick="parent.MapFrame.Category_Expanded[' + i + ']=false;parent.MapFrame.TOC_Hash=\'C' + i + '\';" title="Collapse Category (Hide Layer List for this category)">');
      LocalString += ('<img src="' + Category_Expanded_Image + '" alt="Collapse Category (Hide Layer List for this category)" border="0" height="18" width="18" valign="middle" />');
    } else {
      LocalString += (' onclick="parent.MapFrame.Category_Expanded[' + i + ']=true;parent.MapFrame.TOC_Hash=\'C' + i + '\';" title="Expand Category (Show Layer List for this category)">');
      LocalString += ('<img src="' + Category_Collapsed_Image + '" alt="Expand Category (Show Layer List for this category)" border="0" height="18" width="18" valign="middle" />');
    }
    LocalString += ('</a></td>');
    //Now show the Category Name
    LocalString += ('<td colspan="2" valign="top" align="left"><strong>' + Category_Order[i] + '</strong></td></tr>');
    //If the Category is Expanded, then we need to draw out the Layer names under that Category.
    if (Category_Expanded[i]) {
      if (Category_Layer_Order[i].length>0) {
        TempArray = Category_Layer_Order[i].split(',');
        TempArray2 = Category_Layer_Visibility[i].split(',');
        //Do the check for Bad Scale - This makes sure that if all layers are out of scale we present a message to the user, if 
        //out of scale layers are not being displayed...
        CheckForBadScaleLayer = 'All Layers out of Scale';
        //Cycle through the layers from the Category_Layer_Order which has been split into TempArray
 		    for (var j=0;j<TempArray.length;j++) {
          //If we are not displaying layers that are out of scale, then check the scale here
          //before drawing the layer.
          if (Include_Bad_Scale) {
            //We are displaying layers even if they are out of scale, so change the CheckForBadScalelayer variable...
            CheckForBadScaleLayer = 'Has Some in Scale';
            LocalString += GetOGCTOC_Layer(j, i, TempArray[j], CurrentMapScale);
          } else {
          //Check the layer's scale factor and extent to see if we should display it
          if (Check_Layer_Extent_and_Scale(TempArray[j], eLeft, eBottom, eRight, eTop, CurrentMapScale)) {
            //Passes Extent/Scale check, so display the layer
            CheckForBadScaleLayer = 'Has Some in Scale';
            LocalString += GetOGCTOC_Layer(j, i, TempArray[j], CurrentMapScale);
          }
          }
        }
        //Report an error message if all layers were out of scale...
        if (CheckForBadScaleLayer == 'All Layers out of Scale') {
          LocalString += ('<tr><td>&nbsp;</td><td colspan="2" valign="top" align="left"><span style="color:#CCCCCC">No layers in the current scale</span></td></tr>');
        }
      } else {
        //Report an error message if there are no layers in this category.
        LocalString += ('<tr><td>&nbsp;</td><td colspan="2" valign="top" align="left"><span style="color:#CCCCCC">No Layers available in this category</span></td></tr>');
      }
    }
  }
  //Now close the table up
  LocalString += ('</table></form>');
  return LocalString;
}


//*****************************************************************************
// Function GetOGCTOC_Layer
// This function generates the HTML code for the individual layers displayed 
// by getOGCTOC above.  This was broken out to make the code a little easier
// to read, parse and work with.  It will take a Category, LayerID and 
// information on the current scale and layer within a category to generate
// table rows showing the layer names.  This allows for a different style
// of TOC to be drawn, yet display the same layers.  The table rows should 
// be 3 columns.
//*****************************************************************************
function GetOGCTOC_Layer(CategoryLayerID, CategoryID, LayerID, CurrentMapScale) {
  var LocalString = "";
    //*********************************************************************                   
    //*			  START of Code to Add USGS Grouping Layers                   *
    //*********************************************************************
  //If using the Group rendering then grouped layers only get 1 TOC entry, so
  //we do a check to see if one TOC entry has already been displayed...
  var Temp_Keyword = -1;

  if (USGS_Group_Loaded) {
    Temp_Keyword = IVM_Keyword_check(SRC_Layer_Name[LayerID]);
  }

  if (Temp_Keyword>-1){
    if (!IVM_Selected_Layer_Displayed[Temp_Keyword]){
    	IVM_Selected_Layer_Displayed[Temp_Keyword] = true;
        LocalString += ('<tr><td>&nbsp;</td><td valign="top" align="left">');
	
	if(parent.MapFrame.IVM_Selected_Layer_SubSelect[Temp_Keyword] == "[Not Selected]" || parent.MapFrame.IVM_Selected_Layer_SubSelect[Temp_Keyword] == undefined){
		LocalString += ('<input type="Button" style="font-size: 6pt; padding: 0px; border-style: inset;" name="GroupButton" + Temp_Index  value=" O " ');
	}else{
		LocalString += ('<input type="Button" style="font-size: 6pt; padding: 0px;" name="GroupButton" + Temp_Index  value=" X " ');
	}

/*										
     if(Temp_Keyword == 6){		//You know the number maybe something else				
        LocalString += (' onclick="parent.MapFrame.setCORONA(' + Temp_Keyword + ');"');
		        
      }else {
        LocalString += (' onclick="parent.MapFrame.setLPDAAC(' + Temp_Keyword + ');"');
      }else if (Temp_Keyword > 7) {
	    LocalString += (' onclick="parent.MapFrame.setMODIS(' + Temp_Keyword + ');"');

	  
	  }
*/	  
		if(Temp_Keyword >7 && Temp_Keyword < 10 || Temp_Keyword == 11){
			
	         	LocalString += (' onclick="parent.MapFrame.setMODIS(' + Temp_Keyword + ');"');
		}else if(Temp_Keyword == 6){
	   		//You know the number maybe something else				
        		LocalString += (' onclick="parent.MapFrame.setCORONA(' + Temp_Keyword + ');"');
   		}else{
	         	 LocalString += (' onclick="parent.MapFrame.setLPDAAC(' + Temp_Keyword + ');"');

	  }
	  
	 

/*
     if(Temp_Keyword > 7){						
        LocalString += (' onclick="parent.MapFrame.setMODIS(' + Temp_Keyword + ');"');
		        
      }else {
        LocalString += (' onclick="parent.MapFrame.setCORONA(' + Temp_Keyword + ');"');
      }
*/
    if ((SRC_Layer_Max_Scale[LayerID]!=0 && SRC_Layer_Max_Scale[LayerID]<CurrentMapScale) || ((SRC_Layer_Min_Scale[LayerID]!=0 && SRC_Layer_Min_Scale[LayerID]>CurrentMapScale) ) ){
      LocalString += (' disabled="disabled"');
      DisableColor = '#CCCCCC';
    } else {
      LocalString += (' readonly="readonly"');
      DisableColor = parent.USGSTextColor;
    }
    LocalString += (' />');

    //If the Layer has a documentation URL then write our layer name hot-linked to that URL
    if (SRC_Layer_Documentation_URL[LayerID].length>0) {

       if(parent.MapFrame.IVM_Selected_Layer_SubSelect[Temp_Keyword] == "[Not Selected]" || parent.MapFrame.IVM_Selected_Layer_SubSelect[Temp_Keyword] == "undefined"){
      		LocalString += ('</td><td valign="top" align="left"><a href="' + SRC_Layer_Documentation_URL[LayerID] + '" target="_blank" title="View Documentation about this layer."><span style="color: ' + DisableColor + ';">' + parent.MapFrame.IVM_Keyword_Array[Temp_Keyword] + '</span></a></td></tr>');	   
	}else{		
      		LocalString += ('</td><td valign="top" align="left"><a href="' + SRC_Layer_Documentation_URL[LayerID] + '" target="_blank" title="View Documentation about this layer."><span style="color: ' + DisableColor + ';">' + parent.MapFrame.IVM_Selected_Layer_SubSelect[Temp_Keyword] + '</span></a></td></tr>');
        }

    } else {
      //No Documentation URL, so if there is a Metadata URL hot-link the layer name to that
      if (SRC_Layer_Metadata_URL[LayerID].length>0) {

	    if(parent.MapFrame.IVM_Selected_Layer_SubSelect[Temp_Keyword] == "[Not Selected]" || parent.MapFrame.IVM_Selected_Layer_SubSelect[Temp_Keyword] == "undefined"){
      		LocalString += ('</td><td valign="top" align="left"><a href="' + SRC_Layer_Metadata_URL[LayerID] + '" target="_blank" title="View Documentation about this layer."><span style="color: ' + DisableColor + ';">' + parent.MapFrame.IVM_Keyword_Array[Temp_Keyword] + '</span></a></td></tr>');	   
	     }else{		
      		LocalString += ('</td><td valign="top" align="left"><a href="' + SRC_Layer_Metadata_URL[LayerID] + '" target="_blank" title="View Documentation about this layer."><span style="color: ' + DisableColor + ';">' + parent.MapFrame.IVM_Selected_Layer_SubSelect[Temp_Keyword] + '</span></a></td></tr>');
	     }

      } else {
        //No Documentation URL or Metadata URL, so just print the Layer name.

	    if(parent.MapFrame.IVM_Selected_Layer_SubSelect[Temp_Keyword] == "[Not Selected]" || parent.MapFrame.IVM_Selected_Layer_SubSelect[Temp_Keyword] == "undefined"){
      		LocalString += ('</td><td valign="top" align="left"><span style="color: ' + DisableColor + ';">' + parent.MapFrame.IVM_Keyword_Array[Temp_Keyword] + '</span></a></td></tr>');	   
	     }else{		
      		LocalString += ('</td><td valign="top" align="left"><span style="color: ' + DisableColor + ';">' + parent.MapFrame.IVM_Selected_Layer_SubSelect[Temp_Keyword] + '</span></a></td></tr>');
	     }
      }
    }
    //If we are displaying layer classification and this layer has a legend image URL defined, then we display that
    if (Display_Layer_Classification && SRC_Layer_Icon_URL[LayerID].length > 0) {
      LocalString += ('<tr><td>&nbsp;</td><td>&nbsp;</td><td valign="top" align="left">');
      LocalString += ('<img src="' + SRC_Layer_Icon_URL[LayerID] + '" style="background-color: #FFFFFF;" alt="Classification for ' + SRC_Layer_Name[LayerID] + '" /></td></tr>');
    }

    }//end if (!IVM_Selected_Layer_Displayed[Temp_Keyword])
  }else{
    //*********************************************************************
    //*			  END of Code to Add USGS Grouping Layers                     *
    //*********************************************************************

    LocalString += ('<tr><td>&nbsp;</td><td valign="top" align="left">');
    LocalString += ('<input type="checkbox"');

   //Put the visibility into a local array
    VisibleArray = Category_Layer_Visibility[CategoryID].split(',');
    //Mark the checkbox as checked if the current layer is visible

    if (VisibleArray[CategoryLayerID]=='true') { LocalString += (' checked="checked"'); }

    //Construct the visiblity function for clickin the checkbox to set the visibility string for the category
    //with the current layer flipped.
    //If we are using  the Group Layers, we want to update the visibility
    //of the layers based upon the group rendering.
    LocalString += (' onclick="parent.MapFrame.change_Layer_Visibility(' + CategoryID + ',' + CategoryLayerID + ');"');
    //And redraw the OGC background layers when the checkbox is clicked
    //LocalString += ('parent.MapFrame.afterMapRefresh();"');
    //enable/disable the checkbox and set a string used later to color-code the label
    if ((SRC_Layer_Max_Scale[LayerID]!=0 && SRC_Layer_Max_Scale[LayerID]<CurrentMapScale) || ((SRC_Layer_Min_Scale[LayerID]!=0 && SRC_Layer_Min_Scale[LayerID]>CurrentMapScale) ) ){
      LocalString += (' disabled="disabled"');
      DisableColor = '#CCCCCC';
    } else {
      LocalString += (' readonly="readonly"');
      DisableColor = parent.USGSTextColor;
    }
    //and finally close the check box
    LocalString += (' />');

    //If the Layer has a documentation URL then write our layer name hot-linked to that URL
    if (SRC_Layer_Documentation_URL[LayerID].length>0) {
      		LocalString += ('</td><td valign="top" align="left"><a href="' + SRC_Layer_Documentation_URL[LayerID] + '" target="_blank" title="View Documentation about this layer."><span style="color: ' + DisableColor + ';">' + SRC_Layer_Name[LayerID] + '</span></a></td></tr>');
    } else {
      //No Documentation URL, so if there is a Metadata URL hot-link the layer name to that
      if (SRC_Layer_Metadata_URL[LayerID].length>0) {

        LocalString += ('</td><td valign="top" align="left"><a href="' + SRC_Layer_Metadata_URL[LayerID] + '" target="_blank" title="View Documentation about this layer."><span style="color: ' + DisableColor + ';">' + SRC_Layer_Name[LayerID] + '</span></a></td></tr>');

      } else {
        //No Documentation URL or Metadata URL, so just print the Layer name.

        LocalString += ('</td><td valign="top" align="left"><span style="color: ' + DisableColor + ';">' + SRC_Layer_Name[LayerID] + '</span></td></tr>');

      }
    }
    //If we are displaying layer classification and this layer has a legend image URL defined, then we display that
    if (Display_Layer_Classification && SRC_Layer_Icon_URL[LayerID].length > 0) {
      LocalString += ('<tr><td>&nbsp;</td><td>&nbsp;</td><td valign="top" align="left">');
      LocalString += ('<img src="' + SRC_Layer_Icon_URL[LayerID] + '" style="background-color: #FFFFFF;" alt="Classification for ' + SRC_Layer_Name[LayerID] + '" /></td></tr>');
    }
    //*********************************************************************                   
    //*			  START of Code to Add USGS Grouping Layers                   *
    //*********************************************************************
  } // end if (Temp_Keyword>-1)
    //*********************************************************************
    //*			  END of Code to Add USGS Grouping Layers                     *
    //*********************************************************************

    return LocalString;
}
//*****************************************************************************
// Function simpleOGCTOC
// This function will generate HTML code to draw the OGC layer list with no
// categories.  In essence, it will look just like the ESRI HTML TOC, but can
// have a few more capabilities, like URL, and Legend embedding...  
//*****************************************************************************
function simpleOGCTOC() {
 
  //Initialize the String to return with the table header
  var LocalString = '';
  if (Show_TOC_Title) {
    LocalString += ('<div align="left" class="title_label">&nbsp;Layers</div>');
  }
  LocalString += '<form name="SimpleOGClist"><table border="0" cellpadding="0" cellspacing="0" summary="Categorized Layer list of OGC layers">';
  //Get the Current Scale from USGS Scale Tool
  var CenterAdjust = Math.abs(eRight - eLeft);
  var CurrentMapScale = HaversineScale((eLeft + CenterAdjust), eBottom, (eLeft + CenterAdjust), eTop, mHeight, ScaleToolDPI);
  //Do the check for Bad Scale - This makes sure that if all layers are out of scale we present a message to the user, if 
  //out of scale layers are not being displayed...
  CheckForBadScaleLayer = 'All Layers out of Scale';
  //Cycle through the Categories array
	for (var i=0;i<Category_Order.length;i++) {
    if (Category_Layer_Order[i].length>0) {
      TempArray = Category_Layer_Order[i].split(',');
      TempArray2 = Category_Layer_Visibility[i].split(',');
      //Cycle through the layers from the Category_Layer_Order which has been split into TempArray
	    for (var j=0;j<TempArray.length;j++) {
        //If we are not displaying layers that are out of scale, then check the scale here
        //before drawing the layer.
        if (Include_Bad_Scale) {
          //We are displaying layers even if they are out of scale, so change the CheckForBadScalelayer variable...
          CheckForBadScaleLayer = 'Has Some in Scale';
          LocalString += GetOGCTOC_Layer(j, i, TempArray[j], CurrentMapScale);
        } else {
          //Check the layer's scale factor and extent to see if we should display it
          if (Check_Layer_Extent_and_Scale(TempArray[j], eLeft, eBottom, eRight, eTop, CurrentMapScale)) {
            //Passes Extent/Scale check, so display the layer
            CheckForBadScaleLayer = 'Has Some in Scale';
            LocalString += GetOGCTOC_Layer(j, i, TempArray[j], CurrentMapScale);
          }
        }
      }
    }
  }
  //Report an error message if all layers were out of scale...
  if (CheckForBadScaleLayer == 'All Layers out of Scale') {
    LocalString += ('<tr><td>&nbsp;</td><td colspan="2" valign="top" align="left"><span style="color:#CCCCCC">No layers in the current scale</span></td></tr>');
  }
  //Now close the table up
  LocalString += ('</table></form>');
  return LocalString;
}

//*****************************************************************************
// Function pan_Move_Images
// This function will move the visible images by a specified amount.  It should
// be called from the panMouse function in aimsNavigation.js. Since the xMove
// and yMove are calculated there, they need to be passed in.  The call to 
// this function should be placed after the clipLayer and MoveLayer calls that
// move layer "theMap".   
//*****************************************************************************
function pan_Move_Images(xMove, yMove) {
  if (Panning_Moves_OGC_Background) {
    //set Number_OGC_Layers to total count of Layers defined.
    Number_OGC_Layers = SRC_Layer_URL.length;
    //Now cycle through the layers and move them by xMove and yMove
    for (var i=0;i<Number_OGC_Layers;i++) {
      if (isVisible("theBackground" + i)) { moveLayer("theBackground" + i,xMove+hspc,yMove+vspc); }
    }
  }
}

//*****************************************************************************
// Function pan_Finished_Moving
// This function moves all the Background OGC Layers back to the correct 
// position in the window.  This is called from the stopPan function in 
// aimsnavigation.js to return the layers back to where they were when the 
// panning started.  
//*****************************************************************************
function pan_Finished_Moving() {
  if (Panning_Moves_OGC_Background) {
    //set Number_OGC_Layers to total count of Layers defined.
    Number_OGC_Layers = SRC_Layer_URL.length;
    for (var i=0;i<Number_OGC_Layers;i++) {
    	moveLayer("theBackground" + i,hspc,vspc);
    }
  }
}

//*****************************************************************************
// Function toggleLegend
// This function changes the Display_Layer_Classification setting and then 
// it will refresh the TOC.  (On the assumption that the TOC is displayed 
// in that... 
//*****************************************************************************
function toggleLegend() {
  Display_Layer_Classification = !Display_Layer_Classification;
  parent.TOCFrame.document.location=appDir+"toc.htm";
}

//*****************************************************************************
// Function Check_Layer_Extent_and_Scale
// This function checks a layer to see if it is outside of the current extent
// or the current scale is outside of the layer's scale.  It returns true only
// if the layer's extent is inside the current extent or the current scale is
// inside the layer's scale range.
//*****************************************************************************
function Check_Layer_Extent_and_Scale(LayerID, MapLeft, MapBottom, MapRight, MapTop, MapScale) {
  var tempCheck = true;
  //Check the layer's scale factor to see if we should display it
  if (SRC_Layer_Min_Scale[LayerID] != 0 || SRC_Layer_Max_Scale[LayerID] != 0) {
    if (SRC_Layer_Min_Scale[LayerID] != 0 && SRC_Layer_Min_Scale[LayerID] > MapScale) {
      //Below Minimum Scale
      tempCheck = false;
    } else if (SRC_Layer_Max_Scale[LayerID] != 0 && SRC_Layer_Max_Scale[LayerID] < MapScale) {
      //Above Maximum Scale
      tempCheck = false;
    }
  }
  //If we have not already gotten a negative, then don't need to check the layer extent
  if (tempCheck) {
    if (SRC_Layer_Extent_Right[LayerID] <= MapLeft) {
      //Layer extent is to the left of the map
      tempCheck = false;
    } else if (SRC_Layer_Extent_Left[LayerID] >= MapRight) {
      //Layer extent is to the right of the map
      tempCheck = false;
    } else if (SRC_Layer_Extent_Bottom[LayerID] >= MapTop) {
      //Layer extent is above the map
      tempCheck = false;
    } else if (SRC_Layer_Extent_Top[LayerID] <= MapBottom) {
      //Layer extent is below the map
      tempCheck = false;
    }
  }
  return tempCheck;
}

//*****************************************************************************
// Function change_Layer_Visibility
// This function changes the category visibility string used to control if a 
// layer is visible or not.  It takes in an index which identifies which layer
// in a category to change, and then produces a new string with that one value
// flipped. 
//*****************************************************************************
function change_Layer_Visibility(CategoryID, CategoryLayerID) {
  //Start with an empty string
  VisibilityString = '';
  //Put the visibility into a local array
  VisibleArray = Category_Layer_Visibility[CategoryID].split(',');
  //Cyle through visibility array and keep all values the same except for CategoryLayerID
  for (var k=0;k<VisibleArray.length;k++){
    if (k==CategoryLayerID && VisibleArray[k].toLowerCase()=='true') {
      VisibilityString += ('false');
    } else if (k==CategoryLayerID && VisibleArray[k].toLowerCase()=='false') {
      VisibilityString += ('true');
    } else {
      VisibilityString += (VisibleArray[k]);
    }
    if (k<VisibleArray.length-1) { VisibilityString += (','); }
  }
  //Now set the Category visibility to the string assembled above
  Category_Layer_Visibility[CategoryID] = VisibilityString;
  afterMapRefresh();
}

//*****************************************************************************
// Function VisibleLayerInfo
// This function lists all the layers currently visible and provides links to
// directly open the image.
//*****************************************************************************
function VisibleLayerInfo() {
  //Start with an Empty String
  var LayerInfoString = '<small>(Layers listed in order with bottom layer first, top layer last)</small><br />';
  //Get the Current Scale from USGS Scale Tool
  var CenterAdjust = Math.abs(eRight - eLeft);
  var CurrentMapScale = HaversineScale((eLeft + CenterAdjust), eBottom, (eLeft + CenterAdjust), eTop, mHeight, ScaleToolDPI);
  //Cycle through the Categories from the Category_Order array
	for (var i=Category_Order.length-1;i>=0;i--) {
    if (Category_Layer_Order[i].length>0) {
      //For each category, get the Layer_Order and Layer_Visibility and split into some temp arrays.
      TempArray = Category_Layer_Order[i].split(',');
      TempArray2 = Category_Layer_Visibility[i].split(',');
      //Cycle through the layers for this current category in Layer_Order
	    for (var j=TempArray.length-1;j>=0;j--) {
        //Check the layer's scale factor and extent to see if we should display it
        if (Check_Layer_Extent_and_Scale(TempArray[j], eLeft, eBottom, eRight, eTop, CurrentMapScale)) {
          //Passes Extent/Scale check, so display the layer
          //Build the OGC WMS request string
          /*if (SRC_Layer_URL[TempArray[j]].indexOf('terraservice')>0) {
            TempString = SRC_Layer_URL[TempArray[j]] + CheckForExtentChange + '&REQUEST=GetMap';
          } else {*/
            TempString = SRC_Layer_URL[TempArray[j]] + CheckForExtentChange + '&REQUEST=GetMap&EXCEPTIONS=se_blank';
          //}
          //Now display the information from that layer 
          if (TempArray2[j]=='true') {
            LayerInfoString += SRC_Layer_Name[TempArray[j]] + ' <a href="' + TempString + '" target="_blank" title="Open Current Layer image in new window"><img src="/website/ImageArchive/secondary/document.gif" alt="Open Current Layer image in new window" width="16" height="16" border="0" /></a><br />';
          }
        }
      }
    }
  }
  return LayerInfoString;
}

//*****************************************************************************
// Function OGCLayerMetadata
// This function lists all the layers currently visible and provides links to
// directly open the image.
//*****************************************************************************
function OGCLayerMetadata() {
  var TempArray;
  var TempArray2;
  var TempString;
  //Save the Use External Window variable so we can reset it when done
  //(It will get set to true to force this to pop up a new window)
  var Local_useExternalWindow = useExternalWindow;
  useExternalWindow = true;
  var WindowContent='';
  WindowContent += ('<ul>');
  WindowContent += ('Current Extent = ' + eLeft + ', ' + eBottom + ', ' + eRight + ', ' + eTop + '<br />');
  WindowContent += ('Map Image Size = ' + iWidth + ', ' + iHeight + '<br />');
  var CenterAdjust = Math.abs(eRight - eLeft);
  var ApproxScale = HaversineScale((eLeft + CenterAdjust), eBottom, (eLeft + CenterAdjust), eTop, iHeight, ScaleToolDPI);
  WindowContent += ('The current Vertical Map Scale (at center) is 1 inch = ' + ApproxScale + ' ');
  if ( MapUnits.toUpperCase() == "CENTIMETERS" ) {
    WindowContent += ('Centimeters');
  } else if ( MapUnits.toUpperCase() == "FEET" ) {
    WindowContent += ('Feet');
  } else if ( MapUnits.toUpperCase() == "KILOMETERS" ) {
    WindowContent += ('Kilometers');
  } else if ( MapUnits.toUpperCase() == "METERS" ) {
    WindowContent += ('Meters');
  } else if ( MapUnits.toUpperCase() == "MILES" ) {
    WindowContent += ('Miles');
  } else {
    WindowContent += ('Inches');
  }
  WindowContent += ('</ul>');
  WindowContent += ('<br /><h2>OGC Layer Metadata:</h2><br />');
  //Create the table
	WindowContent += ('<table summary="OGC Layer Metadata Table" border="1" cellspacing="2" cellpadding="2">');
	WindowContent += ('<thead><th><a href="javascript:void(0);" onclick="alert(\'This is the category and layer name that is displayed in the layer list.\');">Layer</a></th>');
  WindowContent += ('<th nowrap><a href="javascript:void(0);" onclick="alert(\'A short description of what the data portrays, including links to documentation, and information that describes at what scales this data will appear, and what geographic extent this data has coverage for.\');">Description, Scale Range, and Extent Limit</a></th>');
  WindowContent += ('<th><a href="javascript:void(0);" onclick="alert(\'A link to a static image showing the layer classification (Color Key).\');">Legend</a></th>');
  WindowContent += ('<th><a href="javascript:void(0);" onclick="alert(\'A link to FGDC or OGC style metadata that describes this data in much more detail, including information on obtaining the data.\');">Metadata</a></th>');
  WindowContent += ('<th><a href="javascript:void(0);" onclick="alert(\'A link to the home page for the project or data set description.\');">Documentation</a></th>');
  WindowContent += ('<th><a href="javascript:void(0);" onclick="alert(\'A link to the OpenGIS Consortium capabilities file describing the WMS request that this layer can handle, allowing GIS data experts to use the WMS services directly within their own applications.\');">Capabilities</a></th>');
  WindowContent += ('<th><a href="javascript:void(0);" onclick="alert(\'A link that will display the current WMS request for just this layer in a new window.  GIS data experts could save this image, create a world file, and use this image locally.\');">Current Image</a></th></thead>');
  //Cycle through the Categories
	for (var i=0;i<Category_Order.length;i++) {
    if (Category_Layer_Order[i].length>0) {
      TempArray = Category_Layer_Order[i].split(',');
      TempArray2 = Category_Layer_Visibility[i].split(',');
      //Cycle through the layers in each category
	    for (var j=0;j<TempArray.length;j++) {
        WindowContent += ('<tr>');
        WindowContent += ('<td>' + Category_Order[i] + '<br />' + SRC_Layer_Name[TempArray[j]] + '</td>');
        WindowContent += ('<td>' + SRC_Layer_Description[TempArray[j]]);
        WindowContent += ('<br />Scale Range: ' + SRC_Layer_Min_Scale[TempArray[j]] + ' - ' + SRC_Layer_Max_Scale[TempArray[j]]);
        WindowContent += ('<br />Extent Coverage: ' + SRC_Layer_Extent_Left[TempArray[j]] + ', ' + SRC_Layer_Extent_Bottom[TempArray[j]] + ' - ' + SRC_Layer_Extent_Right[TempArray[j]] + ', ' + SRC_Layer_Extent_Top[TempArray[j]]);
        WindowContent += ('</td>');
        if (SRC_Layer_Icon_URL[TempArray[j]].length>0) {
          WindowContent += ('<td nowrap="nowrap" align="CENTER"><a href="' + SRC_Layer_Icon_URL[TempArray[j]] + '" title="Open Layer Classification in a new window" target="_blank"><img src="/website/ImageArchive/secondary/document.gif" alt="Open Layer Classification in a new window" width="16" height="16" border="0" /></a></td>');
        } else {
          WindowContent += ('<td nowrap="nowrap" align="CENTER">None</td>');
        }
        if (SRC_Layer_Metadata_URL[TempArray[j]].length>0) {
          WindowContent += ('<td nowrap="nowrap" align="CENTER"><a href="' + SRC_Layer_Metadata_URL[TempArray[j]] + '" title="Open Layer Metadata in a new window" target="_blank"><img src="/website/ImageArchive/secondary/document.gif" alt="Open Layer Metadata in a new window" width="16" height="16" border="0" /></a></td>');
        } else {
          WindowContent += ('<td nowrap="nowrap" align="CENTER">None</td>');
        }
        if (SRC_Layer_Documentation_URL[TempArray[j]].length>0) {
           WindowContent += ('<td nowrap="nowrap" align="CENTER"><a href="' + SRC_Layer_Documentation_URL[TempArray[j]] + '" title="Open Layer Documentation in a new window" target="_blank"><img src="/website/ImageArchive/secondary/document.gif" alt="Open Layer Documentation in a new window" width="16" height="16" border="0" /></a></td>');
        } else {
          WindowContent += ('<td nowrap="nowrap" align="CENTER">None</td>');
        }
        if (SRC_Layer_URL[TempArray[j]].length>0) {
           WindowContent += ('<td nowrap="nowrap" align="CENTER"><a href="' + SRC_Layer_URL[TempArray[j]] + '&REQUEST=capabilities' + CheckForExtentChange + '" title="Open WMS Capabilities in a new window" target="_blank"><img src="/website/ImageArchive/secondary/document.gif" alt="Open WMS Capabilities in a new window" width="16" height="16" border="0" /></a></td>');
        } else {
          WindowContent += ('<td nowrap="nowrap" align="CENTER">None</td>');
        }
        if (TempArray2[j]=='true') {
          /*if (SRC_Layer_URL[TempArray[j]].indexOf('terraservice')>0) {
            TempString = SRC_Layer_URL[TempArray[j]] + CheckForExtentChange + '&REQUEST=GetMap';
          } else {*/
            TempString = SRC_Layer_URL[TempArray[j]] + CheckForExtentChange + '&REQUEST=GetMap&EXCEPTIONS=se_blank';
          //}
          WindowContent += ('<td nowrap="nowrap" align="CENTER"><a href="' + TempString + '" target="_blank" title="Open Current Layer image in new window"><img src="/website/ImageArchive/secondary/document.gif" alt="Open Current Layer image in new window" width="16" height="16" border="0" /></a></td>');
        } else {
          WindowContent += ('<td nowrap="nowrap" align="CENTER">None</td>');
        }
        WindowContent += ('</tr>');
      }
    }
  }
  WindowContent += ('</table>');
  WindowContent += ('<br /><br /><br />');
  WindowContent += ('Alternate Content URL: <a href="' + parent.USGSalternative + '" target="_blank">' + parent.USGSalternative + '</a><br />');
  Create_Pop_Up_Window('OGC Map Information', '', WindowContent, 'OGCMetadataWindow', 'scrollbars=yes,resizable=yes');
  useExternalWindow = Local_useExternalWindow;
}


//*****************************************************************************
// Function IdentifyAllWindow
// This function takes the place of the normal identify call.  It will open a 
// new window and go through all the visible layers, and create an IFrame for
// each that sends a WMS Identify request with an X,Y coordinate.  This does 
// not highlight features on the map and may return errors in some IFrames if
// there is no feature where the X,Y coordinate are
//*****************************************************************************
function IdentifyAllWindow(e) {
  //Get the X and Y to pass to the identify queries
	var theX = mouseX;
	var theY = mouseY;
  var TempArray;
  var TempArray2;
  var TempString;
  //Save the Use External Window variable so we can reset it when done
  //(It will get set to true to force this to pop up a new window)
  var Local_useExternalWindow = useExternalWindow;
  useExternalWindow = true;
  var WindowContent='';
  //Get the Current Scale from USGS Scale Tool
  var CenterAdjust = Math.abs(eRight - eLeft);
  var CurrentMapScale = HaversineScale((eLeft + CenterAdjust), eBottom, (eLeft + CenterAdjust), eTop, mHeight, ScaleToolDPI);
  //Cycle through the Categories from the Category_Order array
	for (var i=Category_Order.length-1;i>=0;i--) {
    if (Category_Layer_Order[i].length>0) {
      //For each category, get the Layer_Order and Layer_Visibility and split into some temp arrays.
      TempArray = Category_Layer_Order[i].split(',');
      TempArray2 = Category_Layer_Visibility[i].split(',');
      //Cycle through the layers for this current category in Layer_Order
	    for (var j=TempArray.length-1;j>=0;j--) {
        //Check the layer's scale factor and extent to see if we should display it
        if (Check_Layer_Extent_and_Scale(TempArray[j], eLeft, eBottom, eRight, eTop, CurrentMapScale)) {
          //Only create an IFrame for layers that are visible and have an Identify string defined...
          if ( TempArray2[j]=='true' && SRC_Layer_IDLayers[TempArray[j]].length > 0 ) {
            TempString = SRC_Layer_URL[TempArray[j]] + '&WIDTH=' + mWidth + '&HEIGHT=' + mHeight + '&BBOX=' + eLeft + ',' + eBottom + ',' + eRight + ',' + eTop;
            TempString += '&REQUEST=feature_info&EXCEPTIONS=INIMAGE&INFO_FORMAT=MIME&X=' + theX + '&Y=' + theY + '&QUERY_LAYERS=' + SRC_Layer_IDLayers[TempArray[j]];    
            WindowContent += ('<strong>' + SRC_Layer_Name[TempArray[j]] + '</strong> (<a href="' + TempString + '" title="Open ' + SRC_Layer_Name[TempArray[j]] + ' identify results in a new window" target="_blank"><img src="/website/ImageArchive/secondary/document.gif" alt="Open ' + SRC_Layer_Name[TempArray[j]] + ' identify results in a new window" width="16" height="16" border="0" /></a>)');
            WindowContent += ('<blockquote><iframe width="100%" src="' + TempString + '">[Unable to display inline frames. Visit <A href="' + TempString + '">the layer Identify Results for this layer.</A>]</iframe></blockquote>');
          }
        }
      }
    }
  }
  Create_Pop_Up_Window('OGC Identify Features', '', WindowContent, 'OGCInfo', 'scrollbars=yes,resizable=yes');
  useExternalWindow = Local_useExternalWindow;
}

//*****************************************************************************
// Function CheckDownloadStatus
// Subtract one from the Downloading_Count variable, an image is done... 
//*****************************************************************************
function FinishedLoading() {
//alert ("from finish count" + parent.OGCDownLoading_Count + "," +OGCDownLoading_Count +"," +top.OGCDownLoading_Count + "," +document.OGCDownLoading_Count );

  parent.OGCDownLoading_Count--;
  //Downloading_Count--;
}