
function openSelectList(monitoringProgram,list) {
  var visibleCount = 0;
 
  $(monitoringProgram + " > .selHead").each( function() { 
  	if ($(this).is(':visible')) visibleCount++;
  	$(this).next().hide(); 
  });
  
//  var z = $(monitoringProgram).height() - (visibleCount * ($(list).height()+7));
//  $(list).next().css("min-height",z).css("max-height",z).height(z);
  
  $(list).next().toggle();
}

function SelectListClick(obj) {
  
}

function loadSelectList(obj) {
  try {
    var monitoringProgram = obj.parent().attr("id");
    var _data = {
      list: obj.attr("dbfieldname"),
      tm: obj.parent().find("#TestMaterial").attr("selected"), //need to know if testmaterial is water or tissue (JORAM)
      id: obj.attr("id"),
      target: "#" + obj.parent().attr("id") + " > #" + obj.attr("id"),
      monitoringprogram: monitoringProgram
    };

    obj.next().html("<b>Loading...</b>");  	    
    //build the sql select data 
    obj.parent().find(".selHead").each(function() {
      var x = $(this).attr("selected");
      if ($(this).attr("selected") != "null") {
        _data["*" + $(this).attr("id")] = $(this).attr("dbfieldname") + " " + $(this).attr("operator") + " (" + $(this).attr("dbvalues") + ")";
      }
    });
	
    $.ajax({ 
      type: "GET", 
      url: "http://eis.sfei.org/wqt/php/loadSearchTerms.php", 
      data: _data, 
      dataType: "json",
      success: function(data) {
        $(data.target).next().html(data.html);
        $(data.target).next().find("li").each(function() {  //roll through this .selBody's (next) li and assign a click function
//          alert($(this).attr("id"));
          $(this).bind("click",function(e) { 
            selectFunction(e);
          });
        });
//        $("#" + data.monitoringprogram + " > .selBody li").each(function() {
//          alert($(this).attr("id"));
//          $(this).bind("click",function(e) { 
//            selectFunction(e);
//          });
//        });
      }
    });
  } catch(err) {
    if (debug == true) console.log("LoadSelectList Error: " + err);
  }
}

function resetChildren(obj,prompt) {
  try {
    var x = obj.parent()[0].id;
    
    obj.nextAll('.selHead').each(function() {
      $(this).next().html(prompt);
      $(this).attr("selected","null");
      $(this).attr("dbvalues","null");
      $(this).html($(this).attr("title"));
      $(this).css("background","#00AEEF url('http://eis.sfei.org/wqt/css/slices/check2.gif') no-repeat");
    });
    

/*
    // clear out all the subsequent selection lists
    var child = "#" + obj.parent()[0].id + " #" + obj.attr("_child");
    var o = $("#" + obj.parent()[0].id + " #" + obj.attr("_child"));
    o.next().html(prompt);
    o.attr("selected",null);
    o.attr("dbvalues",null);
    o.html(o.attr("title"));
    o.css("background","#00AEEF url('http://eis.sfei.org/wqt/css/slices/check2.gif') no-repeat");
    while (o.attr("_child") != "none") {
      o = $("#" + obj.parent()[0].id + " > #" + o.attr("_child"));
      o.next().html(prompt);
      o.attr("selected",null);
      o.attr("dbvalues",null);
      o.html(o.attr("title"));
      o.css("background","#00AEEF url('http://eis.sfei.org/wqt/css/slices/check2.gif') no-repeat");
      if (debug == true) console.log("id = " + o.attr("id") + " child = " + o.attr("_child"));
    }
    */
  } catch(err) {
    if (debug == true) console.log("resetChildren exception: " + err);
  }
}

function fixTestMaterial(testMaterial,matrix,species,parameterType) {
  var retval = "";
  if (testMaterial == "Sediment") {
  	retval = "Sed%";
  } else if (testMaterial == "Water") {
  	if (parameterType == "TOX") retval = "WaterTox%*" + "CGIG,MEDU,MYSI,THAL,MYSI";

  	else retval = "WaterChem*" + matrix;
  } else {
  	retval = "Tissue";
  }
  return retval;
}

