// JavaScript Document
/***********************************************************************************
                           func_libs.js
                                                   2001, 2002 (c) Arthur J. Milgram   
***********************************************************************************/

/* INVARIANT FUNCTIONS USABLE BY OTHER JAVASCRIPTS. DO NOT CHANGE THIS FILE WITHOUT THE */
/* CONSENT OF A VERY LARGE AND VERY INFORMED COMMITTEE!!!!!                             */


/****************************************************************************************/
/*                               Universal Header printer                               */
/*                                                                                      */
/****************************************************************************************/


function resolveName (name) {
		var result = name.match("Pf");
		if (result != null) {
			return("<I>Plasmodium&nbsp;falciparum</I>&nbsp;");
		}
		result = name.match("Py");
		if (result != null) {
			return("<I>Plasmodium&nbsp;yoelii</I>&nbsp;");
		}
		result = name.match("Pv");
		if (result != null) {
			return("<I>Plasmodium&nbsp;vivax</I>&nbsp;");
		}
		// need to fail silently, ecause this is a high profile function.
		// i.e. appears at the top of important pages.
		return("<i>Plasmodium</i>&nbsp;spp.&nbsp;");
}

function myWindowResizeTo (w, h) {
	if (w > window.screen.availWidth) {
		w = window.screen.availWidth;
	}
	if (h > window.screen.availHeight) {
		h = window.screen.availHeight;
	}
	window.resizeTo(w,h);
}


// added target=\"_parent\" 5-29-02 to deal with framset pages. AJM
// also added mouseover functions

function printHeader(PAGE_TITLE, baseURL) 
{

var rootBaseURL = makeRootPath2ThisFile();
var headerString = "" +

"<table WIDTH=\"640\" align=center>" +
"<!-- PICTURES AND TITLE -->" +
	"<tr>" +
		"<td ALIGN=LEFT width=40><img SRC=\"" + baseURL + "sourcedir/ring.gif\" BORDER=0 height=40 width=40></td>" +
		"<td ALIGN=CENTER><b><font face=\"Arial,Helvetica\" size=+2>" + PAGE_TITLE + "</font></b></td>" +
		"<td ALIGN=RIGHT width=40><img SRC=\"" + baseURL + "sourcedir/mero.gif\" BORDER=0 height=40 width=40></td>" +
	"</tr>" +
"<!-- NAVIGATION BAR //-->" +
	"<tr>" +
		"<td colspan=\"3\">" +
			"<table width=\"640\">" +
				"<tr>" +
					"<td class=\'pdb_tb\' bgcolor=\'#444488\' width=70 align=\'center\'>" +
						"<a class=\'pdb_tb\' href=\"" + rootBaseURL + "index.html\" target=\"_parent\"" + 
						"onmouseover=\"self.status='Click here to go to main navigation page.'; return true\">" +
						"<font color=\'white\'>Home</font></a></td>" +
					"<td class=\'pdb_tb\' bgcolor=\'#444488\' width=70 align=\'center\'>" +
						"<a class=\'pdb_tb\' href=\"http://plasmodb.org\" target=\"_parent\"" + 
						" onclick=\"return checkInternet()\" " + 
						"onmouseover=\"self.status='Click here to go to PlasmoDB home page.'; return true\">" +
        				"<font color=\'white\'>PlasmoDB</font></a></td>" +						
					"<td class=\'pdb_tb\' bgcolor=\'#444488\' width=70 align=\'center\'>" +
						"<a class=\'pdb_tb\' href=\"" + baseURL + "tools.html\" target=\"_parent\"" + 
						"onmouseover=\"self.status='Click here to go to sequence manipulation tools page.'; return true\">" +
						"<font color=\'white\'>Tools</font></a></td>" +
					"<td class=\'pdb_tb\' bgcolor=\'#444488\' width=70 align=\'center\'>" +
						"<a class=\'pdb_tb\' href=\"" + baseURL + "cd.html\" target=\"_parent\"" + 
						"onmouseover=\"self.status='Click here to find out more about this CD.'; return true\">" +
						"<font color=\'white\'>About&nbsp;CD</font></a></td>" +
					"<td class=\'pdb_tb\' bgcolor=\'#444488\' width=70 align=\'center\'>" +
						"<a class=\'pdb_tb\' href=\"" + baseURL + "sequences.html\" target=\"_parent\"" + 
						"onmouseover=\"self.status='Click here to go to sequence file downloads.'; return true\">" +
						"<font color=\'white\'>Data&nbsp;sets</font></a></td>" +
					"<td class=\'pdb_tb\' bgcolor=\'#444488\' width=70 align=\'center\'>" +
						"<a class=\'pdb_tb\' href=\"" + baseURL + "history.html\" target=\"_parent\"" + 
						"onmouseover=\"self.status='Click here to retrieve and combine old searches.'; return true\">" +
        				"<font color=\'white\'>History</font></a></td>" +
					"<td class=\'pdb_tb\' bgcolor=\'#444488\' width=70 align=\'center\'>" +
						"<a class=\'pdb_tb\' href=\"" + baseURL + "multiseqrettoolpage.html\" target=\"_parent\"" + 
						"onmouseover=\"self.status='Click here to retrieve sequences.'; return true\">" +
        				"<font color=\'white\'>Seq&nbsp;Retrieval</font></a></td>" +
					"<td class=\'pdb_tb\' bgcolor=\'#444488\' width=70 align=\'center\'>" +
						"<a class=\'pdb_tb\' href=\"" + baseURL + "help/plasmohelp.html\" target=\"_parent\"" + 
						"onmouseover=\"self.status='Click here to help, tutorials and FAQs.'; return true\">" +
						"<font color=\'white\'>Help</font></a></td>" +						
				"</tr>" +
			"</table>" +
			"<a name=\'toolbar\'></a>" +
		"</td>" +
	"</tr>" +
"<!-- DIVIDING LINE -->" +
	"<tr><td colspan=3><hr></td></tr>" +
"</table>";

 // document.write(headerString);
    return headerString;
}	//end of printHeader()

