var gSelectedIndex = -1;
var isListNew = true;
/* key code constants */
var ENTER = 13;
var KEYUP = 38;
var KEYDOWN = 40;
var ESC = 27;
var DEFAULT_INPUT_TEXT = "Enter Search";

function sendRequestAutoComplete(url, /*Object containing parameters */payload)
{		
	dojo.xhrGet	(
		{
			url: url,
			handleAs: "text",
			sync: "true",
			content: payload,
			load: handleResponseAutoComplete
		}	
	);
}
function changeOpacityAutoComplete(obj, opacity, decrease) 
{
    obj.style.opacity = (opacity / 100);
    obj.style.filter = "alpha(opacity:" + opacity + ")";
    if (decrease)
        opacity--;
    else
        opacity++;      
    if (opacity != 100 && opacity != 0)
        setTimeout(function(){changeOpacityAutoComplete(obj, opacity, decrease);}, 5);
} 
function handleResponseAutoComplete(response)
{
	var nameStrings =  response.split("|");	
	// sometimes nameStrings[0] gets a leading "\r\n" escape sequence after split.  
	//  erasing that for proper handling later in this method.
	nameStrings[0] = nameStrings[0].replace("\r\n", "");
	nameStrings[0] = nameStrings[0].replace("\n", ""); // quirk within builds
	var names = nameStrings[1].split("\n");
	
	isMolAuto = true;	
	var molIds = new Array();
	if (isMolAuto)	{
		for (var i=0; i < names.length - 1; i++)	{
	  	  	var id = names[i].split("&&")[0]; // for molecules, name is in format "id&&name"
	  	  	molIds.push(id);
	  		names[i] = names[i].split("&&")[1];
	  	}
	}

	var isBelow = ttBelow();  // whether Tooltip is below entry node	
	var suggestList = document.getElementById('suggestList'+ucfirst(nameStrings[0]));
	suggestList.innerHTML = "";
	var totalListHeight = 0;
	var listWidth = suggestList.style.width;
	for(var i=0; i < names.length - 1; i++) 
	{
	  var suggestItem = document.createElement("div");
	  suggestItem.id = "resultlist" + i;
	  suggestItem.onmouseover = function(){selectItemAutoComplete(this);};
	  suggestItem.onmouseout = function(){unselectItemAutoComplete(this);};
	  
	  if (!dojo.isIE && isMolAuto)	{
		suggestItem.value = molIds[i];
		suggestItem.onclick = function(){setMoleculeAutoComplete(this.textContent, nameStrings[0], this.value);};
	  }
	  else if (dojo.isIE && isMolAuto)	{
		suggestItem.value = molIds[i];
		suggestItem.onclick = function(){setMoleculeAutoComplete(this.innerText, nameStrings[0], this.value);};
	  }
	  else	{
		suggestItem.value = nameStrings[i];
		suggestItem.onclick = function(){setOrganismAutoComplete(this.innerHTML, nameStrings[0]);};
	  }
	  suggestItem.className = "suggestLink";
	  suggestItem.innerHTML = names[i];	  	
	  suggestList.style.top = "";
	  suggestList.style.borderBottomWidth = "";
	  suggestList.style.borderTopWidth = "";
	  	  
	  if (dojo.isIE)	{  
		  // to fix IE quirk re: SELECT elements
		  // see http://www.macridesweb.com/oltest/IframeShim.html
		  var iframe = document.createElement("iframe");
		  iframe.style.top = "0px";
		  iframe.style.left = "0px";
		  iframe.style.position = "absolute";
		  iframe.frameBorder = "1";
		  iframe.scrolling = "no";
		  iframe.style.zIndex = "-1";
		  iframe.style.filter="progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)";
		  suggestItem.appendChild(iframe);
	  }	  
	  suggestList.appendChild(suggestItem);
	}		
	if (names.length > 1) {
		suggestList.style.display = "";		
		totalListHeight = suggestList.scrollHeight;
		var listWidth = suggestList.scrollWidth;
		var itemHeight = totalListHeight / (names.length - 1);
		var lastItemLoc = findPos(suggestList.lastChild.previousSibling);
		var bottomWindow = getScreenSize();
		var flipDisplayList = false;
		  //console.log("lastitem = " + lastItemLoc[1]);
		  //console.log("bottomwindow = " + bottomWindow[1]);
		if (lastItemLoc[1] >= bottomWindow[1] )	{
		  flipDisplayList = true;
		}	
		if (flipDisplayList || !isBelow)	{  // Tooltip is above entry node
		  if (flipDisplayList == false)	{
		    suggestList.style.top = "-" + totalListHeight + "px";
		  }
		  else {
			suggestList.style.top = "-" + (totalListHeight - itemHeight) + "px";
		  }
		  suggestList.style.borderBottomWidth = "0px";
		  suggestList.style.borderTopWidth = "1px";  
		}
		else	{
		  suggestList.style.top = "";
		  suggestList.style.borderBottomWidth = "";
		  suggestList.style.borderTopWidth = "";
		}
		if(isListNew == true) {
			//changeOpacityAutoComplete(suggestList, 0, false);
			isListNew = false;		  
		}			
	} else {
		suggestList.style.display = "none";
	}
}

