//AdvancedQueryLogic.js 
//  This file contains numerous javascript methods for the handling of logic on the 
//AdvancedQuery forms (Epitope, Bcell, MhcBind, Tcell, MhcElution).  

//The AdvancedQuery forms contain expandable sections which must remain expanded and populated
//if a user 'revizes' their query.  The forms also contain multiple 'Objects", each displaying
//different fields and field names depending on user selected values and the object type. The 
//user can also choose if particular objects may, must, or must not exist in query results,
//and if 'must not' is the selected option, make all fields of that object and 
//its sub-objects read only.  
//

//To handle the maintaining of field values once the user comes back to the page, without
//manually entering the values in PHP code, a temporary Div ('revise help container')
//is created by php which creates temporary hidden fields for each field in the form.
//These values are then read back by javascript and put into the fields where they belong
//via javascript.

//The method of most importance is the 'aq_load', where many methods are called initializing
//the page.  You should start there to learn more.


//this array holds the field names of all for, fields that are readonly (finder text fields)
//Since the 'AnyNoneSome' method will make all fields under a header selected for 'must not'
//become readonly, there must be a record of all fields that must remain read only
//in case a different value is selected.
var readOnlyArray;

//A good example of object literal syntax for javascript, but not actually a used piece of 
//code...
var FLAGS = {
    w3: function() {
        return !!(document.getElementById && document.createElement);
    }(),
    ie: function() {
    return (navigator.appName=='Microsoft Internet Explorer') ? true : false;        
    }()
};


//Subtype -> Object Type Map
//
//For all object fields, the user may select a particular subtype, where many subtypes
//map to a single object type.  This is that map. From different object types,
//different fields are displayed
var subtypeMap = new Object();
subtypeMap['Peptide, no natural source'] = "Sequence Molecule No Natural Source";
subtypeMap['Carbohydrate'] = "Accession Non-Sequence Molecule";
subtypeMap['Lipid'] = "Accession Non-Sequence Molecule";
subtypeMap['Fatty acid'] = "Accession Non-Sequence Molecule";
subtypeMap['Glycolipid'] = "Accession Non-Sequence Molecule";
subtypeMap['Peptidoglycan'] = "Accession Non-Sequence Molecule";
subtypeMap['Other Non-Sequence'] = "Accession Non-Sequence Molecule";
subtypeMap['Protein'] = "Accession Sequence Molecule";
subtypeMap['Multi-Chain protein'] = "Multi-Chain Molecule";
subtypeMap['Peptide from protein'] = "Fragment of a Natural Sequence Molecule";
subtypeMap['Carbohydrate fragment'] = "Fragment of a Natural Non-Sequence Molecule";
subtypeMap['Lipid fragment'] = "Fragment of a Natural Non-Sequence Molecule";
subtypeMap['Fatty acid fragment'] = "Fragment of a Natural Non-Sequence Molecule";
subtypeMap['Glycolipid fragment'] = "Fragment of a Natural Non-Sequence Molecule";
subtypeMap['Peptidoglycan fragment'] = "Fragment of a Natural Non-Sequence Molecule";
subtypeMap['Other fragment'] = "Fragment of a Natural Non-Sequence Molecule";
subtypeMap['Discontinuous protein residues'] = "Discontinuous Region on Accession Sequence Molecule";
subtypeMap['Polysaccharide repeating unit'] = "Discontinuous Region on Accession Non-Sequence Molecule";
subtypeMap['Region on multi-chain protein'] = "Region on Multi-Chain Molecule";
subtypeMap['Derivative of Organism'] = "Derivative of Organism";
subtypeMap['BAL (bronchoalveolar lavage)'] = "Organism Tissue";
subtypeMap['Blood'] = "Organism Tissue";
subtypeMap['Bone Marrow'] = "Organism Tissue";
subtypeMap['Breast'] = "Organism Tissue";
subtypeMap['CNS'] = "Organism Tissue";
subtypeMap['CSF (cerebrospinal fluid)'] = "Organism Tissue";
subtypeMap['Embryo'] = "Organism Tissue";
subtypeMap['Eye'] = "Organism Tissue";
subtypeMap['Gastrointestinal tract'] = "Organism Tissue";
subtypeMap['Heart'] = "Organism Tissue";
subtypeMap['Kidney'] = "Organism Tissue";
subtypeMap['Liver'] = "Organism Tissue";
subtypeMap['Lung'] = "Organism Tissue";
subtypeMap['Lymph Node'] = "Organism Tissue";
subtypeMap['Lymphoid'] = "Organism Tissue";
subtypeMap['Other'] = "Organism Tissue";
subtypeMap['Pancreas'] = "Organism Tissue";
subtypeMap['Peritoneal fluid'] = "Organism Tissue";
subtypeMap['Salivary gland'] = "Organism Tissue";
subtypeMap['Skin'] = "Organism Tissue";
subtypeMap['Spleen'] = "Organism Tissue";
subtypeMap['Synovial Fluid'] = "Organism Tissue";
subtypeMap['Thymus'] = "Organism Tissue";
subtypeMap['Umbilical cord blood'] = "Organism Tissue";
subtypeMap['Recombinant Organism'] = "Recombinant Organism";
subtypeMap['Plasmid'] = "Plasmid";
subtypeMap['Phage display'] = "Object Library";
subtypeMap['Yeast display'] = "Object Library";
subtypeMap['Bacterial display'] = "Object Library";
subtypeMap['Ribosomal display'] = "Object Library";
subtypeMap['Peptide conjugate'] = "Complexed Molecule";
subtypeMap['Protein conjugate'] = "Complexed Molecule";
subtypeMap['Multi-Antigenic Peptide (MAP, branched)'] = "Complexed Molecule";
subtypeMap['Peptide Repeat Sequence (linear)'] = "Complexed Molecule";
subtypeMap['Peptide plus Multi-Chain'] = "Complexed Molecule";
subtypeMap['Fatty acid conjugate'] = "Complexed Molecule";
subtypeMap['Glycolipid conjugate'] = "Complexed Molecule";
subtypeMap['Nucleotide conjugate'] = "Complexed Molecule";
subtypeMap['Other Complexed Molecule'] = "Complexed Molecule";
subtypeMap['Infected Cell'] = "Infected Cell";
subtypeMap['Transfected Cell'] = "Transfected Cell";
subtypeMap['Pulsed Cell'] = "Pulsed Cell";
subtypeMap['Ascitic fluid (Hybridoma)'] = "Experimentally Generated Fluids Containing Antibodies";
subtypeMap['Culture supernatant (Hybridoma)'] = "Experimentally Generated Fluids Containing Antibodies";
subtypeMap['Culture supernatant (B cell)'] = "Experimentally Generated Fluids Containing Antibodies";
subtypeMap['Cell'] = "Cell";
subtypeMap['Organism'] = "Organism";
// end subtype -> object type map