function downloadExcel(id,showqual) {
  
  if (showqual == 0) $("#abbr_qualifiers" + id).val("no");
  else $("#abbr_qualifiers" + id).val("yes");
  //var f = $("#" + id + "_form");

  //alert("submitting form with id: " + id + " - " + showqual);
  $("#" + id + "_form").submit();
}

function customFunctionRMPParameterType(evt,monitoringProgram,obj) {
  var parent = $(obj.parent().parent().prev());
  if (monitoringProgram == "rmpAccordion") {
    var date = new Date(); 
    var id = date.getTime();

    resetUSER();
    var _data = loadUSER(monitoringProgram);
        
    var year1 = parseInt(USER[DIND].year1);
    var year2 = parseInt(USER[DIND].year2);
    var divstr = "";
    divstr += "<div id='" + id + "_div'><form id='" + id + "_form' action='http://legacy.sfei.org/RMP/report'>";
    divstr += "<input type='hidden' name='action' value='excel'>";
    divstr += "<input type='hidden' name='directive' value='render'>";
    divstr += "<input type='checkbox' name='regions' checked value='_all_'>";
    divstr += "<input type='hidden' name='parameter_type' value='" + USER[DIND].parametertype + "'>";
    divstr += "<input type='hidden' name='test_material' value='" + fixTestMaterial(USER[DIND].test_material,USER[DIND].matrix,USER[DIND].species,USER[DIND].parametertype) + "'>";
    divstr += "<input type='hidden' id='abbr_qualifiers" + id + "' name='abbr_qualifiers' value='yes'>";
//    alert("USER[DIND].parametertype = " + USER[DIND].parametertype);
    for (y=year1; y <= year2; y++) {
      divstr += "<input type='checkbox' name='collection_date' checked value='" + y + "'>";
    }

    divstr += "</form></div>";
    $("#rmpforms").append(divstr);
    //    var form = $("#bort_form");
    //    form.submit();
    //    var ser = form.serialize();
    //    alert(ser);$("#" + monitoringProgram + " > .selBody li").bind("click",


    var urlDesc = USER[DIND].program + ', ' + USER[DIND].test_material + (USER[DIND].matrix == null ? '' : ' ' + USER[DIND].matrix) + ', ' + USER[DIND].year1 + '-' + USER[DIND].year2 + " " + USER[DIND].parametertype;
    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/excel.jpg" height="15" width="15" /></td>' +
			       '<td align="left" colspan="2" style="font:trebuchet,helvetica,arial,sans-serif; font-size:12px">' + urlDesc + '</td>' +
			     '</tr><tr>' +
			       '<td>&nbsp;</td>' +
			       '<td align="left">' +
			         '<a style="font:trebuchet,helvetica,arial,sans-serif; font-size:12px;" ' +
			         'href="#" onclick="javascript:downloadExcel(' + id + ',0);return false">Download Excel (All Qualifiers)</a>' +
			       '</td>' +
			       '<td align="left">' +
			         '<a style="font:trebuchet,helvetica,arial,sans-serif; font-size:12px;" ' +
			         'href="#" onclick="javascript:downloadExcel(' + id + ',1);return false">Download Excel (Primary Qualifiers)</a>' +
			       '</td>' +
                 '</tr>' +
               '</tbody></table></div>';			       
  
  	
    $('#tab-down-content').append(html);

  }
  //parent.html(parent.html() + " (<i>Download</i>)");
  
}

function customFunctionTestMaterial(evt,monitoringProgram,obj) {
  if (obj.attr("alt") == "Water") {
    $("#" + monitoringProgram + " > #Fraction").show();
    $("#" + monitoringProgram + " #Fraction").attr("title","Fraction");
  } else if (obj.attr("alt") == "Tissue") {			// JORAM
    $("#" + monitoringProgram + " > #Fraction").show();	
    $("#" + monitoringProgram + " #Fraction").attr("title","Species");
  } else {									
    $("#" + monitoringProgram + " > #Fraction").hide();
  }
}