// Jessie requested that feature pages and all other JavaScript DHTML pages have a footer
// like those on the front "chatty text" pages. This function is called by DHTML pages.
// It should also be used by front "chatty text" pages. STICYDKIWYD.

function printPagesDesiredFooter() {

	document.write("<font face=\"Arial,Helvetica\"><font color=\"#000000\"><font size=-1>GenePlot v4.1.&nbsp;-&nbsp;12/2005; <i>P. falciparum</i> data release February 2005. <i>P. vivax</i> data release November 2005. <i>P. yoelii</i> data release October 2002.&nbsp;Please address questions, suggestions and comments on <i>Plasmodium</i>&nbsp;GenePlot to <a href=\"mailto:helpcd@plasmodb.org\" onclick=\"return checkInternet()\">helpcd@plasmodb.org</a></font>");

	return;
}


/****************************************************************************************/
/*                             Functions from header scripts                            */
/*                                                                                      */
/****************************************************************************************/


/*******************************************************/
/* support paraphenalia for determining paths and etc. */
/*******************************************************/

function findPath2RootOfDB(currentLocation) {
	var retString;
	var directoryName = "geneplot/";
	var offset = currentLocation.lastIndexOf(directoryName);
	if (offset == -1) {
		// Need to trim of HTML file name from current location
		offset = currentLocation.lastIndexOf("/");
		if (offset == -1) {
			// can't do anything with this
			alert("Bad path data! auto-path generation failed!");
		} else {
			retString = currentLocation.substr(0, offset) + "/plasmodium_geneplot/";
		}
	} else {
		offset = offset + directoryName.length;
		retString = currentLocation.substr(0, offset);
	}
	return(retString);
}

function findRootPathOfCD(currentLocation) {
	var retString;
	var directoryName = "publications";
	var offset = currentLocation.lastIndexOf(directoryName);
	if (offset == -1) {
		//alert("Bad path data! auto-path generation failed!");
		directoryName = "plasmodium_geneplot";
		offset = currentLocation.lastIndexOf(directoryName);
		if (offset == -1) {
			retString = currentLocation;
		} else {
			retString = currentLocation.substr(0, offset);
		}
	} else {
		retString = currentLocation.substr(0, offset);
	}
	return(retString);
}


function makeRootPath2ThisFile() {

	var retString = findRootPathOfCD(window.location.href);
	return(retString);

}

function makePath2ThisFile() {

	var retString = findPath2RootOfDB(window.location.href);

	return(retString);

}