function getSuggestionsAutoComplete(organism,type)
{
	var url = "autoCompleteServerSide.php";
	var length = organism.value.length;
	var index = organism.value.lastIndexOf(";");
	var searchValue = organism.value;
	if(index != -1) {
		searchValue = organism.value.substring(0,index+1) + organism.value.substring(index+1, length).trim();
		length = organism.value.substring(index+1, length).trim().length;		
	}
	var category = organism.title;
	if (category == undefined || category == null || category == "")	{
		category = "all";
	}
	
	//var payload = "name=" + searchValue.trim() + "&type=" + type + "&category=" + category;
	var payload = {name:searchValue.trim(), type:type, category:category};
	if(index != length-1 && length > 1) {
		sendRequestAutoComplete(url, payload);
	}	
}
String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
};

function checkKeyAutoComplete(e, obj)
{
	var type = obj.id;
	var organism = document.getElementById(type);
	/* get key pressed */
    var code = (e && e.which) ? e.which : window.event.keyCode;  
	/* if up or down move thru the suggestion list */
	if (code == KEYDOWN || code == KEYUP)
    {
        var index = gSelectedIndex;
        if (code ==  KEYDOWN)
           index++;
        else	{	
           index--;
           if (index == -2)	{  // flipped result list
        	  index = 9; 
           }
        }

       /* find item in suggestion list being looked at if any */
       var selectedItem = document.getElementById("resultlist" + index);
       while (!selectedItem && index >= 0)	{
         // find selectedItem with highest index when list is flipped
    	 index--;
    	 selectedItem = document.getElementById("resultlist" + index);
       }
       if (selectedItem)
       {		  	      
    	   var theText;
    	   if (dojo.isIE)	{
    		 theText = selectedItem.innerText;
    	   }
    	   else	{
    		 theText = selectedItem.textContent;   
    	   }
    	   selectItemAutoComplete(selectedItem);
           	var stringIndex = organism.value.lastIndexOf(";");
           	if(stringIndex == -1) {
				organism.value = replaceStringAutoComplete(theText);
			}else {
				organism.value = organism.value.substring(0,stringIndex) + ";" + replaceStringAutoComplete(theText);
			}
		   /* set the field to the suggestion */
       }
    }
	else if (code == ENTER)  /* clear list if enter key */
	{	
	
		var selectedItem = document.getElementById("resultlist" + gSelectedIndex);
		var applyButton = dojo.byId("closeDialog" + ucfirst(type));
		if (selectedItem == null)	{ // ENTER with no list clicks Apply button in texttool
			applyButton.click();
		}
		else	{
			selectedItem.onclick();
			clearListAutoComplete(type);
			if(organism.value.lastIndexOf(";") != organism.value.length - 1){
				organism.value = organism.value + ";";
			}
			applyButton.click();
		}
		
		
		//var applyButton = dojo.byId("closeDialog" + ucfirst(type));
		//applyButton.click();

	}else if (code == ESC) {
		//var anns = (obj.name).replace("Tool","");
		//var node = document.getElementsByName((obj.name).replace("Tool",""))[0];
		var node = dojo.byId((obj.name).replace("Tool",""));
		if (isBlank(node))	{
			node = document.getElementsByName((obj.name).replace("Tool",""))[0];
		}
		var originalText = node.value;
		clearListAutoComplete(type);
		var dialogId = "dialogData" + ucfirst(type.replace("Tool",""));
		var dialog = dijit.byId(dialogId);	
		node.blur();
		
	}else 
		if (organism == obj) /* otherwise get more suggestions */ {
			gSelectedIndex = -1;
			var func = function(){
				getSuggestionsAutoComplete(obj, type);
			};
			if (organism.zid) {
				clearTimeout(organism.zid);
			}
			organism.zid = setTimeout(func, 100);
		}
}