function selectFunction(evt) {    
  try {
//    var obj = $("#" + evt.currentTarget.id);
    var obj = $(evt.target); //$(evt.currentTarget);
    var parent = $(obj.parent().parent().prev());
    var monitoringProgram = $(parent.parent()).attr("id");
    

    parent.attr("selected",obj.attr("alt"));
    parent.attr("dbvalues",obj.attr("dbvalues"));
    parent.trigger('customFunction',[monitoringProgram,obj]);
    if (parent.attr("_child") == "none") {
      // all selections made; render results 
      parent.html(parent.attr("title") + ": <a>" + obj.attr("alt") + "</a>"); // JORAM -- append analyte name
      openSelectList('#' + monitoringProgram,null);  // JORAM -- close the list
      $("#" + monitoringProgram + " #" + parent.attr("id")).css("background","#00AEEF url('http://eis.sfei.org/wqt/css/slices/check2_over.gif') no-repeat");
      renderResults(monitoringProgram);
    } else {
      var child = findVisibleChild(monitoringProgram,parent);
      parent.html(parent.attr("title") + ": <a>" + obj.attr("alt") + "</a>");
      openSelectList("#" + monitoringProgram,child);  
      resetChildren(parent,"<br>Please select <b>" + child.attr("title") + "</b> first.<br>");
      loadSelectList(child);
	  // JORAM -- Change background image to reflect selection (add check image)
	  $('#' + monitoringProgram + ' #' + parent.attr("id")).css("background","#00AEEF url('http://eis.sfei.org/wqt/css/slices/check2_over.gif') no-repeat");
    }
    parent.trigger('customFunctionPost',[monitoringProgram,obj]);
  } catch(err) {
  	if (debug == true) console.log("selectFunction Error: " + err);
  }
}

function findVisibleChild(monitoringProgram,obj) {
  var child = "";
  try {
  	var name = obj.attr("id");
  	var cname = obj.attr("_child");
  	var child = $("#" + monitoringProgram + " > #" + cname);
    
    var x = child.css('display');
      
  	while (child.css('display') == "none") {    // skip past invisible selHeads
  	  cname = child.attr("_child");
  	  child = $("#" + monitoringProgram + " > #" + cname);
	}
  } catch (err) {
    if (debug == true) console.log("findVisibleChild Error: " + err);  	
  }
  return child;
}

function fixMatrix(str) {
  var retstr = "";
  
  if (str == "Water Column Dissolved") retval = "Dissolved";
  else if (str == "Water Column Total") retval = "Total";
  else retval = str;
  return retval;
}

function fixString(str) {
  var retstr = str.replace(/\^/g,"");
//  retstr = retstr.replace(/\'/g,"''");
  retstr = (retstr == "Sed%" ? "Sediment" : (retstr == "Water%" ? "Water" : retstr));
  return retstr;
}

