
var lastType = null;
var resetPressed = 0;

function init() {
	dwr.util.useLoadingMessage();
	
	for (var i = 1; i <= 6; i++) {
		if (i > 1) { makeBooleanConditionals(document.getElementById(i+".boolean")); }
		//fillCategory(i); 
		//document.getElementById(i+".category").options[0].selected = true;
		//filterFields(i);
		addFields(i);
	}
	//set public, published info for admin, arachno-admin
	if (r == 1 ) {
		selectListOption(document.getElementById("publicStatus"), pri);
		if (pub != "hide" && pub != "") {
			makePublishedSelectBox();
			selectListOption(document.getElementById("publishedStatus"), pub);
		} else if (pub == ""){
			makePublishedSelectBox();
		} else {
			document.getElementById("published").style.display="none";
		}
	} 
	//set public, published info for groupAdmin
	if (r == 2 ) {
		if (pri == "" && pub == "") {			
			document.getElementById("published").style.display="none";
			selectListOption(document.getElementById("publicStatus"), pri);
			makeGroupAdminWidgets();
		} else {		
			selectListOption(document.getElementById("publicStatus"), pri);
			if (pub != "hide" && pub != "") {
				makePublishedSelectBox();
				selectListOption(document.getElementById("publishedStatus"), pub);
			} else if (pub == ""){
				makePublishedSelectBox();
			} else if (pub == "hide") {
				makePublishedSelectBox();
				selectListOption(document.getElementById("publishedStatus"), "YES");
				document.getElementById("published").style.display="none";
			}
		}
	} 
	
	//set public info for groupUser and arachnoUser
	if (q == 1) {
		selectListOption(document.getElementById("publicStatus"), pri);
	}

	// now re-select the choices from the previous search
	if (!resetPressed) {
		if (clauses != null) {
			
			for (var i = 0; i < clauses.length; i++) {
			
				
				
			
				var parts = clauses[i].split(":::");
				var row = i+1;
				var choices = parts[0].split("::");
				var coreParts = parts[1].split("-");
				//var category = coreParts[0];
				
				// display the row:
				if (row > 1) { document.getElementById(row+".row").style.display = ""; }
				
				// choose the category:
				/*
				var catOptions = document.getElementById(row+".category").options;
				for (var j = 0; j < catOptions.length; j++) {
					if (catOptions[j].value == category) {
						catOptions[j].selected = true;
						filterFields(row);
						break;
					}
				}
				*/
				// choose the field:
				var fieldOptions = document.getElementById(row+".fields").options;
				for (var j = 0; j < fieldOptions.length; j++) {
					if (fieldOptions[j].value == parts[1]) {
						fieldOptions[j].selected = true;
						
						// special cases: field is of type list or concentration, in this case choose the selected index
						// when the list is created (in the dwr part) as this is the only place it can be done
						var selectedId = -1;
						if ((choices[0] == "list")||(choices[0] == "concentration")||(choices[0] == "mullist")) { 
							selectedId = choices[3]; 
						}
						makeConditionalWidgets(row, selectedId);
						break;
					}
				}
				
				// choose the conditionals:
				if (choices[0] == "numeric") {
					
					if (choices.length % 2 == 1) {
						var tmp_choices = choices[0] + "::" + choices[1] + "-" + choices[2];
						for (var j = 3; j < choices.length; j++) {
							tmp_choices += "::" + choices[j];
						}
						choices = null;
						choices = tmp_choices.split("::");
					}
					for (var j = 1; j <= 2; j++) {
						if ((j == 1)||(choices.length > 4)) {
							var conOptions = document.getElementById(row+".numeric.conditional."+j).options;
							for (var k = 0; k < conOptions.length; k++) {
									if (conOptions[k].value == decode(choices[j*2])) {
									conOptions[k].selected = true;
									if (choices[1] == "Date(toxin.releaseDate)") {
										var value = decodeDate(choices[(j*2)+1]);
										document.getElementById(row+".numeric.searchTerm."+j).value = value;
										
									} else {
										document.getElementById(row+".numeric.searchTerm."+j).value = choices[(j*2)+1];
									}									
									break;
								}
							}
						}
					}
				}		
				else if (choices[0] == "concentration") {
					
					// do some post processing of the number of choices, and concatenate the
					// unusual joins together.
					if (choices.length % 2 == 0) {
						var tmp_choices = choices[0] + "::" + choices[1] + "-" + choices[2];
						for (var j = 3; j < choices.length; j++) {
							tmp_choices += "::" + choices[j];
						}
						choices = null;
						choices = tmp_choices.split("::");
					}
					
					// choose the concentration that was selected
					var concentrations = document.getElementById(row+".concentration.choices").options;
					for (var j = 0; j < concentrations.length; j++) {
						alert(concentrations[j].value + " vs " + choices[2]);
						if (concentrations[j].value == choices[2]) {
							concentrations[j].selected = true;
						}
					}
					
					// choose the boolean choices, and populate the text fields
					for (var j = 1; j <= 2; j++) {
						if ((j == 1)||(choices.length > 5)) {
							var conOptions = document.getElementById(row+".concentration.conditional."+j).options;
							for (var k = 0; k < conOptions.length; k++) {
								if (conOptions[k].value == decode(choices[j*2+1])) {
									conOptions[k].selected = true;
									document.getElementById(row+".concentration.searchTerm."+j).value = choices[(j*2)+2];
									break;
								}
							}
						}
					}
				}
				
				else if (choices[0] == "list") {
					var listConditionals = document.getElementById(row+".list.conditional").options;
					for (var j = 0; j < listConditionals.length; j++) {
						if (listConditionals[j].value == choices[2]) {
							listConditionals[j].selected = true;
							break;
						}
					}
				}
				else if (choices[0] == "mullist") {
					var listConditionals = document.getElementById(row+".mullist.conditional").options;
					for (var j = 0; j < listConditionals.length; j++) {
						if (listConditionals[j].value == choices[2]) {
							listConditionals[j].selected = true;
							break;
						}
					}
				}
				
				
				else {
					var	conOptions = document.getElementById(row+"."+choices[0]+".conditional").options;
					for (var k = 0; k < conOptions.length; k++) {
						if (conOptions[k].value == choices[2]) {
							conOptions[k].selected = true;
							document.getElementById(row+"."+choices[0]+".searchTerm").value = choices[3];
							break;
						}
					}
				}
					
				
			}
		
			// now also process the booleans:
			for (var i = 1; i < booleans.length; i++) { // ignore the first one
				var boolOptions = document.getElementById((i+1)+".boolean").options;
				for (var j = 0; j < boolOptions.length; j++) {
					if (boolOptions[j].value == booleans[i]) {
						boolOptions[j].selected = true;
						break;
					}
				}
			}	

			
			// finally, re-select the chosen groupings
			for (var i = 0; i < groups.length; i++) {
				document.getElementById((i+1)+"."+groups[i]).checked = true;
			}		
		}		
	}
}	