function selectItemAutoComplete(selectedItem) 
{
    var lastItem = document.getElementById("resultlist" + gSelectedIndex);
    if (lastItem != null)
        unselectItemAutoComplete(lastItem);

    selectedItem.className = 'suggestLinkOver';
    gSelectedIndex = parseInt(selectedItem.id.substring(10));
}

function unselectItemAutoComplete(selectedItem) 
{
	selectedItem.className = 'suggestLink';
}

function replaceStringAutoComplete(s) {
	var temp1 = s.replace("<b>","");
	var temp2 = temp1.replace("</b>","");
	temp1 = temp2.replace("<B>","");
	temp2 = temp1.replace("</B>","");
	
	var pos = temp2.indexOf("(taxid:"); 
	var pos2 = temp2.indexOf("(id:"); 
	if(pos != -1) {
		temp2 = temp2.substring(0,pos-1);
	}else if(pos2 != -1) {
		temp2 = temp2.substring(0,pos2-1);
	}
	return temp2;
}

function setOrganismAutoComplete(value, type) 
{
	var initialVal = document.getElementById(type).value;
	var index = initialVal.lastIndexOf(";");
	if(index == -1) {
		document.getElementById(type).value = replaceStringAutoComplete(value) + ";";
	}else {
		document.getElementById(type).value = initialVal.substring(0,index) + ";" + replaceStringAutoComplete(value) + ";";
	}
    clearListAutoComplete(type);
}

/**
 * 
 */
function setMoleculeAutoComplete(/*innerHTML of one suggested item*/ value, 
		/*DOM id field of popup*/ type, 
		/*ID corresponding to suggestion*/ id)	
{

	if (dojo.isIE)	{
	// delete iframetag if present (IE quirk)
		var patt = new RegExp("<IFRAME.*</IFRAME>", "ig");
		value = value.replace(patt, "");
	}
	// Remove any synonym text before proceeding.  Synonym text is directly after '[]' text block for accession.
	var assayObiPattern = /assayObi/;
	var isAssayObi = assayObiPattern.test(type);
	if (value.lastIndexOf("]") != -1  && !isAssayObi)	{
		var endOfAccIndex = value.lastIndexOf("]");
		value = value.slice(0,endOfAccIndex + 1);
	}
	
	// For Assay OBI only:
	//	Remove all supplementary text within, and including, the "[]" 
	
	if (isAssayObi)	{
		/// check to make sure brackets are there.  if not, do nothing.
		var firstBracketIdx = value.indexOf("[");
		var secondBracketIdx = value.lastIndexOf("]");
		if (firstBracketIdx != -1 && secondBracketIdx != -1)	{
			// strip out the text in brackets then.
			var insideBrackets = value.slice(firstBracketIdx, secondBracketIdx + 1);
			value = value.replace(insideBrackets, "");
			value = value.trim();
		} else	{
			// do nothing for now.
		}
		
	}
	
	var idStr = new String(id);  	
	var autoIdField = type.replace("NameTool", "AutoIds");
	var initialVal = document.getElementById(type).value;
	var initialIds = document.getElementById(autoIdField).value;
	var index = initialVal.lastIndexOf(";");
	var indexIds = initialIds.lastIndexOf(";");
	if(index == -1) {  // Empty field, i.e. no previous names present
		document.getElementById(type).value = replaceStringAutoComplete(value) + ";";
		document.getElementById(autoIdField).value = replaceStringAutoComplete(idStr) + ";";
	} else {  // Append new item onto list of existing names
		document.getElementById(type).value = initialVal.substring(0,index) + ";" + replaceStringAutoComplete(value) + ";";
		document.getElementById(autoIdField).value = initialIds.substring(0,indexIds) + ";" + replaceStringAutoComplete(idStr) + ";";
	}
	clearListAutoComplete(type);
	
}
function checkClickAutoComplete(e)
{
	var target = ((e && e.target) ||(window && window.event && window.event.srcElement));
    var tag = target.tagName;
    if (tag.toLowerCase() != "input" && tag.toLowerCase() != "div")
    	clearListAutoComplete();
}

