// JavaScript functions for finders.

// openTreeFinder:
// Opens a tree finder (species or disease).
// Parameters:
//   findertype 	a valid species or disease finder type, as defined in
//              	gov.nih.niaid.iedb.common.finder.FinderConstants
//   selectiontype 	a valid selection type (single or multiple) as defined in
//              	gov.nih.niaid.iedb.common.finder.FinderConstants
//   formname		the name of the form that contains the fields that this finder
//					will populate; with normal HTML, this is the "name" attribute
//					of the "form" tag; the Struts "html:form" tag sets this attribute
//					automatically to the name of the Java form class used to hold
//					the form's values
//   namefield		the name of the non-editable text form field that will display items
//					selected in the finder
//	 idfield		the name of the hidden form field that will get the ID's of items
//					selected in the finder; for multiple selection finders, the id's will
//					be delimited by semicolons, and there will be a semicolon both before
//					and after each id (including the first and the last)
//   pathfield		the name of the hidden form field that will get the path-to-root of items
//					selected in the finder (IF NONE, SEND AN EMPTY STRING: '' );
//					for multiple selection finders, the paths will be delimited
//					by semicolons
function openTreeFinder(findertype,selectiontype,formname,namefield,idfield,pathfield)
{
	var childWindowTreeFinder = window.open("/finders/treefinder.do?dispatch=load&findertype=" + findertype
		+ "&selectiontype=" + selectiontype
		+ "&formname=" + formname
		+ "&namefield=" + namefield
		+ "&idfield=" + idfield
		+ "&pathfield=" + pathfield,
		"Finder", "scrollbars=no,width=700,height=700,toolbar=no,status=no,menubar=no,resizable=no");
	if (childWindowTreeFinder.opener == null) childWindowTreeFinder.opener = self;
	childWindowTreeFinder.focus();
}
function openOrganismFinder(findertype,selectiontype,formname,namefield,idfield,pathfield)
{
	var screen_width = screen.width;
	var screen_height = screen.height;
	var childWindowTreeFinder = null;
	
	// Check on 800x600 resolution added per JIRA EXT-647
	if ((screen_width == 800 && screen_height == 600) || (screen_width == 1024 && screen_height == 768))	{
		childWindowTreeFinder = window.open("/finders/treefinder.do?dispatch=load&findertype=" + findertype
		+ "&selectiontype=" + selectiontype
		+ "&formname=" + formname
		+ "&namefield=" + namefield
		+ "&idfield=" + idfield
		+ "&pathfield=" + pathfield,
		"SpeciesFinder", "scrollbars=yes,width=700,height=500,toolbar=no,status=no,menubar=no,resizable=no");
	}
	else {	
		childWindowTreeFinder = window.open("/finders/treefinder.do?dispatch=load&findertype=" + findertype
		+ "&selectiontype=" + selectiontype
		+ "&formname=" + formname
		+ "&namefield=" + namefield
		+ "&idfield=" + idfield
		+ "&pathfield=" + pathfield,
		"SpeciesFinder", "scrollbars=no,width=700,height=700,toolbar=no,status=no,menubar=no,resizable=no");
	}
	
	if (childWindowTreeFinder.opener == null) childWindowTreeFinder.opener = self;
	childWindowTreeFinder.focus();
}

