/*
 * Sets active tab on main page.
 */
function setActiveTab(tab)
{
	ntabs = 6;

	for (i = 0; i < ntabs; i++)
	{
		document.getElementById("tabdiv" + i).style.display = "none";
		document.getElementById("tabb" + i).className = "";
		if (i == tab)
		{
			document.getElementById("tab" + i).className = "tab_active";
			document.getElementById("tab" + i).style.width = "88px";
			document.getElementById("tabdiv" + i).style.display = "";
			document.getElementById("tabb" + i).className = "tab_active_b";
		}
		else if (i == tab - 1)
		{
			document.getElementById("tab" + i).className = "tab_left";
			document.getElementById("tab" + i).style.width= "73px";
		}
		else if (i == tab + 1)
		{
			document.getElementById("tab" + i).className = "tab_right";
			document.getElementById("tab" + i).style.width= "73px";
		}
		else 
		{
			document.getElementById("tab" + i).className = "tab_normal";
			document.getElementById("tab" + i).style.width = "78px";
		}
	}

	if (tab == 0)
		document.getElementById("tabml").className = "tab_marginb";
	else
		document.getElementById("tabml").className = "tab_margin";
	if (tab == ntabs - 1)
		document.getElementById("tabmr").className = "tab_marginb";
	else
		document.getElementById("tabmr").className = "tab_margin";			
	document.getElementById("search_form").style.display = "none";	  	    				  	    
	document.getElementById("search_form").style.display = "";
}

/*
 * Creates object used in all AJAX requests.
 * Returns the object or null if browser is not supported.
 */
function getRequestObject()
{
	try
	{
		// Firefox, Opera 8.0+, Safari
		xmlHttp = new XMLHttpRequest();
	}
	catch (e)
	{
		// Internet Explorer
		try
		{
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			try
			{
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e)
			{
				xmlHttp = null;
			}
		}
	}
	
	return xmlHttp;
}

// Stores short names received from the web service
var cachedResiduesShortNames = new Array();

/*
 * Ramoves all option elements from the list.
 */
function clearList(destSelectId)
{
	toRemove = document.getElementById(destSelectId).options.length;
	for (j = 0; j < toRemove; j++)
		document.getElementById(destSelectId).options[0] = null;
}

/*
 * Fills the list of some select element with options which contain 
 * short names of residue.
 */
function setShortNamesOptions(destSelectId, options)
{
	i = 1;
	clearList(destSelectId);
	document.getElementById(destSelectId).options[0] = new Option("Any", "0");
	for (opt in options)
	{
		if (options[opt] != "")
		{
			tokens = options[opt].split(":");
			id = tokens[0];
			newOption = new Option(tokens[1], id + "," + tokens[1]);
			if (tokens[2] != "")
				newOption.title = tokens[2];
			document.getElementById(destSelectId).options[i] = newOption;
			i = i + 1;
		}
	} 
	document.getElementById(destSelectId + "Row").style.display = "";
	document.getElementById(destSelectId + "Wait").style.display = "none";
}

/*
 * Retrieves names of residues from the web service and fills the
 * list with them.
 */
function setResiduesShortNames(residue, destSelectId, destValue)
{
    /*
	if (residue == "any" || isUpper(residue))
	{
		document.getElementById(destSelectId + "Row").style.display = "none";
		if (isUpper(residue))
		{
			document.getElementById(destSelectId + "Info").style.display = "";
			if (residue == 'A') document.getElementById(destSelectId + "InfoText").innerHTML = 'ADE';
			if (residue == 'C') document.getElementById(destSelectId + "InfoText").innerHTML = 'CYT';
			if (residue == 'G') document.getElementById(destSelectId + "InfoText").innerHTML = 'GUA';
			if (residue == 'U') document.getElementById(destSelectId + "InfoText").innerHTML = 'URI';
		}
		else
			document.getElementById(destSelectId + "Info").style.display = "none";
		return;
	}
	document.getElementById(destSelectId + "Info").style.display = "none";
	
	if (typeof(cachedResiduesShortNames[residue]) != 'undefined')
	{
		setShortNamesOptions(destSelectId, cachedResiduesShortNames[residue]);
		return;
	}
	
	xmlHttp = getRequestObject();	
	if (xmlHttp == null)
	{
		document.getElementById(destSelectId).options[0] = new Option("Your browser is not supported", -1);
		return;
	}
	
	xmlHttp.onreadystatechange = function()
	{
		if(xmlHttp.readyState==4)
		{
			options = xmlHttp.responseText.split("\n");
			cachedResiduesShortNames[residue] = options;
			setShortNamesOptions(destSelectId, options);
			if (!(destValue === undefined))
				selectItem(destSelectId, destValue);				 
		}
	}
	
	clearList(destSelectId);
	document.getElementById(destSelectId).options[0] = new Option("Please wait...", "0");
	document.getElementById(destSelectId + "Row").style.display = "";
	document.getElementById(destSelectId + "Wait").style.display = "";
	
	xmlHttp.open("GET", "service.php?name=short&value=" + residue, true);
	xmlHttp.send(null); */
}