function addFields(rowNumber) {
	var fieldList = document.getElementById(rowNumber+".fields");
	
		// add an empty option:
		//var chooseOption = document.createElement("OPTION");
		//chooseOption.text = "please choose";
		//chooseOption.disabled = false;
		//fieldList.options.add(chooseOption);
		
		addOption(fieldList, "0-a-empty", "please choose");
		
		
		// the main toxin information:
		var g1 = document.createElement("OPTGROUP");
		g1.label = "Toxin Metadata";
		g1.className = "optgroup";
		if (r == 1 || r == 2 || q == 1) { addOption(fieldList, "1-numeric-toxin.id", "Toxin ID", g1); }
		addOption(fieldList, "1-text-toxin.name", "Toxin Name", g1);
		addOption(fieldList, "1-text-toxin.description","Toxin Description", g1);
		addOption(fieldList, "1-list-toxin.toxinGroup.id","Generic Toxin Group", g1);
		//addOption(fieldList, "1-list-toxin.toxinFamily.toxinSuperFamily.id","Toxin Super Family", g1);
		//addOption(fieldList, "1-list-toxin.toxinFamily.id","Toxin Family", g1);
		addOption(fieldList, "1-numeric-toxin.discoveryYear-discoveryYear","Toxin Discovery Year", g1);
		addOption(fieldList, "1-text-syn.synonym-toxin.toxinSyns as syn","Toxin Synonym", g1);
		addOption(fieldList, "1-text-ref.accession-toxin.references as ref","Toxin Accession Number", g1);
		addOption(fieldList, "1-numeric-size(seq.structures)-toxin.sequences as seq-numberOfPDBs", "Number of solved PDB structures", g1);
		addOption(fieldList, "1-numeric-Date(toxin.releaseDate)-releaseDate","Date Toxin Added (dd/mm/yyyy)", g1);
		fieldList.appendChild(g1);
	
		var g2 = document.createElement("OPTGROUP");
		g2.label = "Biological Activity";
		g2.className = "optgroup";
		addOption(fieldList, "2-mullist-activity.id-toxin.activities as activity","Biological Activities", g2);
		addOption(fieldList, "2-mullist-phyla.taxon.ncbiTaxon.id-toxin.phylas as phyla","Phyletic Specificities", g2);
		addOption(fieldList, "2-concentration-phyla.ed-toxin.phylas as phyla","Phyla Effective Dosage (ED50)", g2);
		addOption(fieldList, "2-concentration-phyla.ld-toxin.phylas as phyla","Lethal Dosage (LD50)", g2);
		addOption(fieldList, "2-concentration-phyla.pd-toxin.phylas as phyla","Paralytic Dosage (PD50)", g2);
		addOption(fieldList, "2-numeric-size(toxin.activities)-numberOfActivities", "Number of Biological Activities", g2);
		addOption(fieldList, "2-numeric-size(toxin.toxinMolTargets)-numberOfMolTargets", "Number of Molecular Targets", g2);
		fieldList.appendChild(g2);
	
		var g3 = document.createElement("OPTGROUP");
		g3.label = "Protein Information";
		g3.className = "optgroup";
		addOption(fieldList, "3-mullist-ptran.ptranType.id-toxin.ptrans as ptran", "Posttranslational Modifications", g3);
		addOption(fieldList, "3-numeric-size(toxin.ptrans)-numberOfPtrans","Number of Posttran. Modifications", g3);
		addOption(fieldList, "3-numeric-size(toxin.disulfides)-numberOfDisulfides","Number of Disulfide Bonds", g3);
		fieldList.appendChild(g3);
		
		var g4 = document.createElement("OPTGROUP");
		g4.label = "Source Species Taxonomy";
		g4.className = "optgroup";
		addOption(fieldList, "4-list-toxin.lsidSpider.id","Species", g4);
		addOption(fieldList, "4-list-toxin.lsidSpider.lsidCurrent.lsidTaxonomy.family-special:family","Family", g4);
		addOption(fieldList, "4-list-common.id-toxin.lsidSpider.lsidSpiderCommons as common","Common Name", g4);
		addOption(fieldList, "4-text-historicTaxonomy","Historic Taxonomy", g4);
		fieldList.appendChild(g4);
	
		var g5 = document.createElement("OPTGROUP");
		g5.label = "Literature Information";
		g5.className = "optgroup";
		addOption(fieldList, "6-text-lit.title-toxin.literatures as lit","Journal Article Title", g5);
		//addOption(fieldList, "6-text-lit.citation-toxin.literatures as lit","Citation", g5);
		addOption(fieldList, "6-text-lit.authors-toxin.literatures as lit","Author List", g5);
		addOption(fieldList, "6-numeric-lit.year-toxin.literatures as lit-x", "Year", g5);
		addOption(fieldList, "6-text-depositionAuthors","Deposition Authors", g5);
		addOption(fieldList, "6-text-lit.patentId-toxin.literatures as lit","Patent ID", g5);
		fieldList.appendChild(g5);
		
		var g6 = document.createElement("OPTGROUP");
		g6.label = "Mature Toxin Mass";
		g6.className = "optgroup";
		addOption(fieldList, "6-numeric-sequence.avgMassReduced-toxin.sequences as sequence-avgMassReduced","Average Reduced Mass (Da)", g6);
		addOption(fieldList, "6-numeric-sequence.avgMassOxidised-toxin.sequences as sequence-avgMassOxidised","Average Oxidised Mass (Da)", g6);
		addOption(fieldList, "6-numeric-sequence.isotopicMassReduced-toxin.sequences as sequence-isoMassReduced","Monoisotopic Reduced Mass (Da)", g6);
		addOption(fieldList, "6-numeric-sequence.isotopicMassOxidised-toxin.sequences as sequence-isoMassOxidised","Monoisotopic Oxidised Mass (Da)", g6);
		fieldList.appendChild(g6);
	}

