function Rgrtsest() {

  var rdecimal = DATA[0].rdecimal; 
  if ( rdecimal == null ) { rdecimal = 3; }
  $('#tab-cdf-content').html('<a><img src="http://eis.sfei.org/labs/icons/spinner.gif">' +
                             '</img>&nbsp;Loading...</a>');
  $('#tab-stats-content').html('<a><img src="http://eis.sfei.org/labs/icons/spinner.gif">' +
                               '</img>&nbsp;Loading...*</a>');

  var url = "http://eis.sfei.org/wqt/R/brew/grts_ajax.rhtml";
  url = url + "?program=" + USER[DIND].program + "&year1=" +
                            USER[DIND].year1 + "&year2=" + USER[DIND].year2 +
                            "&species=" + USER[DIND].species + "&analyte=" + USER[DIND].analyte +
                            "&test_material=" + USER[DIND].test_material + "&matrix=" +
                            USER[DIND].matrix;
  url = url + "&sid=" + Math.random();

  $.ajax({
    url: url,
    type: 'GET',
    error: function(e) {
      alert("Error: " + e);
    },
    success: function(str) {
      // a json string is returned 
      var json = RparseJSON(str);
      

      // Create a message for the user
      var msg = '<div style="width: 500px;">The data used for this analysis are from a probabilistic survey ' +
                'design. These results therefore represent spatially unbiased estimates. More ' +
                'information is available <a href="http://www.epa.gov/nhrlsup1/arm/index.htm" ' +
                'target="_blank">here.</a></div>';

      if ( (USER[DIND].GRTS) & (USER[DIND].program == 'RMP') ) {
        var phtml = USER[DIND].title_string + '<div id="cdfaccordion">';
        var thtml = USER[DIND].title_string +
          '<table id="stats-table" class="tablesorter"' +
          'border=0 cellpadding=0 cellspacing=1>' +
          '<thead><tr>' +
          '<th>Region &nbsp;&nbsp;&nbsp;</th>' +
          '<th>Frame Area (sq km) &nbsp;&nbsp;&nbsp;</th>' +
          '<th>Mean &nbsp;&nbsp;&nbsp;</th>' +
          '<th>Upper Confidence &nbsp;&nbsp;&nbsp;</th>' +
          '<th>Lower Confidence &nbsp;&nbsp;&nbsp;</th>' +
          '<th>Standard Deviation &nbsp;&nbsp;&nbsp;</th>' +
          '<th>N &nbsp;&nbsp;&nbsp;</th>' +
          '<th>Min Value &nbsp;&nbsp;&nbsp;</th>' +
          '<th>Max Value &nbsp;&nbsp;&nbsp;</th>' +
          '</tr></thead>' +
          '<tbody> ';
        for (var i=0; i<json.length; i++) {
          phtml +=  '<div>' +
                    '<div class="title">' + json[i].region + '</div>';
          if (json[i].fail==0) {
            phtml += '<div><img style="display:block; margin-left:auto; margin-right:auto;" ' +
                     'src="' + json[i].url + '"><br>' + 
                     '<table id="cdf-table" class="tablesorter" ' +
                     'border=0 cellpadding=0 cellspacing=1>' +
                     '<thead><tr>'+
                     '<th align="center">Percentile &nbsp;&nbsp;&nbsp;</th>' +
                     '<th align="center">Value &nbsp;&nbsp;&nbsp;</th>' +
                     '<th align="center">Upper Confidence &nbsp;&nbsp;&nbsp;</th>' +
                     '<th align="center">Lower Confidence &nbsp;&nbsp;&nbsp;</th>' +
                     '</tr></thead>' +
                     '<tbody>' +
                     '<tr><td align="center">99</td>' +
                     '<td align="center">' + json[i].c99.toFixed(rdecimal) + '</td>' +
                     '<td align="center">' + json[i].u99.toFixed(rdecimal) + '</td>' +
                     '<td align="center">' + json[i].l99.toFixed(rdecimal) + '</td></tr>' +
                     '<tr><td align="center">95</td>' +
                     '<td align="center">' + json[i].c95.toFixed(rdecimal) + '</td>' +
                     '<td align="center">' + json[i].u95.toFixed(rdecimal) + '</td>' +
                     '<td align="center">' + json[i].l95.toFixed(rdecimal) + '</td></tr>' +
                     '<tr><td align="center">75</td>' +
                     '<td align="center">' + json[i].c75.toFixed(rdecimal) + '</td>' +
                     '<td align="center">' + json[i].u75.toFixed(rdecimal) + '</td>' +
                     '<td align="center">' + json[i].l75.toFixed(rdecimal) + '</td></tr>' +
                     '<tr><td align="center">50</td>' +
                     '<td align="center">' + json[i].c50.toFixed(rdecimal) + '</td>' +
                     '<td align="center">' + json[i].u50.toFixed(rdecimal) + '</td>' +
                     '<td align="center">' + json[i].l50.toFixed(rdecimal) + '</td></tr>' +
                     '<tr><td align="center">25</td>' +
                     '<td align="center">' + json[i].c25.toFixed(rdecimal) + '</td>' +
                     '<td align="center">' + json[i].u25.toFixed(rdecimal) + '</td>' +
                     '<td align="center">' + json[i].l25.toFixed(rdecimal) + '</td></tr>' +
                     '</tbody>' +
                     '</table>' +
                     '</div>';
          } else {
            phtml += '<div><a>' + json[i].errmsg + '</a></div>';
          }
          phtml += '</div>';
          thtml += '<tr>' +
                   '<td align="left">' + json[i].region + '</td>' +
                   '<td align="center">' + json[i].frameArea + '</td>';
          if (json[i].fail==0) {
            thtml += '<td align="center">' + json[i].mn.toFixed(rdecimal) + '</td>' +
                     '<td align="center">' + json[i].mnu.toFixed(rdecimal) + '</td>' +
                     '<td align="center">' + json[i].mnl.toFixed(rdecimal) + '</td>' +
                     '<td align="center">' + json[i].sd.toFixed(rdecimal) + '</td>' +
                     '<td align="center">' + json[i].nresp + '</td>' +
                     '<td align="center">' + json[i].min.toFixed(rdecimal) + '</td>' +
                     '<td align="center">' + json[i].max.toFixed(rdecimal) + '</td>';
          } else {
            thtml += '<td align="center">NA</td>' +
                     '<td align="center">NA</td>' +
                     '<td align="center">NA</td>' +
                     '<td align="center">NA</td>' +
                     '<td align="center">NA</td>' +
                     '<td align="center">NA</td>' +
                     '<td align="center">NA</td>';
          }
          thtml += '</tr>';
        }
        phtml += '</div>' + msg;
        thtml += '</tbody></table>' + msg;

        $('#tab-cdf-content').html(phtml);
        $('#tab-stats-content').html(thtml);
        $('#stats-table').tablesorter({ widgets: ['zebra'] });  
      } else {
        // Not RMP data ...
        // Shouldn't get here.
        var phtml = 'CDF analysis not possible for this selection. CDF analysis is currently ' +
                    'only available for RMP sediment and water data from 2002 to the present.';
        var thtml = 'Statistical analysis is currently only implemented for RMP sediment and water ' +
                    'data from 2002 to present.';
        $('#tab-cdf-content').html(phtml);
        $('#tab-stats-content').html(thtml);
      }

      $('#cdfaccordion').accordion( {
        header: 'div.title',
        autoHeight: false,
        alwaysOpen: false,
        active: '.title:first'
      });
    }
  });
}


