<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">


<HTML xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">

   <HEAD>
      <META http-equiv="content-type" content="text/html; charset=utf-8"/>
      <TITLE>CEDEN AdvancedQueryTool</TITLE>
      <LINK REL='stylesheet' HREF='./Style/style.css' TYPE='text/css'>
      <LINK REL="icon" HREF="favicon.ico" TYPE="image/x-icon">
      <LINK REL="shortcut icon" HREF="favicon.ico" TYPE="image/x-icon">

<SCRIPT SRC='https://maps.google.com/maps?file=api&amp;v=2.x&amp;sensor=false&amp;key=AIzaSyC4X0H6e8jXjmXIZWLked2oewW3wtHtTwE' TYPE='text/javascript'></SCRIPT>              

      <SCRIPT SRC="/JS/markermanager.js"></SCRIPT>

      <SCRIPT SRC="/JS/select.js"></SCRIPT> 
      <SCRIPT SRC="/JS/cedenlib.js"></SCRIPT> 
      <SCRIPT SRC="/JS/tooltip.js"></SCRIPT> 
      <SCRIPT SRC="/JS/customalert.js"></SCRIPT> 



      <SCRIPT TYPE="text/javascript">
      //<![CDATA[


      //---------------------------------------------------------------------------------------------------
      //
      //  Note:   The station data should come to the client sorted by longitude - latitude.
      //          Something like this:
      //
      //          select latitude, longitude, round(latitude, 1) lat, round(longitude, 1) lng
      //          from geometry
      //          where latitude is not null and longitude is not null
      //          order by lng, lat
      //
      //---------------------------------------------------------------------------------------------------

      

					// Define global variables 
      var browser              = 'other'; 
      var category             = 'wq';
      var limit1               = 1000;
      var limit2               = 60000;
      var sep                  = '<BR>';
      var sp                   = '&nbsp;';
      var saved_paramgrps_row  = null;
      //var saved_intervals_row  = null;
      var aqtstatusmsg         = "Dear CEDEN User," + sep + sep +
                                 "Per your request, we have added selection by region " +
                                 "and search boxes to this query tool. " + 
                                 "(Note that you can search HUC or stations by name or by code.) " + sep + sep +
                                 "However, the development of selecting regions on the map " +
                                 "and the new Time Series result category are on hold." + sp + sp +  
                                 "This tool will be removed in the near future and is being replaced by " +
                                 "a new query tool." + sep + sep +
                                 "Thank you for your understanding and for using the CEDEN AQT." + sep + sep;

      var show_missing_latlng_messages = true;

      var is_geo_null_array = {};

      //var tmpdir_prefix = '/var/tmp/ceden_prod_aqt/';
      var tmpdir_prefix = './tmp/ceden_prod_aqt/';




					// Define global variables and functions 
					// pertaining to map.
      if (GBrowserIsCompatible()) {

         var map = null;
         var countiesOverlay = null;
         var hucOverlay = null;
         var mgr = null;
         var markers = [];		// Array holding xml data used to create markers. 
         var active_markers = [];	// Array holding actual markers active on the map.

					// Maximum number of stations allowed in order to 
         var SHOW_ALL_MARKERS = 305;	// display all of them without having to group them.

         var iconBlue = new GIcon(); 
         iconBlue.image = "./Images/blue_marker_icon.png";
         iconBlue.shadow = "./Images/shadow_icon.png";
         iconBlue.iconSize = new GSize(20, 34); // width (px) and height (px)
         iconBlue.shadowSize = new GSize(37, 34);
         iconBlue.iconAnchor = new GPoint(9, 34);
         iconBlue.infoWindowAnchor = new GPoint(9, 2);
         iconBlue.infoShadowAnchor = new GPoint(18, 25);
         iconBlue.transparent = "https://www.google.com/intl/en_ALL/mapfiles/markerTransparent.png";

         var iconGroup = new GIcon(); 
         iconGroup.image = "./Images/group_markers_icon.png";
         iconGroup.shadow = "./Images/shadow_circle_icon.png";
         iconGroup.iconSize = new GSize(20, 20);
         iconGroup.shadowSize = new GSize(29, 24);
         iconGroup.iconAnchor = new GPoint(10, 20);
         iconGroup.infoWindowAnchor = new GPoint(10, 10);
         //iconGroup.infoShadowAnchor = new GPoint(9, 17);
         //iconGroup.transparent = "https://www.google.com/intl/en_ALL/mapfiles/markerTransparent.png";

 
         var dragselectcontrol;

         var customIcons = [];
         customIcons["GROUPED_MARKERS"] = iconGroup;
         customIcons["SHOW_ALL_MARKERS"]= iconBlue;





					// You would think that the client 
					// would automatically decode these 
					// characters, but it does not.  So we 
					// force it to decode them for us so we
					// do not have to do the character mapping
					// ourselves.  

         function html_entity_decode(str) {

            var temp_text = document.createElement('textarea');

            temp_text.innerHTML = str;
            return temp_text.value;
         }



         function changeImage(new_image_name, image_id) {

            var image1 = document.getElementById(image_id);
            image1.src = '/Images/' + new_image_name;

         }




         function getStationsInfoWindowParams(station_code, point) {

           var params = '';
					// This is needed for IE, which 
					// blows up on window names with dashes
           var station_code_window_name = station_code.replace('-','_');

           params = './show_station_info_window.php?station_code=' + station_code + 
                    '&lat=' + point.lat() + '&lng=' + point.lng() + '&category=' + category;

           params = "\'" + params + "\'," + "\'station_info_" + station_code_window_name + "\'";

           params = params + "," + "\'height=400,width=680,resizeable,scrollbars,menubar\'";

           return (params); 

         }//getStationsInfoWindowParams()







         function createMarker(point, name, code, icon) {

            var marker = new GMarker(point, icon);
            var info   = '';
            var params = '';



					// For grouped stations map icon
            if (name == 'none') {
               info = '<B>Please zoom in more or select a smaller region <BR>' +
                      'to see individual stations.</B>';
            }
            else {			// For individual stations

               params  = getStationsInfoWindowParams(code, point);

               if (category == 'ben') tag = 'Organism Counts';
               else                   tag = 'Parameter Counts';

               info = '<B>Station: ' + name + '</B><BR>' +
                      'Code:  '      + code + '</B><BR>' +
                      '<A HREF="./AdvancedQueryTool" onclick="window.open(' + params + ');return false;">' + tag + '</A>';
            }

            GEvent.addListener(marker, "click", function() {
               //map.openInfoWindowHtml(point, info);
               marker.openInfoWindowHtml(info);
            });

            active_markers.push(marker);
            return marker;

         }//createMarker()







         function showAllMarkers(markers) {

            //if (map.isLoaded()) {alert ("map is loaded with boundaries: " + map.getSize()); }

            var point;
            var name;
            var code;
            var m_length = markers.length;

            for (var i = 0; i < m_length; i++) {

					// Only add them if they have lat/lng.
               if (markers[i].getAttribute("lat")) {

                  point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
                                      parseFloat(markers[i].getAttribute("lng")));
                  name = markers[i].getAttribute("name");
                  code = markers[i].getAttribute("code");
                  map.addOverlay(createMarker(point, name, code, customIcons["SHOW_ALL_MARKERS"]));

               }//if

            }//for

         }//showAllMarkers()







         function processMarkers(markers) {

            var batch = [];
            var point;
            var name;
            var code;
            var m_length = markers.length;

            for (i = 0; i < m_length; i++) {
               point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
                                   parseFloat(markers[i].getAttribute("lng")));
               name = markers[i].getAttribute("name");
               code = markers[i].getAttribute("code");

               batch.push(createMarker(point, name, code, customIcons["SHOW_ALL_MARKERS"]));
            }
            return batch;

         }//processMarkers()









         function groupMarkers(markers, group_size) {

            var batch = [];
            var point;
            var m_length = markers.length;

            var lat_sum     = 0.0;
            var lng_sum     = 0.0;
            var lat_average = 0.0;
            var lng_average = 0.0;
            var divisor     = 0;
            var index       = 0;

            if (group_size == m_length) {
               point = new GLatLng(36.17, -119.74);
               batch.push(createMarker(point, "none", "none", customIcons["GROUPED_MARKERS"]));
               return batch;
            }


            var lat = 0.0;

            for (var i = 0; i < m_length; i = i + group_size) {

               for (var j = 0, divisor = 0; j < group_size; j++) {

                  divisor++;
                  index = i + j;
                  if (index >= m_length) {
                      break;
                  }


                  lat = parseFloat(markers[index].getAttribute("lat"));
                  lng = parseFloat(markers[index].getAttribute("lng"));

					// Check for missing/null/zero georeferences.
					// Skip them if found and decrement divisor.
                  if (isNaN(lat) || isNaN(lng) || lat < 30 ) {
                     divisor--;
                  }
                  else {
                    lat_sum = lat_sum + parseFloat(markers[index].getAttribute("lat")); 
                    lng_sum = lng_sum + parseFloat(markers[index].getAttribute("lng"));
                  }

               }//for j


               lat_average = (lat_sum / divisor);
               lng_average = (lng_sum / divisor);

               if (!(isNaN(lat_average) || isNaN(lng_average) || lat_average < 30 )) {

					// Don't keep extraneous values.
                  if (lat_average >   32.5492 && lat_average <   42.0046 && 
                      lng_average > -124.2945 && lng_average < -114.2038) {

                     point = new GLatLng(lat_average, lng_average);
                     batch.push(createMarker(point, "none", "none", customIcons["GROUPED_MARKERS"]));

                  }//if

               }//ifNaN

               lat_sum = 0;
               lng_sum = 0;

            }//for i

            return batch;

         }//groupMarkers()









         function manageMarkers(markers) {

           mgr = new MarkerManager(map);

           var mlen = markers.length;


					// The first argument to addMarkers is the 
					// array of markers returned from groupMarkers()
					// or processMarkers().  The second and third 
					// arguments to addMarkers is zoom range.
					//
					// The first argument to groupMarkers is 
					// the markers themselves, the second is how
					// many to average together - i.e., "clumping factor".
					//
					// Default zoom level upon load is 6.  
					// Zoom range is 0-21.

           if (mlen <= 100) {
              mgr.addMarkers(groupMarkers(markers, mlen),0, 4);
              mgr.addMarkers(groupMarkers(markers, 2),   5, 5);
              mgr.addMarkers(processMarkers(markers),    6, 17);
           }
           else if (mlen > 100 && mlen <= 300) {
              mgr.addMarkers(groupMarkers(markers, mlen),0, 4);
              mgr.addMarkers(groupMarkers(markers, 6),   5, 5);
              mgr.addMarkers(processMarkers(markers),    6, 17);
           }
           else if (mlen > 300 && mlen <= 600) {
              mgr.addMarkers(groupMarkers(markers, mlen),0, 4);
              mgr.addMarkers(groupMarkers(markers,  28), 5, 5);
              mgr.addMarkers(groupMarkers(markers,  12), 6, 6);
              mgr.addMarkers(groupMarkers(markers,   3), 7, 7);
              mgr.addMarkers(processMarkers(markers),    8, 17);
           }
           else if (mlen > 600 && mlen <= 900) {
              mgr.addMarkers(groupMarkers(markers, mlen),0, 4);
              mgr.addMarkers(groupMarkers(markers,  36), 5, 5);
              mgr.addMarkers(groupMarkers(markers,  15), 6, 6);
              mgr.addMarkers(groupMarkers(markers,   5), 7, 7);
              mgr.addMarkers(processMarkers(markers),    8, 17);
           }
           else if (mlen > 900 && mlen <= 1200) {
              mgr.addMarkers(groupMarkers(markers, mlen),0, 4);
              mgr.addMarkers(groupMarkers(markers,  40), 5, 5);
              mgr.addMarkers(groupMarkers(markers,  15), 6, 6);
              mgr.addMarkers(groupMarkers(markers,   6), 7, 7);
              mgr.addMarkers(processMarkers(markers),    8, 17);
           }
           else if (mlen > 1200 && mlen <= 1500) {
              mgr.addMarkers(groupMarkers(markers, mlen),0, 4);
              mgr.addMarkers(groupMarkers(markers,  44), 5, 5);
              mgr.addMarkers(groupMarkers(markers,  12), 6, 6);
              mgr.addMarkers(groupMarkers(markers,   6), 7, 7);
              mgr.addMarkers(groupMarkers(markers,   4), 8, 8);
              mgr.addMarkers(processMarkers(markers),    9, 17);
           }
           else if (mlen > 1500 && mlen <= 1800) {
              mgr.addMarkers(groupMarkers(markers, mlen),0, 4);
              mgr.addMarkers(groupMarkers(markers,  50), 5, 5);
              mgr.addMarkers(groupMarkers(markers,  11), 6, 6);
              mgr.addMarkers(groupMarkers(markers,   6), 7, 7);
              mgr.addMarkers(groupMarkers(markers,   4), 8, 8);
              mgr.addMarkers(processMarkers(markers),    9, 17);
           }
           else if (mlen > 1800 && mlen <= 2100) {
              mgr.addMarkers(groupMarkers(markers, mlen),0, 4);
              mgr.addMarkers(groupMarkers(markers,  52), 5, 5);
              mgr.addMarkers(groupMarkers(markers,  20), 6, 6);
              mgr.addMarkers(groupMarkers(markers,   8), 7, 7);
              mgr.addMarkers(groupMarkers(markers,   6), 8, 8);
              mgr.addMarkers(processMarkers(markers),    9, 17);
           }
           else if (mlen > 2100 && mlen <= 3000) {
              mgr.addMarkers(groupMarkers(markers, mlen),0, 4);
              mgr.addMarkers(groupMarkers(markers,  60), 5, 5);
              mgr.addMarkers(groupMarkers(markers,  32), 6, 6);
              mgr.addMarkers(groupMarkers(markers,  10), 7, 7);
              mgr.addMarkers(groupMarkers(markers,   4), 8, 8);
              mgr.addMarkers(processMarkers(markers),    9, 17);
           }
           else {
              mgr.addMarkers(groupMarkers(markers, mlen),0, 4);
              mgr.addMarkers(groupMarkers(markers, 150), 5, 5);
              mgr.addMarkers(groupMarkers(markers,  75), 6, 6);
              mgr.addMarkers(groupMarkers(markers,  30), 7, 7);
              mgr.addMarkers(groupMarkers(markers,  10), 8, 8);
              mgr.addMarkers(groupMarkers(markers,   5), 9, 9);
              mgr.addMarkers(processMarkers(markers),   10, 17);
           }

           mgr.refresh();

         }//manageMarkers()






					// Action:  Create a string
					//          of parameters that
					//          has selected option
					//          values followed by 
					//          lat/lng borders and 
					//          separated by ampersands.

         function getPostParameters() {

            var params     = getParamString();



            if (min_lat && max_lat && min_lng && max_lng) {

               if (params) params = params + '&';

               params = params +  'min_lat=' + min_lat +
                                 '&max_lat=' + max_lat +
                                 '&min_lng=' + min_lng +
                                 '&max_lng=' + max_lng;
            }//if


            return params;

         }//getPostParameters()






					// Action:   Call to database sending
					//           form data as parameters and 
					//           receiving xml elements back 
					//           containing station data.
					//          
					// Returns:  Array of xml elements
					//           containing lat/lng and
					//           other data from db.

         function getMapData() {

            var req_string    = './get_map_data.php?&category=' + category + '&' + getDateString();
            var params        = getPostParameters();
            var my_markers    = [];

           //synchronous call
            var request = GXmlHttp.create();
            request.open('POST', req_string, false);
            request.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=utf-8");
            request.send(params);
            var xml = request.responseXML;
            my_markers = xml.documentElement.getElementsByTagName('marker'); 

            return (my_markers);

         }//getMapData()


      }//if isCompatible
      else {

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

      }//notCompatible









      function changeResultCategory(id) {

         category = id;
         updateResultCategory(id);
         map = null;
         countiesOverlay = null;
         hucOverlay = null;
         mgr = null;
         markers = [];
         active_markers = [];
         initialize(id);

      }//changeResultCategory();








					// Used to add specific rows
					// to selection drop down table

      function addTableRow(which_row,which_table_id) {
 
         var table = document.getElementById(which_table_id);
         var add_after_row = null;
 
         switch (which_row) {
            case 'paramgrps_selection':
               add_after_row = document.getElementById('projects_row');
               add_after_row.parentNode.insertBefore(saved_paramgrps_row, add_after_row.nextSibling);
               break;

            //case 'intervals_selection':
            //   add_after_row = document.getElementById('matrixes_row');
            //   add_after_row.parentNode.insertBefore(saved_intervals_row, add_after_row.nextSibling);
            //   break;

            default:
               return;

         }//switch





/*
         var table_body = document.getElementById(which_table_id).tBodies[0];
         var row = table.insertRow(row_position);
         //row.innerHTML = paramgrps_row_html;
         row.style.verticalAlign = 'top';
 
         var cell1 = row.insertCell(0);
         cell1.innerHTML = paramgrps_col1_html;
         //cell1.style.align = 'right';
         //cell1.style.verticalAlign = 'top';
         //cell1.style.width = '15%';

         var cell2 = row.insertCell(1);
         cell2.innerHTML = paramgrps_col2_html;
         //cell2.style.align = 'left';

         //paramgrps_row_html = '';
*/ 


 
      }//addTableRow()



      function saveRows() {

            var table_body = document.getElementById('drop_down_selections_table').tBodies[0];
            saved_paramgrps_row = table_body.rows[5].cloneNode(true);
            //saved_intervals_row = table_body.rows[8].cloneNode(true);

      }//saveRows()


 
					// Used to remove specific rows
					// from selection drop down table
      function removeTableRow(which_row, which_table_id) {

         var row_position = 0;
 
         switch (which_row) {
            case 'paramgrps_selection':
                  row_position = 5;
                  break;

            //case 'intervals_selection':
            //      row_position = 8;
            //      break;

            default:
               return;

         }//switch



         try {

            var table      = document.getElementById(which_table_id);

            table.deleteRow(row_position);


        }//try
        catch(e) {
            alert(e);
        }

      }//removeTableRow()




					// Switches original button
					// to new selection, along 
					// with associated selection layer.
					// Pass button reference names as lower
					// case strings.

      function switchButton(old_button, new_button)  {


					// Change select element name and id

         var element  = document.getElementById(old_button + '_select');

         if (element === null) 
            element = document.getElementById(new_button + '_select');


         element.name =  select_button_names[new_button + '_button'];
         element.id   =  new_button + '_select';


					// Change id of related search box.
         element  = document.getElementById(old_button + '_search');
         if (element === null)  element = document.getElementById(new_button + '_search');
         element.id = new_button + '_search';



					// Remove old button from button array
         if (select_buttons.hasOwnProperty(old_button + '_button'))
            delete select_buttons[old_button + '_button'];

					// Add new button to button array
         select_buttons[new_button + '_button']    = new_button + '_select';

					// Update button element id
         element  = document.getElementById(old_button + '_button');
         if (element === null)  element = document.getElementById(new_button + '_button');
         element.id = new_button + '_button';


					// Update related top layer id

         element  = document.getElementById(old_button + '_select_top_layer');
         if (element === null)  element = document.getElementById(new_button + '_select_top_layer');
         element.id = new_button + '_select_top_layer';


      }//switchButton()









      function initCap(str) { 

         var str = str.substring(0,1).toUpperCase() + str.substring(1,str.length).toLowerCase(); 

         return str; 
      } 




      function showMatrixSpecies() {

					// Add matrix/species selection box back to page
         document.getElementById('matrix_species_selection').style.visibility = 'visible';

         var element  = document.getElementById('matrix_button');
         if (element === null)  element = document.getElementById('species_button');

					// Display button image.
         element.style.display = 'block';

      }//showmatxspecies()






      function hideMatrixSpecies() {

					// Remove species and matrix from buttons array
         if (select_buttons.hasOwnProperty('matrix_button'))
            delete select_buttons['matrix_button'];
         if (select_buttons.hasOwnProperty('species_button'))
            delete select_buttons['species_button'];


					// Hide matrix/species button and select box.

         var element  = document.getElementById('matrix_button');
         if (element === null) {
            element  = document.getElementById('species_button');
         }
         if (element !== null)  element.style.display = 'none';

         document.getElementById('matrix_species_selection').style.visibility = 'hidden';

      }//hidematxspecies()









      function showIntervals() {

					// Add interval back to button array
         select_buttons['interval_button'] = 'interval_select';



					// Only add intervals if not there.
         var element  = document.getElementById('interval_select');
         if (element === null)  {

            addTableRow('intervals_selection', 'drop_down_selections_table');

         }//if

					// Now it should be there.
         element  = document.getElementById('interval_select');

					// Add 
         if (element !== null) {
            element.name =  'intervals[]';
            element.id   =  'interval_select';
         }//if

      }//showIntervals()







      function hideIntervals() {
                                        // Remove interval from buttons array
         if (select_buttons.hasOwnProperty('interval_button'))
            delete select_buttons['interval_button'];


         var element  = document.getElementById('interval_select');

                                        // Is interval selection already there?
                                        // If so, remove it.
         if (element !== null ) {

            removeTableRow('intervals_selection', 'drop_down_selections_table');

         }


      }//hideIntervals()






      function showParamGroups() {

					// Add group button back to buttons array.
         select_buttons['group_button'] = 'group_select';


                                       // Only add parameter groups row 
                                       // to table if it is missing.

         var element  = document.getElementById('group_select');

         if (element === null) {

            addTableRow('paramgrps_selection', 'drop_down_selections_table');

         }//if

					// Now it should be there.
         element  = document.getElementById('group_select');

         if (element !== null) {
            element.name =  'groups[]';
            element.id   =  'group_select';
         }//if

         setGroup('parameter');

      }//showParamGroups()





      function hideParamGroups() {

                                        // Remove group from buttons array

         if (select_buttons.hasOwnProperty('group_button'))
            delete select_buttons['group_button'];


         var element  = document.getElementById('group_select');

                                        // Only remove parameter groups if
                                        // it is actually there.
         if (element !== null) {
            removeTableRow('paramgrps_selection', 'drop_down_selections_table');
         }//if


      }//hideParamGroups()







                                        // Hide QA checkbox and link
      function hideQA() {

         var qa     = document.getElementById('qa_checkbox');
         var qalink = document.getElementById('show_qa_link');

         if (qa     !== null) qa.style.visibility     = 'hidden';
         if (qalink !== null) qalink.style.visibility = 'hidden';

      }//hideqa()






                                        // Add QA back to page
      function showQA() {

         var qa     = document.getElementById('qa_checkbox');
         var qalink = document.getElementById('show_qa_link');

         if (qa     !== null) qa.style.visibility     = 'visible';
         if (qalink !== null) qalink.style.visibility = 'visible';

      }//showqa()






                                        // Hide Sample Composite checkbox.
      function hideCompositeCheckBox() {

         var comp   = document.getElementById('composite_checkbox');

         if (comp   !== null) comp.style.visibility   = 'hidden';

      }//hidecomp()






      function showCompositeCheckBox() {

         document.getElementById('composite_checkbox').innerHTML =  
                  "<INPUT TYPE = 'checkbox' NAME='include_comp' ID='include_comp' " + 
                  " onclick='showRecordCount();'>Include Sample Composite Data<BR>";

         document.getElementById('composite_checkbox').style.visibility = 'visible';

      }//showcomp()









					// Set group tags, text, image source
					// to correct values for given group.
					// Pass group name in as lower case string.

      function setGroup(which_group) {

         select_tags_value['group_select']    = 'All ' + initCap(which_group) + ' Groups';
         select_tags_text['group_select']     = 'Do not limit search by ' + initCap(which_group) + ' Group';
         select_buttons_src['group_button']   = './Images/select_' + which_group + '_groups.png';


      }//setGroup()




					// Returns select_id for which parameter is
					// currently active for parameter groups.
      function getWhichParameter() {

         var pattern = /Organism/i;

         if (pattern.test(select_tags_value['group_select'])) return 'organism';

         return 'analyte';

      }//getWhichParameter()








					// Process change in Result Category
					// for Habitat
      function processHabitat() {


         hideParamGroups();

                                        // Set parameter keys/values

         switchButton('organism', 'analyte');


					// Hide QA and Sample Composite.
         hideQA();
         hideCompositeCheckBox();

					// Hide matrix and species.
         hideMatrixSpecies();


     }//processHabitat()









					// Process change in Result Category
					// for Benthic
     function processBenthic() {


         showParamGroups();


         setGroup('organism');


         switchButton('analyte', 'organism');



					// Hide QA and Sample Composite.
         hideQA();
         hideCompositeCheckBox();


					// Hide matrix and species.
         hideMatrixSpecies();



      }//processBenthic()








					// Action:  Update elements on the
					//          page and in the code that are 
					//          specific to a given result 
					//          category. (For example, 
					//          changing from WQ to Tissue.)
					//
                                        // The purpose of this code is to deal
                                        // with drop-down selection box changes
                                        // that must be made when users switch
                                        // from one Result Category to another.
                                        //
                                        // Originally an attempt was made to
                                        // reset all the document elements
                                        // on the HTML page to 'species',
                                        // including the id for the matrix
                                        // element.  Unfortunately, only some
                                        // browsers (Firefox) could consistently
                                        // handle the DHTML involved.  So we must
                                        // reuse the matrix select id (matrix_select)
					// for species by setting its properties 
					// to species as seen below.
                                        // Furthermore, removing matrix element
                                        // as a result of benthic causes client
                                        // to not include element in DOM.  Must
					// change visibility instead.

      function updateResultCategory(id) {

         hideSearchStringBoxes();

         //hideIntervals();

         switch (id) {
            case 'hab':
               processHabitat();
               return;

            case 'ben':
               processBenthic();
               return;

            default:

         }//switch



         showParamGroups();

         showMatrixSpecies();


         switchButton('organism','analyte');



         
         if (id == 'tis') { 

            switchButton('matrix','species');

            showCompositeCheckBox();

            showQA();
            
         }
         else if (id == 'ts') { 

            switchButton('species','matrix');

            hideQA();

            hideCompositeCheckBox();

            //showIntervals();

         }
         else {

            switchButton('species','matrix');

            hideCompositeCheckBox();

            showQA();


         }//else 




      }//updateResultCategory()














					// Action:  Create an array of stations that
					//          are lacking georeferences (lat/lng).

      function createNullGeoStationsArray(all_markers) {

            var nullGeoStationsArray = new Array();
            var all_m_length = all_markers.length;

            for (var i = 0; i < all_m_length; i++) {

               if (!all_markers[i].getAttribute("lat")) {
                  nullGeoStationsArray[i] = new Array(all_markers[i].getAttribute("code"),
                                                      all_markers[i].getAttribute("name"));  
               }//if

            }//for


            return nullGeoStationsArray;

      }//createNullGeoStationsArray()











					// Action:  Create an array of stations that
					//          have georeferences (lat/lng).

      function createGeoStationsArray(all_markers) {

            var all_m_length = all_markers.length;


            for (var i = 0; i < all_m_length; i++) {

               if (!all_markers[i].getAttribute("lat")) {
                   all_markers[i].removeNode();
               }//if

            }//for

            return all_markers;

      }//createGeoStationsArray()




					// Action:
					// - Change 'Map Stations' button 
					//   image from red back to normal. 
					// - Remove selection rectangle
					// - Clear the deactivated screen 
					//   which was set by the rectangle 
					//   selection tool. 
					// - Hide the loading image.
      function resetMapSelection() {

         if (min_lat || min_lng) {

            //GEvent.trigger(document.getElementById('selection_tool_div'), 'click');
            dragselectcontrol.resetDragSelect_();

         }//if

         hideLoading();

         changeImage('map_stations.png', 'stations_button');

      }//resetMapSelection()





      function clearMap() {

         if (mgr)  mgr.clearMarkers();

         if (map)  map.clearOverlays();
         

      }//clearMap()




      function clearStations() {

         if (mgr)  mgr.clearMarkers();

         if (map)  {
            for (var i in active_markers)  map.removeOverlay(active_markers[i]);
         }//if

      }//clearStations()







					// Action:  Check to see if given select
					//          box is in its initial or default 
					//          state, or whether it has been
					//          populated with items, regardless
					//          of whether they were selected 
					//          or not.
					// Returns: true if populated with items, 
					//          and false otherwise. 

      function isSelectBoxPopulated(select_id) {

         var pattern = /^Do not limit search/;
         var select_box = document.getElementById(select_id);
         if (pattern.test(select_box[0].text)) return false;

         return true;

      }//isSelectBoxPopulated()







					// Action:  Finds number of selected
					//          stations in stations drop-
					//          down box that are missing lat/lngs.
					// Returns: Returns number of selected
					//          stations without georefs.

      function getNumberSelectedStationsMissingLatLngs() {

         var split_array             = [];
         var number_missing_geo      = 0;
         var selected_station_params = getSelectedParameters('station_select');


					// Count number of missing lat/lngs
					// found in the user's selected stations
					// in the drop down box.

         for (var i=0; i < selected_station_params.length; i++) {

           split_array = selected_station_params[i].split('=');
           
           if (is_geo_null_array[split_array[1]] == '1') number_missing_geo++;

         }//for

         return number_missing_geo;

      }//getNumberSelectedStationsMissingLatLngs()








					// Action:  Sends message to user
					//          that all of the stations  
					//          that they are trying to map
					//          are missing lat/lngs.
					//
					// Input:   Number stations selected (by any means) 
					//          Number of selected stations missing lat/ngs
					//

      function allStationsMissingLatLngs(number_selected, number_missing_geo) {

                                        // If ALL user's stations are missing
                                        // lat/lngs, inform them that we cannot
                                        // map their stations and return.
         var infomessage = '';
         if (number_selected == 1) infomessage = 'Your selected station was';
         else                      infomessage = 'All ' + number_missing_geo + 
                                                 ' of your selected stations were';

         infomessage = infomessage + ' sent by data providers to CEDEN without latitude or longitude.' + sep +
                       sep +
                          'Stations without georeferences cannot be displayed on the map.  ' + sep +
                       sep +
                       '(Note that stations without latitude/longitudes are displayed in ' + sep +
                       ' red in the selection box.)'
                       //'Uncheck "Include stations that are missing lat/lngs" and try again.';


         makeAlert('All Stations Missing Lat/Lngs', infomessage, 210, 500, 200);



      }//allStationsMissingLatLngs()







					// Action:  Sends message to user
					//          that some of the stations  
					//          that they are trying to map
					//          are missing lat/lngs.
					//
					// Input:   Number of selected stations missing lat/ngs
					//


      function someStationsMissingLatLngs(number_missing_geo) {


         var phrase = '';




         if (number_missing_geo == 1) phrase = 'One of your selected stations is';
         else                         phrase = 'There are ' + number_missing_geo +
                                                  ' of your selected stations that were ';


         var infomessage = phrase + ' given to CEDEN without latitude or longitude. ' + sep + sep +
                          'Stations without georeferences cannot be displayed on the map.  ' + sep + sep +
                          'Note that the "Select Stations" drop-down box shows what is on   ' + sep +
                          'the map; therefore, if you want to keep stations without lat/lngs,' + sep +
                          'do not "Map Stations".';


         makeAlert('Some Stations Missing Lat/Lngs', infomessage, 210, 500, 200);

      }//someStationsMissingLatLngs()















					// Action:  Show selected stations
					//          on the map.  Includes 
					//          selections made with  
					//          rectangle selection tool
					//          as well as selections made 
					//          in the drop-down form boxes.
      function showStations() {

         if (!isValidDateRange()) {
            resetColor('available_dates', '#FF0033');
            makeAlert ("Invalid Date Selection", 
                       'Please enter a valid date range within "Available Dates", or deselect date range completely.',
                       150, 500, 200);
            hideLoading();
            return;
         }//if


         clearStations();


					// When all of user's selected stations 
					// in the drop-down box are missing
					// lat/lngs, there is no point in trying
					// to map them.
					// Instead, send a message and return.

         var number_selected         = getNumberSelected('station_select');
         var number_missing_geo      = getNumberSelectedStationsMissingLatLngs();

         if (isSelectBoxPopulated('station_select') && 
             (number_selected > 0) && (number_selected == number_missing_geo)) {
            if (show_missing_latlng_messages) allStationsMissingLatLngs(number_selected, number_missing_geo);
            resetMapSelection();
            return;
         }//if



         markers = getMapData();	// Get station markers with lat/lngs.


					// In this case, we need to check again 
					// whether all stations have no lat/lngs
					// or not since it may come from 
					// some other item (like a project) 
					// with no georefs at all, even though
					// nothing was selected in the stations
					// drop-down. 
         var nullGeoStationsArray = createNullGeoStationsArray(markers);

         number_selected      = markers.length;
         number_missing_geo   = nullGeoStationsArray.length;

         if (number_selected != 0 && (number_selected == number_missing_geo)) {
            if (show_missing_latlng_messages) allStationsMissingLatLngs(number_selected, number_missing_geo);
            resetMapSelection();
            return;
         }//if


					// If all stations they picked were  
					// missing georefs, we would have 
					// handled that case above.
					// Therefore, there must be some other
					// there is some other reason no stations
					// are not showing up.  Let's tell user 
					// what the possible reasons are and 
					// then return immediately.
         if (markers.length == 0) {



            var infomessage = 'No stations found. There are a few possibilities as to why:' + sep +
                   sep +
                   '1) There may actually be no existing stations that match the choices ' + sep + 
                   sp + sp + sp + sp +
                   'you have made, especially if the date range is too narrow.' + sep + 
                   sep + 
                   '2) When you see GREEN CIRCLES on the map, they are grouped stations ' + sep + 
                   sp + sp + sp + sp +
                   'since there are too many to show individually.  We are using an ' + sep + 
                   sp + sp + sp + sp +    
                   'average to group them, so occasionally the circle is not in the ' + sep + 
                   sp + sp + sp + sp +    
                   'exact same location as the individuals.  In that case, zoom in ' + sep + 
                   sp + sp + sp + sp +    
                   'closer or draw a larger box to get the individual stations that ' + sep + 
                   sp + sp + sp + sp +    
                   'you want.' + sep +
                   sep + 
                   '3) If you drew a rectangle on the map, there may actually be no ' + sep +
                   sp + sp + sp + sp +    
                   'existing stations in that location.' + sep +
                   sp + sp + sp + sp +    
                   '[Be sure to select the POINT, not the head of the station marker.]' + sep +
                   sep + 
                   '4) If you already have made selections in the drop-down boxes ' + sep +
                   sp + sp + sp + sp +    
                   'or on the map then drew a map rectangle that is outside those ' + sep +
                   sp + sp + sp + sp +    
                   'locations, there will no stations to match what you have already ' + sep + 
                   sp + sp + sp + sp +    
                   'chosen.' + sep +
                   sp + sp + sp + sp +    
                   'In that case, you should choose "Start Over", map your selections, ' + sep +
                   sp + sp + sp + sp +    
                   'and draw your rectangle in the area of your prior selections.';

            makeAlert('No Stations Found', infomessage, 450, 500, 50);


            resetMapSelection();
            return;

         }//if nomarkers



                                        // If only some stations are missing lat/lngs,
                                        // tell user these will not display either on
                                        // the map or in the Select box and continue
                                        // on to show stations having lat/lngs on map.

         if ((number_missing_geo > 0) && show_missing_latlng_messages) 
            someStationsMissingLatLngs(number_missing_geo);
 
        


         if (markers.length < SHOW_ALL_MARKERS && map.getZoom() >= 6) {
            if (markers.length > 0) {
               showAllMarkers(markers);
            }
         }
         else {
            manageMarkers(markers);
         }


					// Put these stations that are now on the 
					// map into the stations drop-down selection 
					// box.
         populateStationsSelectBoxFromMap(markers);

         resetMapSelection();

         disableSelectBox('station_select');

         showAvailableDateRange();

      }//showStations()









      function showLoading() {

         document.getElementById('load_image').style.display = '';
         document.getElementById('load_image').src = document.getElementById('load_image').src;
         document.getElementById('wait_message').innerHTML = '&nbsp;&nbsp;&nbsp;&nbsp;Please wait...';
         resetColor('wait_message', '#FF0033');
         
      }//showLoading()




      function hideLoading() {

         document.getElementById('load_image').style.display = 'none';
         document.getElementById('wait_message').innerHTML = '&nbsp;';

      }//hideLoading()





      function showStationsLoading() {
         showLoading(); 
         window.setTimeout('showStations()',150);
      }






      function showOptionsLoading(button_id) {
         showLoading(); 
         window.setTimeout(function(){showOptions(button_id)},150);
      }





      function hideExcelHelp(id) {
         document.getElementById(id).innerHTML = "";
      }




      function showExcelHelp(id) {
         document.getElementById(id).innerHTML =
            "<A CLASS='aclass4' HREF='/AdvancedQueryTool' " +
            "   onclick=\"window.open('excel_help.html','excel_help','width=680,height=400,resizable=yes');return false;\">" +
                         "Trouble with opening Excel?" +
            "</A><BR>";
      }//showExcelHelp()










					// Clear current record count value
      function clearRecordCount() {
         document.getElementById('record_count').value = ' ';
      }


					// Input:   element id of DOM checkbox
					// Returns: true if checked, false  
					//          otherwise.
      function isChecked(id) {
         if (document.getElementById(id).checked) return true;
         return false;
      }




      
					// Action:  Return number of records
					//          that are available for 
					//          the user's current selections.
					//          This is done real time.
					// Returns: Number of records found.
      function getRecordCount() {

                                        // Get the value of the include_non_georefs checkbox.
         //var non_georef = 'no';
         //if (isChecked('include_non_georefs')) non_georef = 'yes';



                                        // Get the value of the non-QA data checkbox.
                                        // Since ben has no QA, we skip this check if
                                        // current category is benthic.

         var include_qa = 'no';
         if ((category != 'ben') && isChecked('include_qa')) include_qa = 'yes';


                                        // Get the value of the include composite data checkbox.
         var include_comp = 'no';
         if ((category == 'tis') && isChecked('include_comp')) include_comp = 'yes';


         var params = getParamString();

       //var req_string = '/show_record_count.php?&include_non_georefs=' + non_georef   +

         var req_string = '/show_record_count.php?&category='            + category     +
                                                 '&include_qa='          + include_qa   +
                                                 '&include_comp='        + include_comp +
                                                 '&' + getDateString();


         var request = GXmlHttp.create();
         request.open('POST', req_string, false);
         request.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=utf-8");
         request.send(params);
         var xml = request.responseXML;
         var count_array = xml.documentElement.getElementsByTagName('count');
         var record_count = count_array[0].getAttribute('record_count');

         return (record_count);

      }//getRecordCount()






      function updateRecordCountBox(record_count) {


         document.getElementById('record_count').size  = record_count.length;
         document.getElementById('record_count').value = record_count;

      }//updateRecordCountBox






					// Action:  Show number of records
					//          that are available for 
					//          the user's current selections.
					//          This is updated asynchronously
					//          using AJAX.
      function showRecordCount() {


					// Clear the record count box so that
					// the old count is gone while we wait 
					// for the asynch update of the new count.
					// Avoids confusion in case new count takes
					// too long to update or fails to update at all.
         clearRecordCount();

                                        // Get the value of the include_non_georefs checkbox.
         //var non_georef = 'no';
         //if (isChecked('include_non_georefs')) non_georef = 'yes';



                                        // Get the value of the non-QA data checkbox.
                                        // Since ben has no QA, we skip this check if 
                                        // current category is benthic.

         var include_qa = 'no';
         if ((category != 'ben') && isChecked('include_qa')) include_qa = 'yes';


                                        // Get the value of the include composite data checkbox.
         var include_comp = 'no';
         if ((category == 'tis') && isChecked('include_comp')) include_comp = 'yes';


         var params = getParamString();

       //var req_string = '/show_record_count.php?&include_non_georefs=' + non_georef   + 

         var req_string = '/show_record_count.php?&category='            + category     +
                                                 '&include_qa='          + include_qa   +
                                                 '&include_comp='        + include_comp +
                                                 '&' + getDateString();

         var request = GXmlHttp.create();
         request.onreadystatechange = function() {
            if (request.readyState == 4) {
               if (request.status != 200) {
                   //alert(request.status);
               } else {
                   var xml = request.responseXML;
                   //var responseText = xmlhttp.responseText;
                   //markers = eval(responseText);
                   if (!xml) {
                      alert('No data in showRecordCount.');
                   } else {
                       var count_array = xml.documentElement.getElementsByTagName('count');
                       var record_count = count_array[0].getAttribute('record_count');

                                        // Only change the drop-down box for download
                                        // format options if the user has left the 
                                        // row limit radio buttons on 'All Rows'.
                                        // This is because the download format 
					// options are being handled by the 
                                        // 'changeRowLimit' function in cases
                                        // where they changed it to something else.

                       if (document.getElementById('all_rows').checked) 
                          changeDownloadOptions(record_count);

                       updateRecordCountBox(record_count);

                   }//else xml

               }//else !200
            }//if schange
         }//func()

         request.open('POST', req_string, true);
         request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
         request.setRequestHeader("Content-length", params.length);
         request.setRequestHeader("Connection", "close"); 
         request.send(params);

      }//showRecordCount()





					// Return milliseconds since the Unix epoch.
      function getDateTime() {

        return (new Date().getTime());

      }//getDateTime()








					// Action:  Process user's request to 
					//          download data.  Data can be
					//          downloaded real-time or 
					//          asychronously, depending upon
					//          the size of the request.
					//          This function gathers the 
					//          parameters needed for making
					//          the data request, then sends 
					//          them to save_sql.php. That program
					//          will then synthesize the actual 
					//          sql needed for the request and 
					//          write the sql out to a temporary
					//          file.   That file will be used by
					//          retrieve_data.php if the request is
					//          small enough to be processed real-time,
					//          or by a cron-scheduled perl program 
					//          for larger, asychronous requests.
					//
					// Note:    Major specification change:
					//          Specs orig. called for main non-qa data and
					//          qa data to be appended to the same
					//          file.  However, now sample composite data
					//          has been added and users want it 
					//          downloaded real-time in a separate file.  
					//          This has caused a substantial re-write.
					//          See code below which handles the two 
					//          requests sequentially.


      function retrieveData() {
                                        // Get the value of the include_non_georefs checkbox.
         //var non_georef = 'no';
         //if (isChecked('include_non_georefs')) non_georef = 'yes';

					// Make sure we still have some records!
					// Probably due to date range that is too 
					// narrow if we have none at this point. 
         var record_count = getRecordCount();

					// Note we are not changing download 
					// options drop down box as we did above 
					// in showRecordCount().  This is because
					// they have already chosen a download 
					// format and if the record count changes
					// at all, it will be smaller since each
					// successive option either leaves the
					// selected set the same or narrows it.
         updateRecordCountBox(record_count);

         if (record_count <= 0) {
            if (isDateRangeSelected()) 
               makeAlert('No records for this date range', 
                         'Please check the date range.  It may be too narrow for these current selections.',
                          200, 500, 200);
            else
               makeAlert('No records found.', 
                         'There are no records found for these current selections.  Please try again ' +
                         'or contact us if you believe this message to be in error.',
                          200, 500, 200);
          
            return;
         }//if

         

                                        // Get the value of the non-QA data checkbox.
                                        // Since ben has no QA, we skip this check if
                                        // current category is benthic.
         var include_qa = 'no';
         if ((category != 'ben') && isChecked('include_qa')) include_qa = 'yes';


                                        // Get the value of the include composite 
					// data checkbox.
         var include_comp = 'no';
         if ((category == 'tis') && isChecked('include_comp')) include_comp = 'yes';



         
                                        // See if the first_rows_limit
					// records radio button is selected.
					// If so, set row limit to that choice.
         var first_rows_limit = '';
         if      (document.getElementById('first_rows_limit1').checked)  first_rows_limit = limit1; 
         else if (document.getElementById('first_rows_limit2').checked)  first_rows_limit = limit2; 

         

         var params = getParamString();
         var select_box = document.getElementById('download_format');
         var format = select_box.options[select_box.selectedIndex].value; 
         var record_count = document.getElementById('record_count').value;
         var file_name  = '';
         var req_string = '';
         var request;




					// Check to see if user is requesting 
					// too many records to process real-time.
         var asynch = false;
         if (!(first_rows_limit) && record_count > limit2) asynch = true;

         var random_number = Math.floor((Math.random()*100000000000)+1);



					// ------- Asychronous Data Retrieval -------
         if  (asynch) {
					
					// Create file name to store sql.
            var qa_name = '';
            var comp_name = '';
            if (include_qa == 'yes')   qa_name = 'qa';
            if (include_comp == 'yes') comp_name = 'comp';


            file_name = tmpdir_prefix + 'ceden_sql_asynch_' + qa_name + comp_name + '_' + random_number + '.tmp';


					// Save request sql in a file.

            //req_string = '/save_sql.php?&include_non_georefs=' + non_georef +
            req_string = '/save_sql.php?&category='         + category   +
                                       '&first_rows_limit=' + first_rows_limit +
                                       '&include_main='     + 'yes' +
                                       '&include_qa='       + include_qa +
                                       '&include_comp='     + include_comp +
                                       '&file_name='        + file_name  +
                                       '&' + getDateString();

            request = GXmlHttp.create();
            request.open('POST', req_string, false);
            request.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=utf-8");
            request.send(params);
            request.abort();


					// This program will get the user's 
					// email address and append it to 
					// to the request file.  It will then
					// store the file in the appropriate
					// location for asynch processing.

            openWindow('get_user_email.php?file_name=' + file_name,'get_email',400,800);



         }//if asynch 
         else {				// ------- Real-time Data Retrieval ---------


					// Save main data request sql in a file.

            file_name = tmpdir_prefix + 'ceden_sql_' + random_number;

            //req_string = '/save_sql.php?&include_non_georefs=' + non_georef +
            req_string = '/save_sql.php?&category='         + category   +
                                       '&first_rows_limit=' + first_rows_limit +
                                       '&include_main='     + 'yes' +
                                       '&include_qa='       + include_qa +
                                       '&file_name='        + file_name  +
                                       '&' + getDateString();
            request = GXmlHttp.create();
            request.open('POST', req_string, false);
            request.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=utf-8");
            request.send(params);
            request.abort();


					// Read and process the sql file to
					// retrieve non-qa and qa data for user.

            openWindow('retrieve_data.php?file_name='       + file_name    +
                                       '&category='         + category     +
                                       '&format='           + format,
                                       'retrieve_data',400,800);






					// Retrieve sample composite data for
                                        // user, but only if user has requested
                                        // retrieval of tissue sample composite.
            if (include_comp == 'yes') {

					// Save sample composite request sql in 
					// its own file.

               file_name = tmpdir_prefix + 'ceden_sql_samplecomp_' + random_number;

               //req_string = '/save_sql.php?&include_non_georefs=' + non_georef +
               req_string = '/save_sql.php?&category='         + category   +
                                          '&include_comp='     + include_comp +
                                          '&first_rows_limit=' + first_rows_limit +
                                          '&file_name='        + file_name  +
                                          '&' + getDateString();

               request = GXmlHttp.create();
               request.open('POST', req_string, false);
               request.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=utf-8");
               request.send(params);
               request.abort();



					// Read and process this sql file to
					// retrieve sample comp data for user.

               openWindow('retrieve_data.php?file_name='      + file_name    +
                                             '&category='     + category     +
                                             '&format='       + format       +
                                             '&include_comp=' + include_comp,
                                             'retrieve_data_comp',400,800);

            }//if comp


         }//else realtime

      }//retrieveData()











      function getBrowser() {

         var pattern_ms = /Microsoft/;
         var pattern_nn = /Netscape/;

         if (pattern_ms.test(navigator.appName)) {
 
            return ('microslop');

         }//if
         else if ( navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {

            return ('chrome');
         }
         else if (pattern_nn.test(navigator.appName)) {

            return ('firefox');

         }//else if
         else {
            return ('other');
         }

      }//getBrowser()





					// Initialize the map and
					// interface elements.
      function initialize(result_category) {

					// Presumably result_category 
					// will always have a value -- 
					// it should never be null.
         category = result_category;	// Set global variable: category

         document.getElementById(category).checked = true;

         if (!saved_paramgrps_row) {
            saveRows();
            //hideIntervals();
         }//if

         if (GBrowserIsCompatible()) {

            is_geo_null_array = {};	// Clear out global assoc 'array'

            browser = getBrowser();	// Initialize global brower var



					// Initialize map
            GUnload();
            map = new GMap2(document.getElementById("map_canvas"));
            map.setCenter(new GLatLng(36.4419, -120.1419), 6);
            map.setUIToDefault();
            map.enableDoubleClickZoom();
            setupDragSelect();

					// Reset rest of UI

					// Clear checkboxes
            //clearCheckBox('include_non_georefs');
            clearCheckBox('automap_stations_on');
            if (category == 'tis') clearCheckBox('include_comp');
            if (category != 'ben') clearCheckBox('include_qa');

            resetRadioButton('all_rows');
            resetDownloadFormat();
            resetAllSelectBoxes();
            processRegionTypeSelection('county_select');
            showText();
            disableAllSelectBoxes();
            replaceAllSelectButtons();
            showSearchStringBoxes();
            showAvailableDateRange();
            clearDates();
            changeRowLimit('all_rows');
            hideLoading();

         }//if compat
         else {
            alert("Sorry, the Google Maps API is not compatible with this browser");
         }

      }//initialize()






      function setupDragSelect() {

         var boxStyleOpts = {
            opacity: .2,
            border: "2px solid red"
         };

         var otherOpts = {
            buttonHTML: "<img id='draw_tool_button' src='/Images/draw_tool_icon3.png' alt='Drag a region on the map' title='Drag a region on the map' />",
            buttonSelectingHTML: "<img id='drawing_tool_button' src='/Images/draw_tool_icon4.png' alt='Click to Deselect' title='Click to Deselect'/>",
            buttonStartingStyle: {width: '24px', height: '24px'},
            overlayRemoveTime: 1000
         };

         dragselectcontrol =  new DragSelectControl(boxStyleOpts, otherOpts, {});
         map.addControl(dragselectcontrol, 
                        new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(19, 310)));


      }//setupDragSelect()








					// Action:  Show or hide county lines 
					//          on the map.  It is a toggle -
					//          if lines are currently shown 
					//          they will be hidden.  If not,
					//          they will be shown.
      function showHideCounties() {

         var button = document.getElementById('counties_button');

         if (map) {

            if (!countiesOverlay) {
               countiesOverlay = new GGeoXml("http://" + "ceden.waterboards.ca.gov" + "/Data/counties.kml");
               map.addOverlay(countiesOverlay);
               button.src = './Images/hidecounties_small.png';
            }
            else {
               if (countiesOverlay.isHidden()) {
                  countiesOverlay.show();
                  button.src = './Images/hidecounties_small.png';
               }
               else {
                  countiesOverlay.hide();
                  button.src = './Images/counties_small.png';
               }

            }//if counties


         }//if map

      }//showHideCounties()





                                        // Action:  Show or hide HUC lines
                                        //          on the map.  It is a toggle -
                                        //          if lines are currently shown
                                        //          they will be hidden.  If not,
                                        //          they will be shown.
      function showHideHUC() {

         var button = document.getElementById('huc_button');

         if (map) {

            if (!hucOverlay) {
               hucOverlay = new GGeoXml("http://" + "ceden.waterboards.ca.gov" +  "/Data/huc8a.kmz");
               map.addOverlay(hucOverlay);
               button.src = './Images/hide_huc8_small.png';
            }
            else {
               if (hucOverlay.isHidden()) {
                  hucOverlay.show();
                  button.src = './Images/hide_huc8_small.png';
               }
               else {
                  hucOverlay.hide();
                  button.src = './Images/huc8_small.png';
               }

            }//if huc

         }//if map

      }//showHideHUC()







					// Element ID's of 
					// date drop-down 
					// selection boxes.
      var date_selections = [];
      date_selections[0] = 'from_month';
      date_selections[1] = 'from_day';
      date_selections[2] = 'from_year';
      date_selections[3] = 'to_month';
      date_selections[4] = 'to_day';
      date_selections[5] = 'to_year';




					// Element ID's of 
					// drop-down selection
					// boxes (not including
					// date range) indexed by
					// IDs of the related href
					// [Select/Done] buttons.
					//
					// Careful with changing these,
					// since they determine what is
					// active on the page at any 
					// given time.
					// Note that matrix element is
					// shared with species, and 
					// analyte is shared with organisms,
					// and groups are either param grps
					// or organism groups.
      var select_buttons = {
         'region_button' :  'county_select',
         'program_button':  'program_select',
         'project_button':  'project_select',
         'group_button'  :  'group_select',
         'analyte_button':  'analyte_select',
         'station_button':  'station_select',
         'matrix_button' :  'matrix_select'
      };


					// These are just the names
					// of button elements.  All
					// must be represented here.
      var select_button_names = {
         'analyte_button'   :  'analytes[]',
         'group_button'     :  'groups[]',
         //'interval_button'  :  'intervals[]',
         'matrix_button'    :  'matrixes[]',
         'organism_button'  :  'organisms[]',
         'program_button'   :  'programs[]',
         'project_button'   :  'projects[]',
         'region_button'    :  'counties[]',
         'species_button'   :  'species[]',
         'station_button'   :  'stations[]'
      };

					// Source attributes for 
					// select button images
					// indexed by IDs of 
					// the related href
					// [Select/Done] buttons.
					// Include all buttons here.
      var select_buttons_src = {
         'analyte_button' :  './Images/select_parameters.png',
         'group_button'   :  './Images/select_parameter_groups.png',
         //'interval_button':  './Images/select_intervals.png',
         'matrix_button'  :  './Images/select_matrixes.png',
         'organism_button':  './Images/select_organisms.png',
         'program_button' :  './Images/select_programs.png',
         'project_button' :  './Images/select_projects.png',
         'region_button'  :  './Images/select_county.png',
         'species_button' :  './Images/select_species.png',
         'station_button' :  './Images/select_stations.png'
      };



					// Include all buttons here.
      var select_buttons_title = {

         'analyte_button' :  'Select Parameters',
         'group_button'   :  'Select Groups',
         //'interval_button':  'Select Interval',
         'matrix_button'  :  'Select Matrixes',
         'organism_button':  'Select Organisms',
         'program_button' :  'Select Programs',
         'project_button' :  'Select Projects',
         'region_button'  :  'Select Regions',
         'species_button' :  'Select Species',
         'station_button' :  'Select Stations'

      };





					// Values of the default 
					// options initially set in 
					// the selection drop-down  
					// boxes (except date range). 
					// Include all such items here.
      var select_tags_value = {
         'analyte_select'  : 'All Parameters',
         'county_select'   : 'All Counties',
         'group_select'    : 'All Groups',
         //'interval_select' : 'All Intervals',
         'huc8_select'     : 'All HUC8s',
         'huc10_select'    : 'All HUC10s',
         'huc12_select'    : 'All HUC12s',
         'matrix_select'   : 'All Matrixes',
         'organism_select' : 'All Organisms',
         'program_select'  : 'All Programs',
         'project_select'  : 'All Projects',
         'rb_select'       : 'All Regional Boards',
         'species_select'  : 'All Species',
         'station_select'  : 'All Stations',
         'wbt_select'      : 'All Waterbody Types'
      }








					// Text of the default 
					// options initially set in 
					// the selection drop-down  
					// boxes (except date range).
					// Include all such items here.
      var select_tags_text = {
         'analyte_select'  : 'Do not limit search by Parameters',
         'county_select'   : 'Do not limit search by Counties',
         'group_select'    : 'Do not limit search by Parameter Groups',
        // 'interval_select' : 'Do not limit search by Intervals',
         'huc8_select'     : 'Do not limit search by HUC8',
         'huc10_select'    : 'Do not limit search by HUC10',
         'huc12_select'    : 'Do not limit search by HUC12',
         'matrix_select'   : 'Do not limit search by Matrixes',
         'organism_select' : 'Do not limit search by Organisms',
         'program_select'  : 'Do not limit search by Programs',
         'project_select'  : 'Do not limit search by Projects',
         'rb_select'       : 'Do not limit search by Regional Boards',
         'species_select'  : 'Do not limit search by Species',
         'station_select'  : 'Do not limit search by Stations',
         'wbt_select'      : 'Do not limit search by Waterbody Type'
      }










					// Comes in as year-month-day:
					// min_date_array[0] is year
					// min_date_array[1] is month 
					// min_date_array[2] is day 
      var min_date_array = [];
      var max_date_array = [];




                                        // Action:  Checks to see if anything
                                        //          is chosen in the date selection
					//          boxes other than the default of 
					//          'All' dates.
					// Returns: true or false
      function isDateRangeSelected() {

          for (var i = 0; i < date_selections.length; i++) {
            if (!isDefaultSelected(date_selections[i]))  return true;
          }

          return false;

      }//isDateRangeSelected()





                                        // Action:  Return boolean true if any drop-down
                                        //          besides the one passed in is selected,
                                        //          or if date range is selected,
                                        //          otherwise return false.

      function isAnyOtherParamSelected(button_id) {

         var button;

         for (button in select_buttons) {
            if ((button != button_id) && isSomethingSelected(select_buttons[button])) {
               return true;
            }

         }//for

         if (!isDateSelection(button_id)) {
            if (isDateRangeSelected()) return true;
         }

         return false;

      }//isAnyOtherParamSelected()







					// Action:  - Remove all [Select] buttons
					//            from view by replacing with 
					//            transparent image.
					//            
      function hideSelectButtons() {
         var button;

         for (button in select_buttons) {
            document.getElementById(button).src = './Images/transparent_spacer2.gif';
         }

      }//hideSelectButtons()










     function testKeyPress(e, search_id) {

        //var search_string = document.getElementById(search_id).value;
        //if (!search_string) return false;


        // look for window.event in case event isn't passed in
        if (typeof e == 'undefined' && window.event) { e = window.event; }

        if (e.keyCode == 13) {
            e.preventDefault();
            e.stopPropagation();
            showOptionsLoading(getButtonId(search_id));
            return false;
        }

     }//testKeyPress()




					// Action:  Checks user input in the
					//          search string box to see
					//          if nothing was entered, 
					//          in which case it resets 
					//          box to default value.

      function checkMissingSearchValue(user_input_value, search_id) {

         if (!user_input_value) {
            resetSearchStringBox(search_id);
         }//if

      }//checkMissingSearchValue()





					// Action:  Checks user input in the
					//          given search string box for
					//          security purposes (also
					//          being checked on backend).
					//          Also checks to see if nothing
					//          was entered, in which case 
					//          resets to default value.

      function isBadSearchValue(select_id) {

         var user_input_value = getSearchString(select_id);


					// Nothing entered is ok.
         if (!user_input_value) {
            return false;
         }//if
 
         var search_id = getSearchStringId(select_id);

         if (user_input_value.length > 200) {
            alert ("Please limit your search string to 200 characters or less.");
            resetSearchStringBox(search_id);
            return true;
         }

         var pattern = /^(?=.*[A-Z0-9])[\w.,"'\(\)~@\-_& ]+$/i;

         if (!pattern.test(user_input_value)) {
            alert ("Please only use alphanumeric characters and punctuation in your search string.");
            resetSearchStringBox(search_id);
            return true;
         }
       
         return false;

      }//isBadSearchValue()





					// Action:  Takes name and splits
					//          into parts based on '_'
					//          separator.  Appends 
					//          '_select' to first part 
					//          of input string and 
					//          returns it.

      function getButtonId(search_id) {

         var name_array = search_id.split('_');

         return (name_array[0] + '_button');
      }





					// Action:  Takes name and splits
					//          into parts based on '_'
					//          separator.  Appends 
					//          '_search' to first part 
					//          of input string and 
					//          returns it.

      function getSearchStringId(name) {

         var name_array = name.split('_');

         var pattern = /county|rb|wbt|huc8|huc10|huc12/i;

         if (name_array[0].match(pattern)) name_array[0] = 'region';

         return (name_array[0] + '_search');
      }






					// Action:  - Remove all search string 
					//            input boxes from view, as well 
					//            as the label that accompanies them.
					//            
      function hideSearchStringBoxes() {

         var button;

         for (button in select_buttons) {

            var search_id = getSearchStringId(button);
            var element   = document.getElementById(search_id);

            if (element !== null ) {
               element.style.display = 'none';
            }

         }//for

					// Hide search label
         document.getElementById('search_string_label').style.display = 'none';

      }//hideSearchStringBoxes()


					// Action:  - Show all search string 
					//            input boxes for current set
					//            of selections, as well 
					//            as the label that accompanies 
					//            the search boxes.
					//            
      function showSearchStringBoxes() {

         var button;

         for (button in select_buttons) {


            var search_id = getSearchStringId(button);

					// We really don't need a search box
					// for intervals.
            if (search_id == 'interval_search') continue;

            var element   = document.getElementById(button);

        
					// Not all buttons are visible for a 
					// given result category.

            if ((element !== null) && (document.getElementById(button).style.display != 'none'))
               document.getElementById(search_id).style.display = 'block';

         }//for

					// Show search label
         document.getElementById('search_string_label').style.display = 'block';

         resetSearchStringBoxes();

      }//showSearchStringBoxes()






					// Action:  - Reset given search string 
					//            input box value.
					//            
      function resetSearchStringBox(search_id) {

            var temp_search_id = search_id;
            var search_box_value = '';

            if (search_id == 'analyte_search')      temp_search_id = 'parameter_search'; 
            else if (search_id == 'region_search')  temp_search_id = getSearchStringId(select_buttons['region_button']);

            search_box_value = temp_search_id.replace('_',' ');

            document.getElementById(search_id).value = search_box_value;

      }//resetSearchStringBox()





					// Action:  - Reset all search string 
					//            input box values.
					//            
      function resetSearchStringBoxes() {

         var button;

         for (button in select_buttons) {

            var search_id = getSearchStringId(button);

            var element   = document.getElementById(search_id);

            if (element !== null ) {
               resetSearchStringBox(search_id);
            }

         }//for


      }//resetSearchStringBoxes()









					// Action:  For each selected item in
					//          the given select box, add the 
					//          option value to an array of
					//          parameter strings.
					// Input:   select_id - This is the 
					//          selection box from which we 
					//          get our items.
					// Returns: options - Array of name=value
					//          pairs for all selected items in 
					//          given select box.
      function getSelectedParameters(select_id) {

         var selected_array = [];
         var select_box     = document.getElementById(select_id);
         var param_name     = select_box.getAttribute('name');


         for (var i = 0; i < select_box.options.length; i++)  {

            if (select_box.options[i].selected) {
               selected_array.push(param_name + '=' + select_box.options[i].value);
            }

         }//for

         return selected_array;

      }//getSelectedParameters()




					//Action:  For all select boxes in form, 
					//         fill an array with all selected 
					//         items found in each, as name=value pairs.
					//         Then join array with ampersand as 
					//         separator.
					//Input:   n/a
					//Returns: string containing ampersand-separated
					//         list of name=value pairs for all 
					//         selected items in all select boxes.

      function getParamString() {

         var param_array     = [];
         var select_form     = document.getElementById("selection_form");

					// We are going to find FORM select 
					// boxes by using this pattern match.
					// We are matching against the 'type'
					// of element, as defined by the DOM.
         var pattern = /^select-/;

         var has_group_select = false;

					// This loops through all elements of form,
					// looking for multiple selection boxes.
         for (var i=0; i < select_form.length; i++) {
            if (pattern.test(select_form.elements[i].type)) {

					// Skip over unrelated elements for benthic:
               if (category == 'ben' || category == 'hab')
                  if ((select_form.elements[i].getAttribute('id') == 'species_select') ||
                      (select_form.elements[i].getAttribute('id') == 'matrix_select' )) continue;

					// Is group selection currently active on page?
               if (select_form.elements[i].getAttribute('id') == 'group_select') has_group_select = true;


					// This passes the id value of the selection 
					// box (e.g. 'analyte_select') to getSelectedParameters(),
					// which returns an array of name=value pairs.
               param_array = param_array.concat(getSelectedParameters(select_form.elements[i].getAttribute('id')));

            }//if


         }//for

         if ((category != 'hab') && (!has_group_select)) 
            param_array = param_array.concat(getSelectedParameters('group_select'));

         return (param_array.join('&'));

      }//getParamString()





					// Action:  Create string with dates 
					//          selected by user to be 
					//          appended to the get request
					//          string.
					// Returns: Ampersand-delimited date
					//          string. 
      function getDateString() {

         var dates  = '';

         dates =          'from_month=' + document.getElementById('from_month').value;
         dates = dates + '&from_day='   + document.getElementById('from_day').value;
         dates = dates + '&from_year='  + document.getElementById('from_year').value;

         dates = dates + '&to_month=' + document.getElementById('to_month').value;
         dates = dates + '&to_day='   + document.getElementById('to_day').value;
         dates = dates + '&to_year='  + document.getElementById('to_year').value;

         return (dates);

      }//getDateString()






					// Action:  Generate request to database
                                        //          to get min and max sample dates 
                                        //          for the current user selections.
                                        //          Current selections from analytes, 
                                        //          stations, etc. are included, but  
                                        //          current selections of dates are   
                                        //          not needed since they are what is 
                                        //          being updated.
                                        // Returns: date_range - Array of xml elements
      function getDateRange() {

         var params = getParamString();


					// Get the value of the include_non_georefs checkbox.
         //var non_georefs = 'no';
         //if (isChecked('include_non_georefs')) non_georefs = 'yes';

         //var req_string = '/get_date_range.php?&category=' + category + '&include_non_georefs=' + non_georefs;
         var req_string = '/get_date_range.php?&category=' + category; 

         var request = GXmlHttp.create();
         request.open('POST', req_string, false);
         request.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=utf-8");
         request.send(params);
         var xml = request.responseXML;
         var date_range = xml.documentElement.getElementsByTagName('date');

         return date_range;

      }//getDateRange()




					//Action:  For given selection's search string box,
					//         test to see if value is default
					//         message.  Return true if it is,
					//         false otherwise.
      function isDefaultSearchStringValue(select_id) {

         var search_id     = getSearchStringId(select_id);
         var current_value = document.getElementById(search_id).value;


         if (search_id == 'analyte_search')      search_id = 'parameter_search'; 
         else if (search_id == 'region_search')  search_id = getSearchStringId(select_buttons['region_button']);

         var default_value = search_id.replace('_',' ');

         if (current_value == default_value) return true;

         return false;

      }//isDefaultSearchStringValue()



					//Action:  For given selection,
					//         return search string
					//         in the related search text
					//         box, if any.
      function getSearchString(select_id) {

         var search_id     = getSearchStringId(select_id);


					// Some select items do not have
					// a search function.
         var element = document.getElementById(search_id);

         if (element === null ) {
            return '';
         }

         if (isDefaultSearchStringValue(select_id)) return '';



         return element.value;

      }//getSearchString()




					//Action:  For all selection boxes,
					//         create a param_array of 
					//         selected items.
					//         For each element in the 
					//         param_array, create  
					//         a string of parameters 
					//         separated by ampersands
					//         to append to request string
					//         that is sent to get_options 
					//         program.  The result of the 
					//         request is an array of options.
					//         Also append additional data
					//         as GET parameters.
					//Input:   select_id - This is the 
					//         selection box we want to 
					//         populate.
					//Returns: options - Array of xml elements
      function getOptions(select_id) {

					// Operates on all relevant 
					// selection boxes.
         var params = getParamString();

         var search_string = getSearchString(select_id);

         search_string = escape(search_string);

         var req_string = '/get_options.php?selected=' + select_id     + 
                          '&category='                 + category      + 
                          '&search_string='            + search_string + 
                          '&' + getDateString();

         var request = GXmlHttp.create();
         request.open('POST', req_string, false);
         request.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=utf-8");
         request.send(params);
         var xml = request.responseXML;
         var options = xml.documentElement.getElementsByTagName('option'); 

         return options;

      }//getOptions()






					//Action:  For each element in the 
					//         options_list array, create  
					//         a selection box option with
					//         text and value to push onto 
					//         options_array. 
					//Input:   select_id - This is the 
					//         selection box we want to 
					//         populate.
					//         Gets options from call to 
					//         getOptions() which returns 
					//         an xml array.
					//Returns: Associative array:
					//            Array of DOM option elements
					//            (i.e., options that are part
					//            of a selection dropdown box)
					//            comprised of name/key pairs
					//
					// Sets:   Global array of key/boolean pairs  
					//            that tells if stations are  
					//            missing lat/lngs or not.
					//            Note that this second array
					//            only applies when stations box 
					//            was selected.  Otherwise, 
					//            this item will be null.

      function getOptionsArray(select_id) {

         var options_array = [];
         var new_option;

         var options_list  = getOptions(select_id);

         is_geo_null_array = {};	// Clear out global associative 'array'


					// options_list is an array of
					// xml elements containing name/key
					// data in each element.  If no 
					// options are selected, we use the 
					// default tags from the select_tags
					// associative arrays defined above 
					// to fill the drop-down box instead.
         if (!options_list[0]) {
            new_option = document.createElement('option');
            new_option.text  = select_tags_text[select_id];
            new_option.value = select_tags_value[select_id];
            options_array.push(new_option);
         }
         else {
					// Since options were selected, these
					// values are being retrieved from the
					// database.

            var options_length = options_list.length;

            for (var i=0; i < options_length; i++) {

               new_option = document.createElement('option');
               
					// html_entity_decode() -
					// The elements coming from the database
					// do have problematic characters which were
					// encoded in the server-side code, so the client
					// code (this program) must decode them back again
					// so that they show as regular characters.

               new_option.text  = html_entity_decode(options_list[i].getAttribute('name'));
               new_option.value = options_list[i].getAttribute('key');
               options_array.push(new_option);

					// Set GLOBAL associative 'array'
               if (select_id == 'station_select') {
                  is_geo_null_array[new_option.value] = options_list[i].getAttribute('is_geo_null');
               }//if
               

            }//for
         }//else


         return options_array;

      }//getOptionsArray()







					// Action: Changes size of given select box
					//         to be maximum of 10 and equal to
					//         the number of items if less than
					//         or equal to 10.

      function fixSelectBoxSize(select_id) {

         var select_box    = document.getElementById(select_id);

					// Size is how many items show in a multiple
					// select box (i.e., the size of the window).  
					// Length is a property of the select box
					// telling how many list items total are 
					// contained within it at the given moment.


         //if (select_box.length > 1)   select_box.multiple = true;
         //else                         select_box.multiple = false;


					// Set number of visible items in box to 
					// reasonable amount.

         if (select_box.length <= 10) select_box.size = select_box.length;
         else                         select_box.size = 10;

					// Necessary if using Chrome since 
					// Chrome has a bug that only allows 
					// select box size 4 for select multiple 
					// boxes.
         if (browser == 'chrome') {

            var show_size  = 17 * select_box.size;

            select_box.style.height = show_size + 'px';

         }//if chrome

      }//fixSelectBoxSize








					// Action:  For each element in the 
					//          options array, dynamically 
					//          add a new option.
					//
					// Input:   select_id - this is the 
					//             selection box we want to 
					//             populate.
					//          options_array - array of 
					//             elements comprised of 
					//             key/value pairs.
					// Global:  is_geo_null_array - array of
					//             key/boolean pairs where key
					//             matches key in options_array
					//             above.  The station referred 
					//             to by the 'key' will have    
					//             matching boolean values to
					//             tell whether the station has
					//             null lat/lngs or not.
					//             This array is null unless
					//             the selection box chosen 
					//             was 'stations'.
					//             Any station without lat/lng
					//             will be set to display in red.
					// Returns: n/a

      function populateSelectBox(select_id, options_array) {

         var select_box    = document.getElementById(select_id);

         select_box.length = 0;


         try {

            for (var i=0; i < options_array.length; i++) {

               if (select_id == 'interval_select') 
                  options_array[i].text = options_array[i].value + ' ' + options_array[i].text;

					// Add option to drop-down box
               select_box.add(options_array[i], select_box.options[null]);

					// If stations selected, color station
					// name red in drop-down if it is missing
					// latitude or longitude.

               if ((select_id == 'station_select') && (is_geo_null_array[options_array[i].value] == true)) {
                  select_box.options[i].style.color = "red";
               }//if

            }//for

         }//try				// Yet more workaround code for IE
         catch (ex) {

            for (var i=0; i < options_array.length; i++) {

               if (select_id == 'interval_select') 
                  options_array[i].text = options_array[i].value + ' ' + options_array[i].text;

					// Add option to drop-down box
               select_box.add(options_array[i], null); 

					// If stations selected, color station
					// name red in drop-down if it is missing
					// latitude or longitude.

               if ((select_id == 'station_select') && (is_geo_null_array[options_array[i].value] == true)) {
                  select_box.options[i].style.color = "red";
               }//if

            }//for

         }//catch

         //if (select_box.length == 1)  select_box.options[0].selected = true;


      }//populateSelectBox()







                                        // Action:  Select all currently
                                        //          available options
                                        //          in the given selection
                                        //          drop-down box.
                                        // Input:   ID of selection box.

      function selectAllOptions(select_id) {

         var select_box = document.getElementById(select_id);

         for (var i = 0; i < select_box.options.length; i++)  {

            select_box.options[i].selected = true;

         }//for

      }//selectAllOptions()







                                        // Action:  Clear select box and 
                                        //          reset default option.
                                        // Input:   ID of selection box.

      function resetSelectBox(select_id) {

         var select_box = document.getElementById(select_id);

         select_box.length = 0;

         try {
            select_box.add(new Option(select_tags_text[select_id], select_tags_value[select_id]), select_box.options[0]);
         }
         catch (ex) {			// More workaround code for IE
            select_box.add(new Option(select_tags_text[select_id], select_tags_value[select_id]), 0);
         }


         fixSelectBoxSize(select_id);


      }//resetSelectBox()








                                        // Action:  Fills station selection
                                        //          drop-down box with stations
                                        //          that were selected by the
                                        //          user on the map.
                                        // Input:   Array of xml elements
                                        //          containing station information.

      function populateStationsSelectBoxFromMap(markers) {

         var options_array = [];
         var new_option;
         var m_length = markers.length;


         if (m_length == 0) {
            resetSelectBox('station_select');
            return;
         }

         for (var i = 0; i < m_length; i++) {
            if (markers[i].getAttribute("lat")) {
               new_option = document.createElement('option');
               new_option.text  = html_entity_decode(markers[i].getAttribute("name"));
               new_option.value = markers[i].getAttribute("key");
               new_option.selected = true;
               options_array.push(new_option);
            }
         }//for


         populateSelectBox('station_select', options_array);
         fixSelectBoxSize('station_select');

					// It is only necessary to sort 
					// stations when we are populating
					// the stations select box from
					// the map, as we are doing in this 
					// function call.  This is because the
					// mapping process sorts by lat/lng
					// (for grouping purposes), not by 
					// station name.
         sortOptions('station_select'); 

      }//populateStationsSelectBoxFromMap()






                                        //Action:  Show only the items selected
                                        //         in the given select box.
                                        //Input:   select_id - this is the
                                        //         selection box we want to
                                        //         change.
                                        //Returns: n/a

      function showSelectedItemsOnly(select_id) {

         var select_box = document.getElementById(select_id);

         for (var i=0; i < select_box.length; i++) {

            if (!select_box.options[i].selected) {
               select_box.remove(i); 
               i--; 
            }

         }//for

         fixSelectBoxSize(select_id);

      }//showSelectedItemsOnly()







      function removeFirstOption(select_id) {

         var select_box = document.getElementById(select_id);

         select_box.remove(0); 
    

      }//removeFirstOption()






                                        // Action: Change button image
                                        //         back to active and
                                        //         turn on click event
                                        //         for given button.
                                        //         Also update tool tips
                                        //         and the help message
                                        //         above Map Stations button.
                                        //
                                        // Input:  id of button

      function changeMapStationsButtonMessages(state) {

         var stations_button = document.getElementById('stations_button');
         var help_message    = document.getElementById('map_stations_button_message');

         switch (state) {
            case 'disabled':  
               stations_button.title  = "Disabled during map selection process";
               help_message.innerHTML = "&nbsp;The <B>Map Stations</B> button is disabled during map selection process.";
               break;

            case 'click_button':
               stations_button.title  = "Click to show stations on the map";
               help_message.innerHTML = "<FONT COLOR='#FF0033'>&nbsp;Click <B>Map Stations</B> after drawing selection box on the map.</FONT>";
               break;

            default:
               stations_button.title  = "Click to show stations on the map";
               help_message.innerHTML = "&nbsp;Click <B>Map Stations</B> at any time to show stations on the map";

         }//switch

      }//changeMapStationsButtonMsg()





                                        // Action: Change button image
                                        //         back to active and 
                                        //         turn on click event
                                        //         for given button.
					//         Also update tool tips 
					//         and the help message
					//         above Map Stations button.
					//
                                        // Input:  id of button

      function enableMapStationsButton(button_id, new_image) {

         changeImage(new_image, button_id);
         if (new_image == 'map_stations_click.png') changeMapStationsButtonMessages('click_button');
         else                                         changeMapStationsButtonMessages('enabled');
         document.getElementById(button_id).onclick = function() { 
            showStationsLoading();
            return false;
         }

      }//enableMapStationsButton()



                                        // Action: Turn off click event
                                        //         for given button and
                                        //         change button image
					//         to disabled (grey).  
					//         Also update tool tips 
					//         and the help message
					//         above Map Stations button.
					//
                                        // Input:  id of button

      function disableMapStationsButton(button_id, new_image) {

         changeImage(new_image, button_id);
         changeMapStationsButtonMessages('disabled');
         document.getElementById(button_id).onclick = null;

      }//disableMapStationsButton()





                                        // Action: Disable all 
                                        //         selection boxes 
      function disableAllSelectBoxes() {

         var button;

         for (button in select_buttons) {
            disableSelectBox(select_buttons[button]);
         }

      }//disableAllSelectBoxes()





					// Action: Add [Select] buttons
					//         to all drop-down 
					//         selection boxes
      function replaceAllSelectButtons() {

         var button;

         for (button in select_buttons) {
            document.getElementById(button).src   = select_buttons_src[button];
            document.getElementById(button).title = select_buttons_title[button];;
            document.getElementById(button).alt   = select_buttons_title[button];;
         }

      }//replaceAllSelectButtons()





                                        // Action: Set all drop-down
                                        //         selection boxes 
                                        //         to initial state
                                        //         (excluding date selections).
      function resetAllSelectBoxes() {

         var button;

         for (button in select_buttons) {
            resetSelectBox(select_buttons[button]); 
         }


         var regional_type_selectbox = document.getElementById('region_type_select'); 
         regional_type_selectbox.options.selectedIndex = 0;

      }//resetAllSelectBoxes()






					// Action:  Return true if 
					//          the given element id 
					//          belongs to one of
					//          the date selection 
					//          drop-down boxes.
                                        //          Else return false.
					// Input:   id of select box to test.

      function isDateSelection(select_id) {

         var pattern = /to_|from_/;

         if (pattern.test(select_id)) return true;

         return false;

      }//



					// Action:  Return true if the default
					//          setting of 'All' items or, 
					//          if date range, then 
					//          'none' has been selected.
					//
					// Input:   id of selection box to test.

      function isDefaultSelected(select_id) {


         var pattern = /All/i;
         var select_box = document.getElementById(select_id);
         var index      = select_box.selectedIndex;

         if (index < 0)  return false;  // Nothing selected at all.

         if (pattern.test(select_box.options[index].value) && select_box.options[index].selected) return true; 

         return false;
    

      }//isDefaultSelected()









      function getNumberSelected(select_id) {

         var number_selected = 0;
         var select_box = document.getElementById(select_id);

         for (var i = 0; i < select_box.options.length; i++)  {

            if (select_box.options[i].selected) number_selected++;
         }

         return number_selected;

      }//getNumberSelected()






                                        // Action:  Return boolean (true or false)
                                        //          to indicate whether everything
                                        //          was selected in the given select
                                        //          box besides the default option of
                                        //          'All'.
                                        // Returns: boolean

      function isEverythingSelected(select_id) {

         var select_box = document.getElementById(select_id);

         if (isDefaultSelected(select_id)) return false;

         for (var i = 0; i < select_box.options.length; i++)  {
            if (!select_box.options[i].selected)  return false;
         }

         return true;

      }//isEverythingSelected()






					// Action:  Return boolean (true or false) 
					//          to indicate whether something 
					//          was selected in the given select
					//          box besides the default option of
					//          'All'.
					// Returns: boolean

      function isSomethingSelected(select_id) {

         var select_box = document.getElementById(select_id);

         if (select_box === null) return false;

         for (var i = 0; i < select_box.options.length; i++)  {
            if (select_box.options[i].selected && !isDefaultSelected(select_id))  return true;
         }

         return false;

      }//isSomethingSelected()








      function clearCheckBox(id) {

         document.getElementById(id).checked = false;

      }//clearCheckBox()







      function resetDownloadFormat() {

         document.getElementById('download_format')[0].selected = true;

      }//resetDownloadFormat()





      function resetRadioButton(id) {

         document.getElementById(id).checked = true;

      }//resetRadioButton()




      function showRowLimitMessage() {

         document.getElementById('row_limit_message').innerHTML = "Note:&nbsp;  " +
                       "If number of records exceeds " + limit2 + 
                       " the data will be zipped and emailed to you.";

      }//showRowLimitMessage()




      function hideRowLimitMessage() {

         document.getElementById('row_limit_message').innerHTML = "&nbsp;"

      }//hideRowLimitMessage()






					// Action:  Process user's download 
					//          row limit changes (radio
					//          buttons in Data Retrieval 
					//          section).
      function changeRowLimit(id) {

         var count = document.getElementById('record_count').value;

         switch (id) {
            case 'all_rows':
                 if (count > limit2) { 
                    showRowLimitMessage();
                 }
                 changeDownloadOptions(count);
                 break;

            case 'first_rows_limit1':
                 hideRowLimitMessage();
                 if (count > limit1) changeDownloadOptions(limit1);
                 else                changeDownloadOptions(count);
                 break;

            case 'first_rows_limit2':
                 hideRowLimitMessage();
                 if (count > limit2) changeDownloadOptions(limit2);
                 else                changeDownloadOptions(count);
                 break;

         }//switch

         resetRadioButton(id);

      }//changeRowLimit()





					// Action:  Set the options in the
					//          Download Options drop-down
					//          selection box based on number
					//          of records and on whether 
					//          row limits were set by user.

      function changeDownloadOptions(record_count) {

         if (record_count == ' ') return;

         if (record_count > limit2) {
            document.getElementById('download_format').length = '0';  
            document.getElementById('download_format').options[0]=new Option('text','text', false, false);

            hideExcelHelp('excel_help');
         }
         else if (record_count <= limit1) {
            document.getElementById('download_format').length = '0';  
            document.getElementById('download_format').options[0]=new Option('excel','excel', false, false);
            document.getElementById('download_format').options[1]=new Option('html','html', false, false);
            document.getElementById('download_format').options[2]=new Option('text','text', false, false);

            showExcelHelp('excel_help');
         }
         else if (record_count > limit1) {
            document.getElementById('download_format').length = '0';  
            document.getElementById('download_format').options[0]=new Option('excel','excel', false, false);
            document.getElementById('download_format').options[1]=new Option('text','text', false, false);

            showExcelHelp('excel_help');
         }

      }//changeDownloadOptions()








					// Action:  Reset date range selections
					//          to default.  (Clear them out.)
      function resetDateRangeSelectionBoxes() {

          for (var i = 0; i < date_selections.length; i++) {
            document.getElementById(date_selections[i]).options[0].selected = true;
          }

      }//resetDateRangeSelectionBoxes()





                                        // Action:  Clear user date range selection
                                        //          by reinitializing boxes and
                                        //          clearing error indicator from
                                        //          Available Date Range label.
      function clearDates() {

         resetColor('available_dates', 'white');
         initializeDateRangeSelectionBoxes();

      }//clearDates()




                                        // Action:  Return true if this is a case
                                        //          where we should skip updates
					//          to the given selection box,
					//          false otherwise.
      function skipSelectionUpdate(select_id) {
                                        // If this is the stations select box:

         if (select_id == 'station_select') {


					// If there are no stations inside
					// the stations select box (it is 
					// empty when only the init statement
					// is found there), we definitely need 
					// to proceed to populate the drop-down 
					// with stations.

            var pattern = /^Do not limit search/;
            var select_box = document.getElementById('station_select');
            if (pattern.test(select_box[0].text)) return false;



                                        //    But if there are station markers on
                                        //    the map and NOTHING else besides 
					//    stations is selected in drop-down 
					//    boxes, don't repopulate the box.  
                                        //    Leave current station selections alone, 
                                        //    because they represent stations the 
                                        //    user has already chosen on the map.

            if ((markers.length != 0) &&
                (!isAnyOtherParamSelected('station_button'))) {
               return true;

            }//if

         }//if stations

         return false;

      }//skipSelectionUpdate()



                                        // Action:  Process user's 
                                        //          Region Type selection.
                                        //          This includes setting 
                                        //          region button graphics,
                                        //          element id, selection array
					//          values, etc.

      function processRegionTypeSelection(selected_type) {
 
					// Get elements to change via currently selected type:
         var original_selected_id  = select_buttons['region_button']; 
         var selected_element      = document.getElementById(original_selected_id);

         var select_array_name     = '';
         var selected_region       = '';
         var selected_button_image = '';
         var selected_tag_text     = '';


         switch (selected_type) {

            case 'county_select':
               select_array_name     = 'counties[]';      
               selected_region       = 'Counties';
               selected_button_image = './Images/select_county.png';
               selected_tag_text     = 'County';
               break;

            case 'rb_select':
               select_array_name     = 'rbs[]';      
               selected_region       = 'Regional Boards';
               selected_button_image = './Images/select_rb.png';
               selected_tag_text     = 'RB';
               break;

            case 'wbt_select':
               select_array_name     = 'wbts[]';      
               selected_region       = 'Waterbody Types';
               selected_button_image = './Images/select_wbt.png';
               selected_tag_text     = 'Waterbody Type';
               break;

            case 'huc8_select':
               select_array_name     = 'huc8s[]';      
               selected_region       = 'HUC8';
               selected_button_image = './Images/select_huc8.png';
               selected_tag_text     = 'HUC8';
               break;

            case 'huc10_select':
               select_array_name     = 'huc10s[]';      
               selected_region       = 'HUC10';
               selected_button_image = './Images/select_huc10.png';
               selected_tag_text     = 'HUC10';
               break;

            case 'huc12_select':
               select_array_name     = 'huc12s[]';      
               selected_region       = 'HUC12';
               selected_button_image = './Images/select_huc12.png';
               selected_tag_text     = 'HUC12';
               break;

            default:
               alert('Unknown region type selection.  Please report error to CEDEN development team.');
               return;


          }//switch


 
					// Set element id to new selection.
          selected_element.id   = selected_type;


                                        // Change reference to the correct region 
                                        // in the select_buttons associative array.

          select_buttons['region_button']             = selected_type;
          select_buttons_src['region_button']         = selected_button_image;
          document.getElementById(selected_type).name = select_array_name;


          document.getElementById('region_button').title    = 'Select ' + selected_region;
          document.getElementById('region_button').alt      = 'Select ' + selected_region;
          document.getElementById('region_button').src      =  selected_button_image;


          var top_layer = document.getElementById(original_selected_id + '_top_layer');
          top_layer.id = selected_type + '_top_layer';

					// We reset stations anytime region type is changed.
          //resetSelectBox('station_select');
          //clearMap();

          resetSelectBox(selected_type);
          resetSearchStringBox('region_search');

      }//processRegionTypeSelection()



					// Action:  - Hide page text such as 
					//            Help for Missing Georefs
					//            link, etc.
      function hideText() {

         document.getElementById('href_missinggeo_text').innerHTML =  '';
         document.getElementById('rt_select_text').innerHTML       =  '';

      }//hideText()


					// Action:  - Show page links
      function showText() {

         document.getElementById('href_missinggeo_text').innerHTML =  'Missing&nbsp;Georeferences&nbsp;Info';
         document.getElementById('rt_select_text').innerHTML       =  'Region&nbsp;Type&nbsp;Selection:';

      }//showText()







					// Action:  Populate date range
					//          selection boxes with 
					//          dates using the available
					//          date range for the current
					//          selections.  (Only uses
					//          available date range to set 
					//          year -- months and days are 
					//          always the same for any year.)
      function initializeDateRangeSelectionBoxes() {

         var from_year = Number(min_date_array[0]);
         var to_year   = Number(max_date_array[0]);
         var number_years = (to_year - from_year) + 1;



					// From Year
         var options_array  = [];
         var new_option = document.createElement('option');
         new_option.text  = ' ';
         new_option.value = 'All';
         options_array.push(new_option);

         for (var i=0; i < number_years; i++) {

            new_option  = document.createElement('option');
            new_option.text   = from_year + i;
            new_option.value  = from_year + i;
            options_array.push(new_option);

         }//for

         populateSelectBox('from_year', options_array);




					// To Year
         options_array.length = 0;
         new_option = document.createElement('option');
         new_option.text  = ' ';
         new_option.value = 'All';
         options_array.push(new_option);

         for (var i=0; i < number_years; i++) {
            new_option  = document.createElement('option');
            new_option.text   = from_year + i;
            new_option.value  = from_year + i;
            options_array.push(new_option);

         }//for

         populateSelectBox('to_year', options_array);



					// From Month 
         options_array.length = 0;
         new_option = document.createElement('option');
         new_option.text  = ' ';
         new_option.value = 'All';
         options_array.push(new_option);

         for (var month_index in months) {

            new_option  = document.createElement('option');
            new_option.text   = months[month_index];
            new_option.value  = month_index;
            options_array.push(new_option);

         }//for

         populateSelectBox('from_month', options_array);


					// To Month 
         options_array.length = 0;
         new_option = document.createElement('option');
         new_option.text  = ' ';
         new_option.value = 'All';
         options_array.push(new_option);

         for (var month_index in months) {

            new_option  = document.createElement('option');
            new_option.text   = months[month_index];
            new_option.value  = month_index;
            options_array.push(new_option);

         }//for

         populateSelectBox('to_month', options_array);

 


                                        // From Day
         options_array.length = 0;
         new_option = document.createElement('option');
         new_option.text  = ' ';
         new_option.value = 'All';
         options_array.push(new_option);

         for (var i=1; i<=31; i++) {

            new_option  = document.createElement('option');

            if (i < 10) i = '0' + i;
            new_option.text   =  i;
            new_option.value  =  i;
            options_array.push(new_option);

         }//for

         populateSelectBox('from_day', options_array);



                                        // To Day
         options_array.length = 0;
         new_option = document.createElement('option');
         new_option.text  = ' ';
         new_option.value = 'All';
         options_array.push(new_option);

         for (var i=1; i<=31; i++) {

            new_option  = document.createElement('option');

            if (i < 10) i = '0' + i;
            new_option.text   =  i;
            new_option.value  =  i;
            options_array.push(new_option);

         }//for

         populateSelectBox('to_day', options_array);

         //for (var i = 0; i < date_selections.length; i++) {
         //  document.getElementById(date_selections[i]).options[0].selected = true;
         //}

      }//initializeDateRangeSelectionBoxes()











					// Action:  Check to see whether the
					//          first date is before the 
					//          second.
					// Returns: true if so, false otherwise.

      function isFromDateBeforeToDate(from_year, from_month, from_day, to_year, to_month, to_day) {

         var julian_from_date = getJulianDate(from_year, from_month, from_day);
         var julian_to_date   = getJulianDate(to_year,   to_month,   to_day);

         if (julian_from_date <= julian_to_date) return true;

         return false;

      }//isFromDateBeforeToDate()




      function getJulianDate(YY, MM, DD) {

         HR=0;
         MN=0;
         SC=0;

         with (Math) {  
            HR = HR + (MN / 60) + (SC/3600);
            GGG = 1;
            if (YY <= 1585) GGG = 0;
            JD = -1 * floor(7 * (floor((MM + 9) / 12) + YY) / 4);
            S = 1;
            if ((MM - 9)<0) S=-1;
            A = abs(MM - 9);
            J1 = floor(YY + S * floor(A / 7));
            J1 = -1 * floor((floor(J1 / 100) + 1) * 3 / 4);
            JD = JD + floor(275 * MM / 9) + DD + (GGG * J1);
            JD = JD + 1721027 + 2 * GGG + 367 * YY - 0.5;
            JD = JD + (HR / 24);
          }
          return (JD);

      }//getJulianDate()





					// Action:  Check to see whether the
					//          given date is between the 
					//          current available date range.
					//          Checking year is unnecessary
					//          because selection box limits
					//          that choice to available years.
					// Returns: true or false
      function isBetweenAvailableDateRange(year, month, day) {

         var available_from_year  = Number(min_date_array[0]);
         var available_from_month = Number(min_date_array[1]);
         var available_from_day   = Number(min_date_array[2]);

         var available_to_year    = Number(max_date_array[0]);
         var available_to_month   = Number(max_date_array[1]);
         var available_to_day     = Number(max_date_array[2]);


         var julian_from_date = getJulianDate(available_from_year, available_from_month, available_from_day);
         var julian_to_date   = getJulianDate(available_to_year,   available_to_month,   available_to_day);
         var julian_test_date = getJulianDate(year, month, day);

         if (julian_test_date >= julian_from_date && julian_test_date <= julian_to_date) return true;

         return false;

      }//isBetweenAvailableDateRange()



                                        // Action:  Check to see whether the
                                        //          available date range is 
					//          completely within the 
					//          given dates.
                                        // Returns: true or false

      function containsAvailableDateRange(from_year, from_month, from_day, 
                                          to_year,   to_month,   to_day) {


         var available_from_year  = Number(min_date_array[0]);
         var available_from_month = Number(min_date_array[1]);
         var available_from_day   = Number(min_date_array[2]);

         var available_to_year    = Number(max_date_array[0]);
         var available_to_month   = Number(max_date_array[1]);
         var available_to_day     = Number(max_date_array[2]);


         var julian_avail_from_date = getJulianDate(available_from_year, available_from_month, available_from_day);
         var julian_avail_to_date   = getJulianDate(available_to_year,   available_to_month,   available_to_day);
         var julian_from_date       = getJulianDate(from_year, from_month, from_day);
         var julian_to_date         = getJulianDate(to_year, to_month, to_day);


         if (julian_avail_from_date >= julian_from_date && julian_avail_to_date <= julian_to_date) return true;

         return false;

      }//containsAvailableDateRange()












					// Action:  Check to see whether the user's
					//          selected dates are complete.
					// Returns: true if incomplete, otherwise false
      function isIncompleteDateRange() {

          for (var i = 0; i < date_selections.length; i++) {
            if (isDefaultSelected(date_selections[i]))  return true;
          }
          return false;

      }//isIncompleteDateRange()


      function isDateRangeNotInitialized() {
          var index = 0;

          for (var i = 0; i < date_selections.length; i++) {
             index = document.getElementById(date_selections[i]).selectedIndex;
             if (index <= 0)  return true;
          }
          return false;
      }





					// Action:  Check to see whether the
					//          given user date range is valid. 
					// Returns: true or false
      function isValidDateRange() {

					// If no date selected, it is valid.
         if (!isDateRangeSelected()) return true;

					// Some part of date range was selected, 
					// but may be incomplete.
         if (isIncompleteDateRange()) return false;


         var from_month_box = document.getElementById('from_month');
         var from_day_box   = document.getElementById('from_day');
         var from_year_box  = document.getElementById('from_year');

         var to_month_box   = document.getElementById('to_month');
         var to_day_box     = document.getElementById('to_day');
         var to_year_box    = document.getElementById('to_year');

         var from_month  = Number(from_month_box[from_month_box.selectedIndex].value); 
         var from_day    = Number(from_day_box[from_day_box.selectedIndex].value); 
         var from_year   = Number(from_year_box[from_year_box.selectedIndex].value); 

         var to_month    = Number(to_month_box[to_month_box.selectedIndex].value); 
         var to_day      = Number(to_day_box[to_day_box.selectedIndex].value); 
         var to_year     = Number(to_year_box[to_year_box.selectedIndex].value); 

					// If the FROM date is before the TO date
					// it is invalid.

         if (!isFromDateBeforeToDate(from_year, from_month, from_day, to_year, to_month, to_day)) return false;

					// Let's let them pick a date 
					// range that overlaps the available
					// date range.  Too irritating to have 
					// the errors pop up all the time just 
					// because one of the two selected dates 
					// is outside the range.  This can happen
					// after they choose the dates then pick
					// a selection in the drop-down boxes 
					// because each selection they make resets
					// the available date range, thus creating
					// a date out of range error.  Not good.
					// So as long as we have SOME of the dates
					// in the user-selected date range in common with
					// available dates for the data, we are ok.

         if (isBetweenAvailableDateRange(from_year, from_month, from_day) ||
             isBetweenAvailableDateRange(to_year,   to_month,   to_day))    return true;


					// If the available date range is contained
					// within the user's selections, it is valid.

         if (containsAvailableDateRange(from_year, from_month, from_day, 
                                        to_year,   to_month,   to_day))     return true;
         return false;
         
      }//isValidDateRange()

      


					// Action:  Show from and to dates
					//          which are the maximum and 
					//          minimum sample dates for 
					//          the current user selections.
					//          This is updated asynchronously
					//          using AJAX.
					//          Also updates record count.
      function showAvailableDateRange() {

         clearRecordCount();

         var params = getParamString();

					// Get the value of the include_non_georefs checkbox.
         //var non_georefs = 'no';
         //if (isChecked('include_non_georefs')) non_georefs = 'yes';

         var req_string = '/get_date_range.php?&category=' + category;
         //                                     '&include_non_georefs=' + non_georefs;

         var request = GXmlHttp.create();
         request.onreadystatechange = function() {
            if (request.readyState == 4) {
               if (request.status != 200) {
                   //alert(request.status);
               } 
               else {
                  var xml = request.responseXML;
                  if (!xml) {
                      alert('No data found for showAvailableDateRange.');
                      document.getElementById('available_dates').innerHTML = 'Unknown Date Range';
                  } else {
                      var date_range = xml.documentElement.getElementsByTagName('date');
                      // global vars used elsewhere
                      min_date_array = date_range[0].getAttribute('min_date').split("-");
                      max_date_array = date_range[0].getAttribute('max_date').split("-");

                      if (!min_date_array[0] || !max_date_array[0]) {
                         alert("No dates found for the selected criteria.");
                         document.getElementById('available_dates').innerHTML = 'Not available for current selections';
                         resetDateRangeSelectionBoxes();
                      }//if
                      else {
                                       // Year data from database plus one for index
                                       // into zero-based array.
                         var from_year_index = Number(min_date_array[0]) + 1;
                         var to_year_index = Number(max_date_array[0]) + 1;

                         document.getElementById('available_dates').innerHTML = months[min_date_array[1]] + "-" +
                                                                                min_date_array[2] + "-" +
                                                                                min_date_array[0] + " to " +
                                                                                months[max_date_array[1]] + "-" +
                                                                                max_date_array[2] + "-" +
                                                                                max_date_array[0];

					// If they selected a date range, don't overwrite it.
                         if (isDateRangeNotInitialized() || isIncompleteDateRange()) initializeDateRangeSelectionBoxes();
                         showRecordCount();
                      }//else

                   }//else xml

               }//else !200
            }//if schange
         }//func()

         request.open('POST', req_string, true);
         request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
         request.setRequestHeader("Content-length", params.length);
         request.setRequestHeader("Connection", "close");
         request.send(params);


      }//showAvailableDateRange()







      function enableSelectBox(select_id) {

         var select_layer = document.getElementById(select_id + '_top_layer');

         select_layer.style.height = '0px';
         select_layer.style.width  = '0px';
         select_layer.innerHTML    = '';
         select_layer.title        = '';

      }//enableSelectBox()



      function disableSelectBox(select_id) {

         var select_box   = document.getElementById(select_id);
         var width        = parseInt(select_box.offsetWidth) - 20;
         var trans_image  = "url(/Images/transparent_spacer.gif)";
         var select_layer = document.getElementById(select_id + '_top_layer');


         select_layer.style.backgroundImage = trans_image;
         select_layer.style.width           = width + 'px';
         select_layer.style.height          = '100%';
         select_layer.innerHTML             = '&nbsp;';
         select_layer.title                 = 'To select items, please use the [Select] button.';

      }//disableSelectBox()




      function showHelpMessage() {
         alert('To select items, please use the [Select] button.');
      }

      function resetColor(id, color) {
         document.getElementById(id).style.color = color;
      }







					// Action:  Show options in the multiple
					//          selection drop-down box for
					//          the given selection box id.
					//
					// Input:   ID of the href [Select/Done] 
					//          button that is associated with the 
					//          desired drop-down box.
      function showOptions(button_id) {

         if (!isValidDateRange()) {

               resetColor('available_dates', '#FF0033');
               makeAlert ("Invalid Date Selection", 
                          'Please enter a valid date range within "Available Dates", or deselect date range completely.',
                          150, 500, 200);
               hideLoading();
               return;

         }//if invalidDate



         var button_element = document.getElementById(button_id);
         var select_id = select_buttons[button_id];



					// Check to see if user just pressed
					// a select button.
					// This works because we have not
					// yet updated the button image to be
					// 'Done' yet -- if the src image
					// name still matches 'select...'
					// then they just clicked the select
					// button.  
         if (button_element.src.match('select')) {

					// Check to see if search string 
					// was entered and if so, check 
					// its validity.

            if (isBadSearchValue(select_id)) {
               hideLoading();
               return;
            }


            hideSelectButtons();
            hideText();
            disableAllSelectBoxes();
            enableSelectBox(select_id);

                                        // Check for cases where we should
                                        // not perform selection box updates.

            if (skipSelectionUpdate(select_id)) {

               button_element.src = './Images/done_button.png';
               hideLoading();

            }//if
            else {
					// Fill selection box with items that 
					// are limited by previous selections, 
					// if any.


					// Check for special case of group 
					// selection which necessitates clearing 
					// related parameter box.

               if (button_id == 'group_button') {

                  if (isSomethingSelected('organism_select')) {
                     makeAlert ('Resetting Organisms', 
                                "Reselecting 'Organism Groups' resets your 'Organisms' selection." + sep +
                                sep +
                                "This is because 'Organism Groups' determines 'Organisms'",
                                 150, 500, 200);
                     resetSelectBox('organism_select'); 
                  }
                  else if (isSomethingSelected('analyte_select')) {
                     makeAlert ('Resetting Parameters', 
                                "Reselecting 'Parameter Groups' resets your 'Parameters' selection." + sep +
                                sep +
                                "This is because 'Parameter Groups' determines 'Parameters'",
                                 150, 500, 200);

                     resetSelectBox('analyte_select'); 

                  }//elseif


               }//if grp
   
   
   
   					// Get the items from DB for this 
   					// drop-down box.
               var options_array  = getOptionsArray(select_id);
               hideSearchStringBoxes();


   					// If value of option is 'Do not'
   					// nothing was returned.
               var pattern = /^Do not limit search/;
               if (pattern.test(options_array[0].text)) {

                  if (isDateRangeSelected()) 
                         alert ('No options were found for this range of dates.  Please try again.');
                  else if (button_id == 'region_button') {

                     var region_type = '';

                     switch (select_id) {
                        case 'county_select':
                           region_type = 'counties';      
                           break;
                        case 'rb_select':
                           region_type = 'regional boards';      
                           break;
                        case 'wbt_select':
                           region_type = 'waterbody types';      
                           break;
                        case 'huc10_select':
                           region_type = 'HUC10s';      
                           break;
                        default: region_type = 'region';
                     }//switch

                     var errmsg = '';
                     var search_string = getSearchString(select_id);

                     if (search_string) { 
                        errmsg = 'No ' + region_type +
                                 ' matches your search selection.';
                     }
                     else { 
                        if (select_id == 'wbt_select') 
                           errmsg = 'No waterbody types are found for these selections.';
                        else
                           errmsg = 'No ' + region_type + 
                                    ' was given to CEDEN for these stations. ' + sep + sep +
                                    'They may be missing georeferences or may be ' +
                                    'outside the boundaries of this region type.';
                     }//else

                     makeAlert('No Regions Found', errmsg, 180, 500, 200);

                  }//else region
                  else   alert ('No options were found for these selections.  Please try again.');

                  button_element.src = select_buttons_src[button_id];
                  disableAllSelectBoxes();
                  replaceAllSelectButtons();
                  showSearchStringBoxes();
                  showText();
               }
               else {
                  populateSelectBox(select_id, options_array);
                  fixSelectBoxSize(select_id);
                  button_element.src = './Images/done_button.png';
               }//else


            }//else

         
         }//if [Select]
         else {				// -- If we are here, they selected [Done] --


					// Testing to see if they clicked [Done] 
					// without actually select anything.  
					// If so, set them back  to 'Do not limit...' 
					// and if they are selecting things from 
					// the stations drop-down, clear the map 
					// as well as reinitializing the selection box.

            if (!isSomethingSelected(select_id)) { 

               button_element.src = select_buttons_src[button_id];
               //resetColor(link_id, '#FFFFFF');
               disableAllSelectBoxes();
               replaceAllSelectButtons();
               showSearchStringBoxes();

                                        // Keep analytes/organisms if groups is still chosen.

               if     (select_id == 'analyte_select' && isSomethingSelected('group_select'))
                  selectAllOptions('analyte_select');
               else if (select_id == 'organism_select' && isSomethingSelected('group_select'))
                  selectAllOptions('organism_select');
               else
                  resetSelectBox(select_id);

               if (select_id == 'station_select') clearStations();
               showRecordCount();
               showText();

            }//if
            else {   
					// Get rid of unselected options 
					// from drop down select box.
               showSelectedItemsOnly(select_id);

               button_element.src = select_buttons_src[button_id];

               disableAllSelectBoxes();
               replaceAllSelectButtons();
               showSearchStringBoxes();

					// If they chose 'Parameter Groups',
					// we must still populate the analytes
					// drop-down box, too, to show the analytes
					// that belong to that parameter group.
					// They will be limited by prior selections,
					// just as the other drop-down selections are.
               if (select_id == 'group_select') {

                  var which_param     = getWhichParameter();
                  var options_array   = getOptionsArray(which_param + '_group_select');


                                        // If value of option is 'Do not limit...'
                                        // nothing was returned.
                  var pattern = /^Do not limit search/;
                  if (pattern.test(options_array[0].text)) {
                     alert ('No options were found for these selections.  Please try again. (Note: Check Parameter Groups).');
                     button_element.src = select_buttons_src[button_id];
                     disableAllSelectBoxes();
                     replaceAllSelectButtons();
                  }
                  else {
                     populateSelectBox(which_param + '_select', options_array);
                     fixSelectBoxSize(which_param  + '_select');
                     selectAllOptions(which_param  + '_select');

                  }//else
               }//if pgroups


					// If user has turned on automatic
					// station mapping
                      			// Note that showAvailableDateRange 
					// is already called from showStations()
					// so no need to call it here.

               if (document.getElementById('automap_stations_on').checked == true) { 
                  showStations();
               }
               else {
					// In this case, we need to call 
					// showAvailableDateRange explicitly.

                  showAvailableDateRange();
               }

            }//else something selected

            showText();

         }//else [Done]

         hideLoading();

      }//showOptions()



      //]]>
      </SCRIPT>

   </HEAD>




<!--
  <BODY onload='makeAlert("AQT Status", aqtstatusmsg, 260, 500, 200);if(typeof(category) != "undefined") initialize(category); else initialize("wq");' 
-->
  <BODY onload='if(typeof(category) != "undefined") initialize(category); else initialize("wq");' 
        onunload='GUnload()' 
        STYLE='font-size: 9pt; font-family: arial'>



     <table class="tclass1">
       <tr>
         <td class="tdclass1"><a href="http://ceden.org/index.shtml"><img src="./Images/ceden_header_3f.jpg" alt="CEDEN Logo" border="0"></a></td>
         <td class="tdclass1" width="100%">&nbsp;</td>
       </tr>
     </table>

     <table border="0" width="100%" bgcolor="#69aa36" class="">
        <tr>
           <td width="100px;"
               align="center"
               valign="middle"
               bgcolor="#9acd32"
               style="border-color:#000000; border-style:solid; border-width:1px;"
               onmouseover="this.bgColor='#9acd32';"
               onmouseout ="this.bgColor='#9acd32';">

                 <a class="aclass6" href="http://ceden.waterboards.ca.gov/AdvancedQueryTool.php">Find Data</a>
           </td>

           <td width="100px;"
               align="center"
               valign="middle"
               bgcolor="#69aa36"
               onmouseover="this.bgColor='#9acd32';"
               onmouseout ="this.bgColor='#69aa36';">

                 <a class="aclass6" href="http://ceden.org/ceden_submitdata.shtml">Submit Data</a>
           </td>

           <td width="100px;"
               align="center"
               valign="middle"
               bgcolor="#69aa36"
               onmouseover="this.bgColor='#9acd32';"
               onmouseout ="this.bgColor='#69aa36';">

                 <a class="aclass6" href="http://ceden.org/about_us.shtml">About CEDEN</a>
           </td>
           <td align="right" valign="middle">
              &nbsp;
           </td>
           <td align="right" valign="middle">
               <a class="aclass6" href="http://ceden.org/contact_us.shtml">contact&nbsp;us</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;<a class="aclass6" href="http://ceden.org/site_map.shtml">site&nbsp;map</a>
           </td>

           <td width="280px" align="right" valign="middle">
               <form style="float:right" name="cse" id="searchbox_demo" action="https://www.google.com/cse">
                  <input type="hidden" name="cref" value="" />
                  <input type="hidden" name="ie" value="utf-8" />
                  <input type="hidden" name="hl" value="" />
                  <input name="q" type="text" size="30" />
                  <input type="submit" name="sa" value="Search" />
               </form><script type="text/javascript" src="https://www.google.com/cse/tools/onthefly?form=searchbox_demo&lang="></script>
           </td>
        </tr>
     </table>

<!-- End ceden.org -->




     <TABLE  ALIGN='left' BORDER='0' CELLPADDING='0' CELLSPACING='0'>
        <TR>
           <TD VALIGN='top'>
              <DIV ID='map_canvas' STYLE='width: 550px; height: 700px'></DIV>
           </TD>
           <TD VALIGN='top'>
              <TABLE ID='selections_table' BORDER='0' STYLE='margin-bottom:0' CELLPADDING=0 CELLSPACING=0>
              
              <TR>
              <TD>
              <FORM onSubmit='return false;' 
                    NAME='selection_form'
                    ID='selection_form'
                    ACTION='./AdvancedQueryTool' 
                    METHOD='post'>

              <DIV ID='result_category'>
                 <TABLE STYLE='margin-left:3%;margin-top:1%;margin-bottom:2%' BORDER='0' CELLPADDING='5' CELLSPACING='0' WIDTH='530' HEIGHT='40'>
                    
<!-- Maintenance Message -->

<!--<TR>
<TD colspan=2>


<div style="background-color: red;padding:2px;">

<h3><font color="black">The CEDEN query tool will be unavailable from 5pm on Friday April 8th thru 8am on Monday April 11th due to building electrical maintenance procedures.</font></h3>

</div>

</TD>
</TR>-->

<!-- End Maintenance Message -->




                     <TR STYLE='height:35px'> 
                       <TD CLASS='tdclass10' ALIGN='right' BGCOLOR='#31B8CC'>
                          RESULT&nbsp;CATEGORY:&nbsp;&nbsp;
                       </TD>
                       <TD CLASS='tdclass7' ALIGN='left' BGCOLOR='#31B8CC'>
                          <INPUT TYPE='radio' 
                                 NAME='result_category' 
                                 ID='wq' 
                                 NAME='wq' 
                                 VALUE='wq' 
                                 onclick='changeResultCategory(this.id);'/>Water Quality&nbsp;&nbsp;
                          <INPUT TYPE='radio' 
                                 NAME='result_category' 
                                 ID='tox' 
                                 NAME='tox' 
                                 VALUE='tox' 
                                 onclick='changeResultCategory(this.id);'/>Toxicity&nbsp;&nbsp;
                          <INPUT TYPE='radio' 
                                 NAME='result_category' 
                                 ID='tis' 
                                 NAME='tis' 
                                 VALUE='tis' 
                                 onclick='changeResultCategory(this.id);'/>Tissue&nbsp;&nbsp;
                                 <BR>
                          <INPUT TYPE='radio' 
                                 NAME='result_category' 
                                 ID='ben' 
                                 NAME='ben' 
                                 VALUE='ben' 
                                 onclick='changeResultCategory(this.id);'/>Benthic&nbsp;&nbsp;
                          <INPUT TYPE='radio' 
                                 NAME='result_category' 
                                 ID='hab' 
                                 NAME='hab' 
                                 VALUE='hab' 
                                 onclick='changeResultCategory(this.id);'/>Habitat&nbsp;&nbsp;
<!--
                          <INPUT TYPE='radio' 
                                 NAME='result_category' 
                                 ID='ts' 
                                 NAME='ts' 
                                 VALUE='ts' 
                                 onclick='changeResultCategory(this.id);'/>Time Series&nbsp;&nbsp;
//-->
                       </TD>
                       <TD>
                        &nbsp;
                        <IMG SRC='/Images/help.gif'
                               BORDER='0'
                               ALIGN='top'
                               onmouseover='tooltip.show("Help for Result Categories", 160);'
                               onmouseout='tooltip.hide();'
                               onclick='openWindow("help_result_category.html","help_result_category", 240, 600); return false;'>
                       </TD>
                    </TR>
                    <TR>
                       <TD STYLE='color:#63D5E6;font-size:10pt' ID='automapping_message' ALIGN='left' COLSPAN='3'>
                          <INPUT TYPE='checkbox' 
                                 CHECKED='no'
                                 ID='automap_stations_on' 
                                 NAME='automap_stations_on' 
                                 VALUE='no'
                                 onclick='clearStations();'>Turn&nbsp;on&nbsp;automatic&nbsp;station&nbsp;&nbsp;mapping.
                        <IMG SRC='/Images/help.gif'
                               BORDER='0'
                               ALIGN='top'
                               onmouseover='tooltip.show("Help for automapping stations", 140);'
                               onmouseout='tooltip.hide();'
                               onclick='openWindow("help_automapping.html","help_automapping", 370, 750); return false;'>
                       </TD>
                    </TR>
                 </TABLE>
              </DIV><!-- result_category -->
             </TD>
             </TR>
             <TR>
             <TD>
              <DIV ID='buttons'>
              <TABLE ALIGN='left' BORDER='0' CELLPADDING='0' CELLSPACING='0' STYLE='margin-top:0;margin-bottom:0'>
                 <TR>
                    <TD WIDTH='38' ALIGN='center'>
                       &nbsp;
                    </TD>
                    <TD STYLE='color:#63D5E6;font-size:10pt' ID='map_stations_button_message' ALIGN='left' VALIGN='top' COLSPAN='10'>
                       &nbsp;Click <B>Map Stations</B> at any time to show currently selected stations on the map 
                    </TD>
                 </TR>
                 <TR>
                    <TD WIDTH='38' ALIGN='center' STYLE='color:#FFFFFF'>
                       <SPAN ID='loading'><IMG ID='load_image' SRC='/Images/loading.gif' BORDER='0' STYLE='display:none'></SPAN> 
                    </TD>
                    <TD>
                                   <!--
                                        If user has selected a
                                        result category, keep it.
                                        Otherwise, assume we are
                                        starting application anew
                                        so default to water quality.
                                        Default is set because category
                                        is assigned in the global var
                                        section above.
                                   -->

                       <INPUT TYPE='image'
                              NAME='start_over'
                              SRC='./Images/start_over.png'
                              VALUE='submit'
                              ALT='Start Over'
                              onclick='changeResultCategory(category); return false;'><BR>
                    </TD>
                    <TD>&nbsp;</TD>
                    <TD>
                       <INPUT TYPE='image' 
                              NAME='stations_button' 
                              ID='stations_button' 
                              SRC='./Images/map_stations.png' 
                              VALUE='submit' 
                              ALT='Map Stations' 
                              TITLE='Click to show stations on the map' 
                              onclick='showStationsLoading(); return false;'><BR>
                    </TD>
                    <TD>&nbsp;</TD>
                    <TD>
                       <INPUT TYPE='image'
                              NAME='help'
                              ID='help'
                              SRC='./Images/help.png'
                              VALUE='submit'
                              ALT='Help'
                              TITLE='Main Help Screen'
                              onclick='openWindow("http://ceden.org/help.shtml","help_main", 600, 670); return false;'>
                       <IMG SRC='/Images/help.gif'
                              BORDER='0'
                              ALIGN='top'
                              onmouseover='tooltip.show("Help for using buttons", 135);'
                              onmouseout='tooltip.hide();'
                              onclick='openWindow("help_buttons.html","help_buttons", 380, 600); return false;'>
                    </TD>
                </TR>
                <TR>
                    <TD COLSPAN='6' STYLE='color:#FFFFFF;font-weight:600'><SPAN ID='wait_message'>&nbsp;</SPAN></TD>
                </TR>

              </TABLE>
              </DIV><!-- buttons -->

             </TD>
             </TR>
             <TR>
             <TD>
              <DIV ID='selections'>
                 <TABLE  ID='drop_down_selections_table'
                         STYLE='margin-left:4%;margin-top:0%' 
                         WIDTH='100%' 
                         ALIGN='left' 
                         BORDER='0' 
                         CELLPADDING='4' 
                         CELLSPACING='3'>
                    <TR>
                       <TD ALIGN='left' VALIGN='top' STYLE='color:#63D5E6;font-size:11pt' COLSPAN='8'>
                          <A CLASS='aclass2' 
                             HREF="./AdvancedQueryTool"
                                  onclick='openWindow("help_missing_georefs.html", "help_missing_geo", 415, 612); return false;'><SPAN ID='href_missinggeo_text'>Missing&nbsp;Georeferences&nbsp;Info</SPAN></A>&nbsp;&nbsp;&nbsp;&nbsp;
                       </TD>
                    </TR>
                    <TR>
                       <TD WIDTH='15%' ALIGN='left' VALIGN='top' STYLE='color:#63D5E6;font-size:11pt'>
                           <B><SPAN ID='rt_select_text'>Region&nbsp;Type&nbsp;Selection:</SPAN></B>
                       </TD>
                       <TD ALIGN='left' VALIGN='top'>
                           <SELECT
                              ID='region_type_select'
                              STYLE='z-index:1'
                              SIZE='1'
                              onchange="processRegionTypeSelection(this.options[this.selectedIndex].value);return false;">
                              <OPTION VALUE='county_select' SELECTED>County</OPTION>
                              <OPTION VALUE='rb_select'>Regional Board</OPTION>
                              <OPTION VALUE='wbt_select'>Water Body Type</OPTION> 
                              <OPTION VALUE='huc8_select'>HUC8</OPTION>
                              <OPTION VALUE='huc10_select'>HUC10</OPTION>
                              <OPTION VALUE='huc12_select'>HUC12</OPTION>
                           </SELECT>
                       </TD>
                       <TD ALIGN='left' VALIGN='top' STYLE='color:#63D5E6;font-size:11pt'>
                           <SPAN ID='search_string_label'><B>Search Text:</B></SPAN>
                       </TD>
                    </TR>
                    <TR>
                       <TD WIDTH='15%' ALIGN='right' VALIGN='top'>
                          <IMG SRC='/Images/select_county.png'
                               ID='region_button'
                               BORDER='0'
                               ALIGN='top'
                               ALT='Select Counties'
                               TITLE='Select Counties'
                               onclick="showOptionsLoading(this.id); return false;">
                       </TD>
                       <TD ALIGN='left' VALIGN='top'>
                          <DIV STYLE="position:relative;z-index:1;padding:0px;border:0">
                             <SELECT MULTIPLE
                                     STYLE='z-index:1'
                                     SIZE='1'
                                     ID='county_select'
                                     NAME='counties[]'>
                                <OPTION VALUE='All Counties'>Do not limit search by Counties</OPTION>
                             </SELECT>
                             <DIV ID='county_select_top_layer'
                                  TITLE='To select items, please click the [Select] button'
                                  STYLE="position:absolute;top:0;left:0;z-index:2;width:100%;height:100%;padding:3px;border:0;"
                                  onclick='showHelpMessage();'>&nbsp;
                             </DIV>
                          </DIV>
                       </TD>
                       <TD VALIGN='top'>
                             <INPUT ID='region_search' 
                                    TYPE='text' 
                                    onfocus="this.value=''"
                                    onkeypress="testKeyPress(event,this.id);"
                                    onblur="checkMissingSearchValue(this.value, this.id);"
                                    STYLE='color:gray;position:absolute;z-index:10'
                                    MAXLENGTH='200' 
                                    SIZE='20' />
                       </TD>
                    </TR>
                    <TR>
                       <TD WIDTH='15%' ALIGN='right' VALIGN='top'>
                          <IMG SRC='/Images/select_programs.png'
                               ID='program_button'
                               BORDER='0'
                               ALIGN='top'
                               ALT='Select Programs'
                               TITLE='Select Programs'
                               onclick='showOptionsLoading(this.id); return false;'>
                       </TD>
                       <TD ALIGN='left'>
                          <DIV STYLE='float:left;position:relative;z-index:1;padding:0px;border:0'>
                             <SELECT MULTIPLE
                                     STYLE='z-index:1'
                                     SIZE='1' 
                                     ID='program_select' 
                                     NAME='programs[]'> 
                                <OPTION VALUE='All Programs'>Do not limit search by Programs</OPTION>
                             </SELECT>
                             <DIV ID='program_select_top_layer' 
                                  TITLE='To select items, please click the [Select] button' 
                                  STYLE="position:absolute;top:0;left:0;z-index:2;width:100%;height:100%;padding:0px;border:0" 
                                  onclick='showHelpMessage();'>&nbsp;
                             </DIV>&nbsp;<IMG SRC='/Images/help.gif'
                                              STYLE='position:absolute;z-index:3'
                                              BORDER='0'
                                              ALIGN='top'
                                              onmouseover='tooltip.show("Help for using selection boxes", 180);'
                                              onmouseout='tooltip.hide();'
                                              onclick='openWindow("help_select_boxes.html","help_select", 450, 660); return false;'>
                          </DIV>
                       </TD>
                       <TD VALIGN='top'>
                             <INPUT ID='program_search' 
                                    TYPE='text' 
                                    onfocus="this.value=''"
                                    onkeypress="testKeyPress(event,this.id);"
                                    onblur="checkMissingSearchValue(this.value, this.id);"
                                    STYLE='color:gray;position:absolute;z-index:10'
                                    MAXLENGTH='200' 
                                    SIZE='20' />

                       </TD>
                    </TR>
                    <TR ID='projects_row'>
                       <TD WIDTH='15%' ALIGN='right' VALIGN='top'>
                          <IMG SRC='/Images/select_projects.png'
                               ID='project_button'
                               BORDER='0'
                               ALIGN='top'
                               ALT='Select Projects'
                               TITLE='Select Projects'
                               onclick='showOptionsLoading(this.id); return false;'>
                       </TD>
                       <TD ALIGN='left'>
                          <DIV STYLE="position:relative;z-index:1;padding:0px;border:0">
                             <SELECT MULTIPLE
                                     STYLE='z-index:1'
                                     SIZE='1' 
                                     ID='project_select' 
                                     NAME='projects[]'>
                                <OPTION VALUE='All Projects'>Do not limit search by Projects</OPTION>
                             </SELECT>
                             <DIV ID='project_select_top_layer' 
                                  TITLE='To select items, please click the [Select] button' 
                                  STYLE="position:absolute;top:0;left:0;z-index:2;width:100%;height:100%;padding:3px;border:0;" 
                                  onclick='showHelpMessage();'>&nbsp;
                             </DIV>
                          </DIV>
                       </TD>
                       <TD VALIGN='top'>
                             <INPUT ID='project_search' 
                                    TYPE='text' 
                                    onfocus="this.value=''"
                                    onkeypress="testKeyPress(event,this.id);"
                                    onblur="checkMissingSearchValue(this.value, this.id);"
                                    STYLE='color:gray;position:absolute;z-index:10'
                                    MAXLENGTH='200' 
                                    SIZE='20' />
                       </TD>
                    </TR>
                    <TR>
                       <TD WIDTH='15%' ALIGN='right' VALIGN='top'>
                          <IMG SRC='/Images/select_parameter_groups.png'
                               ID='group_button'
                               BORDER='0'
                               ALIGN='top'
                               ALT='Select Parameter Groups'
                               TITLE='Select Parameter Groups'
                               onclick='showOptionsLoading(this.id); return false;'>
                       </TD>
                       <TD ALIGN='left'>
                          <DIV ID='paramgrps_selection' STYLE='position:relative;z-index:1;padding:0px;border:0'>
                             <SELECT MULTIPLE
                                     STYLE='z-index:1'
                                     SIZE='1' 
                                     ID='group_select' 
                                     NAME='groups[]'> 
                                <OPTION VALUE='All Groups'>Do not limit search by Parameter Groups</OPTION>
                             </SELECT>
                             <DIV ID='group_select_top_layer' 
                                  TITLE='To select items, please click the [Select] button' 
                                  STYLE="position:absolute;top:0;left:0;z-index:2;width:100%;height:100%;padding:0px;border:0" 
                                  onclick='showHelpMessage();'>
                             </DIV>&nbsp;<IMG SRC='/Images/help.gif'
                                              ID='paramgrps_help'
                                              STYLE='position:absolute;z-index:3'
                                              BORDER='0'
                                              ALIGN='top'
                                              onmouseover='tooltip.show("Help for Parameter Groups", 160);'
                                              onmouseout='tooltip.hide();'
                                              onclick='openWindow("help_parameter_groups.html","help_groups", 370, 600); return false;'>
                          </DIV>
                       </TD>
                       <TD VALIGN='top'>
                             <INPUT ID='group_search'
                                    TYPE='text' 
                                    onfocus="this.value=''"
                                    onkeypress="testKeyPress(event,this.id);"
                                    onblur="checkMissingSearchValue(this.value, this.id);"
                                    STYLE='color:gray;position:absolute;z-index:10'
                                    MAXLENGTH='200' 
                                    SIZE='20' />
                       </TD>
                    </TR>
                    <TR>
                       <TD WIDTH='15%' ALIGN='right' VALIGN='top'>
                          <IMG SRC='/Images/select_parameters.png'
                               ID='analyte_button'
                               BORDER='0'
                               ALIGN='top'
                               ALT='Select Parameters'
                               TITLE='Select Parameters'
                               onclick='showOptionsLoading(this.id); return false;'>
                       </TD>
                       <TD ALIGN='left'>
                          <DIV STYLE='position:relative;z-index:1;padding:0px;border:0'>
                             <SELECT MULTIPLE
                                     STYLE='z-index:1'
                                     SIZE='1' 
                                     ID='analyte_select' 
                                     NAME='analytes[]'>
                                <OPTION VALUE='All Analytes'>Do not limit search by Parameters</OPTION>
                             </SELECT>
                             <DIV ID='analyte_select_top_layer' 
                                  TITLE='To select items, please click the [Select] button' 
                                  STYLE='position:absolute;top:0;left:0;z-index:2;width:100%;height:100%;padding:0px;border:0' 
                                  onclick='showHelpMessage();'>
                             </DIV>&nbsp;<IMG SRC='/Images/help.gif'
                                              STYLE='position:absolute;z-index:3'
                                              BORDER='0'
                                              ALIGN='top'
                                              onmouseover='tooltip.show("Help for Parameters", 130);'
                                              onmouseout='tooltip.hide();'
                                              onclick='openWindow("help_parameters.html","help_parameters", 270, 600); return false;'>
                          </DIV>
                       </TD>
                       <TD VALIGN='top'>
                             <INPUT ID='analyte_search' 
                                    TYPE='text' 
                                    onfocus="this.value=''"
                                    onkeypress="testKeyPress(event,this.id);"
                                    onblur="checkMissingSearchValue(this.value, this.id);"
                                    STYLE='color:gray;position:absolute;z-index:10'
                                    MAXLENGTH='200' 
                                    SIZE='20' />
                       </TD>
                    </TR>
                    <TR>
                       <TD WIDTH='15%' ALIGN='right' VALIGN='top'>
                          <IMG SRC='/Images/select_stations.png'
                               ID='station_button' 
                               BORDER='0'
                               ALIGN='top'
                               ALT='Select Stations'
                               TITLE='Select Stations'
                               onclick='showOptionsLoading(this.id); return false;'>
                          <DIV ID='no_georef_info'><A CLASS='aclass2' 
                                                  HREF="./AdvancedQueryTool"
                                                  onclick='openWindow("help_missing_georefs.html", "help_missing_geo", 415, 612); return false;'><SPAN ID='href_missinggeo_text'>Missing&nbsp;Georeferences&nbsp;Info</SPAN></A>&nbsp;&nbsp;&nbsp;&nbsp;
                          </DIV>
                       </TD>
                       <TD ALIGN='left'>
                          <DIV STYLE="position:relative;z-index:1;padding:0px;border:0">
                             <SELECT MULTIPLE
                                     STYLE='z-index:1'
                                     SIZE='1' 
                                     ID='station_select' 
                                     NAME='stations[]'> 
                                <OPTION VALUE='All Stations'>Do not limit search by Stations</OPTION>
                             </SELECT>
                             <DIV ID='station_select_top_layer' 
                                  TITLE='To select items, please click the [Select] button' 
                                  STYLE="position:absolute;top:0;left:0;z-index:2;width:100%;height:100%;padding:0px;border:0" 
                                  onclick='showHelpMessage();'>&nbsp;
                             </DIV>
                          </DIV>
                          <FONT COLOR='#FFFFFF'>(Stations missing lat/lngs will be shown in </FONT><FONT COLOR='red'>red</FONT><FONT COLOR='#FFFFFF'>.)</FONT>
                       </TD>
                       <TD VALIGN='top'>
                             <INPUT ID='station_search' 
                                    TYPE='text' 
                                    onfocus="this.value=''"
                                    onkeypress="testKeyPress(event,this.id);"
                                    onblur="checkMissingSearchValue(this.value, this.id);"
                                    STYLE='color:gray;position:absolute;z-index:10'
                                    MAXSIXE='200'
                                    SIZE='20' />
                       </TD>
                    </TR>
                    <TR ID='matrixes_row'>
                       <TD WIDTH='15%' ALIGN='right' VALIGN='top'>
                          <IMG SRC='/Images/select_matrixes.png'
                               ID='matrix_button'
                               BORDER='0'
                               ALIGN='top'
                               ALT='Select Matrixes'
                               TITLE='Select Matrixes'
                               onclick='showOptionsLoading(this.id); return false;'>
                       </TD>
                       <TD ALIGN='left'>
                          <DIV ID='matrix_species_selection' STYLE='position:relative;z-index:1;padding:0px;border:0'>
                             <SELECT MULTIPLE
                                     STYLE='z-index:1'
                                     SIZE='1'
                                     ID='matrix_select'
                                     NAME='matrixes[]'>
                                <OPTION VALUE='All Matrixes'>Do not limit search by Matrixes</OPTION>
                             </SELECT>
                             <DIV ID='matrix_select_top_layer' 
                                  TITLE='To select items, please click the [Select] button' 
                                  STYLE='position:absolute;top:0;left:0;z-index:2;width:100%;height:100%;padding:0px;border:0' 
                                  onclick='showHelpMessage();'>&nbsp;
                             </DIV>
                          </DIV>
                       </TD>
                       <TD VALIGN='top'>
                             <INPUT ID='matrix_search' 
                                    TYPE='text' 
                                    onfocus="this.value=''"
                                    onkeypress="testKeyPress(event,this.id);"
                                    onblur="checkMissingSearchValue(this.value, this.id);"
                                    STYLE='color:gray;position:absolute;z-index:10'
                                    MAXLENGTH='200' 
                                    SIZE='20' />
                       </TD>
                    </TR>
<!--
                    <TR>
                       <TD WIDTH='15%' ALIGN='right' VALIGN='top'>
                          <IMG SRC='/Images/select_intervals.png'
                               ID='interval_button'
                               BORDER='0'
                               ALIGN='top'
                               ALT='Select Intervals'
                               TITLE='Select Intervals'
                               onclick='showOptionsLoading(this.id); return false;'>
                       </TD>
                       <TD ALIGN='left'>
                          <DIV ID='intervals_selection' STYLE='position:relative;z-index:1;padding:0px;border:0'>
                             <SELECT MULTIPLE
                                     STYLE='z-index:1'
                                     SIZE='1'
                                     ID='interval_select'
                                     NAME='intervals[]'>
                                <OPTION VALUE='All Intervals'>Do not limit search by Intervals</OPTION>
                             </SELECT>
                             <DIV ID='interval_select_top_layer' 
                                  TITLE='To select items, please click the [Select] button' 
                                  STYLE='position:absolute;top:0;left:0;z-index:2;width:100%;height:100%;padding:0px;border:0' 
                                  onclick='showHelpMessage();'>&nbsp;
                             </DIV>
                          </DIV>
                       </TD>
                       <TD VALIGN='top'>
                             <INPUT ID='interval_search' 
                                    TYPE='text' 
                                    onfocus="this.value=''"
                                    onkeypress="testKeyPress(event,this.id);"
                                    onblur="checkMissingSearchValue(this.value, this.id);"
                                    STYLE='color:gray;position:absolute;z-index:10'
                                    MAXLENGTH='200' 
                                    SIZE='20' />
                       </TD>
                       <TD></TD>
                    </TR>
-->
                 </TABLE>
              </DIV><!-- selections -->
             </TD>
             </TR>
             <TR>
             <TD>
              <BR>
              <DIV ID='dates' STYLE='margin-left:10pt'>
                 <TABLE ALIGN='left' BORDER='0' CELLPADDING='2'>
                    <TR>
                       <TD STYLE="color:#63D5E6; font-size:10pt" ALIGN='left' COLSPAN='4'>
                          Available date range: <SPAN ID='available_dates' STYLE="color:white; font-size:10pt; font-weight:bold">&nbsp;</SPAN>
                                 <IMG SRC='/Images/help.gif'
                                      BORDER='0'
                                      onmouseover='tooltip.show("Help for Available Date Range", 180);'
                                      onmouseout='tooltip.hide();'
                                      onclick='openWindow("help_available_date_range.html","help_available_date_range", 335, 600); return false;'>

                       </TD>
                    </TR>
                    <TR>
                       <TD CLASS='tdclass6' ALIGN='left'>
                                   From:&nbsp;
                                </TD>
                                <TD>
                                   <SELECT NAME='from_month' ID='from_month' onclick="resetColor('available_dates', 'white');">
                                   </SELECT>
                                   <SELECT NAME='from_day' ID='from_day'     onclick="resetColor('available_dates', 'white');">
                                   </SELECT>
                                   <SELECT NAME='from_year' ID='from_year'   onclick="resetColor('available_dates', 'white');">
                                   </SELECT>&nbsp;
                                   <IMG SRC='/Images/help.gif' 
                                        BORDER='0' 
                                        onmouseover='tooltip.show("Date Range Help", 110);'
                                        onmouseout='tooltip.hide();'
                                        onclick='openWindow("help_date_range.html","help_date_range", 470, 600); return false;'>
                                </TD>
                                <TD ROWSPAN='2'>
                                   &nbsp;&nbsp;&nbsp;&nbsp;
                                   <A CLASS='aclass2'
                                      HREF="./AdvancedQueryTool"
                                      onmouseover='tooltip.show("Controlled Vocabulary Application", 120);'
                                      onmouseout='tooltip.hide();'
                                      onclick='openWindow("http://ceden.org/CEDEN_checker/Checker/LookUpLists.php","show_cvocab", 650, 1100); return false;'>Show Controlled Vocabulary</A><BR>
                                   &nbsp;&nbsp;&nbsp;&nbsp;
                                   <A CLASS='aclass2'
                                      HREF='/AdvancedQueryTool'
                                      onmouseover='tooltip.show("Show Station Lookup Info", 100);'
                                      onmouseout='tooltip.hide();'
                                      onclick='openWindow("http://ceden.org/CEDEN_Checker/Checker/DisplayCEDENLookUp.php?List=StationLookUp","show_stationlu", 400, 600); return false;'>Show Station Lookup</A><BR>
                                   &nbsp;&nbsp;&nbsp;&nbsp;
                                   <A CLASS='aclass2' 
                                      ID = 'show_qa_link'
                                      HREF="./AdvancedQueryTool" 
                                      onmouseover='tooltip.show("Show Quality Assurance Info", 120);'
                                      onmouseout='tooltip.hide();'
                                      onclick='openWindow("http://ceden.org/CEDEN_Checker/Checker/DisplayCEDENLookUp.php?List=QALookUp","show_qa_lookup", 400, 600); return false;'>Show QA Lookup</A><BR>
                                </TD>
                             </TR>
                             <TR>
                                <TD CLASS='tdclass6'>
                                   &nbsp;&nbsp;&nbsp;To:&nbsp;
                                </TD>
                                <TD>
                                   <SELECT NAME='to_month' ID='to_month'  onclick="resetColor('available_dates', 'white');">
                                   </SELECT>
                                   <SELECT NAME='to_day' ID='to_day'      onclick="resetColor('available_dates', 'white');">
                                   </SELECT>
                                   <SELECT NAME='to_year' ID='to_year'    onclick="resetColor('available_dates', 'white');">
                                   </SELECT>
                                   <A CLASS='aclass5' 
                                      HREF="./AdvancedQueryTool" 
                                      onclick="clearDates();return false;">[Clear Dates]</A>
                                </TD>
                                <TD>
                                   <!--
                                   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                   <A CLASS='aclass2' 
                                      HREF="./AdvancedQueryTool" 
                                      onclick="return false;">Show Column Definitions</A>
                                    -->
                                </TD>
                             </TR>
                          </TABLE>
                       </DIV><!-- dates -->
              </FORM>
             </TD>
             </TR>
             <TR>
             <TD>
                 <FORM onSubmit='return false;' 
                       NAME='data_retrieval_form'
                       ID='data_retrieval_form'
                       ACTION='./AdvancedQueryTool' 
                       METHOD='post'>
                       <DIV ID='retrieve_data' STYLE='margin-left:3%'>
                          <TABLE BORDER='0' CELLSPACING='0' CELLPADDING='5' WIDTH='520'>
                             <TR>
                                <TD ALIGN='right' HEIGHT='3' COLSPAN='4'>
                                   <IMG SRC='/Images/help.gif' 
                                        BORDER='0' 
                                        onmouseover='tooltip.show("Help for Retrieve Data", 140);'
                                        onmouseout='tooltip.hide();'
                                        onclick='openWindow("help_retrieve_data.php","help_retrieve_data", 660, 600); return false;'>
                                </TD>
                             </TR>
                             <TR BGCOLOR='#63D5E6'>
                                <TD CLASS='tdclass5'>
                                   <INPUT TYPE='image'
                                          NAME='retrieve_data'
                                          ID='retrieve_data'
                                          SRC='./Images/retrievedata_small.png'
                                          VALUE='submit'
                                          ALT='Retrieve Data'
                                          onclick='retrieveData(); return false;'>
                                </TD>
                                <TD CLASS='tdclass5' ALIGN='left'>
                                   <INPUT TYPE = 'radio' 
                                          onclick="changeRowLimit(id);"
                                          NAME = 'row_limit' 
                                          ID   = 'all_rows'
                                          VALUE= 'all_rows' CHECKED>All Rows<BR>
                                   <INPUT TYPE = 'radio' 
                                          onclick="changeRowLimit(id);"
                                          NAME = 'row_limit' 
                                          ID   = 'first_rows_limit1'
                                          VALUE= '1000'>First 1000 Records Only<BR>
                                   <INPUT TYPE = 'radio' 
                                          onclick="changeRowLimit(id);"
                                          NAME = 'row_limit' 
                                          ID   = 'first_rows_limit2'
                                          VALUE= '60000'>First 60000 Records Only<BR>
                                </TD>
                                <TD CLASS='tdclass5'>
                                   Record Count:&nbsp;<INPUT TYPE='text' ID='record_count' SIZE='6' READONLY STYLE='background-color:#CCCCCC'><BR>
                                   <SPAN ID='excel_help'></SPAN>
                                   Download Format:&nbsp;
                                   <SELECT NAME='download_format' ID='download_format'>
                                      <OPTION VALUE='excel'>excel</OPTION>
                                   </SELECT><BR>
                                   <SPAN ID='qa_checkbox'>
                                      <INPUT TYPE = 'checkbox' NAME='include_qa'   ID='include_qa'   onclick='showRecordCount();'>Include QA Data<BR>
<!--
                                      <INPUT TYPE = 'checkbox' NAME='include_qa'   ID='include_qa'>Include QA Data<BR>
-->
                                   </SPAN>
                                   <DIV ID='composite_checkbox'></DIV>
                                </TD>
                             </TR>
                             <TR ALIGN='left' VALIGN='top'>
                                <TD COLSPAN='4' STYLE='color:#63D5E6;font-size:10pt'>
                                   <SPAN ID='row_limit_message'>Note:&nbsp;  If number of records exceeds 
                                   60000, 
                                   the data will be zipped and emailed to you.</SPAN>
                                </TD>
                             </TR>
                          </TABLE>
                        </DIV><!-- retrieve data -->
              </FORM>
              <CENTER>
                <A HREF='help_browser.html'
                   CLASS='aclass5'
                   onclick='openWindow("help_browser.html","help_browser", 600, 650); return false;'>
                   <IMG SRC='/Images/firefox_small.png'
                        ALT='Why use Firefox'
                        TITLE='Why use Firefox'
                        BORDER='0'
                        onclick='openWindow("help_browser.html","help_browser", 600, 660); return false;'><U>Why is this site best viewed with Firefox?</U></A><BR>
                <A HREF='contact.html'
//                   CLASS='aclass5'
//                   BORDER='0'
                   onclick='openWindow("contact.html", "contact); return false;'>
                   <U>Please contact us for help or to report issues.</U>
                </A>
                <BR>
                <BR>
                <BR>
                <BR>
                <BR>
              </CENTER>

             </TD>
             </TR>
             </TABLE>
          </TD>
       </TR>
     </TABLE>

     <DIV id="alertLayer" class="alertBoxStyle"></DIV>

     <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>


  </BODY>

</HTML>