function makeArachnoAdminWidgets() {
	var published = document.getElementById("publicStatus").value;
	if (published === "NoNo") {
		document.getElementById("published").style.display="none";
		addOption(document.getElementById("publishedStatus"), "hide", "");
		selectListOption(document.getElementById("publishedStatus"), "hide");		
	} else {
		makePublishedSelectBox();
	}
}


function makeGroupAdminWidgets() {
	var published = document.getElementById("publicStatus").value;
	if (published === "YesYes" || published == "") {
		document.getElementById("published").style.display="none";
    	addOption(document.getElementById("publishedStatus"), "hide", "");
    	selectListOption(document.getElementById("publishedStatus"), "hide");
	} else {
		makePublishedSelectBox();
	}
}

function makePublishedSelectBox() {
	dwr.util.removeAllOptions(document.getElementById("publishedStatus"));
	document.getElementById("published").style.display="";
	addOption(document.getElementById("publishedStatus"), "YESANDNO", "Any");
	addOption(document.getElementById("publishedStatus"), "YES", "Curated");
	addOption(document.getElementById("publishedStatus"), "NO", "Uncurated");	
}

function makeConditionalWidgets(rowNumber, selectedId) {
	var parts = document.getElementById(rowNumber+".fields").value.split("-");
	var type = parts[1];
	if (type == "text") {
		document.getElementById(rowNumber+".text.searchTerm").value = "";
		if (document.getElementById(rowNumber+".text.conditional").options.length == 0) {
			makeTextConditionals(document.getElementById(rowNumber+".text.conditional"));
		}
	}
	else if (type == "list") {
		if (document.getElementById(rowNumber+".list.conditional").options.length == 0) {
			makeListConditionals(document.getElementById(rowNumber+".list.conditional"));
		}
		addListOptions(rowNumber, parts[2], selectedId);
	}
	else if (type == "mullist") {
		if (document.getElementById(rowNumber+".mullist.conditional").options.length == 0) {
			makeMulListConditionals(document.getElementById(rowNumber+".mullist.conditional"));
		}
		addListOptions(rowNumber, parts[2], selectedId);
	}
	else if (type == "numeric") {
		for (var i = 1; i <= 2; i++) {
			if (document.getElementById(rowNumber+".numeric.conditional."+i).options.length == 0) {
				makeNumericConditionals(document.getElementById(rowNumber+".numeric.conditional."+i));
			}
		}
	}
	else if (type == "concentration") {
		makeConcentrationChoices(rowNumber, selectedId, parts[2]);
		for (var i = 1; i <= 2; i++) {
			if (document.getElementById(rowNumber+".concentration.conditional."+i).options.length == 0) {
				makeNumericConditionals(document.getElementById(rowNumber+".concentration.conditional."+i));
			}
		}
	}
	if (lastType) { 
		document.getElementById(rowNumber+"."+lastType).style.display = "none"; 
	}
	if (type != "a") {
		document.getElementById(rowNumber+".text").style.display = "none";
		document.getElementById(rowNumber+".numeric").style.display = "none";
		document.getElementById(rowNumber+".list").style.display = "none";
		document.getElementById(rowNumber+".mullist").style.display = "none";
		document.getElementById(rowNumber+".concentration").style.display = "none";
		document.getElementById(rowNumber+"."+type).style.display = "";
	}
	document.getElementById(rowNumber+".radio").style.display = "";
	if (rowNumber < 6) {
		document.getElementById(rowNumber+".addButton").style.display = "";
	}
	if (rowNumber > 1) {
		document.getElementById(rowNumber+".removeButton").style.display = "";
	}
	lastType = type;
}