//begin epitope relation -> subtype map
//
//This mapps the available object subtypes for a given epitope relation.
var eRelationToSubtypes = new Array();
eRelationToSubtypes[""] = [""];
eRelationToSubtypes['Epitope'] = [""];
eRelationToSubtypes['Source Antigen'] = ['','Protein','Carbohydrate','Lipid','Fatty acid','Glycolipid','Peptidoglycan','Other Non-Sequence','Multi-Chain protein'];
eRelationToSubtypes['Source Organism'] = ['Organism'];
eRelationToSubtypes['Derivative of Source Organism'] = ['Derivative of Organism'];
eRelationToSubtypes['Fragment of Source Antigen'] = ['','Peptide from protein','Carbohydrate fragment','Lipid fragment','Fatty acid fragment','Glycolipid fragment','Peptidoglycan fragment','Other fragment'];
eRelationToSubtypes['Other'] = ['','Peptide from protein','Peptide, no natural source','Protein','Organism','Carbohydrate fragment','Lipid fragment','Fatty acid fragment','Glycolipid fragment','Peptidoglycan fragment','Other fragment','Carbohydrate','Lipid','Fatty acid','Glycolipid','Peptidoglycan','Other Non-Sequence','Multi-Chain protein','Derivative of Organism'];
eRelationToSubtypes['Structurally Related'] = ['','Peptide from protein','Peptide, no natural source','Protein','Organism','Carbohydrate fragment','Lipid fragment','Fatty acid fragment','Glycolipid fragment','Peptidoglycan fragment','Other fragment','Carbohydrate','Lipid','Fatty acid','Glycolipid','Peptidoglycan','Other Non-Sequence','Multi-Chain protein','Derivative of Organism'];
eRelationToSubtypes['Taxonomic Parent'] = ['','Peptide from protein','Protein','Organism','Carbohydrate fragment','Lipid fragment','Fatty acid fragment','Glycolipid fragment','Peptidoglycan fragment','Other fragment','Carbohydrate','Lipid','Fatty acid','Glycolipid','Peptidoglycan','Other Non-Sequence','Multi-Chain protein','Derivative of Organism'];
eRelationToSubtypes['Taxonomic Sibling'] = ['','Peptide from protein','Protein','Organism','Carbohydrate fragment','Lipid fragment','Fatty acid fragment','Glycolipid fragment','Peptidoglycan fragment','Other fragment','Carbohydrate','Lipid','Fatty acid','Glycolipid','Peptidoglycan','Other Non-Sequence','Multi-Chain protein','Derivative of Organism'];
eRelationToSubtypes['Taxonomic Child'] = ['','Peptide from protein','Protein','Organism','Carbohydrate fragment','Lipid fragment','Fatty acid fragment','Glycolipid fragment','Peptidoglycan fragment','Other fragment','Carbohydrate','Lipid','Fatty acid','Glycolipid','Peptidoglycan','Other Non-Sequence','Multi-Chain protein','Derivative of Organism'];
eRelationToSubtypes['Other Structure from Source Organism'] = ['','Peptide from protein','Protein','Organism','Carbohydrate fragment','Lipid fragment','Fatty acid fragment','Glycolipid fragment','Peptidoglycan fragment','Other fragment','Carbohydrate','Lipid','Fatty acid','Glycolipid','Peptidoglycan','Other Non-Sequence','Multi-Chain protein','Derivative of Organism'];

//end er -> subtype map

//These are all of the possible object fields 
var objectFields = ['ObjectMultiChainMoleculeName','ObjectCellType','ObjectTissueType','ObjectOrigin','ObjectDerivativeType','ObjectPrimaryMoleculeSequence','ObjectRegion',   'ObjectPrimaryMoleculeModifiedSequence','ObjectPrimaryMoleculeModification',   'ObjectPrimaryMoleculeSourceId','ObjectPrimaryMoleculeSourceName','ObjectPrimaryMoleculeSourceAccessionNumber', 'ObjectStartingPosition','ObjectEndingPosition',   'ObjectOrganismId','ObjectOrganismName',   'ObjectSecondaryMoleculeModifiedSequence','ObjectSecondaryMoleculeModification',   'ObjectSecondaryMoleculeSourceId','ObjectSecondaryMoleculeSourceName','ObjectSecondaryMoleculeSourceAccessionNumber','ObjectSecondaryMoleculeSourceChemicalType',    'ObjectSecondaryOrganismId','ObjectSecondaryOrganismName','ObjectGenericOrganismName','ObjectGenericSourceName'];

//this method initializes the read only array
var aqReadOnlyHelper = {	
	initArray:function(x)
	{		
		var inputs = document.getElementsByTagName('input');
							
		//getting all readonly (finder) fields for switching readonly status later
		for(var idx=0; idx < inputs.length; idx++){
			//if(idx>50 && idx < 60)alert(inputs[idx].nodeName+ " : "+ inputs[idx].readOnly);		
			if(inputs[idx].readOnly==true){			
				x.push(inputs[idx]);
			}
		}		
		return x;	
	}
	
}

function testSumpin(spot){
	// why blank buttons?
	alert("Pause! " + spot);
	var	buttonRow = document.getElementById("EpitopeObjectGenericSourceName");
	var button0 = buttonRow.getElementsByTagName('input')[0];
	alert("EpitopeGeneric Source Molecule button0 is a : "+button0.nodeName + " with value " + button0.value);
	var button1 = buttonRow.getElementsByTagName('input')[1];
	alert("EpitopeGeneric Source Molecule button1 is a : "+button1.nodeName + " with value " + button1.value);
	var button2 = buttonRow.getElementsByTagName('input')[2];
	if(button2 != null)
	alert("EpitopeGeneric Source Molecule button2 is a : "+button2.nodeName + " with value " + button2.value);
	
	//lets see
}



//This is the main method of this file, it gets called as soon as the body loads
function aq_load(objectFieldTypeArray, defaultOpenArray){
	readOnlyArray = new Array();						
				
	//initializes subtype dropdown values
	initializeSubtypeLists();
	
	//reassigning php created temp variables to assist in revising query	
	prePopulate(); 
				
	//We check to see if any object fields are initialized 
	//(indicating user is on the page afterhitting revise)
	//so we will know whether to clear and hide.	
	//Takes the array of objectFieldTypes (Epitope Object, Epitope Related Object)
	//Returns an array of booleans indicating whether populated or not		
	var objectsPopulated = getPopulatedObjects(objectFieldTypeArray);
									
	//sets object fields that are displayed	
	for(var i=0;i< objectFieldTypeArray.length;i++){
		
		if(!objectsPopulated[i]){						
			clearAndHideFields(objectFieldTypeArray[i]);							
			setObjectDefaults(objectFieldTypeArray[i]);			
		}
		else{
			hideObjectFields(objectFieldTypeArray[i]);
			var subtype = document.forms[1].elements['gov_nih_niaid_iedb_common_domain_field_impl_'+
						 objectFieldTypeArray[i] +'ObjectSubtype'];			
			subtypeLogicNoClearing(subtype);
		}	
	}		
	
	//we have to create hidden fields for each object subtype value to populate,
	//since IE does not keep the values of dynamically populated dropdown lists.	
	//if(FLAGS.ie){			
	//	for(var j = 0; j < objectFieldTypeArray.length; j++){
			//hidden subtype prepender
	//		var hsApender = "_hidden";
	//		var hsFieldName = 'gov_nih_niaid_iedb_common_domain_field_impl_'+
	//							 objectFieldTypeArray[j] +'ObjectSubtype' +hsApender;
	//		var hsField = document.forms[1].elements[hsFieldName];						
	//		if(hsField){
	//			var subtype = document.forms[1].elements['gov_nih_niaid_iedb_common_domain_field_impl_'+
	//							 objectFieldTypeArray[j] +'ObjectSubtype'];
	//			subtype.value = hsField.value;
	//			subtypeLogicNoClearing(subtype);				 													
	//		}				
	//	} 
	//}
	
	//makes number selector 'between' box #2 visible
	maintainPopulatedBetweenBoxes();
	

		
	//looks for populated data
	openPopulatedSections(defaultOpenArray);		


			
	//opens headers we want by default
	for(var k=0;k< defaultOpenArray.length;k++){		
		var temp = document.getElementById(defaultOpenArray[k]);		
		//alert(defaultOpenArray[k]);
		//we escape populated reference types since we handled it below
		//we handled it above because the DOM structure is slightly different
		if(temp.id != "articleFieldsHeader" && temp.id != "submissionFieldsHeader" )					
			loadCollapsedSection(temp);	
	}
	

	
	//Expand populated reference type section.
	//currently (07/22/2010) if a user leaves a article field populated, then clicks to go
	//to submission, then back, the fields will remain populated.
	//we assume intelligence on the users part that they will not try
	//searching on both a submission and an article at the same time.
	var refType = document.forms[1].elements['gov_nih_niaid_iedb_common_domain_field_impl_referenceType'];
	for(var z = 0; z < refType.length ; z++){
	var sel = refType[z];
		if(refType[z].value == refType.value){
			refType[z].checked = true;
			refTypeLogic(refType[z]);
			break;
		}
		if(refType[z].checked == true)			
			refTypeLogic(refType[z]);
	}
	

	//this allows the readonly finder fields to stay read only after removing the 'none' condition
	//from anyNoneSome. We will reference this array to know what fields should not be changed back			
	readOnlyArray = new Array();
	readOnlyArray = aqReadOnlyHelper.initArray(readOnlyArray);
	
	//set correct AnyNoneSome status's following Revise
	var radios = document.getElementsByTagName('input');
	for(var q=0; q < radios.length; q++){
		if(radios[q].value == 'absent' && radios[q].checked==true)
			anyNoneSome(radios[q]);
	}
}

//makes a collapsed section expand
function loadCollapsedSection(x){
	//alert("In loadCollapsedSection node name x: " + x.nodeName);
	
	var a;
	//MS IE navigates nodes differently than firefox
	if(navigator.appName=='Microsoft Internet Explorer'){		
		a = x.childNodes[0].childNodes[0];	
	}
	else{	
		a = x.childNodes[1].childNodes[0];	
	}
	expandCollapse(a);		
}