function loadUSER(monitoringProgram) {
  USER[DIND].program = (monitoringProgram == "rmpAccordion" ? "RMP" : "FMP");
  if (USER[DIND].program == 'FMP') USER[DIND].test_material = "Tissue";
  var _data = {
    monitoringprogram: USER[DIND].program
  };
        
  $("#" + monitoringProgram + " > .selHead").each( function() {
    var x = $(this).attr("selected");
      
    if ($(this).attr("selected") != "null") {
      if      ($(this).attr("id") == "TestMaterial")           USER[DIND].test_material = fixString($(this).attr("selected"));
      else if ($(this).attr("id") == "Fraction")               USER[DIND].matrix        = fixMatrix(fixString($(this).attr("selected")));
      else if ($(this).attr("id") == "Analyte")                USER[DIND].analyte       = fixString($(this).attr("selected"));
      else if ($(this).attr("id") == "fmpAnalyte")             USER[DIND].analyte       = fixString($(this).attr("selected"));
      else if ($(this).attr("id") == "fmpSpecies")             USER[DIND].species       = fixString($(this).attr("selected"));
      else if ($(this).attr("id") == "StartCollectionYear")    USER[DIND].year1         = fixString($(this).attr("selected"));
      else if ($(this).attr("id") == "fmpStartCollectionYear") USER[DIND].year1         = fixString($(this).attr("selected"));
      else if ($(this).attr("id") == "EndCollectionYear")      USER[DIND].year2         = fixString($(this).attr("selected"));        
      else if ($(this).attr("id") == "fmpEndCollectionYear")   USER[DIND].year2         = fixString($(this).attr("selected"));        
      else if ($(this).attr("id") == "fmpSpeciesType")         USER[DIND].speciestype   = fixString($(this).attr("selected"));
      else if ($(this).attr("id") == "fmpTissueType")          USER[DIND].tissuetype    = fixString($(this).attr("selected"));
      else if ($(this).attr("id") == "ParameterType")          USER[DIND].parametertype = fixString($(this).attr("dbvalues"));  //todd 072109 used to be "selected"
      

      
      _data["*" + $(this).attr("id")] = $(this).attr("dbfieldname") + " " + $(this).attr("operator") + " (" + $(this).attr("dbvalues") + ")";
      _data["_" + $(this).attr("id")] = fixString($(this).attr("dbvalues"));
	}
  });	
  return _data;
}

function renderResults(monitoringProgram) {
  try {
    $('#progress-alert').show();	
    resetUSER();
	var _data = loadUSER(monitoringProgram);
	$.ajax({
	  url:"http://eis.sfei.org/wqt/php/getData.php",
	  cache: false,
	  data: _data,
	  success: function(returnData) {
	    $('#progress-alert').hide();
	    DATA = eval(returnData);

		// Need to clean up FMP and RMP data a bit
		// This is temporary -- need to adjust databases
		if (USER[DIND].program == 'FMP') {
		  for (var i=0; i<DATA.length; i++) {
		    //	DATA[i].unit = 'UNITS';
			DATA[i].rdecimal = 3;
		  }
		} else if (USER[DIND].program = 'RMP') {
		  for (var i=0; i<DATA.length; i++) {
		    DATA[i].reportable = true;
			if (DATA[i].result == null) {
			  DATA[i].result = 0.0; // Need to fix how we handle nulls ...
			  DATA[i].reportable = false;
			}
			if (DATA[i].unit == null) {
			  DATA[i].unit = 'UNITS';
			}
			if (DATA[i].qualifier == null) {
			  DATA[i].qualifier = 'None';
			}
		  }
		}
		// Make title string from user inputs and database results
		makeTitleString();

		// AJAX call to perform R analysis
		// 1) is the selected data GRTS? (returns boolean)
		isGRTS();
		// 2) do the stats work
		getMinMax();
		if (USER[DIND].GRTS) {
		  Rgrtsest(); 	// implement GRTS analysis.
		} else {
		  Rdescest(); 	// implement basic descriptive statistics.
		}
				// Krig RMP data
		if ((USER[DIND].program == 'RMP') && (USER[DIND].year1 >= 2002)
			&& (USER[DIND].test_material != 'Tissue') ) {
  		  RkrigRMP();
		}
		// process the data and add to map
        MAP[DIND].map.clearOverlays();  // remove any overlays if they are there
		processData();
		initMapAccordion();
		addMarkers();
		initMarkerControls();
		// Add KML download functionality 
		addKMLdownload();

      },
      error: function(XMLHttpRequest,textStatus,errorThrown) {
        var x= "error";
	  }
    });
  } catch(err) {
  	alert(err);
    if (debug == true) {
      console.log("newResultDialog Error: " + err);
    }
    $('#progress-alert').hide();
  }
}
