function orderByDbName()
{
	setCookie('orderBy', 'dbname');
	document.queryForm.submit();
}

function orderByRelevance()
{
	setCookie('orderBy', 'relevance');
	document.queryForm.submit();
}

function nrOfHitsToShow(nr)
{
	setCookie('hitsToShow', nr);
	document.queryForm.submit();
}

function doStopPropagation(event) {
	event.cancelBubble = true;		// will this continue to work???
	if (event.stopPropagation)
		event.stopPropagation(true);
}

// [Cookie] Sets value in a cookie
function setCookie(cookieName, cookieValue, cookieExpires, cookiePath)
{
	if (cookieExpires)
	{
		var date = new Date();
		date.setTime(date.getTime()+(cookieExpires * 24 * 60 * 60 * 1000));
		cookieExpires = "; expires="+date.toGMTString();
	}

	document.cookie =
		escape(cookieName) + '=' + escape(cookieValue) +
		((cookieExpires) ? cookieExpires : "") +
		((cookiePath) ? "; path=" + cookiePath : "");
};

function getCookie(cookieName)
{
	var name = cookieName + "=";
	var ca = document.cookie.split(';');
	
	for (var i = 0; i < ca.length; ++i)
	{
	    var c = ca[i];
	    while (c.charAt(0) == ' ')
	    	c = c.substring(1, c.length);
	    if (c.indexOf(name) == 0)
	    	return c.substring(name.length, c.length);
	}

	return null;
}

function showBox(id, text)
{
	var p = document.getElementById(id);
	var t = document.getElementById(id + '_text');
	
	if (t.style.display == 'none') {
		t.style.display = '';
		p.innerHTML = 'Hide ' + text;
	}
	else {
		t.style.display = 'none';
		p.innerHTML = 'Show ' + text;
	}
}

function selectTab(select, unselect) {
	var sTab = document.getElementById('opt_' + select + '_tab');
	var uTab = document.getElementById('opt_' + unselect + '_tab');

	var sBox = document.getElementById('opt_' + select + '_box');
	var uBox = document.getElementById('opt_' + unselect + '_box');

	sTab.className = 'selected';
	sBox.style.display = '';
	uTab.className = 'unselected';
	uBox.style.display = 'none';
}

// code to do a live update of the count as a result of the query string

var req;

function loadXMLDoc(url, func) 
{
    // branch for native XMLHttpRequest object
    if (window.XMLHttpRequest)
    {
        req = new XMLHttpRequest();
        req.onreadystatechange = func;
        req.open("GET", url, true);
        req.send(null);
    // branch for IE/Windows ActiveX version
    }
    else if (window.ActiveXObject)
    {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req)
        {
            req.onreadystatechange = func;
            req.open("GET", url, true);
            req.send();
        }
    }
}

function processReqChange() 
{
    // only if req shows "complete"
    if (req.readyState == 4)
    {
        // only if "OK"
        if (req.status == 200)
        {
			var countPanel = document.getElementById("queryCount");
			
			var r = req.responseXML;
			var rr = r.getElementsByTagName('result');
			var cnt = rr[0].firstChild.data;

			countPanel.innerHTML = 'This query returns ' + cnt + ' hits';
			
			countPanel.style.display = '';
        }
    }
}

function updateQueryCount()
{
	var db = document.blastForm.db;
	var q = document.blastForm.mrsQuery;
	
	if (q.value.length > 1)
	{
		loadXMLDoc(
			"count.do?db=" + db.options[db.selectedIndex].value + "&query=" + q.value,
			processReqChange);
	}
	else
	{
		var countPanel = document.getElementById("queryCount");
		countPanel.style.display = 'none';
	}
}