/*
 * Sets the visibility of the fifth residue on the multiplex tab.
 */
function setFifthMultiplex(visible)
{
	visible4 = document.getElementsByName("multiplex4Defined")[0].checked;
	visible &= visible4;
	
	if (visible) style = "";
	else style = "none";
	if (visible4) style4 = "";
	else style4 = "none";
	
	document.getElementById("multiplex5Label").style.display = style4;
	document.getElementById("multiplex5Content").style.display = style;
}

/*
 * Sets the visibility of the fourth residue on the multiplex tab.
 */
function setFourthMultiplex(visible)
{
	if (visible) style = "";
	else style = "none";
	
	document.getElementById("multiplex4Content").style.display = style;
	setFifthMultiplex(document.getElementsByName("multiplex5Defined")[0].checked);
}

/*
 * Called after main page is loaded.
 */					  
function initHomepage()
{
	if (document.getElementById("residueShortNames") != null)
	{
		setResiduesShortNames("any", "residueShortNames");
		// wait until value is probably cached
		setTimeout(function()
		{
			setResiduesShortNames("any", "basepair1ShortNames");
			setResiduesShortNames("any", "basepair2ShortNames");
			setResiduesShortNames("any", "multiplex1ShortNames");
			setResiduesShortNames("any", "multiplex2ShortNames");
			setResiduesShortNames("any", "multiplex3ShortNames");
			setResiduesShortNames("any", "multiplex4ShortNames");
			setResiduesShortNames("any", "step1ShortNames");
			setResiduesShortNames("any", "step2ShortNames");
			setResiduesShortNames("any", "step3ShortNames");
			setResiduesShortNames("any", "step4ShortNames");
		}, 10);
		setFourthMultiplex(false);
		preload = new Image();
		preload.src = 'img/wait.gif';
	}
	postinitHomepage();
}

/* 
 * Sets the value of checked property of all checkboxes in table
 * with nucleotides.
 */
function setAllDetails(checked)
{
	i = 0;
	while (true)
	{
		checkboxes = document.getElementsByName("details[" + i + "]");
		if (checkboxes.length == 0) break;
		checkbox = checkboxes[0];
		checkbox.checked = checked;
		i++;
	}
}

/*
 * Loads example sequence to the textarea.
 */
function loadSequenceExample(id)
{
	text = "";
	switch (id)
	{
		case 1:
			text = "#tRNA(Phe), yeast (Saccharomyces Scerevisiae)\n>strand1\ngCGGAUUUAgCUCAGuuGGGAGAGCgCCAGAcUgAAgAucUGGAGgUCcUGUGuuCGaUCCACAGAAUUCGCACCA";
			break;
		case 2:
			text = "#GNRA hairpin loop with 3 base pairs\n>strand1\nGAGGNRACUC\n(((....)))";
			break;
		case 3:
			text = "#Bulge\n>strand1\nNNNANNN\n(((.(((\n>strand2\nNNNNNN\n))))))";
			break;
		case 4:
			text = "#Non symmetrical internal loop\n>strand1\n(((...(((\n>strand2\n)))..)))";
			break;
		case 5:
			text = "#Three-way junction\n>strand1\n((((((\n>strand2\n)))....(((\n>strand3\n)))...)))";
			break;
		case 6:
			text = "#Kissing loops\n>strand1\n(((.[[[[[[)))\n>strand2\n(((.]]]]]])))";
			break;
	}
	for (i = 1; i < 7; i++)
		if (i + "" == id)
			document.getElementById("seqExample" + i).style.fontWeight = "bold";
		else
			document.getElementById("seqExample" + i).style.fontWeight = "normal";
	document.getElementById("sequences").value = text;
}

function changeSearchButton(id)
{
	document.getElementById("searchButton" + id).value = "Please wait...";
	document.getElementById("searchImage" + id).style.display = "";
}

function onPageReload()
{
	id = 0;
	while (true)
	{
		element = document.getElementById("searchButton" + id);
		if (element == null) break;
		element.value = "Search";
		document.getElementById("searchImage" + id).style.display = "none";
		id++;
	}
}

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;
		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 = '';
	}
}

function openWebmolWindow(name, value)
{
	x=window.open("","webmol","height=550,width=700,status=0,toolbar=0,resizable=1,fullscreen=1,status=0,location=0,scrollbars=0,menubar=0")
	str='<html><head><title>Webmol</title></head><body style="margin:0; padding:0;">'+
		'<object classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93" width="100%" height="100%" align="left" codebase="http://java.sun.com/products/plugin/1.2.2/jinstall-1_2_2-win.cab#Version=1,2,2,0">'+
		'<comment>'+
		'<embed type="application/x-java-applet;version=1.1" width="100%" height="100%" align="left" pluginspage="http://java.sun.com/products/plugin/"'+ 
		'java_code="proteinViewer" java_archive="'+dir+'/snafdb/webmol.jar" PROTEIN="" PDB_STRING="" PATH=""'+ 
		'URL="http://'+loc+'/'+dir+'/snafdb/servicewsession.php?name='+name+'&amp;value='+value+'&amp;" EXT=""/>'+
		'<noembed>'+
		'Plugin tag OBJECT or EMBED not supported by browser.'+
		'</noembed>'+
		'</comment>'+
		'</object></body></html>';
	x.document.write(str);
	x.document.close();
}