function clearListAutoComplete(type)
{
	var suggestList = document.getElementById('suggestList'+ucfirst(type));
	isListNew = true;
	var func = function() {clearListPauseAutoComplete(suggestList);}; 
	setTimeout(func, 500);
}
function clearListPauseAutoComplete(suggestList) {
	
	suggestList.innerHTML = '';
	suggestList.style.display = "none";
}
function clickclearAutoComplete(thisfield, defaulttext) {
	if (thisfield.value == defaulttext) {
		thisfield.value = "";
		//thisfield.className = "sequenceField";
	}
}
function clickrecallAutoComplete(thisfield, defaulttext) {
	clearListAutoComplete(thisfield.id);
}
function ucfirst(str) {
    var firstLetter = str.substr(0, 1);
    return firstLetter.toUpperCase() + str.substr(1);
}
function lcfirst(str) {
    var firstLetter = str.substr(0, 1);
    return firstLetter.toLowerCase() + str.substr(1);
}
function newDialogBox(id) {
	// create a TooltipDialog from some node in the dom (id="dialogData") 
	
	/**
	 * Ad. Search autocompletes use a "_[subsection]" suffix for each button and 
	   dialog box; Simple Search does not. An example suffix would be "_epitope1" for the 
	   first button/dialog box for epitope section, and "_epitope10" for the tenth in the epitope section.  
	   To handle the Ad. Search autocompletes, and 
	   still be compatible with Simple Search, check for suffix and handle
	   rest of this method accordingly.  
	*/
	var suffix;
	var idArray = id.split("_", 2);  // array of size 2
	if (idArray.length > 1)	{  // Ad. Search autocomplete
		suffix = ucfirst(idArray[1]);
	}
	else	{  // Simple Search autocomplete
		suffix = "";
	}
	var ttd = new dijit.TooltipDialog({}, id);						
	var textBoxId = lcfirst(idArray[0].replace("dialogData",""));		
	var dialogTextBoxId = lcfirst(textBoxId) + "Tool";
	textBoxId = textBoxId + suffix;
	dialogTextBoxId = dialogTextBoxId + suffix;
	var closeDialogId = "closeDialog" + ucfirst(dialogTextBoxId);

	var npPattern = /nonPeptidic/;
	var saPattern = /sourceAntigen/;
	var disPattern = /disease/;
	var smPattern = /sourceMolecule/;
	var soPattern = /sourceOrganism/;
	var assayPattern = /assay/;
	var allelePattern = /allele/;
	var assayObiPattern = /assayObi/;
	
	var isMolAuto = false;
	var sourceIds; 
	var dialogMolIds = dialogTextBoxId.replace("NameTool" + suffix, "AutoIds" + suffix);
	if (npPattern.test(dialogTextBoxId))	{
		isMolAuto = true;
		sourceIds = "source1Id" + suffix;
	}
	else if(saPattern.test(dialogTextBoxId)) {
		isMolAuto = true;
		sourceIds = "sourceId" + suffix;
	}
	else if(disPattern.test(dialogTextBoxId)) {
		isMolAuto = true;
		sourceIds = "diseaseId" + suffix;
	}	
	else if(smPattern.test(dialogTextBoxId)) {
		isMolAuto = true;
		sourceIds = "sourceMoleculeId" + suffix;
	}
	else if(soPattern.test(dialogTextBoxId)) {
		isMolAuto = true;
		sourceIds = "sourceOrganismId" + suffix;
	}
	//  assayObiPattern used several times in file and stored as global variable above
	else if(assayPattern.test(dialogTextBoxId) && !assayObiPattern.test(dialogTextBoxId)) {
		isMolAuto = true;
		sourceIds = "assayId" + suffix;
	}
	else if(allelePattern.test(dialogTextBoxId)) {
		isMolAuto = true;
		sourceIds = "alleleId" + suffix;
	}
	else if(assayObiPattern.test(dialogTextBoxId)) {
		isMolAuto = true;
		sourceIds = "assayObiId" + suffix;
	}
	
	// open the tooltip when some node is clicked: 
	var node = dojo.byId(textBoxId);
	var cg = dojo.byId(closeDialogId);
	dojo.query(node).onfocus(function(e){
			dijit.popup.open({
				around: node,
				popup: ttd
			});
			
		clickclearAutoComplete(this, DEFAULT_INPUT_TEXT);	
		dojo.byId(dialogTextBoxId).value=document.getElementById(textBoxId).value;
		if (isMolAuto)	{
			document.getElementById(dialogMolIds).value=
				document.getElementById(sourceIds).value;
		}
		//disable input box while tooltip is open
		node.disabled = true;
		
	});		
	// setup some close logic for this tooltipdialog: 
	dojo.connect(ttd, "onBlur", function(){	
		var originalValue = document.getElementById(textBoxId).value.trim();
		if (isMolAuto) { 
		  var originalIds = document.getElementById(sourceIds).value.trim();
		}
		dijit.popup.close(ttd);
		document.getElementById(textBoxId).value=originalValue;
		if (isMolAuto)	{ 
		  document.getElementById(sourceIds).value = originalIds;
		}
		clearListAutoComplete(dialogTextBoxId);
		checkBlankInput(node);
	});
	// enable input box upon close of tooltip
	dojo.connect(ttd, "onClose", function(){
		node.disabled = false;
	});
	dojo.query(cg).onclick(function(){dijit.popup.close(ttd);});
}