//the initial objects shown, before an epitope relation or subtype is selected
function setObjectDefaults(objectFieldType){		
		displayRowName(objectFieldType, 'ObjectGenericSourceName', 'Source Molecule');
		//displayRowName(objectFieldType, 'ObjectPrimaryMoleculeSourceAccessionNumber', 'Molecule Accession');
		displayRowName(objectFieldType, 'ObjectGenericOrganismName', 'Source Organism');
}

function clearAndHideFields(objectFieldType){

	//objectFields is a global array of all fields that exist in the object sections
	for(var i=0; i < objectFields.length; i++){
		clearField(objectFieldType, objectFields[i]);
		hideField(objectFieldType, objectFields[i]);
	}
	
}

function clearObjectFields(objectFieldType){

	//objectFields is a global array of all fields that exist in the object sections
	for(var i=0; i < objectFields.length; i++){
		clearField(objectFieldType, objectFields[i]);
	}	
}

function hideObjectFields(objectFieldType){

	//objectFields is a global array of all fields that exist in the object sections
	for(var i=0; i < objectFields.length; i++){
		hideField(objectFieldType, objectFields[i]);
	}	
}

function clearField(objectFieldType, x){

	//if(x == "ObjectPrimaryMoleculeModification")
	//			debugger;

	var field = document.getElementById(objectFieldType+ x);
			
	if(field == null){
		objectFieldType = objectFieldType.replace("[]","");
		field = document.getElementById(objectFieldType+ x);
	}
			
	if(field != null){
		var input1 = field.getElementsByTagName('input')[0];
		var input2 = field.getElementsByTagName('input')[1];
		var textarea = field.getElementsByTagName('textarea')[0];
		var select = field.getElementsByTagName('select')[0];				
		
		if(input1 != null && input1.type.toUpperCase() != 'BUTTON'){	
			input1.value='';
		}
		
		if(input2 != null && input2.type.toUpperCase() != 'BUTTON'){	
			input2.value='';
		}
		
		if(textarea != null){
			textarea.value='';
		}
		
		if(select != null){
			//debugging start			
			//var debug = "ClearField: ID "+ field.id;
			var options = select.options;
			//debug += " Select selected length is "+ options.length ;
			for(var i = 0; i < options.length ; i++){
				if(options[i].selected && options[i].value != "Equal To" && options[i].selected && options[i].value != "Exact"){
					//debug += " "+i+"=" + options[i].value +" no longer selected";
					options[i].selected = false;
				}
			}						
			//debugOut(debug);
			//debugging stop
			if(select.value != "Equal To" && select.value != "Exact")			
				select.value='';									
		}
			
	}
	
	
	
}

function hideField(objectFieldType, x){

	var field = document.getElementById(objectFieldType+ x);
	
	if(field == null){
		objectFieldType = objectFieldType.replace("[]","");
		field = document.getElementById(objectFieldType+ x);
	}
			
	if(field != null){		
		field.style.display='none';
	}
}

function displayRow(objectFieldType, x){
	var field = document.getElementById(objectFieldType+ x);
	
	if(field == null){
		objectFieldType = objectFieldType.replace("[]","");
		field = document.getElementById(objectFieldType+ x);
	}
	
	if(field != null){	
		if(navigator.appName=='Microsoft Internet Explorer'){
			field.style.display='inline';
		}
		else
		{		
			field.style.display='table-row';
		} 	
	}	
}

function displayRowName(objectFieldType, x, name){
	displayRow(objectFieldType, x);
	
	try{
		var field = document.getElementById(objectFieldType+ x);
		
		if(field == null){
			objectFieldType = objectFieldType.replace("[]","");
			field = document.getElementById(objectFieldType+ x);
		}
		
		field.getElementsByTagName('td')[0].getElementsByTagName('span')[0].innerHTML=name;
	}
	catch(err){
		alert("Error " + objectFieldType+ x);	
	}
}

function refTypeLogic(selector){
	
	if(selector.value=='Literature'){	
		document.getElementById('litSection').style.display='block';
		document.getElementById('submissionSection').style.display='none';		
	}
	else if(selector.value=='Submission'){	
		document.getElementById('litSection').style.display='none';
		document.getElementById('submissionSection').style.display='block';
	}
	else{	
		document.getElementById('litSection').style.display='none';
		document.getElementById('submissionSection').style.display='none';
	}
}

function numberSelector(x){
	if(x.value == 'Between'){	
	x.parentNode.getElementsByTagName('span')[0].style.display='inline';		
	}
	else{
		x.parentNode.getElementsByTagName('span')[0].getElementsByTagName('input')[0].value='';
		x.parentNode.getElementsByTagName('span')[0].style.display='none';
	}	
}

function expandCollapse(x){
		
	var _table = x.parentNode;
	while(_table.nodeName.toUpperCase() != "TABLE")							
		_table = _table.parentNode;
		
	var tbody = _table.getElementsByTagName('tbody')[0];
					
	var expandedInner = "&nbsp;<img src=\"images/minusmid.gif\">&nbsp;";
	var collapsedInner = "&nbsp;<img src=\"images/plusmid.gif\">&nbsp;";
	
	//alert(x.innerHTML);
	try{			
	if(x.innerHTML.match("minusmid.gif")){
		//alert("In expandCollapse expanded. node name: " + x.nodeName);
		x.innerHTML=collapsedInner;		
		tbody.style.display='none';
		//for show hide fields label
		//x.parentNode.parentNode.getElementsByTagName('span')[1].style.display='none';	
	}
	else if(x.innerHTML.match("plusmid.gif")){
		//alert("In expandCollapse collapsed. node name: " + x.nodeName);
		x.innerHTML=expandedInner;
		//for show hide fields label
		//x.parentNode.parentNode.getElementsByTagName('span')[1].style.display='inline';			
		if(navigator.appName=='Microsoft Internet Explorer'){
			tbody.style.display='block';
		}
		else{	
			tbody.style.display='table-row-group';
		}
	}
	
	}catch(e){
		//debugger;
		//alert(x.nodeName);		
	}
	
}


function subtypeLogic(x){

	//var objectTable = document.getElementById(objectFieldType + "ObjectTable");
	//working up DOM tree to get to the parent table from the selector that resides in it
	//var objectTable = x.parentNode.parentNode.parentNode.parentNode.parentNode;
	
	//setting the hidden field associated with the object subtype
	var hsField = document.forms[1].elements[x.name+"_hidden"];
	if(hsField)
		hsField.value = x.value;		
	
	//getting the objectFieldType from the subtype list (x) id
	var name = x.name;	
	name = name.replace("gov_nih_niaid_iedb_common_domain_field_impl_", "");		
	var objectFieldType = name.replace("ObjectSubtype","");	
	var objectType = '';
	
	//subtype to type mapping
	//if subtype = x or i, or j or..., then object type must = y	
	objectType = subtypeMap[x.value];
		
	//now that we have the subtype mapped to an object type, display the type
	//document.getElementById(objectFieldType+ 'ObjectType').getElementsByTagName('input')[0].value=objectType;
	//commented out because object type is no longer displayed
	
			
	//make all fields clear and disapear	
	clearAndHideFields(objectFieldType);
  	

  
	//initialize fields that are meant to appear
	objectFieldDisplay(objectType, objectFieldType);
}

function subtypeLogicNoClearing(x){
	
	//getting the objectFieldType from the subtype list (x) id
	var name = x.name;	
	name = name.replace("gov_nih_niaid_iedb_common_domain_field_impl_", "");		
	var objectFieldType = name.replace("ObjectSubtype","");	
	var objectType = '';
	
	//subtype to type mapping
	//if subtype = x or i, or j or..., then object type must = y	
	objectType = subtypeMap[x.value];

	//initialize fields that are meant to appear
	objectFieldDisplay(objectType, objectFieldType);	
	
}

