// Define some variables 
var defaultscale  = 0.40;
var smallestscale = 0.4; // defines smallest marker size as fraction of defaultscale
var ndscale       = 0.5 * 3 * defaultscale; // defines size of black triangles
var myopacity     = 1;
var dx;

function processData() {
  if (DATA.length < nbins) { nbins = DATA.length; }
  
  DATA.nonReportablesPresent = false;
  dx = (DATA.max - DATA.min) / nbins;
      
  if (USER[DIND].program == 'FMP') {
    for (var i=0; i<DATA.length; i++) {
      DATA[i].opacity = myopacity;
      DATA[i].name    = DATA[i].StationName;
      DATA[i].desc    = "Station Code:   " + DATA[i].StationCode + "<br>" +
                        "Coordinates:    " + DATA[i].lon.toString() + "," +
                        DATA[i].lat.toString() + "<br>" +
                        "Analyte:        " + USER[DIND].analyte + "<br>" +
                        "Species:        " + USER[DIND].species + "<br>" +
                        "Tissue Type:    " + USER[DIND].tissuetype + "<br>" +
                        "Date:           " + DATA[i].month + "/" + DATA[i].day +
                        "/" + DATA[i].year + "<br>" +
                        "Average Result: " + DATA[i].result.toFixed(DATA[i].rdecimal) + 
                        " " + DATA[i].unit + "<br><br>" + 
                        '<a class="mybublink" onclick=RspeciesCompare("' + 
                        DATA[i].StationCode + '")>' + 
                        'Compare these results to other species.</a><br>' + 
                        '<a class="mybublink" onclick=RtimeCompare("' + 
                        DATA[i].StationCode + '")><br>' +
                        'View time series at this site.</a>';
      var tmp = (Math.floor( (DATA[i].result - DATA.min)/dx ) + 1)/nbins;
      if (tmp>1) {tmp=1;}
      if (tmp<=0) {tmp=1/nbins;}
      if (nbins==1) {tmp=1;}  // needed to prevent NaN
      DATA[i].color   = scaleToRGB(tmp);
      DATA[i].scale   = (tmp*smallestscale + smallestscale) * defaultscale; // rescale from 0-1 
      DATA[i].icon    = 'blankcircle';
    }
  } else if (USER[DIND].program == 'RMP') {
    for (var i=0; i<DATA.length; i++) {
      DATA[i].opacity = myopacity;  
      DATA[i].name  =   USER[DIND].analyte;
      DATA[i].desc  =   "Result:        " + DATA[i].result.toFixed(DATA[i].rdecimal) + " " +
                        DATA[i].unit + "&nbsp;<br>" +
                       "Test Material: " + USER[DIND].test_material + "<br>" ;
      if (USER[DIND].matrix != null) {
        DATA[i].desc +=  "Matrix:        " + USER[DIND].matrix + "<br>" ;
      }
      DATA[i].desc +=   "Date:          " + DATA[i].month + "/" + DATA[i].day + 
                        "/" + DATA[i].year +  "<br>" +
                        "Site:          " + DATA[i].site_code + "<br>" +
                        "Coordinates:   " + DATA[i].lon.toString() + "," + 
                        DATA[i].lat.toString() +   "<br>" +
                        "Region:        " + DATA[i].region_code + "<br>" +
                        "Program:       " + USER[DIND].program + "<br>" +
                        "Qualifiers:    " + DATA[i].qualifier;
       
      // Data Quality Tiers ... use reportable variable for now, can change
      if (DATA[i].reportable){
        var tmp = (Math.floor( (DATA[i].result - DATA.min)/dx ) + 1)/nbins;
        if (tmp>1) {tmp=1;}
        if (tmp<=0) {tmp=1/nbins;}
        DATA[i].color = scaleToRGB(tmp);
                            DATA[i].scale = (tmp*smallestscale + smallestscale) * defaultscale; // rescale from 0-1
                            DATA[i].icon = 'blankcircle';
      } else {
        DATA.nonReportablesPresent = true;
        DATA[i].color = 'black';
        DATA[i].scale = ndscale;
        DATA[i].icon = 'triangle';
      }
    }
  } else {
    alert('Unknownd Program : ' + USER[DIND].program);
  }
}