// openTableFinder:
// Opens a table finder (allele or assay).
// Parameters:
//   findertype 	a valid allele or assay finder type, as defined in
//              	gov.nih.niaid.iedb.common.finder.FinderConstants
//   selectiontype 	a valid selection type (single or multiple) as defined in
//              	gov.nih.niaid.iedb.common.finder.FinderConstants
//   formname		the name of the form that contains the fields that this finder
//					will populate; with normal HTML, this is the "name" attribute
//					of the "form" tag; the Struts "html:form" tag sets this attribute
//					automatically to the name of the Java form class used to hold
//					the form's values
//   namefield		the name of the non-editable text form field that will display items
//					selected in the finder
//	 idfield		the name of the hidden form field that will get the ID's of items
//					selected in the finder; for multiple selection finders, the id's will
//					be delimited by semicolons, and there will be a semicolon both before
//					and after each id (including the first and the last)
//	 loadparam		parameter needed to load a valid table finder; currently only used to send
//					a valid category when opening an assay finder (assay finders require a valid
//					category name in this parameter, as defined in the ASSAY_TYPE.CATEGORY
//					database column of the UTILITY schema); for other table finders, send
//					a blank string: '' 
//
//	response		String name of fieldname for type of response (assay type)
//
//
//	units			the string name of the field name for the units (assay type)
function openTableFinder(findertype,selectiontype,formname,namefield,idfield,loadparam,responsefield,unitsfield)
{
	var childWindowTableFinder = window.open("/finders/tablefinder.do?dispatch=load&findertype=" + findertype
		+ "&selectiontype=" + selectiontype
		+ "&formname=" + formname
		+ "&namefield=" + namefield
		+ "&idfield=" + idfield
		+ "&loadparam=" + loadparam
		+ "&responsefield=" + responsefield
		+ "&unitsfield=" + unitsfield,
		"Finder", "scrollbars=yes,width=700,height=700,toolbar=no,status=no,menubar=no,resizable=yes");
	if (childWindowTableFinder.opener == null) childWindowTableFinder.opener = self;
	childWindowTableFinder.focus();
}

function openSourceFinder(findertype,selectiontype,formname,namefield,accessionfield,idfield,
						  sequencefield,speciesfield,taxidfield,pathfield,
						  startposfield,endposfield)
{
	var childWindowTableFinder = window.open("/finders/tablefinder.do?dispatch=load&findertype=" + findertype
		+ "&selectiontype=" + selectiontype
		+ "&formname=" + formname
		+ "&namefield=" + namefield
		+ "&accessionfield=" + accessionfield
		+ "&idfield=" + idfield
		+ "&sequencefield=" + sequencefield 
		+ "&speciesfield=" + speciesfield
		+ "&taxidfield=" + taxidfield
		+ "&pathfield=" + pathfield
		+ "&startposfield=" + startposfield
		+ "&endposfield=" + endposfield,
		"Finder", "scrollbars=yes,width=700,height=700,toolbar=no,status=no,menubar=no,resizable=yes");
	if (childWindowTableFinder.opener == null) childWindowTableFinder.opener = self;
	childWindowTableFinder.focus();
}




// clearFields:
// Used to clear the fields that hold the names and ID's of the items selected with the finders.
// Parameters:
//   formname		the name of the form that contains the fields that this finder
//					will populate; with normal HTML, this is the "name" attribute
//					of the "form" tag; the Struts "html:form" tag sets this attribute
//					automatically to the name of the Java form class used to hold
//					the form's values
//   namefield		the name of the non-editable text form field that will display items
//					selected in the finder
//	 idfield		the name of the hidden form field that will get the ID's of items
//					selected in the finder
//	 pathfield		the name of the hidden form field that will get the path-to-root of items
//					selected in the finder (IF NONE, SEND AN EMPTY STRING: '' )
function clearFields(formname,namefield,displayfield,idfield,pathfield)
{
	document.forms[0].elements['finderSelection'].value = '';
	window.opener.document.forms[formname].elements[namefield].value = '';
	window.opener.document.forms[formname].elements[idfield].value = '';
	if( pathfield == 'null' ){pathfield='';}
	if (pathfield != '') {
		window.opener.document.forms[formname].elements[pathfield].value = '';
	}
	window.opener.document.forms[formname].elements[displayfield].value = '';
}
function clearSourceFields(formname,namefield,accessionfield,idfield,pathfield,speciesfield,taxidfield,strainfield)
{
	/* Should not clear the species/path/strain information
	if((pathfield != '') && (pathfield != 'null')){
		window.opener.document.forms[formname].elements[pathfield].value = '';
	}
	*/
	//alert(accessionfield);
	if((accessionfield != '') && (accessionfield != 'null')){
		window.opener.document.forms[formname].elements[accessionfield].value = '';
	}
	window.opener.document.forms[formname].elements[namefield].value = '';
	window.opener.document.forms[formname].elements[idfield].value = '';	
	document.forms[0].elements['finderSelection'].value = '';
}