function showClause(rowNumber) {
	document.getElementById(rowNumber+".row").style.display = "";
	document.getElementById((rowNumber-1)+".addButton").disabled = true;
}
function removeClause(rowNumber) {
	if (rowNumber > 1) {
		document.getElementById(rowNumber+".row").style.display = "none";
		document.getElementById((rowNumber-1)+".addButton").disabled = false;
	}
	else {
		document.getElementById(rowNumber+".addButton").style.display = "none";
	}
	clearFields(rowNumber);
}

function clearFields(rowNumber) {
	var fieldData = document.getElementById(rowNumber+".fields").value.split("-");
	var type = fieldData[1];
	
	if (type == "text") {
		document.getElementById(rowNumber+".text.conditional").options[0].selected = true;
		document.getElementById(rowNumber+".text.searchTerm").value = null;
	}
	else if (type == "list") {
		document.getElementById(rowNumber+".list.conditional").options[0].selected = true;
		document.getElementById(rowNumber+".list.choices").options[0].selected = true;
	}
	else if (type == "mullist") {
		document.getElementById(rowNumber+".mullist.conditional").options[0].selected = true;
		document.getElementById(rowNumber+".mullist.choices").options[0].selected = true;
	}
	else if (type == "numeric") {
		for (var i = 1; i <= 2; i++) {
			document.getElementById(rowNumber+".numeric.conditional."+i).options[0].selected = true;
			document.getElementById(rowNumber+".numeric.searchTerm."+i).value = null;
		}
	}
	else if (type == "concentration") {
		document.getElementById(rowNumber+".concentration.choices").options[0].selected = true;
		for (var i = 1; i <= 2; i++) {
			document.getElementById(rowNumber+".concentration.conditional."+i).options[0].selected = true;
			document.getElementById(rowNumber+".concentration.searchTerm."+i).value = null;
		}
	}
	document.getElementById(rowNumber+".text").style.display = "none";
	document.getElementById(rowNumber+".list").style.display = "none";
	document.getElementById(rowNumber+".mullist").style.display = "none";
	document.getElementById(rowNumber+".numeric").style.display = "none";
	document.getElementById(rowNumber+".concentration").style.display = "none";
	document.getElementById(rowNumber+".radio").style.display = "none";
	document.getElementById(rowNumber+".fields").options[0].selected = true;
	//document.getElementById(rowNumber+".category").options[0].selected = true;
	//filterFields(rowNumber);
	addFields(rowNumber);
}