//this function determines what fields are shown for an object, depending on the
//object type
function objectFieldDisplay(objectType, objectFieldType){
			if(objectType == 'Sequence Molecule No Natural Source'){
				 displayRow(objectFieldType, 'ObjectSubtype');
				 displayRowName(objectFieldType, 'ObjectPrimaryMoleculeSequence', 'Linear Sequence');
				 displayRowName(objectFieldType, 'ObjectPrimaryMoleculeModifiedSequence', 'Modified Residue(s)');
				 displayRowName(objectFieldType, 'ObjectPrimaryMoleculeModification', 'Modification(s)');
			}
			
			else if(objectType == 'Accession Non-Sequence Molecule'){
				 displayRow(objectFieldType, 'ObjectSubtype');
				 displayRowName(objectFieldType, 'ObjectPrimaryMoleculeSourceName', 'Molecule Name');
				 displayRowName(objectFieldType, 'ObjectOrganismName', 'Source Organism');
			}
			
			else if(objectType == 'Accession Sequence Molecule'){
				 displayRow(objectFieldType, 'ObjectSubtype');
				 displayRowName(objectFieldType, 'ObjectPrimaryMoleculeModifiedSequence', 'Modified Residue(s)');
				 displayRowName(objectFieldType, 'ObjectPrimaryMoleculeModification', 'Modification(s)');
				 displayRowName(objectFieldType, 'ObjectPrimaryMoleculeSourceName', 'Molecule Name');
				 displayRowName(objectFieldType, 'ObjectOrganismName', 'Organism');
			}
			
			else if(objectType == 'Multi-Chain Molecule'){
				 displayRow(objectFieldType, 'ObjectSubtype');
				 displayRowName(objectFieldType, 'ObjectMultiChainMoleculeName', 'Molecule Name');
				 displayRowName(objectFieldType, 'ObjectPrimaryMoleculeModifiedSequence', 'Modified Residue(s)');
				 displayRowName(objectFieldType, 'ObjectPrimaryMoleculeModification', 'Modification(s)');
				 displayRowName(objectFieldType, 'ObjectPrimaryMoleculeSourceName', 'Chain 1 Accession Name');
				 displayRowName(objectFieldType, 'ObjectOrganismName', 'Source Organism');
				 displayRowName(objectFieldType, 'ObjectSecondaryMoleculeModifiedSequence', 'Modified Residue(s)');
				 displayRowName(objectFieldType, 'ObjectSecondaryMoleculeModification', 'Modification(s)');
				 displayRowName(objectFieldType, 'ObjectSecondaryMoleculeSourceName', 'Chain 2 Name');
				 displayRowName(objectFieldType, 'ObjectSecondaryOrganismName', 'Source Organism');
			}
			
			else if(objectType == 'Fragment of a Natural Sequence Molecule'){
				 displayRow(objectFieldType, 'ObjectSubtype');
				 displayRowName(objectFieldType, 'ObjectPrimaryMoleculeSequence', 'Linear Sequence');
				 displayRowName(objectFieldType, 'ObjectPrimaryMoleculeModifiedSequence', 'Modified Residue(s)');
				 displayRowName(objectFieldType, 'ObjectPrimaryMoleculeModification', 'Modification(s)');
				 displayRowName(objectFieldType, 'ObjectStartingPosition', 'Starting Position');
				 displayRowName(objectFieldType, 'ObjectEndingPosition', 'Ending Position');
				 displayRowName(objectFieldType, 'ObjectSecondaryMoleculeSourceName', 'Source Molecule Name');
				 displayRowName(objectFieldType, 'ObjectSecondaryOrganismName', 'Source Organism');
			}
			
			else if(objectType == 'Fragment of a Natural Non-Sequence Molecule'){
				 displayRow(objectFieldType, 'ObjectSubtype');
				 displayRowName(objectFieldType, 'ObjectPrimaryMoleculeSourceName', 'Name');
				 displayRowName(objectFieldType, 'ObjectSecondaryMoleculeSourceName', 'Source Name');
				 displayRowName(objectFieldType, 'ObjectSecondaryOrganismName', 'Source Organism');
			}
			
			else if(objectType == 'Discontinuous Region on Accession Sequence Molecule'){
				 displayRow(objectFieldType, 'ObjectSubtype');
				 displayRowName(objectFieldType, 'ObjectRegion', 'Discontinuous Residues');
				 displayRowName(objectFieldType, 'ObjectSecondaryMoleculeModifiedSequence', 'Modified Residue(s)');
				 displayRowName(objectFieldType, 'ObjectSecondaryMoleculeModification', 'Modification(s)');
				 displayRowName(objectFieldType, 'ObjectSecondaryMoleculeSourceName', 'Source Name');
				 displayRowName(objectFieldType, 'ObjectSecondaryOrganismName', 'Source Organism');
			}
			
			else if(objectType == 'Discontinuous Region on Accession Non-Sequence Molecule'){
				 displayRow(objectFieldType, 'ObjectSubtype');
				 displayRowName(objectFieldType, 'ObjectPrimaryMoleculeSourceName', 'Name');
				 displayRowName(objectFieldType, 'ObjectSecondaryMoleculeSourceName', 'Source Name');
				 displayRowName(objectFieldType, 'ObjectSecondaryOrganismName', 'Source Organism');
			}
			
			else if(objectType == 'Region on Multi-Chain Molecule'){
				 displayRow(objectFieldType, 'ObjectSubtype');
				 displayRowName(objectFieldType, 'ObjectMultiChainMoleculeName', 'Molecule Name');
				 displayRowName(objectFieldType, 'ObjectRegion', 'Discontinuous Residues');
				 displayRowName(objectFieldType, 'ObjectPrimaryMoleculeModifiedSequence', 'Modified Residue(s)');
				 displayRowName(objectFieldType, 'ObjectPrimaryMoleculeModification', 'Modification(s)');
				 displayRowName(objectFieldType, 'ObjectPrimaryMoleculeSourceName', 'Chain 1 Name');
				 displayRowName(objectFieldType, 'ObjectOrganismName', 'Source Organism');
				 displayRowName(objectFieldType, 'ObjectSecondaryMoleculeModifiedSequence', 'Modified Residue(s)');
				 displayRowName(objectFieldType, 'ObjectSecondaryMoleculeModification', 'Modification(s)');
				 displayRowName(objectFieldType, 'ObjectSecondaryMoleculeSourceName', 'Chain 2 Name');
				 displayRowName(objectFieldType, 'ObjectSecondaryOrganismName', 'Source Organism');
			}
			
			else if(objectType == 'Derivative of Organism'){
				 displayRow(objectFieldType, 'ObjectSubtype');
				 displayRowName(objectFieldType, 'ObjectDerivativeType', 'Derivative Type');
				 displayRowName(objectFieldType, 'ObjectOrganismName', 'Source Organism');
			}
			
			else if(objectType == 'Organism Tissue'){
				 displayRow(objectFieldType, 'ObjectSubtype');
				 displayRowName(objectFieldType, 'ObjectTissueType', 'Tissue Type');
				 displayRowName(objectFieldType, 'ObjectOrganismName', 'Source Organism');
			}
			
			else if(objectType == 'Recombinant Organism'){
				 displayRow(objectFieldType, 'ObjectSubtype');
				 displayRowName(objectFieldType, 'ObjectPrimaryMoleculeSequence', 'Peptide Sequence');
				 displayRowName(objectFieldType, 'ObjectPrimaryMoleculeSourceName', 'Peptide Source Name');
				 displayRowName(objectFieldType, 'ObjectOrganismName', 'Recombinant Organism');
				 displayRowName(objectFieldType, 'ObjectSecondaryMoleculeSourceName', 'Molecule Name');
				 displayRowName(objectFieldType, 'ObjectSecondaryOrganismName', 'Molecule Source Organism');
			}
			
			else if(objectType == 'Plasmid'){
				 displayRow(objectFieldType, 'ObjectSubtype');
				 displayRowName(objectFieldType, 'ObjectPrimaryMoleculeSequence', 'Peptide Sequence');
				 displayRowName(objectFieldType, 'ObjectPrimaryMoleculeSourceName', 'Peptide Source Name');
				 displayRowName(objectFieldType, 'ObjectOrganismName', 'Peptide Source Organism');
				 displayRowName(objectFieldType, 'ObjectSecondaryMoleculeSourceName', 'Molecule Name');
				 displayRowName(objectFieldType, 'ObjectSecondaryOrganismName', 'Molecule Source Organism');
			}
			
			else if(objectType == 'Object Library'){
				 displayRow(objectFieldType, 'ObjectSubtype');
			}
			
			else if(objectType == 'Complexed Molecule'){
				 displayRow(objectFieldType, 'ObjectSubtype');
				 displayRowName(objectFieldType, 'ObjectPrimaryMoleculeSequence', 'Peptide Sequence');
				 displayRowName(objectFieldType, 'ObjectPrimaryMoleculeModifiedSequence', 'Peptide Modified Sequence');
				 displayRowName(objectFieldType, 'ObjectPrimaryMoleculeModification', 'Peptide Modification');
				 displayRowName(objectFieldType, 'ObjectPrimaryMoleculeSourceName', 'Peptide Source Name');
				 displayRowName(objectFieldType, 'ObjectOrganismName', 'Peptide Source Organism');
				 displayRowName(objectFieldType, 'ObjectSecondaryMoleculeSourceName', 'Molecule Name');
				 displayRowName(objectFieldType, 'ObjectSecondaryOrganismName', 'Molecule Source Organism');
			}
			
			else if(objectType == 'Infected Cell'){
				 displayRow(objectFieldType, 'ObjectSubtype');
				 displayRowName(objectFieldType, 'ObjectCellType', 'Cell Type');
				 displayRowName(objectFieldType, 'ObjectOrganismName', 'Cell Source Organism');
			}
			
			else if(objectType == 'Transfected Cell'){
				 displayRow(objectFieldType, 'ObjectSubtype');
				 displayRowName(objectFieldType, 'ObjectCellType', 'Cell Type');
				 displayRowName(objectFieldType, 'ObjectPrimaryMoleculeSequence', 'Peptide Sequence');
				 displayRowName(objectFieldType, 'ObjectPrimaryMoleculeSourceName', 'Peptide Source Name');
				 displayRowName(objectFieldType, 'ObjectOrganismName', 'Cell Source Organism');
				 displayRowName(objectFieldType, 'ObjectSecondaryMoleculeSourceName', 'Molecule Name');
				 displayRowName(objectFieldType, 'ObjectSecondaryOrganismName', 'Molecule Source Organism');
			}
			
			else if(objectType == 'Pulsed Cell'){
				 displayRow(objectFieldType, 'ObjectSubtype');
				 displayRowName(objectFieldType, 'ObjectCellType', 'Cell Type');
				 displayRowName(objectFieldType, 'ObjectPrimaryMoleculeSequence', 'Peptide Sequence');
				 displayRowName(objectFieldType, 'ObjectPrimaryMoleculeSourceName', 'Peptide Source Name');
				 displayRowName(objectFieldType, 'ObjectOrganismName', 'Cell Source Organism');
				 displayRowName(objectFieldType, 'ObjectSecondaryMoleculeSourceName', 'Molecule Name');
				 displayRowName(objectFieldType, 'ObjectSecondaryOrganismName', 'Molecule Source Organism');
			}
			
			else if(objectType == 'Experimentally Generated Fluids Containing Antibodies'){
				 displayRow(objectFieldType, 'ObjectSubtype');
				 displayRowName(objectFieldType, 'ObjectOrganismName', 'Organism');
			}
			
			else if(objectType == 'Cell'){
				 displayRow(objectFieldType, 'ObjectSubtype');
				 displayRowName(objectFieldType, 'ObjectCellType', 'Cell Type');
				 displayRowName(objectFieldType, 'ObjectTissueType', 'Tissue Type');
				 displayRowName(objectFieldType, 'ObjectOrigin', 'Cell Culture Conditions');
			}
			
			else if(objectType == 'Organism'){
				 displayRow(objectFieldType, 'ObjectSubtype');
				 displayRowName(objectFieldType, 'ObjectOrganismName', 'Organism');
			}
					
	else{
		//alert("No object type has been selected for "+objectFieldType+", setting setObjectDefaults");
		setObjectDefaults(objectFieldType);		
	}

}