// This is used by the finder code to populate the name and ID form fields
// in the window that opened the finder (see open* functions above).
// Since we can't reference the selection type constants in
// gov.nih.niaid.iedb.common.finder.FinderConstants here,
// we pass them in as the last two parameters (ugly: will try to find a better way).
// Parameters:
//   selectiontype 	a valid selection type (single or multiple) as defined in
//              	gov.nih.niaid.iedb.common.finder.FinderConstants
//   formname		the name of the form that contains the fields that this finder
//					will populate; this is passed in to the finder by the form
//					that opened it
//   namefield		the name of the non-editable text form field that will display items
//					selected in the finder; this is passed in to the finder by the form
//					that opened it
//	 idfield		the name of the hidden form field that will get the ID's of items
//					selected in the finder; this is passed in to the finder by the form
//					that opened it
//	 pathfield		the name of the hidden form field that will get the path-to-root of items
//					selected in the finder; this is passed in to the finder by the form
//					that opened it
//   nameval		the value to place in the name field
//	 idval			the value to place in the id field
//	 pathval		the value to place in the path field
//	 singlesel		the single selection type constant defined in
//              	gov.nih.niaid.iedb.common.finder.FinderConstants
//	 multisel		the multiple selection type constant defined in
//              	gov.nih.niaid.iedb.common.finder.FinderConstants
function selectNode(selectiontype,formname,namefield,displayfield,idfield,pathfield,nameval,idval,pathval,singlesel,multisel)
{
	var displayval = convertHtmlEntityToUnicode(nameval);
	nameval = convertUnicodeToHtmlEntity(nameval);  // converts any UTF-8 char to HTML entities for search
	if( pathfield == 'null' ){pathfield='';}
	if (selectiontype == singlesel) {
		window.opener.document.forms[formname].elements[namefield].value = nameval;
		window.opener.document.forms[formname].elements[displayfield].value = displayval;
		document.forms[0].elements['finderSelection'].value = displayval;
		window.opener.document.forms[formname].elements[idfield].value = idval;
		if (pathfield != '') {
			window.opener.document.forms[formname].elements[pathfield].value = pathval;
		}
		window.close();
	}
	else {
	// For the Multiple Selection - Select 
		selectbox = document.forms[0].elements['finderSelection'];
		var isNew = true;
		var boxLength = selectbox.length;
		if (boxLength != 0) {
			for (i = 0; i < boxLength; i++) {
				thisitem = selectbox.options[i].text;
				//if(thisitem == nameval) {
				if(thisitem == displayval) {
					isNew = false;
					break;
				}
			}
		}
		if (isNew) {
		var optn = document.createElement("OPTION");

		optn.text = displayval;
		optn.value = displayval;
		selectbox.options.add(optn);
		
		window.opener.document.forms[formname].elements[namefield].value =
				window.opener.document.forms[formname].elements[namefield].value + nameval + ";";
		window.opener.document.forms[formname].elements[displayfield].value =
			window.opener.document.forms[formname].elements[displayfield].value + displayval + ";";
	  
		if (!isBlank(idfield)){
		    window.opener.document.forms[formname].elements[idfield].value =
			  window.opener.document.forms[formname].elements[idfield].value + idval + ";";
		  }
		  if (!isBlank(pathfield)){
		    window.opener.document.forms[formname].elements[pathfield].value =
		  	  window.opener.document.forms[formname].elements[pathfield].value + pathval + ";";
		  }
		}	
	}

	// Return false, since the link that took us here is fake.  The link should be something like:
	// <a href="#" onclick="selectNode(...)">nameval</a>
	return false;
} 