function resetAll() {
	for (var i = 1; i <= 6; i++) {
		removeClause(i);
	}
	resetPressed = 1;
}

function removeAllOptions(selectbox) {
	for (var i = selectbox.options.length-1; i >= 0; i--) {
		selectbox.remove(i);
	}
}


function addListOptions(rowNumber, key, selectedId) {
	dwr.util.removeAllOptions(rowNumber+".list.choices");
	dwr.util.removeAllOptions(rowNumber+".mullist.choices");
	switch (key) {
		case "activity.id":
			getActivityList(rowNumber, selectedId);
			break;
		case "phyla.taxon.ncbiTaxon.id":
			getPhyleticSpecificityList(rowNumber, selectedId);
			break;
		case "toxin.lsidSpider.id":
			getSpeciesList(rowNumber, selectedId);
			break;
		case "toxin.lsidSpider.lsidCurrent.lsidTaxonomy.family":
			getDistinctFamiliesList(rowNumber, selectedId);
			break;
		case "common.id":
			getDistinctCommonNamesList(rowNumber, selectedId);
			break;
		case "ptran.ptranType.id":
			getPtransList(rowNumber, selectedId);
			break;
		case "toxin.toxinFamily.id":
			getToxinFamiliesList(rowNumber, selectedId);
			break;
		case "toxin.toxinFamily.toxinSuperFamily.id":
			getToxinSuperFamiliesList(rowNumber, selectedId);
			break;
		case "toxin.toxinGroup.id":
			getToxinGroupList(rowNumber, selectedId);
			break;
			
	}
}

function getActivityList(rowNumber, selectedId) {
	var publicStatus = getStatus("public", "publicStatus");
	var publishedStatus = getStatus("published", "publishedStatus");
	
	ToxinManager.getDistinctActivitiesByConditions(publicStatus, publishedStatus, 
		function(activities) {
		    if (activities.length > 0) {
				for (var i = 0; i < activities.length; i++) {
					var activity_id = activities[i][0];
					var activity_name = activities[i][1];
			 		var activity = { id:activity_id, name:activity_name };
		 			dwr.util.addOptions(rowNumber+".mullist.choices", [activity], "id", "name");
		 		}
		 		selectListOption(document.getElementById(rowNumber+".mullist.choices"), selectedId);
		    } else {
		    	setNullOptions(rowNumber, ".mullist.choices", selectedId);
		    }
		}
	 );
}
function getPhyleticSpecificityList(rowNumber, selectedId) {
	//TaxonManager.getAllTaxa(
	var publicStatus = getStatus("public", "publicStatus");
	var publishedStatus = getStatus("published", "publishedStatus");	
	ToxinManager.getTargetPhylaByConditions(publicStatus, publishedStatus, function(taxa) {
		if (taxa.length > 0) {
			for (var i = 0; i < taxa.length; i++) {
	 			var taxon = { id:taxa[i].ncbiTaxon.id, name:taxa[i].ncbiTaxon.name };
				dwr.util.addOptions(rowNumber+".mullist.choices", [taxon], "id", "name");
			}
			selectListOption(document.getElementById(rowNumber+".mullist.choices"), selectedId);
		} else {
			setNullOptions(rowNumber, ".mullist.choices", selectedId);
		}
	});
}
function getSpeciesList(rowNumber, selectedId) {
	var publicStatus = getStatus("public", "publicStatus");
	var publishedStatus = getStatus("published", "publishedStatus");
	

	ToxinManager.getToxinCountAndToxinSpeciesByConditions(publicStatus, publishedStatus, 
		function(spiders) {
			if (spiders.length > 0) {
				for (var i = 0; i < spiders.length; i++) {
					var spider = spiders[i][1];
					var spider_name = spider.lsidCurrent.genus + " " + spider.lsidCurrent.species;
					if (spider.imageFileName != null) {
						spider_name = spider_name + " *";
					}
			 		spider = { id:spider.id, name:spider_name };
		 			dwr.util.addOptions(rowNumber+".list.choices", [spider], "id", "name");
		 		}
		 		selectListOption(document.getElementById(rowNumber+".list.choices"), selectedId);
			} else {
				setNullOptions(rowNumber, ".list.choices", selectedId);
			}
		} 
	 );
}