function anyNoneSome(x){
	var tbody = x.parentNode.parentNode.parentNode.parentNode.parentNode.lastChild;	
	if(x.value=='absent'){
	
	
		//text inputs
		var inputs = tbody.getElementsByTagName('input');
		var textAreas = tbody.getElementsByTagName('textarea');
		
		//alert("Input "+ 0+" is "+inputs[0].value + " name:" +inputs[0].name);
		//alert("Input "+ 1+" is "+inputs[1].value + " name:" +inputs[1].name);
		//alert("Input "+ 2+" is "+inputs[2].value + " name:" +inputs[2].name);
		for(var i=0;i<inputs.length;i++){
		    // For Hidden Values
			if(inputs[i].type=='hidden'){
				//alert("Input disabled: "+ i+" is "+inputs[i].value + " name:" +inputs[i].name);
				inputs[i].value='';
			}
			else if(inputs[i].type=='text'){
				inputs[i].value='';
				inputs[i].readOnly=true;
				inputs[i].className='readOnly';
			}
			else if(inputs[i].type=='button'){
				//alert("Input disabled: "+ i+" is "+inputs[i].value + " name:" +inputs[i].name);
				inputs[i].disabled='disabled';
			}	
		}
		for(var j=0; j<textAreas.length;j++){
			textAreas[j].readOnly='readonly';
			textAreas[j].value='';
		}
		
		//selects
		var selects = tbody.getElementsByTagName('select');
		for(var i=0;i<selects.length;i++){			
			selects[i].disabled='disabled';
			selects[i].value='';						
		}
				
	}
	else if(x.value=='either' || x.value=='present'){
		var inputs = tbody.getElementsByTagName('input');
		var textAreas = tbody.getElementsByTagName('textarea');
		
		//alert("Input "+ 0+" is "+inputs[0].value);
		//alert("Input "+ 1+" is "+inputs[1].value);
		//alert("Input "+ 2+" is "+inputs[2].value);
		
		for(var i=0;i<inputs.length;i++){
			if(inputs[i].type=='text'){			
			var existsInReadOnlyArray = false;			
			for(var k=0; k < readOnlyArray.length; k++){			
				if(inputs[i].name==readOnlyArray[k].name){
					existsInReadOnlyArray=true;
				}
			}
						
				if(!existsInReadOnlyArray){
					
					inputs[i].readOnly=false;
					inputs[i].className='';				
				}
			}
			else if(inputs[i].type=='button'){
				inputs[i].disabled='';		
			}
						
		}
		for(var j=0; j<textAreas.length;j++){
			textAreas[j].readOnly=false;
		}
		
		//selects
		var selects = tbody.getElementsByTagName('select');
		for(var i=0;i<selects.length;i++){			
			selects[i].disabled='';						
		}
				
	}
	
}


	
function inVivoOneANSException(x){

	//we need 1st in vivo process and 1st immunogen to be in sync
	//so we will pass x and the corresponding x for the other section to the
	//anyNoneSome method
	
	//now also 2nd in vivo and 2nd immunogen 12/11/08
	
	var x_name = x.name;
	var x_value = x.value;
	var span;
	if(x_name.match("1stInVivo")){		
		span = document.getElementById("immunogenOneANS");	
	}	
	else if(x_name.match("1stImmunogen")){
		span = document.getElementById("inVivoOneANS");
	}
	else if(x_name.match("2ndInVivo")){
		span = document.getElementById("immunogenTwoANS");
	}
	else if(x_name.match("2ndImmunogen")){
		span = document.getElementById("inVivoTwoANS");
	}
	else if(x_name.match("inVitroAdministration")){
		span = document.getElementById("inVitroImmunogenANS");
		
		if(span == null)
			span = document.getElementById("inVitroImmunogenANS");
			
		if(span == null)
			span = document.getElementById("inVitroProcessedAntigenANS");			
	}
	else if(x_name.match("inVitroImmunogen")){
		span = document.getElementById("inVitroAdministrationANS");
	}	
	else if(x_name.match("inVitroProcessedAntigen")){
		span = document.getElementById("inVitroAdministrationANS");
	}
	
	
		
	var inputs = span.getElementsByTagName("input");
		
	var selectedInput;
		
	for(var i=0; i < inputs.length; i++){
		if(inputs[i].value.match(x_value)){
			selectedInput = inputs[i];
		}			
	}
	
	selectedInput.checked = true;
	
	anyNoneSome(x);
	anyNoneSome(selectedInput);
					
}
	