//Checks to see if Tooltip pops up above or below the search entry node
function ttBelow ()		{
	var popups = dojo.query(".dijitPopup");
	var theclassname = popups[0].childNodes[0].className;
	var patt1 = new RegExp("dijitTooltipBelow");
	var isBelow = (patt1.test(theclassname)) ? true : false;
	return isBelow;
}
function createIFrame (itemWidth, itemHeight)	{	  
	var iframe = document.createElement("iframe");
	  iframe.style.top = "0px";
	  iframe.style.left = "0px";
	  iframe.style.position = "absolute";
	  iframe.frameBorder = "0";
	  //iframe.src = "javascript:false;";
	  iframe.scrolling = "no";
	  iframe.style.zIndex = "0";
	  iframe.style.width = itemWidth;
	  iframe.style.height = itemHeight;
	  iframe.style.filter="progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)";	
	return iframe;
}

//Gotten from http://www.quirksmode.org/js/findpos.html
function findPos(obj) {
 var curleft = curtop = 0;
 if (obj && obj.offsetParent) {
	    do {
	         curleft += obj.offsetLeft;
	         curtop += obj.offsetTop;
	     } while (obj = obj.offsetParent);
 }
 return [curleft,curtop];
}
function getScreenSize() {
	  var myWidth = 0, myHeight = 0;
	  if( typeof( window.innerWidth ) == 'number' ) {
	    //Non-IE
	    myWidth = window.innerWidth;
	    myHeight = window.innerHeight;
	  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
	    //IE 6+ in 'standards compliant mode'
	    myWidth = document.documentElement.clientWidth;
	    myHeight = document.documentElement.clientHeight;
	  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
	    //IE 4 compatible
	    myWidth = document.body.clientWidth;
	    myHeight = document.body.clientHeight;
	  }
	  return [myWidth, myHeight];
}