function setNullOptions(rowNumber, conditional, selectedId) {
	var item = { id:"nil", name:"No options available" };
	dwr.util.addOptions(rowNumber+conditional, [item], "id", "name");
	selectListOption(document.getElementById(rowNumber+".list.choices"), selectedId);
}

function getDistinctFamiliesList(rowNumber, selectedId) {
	var publicStatus = getStatus("public", "publicStatus");
	var publishedStatus = getStatus("published", "publishedStatus");
	
	ToxinManager.getDistinctTaxonomicFamilyNamesByConditions(publicStatus, publishedStatus, 
		function(families) {
			if (families.length > 0) { 
				for (var i = 0; i < families.length; i++) {
					var family = { id:families[i], name:families[i] };
		 			dwr.util.addOptions(rowNumber+".list.choices", [family], "id", "name");
		 		}
		 		selectListOption(document.getElementById(rowNumber+".list.choices"), selectedId);
			} else {
				setNullOptions(rowNumber, ".list.choices", selectedId);
			}
		});
}
function getDistinctCommonNamesList(rowNumber, selectedId) {
	var publicStatus = getStatus("public", "publicStatus");
	var publishedStatus = getStatus("published", "publishedStatus");

	ToxinManager.getDistinctCommonNamesByConditions(publicStatus, publishedStatus, 
		function(names) {
			if (names.length > 0) {
				for (var i = 0; i < names.length; i++) {
					var name = { id:names[i][0], name:names[i][1] };
					var hasPhoto = 0;
					if (names[i][2] != null) {
						name = { id:names[i][0], name:names[i][1]+" *" };
					}
		 			dwr.util.addOptions(rowNumber+".list.choices", [name], "id", "name");
		 		}
		 		selectListOption(document.getElementById(rowNumber+".list.choices"), selectedId);
			} else {
				setNullOptions(rowNumber, ".list.choices", selectedId);
			}
		}
	 );
}

//function getToxinSuperFamiliesList(rowNumber, selectedId) {
//	ToxinSuperFamilyManager.getAllToxinSuperFamilies(
//     	function(toxinSuperFamilies) {
//     		dwr.util.addOptions(rowNumber+".list.choices", toxinSuperFamilies, "id", "name");
//     		selectListOption(document.getElementById(rowNumber+".list.choices"), selectedId);
//     	}
//     );
//}

function getToxinFamiliesList(rowNumber, selectedId) {
	var publicStatus = getStatus("public", "publicStatus");
	var publishedStatus = getStatus("published", "publishedStatus");
	ToxinManager.getToxinFamiliesByConditions(publicStatus, publishedStatus,
	//ToxinFamilyManager.getAllToxinFamilies(
     	function(toxinFamilies) {
		    if (toxinFamilies.length > 0) {
     		dwr.util.addOptions(rowNumber+".list.choices", toxinFamilies, "id", "name");
     		selectListOption(document.getElementById(rowNumber+".list.choices"), selectedId);
		    } else {
		    	setNullOptions(rowNumber, ".list.choices", selectedId);
		    }
     	}
     );
}
function getToxinGroupList(rowNumber, selectedId) {
	var publicStatus = getStatus("public", "publicStatus");
	var publishedStatus = getStatus("published", "publishedStatus");
	
	ToxinManager.getToxinCountAndToxinGroupsByConditions(publicStatus, publishedStatus,
     	function(toxinGroups) {
			if (toxinGroups.length > 0) {
     		var groupsArray = new Array();
     		for (var i = 0; i < toxinGroups.length; i++) {
     			var group = toxinGroups[i];
     			var id = group[1];
     			var name = group[2];
     			groupsArray[groupsArray.length] = { id:id, name:name };
     		}
     		dwr.util.addOptions(rowNumber+".list.choices", groupsArray, "id", "name");
     		selectListOption(document.getElementById(rowNumber+".list.choices"), selectedId);
			} else {
				setNullOptions(rowNumber, ".list.choices", selectedId);
			}
     	}
     );
}