function aq_preprocess(form_name){
	var aq_form = document.forms[form_name];
	
	/////////////////////////////////////
	//
	//	Step 0
	//  Remove any previously existing sql value holding fields
	//	ie, any field with a value starting with gov_nih...
	//
	var aq_form = document.forms[1];
	for(var i = 0; i < aq_form.elements.length; i++){
		var node = aq_form.elements[i];
		if(node.value.match('gov_nih_niaid_iedb_common_domain_field_impl_')){
			//alert("Possible number field " + node.name+ " value:"+ node.value );
			node.value=null;
			var parent = node.parentNode;
			parent.removeChild(node);
		}
	}
					
	//////////////////////////////////////
	//
	//	Step 1
	//  Handling all number fields to convert to sql syntax
	var selectors = new Array();
	var value1s = new Array();
	var value2s = new Array();
	
	//getting all the selector fields, which are used to check number range
	//we can then get the input name using our naming convention
	// xValue1 xValue2 xSelector
	for(var i = 0; i < aq_form.elements.length; i++){
					
		//finding populated number input fields (if populated, value1 always used)		
		if(aq_form.elements[i].name.match('Value1')){
									
			var selectorName = aq_form.elements[i].name.replace('Value1','Selector');
			var value2Name = aq_form.elements[i].name.replace('Value1','Value2');
			var checkSelector = aq_form.elements[selectorName];
			
			//populating selector array. must have special logic to handle
			//re-posted fields, since all arrays have "[]" added to the end
			//of their form names
			if(checkSelector == null){
				checkSelector = aq_form.elements[selectorName+"[]"];				
			}

			//checking for bad input			
			if( isNaN(aq_form.elements[value2Name].value) && aq_form.elements[value2Name].value !=''){
				 alert("Bad input in a number field: "+ aq_form.elements[value2Name].value);
				 return;
			}
			else if(isNaN(aq_form.elements[i].value)){
				 alert("Bad input in a number field: "+ aq_form.elements[i].value);
				 return;							 
			}
			else if(checkSelector.value == 'Between') {
				if(aq_form.elements[value2Name].value != '' && aq_form.elements[i].value =='') {
					alert('Value one of between clause is blank');
					return;
				}else if(aq_form.elements[value2Name].value == '' && aq_form.elements[i].value !='') {
					alert('Value two of between clause is blank');
					return;
				}
			}
			if(aq_form.elements[i].value != '') {
				//populating number arrays
				value1s.push(aq_form.elements[i]);
				value2s.push(aq_form.elements[value2Name]);								
				
				selectors.push(checkSelector);
			}  		
		} 									
	}
	
	
	//creating the query string to be stored in the value of Value1,
	//value 1 is then renamed stripped of the 'Value1'  
	
	// the value should be the query string as it will go into sql,
	// but using the form name as the place holder for the column name, this
	// will be replaced later using the map						
	for(var i = 0; i < selectors.length; i++){
		//alert(selectors[i].name);		
		var newValue = " ";
		try{
			selectors[i].name = selectors[i].name.replace('[]','');
			var newName = selectors[i].name.replace('Selector','');
			
		}
		catch(err){
			alert("Selectors[i] not defined. Prior selector was " +selectors[i-1].name);
		}
		if(selectors[i].value == 'After'){
			newValue += newName + " > "+ value1s[i].value + " ";
		}
		else if (selectors[i].value == 'Before'){
			newValue += newName + " < "+ value1s[i].value + " ";		
		}
		else if (selectors[i].value == 'Between'){
			newValue += "( "+ newName + " >= "+ value1s[i].value + 
						" AND " + newName + "<= " + value2s[i].value + " ) ";
		}
		else if (selectors[i].value == 'Equal To'){
			newValue += newName + " = "+ value1s[i].value + " ";
		}
		
		
		var newInput = document.createElement("input");
		newInput.setAttribute("type","hidden");
		newInput.name = newName;
		newInput.value = newValue;
		selectors[i].parentNode.appendChild(newInput);
															
	}	
		
	
	
	//////////////////////////////////
	//
	//	Step 2
	//	Handling all select inputs to append a '[]' to the end of form names to cue PHP that it is an
	//	incomming array
	//
	
	var selectInputs = document.getElementsByTagName('select');		
	for( var q = 0; q < selectInputs.length; q++){					
		if( selectInputs[q].name.indexOf("[]") < 0) // dont need to have more than one set of '[]'s
			selectInputs[q].name = selectInputs[q].name + "[]";					
	}
	
	aq_form.submit();

}

function validationError(x){
	alert("Form contains invalid input: " + x);
}
	
function initializeSubtypeLists(){
	
	var select = document.getElementsByTagName('select');
	var newOption;
	
	for(var i = 0; i < select.length; i++){
		
		if(select[i].name == 'gov_nih_niaid_iedb_common_domain_field_impl_EpitopeObjectSubtype'){			
			setDefaultEpitopeSubtypes(select[i]);			
		}
		else if(select[i].name == 'gov_nih_niaid_iedb_common_domain_field_impl_RelatedObjectSubtype'){			
			setDefaultRelatedSubtypes(select[i]);													
		}
		else if(select[i].name.match('ContainerObjectSubtype')){
			setDefaultContainerSubtypes(select[i]);
		}
		else if(select[i].name.match('AntibodyObjectSubtype') || select[i].name.match('TcrObjectSubtype')){
			setDefaultMultiChainMoleculeSubtypes(select[i]);
		}
		else if(select[i].name.match('ObjectSubtype')){
			setDefaultObjectSubtypes(select[i]);						
		}
		
	}
}

function epitopeRelationSubtypeModifier(x){
	
	//user selects an epitope relation from select tag x
	
	//using the name of x, we manage to get the id of the row containing
	//the subtype we need to change	
	var erSelect = x.name;		
	erSelect = erSelect.replace("gov_nih_niaid_iedb_common_domain_field_impl_", "");		
	var objectSubType = erSelect.replace("EpitopeRelation","ObjectSubtype");
				
	//we get the subtype selector
	stSelect = document.getElementById(objectSubType).getElementsByTagName('select')[0];
	
	//alert(stSelect.name);
	
	//do some logic to make sure appropriate actions are taken	
	//if the er relation is an empty string, no filtering
	if(x.value == ""){
		removeAllOptions(stSelect);
		stSelect = setDefaultObjectSubtypes(stSelect);
		subtypeLogic(stSelect);
		return;
	}
	
	//if Epitope, go to default for epitope	
	if(x.value == "Epitope"){
		removeAllOptions(stSelect);
		setDefaultEpitopeSubtypes(stSelect);
		subtypeLogic(stSelect);
		return;
	}
	
	//we clear all options from this select
	removeAllOptions(stSelect);						
		
	//alert(x.value);			
	//we then lookup the correct array given the epitope relation
	//this is in a precomputed hashmap similar to the subtype->object type map
	var array = eRelationToSubtypes[x.value];
	
	//alert(array);
	
	//we iterate through the array and create the option elements for the
	//subtype
	try{	
		for(var q=0; q < array.length; q++)
			addChildOptionToSelect(stSelect,array[q],array[q]);		
	}
	catch(err){
		alert("Error: Array Undefined: "+ erSelect.value);
		}
		
	subtypeLogic(stSelect);
						
}

function removeAllOptions(x){
	var tempArray = x.getElementsByTagName("option");	
	var length = tempArray.length;	
	for(var i=0;i<length;i++){					
		x.removeChild(tempArray[0]);
	}		
}

function addChildOptionToSelect(select, label, value){
			//alert(select + " "+  label +" "+ value);
			var newOption;
			newOption = document.createElement("option");
			select.appendChild(newOption);
			newOption.text = label; 
			newOption.value = value; 
			
}  

function setDefaultObjectSubtypes(x){
		
		//ant imgn select options
		var antImgnSelectOptions = [''
						,'Peptide from protein'
						,'Peptide, no natural source'
						,'Protein'
						,'Organism'
						,'Carbohydrate fragment'
						,'Lipid fragment'
						,'Fatty acid fragment'
						,'Glycolipid fragment'
						,'Peptidoglycan fragment'
						,'Other fragment'
						,'Carbohydrate'
						,'Lipid'
						,'Fatty acid'
						,'Glycolipid'
						,'Peptidoglycan'
						,'Other Non-Sequence'
						,'Multi-Chain protein'
						,'Derivative of Organism'];
		for(var i=0; i < antImgnSelectOptions.length; i++){
				addChildOptionToSelect(x, antImgnSelectOptions[i], antImgnSelectOptions[i]);
			}						
}

function setDefaultEpitopeSubtypes(x){
			
			//epitope subtypes						
			var epitopeSelectOptions = [''
						,'Peptide from protein'
						,'Peptide, no natural source'
						,'Carbohydrate fragment'
						,'Lipid fragment'
						,'Fatty acid fragment'
						,'Glycolipid fragment'
						,'Peptidoglycan fragment'
						,'Other fragment'
						,'Carbohydrate'
						,'Lipid'
						,'Fatty acid'
						,'Glycolipid'
						,'Peptidoglycan'
						,'Other Non-Sequence'
						,'Discontinuous protein residues'
						,'Polysaccharide repeating unit'
						,'Region on multi-chain protein'];
			for(var i=0; i < epitopeSelectOptions.length; i++){
				addChildOptionToSelect(x, epitopeSelectOptions[i], epitopeSelectOptions[i]);
			}											
}