function addMarkers() {
  // create a bounds variable so zoom level is automated
  var bounds = new GLatLngBounds();

  // Create array of Markers for pre/post processsing
  var pts = new Array();

  // Modified to not attempt plotting markers that have 'error' for lat/long
  // Mostly Control samples - Todd 07/30/09

  var mapPointCount = 0;
  for (var i=0; i<DATA.length; i++) {
    var tmp = new GLatLng(DATA[i].lat, DATA[i].lon);
    if (!isNaN(tmp.x) && !isNaN(tmp.y)) {   // check to see if we have a valid lat/long
      pts.push( Marker(map,DATA[i]) );
      pts[mapPointCount].myZindex = mapPointCount; // used for ordering markers
      map.addOverlay(pts[mapPointCount]);
      bounds.extend(tmp);
      mapPointCount++;
    }
  }
  MAP[DIND].markerhandle = pts;
                        
  // ===== determine the zoom level from the bounds =====
  map.setZoom(map.getBoundsZoomLevel(bounds));
  // ===== determine the centre from the bounds ======
  map.setCenter(bounds.getCenter());

  // Create legend
  makeLegend();
}


function getMinMax() {
  DATA.min = 1.0E+300;
  DATA.max = -1.0E+300;
  for (var i=0; i<DATA.length; i++) {
    DATA.min = Math.min(DATA.min, DATA[i].result);
    DATA.max = Math.max(DATA.max, DATA[i].result);
  }
  // keep these values for future reference
  DATA.realmin = DATA.min;
  DATA.realmax = DATA.max;
}


function makeLegend() {
  //test
  var DATA_bins = Array();
  var rdecimal = DATA[0].rdecimal;     
  var unit     = DATA[0].unit;
  if ( rdecimal == null ) { rdecimal = 3; }
  if ( unit == null ) { unit = ' '; }
  var html = '<div id="map_legend" class="map_legend"></div>';
  $("#legend_content").append(html);
  // Add ND/Not Reportable marker to legend
  if (DATA.nonReportablesPresent) {
    var tmp = {lon: 0.0, lat: 0.0, scale: 0.0, color: "color", name: "Name"};
    tmp.name = "Not Reported";
    tmp.scale= ndscale;
    tmp.color= 'black';
    tmp.opacity=myopacity;
    tmp.icon = 'triangle';
    DATA_bins.push(tmp);
  }
 

  var val1 = new Number();
  var val2 = new Number();
  for (var i=0; i<nbins; i++) {
    var tmp = {lon: 0.0, lat: 0.0, scale: 0.0, color: "color", name: "Name"};
    val1 = DATA.min + (i*dx);
    val2 = DATA.min + ((i+1)*dx);
    tmp.name  = ( val1.toFixed(rdecimal) + " - " + val2.toFixed(rdecimal)  );
    if (nbins>1) {
      if (DATA.min > DATA.realmin & i==0) {
        tmp.name = '<' + tmp.name;
      }
      if (DATA.max < DATA.realmax & i==nbins-1) {
        tmp.name = ( val1.toFixed(rdecimal) + " - >" + val2.toFixed(rdecimal)  );
      }
    } else {
      tmp.name = DATA.min.toFixed(rdecimal);
    }
    tmp.scale = ((i+1)/nbins*smallestscale+smallestscale) * defaultscale; // rescale 
    tmp.color = scaleToRGB( (i+1)/nbins ); 
    tmp.opacity = myopacity;
    DATA_bins.push(tmp);
  }

  var bns = new Array();
  var mylist = '<table style="border-collapse:collapse;" width="100%">';
  for (var i=0; i<DATA_bins.length; i++) {
    bns.push( Marker(map,DATA_bins[i]) );
    mylist += bns[i].mylist_html; // + '<div class="mylist_spacer"></div>';
  }
  mylist += '</table>';
  var myheader = USER[DIND].title_string + '<div class="mylist_spacer"></div>';
  var d=new Date();
  myfooter = '<div class="mylist_footer">Map Generated: ' +
    (d.getMonth()+1)+'/'+d.getDate()+'/'+d.getFullYear() + 
    '<br>&copy; SFEI www.sfei.org</div>';
  mylist = myheader + mylist + myfooter;
  //alert(mylist);
  $("#map_legend").html(mylist);
}