function clearAutoCompleteData(type, suffix)	{
	// type == which type of autocomplete, e.g. Source Organism, or Host Organism
	if (suffix == null) suffix = "";
	type = type.replace(" ", ""); // for compatibility with both home page and adv. search page DOM element nomenclature
	
	
	if (type == "SourceOrganism")	{
		dojo.byId('sourceOrganismNameTool' + suffix).value = "";
		dojo.byId('sourceOrganismName' + suffix).value = "";
		dojo.byId('sourceOrganismId' + suffix).value = "";
		dojo.byId('sourceOrganismAutoIds' + suffix).value = "";
	}
	else if (type == "HostOrganism")	{
		dojo.byId('hostOrganismNameTool' + suffix).value = "";
		dojo.byId('hostOrganismName' + suffix).value = "";
		dojo.byId('hostOrganismId' + suffix).value = "";
		dojo.byId('hostOrganismAutoIds' + suffix).value = "";
	}
	else if (type == "NonPeptidic")	{
		dojo.byId('nonPeptidicNameTool'+ suffix).value = "";
		dojo.byId('nonPeptidicName'+ suffix).value = "";
		dojo.byId('source1Id'+ suffix).value = "";
		dojo.byId('source1Name'+ suffix).value = "";
		dojo.byId('nonPeptidicAutoIds'+ suffix).value = "";
	}
	else if (type == "SourceAntigen")	{
		dojo.byId('sourceAntigenNameTool'+ suffix).value = "";
		dojo.byId('sourceAntigenName'+ suffix).value = "";
		dojo.byId('sourceId'+ suffix).value = "";
		dojo.byId('sourceAntigenAutoIds'+ suffix).value = "";		
	}
	else if (type == "Disease")	{
		try	{  // home page only.
			dojo.byId('diseaseVisibleNameTool'+ suffix).value = "";
			dojo.byId('diseaseVisibleAutoIds'+ suffix).value = "";		
			dojo.byId('diseaseVisibleName'+ suffix).value = "";
		}
		catch(err)	{  // adv. search only
			dojo.byId('diseaseNameTool' + suffix).value = "";
			dojo.byId('diseaseAutoIds'+ suffix).value = "";
		}	
		dojo.byId('diseaseName'+ suffix).value = "";
		dojo.byId('diseaseId'+ suffix).value = "";
	}
	else if (type == "Assay")	{
		dojo.byId('assayNameTool' + suffix).value = "";
		dojo.byId('assayName' + suffix).value = "";
		dojo.byId('assayId' + suffix).value = "";
		dojo.byId('assayAutoIds' + suffix).value = "";
	}
	else if (type == "Allele")	{
		dojo.byId('alleleNameTool' + suffix).value = "";
		dojo.byId('alleleName' + suffix).value = "";
		dojo.byId('alleleId' + suffix).value = "";
		dojo.byId('alleleAutoIds' + suffix).value = "";
	}
	else if (type == "SourceMolecule")	{
		dojo.byId('sourceMoleculeNameTool' + suffix).value = "";
		dojo.byId('sourceMoleculeName' + suffix).value = "";
		dojo.byId('sourceMoleculeId' + suffix).value = "";
		dojo.byId('sourceMoleculeAutoIds' + suffix).value = "";
	}
	else if (type == "AssayObi")	{
		dojo.byId('assayObiNameTool' + suffix).value = "";
		dojo.byId('assayObiName' + suffix).value = "";
		dojo.byId('assayObiId' + suffix).value = "";
		dojo.byId('assayObiAutoIds' + suffix).value = "";
	}
}


// generalized for all pages using autocomplete
function applyAlleleAuto(/*String*/ suffix)	{
	// Puts value and ID from pop up into page form
	applyPopupValuesToForm(suffix, "allele");
}
function applyAssayAuto(/*String*/ suffix)	{
	// Puts value and ID from pop up into page form
	applyPopupValuesToForm(suffix, "assay");
}
function applyAssayObiAuto(/*String*/ suffix)	{
	// Puts value and ID from pop up into page form
	applyPopupValuesToForm(suffix, "assayObi");
}
function applyNonPeptidicAuto()	{
	// Puts value and ID from pop up into home page form
	var npValue = document.getElementById('nonPeptidicNameTool').value.trim();
	var visibleName = dojo.byId('nonPeptidicName');
	document.getElementById('source1Name').value = 
		visibleName.value = npValue;
	document.getElementById('source1Id').value = 
		document.getElementById('nonPeptidicAutoIds').value;
	
	checkBlankInput(visibleName);
}