function setDefaultRelatedSubtypes(x){

	//Related select options
	var relatedSelectOptions = [''
						,'Peptide from protein'
						,'Peptide, no natural source'
						,'Protein'
						,'Organism'
						,'Carbohydrate fragment'
						,'Lipid fragment'
						,'Fatty acid fragment'
						,'Glycolipid fragment'
						,'Peptidoglycan fragment'
						,'Other fragment'
						,'Carbohydrate'
						,'Lipid'
						,'Fatty acid'
						,'Glycolipid'
						,'Peptidoglycan'
						,'Other Non-Sequence'
						,'Multi-Chain protein'
						,'Derivative of Organism'
						,'BAL (bronchoalveolar lavage)'
						,'Blood'
						,'Bone Marrow'
						,'Breast'
						,'CNS'
						,'CSF (cerebrospinal fluid)'
						,'Embryo'
						,'Eye'
						,'Gastrointestinal tract'
						,'Heart'
						,'Kidney'
						,'Liver'
						,'Lung'
						,'Lymph Node'
						,'Lymphoid'
						,'Other'
						,'Pancreas'
						,'Peritoneal fluid'
						,'Salivary gland'
						,'Skin'
						,'Spleen'
						,'Synovial Fluid'
						,'Thymus'
						,'Umbilical cord blood'];
	for(var i=0; i < relatedSelectOptions.length; i++){
		addChildOptionToSelect(x, relatedSelectOptions[i], relatedSelectOptions[i]);
	}
}

function setDefaultContainerSubtypes(x){

	//container select options
	var containerSelectOptions = [''
						,'Peptide conjugate'
						,'Protein conjugate'
						,'Multi-Antigenic Peptide (MAP, branched)'
						,'Peptide Repeat Sequence (linear)'
						,'Peptide plus Multi-Chain'
						,'Fatty acid conjugate'
						,'Glycolipid conjugate'
						,'Nucleotide conjugate'
						,'Other Complexed Molecule'
						,'Recombinant Organism'
						,'Plasmid'
						,'Infected Cell'
						,'Transfected Cell'
						,'Pulsed Cell'
						,'Phage display'
						,'Yeast display'
						,'Bacterial display'
						,'Ribosomal display'];
	for(var i=0; i < containerSelectOptions.length; i++){
		addChildOptionToSelect(x, containerSelectOptions[i], containerSelectOptions[i]);
	}
}

function setDefaultMultiChainMoleculeSubtypes(x){

	//container select options
	var containerSelectOptions = [ '', 'Multi-Chain protein'];
	for(var i=0; i < containerSelectOptions.length; i++){
		addChildOptionToSelect(x, containerSelectOptions[i], containerSelectOptions[i]);
	}
}

function resetForm(){
	
	//getting form
	var myform = document.forms[1];
	
	//saving this hidden field
	var type = myform['aq_assay_type'].value;
	
	//getting array of inputs
	var inputs = myform.getElementsByTagName("input");
	
	myform.reset();
	
	for(var i=2;i<inputs.length;i++){
		//clear hidden fields
		if(inputs[i].type == 'hidden'){
			inputs[i].value = '';
		}	
		// Clear the Reference Type JIRA - EXT-533
		if(inputs[i].checked){
			selector = "";
			refTypeLogic(selector);		
		}
		// Reset for the Complete Immunization JIRA - EXT-528
		if(inputs[i].type == 'radio'
		&& inputs[i].name != 'gov_nih_niaid_iedb_common_domain_field_impl_referenceType' 
		&& inputs[i].name != 'gov_nih_niaid_iedb_common_domain_field_impl_ComplexViewerStatus' 
		&& inputs[i].name != 'gov_nih_niaid_iedb_common_domain_field_impl_AntigenPresentingCellsAutologousOrSyngeneic'
		&& inputs[i].value =='either'){
						anyNoneSomeEither(inputs[i]);
			}
		}

	myform['aq_assay_type'].value = type;
	
	var select = document.getElementsByTagName('select');
	
	for(var i=0;i<select.length;i++){
			if(select[i].name.match("Selector") && select[i].name != "eValueSelector") {
				numberSelector(select[i]);
			}
	}	
	
}

function anyNoneSomeEither(x){
	var tbody = x.parentNode.parentNode.parentNode.parentNode.parentNode.lastChild;
		var inputs = tbody.getElementsByTagName('input');
		var textAreas = tbody.getElementsByTagName('textarea');
		
		
		for(var i=0;i<inputs.length;i++){
			if(inputs[i].type=='text'){			
			var existsInReadOnlyArray = false;			
			for(var k=0; k < readOnlyArray.length; k++){			
				if(inputs[i].name==readOnlyArray[k].name){
					existsInReadOnlyArray=true;
				}
			}		
			if(!existsInReadOnlyArray){
					inputs[i].readOnly=false;
					inputs[i].className='';				
				}
			}
			else if(inputs[i].type=='button'){
				inputs[i].disabled='';		
			}
						
		}
		for(var j=0; j<textAreas.length;j++){
			textAreas[j].readOnly=false;
		}	
		//selects
		var selects = tbody.getElementsByTagName('select');
		for(var i=0;i<selects.length;i++){			
			selects[i].disabled='';						
		}	
}

function openPopulatedSections(defaultOpenHeaderArray){
	
	//to keep section that the user has populated with data open.
	//returns an array of section header ids that will be expanded on initialization
	

	//get form
	var myform = document.forms[1];
	
	//get all inputs, select, textarea
	var inputs = myform.getElementsByTagName('input');
	var selects = myform.getElementsByTagName('select');
	var textareas = myform.getElementsByTagName('textarea');
	
	//there will be some exceptions, like the anyNoneSome, and the number selectors
	//we can ignore these
	var ignoreFieldStrings = new Array("AnyNoneSome", "Selector", "aq_assay_type");
	
	//a local headerId set to keep all the immediate section wrappers of populated fields
	var parentHeaders = new Array();
					
	//iterate through 'input' arrays.
		//if input value is not null, iterate through parent nodes, checking for
		//new tables, and checking each table to see if it is expanded or collapsed by
		//looking at the expand/collapse graphic and expanding if populated
		//this continues until the parent is the div container and we will know that field
		//is visible
		
		//as we iterate through the tables, if a table header needs to be expanded,
		//we save the link that expands the expand/collapse to an array 'set'
		//once all inputs have been examined, we then loop through those to perform 
		//the expansions	
	
	
	//inputs	
	for(var i=2; i < inputs.length; i++){
				
		if(inputs[i].value != null && inputs[i].value != '' && inputs[i].type.toUpperCase() == 'TEXT'){
			//populated field.  
			
			//checking to see if we care about this field
			if(isIgnoreStringInFieldName(inputs[i].name, ignoreFieldStrings))
				continue;
			
			//we care about this field, it is populated, we need it to be open
			//get all the HeaderIds between it and the advancedQueryTableContainer div
			
			//but to be faster, we will first just get the enclosing headerId
			//after all inputs,selects,textareas have been run through, we will then
			//work up the DOM tree to get the rest of the HeaderIds that need to be open
			
			//alert("Attempting to add to input name:"+inputs[i].name +" and value: "+ inputs[i].value);
			var headerId = getParentHeaderId(inputs[i]);
			//alert("Header id is "+ headerId);
			addToHeaderSet(headerId, parentHeaders);									
		}		
	}
	
	
	//selects
	for(var i=0; i < selects.length; i++){
				
		if(selects[i].value != null && selects[i].value != ''){
			//populated field.  
			
			//checking to see if we care about this field
			if(isIgnoreStringInFieldName(selects[i].name, ignoreFieldStrings))
				continue;
			
			//we care about this field, it is populated, we need it to be open
			//get all the HeaderIds between it and the advancedQueryTableContainer div
			
			//but to be faster, we will first just get the enclosing headerId
			//after all inputs,selects,textareas have been run through, we will then
			//work up the DOM tree to get the rest of the HeaderIds that need to be open
			
			//alert("Attempting to add to input name:"+selects[i].name +" and value: "+ selects[i].value);
			var headerId = getParentHeaderId(selects[i]);
			//alert("Header id is "+ headerId);
			addToHeaderSet(headerId, parentHeaders);									
		}		
	}
	//textareas
	for(var i=0; i < textareas.length; i++){
				
		if(textareas[i].value != null && textareas[i].value != ''){
			//populated field.  
			
			//checking to see if we care about this field
			if(isIgnoreStringInFieldName(textareas[i].name, ignoreFieldStrings))
				continue;
			
			//we care about this field, it is populated, we need it to be open
			//get all the HeaderIds between it and the advancedQueryTableContainer div
			
			//but to be faster, we will first just get the enclosing headerId
			//after all inputs,selects,textareas have been run through, we will then
			//work up the DOM tree to get the rest of the HeaderIds that need to be open
			
			//alert("Attempting to add to input name:"+textareas[i].name +" and value: "+ textareas[i].value);
			var headerId = getParentHeaderId(textareas[i]);
			//alert("Header id is "+ headerId);
			addToHeaderSet(headerId, parentHeaders);									
		}		
	}
	 	
	
	//get any intermediate headers between the parent headers and the div tag
	obtainIntermediateHeaders(parentHeaders);
	
		
	//combine the parentHeaders with the defaultOpenHeaderArray	
	combineTwoSets(parentHeaders, defaultOpenHeaderArray);
			
}