function processCooccurrenceResult() 
{
    // only if req shows "complete"
    if (req.readyState == 4)
    {
        // only if "OK"
        if (req.status == 200)
        {
			var r = req.responseXML;
			var rr = r.getElementsByTagName('coterm');
			if (rr.length > 0)
			{
				var cooccurrenceList = document.getElementById("cooccurrences");
				
				cooccurrenceList.deleteRow(0);
				
				var l = document.createElement("span");
				
				for (i = 0; i < rr.length; ++i) {
					var coterm = rr[i];
				
					var term = coterm.getElementsByTagName("term").item(0).firstChild.data;
					var url = coterm.getElementsByTagName("url").item(0).firstChild.data;
					
					var txt = document.createTextNode(term);
					var a = document.createElement("a");
					a.setAttribute("href", unescape(url));
					a.appendChild(txt);
					
					l.appendChild(a);
					l.appendChild(document.createTextNode(" "));
				}
	
				var td = document.createElement("td");
				td.appendChild(l);
				
				var tr = document.createElement("tr");
				tr.appendChild(td);
				
				cooccurrenceList.appendChild(tr);
			}
			else
			{
				var l = document.getElementById('fetch_cooccurrences_link');
				if (l)
					l.innerHTML = 'no suggestions found';
			}
        }
    }
}

function fetchCooccurrences(db, query)
{
	loadXMLDoc(
		"cooccurrence.do?db=" + db + "&query=" + query, processCooccurrenceResult);
	
	var l = document.getElementById('fetch_cooccurrences_link');
	if (l)
		l.innerHTML = 'please wait...';
}

// --------------------------------------------------------------------
//
// select menu handling
//

function menuItem(name, text, link, enable)
{
	this.name = name;
	this.text = text;
	this.link = link;
	this.enable = enable;
}

function menu()
{
	var items = new Array();
	var args = menu.arguments;
	this.name = args[0];
	this.container = args[1];
	
	for (i = 2; i < args.length; ++i)
		items[i - 2] = args[i];

	this.menuItems = items;
	this.write = writeMenu;
	this.updateItems = updateItems;
}

function writeMenu()
{
	var text = '<img onmouseover="showMenu(\'' + this.name + '\');"' +
					'onmousedown="showMenu(\'' + this.name + '\');"' +
					'id="triangle" src="images/triangle-down-white-2.png"/>';
	text += '<div id="' + this.name + '" ';
	text += 'class="selectMenu" ';
	text += 'onmouseover="overMenu(\'' + this.name + '\');" ';
	text += 'onmouseout="leaveMenu(\'' + this.name + '\');" ';
	text += '><ul>';
	for (i = 0; i < this.menuItems.length; ++i)
	{
		text += '<li onclick="' + this.menuItems[i].link + '" id="' + this.menuItems[i].name + '" class="enabled" >';
		text += this.menuItems[i].text;
		text += '</li>';
	}
	text += '</ul></div>';
	
//	alert(text);
	
	document.write(text);
	document.close();

	var m = document.getElementById(this.name);
	m.menu = this;
}

function showMenu(menu)
{
	var m = document.getElementById(menu);

	m.menu.updateItems();
	
	if (m.style.display != 'block')
	{
		m.style.display = 'block';
	
		window.menu = m;
		window.onclick = new Function("this.menu.style.display = 'none'; this.menu = ''; this.onclick = '';");
	}
}

function updateItems()
{
	for (i = 0; i < this.menuItems.length; ++i)
	{
		var menuItem = this.menuItems[i];

		var item = document.getElementById(menuItem.name);
		
		if (menuItem.enable())
			item.className = 'enabled';
		else
			item.className = 'disabled';
	}
}

function overMenu(menu)
{
	if (window.menuTimerSet)
		window.clearInterval(window.menuTimer);
	window.menuTimerSet = false;
}

function leaveMenu(menu)
{
	if (window.menuTimerSet == false)
	{
		window.menuTimer = window.setInterval(hideMenu, 1000, menu);
		window.menuTimerSet = true;
	}
}

function hideMenu(menu)
{
	if (window.menuTimerSet)
	{
		var m = document.getElementById(menu);
		m.style.display = 'none';
		
		window.clearInterval(window.menuTimer);
		window.menuTimerSet = false;
	}
}

function anySelected(container)
{
	var result = false;

	var cb = document.getElementById(container).getElementsByTagName('input');

	for (var i = 0; result == false && i < cb.length; ++i)
		result = cb[i].checked;

	return result;
}

function allSelected(container)
{
	var result = true;

	var cb = document.getElementById(container).getElementsByTagName('input');

	for (var i = 0; result == true && i < cb.length; ++i)
		result = cb[i].checked;
	
	return result;
}