function Rdescest() {
  // Perform descriptive stats for non GRTS data
  var rdecimal = DATA[0].rdecimal;
  if ( rdecimal == null ) { rdecimal = 3; }


  $('#tab-stats-content').html('<a><img src="http://eis.sfei.org/labs/icons/spinner.gif">' +
                               '</img>&nbsp;Loading...</a>');
  $('#tab-cdf-content').html('<a><img src="http://eis.sfei.org/labs/icons/spinner.gif">' +
                             '</img>&nbsp;Loading...</a>');

  var url = "http://eis.sfei.org/wqt/R/brew/desc_ajax.rhtml";
  url = url + "?program=" + USER[DIND].program + "&year1=" +
               USER[DIND].year1 + "&year2=" + USER[DIND].year2 +
               "&species=" + USER[DIND].species + "&analyte=" + USER[DIND].analyte.replace("'","''").replace('%','_').replace('+','^')
               + "&test_material=" + USER[DIND].test_material + "&matrix=" +
               USER[DIND].matrix + "&speciestype=" + USER[DIND].speciestype + '&tissuetype=' + USER[DIND].tissuetype;
  url = url + "&sid=" + Math.random();

  if (USER[DIND].program == 'RMP') {
    var msg = '<div style="width:500px;">Data used for these statistics are not from a probabilistic survey design. ' +
              'Results therefore are not spatially unbiased. For unbiased estimates of RMP data please ' +
              'select years from 2002 to present.</div>';
  } else {
    var msg = '';
  }


  var thtml = USER[DIND].title_string +
              '<table id="stats-table" class="tablesorter"' +
              'border=0 cellpadding=0 cellspacing=1>' +
              '<thead><tr>' +
              '<th>Region &nbsp;&nbsp;&nbsp;</th>' +
              '<th>Mean &nbsp;&nbsp;&nbsp;</th>' +
              '<th>Standard Deviation &nbsp;&nbsp;&nbsp;</th>' +
              '<th>N &nbsp;&nbsp;&nbsp;</th>' +
              '<th>Min Value &nbsp;&nbsp;&nbsp;</th>' +
              '<th>Max Value &nbsp;&nbsp;&nbsp;</th>' +
              '</tr></thead>' +
              '<tbody> ';
  $.ajax({
    url: url,
    type: 'GET',
    error: 
      function(e) {
        alert("Error: " + e);
      },
    success: 
      function(str) {
        // a json string is returned 
        var json = RparseJSON(str);

        for (var i=0; i<json.length; i++) {
          // create a table of results
          thtml += '<tr><td align="left">' + json[i].region + '</td>';
          if (json[i].fail==0) {
            thtml += '<td align="center">' + json[i].mn.toFixed(rdecimal) + '</td>';
            if (json[i].nresp>1) {
              // std deviation is undefined for sample size <= 1
              thtml += '<td align="center">' + json[i].sd.toFixed(rdecimal) + '</td>';
            } else {
              thtml += '<td align="center">NA</td>';
            }
            thtml += '<td align="center">' + json[i].nresp + '</td>' +
                     '<td align="center">' + json[i].min.toFixed(rdecimal) + '</td>' +
                     '<td align="center">' + json[i].max.toFixed(rdecimal) + '</td>';
          } else {
            thtml += '<td align="center">NA</td>' +
                     '<td align="center">NA</td>' +
                     '<td align="center">NA</td>' +
                     '<td align="center">NA</td>' +
                     '<td align="center">NA</td>';
          }
          thtml += '</tr>';
        }
        thtml += '</tbody></table>' + msg;

        // create the html for the CDF image
        // the url is in the first record of json variable
        if (json[0].fail==0) {
          var phtml = '<div><img style="display:block; margin-left:auto; margin-right:auto;" ' +
                      'src="' + json[0].url + '"></div>';
        } else {
          var phtml = '<div><a>' + json[0].errmsg + '</a></div>';
        }

        $('#tab-stats-content').html(thtml);
        $('#stats-table').tablesorter({widgets: ['zebra']});
        $('#tab-cdf-content').html(phtml);
      }
  });
}