function selectTreeNode(selectiontype,formname,namefield,displayfield,idfield,pathfield,nameval,idval,pathval,singlesel,multisel)
{	
	selectNode(selectiontype,formname,namefield,displayfield,idfield,pathfield,nameval,idval,pathval,singlesel,multisel);
}

function isBlank(x){
	if((x == "") || (x == null) || (x == undefined)){
		return true;
	} else { 
		return false; 
	}
}

function selectSourceNode(selectiontype,
						  formname,
						  namefield,
						  accessionfield,
						  idfield,
						  sequencefield,
						  pathfield,
						  speciesfield,
						  taxidfield,
						  startposfield,
						  endposfield,
						  nameval,
						  accessionval,
						  idval,
						  seqval,
						  pathval,
						  speciesval,
						  taxidval,						  
						  startposval,
						  endposval,						
						  singlesel,
						  multisel,
						  chemTypeField,
						  chemTypeVal)
{ 
	var parentForm = window.opener.document.forms[formname];
	var form = document.forms[0];
	if (selectiontype == singlesel) {
		document.forms[0].elements['finderSelection'].value = nameval;
		if (!isBlank(namefield)) { parentForm.elements[namefield].value = nameval; }
		if (!isBlank(idfield)) { parentForm.elements[idfield].value = idval;	}
		if (!isBlank(sequencefield)) { parentForm.elements[sequencefield].value = seqval;	}
		if (!isBlank(speciesfield)) { parentForm.elements[speciesfield].value = speciesval; }
		if (!isBlank(taxidfield)) { parentForm.elements[taxidfield].value = taxidval; }
		if (!isBlank(startposfield)) { parentForm.elements[startposfield].value = startposval; }
		if (!isBlank(endposfield)) { parentForm.elements[endposfield].value = endposval; }
		if (!isBlank(pathfield)) { parentForm.elements[pathfield].value = pathval; }
		if (!isBlank(accessionfield)) { parentForm.elements[accessionfield].value = accessionval; }
		if (!isBlank(chemTypeField)) { parentForm.elements[chemTypeField].value = chemTypeVal; }
		window.close();
	}
	else {//The source finder should only replace the name and id values when it is a multi-select!
		// For the Multiple Selection - Select 
		selectbox = document.forms[0].elements['finderSelection'];
		var isNew = true;
		var boxLength = selectbox.length;
		if (boxLength != 0) {
			for (i = 0; i < boxLength; i++) {
				thisitem = selectbox.options[i].value;
				if(thisitem == idval) {
					isNew = false;
					break;
				}
			}
		}
		if (isNew) {
		var optn = document.createElement("OPTION");

		optn.text = nameval;
		optn.value = idval;
		selectbox.options.add(optn);
		
		window.opener.document.forms[formname].elements[namefield].val =
				window.opener.document.forms[formname].elements[namefield].value + nameval + ";";
			if (!isBlank(idfield)){		
			window.opener.document.forms[formname].elements[idfield].value =
					window.opener.document.forms[formname].elements[idfield].value + idval + ";";
				}
			if (!isBlank(pathfield)){
			window.opener.document.forms[formname].elements[pathfield].value =
					window.opener.document.forms[formname].elements[pathfield].value + pathval + ";";
				}
		}	
	}


	// Return false, since the link that took us here is fake.  The link should be something like:
	// <a href="#" onclick="selectSourceNode(...)">nameval</a>
	return false;
}

function selectAssayTypeNode(
						  selectiontype,
						  formname,
						  namefield,
						  responsefield,
						  idfield,						  
						  unitsfield,						  
						  nameval,
						  responseval,
						  idval,
						  unitsval,singlesel,multisel)
						  