function applyDiseaseAuto(/*String*/ suffix)	{
	// Puts value and ID from pop up into home page form
	if (suffix == null) suffix = "";
	
	try	{  // handles for home page (unique situation for now)
		var visibleNameTool = dojo.byId('diseaseVisibleNameTool' + suffix);
		var diseaseVisibleName = dojo.byId('diseaseVisibleName' + suffix);
		var diseaseName = dojo.byId('diseaseName' + suffix);
		var diseaseId = dojo.byId('diseaseId' + suffix);
		var diseaseVisibleAutoIds = dojo.byId('diseaseVisibleAutoIds' + suffix);
		var nameToolValue = visibleNameTool.value.trim();
		diseaseVisibleName.value = diseaseName.value = nameToolValue;
		diseaseId.value = diseaseVisibleAutoIds.value;
	}
	catch(err)	{  // handles for adv. search
		applyPopupValuesToForm(suffix, "disease");
	}
	
}
function applyHostOrganismAuto(/*String*/ suffix)	{
	// Puts value and ID from pop up into page form
	applyPopupValuesToForm(suffix, "hostOrganism");
}
function applySourceAntigenAuto(/*String*/ suffix)	{
	// Puts value and ID from pop up into page form
	
	var saValue = document.getElementById('sourceAntigenNameTool').value.trim();
	document.getElementById('sourceAntigenName').value = 
		document.getElementById('sourceName').value = saValue;
	
	document.getElementById('sourceId').value = 
		document.getElementById('sourceAntigenAutoIds').value;
	
	//applyPopupValuesToForm(suffix, "sourceAntigen");
	
	
}
function applySourceMoleculeAuto(/*String*/ suffix)	{
	// Puts value and ID from pop up into page form
	applyPopupValuesToForm(suffix, "sourceMolecule");
}
function applySourceOrganismAuto(/*String*/ suffix)	{
	// Puts value and ID from pop up into page form
	applyPopupValuesToForm(suffix, "sourceOrganism");
	
}
function addACListener()	{
	//For auto complete
	var sug = dojo.query(".suggestList");
	for(var i=0; i < sug.length; i ++) {
		sug[i].style.display = "none";
	}
	var autoTextBoxs = dojo.query(".autoTextBox");
	var textBox = null;
	for(var j=0; j < autoTextBoxs.length; j++) {
		textBox = autoTextBoxs[j];	
		textBox.onkeyup = function(e){
		        checkKeyAutoComplete(e, this);
		};		
	    if (textBox.value != DEFAULT_INPUT_TEXT && textBox.value != null) {
	        textBox.className = "sequenceField";
	    }
	}	
}
function applySelectionToPopup(/*String, not null if used in Ad. Search*/ suffix,
							/*String, type of autoC, such as "sourceOrganism"*/ type,
							/*integer, index of selected item from list*/ gSelectedIndex)	
{	
	if (suffix == null) suffix = "";
	var visibleNameTool = dojo.byId(type + 'NameTool' + suffix);
	//var visibleName = dojo.byId(type + 'Name' + suffix);
	//var theId = dojo.byId(type + 'Id' + suffix);
	//var visibleAutoIds = dojo.byId(type + 'AutoIds' + suffix);
	var nameToolValue = visibleNameTool.value.trim();
	var selectedItem = dojo.byId("resultlist" + gSelectedIndex);
	if (!isBlank(selectedItem))	{
	  setMoleculeAutoComplete(nameToolValue, visibleNameTool.id, selectedItem.value);
	}
	//visibleName.value = nameToolValue;
	//theId.value = visibleAutoIds.value;
}
function applyPopupValuesToForm(/*String, not null if used in Ad. Search*/ suffix,
		/*String, type of autoC, such as "sourceOrganism"*/ type)	{
	if (suffix == null) suffix = "";
	var visibleNameTool = dojo.byId(type + 'NameTool' + suffix);
	var visibleName = dojo.byId(type + 'Name' + suffix);
	var theId = dojo.byId(type + 'Id' + suffix);
	var visibleAutoIds = dojo.byId(type + 'AutoIds' + suffix);
	visibleName.value = visibleNameTool.value.trim();
	theId.value = visibleAutoIds.value;
	
	checkBlankInput(visibleName);
	
}
function checkForAutoNameDelete(type, suffix)	{
	// Get Tooltext DOM element
	if (suffix == null) suffix = "";
	else suffix = ucfirst(suffix);
	var autoTextBox = dojo.byId(type + "NameTool" + suffix);
	var autoIdBox = dojo.byId(type + "AutoIds" + suffix);
	
	var numOfNames = ((autoTextBox.value).split(";")).length;
	var numOfIds = ((autoIdBox.value).split(";")).length;
	if (numOfNames != numOfIds)	{
		// delete the ID(s) corresponding to the name(s) deleted
		
	}
	else	{
		// do nothing
	}
	
}
function checkBlankInput(node)	{
	if (isBlank(node.value))  {	
		node.value = DEFAULT_INPUT_TEXT;
		node.style.color = "#A8A8A8";
	}
	else	{
		node.style.color = "#000000";
	}
}