function RkrigRMP() {
  //debugger;
  var url = "http://eis.sfei.org/wqt/R/brew/krigRMP_ajax.rhtml";
  url = url + "?program=" + USER[DIND].program + "&year1=" +
              USER[DIND].year1 + "&year2=" + USER[DIND].year2 +
              "&species=" + USER[DIND].species + "&analyte=" + USER[DIND].analyte +
              "&test_material=" + USER[DIND].test_material + "&matrix=" +
              USER[DIND].matrix + "&ncolors=" + nbins + "&mnval=" + DATA.min +
              "&mxval=" + DATA.max;
  url = url + "&sid=" + Math.random();

  $.ajax({
    url: url,
    type: 'GET',
    error: function(e) {
      alert("Error: " + e);
    },
    success: function(str) {
      // Returns a JSON string
      var json = RparseJSON(str);
      if (json.fail==0) {
        // Add the kriged contours to the map (as a ground overlay of a png image
        var b = new GLatLngBounds(new GLatLng(json.minlat, json.minlon), new GLatLng(json.maxlat, json.maxlon));
        MAP[DIND].krighandle = new GGroundOverlay(json.pngurl, b);
        MAP[DIND].map.addOverlay(MAP[DIND].krighandle);

        // Add option to remove the krig layer
        var html = '<input type="checkbox" name="contour_toggle" checked="checked" />' +
                   '<a id="contour_layer_label">&nbsp;Data Contours<br></a>';
        $('#map_layer_selector').append(html);

        // attach event listener to radio buttons
        $("input[ name='contour_toggle']").click( function() {
          if ( $("input[ name='contour_toggle']").attr('checked') ) {
            MAP[DIND].map.addOverlay(MAP[DIND].krighandle);
          } else {
            MAP[DIND].map.removeOverlay(MAP[DIND].krighandle);
          }
        });
      }
    }
  });
}