function getParentHeaderId(input){
	
	//alert("Input element node name = " + input.name);
	
	var parentElement = input.parentNode;
			
	while(parentElement.nodeName.toUpperCase() != 'TABLE'){		
		parentElement = parentElement.parentNode;		
	}	
	//alert("Parent element node name = " + parentElement.nodeName);
	
	//parentElement should be a table now. We need to navigate to the thead tr th id
	
	return getHeaderIdFromTable(parentElement);
				
}

function isIgnoreStringInFieldName(fieldName, ignoreArray){

	for(var i = 0; i < ignoreArray.length; i++){
		if(fieldName.indexOf(ignoreArray[i]) > -1){
			return true;
			break;
		}
	}
	return false;
}

function addToHeaderSet(headerString, headerArray){

	for(var i=0; i < headerArray.length; i++){
		if(headerString == headerArray[i])
			return;
	}

	headerArray.push(headerString);
	return;
}

function combineTwoSets(parentHeaderArray, defaultOpenArray){
	
	for(var i=0; i < parentHeaderArray.length; i++){	
		addToHeaderSet(parentHeaderArray[i],defaultOpenArray);	
	}
}

function obtainIntermediateHeaders(parentHeaders){

	for(var i=0; i < parentHeaders.length; i++){
	
		//alert("parentHeaders  name is "+ parentHeaders[i]);
		
		var headElement = document.getElementById(parentHeaders[i]);
		var parentElement = headElement.parentNode;
		
		//alert("parentElement node name is "+ parentElement.nodeName.toUpperCase());
		
		while(parentElement.nodeName.toUpperCase() != 'DIV'){
			//alert("parentElement node name is "+ parentElement.nodeName.toUpperCase());
			if(parentElement.nodeName.toUpperCase() == 'TABLE'){
			 	var id = getHeaderIdFromTable(parentElement);
			 	//alert("Adding intermediate header " + id);
				addToHeaderSet(id, parentHeaders);
			}
				
			parentElement = parentElement.parentNode;		
		}	
			
	}

}

function getHeaderIdFromTable(table){

	var childElements = table.childNodes;
	var thead;
	for(var i=0; i< childElements.length; i++){
		if(childElements[i].nodeName.toUpperCase() == 'THEAD'){
			thead = childElements[i];
			break;
		}	
	}
	//alert("THEAD name is : "+ thead.nodeName);
	
	var header = thead.getElementsByTagName('th'); 
	
	//alert("Header count is " + header.length + " and type = " + header[0].nodeName);
	
	//alert("th name is : "+ header.nodeName);
	if(header != null)
		return header[0].id;

}

function getPopulatedObjects(objectFieldTypeArray){
	
	var length = objectFieldTypeArray.length;
	var populatedArray = new Array(length);
	
	//alert("Populated array size is :" + populatedArray.length);
	
	objectloop:
	for(var j = 0; j < length; j++){
		//get the selector from the objectType name
		var selector = document.forms[1].elements['gov_nih_niaid_iedb_common_domain_field_impl_'+
								 objectFieldTypeArray[j] + 'ObjectSubtype'];
		
		//get object table body from selector
		var tbody = selector.parentNode;
		while(tbody.nodeName.toUpperCase() != "TBODY"){
			tbody = tbody.parentNode;
		}
		
		//var tbody = selector.parentNode.parentNode.parentNode;
		 
		populatedArray[j] = false;
							 
		var inputs = tbody.getElementsByTagName('input');
		var selects = tbody.getElementsByTagName('select');
		var textareas = tbody.getElementsByTagName('textarea');
		
		//inputs	
		for(var i=0; i < inputs.length; i++){				
			if(inputs[i].value != null && inputs[i].value != '' && inputs[i].type.toUpperCase() == 'TEXT'){
			//populated field.  
				populatedArray[j] = true;
				//alert("populatedArray["+j+"] value is " + populatedArray[j] + "because inputs["+i+"] value is "+ inputs[i].value);
				continue objectloop;							
			}		
		}
		
		//selects
		for(var i=0; i < selects.length; i++){			
			if(selects[i].value != null && selects[i].value != '' && selects[i].value != 'Equal To' && selects[i].value != 'Exact'){
				//populated field.  
				populatedArray[j] = true;
				//alert("populatedArray["+j+"] value is " + populatedArray[j] + "because selects["+i+"] value is "+ selects[i].value);
				continue objectloop;											
			}		
		}
		//textareas
		for(var i=0; i < textareas.length; i++){
					
			if(textareas[i].value != null && textareas[i].value != ''){
				//populated field.  
				populatedArray[j] = true;
				//alert("populatedArray["+j+"] value is " + populatedArray[j] + "because textareas["+i+"] value is "+ textareas[i].value);
				continue objectloop;													
			}		
		}										
	}

	return populatedArray;
}


function maintainPopulatedBetweenBoxes(){
	
	var inputs = document.getElementsByTagName('INPUT');
	
	for( var i = 0; i < inputs.length; i++ ){	
		if( inputs[i].name != null && inputs[i].name.match("Value2")){	
			if(inputs[i].value != null && inputs[i].value != ''){
			
				inputs[i].parentNode.style.display='inline';
			}	
		}
	}
}

// Submit the form using Enter on the Text fields
function onEnter(evt,form) {
	var keyCode = null;
	if( evt.which ) {
		keyCode = evt.which;
	} else if( evt.keyCode ) {
		keyCode = evt.keyCode;
	}
	if( 13 == keyCode ) {
		aq_preprocess(form).onclick()
		return false;
	}
	return true;
}


function debugOut(x){

	var divA = document.getElementById("aq_debug");
	var inside = divA.innerHTML;
	if(inside == null)
		inside = "";
	inside = inside + "<br/>" + x;
	divA.innerHTML = inside;
	
}

function prePopulate(){		
	var myForm = document.forms[1];	
	//get all form variables that have the _revise suffix
	var inputs = myForm.getElementsByTagName('input');
	for(var i =0; i < inputs.length; i++){
	
	var pattern = /_revise/;
	var tName = inputs[i].name;		 	 	
		if(tName.search(pattern) > -1){		
			var ogName = tName.replace(pattern,"");
			
			//handling multiple select arrays		
			var pat2 = /\[\]$/;
			var pat3 = /AnyNoneSome$/;
			if(tName.search(pat2) > -1){
			
			 var ogName = ogName.replace(pat2,"");			
			 var ogSelect = myForm.elements[ogName];
			 if(ogSelect != null){
						
			 	var options = ogSelect.options;
			 
			 	for(var j = 0; j < options.length ; j++){
					if(inputs[i].value == options[j].value){				
						options[j].selected = true;
					}
				}	
			 }
			}
			else if(ogName.search(pat3) > -1){ //amyNoneSomes				
				var radios = myForm.elements[ogName];							
				if(radios != null){
					for( var j= 0; j < radios.length; j++){					
						if(inputs[i].value == radios[j].value){
							radios[j].checked = true;
						}										
					}				
				}							
			}
			else{
				var ogField = myForm.elements[ogName]
				if(ogField != null)
					ogField.value = inputs[i].value;
			}																											
		}								
	}	
	document.getElementById("reviseHelpContainer").innerHTML="";	
}