function getPtransList(rowNumber, selectedId) {
	var publicStatus = getStatus("public", "publicStatus");
	var publishedStatus = getStatus("published", "publishedStatus");
	
	ToxinManager.getToxinCountAndPtransByConditions(publicStatus, publishedStatus,
		function(ptrans) {
			if (ptrans.length > 0) {
			var ptransArray = new Array();
			
				for (var i = 0; i < ptrans.length; i++) {
					var ptran = ptrans[i];
					var id = ptran[1];
					var name = ptran[2];
					ptransArray[ptransArray.length] = { id:id, name:name };
				}
				dwr.util.addOptions(rowNumber+".mullist.choices", ptransArray, "id", "name");
				selectListOption(document.getElementById(rowNumber+".mullist.choices"), selectedId);
			} else {
				setNullOptions(rowNumber, ".mullist.choices", selectedId);
			}
		}
	);
}
/*
function getPtransList(rowNumber, selectedId) {
	PtranTypeManager.getAllPtranTypes (
		function(ptrans) {
			dwr.util.addOptions(rowNumber+".mullist.choices", ptrans, "id", "name");
			selectListOption(document.getElementById(rowNumber+".mullist.choices"), selectedId);
		}
	);
}
*/

function getStatus(defaultStatus, statusType) {
	var status = defaultStatus;
	if (document.getElementById(statusType) != null) {
		status = document.getElementById(statusType).value;
	}
	return status;
}

function makeConcentrationChoices(rowNumber, selectedId, searchType) {
	var selectList = document.getElementById(rowNumber+".concentration.choices");
	selectList.options.length = 0;
	ItemManager.getItemsByCategoryId(14, 
		function(concentrations) {
			for (var i = 0; i < concentrations.length; i++) {
				var item = concentrations[i];
				if (item.name == 'pmol/g') {
					addOption(selectList, item.id, item.name);
				}
				if (searchType == 'phyla.ed' && item.id == 86) {					
					addOption(selectList, item.id, item.name);	
				}
			}
			selectListOption(document.getElementById(rowNumber+".concentration.choices"), selectedId);
		}
	);
}

function makeNumericConditionals(selectList) {
	addOption(selectList, "like", "=");
	addOption(selectList, "<", "<");
	addOption(selectList, "<=", "<=");
	addOption(selectList, ">", ">");
	addOption(selectList, ">=", ">=");
}

function makeTextConditionals(selectList) {
	addOption(selectList, "like", "like");
	addOption(selectList, "not like", "not like");
	addOption(selectList, "=", "is");
	addOption(selectList, "!=", "is not");
}

function makeListConditionals(selectList) {
	addOption(selectList, "=", "is");
	addOption(selectList, "!=", "is not");
}

function makeMulListConditionals(selectList) {
	addOption(selectList, "in", "include");
	addOption(selectList, "not in", "don't include");
}

function makeBooleanConditionals(selectList) {
	addOption(selectList, "and", "and");
	addOption(selectList, "or", "or");
	addOption(selectList, "and not", "but not");
}

function addOption(selectbox, value, text, group) {
	var optn = document.createElement("option");
	optn.text = text;
	optn.value = value;
	if (group != null) {
		optn.label = text;
		group.appendChild(optn);
	}
	else {
		selectbox.options.add(optn);
	}
}


function decode(value) {
	if (value == "&gt;") { return ">"; }
	else if (value == "&gt;=") { return ">="; }
	else if (value == "&lt;") { return "<"; }
	else if (value == "&lt;=") { return "<="; }
	else return value;
}

function selectListOption(list, selectedId) {
	if (selectedId != -1) { 		
		var options = list.options;
	 	for (var i = 0; i < options.length; i++) {
	 		if (options[i].value == selectedId) {
	 			options[i].selected = true;
	 			break;
	 		}
	 	}
	 }
}