// Miscellaneous global variables
var myspacer = '<br><div class="myspacer"></div><br>';
var debug = false;


function addExceldownload() {
  alert("test");          
}

function addKMLdownload() {
  var html = '<div id="kml_down" class="kml_down">' +
             '<table border=0 cellspacing=0 cellpadding=5><tbody><tr>' +
             '<td align="center"><img src="http://eis.sfei.org/labs/icons/google_earth.jpg" ' + 
             'height="15" width="15" /></td>' +
             '<td align="right"><a style="font:trebuchet,helvetica,arial,sans-serif; font-size:12px;" ' +
             'href="' + DATA[0].kmzfile + '">Download Map to Google Earth</a></td>' +
             '<td align="right"><a style="font:trebuchet,helvetica,arial,sans-serif; font-size:12px">(' + 
             USER[DIND].program + ', ' + USER[DIND].analyte + ', ' + USER[DIND].test_material + ', ' +
             USER[DIND].year1 + '-' + USER[DIND].year2 + ')</a></td></tr></tbody></table></div>';
//      $('#tab-map').append(html);
  $('#tab-down-content').append(html);
}

function makeTitleString() {
  // There are multiple instances where a title string will need to be displayed. This
  // function will create that string once. The string can then be used anytime.
  // 
  // Currently there are multiple instances of this title string floating around.
  // This function is intended to replace those...
  var unit = DATA[0].unit;
  if (unit == null ) { unit = ' ' };
  if (USER[DIND].program == 'FMP') {
    var myheader = USER[DIND].analyte + ' in ' + USER[DIND].species + ' ' +
                   USER[DIND].tissuetype + ' (' + unit + ')';
  } else if (USER[DIND].program == 'RMP') {
    if (USER[DIND].test_material == 'Sediment') USER[DIND].matrix=null;
    if (USER[DIND].matrix != null ) { 
      // either water or tissue at this point
      if (USER[DIND].test_material == 'Water') {
        var myheader = USER[DIND].matrix + ' ' + USER[DIND].analyte + ' in ' +
                       USER[DIND].test_material + ' (' + unit + ')';
      } else {
        var myheader = USER[DIND].analyte + ' in ' + USER[DIND].matrix + ' ' + USER[DIND].test_material + ' (' + unit + ')';
      }
    } else {
      // sediment
      var myheader = USER[DIND].analyte + ' in ' + USER[DIND].test_material + ' (' + unit + ')';
    }
  }  
      
  if (USER[DIND].year2 > USER[DIND].year1) {
    myheader += '<br>' + USER[DIND].year1 + ' to ' + USER[DIND].year2;
  } else {
    myheader += '<br>' + USER[DIND].year1;
  }
  myheader = '<div class="mylist_header">' + myheader + '</div><br>';
  USER[DIND].title_string = myheader;
}

function isGRTS() {
  // Function to determine if the data are GRTS format
  USER[DIND].GRTS = false;
  if ( (USER[DIND].program == 'RMP') & (USER[DIND].test_material != 'Tissue') &
     (USER[DIND].year1 >= 2002) & (USER[DIND].year2 >= 2002) ) {
    USER[DIND].GRTS = true;
  }
}
