var gSelectedIndex = -1;
var isListNew = true;
/* key code constants */
var ENTER = 13;
var KEYUP = 38;
var KEYDOWN = 40;
var ESC = 27;

function sendRequestAutoComplete(url, payload)
{	
	dojo.xhrGet	(
		{
			url: url+"?"+payload,
			handleAs: "text",
			sync: "true",
			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)
{
	//alert(dojo.query(".suggestList")[0].style.display);
    //alert(response);
	var nameStrings =  response.split("|");	
	var names = nameStrings[1].split("\n");
	var isMolAuto = (nameStrings[0] == "sourceAntigenNameTool"  
		|| nameStrings[0] == "nonPeptidicNameTool");
	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 (isMolAuto)	{
		suggestItem.value = molIds[i];
		suggestItem.onclick = function(){setMoleculeAutoComplete(this.innerHTML, nameStrings[0], this.value);};
	  }
	  else	{
	    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;		
	}
	//organism.value = organism.value.substring(0,index+1) + organism.value.substring(index+1, length).trim();
	var payload = "name=" + searchValue.trim() + "&type=" + type;
	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--;

       /* find item in suggestion list being looked at if any */
       var selectedItem = document.getElementById("resultlist" + index);
       if (selectedItem)
       {		  	      
           selectItemAutoComplete(selectedItem);
           	var stringIndex = organism.value.lastIndexOf(";");
			if(stringIndex == -1) {
				organism.value = replaceStringAutoComplete(selectedItem.innerHTML);
			}else {
				organism.value = organism.value.substring(0,stringIndex) + ";" + replaceStringAutoComplete(selectedItem.innerHTML);
			}
		   /* set the field to the suggestion */
       }
    }
	else if (code == ENTER)  /* clear list if enter key */
	{	
		/*Should be the code needed to add the on Enter selects the first value 
		if(gSelectedIndex == -1) {
			var stringIndex = organism.value.lastIndexOf(";");			
			var selectedItem = document.getElementById("resultlist0");
			if(stringIndex == -1) {
				organism.value = replaceStringAutoComplete(selectedItem.innerHTML);
			}else {
				organism.value = organism.value.substring(0,stringIndex) + ";" + replaceStringAutoComplete(selectedItem.innerHTML);
			}
		}
		*/
		clearListAutoComplete(type);
		if(organism.value.lastIndexOf(";") != organism.value.length-1){
			organism.value = organism.value + ";";
		}
		var applyButton = dojo.byId("closeDialog" + ucfirst(type));
		applyButton.click();

	}else if (code == ESC) {
		var 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, 500);
		}
}

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, 
		/*molecule ID corresponding to suggestion*/ molId)	
{
	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 endOfAccIndex = value.lastIndexOf("]");
	value = value.slice(0,endOfAccIndex + 1);
		
	var molIdStr = new String(molId);
	var molAutoIdField = type.slice(0, type.search("NameTool")) + "AutoIds";	/// use in home page form  	
	var initialVal = document.getElementById(type).value;
	var initialIds = document.getElementById(molAutoIdField).value;
	var index = initialVal.lastIndexOf(";");
	var indexIds = initialIds.lastIndexOf(";");
	if(index == -1) {
		document.getElementById(type).value = replaceStringAutoComplete(value) + ";";
		document.getElementById(molAutoIdField).value = replaceStringAutoComplete(molIdStr) + ";";
	} else {
		document.getElementById(type).value = initialVal.substring(0,index) + ";" + replaceStringAutoComplete(value) + ";";
		document.getElementById(molAutoIdField).value = initialIds.substring(0,indexIds) + ";" + replaceStringAutoComplete(molIdStr) + ";";
	}
    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;
	//changeOpacityAutoComplete(suggestList, 100, 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") 
		
	var ttd = new dijit.TooltipDialog({}, id);						
	var textBoxId = lcfirst(id.replace("dialogData",""));		
	var dialogTextBoxId = lcfirst(textBoxId) + "Tool";
	var closeDialogId = "closeDialog" + ucfirst(dialogTextBoxId);
	
	var npPattern = /nonPeptidic/;
	var saPattern = /sourceAntigen/;
	var isMolAuto = false;
	var dialogMolIds;
	var sourceIds; 
	if (npPattern.test(dialogTextBoxId))	{
		isMolAuto = true;
		dialogMolIds = dialogTextBoxId.replace("NameTool", "AutoIds");
		sourceIds = "source1Id";
	}
	else if(saPattern.test(dialogTextBoxId)) {
		isMolAuto = true;
		dialogMolIds = dialogTextBoxId.replace("NameTool", "AutoIds");
		sourceIds = "sourceId";
	}
	
	// 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, 'Enter Search');	
		document.getElementById(dialogTextBoxId).value=document.getElementById(textBoxId).value;
		if (isMolAuto)	{
			document.getElementById(dialogMolIds).value=
				document.getElementById(sourceIds).value;
		}
	});		
	// setup some close logic for this tooltipdialog: 
	//dojo.query("#closer").onclick(function(e){ dijit.popup.close(tt); });
	//dojo.connect(ttd, "onBlur", function(){dijit.popup.close(ttd);document.getElementById(textBoxId).value=document.getElementById(dialogTextBoxId).value.trim();});
	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;
				
				});
	//dojo.connect(dijit.byId("closeDialog"), "onClick", function(){dijit.popup.close(tt);});
	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];
	}