function openJmolWindow(name, value) 
{
	x=window.open("","jmol","height=524,width=524,status=0,toolbar=0,resizable=1,fullscreen=1,status=0,location=0,scrollbars=0,menubar=0")
	str='<html><head><title>Jmol</title>'+
	'<script src="Jmol/Jmol.js" type="text/javascript"></script>'+
	'</head><body style="margin:0; padding:0;">'+
		"<script type='text/javascript'>var jmolscript = 'load ./snafdb/servicewsession.php?name=" +
		name+"&amp;value="+value+"&amp;" + "';jmolInitialize('Jmol');jmolApplet('100%', jmolscript);</script>" +
		'</body></html>'+"\n";
	x.document.write(str);
	
	x.document.close();
	//x.refresh();
	//setTimeout(x.refresh(), 1000);
	if(ie)
		x.location.reload(true);
	//x=null;
	
}

function isUpper(char)
{
	return char == char.toUpperCase();
}

var loopElements = 0;
function addLoopSequence(id, show)
{
	if (show)
	{
		if (id >= loopElements)
		{
			seqDiv = document.getElementById("loopSequences" + loopElements);
			seqDiv.innerHTML += "	<div class='form_section'>";
			seqDiv.innerHTML += "		<b>Loop strand</b>";
			seqDiv.innerHTML +=	"		<span id=\"seehelpid\">";
			seqDiv.innerHTML +=	"			<sup>";
			seqDiv.innerHTML +=	"				<a href=\"index.php?act=help#loop\" class=\"seehelp\"><b>See Help for RNA FRABASE</b></a>";
			seqDiv.innerHTML +=	"			</sup>";
			seqDiv.innerHTML +=	"		</span>";
			seqDiv.innerHTML +=	"	</div>";
			seqDiv.innerHTML += "	<div class='form_row'>";		
			seqDiv.innerHTML += "		Length:";
			seqDiv.innerHTML += "		<input type='text' name='loopLen[" + loopElements + "]' id='loopLen" + loopElements + "' style='width: 40px'/><br/></div>";
			seqDiv.innerHTML += "	<div class='form_row'>";
			seqDiv.innerHTML += "		Sequence (optional):";
			seqDiv.innerHTML += "		<input type='text' name='loopSeq[" + loopElements + "]' id='loopSeq" + loopElements + "'/><br/></div>";
			seqDiv.innerHTML += "	<div class='form_row'>";
			seqDiv.innerHTML += "		Define another sequence:";
			loopElements++;
			seqDiv.innerHTML += "		<input type='checkbox' name='loopMore[" + loopElements + "]' id='loopMore" + loopElements + "' onclick='addLoopSequence(" + loopElements + ", this.checked)'/><br/></div>";
			seqDiv.innerHTML += "	<div id='loopSequences" + loopElements + "'>";
			seqDiv.innerHTML += "	</div>";
		}
		else
		{
			document.getElementById("loopSequences" + id).style.display = "";
		}
	}
	else
	{
		document.getElementById("loopSequences" + id).style.display = "none";
	}
}

function duplexMode(mode)
{
	if (mode == "exact")
	{
		document.getElementById("duplexInterval").style.display = "none";
		document.getElementById("duplexExact").style.display = "";
	}
	else
	{
		document.getElementById("duplexInterval").style.display = "";
		document.getElementById("duplexExact").style.display = "none";
	}
}

/*
 * Selects element on some list that has specified value.
 */
function selectItem(select, value)
{
	select = document.getElementById(select);
    for (i = 0; i < select.length; i++)
        if (select.options[i].value == value)
            select.options[i].selected = true;
}

/*
 * Checks if the e-mail address enered into some form field
 * is correct.
 */
function validateEmail(field, alerttxt)
{
	with (field)
	{
		apos = value.indexOf("@");
		dotpos = value.lastIndexOf(".");
		if (apos < 1 || dotpos - apos < 2) 
  		{
  			alert(alerttxt);
  			return false;
  		}
		else
			return true;
	}
}

/*
 * Checks if some form field that is required is not empty.
 */
function validateRequired(field, alerttxt)
{
	with (field)
	{
		if (value == null || value == "")
		{
			alert(alerttxt);
			return false;
		}
		else
			return true;
	}
}

/*
 * Checks if data entered into contact form are correct.
 */
function validateContactForm(thisform)
{
	with (thisform)
	{
		if (!validateRequired(email, "Email must be filled out!"))
		{
			email.focus();
			return false;
		}
		if (!validateEmail(email, "Email is not correct!"))
		{
			email.focus();
			return false;
		}
		if (!validateRequired(message, "Message must be filled out!"))
		{
			message.focus();
			return false;
		}
	}
	return true;
}