function RspeciesCompare(stn) {
  // This is an FMP specfic function
  var url = "http://eis.sfei.org/wqt/R/brew/fmpSpeciesComparison.rhtml";
  url = url + "?station=" + stn + "&analyte=" + USER[DIND].analyte + "&tissuetype=" +
              USER[DIND].tissuetype + "&speciestype=" + USER[DIND].speciestype +
              "&year1=" + USER[DIND].year1 + "&year2=" + USER[DIND].year2;
  url += "&sid=" + Math.random();

  $.ajax({
    url: url,
    type: 'GET',
    error: function(e) { alert("Error: " + e); },
    success: function(str) {
      var json = RparseJSON(str);
      $("#tab-graph-content").html('<img style="display:block; margin-left:auto; margin-right:auto;" ' +
        'src="' + json.url + '"/>');
      $('#pagetabs > ul').tabs( 'select','#tab-graph' );
    }
  });
}

function RtimeCompare(stn) {
  // This is an FMP specific function
  var url = "http://eis.sfei.org/wqt/R/brew/fmpTimeComparison.rhtml";
  url = url + "?station=" + stn + "&analyte=" + USER[DIND].analyte + "&tissuetype=" +
        USER[DIND].tissuetype + "&speciestype=" + USER[DIND].speciestype + "&species=" + USER[DIND].species;
  url += "&sid=" + Math.random();
  $.ajax({
    url: url,
    type: 'GET',
    error: function(e) { alert("Error: " + e); },
    success: function(str) {
      var json = RparseJSON(str);
      $("#tab-graph-content").html('<img style="display:block; margin-left:auto; margin-right:auto;" ' +
        'src="' + json.url + '"/><br>');
      $('#tab-graph-content').append('Number years sampled: ',json.n);
      $('#pagetabs > ul').tabs( 'select','#tab-graph' );
    }
  });
}


function RparseJSON(str) {
  // This function parses the string returned from an Rapache/AJAX call
  // the problem is that R prints a bunch of junk too.
  // so we need to parse the returned string to find only
  // the relevant json information
  //
  var idx1 = str.indexOf('xxx');
  var idx2 = str.indexOf('zzz');
  var tmp = str.substring(idx1+3,idx2);
  var json = {};
  json = eval(tmp);
  return(json);
}