{ 
	var parentForm = window.opener.document.forms[formname];
	var form = document.forms[0];
	//The source finder should only replace the name and id values when it is a multi-select!
		// For the Multiple Selection - Select 
		selectbox = document.forms[0].elements['finderSelection'];
		var isNew = true;
		var boxLength = selectbox.length;
		if (boxLength != 0) {
			for (i = 0; i < boxLength; i++) {
				thisitem = selectbox.options[i].value;
				if(thisitem == idval) {
					isNew = false;
					break;
				}
			}
		}
		if (isNew) {
		var optn = document.createElement("OPTION");
		var nameValue = nameval;

		optn.text = nameval;
		optn.value = idval;
		selectbox.options.add(optn);
		
		window.opener.document.forms[formname].elements[namefield].value =
				window.opener.document.forms[formname].elements[namefield].value + nameval + ";";
			if (!isBlank(idfield)){		
			window.opener.document.forms[formname].elements[idfield].value =
					window.opener.document.forms[formname].elements[idfield].value + idval + ";";
				}
			//if (!isBlank(responsefield)) { parentForm.elements[responsefield].value = responseval; }
			//if (!isBlank(unitsfield)) { parentForm.elements[unitsfield].value = unitsval; }	
			}
	return false;
}

// this function set all hidden inputs named 'dispatch' to the argument value
function openSmilesUpdater(formname,namefield) 
{
	var childWindowSmilesUpdater = window.open("smilesUpdaterLoad.do?dispatch=load"
		+ "&smilesFormBean=" + formname
		+ "&smilesFormField=" + namefield,
		"SmilesUpdater", "scrollbars=yes,width=1000,height=700,toolbar=no,status=no,menubar=no,resizable=yes");
	if (childWindowSmilesUpdater.opener == null) childWindowSmilesUpdater.opener = self;
	childWindowSmilesUpdater.focus();
            
}
//this function is alpha specific 
function reviseSearch(){
	var myForm = document.forms[0];
	myForm.action = "home.php";
	myForm.submit();
}

function convertHtmlEntityToUnicode(str)	{
	return convertAnyGreekEntities(str, true);
}
function convertUnicodeToHtmlEntity(str)	{
	return convertAnyGreekEntities(str, false);
}

/**
 * Takes a map of Greek HTML entities and does conversion to or from Unicode.
 * Meant for display on home page and in Molecule Finder.
 * @param str initial string to convert.
 * @param toUnicode "true" = convert to Unicode characters; 
 * "false" = convert to HTML entities
 * @return converted string (initially 'str' parameter)
 */
function convertAnyGreekEntities(str, toUnicode) {
	var theString = str.toString();
	if(theString.length == 0) {  // for extraneous case
		    return "";
    }
	var htmlMap = {
		"greek":[
		  {"html":"&alpha;",
		   "code":"945"},
		  {"html":"&Alpha;",
		   "code":"913"},
		  {"html":"&Beta;",
		   "code":"914"},
		  {"html":"&beta;",
		   "code":"946"},
		  {"html":"&Gamma;",
		   "code":"915"},
		  {"html":"&gamma;",
		   "code":"947"}
		]
	};
	
	if (toUnicode == true)	{  // for conversion from HTML entity to Unicode
		for (var i = 0; i < htmlMap.greek.length; i++)	{
		  var entity = htmlMap.greek[i].html;
	      while (theString.search(entity) != -1)	{
	        var codeConv = String.fromCharCode(htmlMap.greek[i].code);
	        theString = theString.replace(entity, codeConv);
	      }
		}
	}
	else	{  /// for conversion from Unicode to HTML entity
		for (var i = 0; i < htmlMap.greek.length; i++)	{
		  var gCode = htmlMap.greek[i].code;
		  var unicodeChar = String.fromCharCode(gCode);
		  var regular = new RegExp(unicodeChar);
		  var testing = regular.test(theString);	  
		  while (testing)	{
		    var entity = htmlMap.greek[i].html;
		    theString = theString.replace(unicodeChar, entity);
		    testing = regular.test(theString);  
		  }
		}
	}
	return theString;	  
}