function validateSearch(form) {	
	var fail = "";
	for (var i = 1; i <= 6; i++) {
		if (document.getElementById(i+".row").style.display == "") {
			var field = document.getElementById(i+".fields").value;
			var parts = field.split("-");
			if (parts[1] == "text") {
				var text = document.getElementById(i+".text.searchTerm").value;
				if (strip(text) == "") {
					fail = "please enter a search term for the text field\nor remove this search clause";
					document.getElementById(i+".text.searchTerm").focus();
				}
			}
			else if (parts[1] == "numeric") {
				var text = document.getElementById(i+".numeric.searchTerm.1").value;
				var text2 = document.getElementById(i+".numeric.searchTerm.2").value;				
				if (strip(text) == "") {
					fail = "please enter a number in the numeric field\nor remove this search clause";
					document.getElementById(i+".numeric.searchTerm.1").focus();
				} else if (parts[2] == "Date(toxin.releaseDate)") {
					fail = checkdate(text);
					if (text2 != "") {
						fail += checkdate(text2);
					}
				}
			}
			else if (parts[1] == "concentration") {
				var text = document.getElementById(i+".concentration.searchTerm.1").value;
				if (strip(text) == "") {
					fail += "please enter a number in the concentration field\nor remove this search clause";
					document.getElementById(i+".concentration.searchTerm.1").focus();
				}
			}
		}
	}
	
	if (fail =="") return true
	else {alert(fail); return false }

}

//function validateSearch() {
//	for (var i = 1; i <= 6; i++) {
//		if (document.getElementById(i+".row").style.display == "") {
//			var field = document.getElementById(i+".fields").value;
//			var parts = field.split("-");
//			if (parts[1] == "text") {
//				var text = document.getElementById(i+".text.searchTerm").value;
//				if (strip(text) == "") {
//					alert("please enter a search term for the text field\nor remove this search clause");
//					document.getElementById(i+".text.searchTerm").focus();
//					return false;
//				}
//			}
//			else if (parts[1] == "numeric") {
//				var text = document.getElementById(i+".numeric.searchTerm.1").value;
//				var text2 = document.getElementById(i+".numeric.searchTerm.2").value;				
//				if (strip(text) == "") {
//					alert("please enter a number in the numeric field\nor remove this search clause");
//					document.getElementById(i+".numeric.searchTerm.1").focus();
//					return false;
//				} else if (parts[2] == "toxin.releaseDate") {
//					checkdate(text);
//				}
////				if (parts[2] == "toxin.releaseDate") {
////					var text2 = document.getElementById(i+".numeric.searchTerm.2").value;
////					var errorMessage = isDate(strip(text));
////					//alert("Message" + errorMessage);
////					if (errorMessage = "" && text2 != "") {
////							errorMessage = isDate(strip(text2));
////							if (errorMessage != "") {
////								alert(errorMessage);
////								document.getElementById(i+".numeric.searchTerm.2").focus();
////								return false;			
////							}
////					} else if (errorMessage != "") {
////						alert(errorMessage);
////						document.getElementById(i+".numeric.searchTerm.1").focus();
////						return false;						
////					}
////				}					
//			}
//			else if (parts[1] == "concentration") {
//				var text = document.getElementById(i+".concentration.searchTerm.1").value;
//				if (strip(text) == "") {
//					alert("please enter a number in the concentration field\nor remove this search clause");
//					document.getElementById(i+".concentration.searchTerm.1").focus();
//					return false;
//				}
//			}
//		}
//	}
//	return null;
//}

function strip(string) {
	return string.replace(/^\s*|\s*$/g,'');
}

function checkdate(text){
	var divider = "";
	var invalid = true;
	var validformat=/^\d{2}\/\d{2}\/\d{4}$/ //Basic check for format validity
	if (validformat.test(text)) {
		divider = "/"
		invalid = false;
	}
	if (invalid) {
		return("The date format should be : dd/mm/yyyy")
	}
	else{ //Detailed check for valid date ranges
		var dayfield=text.split(divider)[0]
		var monthfield=text.split(divider)[1]
		var yearfield=text.split(divider)[2]
		var dayobj = new Date(yearfield, monthfield-1, dayfield) 
		if (dayobj.getDate()!=dayfield)	{	
			return("Please enter a valid day")
		} else if (dayobj.getMonth()+1!=monthfield){
			return ("Please enter a valid month")
		} else if (dayobj.getFullYear()!=yearfield){
			return ("Please enter a valid year")
		} else {
			return "";
		}
   }
}

function decodeDate(date) {
	var decoded = "";
	if (date.length>0) {
		var subs = date.substring(6, date.length-6);
		var parts = subs.split("-");
		decoded = parts[2] + "/" + parts[1] + "/" + parts[0];
	}
	return decoded;
}