// hard code a path to SequenceTranslationTool
function retSequenceTranslationToolPath (currentLocation) {
	//alert("in retSequenceTranslationToolPath. Checking " + currentLocation);
	var directoryName = "geneplot/";
	var offset = currentLocation.lastIndexOf(directoryName);
	if (offset == -1) {
		alert("Bad path data! auto-path generation failed!");
		return;
	}
	offset = offset + directoryName.length;
	//alert("Offset calculated");
	var retString = currentLocation.substr(0, offset);
	retString = retString + "sequencetranslationtool/";
	//alert("Will send you to path\n" + retString);
	return(retString);
}

/****************************************************************************************/
/*                               End Universal Header printer                           */
/*                                                                                      */
/****************************************************************************************/


/* 
	A small family of functions to check for cookie values for configuration
	parameters.
*/

/*
	Local Cookie Handlers
*/

function setUpCookieSpecs4SiteConfig (additionalData) {
	// function is called by configuresite applet
	var baseData = document.cookie;
	if (baseData.length < 2) {
		document.cookie = escape(additionalData);
	} else {
		document.cookie = baseData + escape(additionalData);
	}
	// appends information to site wide cookie
	// alert("setting cookie");
	return;
}

function checkProjectname () {
		// retrieves data from document.cookie
		var myString = unescape(document.cookie);
		// alert("got: " + myString);
		// specifically just the ProjectName tag's value
		var pointOfContact = myString.indexOf("ProjectName=");
		if (pointOfContact == -1){
			//alert("found nothing");
			return;
		}
		var startOfVal = myString.indexOf("=\"", pointOfContact);
		startOfVal += 2;
		var endOfVal = myString.indexOf("\";", startOfVal);
		if (endOfVal == -1) {
			// send back the whole rest of the line
			return(myString.substr(startOfVal));
		} else {
			// this name value pair is in the middle of the line
			// somewhere, so tease it out.
			return(myString.substr(startOfVal, (endOfVal - startOfVal)));
		}
	}
	
/*
		check4Flag
		resolveFlag2Text
		functions to find FLAG value, and resolve it to a text translation
		
*/

// First seen in headerscript.js This evidently tries to identify the
// type of feature by investigating the FLAG value from the calling URL.
// 
function check4Flag() {
	//alert("sideline one pursued");
	var myTitle;
	var flagRegex = /FLAG=([0-9]+)/;
	var flagArray = flagRegex.exec(callingURLString);
	var flag;
	if(flagArray == null) { 
		myTitle = "Sequence Retrieval";
		return(0);
	} else {
		flag = flagArray[1];
		//myTitle = resolveFlag2Text(flag);
		return(flag); 
	}

}
	
// called directly by headerscript2 if args object initialized.
// otherwise if args fails for some reason the URL is investigated
// through check4Flag, and then this is called.
// --resolveFlag2Text's purpose is to attach an english meaning to a 
// feature's XML FLAG parameter value

function resolveFlag2Text(flag) {
	// convert flag to a text value;
	// you can find the key to the magic numbers elswhere in the source.
	// I'd put it here, but the peopl ein the lab aren't very nice to me, so
	// why should I? Nyah!
	var textOfFlag;

	if ((flag & 8) == 8) {
		textOfFlag = "CDS";
	}
	if ((flag & 16) == 16) {
		textOfFlag = "tRNA";
	}
	if ((flag & 32) == 32) {
		textOfFlag = "rRNA";
	}
	if ((flag & 256) == 256) {
		textOfFlag = "ORF";
	}
	if ((flag & 512) == 512) {
		textOfFlag = "Blast Hit";
	}
	if ((flag & 1024) == 1024) {
		textOfFlag = "GlimmerM";
	}
	if ((flag & 2048) == 2048) {
		textOfFlag = "Genefinder";
	}
	if ((flag & 4096) == 4096) {
		textOfFlag = "PHAT";
	}
	if ((flag & 8192) == 8192) {
		textOfFlag = "Hexamer";
	}
	if ((flag & 16384) == 16384) {
		textOfFlag = "Tandem Repeat Finder";
	}
	if ((flag & 4194304) == 4194304) {
		textOfFlag = "SNP";
	}
	if ((flag & 16777216) == 16777216) {
		textOfFlag = "BAC";
	}
	return(textOfFlag);
}

function findContiginURL (callingURLString) {
	var mycontigFromURL = /Contig=([a-zA-Z0-9_\.]+)/;
	var theContigs;
	var temp = callingURLString.match(mycontigFromURL);
	if(temp == null) { 
		theContigs = "None";
	} else { 
		theContigs = temp[1]; 
	}
	return(theContigs);
}