function selectAll(container)
{
	var cb = document.getElementById(container).getElementsByTagName('input');

	for (i = 0; i < cb.length; ++i)
		cb[i].checked = true;
}

function deselectAll(container)
{
	var cb = document.getElementById(container).getElementsByTagName('input');

	for (i = 0; i < cb.length; ++i)
		cb[i].checked = false;
}

function exportEntries(format)
{
	var form = document.plainForm;

	if (form == null)	// happens on the blast results page
	{
		form = document.clustalForm;
		if (form == null)
			alert('form not found');
		form.action = 'plain.do';
	}

	form.format.value = format;
	form.submit();
}

function export2Clustal(format)
{
	var form = document.plainForm;

	if (form == null)	// happens on the blast results page
	{
		form = document.clustalForm;
		if (form == null)
			alert('form not found');
		form.action = 'plain.do';
	}

	form.format.value = format;
	form.submit();
}
// --------------------------------------------------------------------
//
// shift click support, for Gert
//

var
	gLastClicked, gClickedWithShift;

function doMouseDownOnCheckbox(event)
{
	gClickedWithShift = event.shiftKey;
	return true;
}

function doClickOnCheckbox(event, list, id)
{
	event.cancelBubble = true;		// will this continue to work???
	if (event.stopPropagation)
		event.stopPropagation(true);

	var cb = document.getElementById(id).firstChild;
	var list = document.getElementById(list).getElementsByTagName('td');
	
	if (cb && cb.checked)
	{
		var ix1, ix2;
		
		ix2 = gLastClicked;
		for (i = 0; i < list.length; ++i)
		{
			if (list[i].id == id || list[i].id == gLastClicked)
			{
				ix1 = i;
				break;
			}
		}
		gLastClicked = ix1;
		
		if (ix1 != ix2 && ix2 >= 0 && gClickedWithShift)
		{
			if (ix1 > ix2)
			{
				var tmp = ix1;
				ix1 = ix2;
				ix2 = tmp;
			}
			
			for (i = ix1; i < ix2; ++i)
				list[i].firstChild.checked = true;
		}
	}
	else
	{
		gLastClicked = -1;
	}

	return true;
}

// alternate stylesheet support

function setActiveStyleSheet(title)
{
	var links = document.getElementsByTagName("link");

	for (var i = 0; i < links.length; ++i)
	{
		var a = links[i];
		
		if (a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title"))
		{
			a.disabled = true;
			if (a.getAttribute("title") == title)
				a.disabled = false;
		}
	}
	
	setCookie("style", title, "/");
}

function getActiveStyleSheet()
{
	var links = document.getElementsByTagName("link");
	var result = null;

	for (var i = 0; i < links.length; ++i)
	{
		var a = links[i];
		if (a.getAttribute("rel").indexOf("style") != -1
				&& a.getAttribute("title")
				&& !a.disabled)
		{
			result = a.getAttribute("title");
			break;
		}
	}

	return result;
}

function getPreferredStyleSheet()
{
	var links = document.getElementsByTagName("link");

	for (var i = 0; i < links.length; ++i)
	{
		var a = links[i];

		if (a.getAttribute("rel").indexOf("style") != -1
				&& a.getAttribute("rel").indexOf("alt") == -1
				&& a.getAttribute("title"))
			return a.getAttribute("title");
	}

	return null;
}

// for highlighting query terms

function toggleShowHighlightTerms()
{
	var e = document.getElementById("entrytext");

	if (e != null)
	{
		if (e.className == 'highlightwords')
		{
			e.className = '';
			setCookie("highlight", "off", 365);
		}
		else
		{
			e.className = 'highlightwords';
			setCookie("highlight", "on", 365);
		}
	}
	
	return true;
}

// set the onload and onunload functions

window.onload = function(e)
{
	var cookie = getCookie("style");
	var title = cookie ? cookie : getPreferredStyleSheet();
	if (title != null)
		setActiveStyleSheet(unescape(title));

	cookie = getCookie("highlight");
	if (cookie == "off")
	{
		toggleShowHighlightTerms();
		var cb = document.getElementById("highlightswitch");
		if (cb != null)
			cb.checked = false;
	}
}

window.onunload = function(e)
{
	var title = getActiveStyleSheet();
	setCookie("style", title, 365, "/");
}
