var nowtime = (new Date()).getTime();
var req1, req2, req3, l, r;
// ===================================================================
// Author: Matt Kruse <matt@ajaxtoolbox.com>
// WWW: http://www.AjaxToolbox.com/
// ===================================================================
function AjaxRequest(){var req =new Object();
req.timeout =null;
req.generateUniqueUrl =true;
req.url =window.location.href;
req.method ="GET";
req.async =true;
req.username =null;
req.password =null;
req.parameters =new Object();
req.requestIndex =AjaxRequest.numAjaxRequests++;
req.responseReceived =false;
req.groupName =null;
req.queryString ="";
req.responseText =null;
req.responseXML =null;
req.status =null;
req.statusText =null;
req.aborted =false;
req.xmlHttpRequest =null;
req.onTimeout=null;
req.onLoading=null;
req.onLoaded=null;
req.onInteractive=null;
req.onComplete=null;
req.onSuccess=null;
req.onError=null;
req.onGroupBegin=null;
req.onGroupEnd=null;
req.xmlHttpRequest =AjaxRequest.getXmlHttpRequest();
if(req.xmlHttpRequest==null){return null;}req.xmlHttpRequest.onreadystatechange =
function(){if(req==null || req.xmlHttpRequest==null){return;}if(req.xmlHttpRequest.readyState==1){req.onLoadingInternal(req);}if(req.xmlHttpRequest.readyState==2){req.onLoadedInternal(req);}if(req.xmlHttpRequest.readyState==3){req.onInteractiveInternal(req);}if(req.xmlHttpRequest.readyState==4){req.onCompleteInternal(req);}};
req.onLoadingInternalHandled=false;
req.onLoadedInternalHandled=false;
req.onInteractiveInternalHandled=false;
req.onCompleteInternalHandled=false;
req.onLoadingInternal=
function(){if(req.onLoadingInternalHandled){return;}AjaxRequest.numActiveAjaxRequests++;
if(AjaxRequest.numActiveAjaxRequests==1 && typeof(window['AjaxRequestBegin'])=="function"){AjaxRequestBegin();}if(req.groupName!=null){if(typeof(AjaxRequest.numActiveAjaxGroupRequests[req.groupName])=="undefined"){AjaxRequest.numActiveAjaxGroupRequests[req.groupName] =0;}AjaxRequest.numActiveAjaxGroupRequests[req.groupName]++;
if(AjaxRequest.numActiveAjaxGroupRequests[req.groupName]==1 && typeof(req.onGroupBegin)=="function"){req.onGroupBegin(req.groupName);}}if(typeof(req.onLoading)=="function"){req.onLoading(req);}req.onLoadingInternalHandled=true;};
req.onLoadedInternal=
function(){if(req.onLoadedInternalHandled){return;}if(typeof(req.onLoaded)=="function"){req.onLoaded(req);}req.onLoadedInternalHandled=true;};
req.onInteractiveInternal=
function(){if(req.onInteractiveInternalHandled){return;}if(typeof(req.onInteractive)=="function"){req.onInteractive(req);}req.onInteractiveInternalHandled=true;};
req.onCompleteInternal=
function(){if(req.onCompleteInternalHandled || req.aborted){return;}req.onCompleteInternalHandled=true;
AjaxRequest.numActiveAjaxRequests--;
if(AjaxRequest.numActiveAjaxRequests==0 && typeof(window['AjaxRequestEnd'])=="function"){AjaxRequestEnd(req.groupName);}if(req.groupName!=null){AjaxRequest.numActiveAjaxGroupRequests[req.groupName]--;
if(AjaxRequest.numActiveAjaxGroupRequests[req.groupName]==0 && typeof(req.onGroupEnd)=="function"){req.onGroupEnd(req.groupName);}}req.responseReceived =true;
req.status =req.xmlHttpRequest.status;
req.statusText =req.xmlHttpRequest.statusText;
req.responseText =req.xmlHttpRequest.responseText;
req.responseXML =req.xmlHttpRequest.responseXML;
if(typeof(req.onComplete)=="function"){req.onComplete(req);}if(req.xmlHttpRequest.status==200 && typeof(req.onSuccess)=="function"){req.onSuccess(req);}else if(typeof(req.onError)=="function"){req.onError(req);}delete req.xmlHttpRequest['onreadystatechange'];
req.xmlHttpRequest =null;};
req.onTimeoutInternal=
function(){if(req!=null && req.xmlHttpRequest!=null && !req.onCompleteInternalHandled){req.aborted =true;
req.xmlHttpRequest.abort();
AjaxRequest.numActiveAjaxRequests--;
if(AjaxRequest.numActiveAjaxRequests==0 && typeof(window['AjaxRequestEnd'])=="function"){AjaxRequestEnd(req.groupName);}if(req.groupName!=null){AjaxRequest.numActiveAjaxGroupRequests[req.groupName]--;
if(AjaxRequest.numActiveAjaxGroupRequests[req.groupName]==0 && typeof(req.onGroupEnd)=="function"){req.onGroupEnd(req.groupName);}}if(typeof(req.onTimeout)=="function"){req.onTimeout(req);}delete req.xmlHttpRequest['onreadystatechange'];
req.xmlHttpRequest =null;}};
req.process =
function(){if(req.xmlHttpRequest!=null){if(req.generateUniqueUrl && req.method=="GET"){req.parameters["AjaxRequestUniqueId"] =new Date().getTime() + "" + req.requestIndex;}var content =null;
for(var i in req.parameters){if(req.queryString.length>0){req.queryString +="&";}req.queryString +=encodeURIComponent(i) + "=" + encodeURIComponent(req.parameters[i]);}if(req.method=="GET"){if(req.queryString.length>0){req.url +=((req.url.indexOf("?")>-1)?"&":"?") + req.queryString;}}req.xmlHttpRequest.open(req.method,req.url,req.async,req.username,req.password);
if(req.method=="POST"){if(typeof(req.xmlHttpRequest.setRequestHeader)!="undefined"){req.xmlHttpRequest.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');}content =req.queryString;}if(req.timeout>0){setTimeout(req.onTimeoutInternal,req.timeout);}req.xmlHttpRequest.send(content);}};
req.handleArguments =
function(args){for(var i in args){if(typeof(req[i])=="undefined"){req.parameters[i] =args[i];}else{req[i] =args[i];}}};
req.getAllResponseHeaders =
function(){if(req.xmlHttpRequest!=null){if(req.responseReceived){return req.xmlHttpRequest.getAllResponseHeaders();}alert("Cannot getAllResponseHeaders because a response has not yet been received");}};
req.getResponseHeader =
function(headerName){if(req.xmlHttpRequest!=null){if(req.responseReceived){return req.xmlHttpRequest.getResponseHeader(headerName);}alert("Cannot getResponseHeader because a response has not yet been received");}};
return req;}AjaxRequest.getXmlHttpRequest =function(){if(window.XMLHttpRequest){return new XMLHttpRequest();}else if(window.ActiveXObject){/*@cc_on @*/
/*@if(@_jscript_version >=5)
try{return new ActiveXObject("Msxml2.XMLHTTP");}catch(e){try{return new ActiveXObject("Microsoft.XMLHTTP");}catch(E){return null;}}@end @*/}else{return null;}};
AjaxRequest.isActive =function(){return(AjaxRequest.numActiveAjaxRequests>0);};
AjaxRequest.get =function(args){AjaxRequest.doRequest("GET",args);};
AjaxRequest.post =function(args){AjaxRequest.doRequest("POST",args);};
AjaxRequest.doRequest =function(method,args){if(typeof(args)!="undefined" && args!=null){var myRequest =new AjaxRequest();
myRequest.method =method;
myRequest.handleArguments(args);
myRequest.process();}};
AjaxRequest.submit =function(theform, args){var myRequest =new AjaxRequest();
if(myRequest==null){return false;}var serializedForm =AjaxRequest.serializeForm(theform);
myRequest.method =theform.method.toUpperCase();
myRequest.url =theform.action;
myRequest.handleArguments(args);
myRequest.queryString =serializedForm;
myRequest.process();
return true;};
AjaxRequest.serializeForm =function(theform){var els =theform.elements;
var len =els.length;
var queryString ="";
this.addField =
function(name,value){if(queryString.length>0){queryString +="&";}queryString +=encodeURIComponent(name) + "=" + encodeURIComponent(value);};
for(var i=0;i<len;i++){var el =els[i];
if(!el.disabled){switch(el.type){case 'text': case 'password': case 'hidden': case 'textarea':
this.addField(el.name,el.value);
break;
case 'select-one':
if(el.selectedIndex>=0){this.addField(el.name,el.options[el.selectedIndex].value);}break;
case 'select-multiple':
for(var j=0;j<el.options.length;j++){if(el.options[j].selected){this.addField(el.name,el.options[j].value);}}break;
case 'checkbox': case 'radio':
if(el.checked){this.addField(el.name,el.value);}break;}}}return queryString;};
AjaxRequest.numActiveAjaxRequests =0;
AjaxRequest.numActiveAjaxGroupRequests =new Object();
AjaxRequest.numAjaxRequests =0;

function createMyDiv(dspl,tblname,toolname,divname,scrpt,moleculeType,toolId,trayid,moreText,toolSelected, autoFire, elementId)
{
	var ran_number= (new Date()).getTime();
  	var myElement = document.createElement('div');
  	var txt = "";
  	var toolSelected = getCart().getToolId();
	var pids = getCart().getPids();
	txt += "<div class=\"toolbarHeader\">";
	txt += "<div id=\"header_"+ran_number+"\" style=\"padding: 3px 5px;float:left; font-size: 14px; font-weight: bold;color: #333399;\">"+toolname+"</div>";
	txt += "<div style=\"float: right; margin-right: 3px\"><input type=\"button\" value=\"Back\" class=\"closebtn\" onClick=\"mySequenceManager.loadContent('/toolbox/tools.php?trayid="+trayid+"'); return false;\"><input type=\"button\" value=\"Close\" class=\"closebtn\" onClick=\"overlayclose('subcontent2'); return false;\">";
	
	txt += "</div><div class=\"clearfix\"></div></div>";
	txt += "<div name=\"content\" id=\"content\" style=\"overflow:scroll;height:400px;\">";

  	myElement.innerHTML = txt;

  	//contentFillAppend('toolbox/'+scrpt+'.php?trayid='+trayid+'&rand='+ran_number+'&moleculeType='+moleculeType+'&toolId='+toolId,'subcontent2',txt,'</div>');
  	if (pids=='' && autoFire && !trayid) {
  		myDialog.show('Tools', 'You have to select some sequence before run tools.', 'Select sequences', 'Cancel', function(){mySequenceManager.loadContent('/leftcontent/sequences.php');});
  	} else {
  		mySequenceManager.loadAndSubmit('/toolbox/'+scrpt+'.php?trayid='+trayid+'&rand='+ran_number+'&moleculeType='+moleculeType+'&toolId='+toolId+'&toolname='+toolname+'&toolSelected='+toolSelected+'&pids='+pids, autoFire, elementId);
  	}
	//document.getElementById("subcontent2").innerHTML = txt;
  	//document.getElementById("subcontent2").style.display = "block";
}
function setMyNotesCols() 
{
	var textarea = document.getElementById("myNotes");
	textarea.setAttribute("cols", Math.floor(textarea.clientWidth / 7));
	setMyNotesRows();
}
function setMyNotesRows(myNote) 
{
	var textarea = document.getElementById(myNote);
	var cols = textarea.cols;
	var str = textarea.value;
	str = str.replace(/\r\n?/, "\n");
	var lines = 2;
  	var chars = 0;
	for (i = 0; i < str.length; i++) 
	{
		var c = str.charAt(i);
    	chars++;
    	if (c == "\n" || chars == cols) 
    	{
    		lines ++;
      		chars = 0;
     	}
   	}
	textarea.setAttribute("rows", lines);
	textarea.style.height = lines*12 + "px";
}
/*********************************************** 
* Drop Down/ Overlapping Content - Dynamic Drive (www.dynamicdrive.com) 
* This notice must stay intact for legal use. 
* Visit http://www.dynamicdrive.com/ for full source code 
***********************************************/ 
function overlay2(subobjstr){
	if (subobjstr == 'subcontent2') {
		toggleAllSelects('hide');
	}
	if (document.getElementById){
		var subobj=document.getElementById(subobjstr);
		subobj.style.display = "block";
		return false;
	}
	else
	return true;
}
function overlayclose(subobj){
	if (subobj == 'subcontent2') {
		if (document.getElementById('subcontent2').isContentPaneChanged) {
			naviTreeManager.refreshContentpane();
			document.getElementById('subcontent2').isContentPaneChanged = false;
		} else {
			toggleAllSelects('show');
		}
	}
	document.getElementById(subobj).style.display="none";
}
function blocking(nr)
{
	if (document.layers)
	{
		current = (document.layers[nr].display == 'none') ? 'block' : 'none';
		document.layers[nr].display = current;
	}
	else if (document.all)
	{
		current = (document.all[nr].style.display == 'none') ? 'block' : 'none';
		document.all[nr].style.display = current;
	}
	else if (document.getElementById)
	{
		vista = (document.getElementById(nr).style.display == 'none') ? 'block' : 'none';
		document.getElementById(nr).style.display = vista;
	}
}
function noenter(event) 
{
	if (event && event.which == 13)
		return false;
	else
		return !(window.event && window.event.keyCode == 13); 
}

function CheckAll(bTrue,frm) {
	var el = document.forms[frm];
	for( var i=0; i < el.length; i++ ) {
		if( bTrue ) {
			el.elements[i].checked = 'checked';
		} else {
			el.elements[i].checked = '';
		}
	}
}
function SelectAll(bTrue,frm) {
	//	selects all objects.
	//alert("selectAll");
	var table = dojo.widget.byId("sequenceTable");
	try {
		table.store.forEach(function(element){
			element.isSelected = bTrue;
			if(bTrue) {
				getCart().add(element.src.pid, element.src.accession, 
						element.src.molecule, null, false);
			} else {
				getCart().remove(element.src.pid, false);				
			} 
		});
	} catch(e) {
		alert(e.message);
	}
}
function ImportAll() {
	if(!confirm("Do you really want to import all of your friends' sequences?")) {
		return;
	}
	
	var table = dojo.widget.byId("sequenceTable");
	try {
		table.store.forEach(function(element){
			element.isSelected = true;
			getCart().importAndAdd(element.src.pid, null, 'friend', false);
		});
	} catch(e) {
		alert(e.message);
	}
}
function dhtmlLoadScript(url)
{
   var e = document.createElement("script");
   e.src = url;
   e.type="text/javascript";
   document.getElementsByTagName("head")[0].appendChild(e);
}
function processidt(form, append) {
	var inputs = form.getElementsByTagName('input');
	var seq=document.getElementById("idtseq").innerHTML;
	for (i = 0; i < inputs.length; i++) {
		if (inputs[i].type == 'checkbox') {
			if (inputs[i].checked == 1) {
				if (append == "beginning") {
					seq = inputs[i].name + seq;
				}
				else {
					seq = seq + inputs[i].name;
				}
			}
		}
	}
	document.getElementById("idtseq").innerHTML = seq;
}

function getSelText() {
    var txt = '';
    if (window.getSelection)
    {
        txt = window.getSelection();
    }
    else if (document.getSelection)
    {
        txt = document.getSelection();
    }
    else if (document.selection)
    {
        txt = document.selection.createRange().text;
    }
    else return 'nothing';
	return txt;
}
function toggle(e) {
  if (e.style.display == "none") {
     e.style.display = "";
  } else {
     e.style.display = "none";
  }
}
function toggleAndReplace(e,showText,hideText,showHideDiv) {
  if (e.style.display == "none") {
     e.style.display = "";
	 showHideDiv.innerHTML = hideText;
  } else {
     e.style.display = "none";
	 showHideDiv.innerHTML = showText;
  }
}
function resizeDiv(div, percent, readonly) {
	var divElement = document.getElementById(div);
	if(divElement) {
		var theHeight;
		
		// Window dimensions:
		if (window.innerHeight) {
			theHeight=window.innerHeight;
		}
		
		else if (document.documentElement && document.documentElement.clientHeight) {
			theHeight=document.documentElement.clientHeight;
		}
		else if (document.body) {
			theHeight=document.body.clientHeight;
		}
	
		var h = (theHeight - 65 - 16 - 18 - 38 - 36) * (percent/100);
		
		if (readonly){
			h = h + 54;
		}
		divElement.style.height = h + "px";
	}
}
function validate_required(field,alerttxt,div) {
	with (field) {
		if (value==null||value=="") {
			document.getElementById(div).innerHTML = alerttxt;return false;}
		else {
			return true;
		}
	}
}
function saveTrayTitles(input, trayid, title, log, type) {
	var inputField = document.getElementById(input);
	if (inputField.readOnly == true){
		inputField.readOnly = false;
		inputField.className = 'inputfieldEdit';
		if (type == 'seqtray') {
			function savetrayid() {
				inputField.blur();
				document.onkeyup = null;
			}
		}
		else if (type == 'picture') {
			
		}
		keyListener(0, savetrayid);
	}
	else {
		inputField.readOnly = true;
		inputField.className = 'inputfield';
	}
}
function toggleCollapse(button, divname) {
	var btn = document.getElementById(button);
	blocking(divname);
	
	if (btn.value == 'Collapse') {
		btn.value = 'Expand';
	}
	else {
		btn.value = 'Collapse';
	}
}
/***********************************************
* Cool DHTML tooltip script - Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/
var offsetxpoint=-60; //Customize x offset of tooltip
var offsetypoint=20; //Customize y offset of tooltip
var ie=document.all;
var ns6=document.getElementById && !document.all;
var enabletip=false;
var ie5=document.all&&document.getElementById;
var ns6=document.getElementById&&!document.all;
var tipobj = null;
function ietruebody(){
	return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body;
}
function ddrivetip(thetext, thecolor, thewidth){
	if (ns6||ie){
		if (typeof thewidth!="undefined") tipobj.style.width=thewidth+"px";
		if (typeof thecolor!="undefined" && thecolor!="") tipobj.style.backgroundColor=thecolor;
		tipobj.innerHTML=thetext;
		tipobj.style.zIndex = 10000;
		enabletip=true;
		return false;
	}
}
function positiontip(e){
	if (enabletip){
		var curX=(ns6)?e.pageX : event.clientX+ietruebody().scrollLeft;
		var curY=(ns6)?e.pageY : event.clientY+ietruebody().scrollTop;
		//Find out how close the mouse is to the corner of the window
		var rightedge=ie&&!window.opera? ietruebody().clientWidth-event.clientX-offsetxpoint : window.innerWidth-e.clientX-offsetxpoint-20;
		var bottomedge=ie&&!window.opera? ietruebody().clientHeight-event.clientY-offsetypoint : window.innerHeight-e.clientY-offsetypoint-20;

		var leftedge=(offsetxpoint<0)? offsetxpoint*(-1) : -1000;

		//if the horizontal distance isn't enough to accomodate the width of the context menu
		if (rightedge<tipobj.offsetWidth)
			//move the horizontal position of the menu to the left by it's width
			tipobj.style.left=ie? ietruebody().scrollLeft+event.clientX-tipobj.offsetWidth+"px" : window.pageXOffset+e.clientX-tipobj.offsetWidth+"px";
		else if (curX<leftedge) tipobj.style.left="5px";
		else
		//position the horizontal position of the menu where the mouse is positioned
			tipobj.style.left=curX+offsetxpoint+"px";

		//same concept with the vertical position
		if (bottomedge<tipobj.offsetHeight)
			tipobj.style.top=ie? ietruebody().scrollTop+event.clientY-tipobj.offsetHeight-offsetypoint+"px" : window.pageYOffset+e.clientY-tipobj.offsetHeight-offsetypoint+"px";
		else
			tipobj.style.top=curY+offsetypoint+"px";
		tipobj.style.visibility="visible";
	}
}
function hideddrivetip() {
	if (ns6||ie){
		enabletip=false;
		tipobj.style.visibility="hidden";
		tipobj.style.left="-1000px";
		tipobj.style.backgroundColor='';
		tipobj.style.width='';
	}
}

document.onmousemove=positiontip

function postAJAX(url, query) {
	var status = false;
	dojo.io.bind({
        url: url,
        handler: function(type, data, event) {
            if (type == 'error') {
                //alert('Error!');
            } else {
                //alert(data);
                status = true;
            }
        },
        mimetype: 'text/plain',
        method: 'post',
        sync: true,
        error: function(type, error){ dojo.debug(error.message); },
        timeoutSeconds: 600,
        content: getParameters(query)
	});
	return status;
}
function getParameters(str){
	var ary = new Array;
	var item;
	if(typeof(str) == 'undefined') {
		return ary;
	}
	if(str.indexOf('?', 0) > -1) {
		str = str.split('?')[1];
	}
	str = str.split('&');
	for(var i = 0; str.length > i; i++){
		item = str[i].split("=");
		if(item[0] != '') {
			ary[item[0]] = typeof(item[1]) == 'undefined' ? true : decodeURIComponent(item[1]);
		}
	}
	return ary;
}
function getBlastDatabase(form) {
	var program = form.options[form.selectedIndex].value;
	document.getElementById('database').options.length = 0;	
	if(program.length>0){		
	AjaxRequest.get(
  {
    'url':'toolbox/getBlastDatabases.php?program='+program
    ,'onLoading': function() { document.getElementById("load").style.visibility = "visible"; }
    ,'onComplete': function(req) { document.getElementById("load").style.visibility = "hidden"; createDatabases(req.responseText);}
    //,'onSuccess':function(req){ document.getElementById(l).innerHTML = req.responseText; }
    //,'onError':function(req){ alert('Error!\nStatusText='+req.statusText+'\nContents='+req.responseText);}
  }
);}
}
function createDatabases(response) {
	var obj = document.getElementById('database');
	eval(response);	// Executing the response from Ajax as Javascript code	
}
function contentFill(p,l) {
AjaxRequest.get(
  {
    'url':p
    ,'onLoading': function() { document.getElementById("load").style.visibility = "visible"; }
    ,'onComplete': function() { document.getElementById("load").style.visibility = "hidden"; }
    ,'onSuccess':function(req){ document.getElementById(l).innerHTML = req.responseText; 
								if (l == 'subcontent2') {
									resizeDiv('content', 75, 0);
									return overlay2('subcontent2');
								}
								return true;
							  }
    ,'onError':function(req){ alert('Error!\nStatusText='+req.statusText+'\nContents='+req.responseText);}
  }
);}

function contentFillAppend(p,l,begin,end) {
AjaxRequest.get(
  {
    'url':p
    ,'onLoading': function() { document.getElementById("load").style.visibility = "visible"; }
    ,'onComplete': function() { document.getElementById("load").style.visibility = "hidden"; }
    ,'onSuccess':function(req){ document.getElementById(l).innerHTML = begin+req.responseText+end; }
    ,'onError':function(req){ alert('Error!\nStatusText='+req.statusText+'\nContents='+req.responseText);}
  }
);}
function switchPage(p) {
AjaxRequest.get(
  {
    'url':p
    ,'onLoading': function() { document.getElementById("load").style.visibility = "visible"; }
    ,'onComplete': function() { document.getElementById("load").style.visibility = "hidden"; }
    ,'onSuccess': function(){ //contentFill('rightcontent/pages.php','notebookpages'); 
    							 //contentFill('rightcontent/get_page_title.php','page_title'); 
								 //contentFill('rightcontent/page_load.php','notebook_pages');
							     
								 naviTreeManager.refreshNodeById('notebook.0');
								 naviTreeManager.refreshContentpane();
							   }
    ,'onError': function(req){ alert('Error!\nStatusText='+req.statusText+'\nContents='+req.responseText);}
  }
);}
function submitForm(theform) {
  var status = AjaxRequest.submit(
    theform
    ,{
       'onLoading': function() { document.getElementById("load").style.visibility = "visible"; }
      ,'onComplete': function() { document.getElementById("load").style.visibility = "hidden"; }
      ,'onSuccess':function(){ contentFill('/rightcontent/page_load.php','notebook_pages');}
    }
  );
  return status;
}
function submitToQueue(theform, trayid, batchid, toolid, uid, pageid) {
  	var d;
  	if(parseInt(trayid) <= 0) {
  		// for a new tray.
  		d=myJobQueue.createSeqTray(getCart().getSelectedSequences());
  	} else {
  		d = new dojo.Deferred();
  		d.callback({'trayid' : trayid});
  	}
	d.addCallback(function(data) {
  		var dd=naviTreeManager.refreshNodeById('page.'+data.pageid);
    	dd.addCallback(function(dummy) {
    		var trayid = data.trayid;
    		if (parseInt(trayid) > 0) {
    			theform.acc.value= trayid;
    			theform.trayId.value = trayid;
			 	dojo.io.bind ( {
					url: theform.action,
					load: function (type, data, evt) {
						var ddd=naviTreeManager.refreshNodeById('seqTray.'+trayid);
						ddd.addCallback (function () {
							var resultNode;
							if (data.nodeId && (resultNode = dojo.widget.byId(data.nodeId))) {
								naviTreeManager.invalidateContentpane();
								naviTreeManager.updateContentpane({node: resultNode});
							}
							ddd.callback(true);
						});
						if (data) {
							for (var index=0; index < data.errMessage.length; index++) {
								updateStatusMessage (data.status, data.errMessage[index]);
							}
						}
					},
					error: function(type, error){dojo.debug(error.message);},
					mimetype: "text/json",
					formNode: theform
				});
    		}
    		else {
    			alert('There was an error creating your sequence tray. Please try again.');
    		}
    	});
    	return dd;
    });

	mySequenceManager.close();
	return d;
}
function submitFormToolQueue(theform, trayid) {	
  naviTreeManager.openNotebookPane();
  if(parseInt(trayid) <= 0) {
  	// for a new tray.
  	var d=myJobQueue.createSeqTray(getCart().getSelectedSequences());
  	d.addCallback(function(data) {
  		var dd=naviTreeManager.refreshNodeById('page.'+data.pageid);
    	dd.addCallback(function(dummy) {
    		var trayid = data.trayid;
    		if (parseInt(trayid) > 0) {
    			theform.acc.value= trayid;
    			theform.trayId.value = trayid;
    			myJobQueue.submitToQueue (theform, trayid);
    		}
    		else {
    			alert('There was an error creating your sequence tray. Please try again.');
    		}
    	});
    	return dd;
    });
  } else {
  	myJobQueue.submitToQueue (theform, trayid);
  }
  mySequenceManager.close();
}
/*
function submitFormTool(theform, trayid) {
  if (theform.acc != null && theform.acc.value == 'default') {
    alert('Please select a sequence tray.');
	return false;
  }
  else {
  	mySequenceManager.close();
  }
  var status = AjaxRequest.submit(
    theform
    ,{
    	 'onLoading':  function() { document.getElementById("load").style.visibility = "visible"; }
    	,'onComplete': function() { document.getElementById("load").style.visibility = "hidden"; }
      	,'onSuccess':  function(req){ contentFill('/rightcontent/page_load.php','notebook_pages');
									  naviTreeManager.refreshNodeById('seqTray.'+trayid);
									  var newdiv = document.createElement('div');
									  newdiv.innerHTML = req.responseText;   							
      								}
    }
  );
  return status;
}
* */
function exeJStools(p, jsfunction, rand, tool, enabled, trayid, batchid, reloadPage, tool_id, dataid, run) {
	document.getElementById("load").style.visibility = "visible";
	urchinTracker(p + '&tool=' + tool);
    var status = false;
	dojo.io.bind({
        url: p,
        handler: function(type, data, event) {
            if (type == 'error') {
                //alert('Error!');
            } else {
				if (run) {
					status = jsfunction(document, data, rand, tool, enabled, trayid, batchid, tool_id, dataid); 
				}
            }
            document.getElementById("load").style.visibility = "hidden";
        },
        mimetype: 'text/plain',
        method: 'get',
        sync: true,
        error: function(type, error){ dojo.debug(error.message); },
        timeoutSeconds: 600
    });
	
	return status;
}
function loopSeqTray(p, jsfunction, rand, tool, enabled, trayid, batchid, selectedTray, tool_id, toolMoleculeType) {
	var count = 0;
	var reloadPage = 0;
	var checkSeqType = 0;
	var errorMessage = '';
	if (toolMoleculeType != 'all') {
		checkSeqType = 1;
	}
	var seqs = null;
	
	naviTreeManager.openNotebookPane();

	if(!trayid || trayid=="0") {
		seqs = getCart().getSelectedSequences();
		if(!seqs) {
			return;
		}
		
		trayid = createSeqTray();
		if(!trayid) {
			// failed to create a tray.
			return;
		}
		selectedTray = trayid;
	} else {
		seqs = getSequencesFromTray(trayid);
		if(!seqs) {
			return;
		}
	}

	var pids = [];
	for(var pid in seqs) {
		pids.push(pid);
	}
	for(var i = 0; i < pids.length; i++) {
		var pid = pids[i];
		var seq = seqs[pid];
		
		var run = 1;
		var moleculetype = seq.molecule;
		if (i == pids.length - 1) reloadPage = 1;
		var dataid = seq.id; // inputs[i].getAttribute("dataid");
		var url = '/getseq.php?text='+seq.id;	
		var status = exeJStools(url, jsfunction, rand, tool, enabled, trayid, batchid, reloadPage, tool_id, dataid, run);
	}
	if (errorMessage) alert(errorMessage);

	var pageid = getSessionVariable("last_page");
	var d = naviTreeManager.refreshNodeById('page.'+pageid);
	d.addCallback(function() {
		naviTreeManager.refreshNodeById('seqTray.'+trayid);
	});
	
	mySequenceManager.close();
}
function submitFormCustom(theform, fill, div) {
  var status = AjaxRequest.submit(
    theform
    ,{
    	'onLoading':  function() { document.getElementById("load").style.visibility = "visible"; }
       ,'onComplete': function() { document.getElementById("load").style.visibility = "hidden"; }
       ,'onSuccess':  function(req){ if (div == 'notebook_pages') contentFill(fill, div);
	   								 if (fill && div) mySequenceManager.loadContent(fill);
      							  	 else if(!fill && div) document.getElementById(div).innterHTML = req.responseText;
      						      	 //var status = req.responseText.search(/errormsg/i);
									 var newdiv = document.createElement('div');
									 newdiv.innerHTML = req.responseText;
       						      	 var olddiv = document.getElementById("feedbackSystem");
									 olddiv.appendChild(newdiv);
      							   }
       ,'onError':function(req){ alert('Error!\nStatusText='+req.statusText+'\nContents='+req.responseText);}
    }
  );
  return status;
}
function submitFormRefresh(theform, fill, div, refreshContentPane, refreshNaviPane, toolComments) {
  var status = AjaxRequest.submit(
    theform
    ,{
    	 'onLoading':  function()   { document.getElementById("load").style.visibility = "visible"; }
    	,'onComplete': function()   { document.getElementById("load").style.visibility = "hidden"; }
      	,'onSuccess':  function(req){ 
										if (fill && div){
											contentFill(fill, div);
										}
										if (fill && fill == 'profile') {
											mySequenceManager.loadContent('/prefs.php?message='+req.responseText);
											progressBarUpdate();
										}
										if (refreshContentPane) {
											naviTreeManager.refreshContentpane();
										}       
      									if (refreshNaviPane) {
											naviTreeManager.refreshNodeById(refreshNaviPane);
										}
										if (toolComments) {
											mySequenceManager.loadContent("/leftcontent/viewComments.php?toolid=" + toolComments);
										}
      								}

       	,'onError':function(req){ alert('Error!\nStatusText='+req.statusText+'\nContents='+req.responseText);}
    }
  );
  return status;
}
function getRefresh(p, refreshContentPane, refreshNaviPane, fill, div) {
AjaxRequest.get(
  {
    'url':p
    ,'onLoading': function()  { document.getElementById("load").style.visibility = "visible"; }
    ,'onComplete': function() { document.getElementById("load").style.visibility = "hidden"; }
    ,'onSuccess':function(req){ 
								if (fill && div){
									contentFill(fill, div);
								}
								updateStatusMessage(null, req.responseText);
								if (refreshContentPane) {
									naviTreeManager.refreshContentpane();
								}       
      							if (refreshNaviPane) {
									naviTreeManager.refreshNodeById(refreshNaviPane);
								}
							  }
    ,'onError':function(req){ alert('Error!\nStatusText='+req.statusText+'\nContents='+req.responseText);}
  }
);}
function submitForm2(theform,file,divname) {
  var status = AjaxRequest.submit(
    theform
    ,{
    	'onLoading': function() { document.getElementById("load").style.visibility = "visible"; }
    	,'onComplete': function() { document.getElementById("load").style.visibility = "hidden"; }
      ,'onSuccess':function(req){ contentFill(file,divname); }
    }
  );
  return status;
}
function submitMyForm(theform,mydiv) {
  var status = AjaxRequest.submit(
    theform
    ,{
    	'onLoading': function() { document.getElementById("load").style.visibility = "visible"; }
    	,'onComplete': function() { document.getElementById("load").style.visibility = "hidden"; }
      ,'onSuccess':function(req){ contentFill('rightcontent/page_load.php','notebook_pages'); 
	  								if (mydiv == 'alert') {
										mySequenceManager.close();
										alert(req.responseText);
									}
      							}
    }
  );
  return status;
}
function submitLog(theform) {
  var status = AjaxRequest.submit(
    theform
    ,{
    	'onLoading': function() { document.getElementById("load").style.visibility = "visible"; }
    	,'onComplete': function() { document.getElementById("load").style.visibility = "hidden"; }
      ,'onSuccess':function(req){
      							  document.getElementById("logdiv").innerHTML = req.responseText;
      							}
    }
  );
  return status;
}
function submitSubcontent(theform) {
  var status = AjaxRequest.submit(
    theform
    ,{
       'onLoading': function() { document.getElementById("load").style.visibility = "visible"; }
      ,'onComplete': function() { document.getElementById("load").style.visibility = "hidden"; }
      ,'onSuccess':function(req){ alert(req.responseText); }
      ,'onError': function(req){ alert('Error!\nStatusText='+req.statusText+'\nContents='+req.responseText);}
    }
  );
  return status;
}
function saveMyNote(t,mydiv) {
	var status = AjaxRequest.submit(
    t
    ,{
      'onSuccess':function(req){ document.getElementById(mydiv).innerHTML = req.responseText; hideddrivetip();}
    }
  );
  return status;
}
function SearchBoxKeyPress(e, st, p)
{
	var keynum;
	var keychar;
	var numcheck;
	
	if(window.event) // IE
	{
		keynum = e.keyCode;
	} 
	else if(e.which) // Netscape/Firefox/Opera
	{
		keynum = e.which;
	}

	if( keynum == 13 ) {
		if( p == "s" )
			mySequenceManager.loadContent('/leftcontent/sequences.php?st='+st);
		if( p == "t" )
			mySequenceManager.loadContent('/toolbox/tools.php?st='+st);
		if( p == "n" )
			mySequenceManager.loadContent('/leftcontent/notebook.php?st='+st);
		document.onkeyup = null;
	}
}
function onloadInit() {
    // javascript document init code
 	var ie=document.all;
	var ns6=document.getElementById && !document.all
	var enabletip=false;
	var ie5=document.all&&document.getElementById;
	var ns6=document.getElementById&&!document.all;
	if (ie||ns6)
		tipobj=document.all? document.all["dhtmltooltip"] : document.getElementById? document.getElementById("dhtmltooltip") : "";
}
function closeLogger() {
	overlayclose('subcontent2');
	document.getElementById('logTab').style.backgroundColor='#d4ddf4';
	document.getElementById('logTab').style.color='#333399';
}
function seqGrabber(e){
	// capture the mouse position
	/*
	var posx = 0;
	var posy = 0;
	if (!e) var e = window.event;
	if (e.pageX || e.pageY)
	{
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY)
	{
		posx = e.clientX;
		posy = e.clientY;
	}
	*/
	var h = getSelText();
	var seqtab = document.getElementById('seqGrabberTab');
	//var seqdiv = document.getElementById('seqGrabberDiv');
	if(h!='') {
		//seqdiv.style.top = (posy-65)+'px';
		//seqdiv.style.left = posx+'px';
		///seqdiv.style.zIndex = 999;
		//toggle(document.getElementById('seqGrabberTab'));
		document.getElementById('seqGrabberTab').style.display = 'inline';
		seqtab.style.color='white';
		seqtab.style.backgroundColor='#f78932';
	}
	else {
		seqtab.style.display='none';
	}
}
function clearSelection() {
	 if (window.getSelection)
    {
       var h = window.getSelection();
	   h.removeAllRanges();
             }
    else if (document.getSelection)
    {
     var h = document.getSelection();
	   h.removeAllRanges();
            }
    else if (document.selection)
    {
		document.selection.empty();
    }
}
function startSeqGrabber() {
	var seq=getSelText();
	mySequenceManager.loadContent('/leftcontent/grabsequence.php?seq='+seq); 
	clearSelection();
	return true;
}
function isPublic () {
	if(document.blogForm.public_page[1].checked) {
		return true;
	}
	else return false;
}
function keyListener(button, runFunction) {
	//first, tell the browsers to react to the event
	if( document.captureEvents && Event.KEYUP ) {
  		//remove this part if you do not need Netscape 4 to work
  		document.captureEvents( Event.KEYUP );
	}
	/* this next line tells the browser to detect a keyup
	event over the whole document and when it detects it,
	it should run the event handler function 'alertkey' */
	document.onkeyup = alertkey;

	//now create the event handler function to process the event
	function alertkey(e) {
  		if( !e ) {
    		//if the browser did not pass the event information to the
    		//function, we will have to obtain it from the event register
    		if( window.event ) {
      			//Internet Explorer
      			e = window.event;
    		} else {
      		//total failure, we have no way of referencing the event
      			return;
    		}
  		}
  		if( typeof( e.keyCode ) == 'number'  ) {
    		//DOM
    		e = e.keyCode;
			if (e == '13') {
				if (button) button.click();
				if (runFunction) runFunction();
			}
		}
	}
}
function validateAnalyze() {
}
function seqImport(myform) {
	if(myform.trayid && myform.trayid.value.length!=0) {
		mySequenceManager.close();
		submitFormRefresh(document.forms['t'], '/rightcontent/refreshSeqTray.php?tray_id='+myform.trayid.value, 'seqTray'+myform.trayid.value, 0, 0); 
	}
	else 
	{
		mySequenceManager.submitSequenceEditForm(document.forms['t'],document.forms['t'].action ,'/leftcontent/afterSequenceImport.php');; 
		//mySequenceManager.close();
	}
}

function anyChecked(cart) {
	return cart.hasSeqs();
}
function addSequence(cart) {
	var myform = cart.emulateMySequenceForm();
	var acc = cart.getAcc();
	if (acc == 'default') {
		return false;
		
	} else if (!cart.hasSeqs()) {
		alert("Please select at least one sequence.");
		return false;
		
	} else if (acc == 'delete') {
		var answer = confirm('Are you sure you want to delete the selected sequence(s)?');
		if(answer) {
			myform.delSeq.click();
		}
	} else if (acc == 'addTag') {
		addtagdlg(myform.name, function (objids, tags) {
//			document.getElementById('subcontent2').isContentPaneChanged = true;
			var url = '/leftcontent/rpc_tag_operations.php?action=add' + 
				'&objtype=1&objids=' + objids + '&tags=' + tags;
			var suburl = '/leftcontent/sequences.php';
			var query_base = myform.getAttribute('query_base');
			if (query_base != '') {
				suburl += '?' + query_base;
			}
//			getRefresh(url, 0, 0, suburl,'subcontent2');
			mySequenceManager.submitSequenceEditForm(null, url, suburl);
		});
		
	} else if (acc == 'removeTag') {
		removetagdlg(myform.name, function (objids, tags) {
//			document.getElementById('subcontent2').isContentPaneChanged = true;
			var url = '/leftcontent/rpc_tag_operations.php?action=remove' + 
				'&objtype=1&objids=' + objids + '&tags=' + tags;
			var suburl = '/leftcontent/sequences.php';
			var query_base = myform.getAttribute('query_base');
			if (query_base != '') {
				suburl += '?' + query_base;
			}
//			getRefresh(url, 0, 0, suburl,'subcontent2');
			mySequenceManager.submitSequenceEditForm(null, url, suburl);
		});
		
	} else if (acc == 'new') {
		mySequenceManager.close();
		submitFormRefresh(myform, 0, 0, 1, 'page.'+myform.pageid.value);
		
	} else if (acc == 'exportFasta') {
		mySequenceManager.close();
		
		myform.setAttribute("action", "/leftcontent/sequence_add.php");
		myform.setAttribute("method", "post");
		document.body.appendChild(myform);
		document.emulatedMySequenceForm.submit();
		document.body.removeChild(myform);
		
	} else if ((acc == 'trackArticles') || (acc == 'untrackArticles')) {
		mySequenceManager.close();
		var d = mySequenceManager.submitSequenceEditForm(myform, "/leftcontent/sequence_add.php", null, false);
		d.addCallback (function (data) {
			submitFormRefresh(myform, null, null, 0, 0);
		});
		
	} else {
		mySequenceManager.close();
		dojo.html.scrollIntoView(document.getElementById('seqTray'+myform.acc.value));
		submitFormRefresh(myform, '/rightcontent/refreshSeqTray.php?tray_id='+myform.acc.value, 'seqTray'+myform.acc.value, 0, 0);
		
	}
	return true;
}
function show(nr, type) {
	if (document.layers)
	{		
		if (document.layers[nr].display == 'none') document.layers[nr].display = 'block';
	}
	else if (document.all)
	{
		if (document.all[nr].style.display == 'none') document.all[nr].style.display = 'block';
	}
	else if (document.getElementById)
	{
		if (document.getElementById(nr).style.display == 'none') document.getElementById(nr).style.display = 'block';
	}
}
function hide(nr, type) {
	if (document.layers)
	{		
		if (document.layers[nr].display != 'none') document.layers[nr].display = 'none';
	}
	else if (document.all)
	{
		if (document.all[nr].style.display != 'none') document.all[nr].style.display = 'none';
	}
	else if (document.getElementById)
	{
		if (document.getElementById(nr).style.display != 'none') document.getElementById(nr).style.display = 'none';
	}
}
function runTraySeqSelect(val, trayid, formname, selectInput) {
	if (val != "null") {
		selectInput.selectedIndex = 0;	
	}
	if (val == 'ncbi' || val == 'importFile' || val== 'clipboard') {
		mySequenceManager.loadContent('/leftcontent/sequence_options.php?trayid='+trayid);
	}
	else if (val == 'delete') {
		var inputs = document.forms[formname].getElementsByTagName('input');
		var count = 0;
		for (i = 0; i < inputs.length; i++) {
			if (inputs[i].type == 'checkbox') {
				if (inputs[i].checked == 1) {
					count++;
					
					/*
					if (answer == 'not yet asked') {
						answer = confirm("Are you sure you want to delete the selected sequences?");
					}
					if (answer) getRefresh('/rightcontent/tray_delete.php?sequenceid='+inputs[i].value, 0, 0, '/rightcontent/refreshSeqTray.php?tray_id='+trayid, 'seqTray'+trayid)
					*/					
				}
			}
		}
		if (count == 0) {
			alert("Please select the checkboxes for the sequences you wish to delete.");
		}
		else {
			var answer = confirm("Are you sure you want to delete the selected sequences?");
			if (answer) //getRefresh('/rightcontent/tray_delete.php?sequenceid='+inputs[i].value, 0, 0, '/rightcontent/refreshSeqTray.php?tray_id='+trayid, 'seqTray'+trayid);
						submitFormRefresh(document.getElementById(formname), '/rightcontent/refreshSeqTray.php?tray_id='+trayid, 'seqTray'+trayid, 0, 0);
		}
	}
	else if (val == 'addTag') {
		addtagdlg(formname, function(objids, tags) {
			var url = '/leftcontent/rpc_tag_operations.php?action=add' + 
				'&objtype=1&objids=' + objids + '&tags=' + tags;
			getRefresh(url, 0, 0, '/rightcontent/refreshSeqTray.php?tray_id='+trayid, 'seqTray'+trayid);
		});
	}
	else if (val == 'removeTag') {
		removetagdlg(formname, function (objids, tags) {
			var url = '/leftcontent/rpc_tag_operations.php?action=remove' + 
				'&objtype=1&objids=' + objids + '&tags=' + tags;
				getRefresh(url, 0, 0, '/rightcontent/refreshSeqTray.php?tray_id='+trayid, 'seqTray'+trayid);
		});
	}
}
function runTraySelect(val, trayid, divname, selectInput) {
	if (val == 'edittitle') {
		saveTrayTitles(divname+'_inputtext', trayid, document.getElementById(divname+'_inputtext').value, 'mode'+trayid, 'seqtray');
		document.getElementById(divname+'_inputtext').focus();
	}
	else if (val == 'collapse') hide(divname, 'sequence tray');
	else if (val == 'restore') show(divname, 'sequence tray');
	else if (val == 'delete') {
		var answer = confirm('Are you sure you want to delete the sequence tray?'); 
		if (answer) document.getElementById('deletebtn'+trayid).click();
	}
	selectInput.selectedIndex = 0;
}
function runNoteSelect(val, noteid, pageid, selectInput) {
	if (val == 'collapse') hide('pages_'+noteid, 'note');
	else if (val == 'restore') show('pages_'+noteid, 'note');
	else if (val == 'delete') {
		var answer = confirm('Are you sure you want to delete notes?'); 
		if (answer) getRefresh('rightcontent/note_delete.php?note_id='+noteid, 1, 'page.'+pageid);
	}
	selectInput.selectedIndex = 0;
}
function runResultSelect(val, resultid, pageid, selectInput) {
	if (val == 'collapse') hide('res_'+resultid, 'result');
	else if (val == 'restore') show('res_'+resultid, 'result');
	else if (val == 'delete') {
		var answer = confirm('Are you sure you want to delete results?'); 
		if (answer) getRefresh('/rightcontent/results_delete.php?id='+resultid, 1, 'page.'+pageid);
	}
	selectInput.selectedIndex = 0;
}
function runTitleSelect(val, selectInput) {
	if (val == 'edittitle') {
		function titleblur() {
			document.getElementById('Title').blur();
			document.onkeyup = null;
		}
		keyListener(0, titleblur);
		var btn = document.getElementById('editTitleBtn');
		var inputField = document.getElementById('Title');
		if (inputField.readOnly == true){
			inputField.readOnly = false;
			inputField.className = 'inputfieldEdit';
			inputField.focus();
		}
	}
	if (selectInput) selectInput.selectedIndex = 0;
}
function runImageSelect (val, imageid, pageid, selectInput) {
	if (val == 'edittitle') {
		function imagetitleblur() {
			document.getElementById(imageid+'_inputtext').blur();
			document.onkeyup = null;
		}
		keyListener(0, imagetitleblur);
		var btn = document.getElementById('editTitleBtn');
		var inputField = document.getElementById(imageid+'_inputtext');
		if (inputField.readOnly == true){
			inputField.readOnly = false;
			inputField.className = 'inputfieldEdit';
			inputField.focus();
		}
	}
	else if (val == 'collapse') hide('image_'+imageid, 'result');
	else if (val == 'restore') show('image_'+imageid, 'result');
	else if (val == 'delete') {
		var answer = confirm('Are you sure you want to delete image?'); 
		if (answer) getRefresh('leftcontent/image_delete.php?id='+imageid, 1, 'page.'+pageid);
	}
	selectInput.selectedIndex = 0;
}
function runPagesSelect(val, selectInput, pageid) {
	if (val == 'tray') naviTreeManager.triggerTreeAction('page.'+pageid, 'naviContextMenuNewSeqTray');
	else if (val == 'note') naviTreeManager.triggerTreeAction('page.'+pageid, 'naviContextMenuNewNote');
	else if (val == 'image') naviTreeManager.triggerTreeAction('page.'+pageid, 'naviContextMenuNewImage');
	selectInput.selectedIndex = 0;
}
function runPublishSelect(val, selectInput, pageid, pagelink) {
	if (val == 'email') {
		mySequenceManager.loadContent('/leftcontent/emailPage.php');
	}
	else if (val == 'link') {
		mySequenceManager.loadContent('/action.php?action=emailLink&pageLink=' + pagelink);
	}
	else if (val == 'blog') {
		var title = document.getElementById('Title').value;
		window.open('/userblogs/admin.php?op=newPost&sendTrackbacks=1&postText='
				+encodeURIComponent('<p><a%20href="'+pagelink+'">'+pagelink+'</a></p>'),
			'ltbm'
		);
		//parent.location='/blog/wp-admin/post-new.php?titleSM='+titleSM+'&bodySM='+pagelink;
	}
	selectInput.selectedIndex = 0;
}
function saveTitle() {
	var t = document.getElementById('ttl');
	var status = AjaxRequest.submit(
    t
    ,{
      'onSuccess':function(req){ 
			t.Title.className = 'inputfield';
			t.Title.readOnly = true
			t.Title.blur();
	  		//document.getElementById("title_saved").innerHTML = req.responseText; 	
			naviTreeManager.refreshNodeById('notebook.0');				
	  }
    }
  );
  return status;
}
function getSummarizedSequenceNames(nameArray, cutofflen) {
	var  seqNames = '';
	var  i;
	for (i = 0; i < nameArray.length; i++) {
		if (i != 0) {
			seqNames += ', ';
			if (i % 5 == 0) {
				seqNames += '<br>';
			}
		}
		seqNames += nameArray[i];
		if (seqNames.length > cutofflen) {
			i++;
			break;
		}
	}
	if (seqNames.length > cutofflen && i < nameArray.length) {
		seqNames += ', ';
		if (i++ % 5 == 0) {
			seqNames += '<br>';
		}
		seqNames += "...";
	}
	if (nameArray.length > 5) {
		if (i++ % 5 == 0) {
			seqNames += '<br>';
		}
		seqNames += " ( " + nameArray.length + " sequences total.)";
	}
	
	return seqNames;
}
function getSelectedSequences() {
	var sequences = [ [], [] ];
	
	var seqs = getCart().getSelectedSequences();
	for(var seqId in seqs) {
		sequences[0].push(seqId);
		sequences[1].push(seqs[seqId].accession);
	}
	return sequences;
}
function addtagdlg(formname, addtagdlg_callback) {
	var dlg = dojo.widget.byId('addtagdlg');
	dlg.sn_sequences = getSelectedSequences();
	if (dlg.sn_sequences[0].length == 0) {
		alert("Please select the checkboxes for the sequences you wish to add tags.");
		return;
	}
	document.getElementById('addtagdlg_seqs').innerHTML = 
		getSummarizedSequenceNames(dlg.sn_sequences[1], 200);
	var tagComboBox = dojo.widget.byId('addtagdlg_tag');
	tagComboBox.setValue('');
	dlg.onOK = function() {
		var tagComboBox = dojo.widget.byId('addtagdlg_tag');
		var objids = encodeURIComponent(this.sn_sequences[0]);
		var tags = tagComboBox.getValue();
		if (tags == '') {
			this.hide();
			return;
		}
		tags = encodeURIComponent(tags);
		addtagdlg_callback(objids, tags);
		this.hide();
	}
	dlg.show();
	setTimeout(function() {
		dojo.widget.byId('addtagdlg_tag')._tryFocus();}, 100);
}
function removetagdlg(formname, removetagdlg_callback) {
	var dlg = dojo.widget.byId('removetagdlg');
	dlg.sn_sequences = getSelectedSequences();
	if (dlg.sn_sequences[0].length == 0) {
		alert("Please select the checkboxes for the sequences you wish to remove tags from.");
		return;
	}
	document.getElementById('removetagdlg_seqs').innerHTML = 
		getSummarizedSequenceNames(dlg.sn_sequences[1], 200);
	document.getElementById('removetagdlg_tags').innerHTML = 'Loading Tags...';
	var objids = encodeURIComponent(dlg.sn_sequences[0]);
	var url = '/leftcontent/rpc_tag_operations.php?action=rendertaglist' + 
		'&objtype=1&objids=' + objids;
	contentFill(url, 'removetagdlg_tags');
	dlg.onOK = function() {
		var objids = encodeURIComponent(this.sn_sequences[0]);
		var tags = removetagdlg_getSelectedTags().join(',');
		if (tags == '') {
			this.hide();
			return;
		}
		tags = encodeURIComponent(tags);
		removetagdlg_callback(objids, tags);
		this.hide();
	}
	dlg.show();		
}
function removetagdlg_getSelectedTags() {
	var tags = [];
	var tagsRootElem = document.getElementById('removetagdlg_tags');
	var inputs = tagsRootElem.getElementsByTagName('input');
	for (i = 0; i < inputs.length; i++) {
		if (inputs[i].type == 'checkbox' && inputs[i].checked) {
			tags[tags.length] = inputs[i].getAttribute("value");
		}
	}
	return tags;
}
function toggleAllSelects(toggle) {
	var ie=document.all;
	if (ie && document.getElementById('contentpane')) {
		var status = '';
		if (toggle == 'hide') {
			status = 'none';
		}
		else status = '';
		var contentPaneNode = document.getElementById('contentpane');
		var selects = contentPaneNode.getElementsByTagName("select");
		for (var i = 0; i < selects.length; i++) { 
			selects[i].style.display = status;
		}
	}
}
function extractSeqsSubmitter(myform, pageid) {
	if (myform.acc.value == 'new') {
		submitFormRefresh(myform, 0, 0, 1, 'page.'+pageid);
	}
	else {
		dojo.html.scrollIntoView(document.getElementById('seqTray'+myform.acc.value));
		submitFormRefresh(myform, '/rightcontent/refreshSeqTray.php?tray_id='+myform.acc.value, 'seqTray'+myform.acc.value, 0, 0);
		myform.reset();
	}
}
function openNewWindow(htmlCode) {
	var newWindow = window.open("SmartNote","SmartNote","width=800,height=600,scrollbars=1,resizable=1");
	var text = '<input type="button" value="Send to Printer" onClick="window.print()" /><br /><br />';
	var html = "<html><head></head><body>";
	text += htmlCode;
	html += text + "</body></html>";

	//variable name of window must be included for all three of the following methods so that
	//javascript knows not to write the string to this window, but instead to the new window

	newWindow.document.open();
	newWindow.document.write(html);
	newWindow.document.close();
}
var annotationCount=1;
function addInput(div) {
	//var newitem;
	var newitem = document.createElement('div');
	newitem.innerHTML = "Name: <input name='annotationName["+annotationCount+"]' id='annotationName["+annotationCount+"]' type='text'> Type: <input name='annotationType["+annotationCount+"]' id='annotationType["+annotationCount+"]' type='text'> Range from <input name='from["+annotationCount+"]' id='from["+annotationCount+"]' type='text' size='5'> to <input name='to["+annotationCount+"]' id='to["+annotationCount+"]' type='text' size='5'> Orientation: <select name='orientation["+annotationCount+"]'><option>none</option><option>plus</option><option>minus</option></select><br>";

	var dynamic_item_div = document.getElementById(div);
	//dynamic_item_div.innerHTML += newitem;
	dynamic_item_div.appendChild(newitem);
	annotationCount++;
}
function loadjscssfile(filename, filetype){
 if (filetype=="js"){ //if filename is a external JavaScript file
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", filename)
 }
 else if (filetype=="css"){ //if filename is an external CSS file
  var fileref=document.createElement("link")
  fileref.setAttribute("rel", "stylesheet")
  fileref.setAttribute("type", "text/css")
  fileref.setAttribute("href", filename)
 }
 if (typeof fileref!="undefined")
  document.getElementsByTagName("head")[0].appendChild(fileref)
}
function createSeqTray() {
	var pids = [];
	for(pid in getCart().getSelectedSequences()) {
		pids.push(pid);
	}
	
	var result = null;
	dojo.io.bind({
		url: "/ajax/createSeqTray.php",
        handler: function(type, data, event) {
            if (type == 'error') {
                //alert('Error!');
            } else {
                //alert(data.comment);
                result = data;
            }
        },
        mimetype: 'text/json',
        method: 'post',
        sync: true,
        error: function(type, error){ dojo.debug(error.message); },
        timeoutSeconds: 60,
        content: { 'pids': pids.join(",") }
	});
	
	if(result && result.trayid) {
		//alert("trayid = " + result.trayid);
	//	var pageid = getSessionVariable("last_page");
	//	naviTreeManager.refreshNodeById('page.'+pageid);
		//alert("result.trayid " + result.trayid);
		//dojo.widget.byId('contentpane').refresh();
		return result.trayid;
	} else {
		alert(result.error);
		return false;
	}
}
var getSessionVariable = function(key) {
	var result = null;
	dojo.io.bind ( {
		url: "/ajax/getSessionVariable.php",
		handler: function (type, data, evt) {
			if(type != "error") {
				result = data;
			}
		},
		mimetype: "text/plain",
        method: 'get',
        sync: true,
        error: function(type, error){ dojo.debug(error.message); },
        timeoutSeconds: 60,
        content: { 'key': key }
	});
	return result;
}
function createSeqLink(toolid, onClickOnly) {
	var result = '';
	dojo.io.bind({
        url: '/action.php?action=createToolLink&toolid=' + toolid + '&onClickOnly=' + onClickOnly,
        handler: function(type, data, event) {
            if (type == 'error') {
                //alert('Error!');
            } else {
                //alert(data);
                result = data;
                dojo.byId("analyzeButtonOnCart").onclick = function() {eval(result);};
            }
        },
        mimetype: 'text/plain',
        method: 'post',
        sync: true,
        error: function(type, error){ dojo.debug(error.message); },
        timeoutSeconds: 60
        //content: getParameters(query)
	});
	return status;
}
function getSequencesFromTray(trayid) {
	var result = null;
	dojo.io.bind ( {
		url: "/ajax/getSequencesFromTray.php",
		handler: function (type, data, evt) {
			if(type != "error") {
				if(data) {
					result = data;
				}
			}
		},
		mimetype: "text/json",
        method: 'get',
        sync: true,
        error: function(type, error){ dojo.debug(error.message); },
        timeoutSeconds: 60,
        content: { 'trayid': trayid }
	});
	return result;
}
// setAttribute name doesn't work in IE.
function createElementWithName(type, name) {
  var element;
  try {
    element = document.createElement('<'+type+' name="'+name+'" />');
  } catch (e) { }
  if (!element || !element.name) { // Not in IE, then
    element = document.createElement(type)
    element.name = name;
  }
  return element;
}
function writeDocument(s){document.write(s);}
function getDimerResults(sequence) {
	document.getElementById("load").style.visibility = "visible";
	
    var status = false;
	dojo.io.bind({
        url: "/action.php?action=getDimerResults&seq=" + sequence,
        handler: function(type, data, event) {
            if (type == 'error') {
                //alert('Error!');
            } else {
				openNewWindow(data);
            }
            document.getElementById("load").style.visibility = "hidden";
        },
        mimetype: 'text/plain',
        method: 'get',
        sync: true,
        error: function(type, error){ dojo.debug(error.message); },
        timeoutSeconds: 600
    });
	
	return status;
}
function openStore(formId) {
	var form = document.getElementById(formId);
	form.target = 'MiraiBio Store';
	form.action = 'http://store.miraibio.com/index.php?main_page=product_info&cPath=65&products_id=180&number_of_uploads=0&action=add_miraibio_product';
	form.submit();
	return false;
}
function primerBlast_toggle(_this, id) {
	var element = document.getElementById(id);
	if(!element) { return; }
	if(element.style.display && element.style.display.match(/none/i)) {
		element.style.display = 'block';
		_this.className = _this.className.replace('hiding', 'showing');
	} else {
		element.style.display = 'none';
		_this.className = _this.className.replace('showing', 'hiding');
	}
}
// Toggle article tracking. (On after sequence import dialog.)
function setArticleTracking(_this, pid, indicatorId) {
	var track = _this.checked ? 'y' : 'n';
	_this.disabled = true;
	dojo.io.bind({
		url: '/ajax/setArticleTracking.php',
		handler: function(type, data, event) {
			var isSuccess = false;
			var message = 'Error occured while saving info.';
			if(type != 'error') {
				//alert(data.isSuccess);
				isSuccess = data.isSuccess;
				message = data.message;
			}
			indicateUpdateOnAfterSeqImport(_this, null, indicatorId, isSuccess, message);
		},
		mimetype: 'text/json',
		method: 'get',
		sync: false,
		error: function(type, error) { 
			dojo.debug(error.message); 
			indicateUpdateOnAfterSeqImport(_this, null, indicatorId, false, 'Error occured while saving info.');
		},
		content: {'pid': pid, 'track': track},
		timeoutSeconds: 600
	});
}
// Toggle seq type. (On after sequence import dialog.)
function setSeqType(_this, pid, _type, otherSwitcherIds, indicatorId) {
	//alert(_this.toString() + " " + pid + _type)
	if(!_this.checked) { return; }
	_this.disabled = true;
	for(var i in otherSwitcherIds) {
		var switcherId = otherSwitcherIds[i];
		if(document.getElementById(switcherId)) {
			document.getElementById(switcherId).disabled = true;
		}
	}
	var type = _type=='nucleotide' ? 'n' : 'p';
	dojo.io.bind({
		url: '/ajax/setSeqType.php',
		handler: function(type, data, event) {
			var isSuccess = false;
			var message = 'Error occured while saving info.';
			if(type != 'error') {
				isSuccess = data.isSuccess;
				message = data.message;
			}
			indicateUpdateOnAfterSeqImport(_this, otherSwitcherIds, indicatorId, isSuccess, message);
		},
		mimetype: 'text/json',
		method: 'get',
		sync: false,
		error: function(type, error) { 
			dojo.debug(error.message); 
			indicateUpdateOnAfterSeqImport(_this, otherSwitcherIds, indicatorId, false, 'Error occured while saving info.');
		},
		content: {'pid': pid, 'type': type},
		timeoutSeconds: 600
	});
}
function indicateUpdateOnAfterSeqImport(switcher, otherSwitcherIds, indicatorId, isSuccess, message) {
	//_this.disabled = false;
	var indicator = document.getElementById(indicatorId);
	if(!switcher || !indicator) { return; }
	
	var color = "green";
	if(!isSuccess) {
		color = "red";
		//if error occured, toggle back the switch state.
		switcher.checked = !switcher.checked;
	}
	indicator.innerHTML = "<span style='color:"+color+";'>"+message+"</span>";
	
	indicator.style.display = 'inline';
	dojo.lfx.chain(
		dojo.lfx.fadeShow(indicatorId, 300, dojo.lfx.easeOut),
		dojo.lfx.fadeHide(indicatorId, 3000, dojo.lfx.easeIn, function(){
			switcher.disabled = false;
			for(var i in otherSwitcherIds) {
				var switcherId = otherSwitcherIds[i];
				if(document.getElementById(switcherId)) {
					document.getElementById(switcherId).disabled = false;
				}
			}
		})
	).play();
}