function findFeatureinURL (callingURLString) {
	var featureRegex = /feature=([|a-zA-Z0-9_]+)/;
	var featureArray = featureRegex.exec(callingURLString);
	var feature;
	if(featureArray == null) { 
		feature = "None";
	} else { 
		feature = featureArray[1]; 
	}
	return(feature);
}

function makebannerTitle (theContigs, feature, textOfFlag) {
	var bannerTitle = theContigs + ": " + feature + " " + textOfFlag + " Summary";
	return(bannerTitle);
}

/****************************************************************************************/
/*                                window opening and                                    */
/*                                  positioning                                         */
/****************************************************************************************/

// global counter per page
var pgCounter = 0;
var myX = window.screenX;
var myY = window.screenY;

function incrementWinName(winName) {
		var retName = winName + "_" + pgCounter;
		pgCounter = parseInt(parseInt(pgCounter) + 1);
		return(retName);
}

function nowUCanOpenIt(aURL, winName) {
		//var myX = window.screenX;
		//var myY = window.screenY;
		
		myX = parseInt(parseInt(myX) + 7);
		myY = parseInt(parseInt(myY) + 22);
		
		if (navigator.appName == "Netscape") {
			var controlString = "screenX=" + myX + ",screenY=" + myY + 
			",status=yes,toolbar=yes,width=600,height=500,scrollbars=yes,resizable=yes" +
			",menubar=yes,location=yes";
		} else {
			var controlString = "left=" + myX + ",top=" + myY + 
			",status=yes,toolbar=yes,width=600,height=500,scrollbars=yes,resizable=yes" +
			",menubar=yes,location=yes";		
		}
		
		//alert("win control: " + controlString);
		
		window.open(aURL, winName, controlString); 
		return;
}

function setUpANewWindowAndOpen(aURL, winName) {
		var locName = incrementWinName(winName);
		nowUCanOpenIt(aURL, locName)
		return;
}

/* ****************************** end new window open accounting scripts ********************************* */

/*
		General functions
*/

function checkOrderAndValidate(smallest, largest) {

	var nonDigit = /\D/;
	var smallLet = nonDigit.exec(smallest);
	var largeLet = nonDigit.exec(largest);
	
	//alert("received " + smallest +" and "+ largest);
	
	if (nonDigit.exec(smallest) || nonDigit.exec(largest)) {
		//alert("No characters please");
		return(1);
	} else {
		if (parseInt(smallest) > parseInt(largest)) {
			//alert ("large: " + parseInt(largest) + " small: " + parseInt(smallest));
			return(1);
		} else {
			return(0);
		}
	}
}

// convert a number into a human representation of it. i.e. add commas for each thousand.
function commaLizeNumber(aNumber) {
	var charHere, retString = "";
	var aNumberAsAString = aNumber.toString();
	var length = aNumberAsAString.length;
	var i, j;
	j = 0;
	for (i=(length - 1); i >= 0; i--) {
		charHere = aNumberAsAString.charAt(i);
		retString = charHere + retString;
		j++;
		if ((j%3) == 0 && j < length) {
		//if ((j%3) == 0) {
		retString = "," + retString;
		}
	}
	return(retString);
}

// another number conversion thing. Using this, let's people put commas in their
// numbers making it easier for them to read.
function removeCommas(someNumber) {
	var retNum = someNumber.replace(/,/g, "");
	return(retNum);
}

// because a span should always have coordinates relative to the top strand, make
// sure the span's numbers are in the correct order.
function checknumericPairVals(lessernum, greaternum) {
	// check is a valid number
		var aDigits = /^\d+$/;
		if (aDigits.exec(lessernum) == null || aDigits.exec(greaternum) == null) {
			alert("invalid numeric format");
			return(-3);
		}
        if (parseInt(lessernum) == parseInt(greaternum)) {
			alert("Start and end give dimensionless length.");
			return(-1);
		}
		if (parseInt(lessernum) > parseInt(greaternum)) {
			alert("Start less than end. Can't transform to negative coordinates.");
			return(-2);
		}
		return(0);
}

/*
	Function from David Pearson's dr.html
		Added 6-20-2002
*/
function checkInternet () {
        if (document.cookie.indexOf("PlasmoDB_Accessed=") != -1) return true
        if (confirm("Note: this link will only work if you are connected to the Internet; click 'OK' to continue")) {
            document.cookie = "PlasmoDB_Accessed=true"
            return true
        } else {
            return false
		}
}


