/**
 * @author Andrew Welch
 * These scripts are used exclusively by III system-generated pages and custom forms
 * in the online catalog (e.g., pverify_web.html, viewsaves.html). They were created
 * by Andrew Welch, Aurora Public Library, except where noted. Scripts developed by
 * III for system-generated pages can be found at /scripts/common.js, /scripts/features.js
 * and /scripts/webbridge.js. Scripts for the rest of the APL web site can be found
 * at mainScripts.js.
 */

// ***********************************************************
function doCatStuff() {
// Pulls in multiple scripts that apply to catalog-only pages under a single function.
moveNewSrch(); // all pages;
briefcitFormat(); // briefcit;
showExactItems('View all copies/volumes',7); // briefcit;
offerPurchase(); // browse results and srchhelp_X;
copyJumpTo(); // briefcit;
//createWBlink(); // bib_display;
return true;
}

// createWBlink()
// Duplicates the WebBridge link in the bib display (trying to use
// the {resourcetable} token more than once just breaks WebBridge).
function createWBlink() {
var resource = getElem('wb_bib_link');
	if (!resource) {}
	else {
		var linkspan = getElem('wb_bib_link_copy');
		wb_links = resource.parentNode;
		var wb_window = wb_links.getAttribute('onclick');
		var newWb = document.createElement('a');
		var newWbTxt = document.createTextNode('Explore this title ');
		var ckSpi = isSpanish();
		if (ckSpi == 'Spanish') {
			var accI = unescape('%ED');
			newWbTxt = document.createTextNode('Explorar este t' + accI + 'tulo ');
		}
		newWb.setAttribute('onclick',wb_window);
		newWb.setAttribute('href','');
		newWb.appendChild(newWbTxt);
		linkspan.innerHTML = '';
		linkspan.appendChild(newWb);
	}
}

// createResourceWindow - Replaces III's default function of the same name.
function createResourceWindow( url ) {
this.name = "catalog"; 
resourceWindow = top.open( url, 'ResourceWindow','resizable=yes,status=yes,scrollbars=yes,width=600,height=400');
	if ( resourceWindow.opener == null ) { resourceWindow.opener = window; }
resourceWindow.focus();
return false;
}

//************************************************************
function changeLoad(linkHolder){
// Changes III's WebBridge page load so links load in the 'self' window rather than
// a new window or a parent window with annoying frames.
var el = getElem(linkHolder);
var lnk = el.getElementsByTagName('span');
var theLink;
	if (lnk[0].className == "wblinktext") { theLink = lnk[0]; }
	else if (lnk[1].className == "wblinktext") { theLink = lnk[1]; }
	else {}
var theClick = new String(theLink.firstChild.getAttribute('onclick'));
var clStart = theClick.indexOf('search');
var clEnd = theClick.lastIndexOf(')') - 1;
}

function sortBrowse(){
// appears to fix III version of sortBrowse, which uses improper syntax for the 'if...' conditionals.
  if( document.searchtool.searchtype != null && savedTag != null )
    { document.searchtool.searchtype.options.selectedIndex = savedTag; }
  if( document.searchtool.searcharg != null && savedSearch != null )
    { document.searchtool.searcharg.value = savedSearch; }
  if( document.searchtool.searcharg != null && savedExactSearch != null )
    { document.searchtool.searcharg.value = decodeURIComponent(savedExactSearch); }
  if( document.searchtool.searchscope != null && savedScope != null )
    { document.searchtool.searchscope.options.selectedIndex = savedScope;}
  document.searchtool.submit();
}

// showExactItems()
// Allows the library to specify how many items will appear on the briefcit
// display (using the maxitems argument). If maxitems is not used, ALL attached
// items will appear.
function showExactItems(msg, maxitems) {
var itemsDiv = getElementsByClassName(document, "div", "briefcitItems"); // Change 'briefcitItems' to whatever classname you use to surround your items token. 
var bibTitle = getElementsByClassName(document, "div", "briefcitTitle"); // Change 'briefcitTitle' to whatever classname you use to surround your title token.
var hasDupTitle = false; // If your library also uses the briefTitleOnly script, change this to 'true' (without quotes);
var bibLink, q;
	if (itemsDiv.length == 0) {} // There are no item tables, or this is not a briefcit page;
	else {
		for (var i=0; i<itemsDiv.length; i++) {
		var getTabs = itemsDiv[i].getElementsByTagName('table'); // Find all tables in the itemsDiv;
			if (getTabs.length <= 1 || !document.createElement) {} // There is no 'additional copies' table, so do nothing;
			else {
				itemsDiv[i].innerHTML = ""; // Clear out the existing items table;
				if (hasDupTitle == true) { q = i * 2; }
				else { q = i; }
				var bibT = bibTitle[q].getElementsByTagName('a'); // Get each title's 'A' tag;
//				var bibT = bibTitle[i].getElementsByTagName('a'); // Get each title's 'A' tag;
					if (bibT.length == 0) { return; } // if the title isn't linked, stop.
//				bibLink = bibT[0].href; // Option 1: Creates a link to the full record from the bib's Title link;
				bibLink = bibT[0].href.replace(/frameset/,"holdings"); // Option 2: Creates a link to the full holdings table instead of the full record;
				getHoldings(bibLink, itemsDiv[i], maxitems); // Retrieves the full holdings table;
			}
		}
	}
}
// getHoldings() - Written by Andrew Welch, Aurora Public Library.
// Retrieves item holdings screen (pageURL), compares the number
// of items rows agains maxitems, and creates the appropriate
// table length to load into obj.
function getHoldings(pageURL, obj, maxitems) {
var ajaxOK = createAjaxObj();
	if (!ajaxOK) {}
	else if (ajaxOK) {
		ajaxOK.open("GET", pageURL);
		
		ajaxOK.onreadystatechange = function() {
			if (ajaxOK.readyState == 4 &&
			ajaxOK.status == 200) {
				var innerdiv = ajaxOK.responseText;
				var tabStart = innerdiv.indexOf('class="bibItems"');
				tabStart = tabStart + 17;
				var tabEnd = innerdiv.indexOf('</table',tabStart);
				innerdiv = innerdiv.slice(tabStart,tabEnd);
				var rowCount = 0;
				var rowPos = innerdiv.indexOf("<tr ");
					if (maxitems != null) {
						maxitems = maxitems + 1;
						while ( rowPos != -1 && rowCount <= maxitems ) {
   						rowCount++;
   						rowPos = innerdiv.indexOf("<tr ",rowPos + 1);
						}
					innerdiv = innerdiv.slice(0,rowPos);
					}
				var newDiv = document.createElement('div');
				newDiv.className = "briefcitAllItems";
				newDiv.innerHTML = "<table class='bibItems'>" + innerdiv + "</table>";
					if (rowCount > maxitems && maxitems != null) {
						var newLink = document.createElement('a');
						var newLinkTxt = document.createTextNode('View all copies');
						newLink.className = "moreCopies";
						newLink.href = pageURL;
						newLink.appendChild(newLinkTxt);
						obj.appendChild(newDiv);
						obj.appendChild(newLink);
					}
					else { obj.appendChild(newDiv); }
			}
		}
		ajaxOK.send(null);	
	}
}

// ***********************************************************
function copyJumpTo() {
// On briefcit.html, if the "Jump to Entry" form exists at the bottom,
// moves it to the top also. (in browseSaveJump table cell)
var jumpCell = getElementsByClassName(document, "td", "browseSaveJump");
var DOMw3c = (document.createElement && document.getElementsByTagName);
	if (!jumpCell || jumpCell.length<2 || !DOMw3c) {}
	else {
		var formCt = jumpCell[1].getElementsByTagName("form");
		if (formCt.length == 1) {
			formCt[0].id = "jump_form2";
		}
		else {
			for (var i=0; i<formCt.length; i++) {
				if (formCt[i].id != "export_form") {
					formCt[i].id = "jump_form2";
				}
			}
		}
		var jumpBtn = getElem("jumpToEntry");
		if (!jumpBtn) {	}
		else {
			var origFrm = getElem("jump_form2");
			var origAct = origFrm.getAttribute("action");
			var newJumpFrm = document.createElement("form");
			var newInput = document.createElement("input");
			var newInput2 = document.createElement("input");
			var newInput3 = document.createElement("input");
			var newBtn = document.createElement("A");
			newJumpFrm.id = "jump_form1";
			newJumpFrm.setAttribute("method","post");
			newJumpFrm.setAttribute("action",origAct);
			newInput.setAttribute("type","hidden");
			newInput.value = origFrm.jumpref.value;
			newInput2.setAttribute("type","hidden");
			newInput2.id = "iiiFormHandle_2";
			newBtn.setAttribute("onclick","iiiDoSubmit_jump();");
			newBtn.href = "#";
			newBtnEl = document.createElement("B");
			newBtnText = document.createTextNode("Jump to Entry:");
			newBtnEl.appendChild(newBtnText);
			newBtnEl.style.color = "#003366";
			newBtn.appendChild(newBtnEl);
			newInput3.setAttribute("type","text");
			newInput3.setAttribute("maxlength",origFrm.jumpto.maxlength);
			newInput3.setAttribute("size",origFrm.jumpto.size);
			newInput3.setAttribute("name","jumpto");
			newJumpFrm.appendChild(newInput);
			newJumpFrm.appendChild(newInput2);
			newJumpFrm.appendChild(newBtn);
			newJumpFrm.appendChild(newInput3);
			origJS = origFrm.getElementsByTagName("script");
			jsEnd = origJS[0].innerHTML.lastIndexOf("}");
			str1 = origJS[0].innerHTML.slice(0,jsEnd);
			jumpTxt = "\niiiDoSubmit_jump(); }";
			jumpScript = str1 + jumpTxt;
			jumpScript = origJS[0].innerHTML;
			jumpCell[0].appendChild(newJumpFrm);
		}
	}
}

function iiiDoSubmit_jump() {
// Used in conjunction with copyJumpTo();
var name = "iiiFormHandle_2";
	if (document.getElementById) {
	obj = document.getElementById(name);
	}
	else if (document.all) {
		obj = document.all[name];
	}
	else if (document.layers) {
		obj = document.layers[name];
		obj.form.submit();
	}
}

// ***************************************************************
function isSpanish() {
// Determines whether the current page is a Spanish-language page
// by looking for "*spi" or "_spi.html" in the URL.
var pageURL = new String(document.location);
var iiiSpan = "*spi";
var ourSpan = "_spi.html";
var lang;
	if (pageURL.indexOf(iiiSpan) != -1 || pageURL.indexOf(ourSpan) != -1) {	lang = "Spanish"; }
	else { lang = "English"; }
return lang;
}

// ***************************************************************
function moveNewSrch() {
// Moves the 'New Search' button, which is hidden in the toplogo, to the first
// button position of navigationRow in briefcit and bib_display.
var btnOrig = getElem("startoverBtn");
var navrow = getElementsByClassName(document, "div", "navigationRow");
var bibNav = getElem("navigationRow"); //only appears on bib_display.html;
	if (!btnOrig) {} // 'startoverBtn' not there; patron already logged in;
	else if (!bibNav) { //page is a briefcit page;
		if (navrow.length<1) { }
		else {
		//var navrow = getElementsByClassName(document, "div", "navigationRow");
		var topnavrow = navrow[0];//getElem("navRow0");
		var navform0 = (topnavrow.firstChild.nodeName == "FORM")? topnavrow.firstChild : topnavrow.firstChild.nextSibling;
		var kid1 = (navform0.firstChild.nodeName == "A")? navform0.firstChild : navform0.firstChild.nextSibling;
		var newNode = document.createElement("b");
			newNode.innerHTML = btnOrig.innerHTML;
			navform0.insertBefore(newNode, kid1);
			if (navform0.childNodes[2].nodeName == "B") {
				navform0.removeChild(navform0.childNodes[2]);
			}
			else if (navform0.firstChild.nodeName == "B" && navform0.firstChild.nextSibling.nodeName == "B") {
				navform0.removeChild(navform0.firstChild);
			}
			else {}
		}
	}	
	else if (bibNav) { 
//		var navChild = (bibNav.firstChild.nodeName == "A")? bibNav.firstChild : bibNav.firstChild.nextSibling;
		var navChild = bibNav.firstChild;
		var newNode = document.createElement("b");
		newNode.innerHTML = btnOrig.innerHTML;
		bibNav.insertBefore(newNode, navChild);
		if (bibNav.childNodes[0].nodeName == "B" && bibNav.childNodes[1].nodeName == "B") {
			bibNav.removeChild(bibNav.firstChild);
		}
		else {}
	}
	else {}
}

// ***********************************************************
function createParent(which,clName) {
// Used on Featured List to give nav button container a className.
// Event trigger attached to BUT_RET2FEAT and FEATURED_LISTS.
	if (!which || which.length == 0) {}
	else {which.parentNode.parentNode.className = clName;}
}


// ***********************************************************
function offerPurchase_XXX() {
// Presents a "Suggest a purchase" link to the user on a failed search;
var notFound = $(".yourEntryWouldBeHereData");
var offerTxt = "<div><a href='/acquire' class='strong' title='Suggest an item for the library to purchase'>Suggest&nbsp;a&nbsp;purchase</a></div>";
var navbar = $(".navigationRow a");
var srchUrl = new String(document.location);
var srcharg = $("input[name=searcharg]")[0];
var srchtype = $("select[name=searchtype] option:selected")[0].value;
	if (!notFound[0]) {return;} // yourEntryWouldBeHereData cell doesn't exist;
//	var allLinks = $(navbar[0] + " a"); alert(allLinks.length);
	for (var m; m<navbar.length; m++) { // look for the Prospector link in nav row;
		if (navbar[m].href.indexOf('prospector.coalliance.org/search') == -1) {}
		else {
			var prosLink = navbar[m].href;
			offerTxt = "<div><a href='" + prosLink + "' class='strong' title='Search other libraries with Prospector'>Search&nbsp;other&nbsp;libraries</a></div>" + offerTxt;
		}
	}
	var nfText = $(".yourEntryWouldBeHereData b");
	var nfAU = $(notFound[0] + " br");
	if (!nfText[0]) {}
	else if (nfAU[0]) {
		$(notFound)[0].innerHTML += "&nbsp;or you can " + offerTxt;
	}
	else { // offer a swapped search, even if the author name has more than two words;
		var spaces = srcharg.value.split(/ /g);
		if (spaces.length > 2) {
			srcharg.value = srcharg.value.trim();
			var fstop = srcharg.value.indexOf(" ");
			var lstop = srcharg.value.lastIndexOf(" ");
			var fname = srcharg.value.slice(0,lstop);
			var lname = srcharg.value.slice(lstop);
			var newname = lname + ", " + fname;
			var newnameURL = newname.replace(/ /g,"+");
//				var brk = srchUrl.indexOf('&');
//				var srchUrl1 = srchUrl.slice(0,brk);
//				srchUrl1 = srchUrl1.replace(/(.+(SEARCH|searcharg)=).+(&.+)/,"");
//				notFound[0].innerHTML += "- Change search to <a href='/search/a?SEARCH" + newnameURL + "&sortdropdown=-&searchscope=2' class='bold'>" + newname + "</a> or ";
		}
		else {}
		var nfStr = $(notFound)[0].innerHTML;
		if (nfStr.indexOf('--') == -1) {
			$(notFound)[0].innerHTML += "&nbsp;&nbsp;(" + offerTxt + ")";
		}
		else {
			$(notFound)[0].innerHTML += "&nbsp;or " + offerTxt; 
		}
	}
}

// ***********************************************************
function offerPurchase() {
// Presents alternatives to the user on a failed search;
var notFound = getElementsByClassName(document, "td", "yourEntryWouldBeHereData");
var acquire = "/acquire";
var shop = "http://apl.mylibrarybookstore.com";
var navbar = getElementsByClassName(document, "div", "navigationRow");
var srchUrl = new String(document.location);
var srcharg = document.getElementsByName('searcharg')[0];
var srchtype = document.getElementsByName('searchtype')[0];

if (!notFound[0]) {return;}
var srchopt = srchtype[srchtype.selectedIndex].value;
var allLinks = navbar[0].getElementsByTagName('a');
var fieldterm = srcharg.value.trim();
var keyterms = fieldterm.replace(/ /g,'+');
switch(srchopt) {
	case "t":
	acquire = "/acquire?title=" + keyterms;
	break;
	case "a":
	acquire = "/acquire?author=" + keyterms;
	break;
	case "i":
	shop = "https://apl.mylibrarybookstore.com/MLB/actions/searchHandler.do?key=" + keyterms + "&amp;NextPage=bookDetails&amp;parentNum=11684";
	break;
}
var key = "/search/X?SEARCH=" + keyterms + "&amp;searchscope=2&amp;sortdropdown=-";
var keyTxt = "<a href='" + key + "' class='block bold' title='Searching as keywords'>Searching for \"" + fieldterm + "\" as keywords</a>";
var acquireTxt = "<a href='" + acquire + "' class='block bold' title='Suggesting an item for the library to purchase'>Suggesting&nbsp;a&nbsp;purchase</a>";
var mlbText = "<a href='" + shop + "' class='block bold' title='Shopping and buying at MyLibraryBookstore'>Shopping and buying at MyLibraryBookstore</a>";
var illText = "<a href='/illb' class='block bold' title='Submitting an Interlibrary Loan (ILL) request'>Submitting an Interlibrary Loan (ILL) request</a>";
	for (var m=0; m<allLinks.length; m++) { // look for the Prospector link in nav row;
		if (allLinks[m].href.indexOf('prospector.coalliance.org/search') == -1) {}
		else {
			var prosLink = allLinks[m].href;
			prospTxt = "<a href='" + prosLink + "' class='block bold' title='Searching other libraries with Prospector'>Searching&nbsp;for \"" + fieldterm + "\" at&nbsp;other&nbsp;Prospector&nbsp;libraries</a>";
			offerTxt = keyTxt + prospTxt + illText + acquireTxt + mlbText;
		}
	}
var nfText = notFound[0].getElementsByTagName("b");
var nfAU = notFound[0].getElementsByTagName("br");
	if (nfText.length==0) {}
	else if (nfAU.length>0) {
		notFound[0].innerHTML += "&nbsp;or try:" + offerTxt;
	}
	else { // offer a swapped search, even if the author name has more than two words;
		var spaces = srcharg.value.split(/ /g);
		if (spaces.length > 2) {
			srcharg.value = srcharg.value.trim();
			var fstop = srcharg.value.indexOf(" ");
			var lstop = srcharg.value.lastIndexOf(" ");
			var fname = srcharg.value.slice(0,lstop);
			var lname = srcharg.value.slice(lstop);
			var newname = lname + ", " + fname;
			var newnameURL = newname.replace(/ /g,"+");
//			var brk = srchUrl.indexOf('&');
//			var srchUrl1 = srchUrl.slice(0,brk);
//			srchUrl1 = srchUrl1.replace(/(.+(SEARCH|searcharg)=).+(&.+)/,"");
//			notFound[0].innerHTML += "- Change search to <a href='/search/a?SEARCH" + newnameURL + "&sortdropdown=-&searchscope=2' class='bold'>" + newname + "</a> or ";
		}
		else {}
	var nfStr = new String(notFound[0].innerHTML);
		if (nfStr.indexOf('--') == -1) {
			notFound[0].innerHTML += "&nbsp;-&nbsp;Try:" + offerTxt;
		}
		else {
			notFound[0].innerHTML += "&nbsp;or try: " + offerTxt; 
		}
	}
}

// ***********************************************************
function bibPermLink() {
// Creates a clickable URL from the 'recordnum' id of the bib display.
var bibrec = getElem("recordnum");
var numStr = bibrec.href;
	if (numStr.slice(-4) == "*spi") { // if it's a Spanish URL;
		document.write("URL permanente para este registro:<div><a href=\"" + numStr + "\">" + numStr + "</a></div>");
	}
	else {
		document.write("Permanent link to this record:<div><a href=\"" + numStr + "\">" + numStr + "</a></div>");
	}
}// end bibPermLink()


// ***********************************************************
function briefcitFormat() {
// Does some cleanup of briefcit display; changes author name to
// FirstName LastName, puts year in parentheses behind author, deletes
// Length field and/or Author field if there is no content in them.
var bibRow = getElementsByClassName(document, "tr", "briefcitRow");
var bibitems = getElementsByClassName(document, "td", "briefcitDetail");
var bibYear = getElementsByClassName(document, "div", "briefcitYear");
var bibPub = getElementsByClassName(document, "div", "briefcitPub")
var bibLength = getElementsByClassName(document, "div", "briefcitLength");
var bibAuthor = getElementsByClassName(document, "span", "briefcitAuthor");
var bibAuthorL = getElementsByClassName(document, "div", "briefcitAuthorLabel");
var hasNum = new RegExp(".*[0-9]+.*");
	if (bibRow.length == 0) {}
	else {
	for (m=0; m<bibitems.length; m++) {
		if (!bibYear) { }
		else if (!bibYear[m].innerHTML.match(hasNum)) {
			bibYear[m].style.display = "none";
		}
		else {
			var yearText = bibYear[m].firstChild.nodeValue;
			var yearClean = yearText.replace(/\n*\s*[cp]?/g,"");
			bibPub[m].innerHTML = '(' + yearClean + ')';
			bibYear[m].firstChild.nodeValue = yearClean;
		}
		if (!bibLength[m]) {}
		else if (!bibLength[m].innerHTML.match(hasNum)) { //Length field has no numbers (ie, is empty or useless);
			bibLength[m].style.display = "none";
		}
		else {
			var lengthText = bibLength[m].firstChild.nodeValue;
			lengthText = lengthText.replace(/\s+[:;]\s+$/,"");
				if (lengthText.indexOf(' p.') != -1) {
					lengthText = lengthText.replace(/\sp\./," pages");
				}
				if (lengthText.indexOf('ca. ') != -1) {
					lengthText = lengthText.replace(/ca\./,"about");
				}
			bibLength[m].firstChild.nodeValue = lengthText; //remove trailing punctuation;
		}
		if (!bibAuthor) { }
		else if (!bibAuthor[m].firstChild) {
			bibAuthorL[m].style.display = "none"; //delete the entire Author div
		}
		else {
			var auText = bibAuthor[m].firstChild.nodeValue;
			var auTrim = auText.trim();
			var findCom = auTrim.indexOf(",");
			var deleteCom = findCom + 2;
			var cleanEx = auTrim.replace(/[,\.]$/,"");
			var nameEnd = cleanEx.length;
			var lName = auTrim.slice(0,findCom);
			var fName = auTrim.slice(deleteCom,nameEnd);		
			if (findCom == -1){	}
			else {
				bibAuthor[m].firstChild.nodeValue = "by " + fName + " " + lName + ". ";
			}
		}
	}
	var bookJacket = getElementsByClassName(document, 'div', 'briefcitJacket');
	if (bookJacket.length == 0) {}
	else {
//		for (var z=0; z<bookJacket.length; z++) {
		var z = bookJacket.length;
		while (z--) {
			var jackImg = bookJacket[z].getElementsByTagName('img');
			var makeImg = document.createElement('img');
			if (jackImg[0].src.indexOf('Product=&') != -1) {
				jackImg[0].src = '/screens/images/imgmissing.gif';
			}
			if (jackImg.length > 0) {
				if (jackImg[0].height > 20) {}
				else {
					makeImg.setAttribute('src','/screens/images/imgmissing.gif');
					bookJacket[z].appendChild(makeImg);
				}
			}
			else if (jackImg.length == 0) {
				makeImg.setAttribute('src','/screens/images/imgmissing.gif');
				bookJacket[z].appendChild(makeImg);
			}
		}
	}
	}
}

function insertHold() {
// Creates a Request link next to the item status in bib_display
// by copying the href of the real Request button from the nav row.
// If the status of an item is noncirculating, the link doesn't appear.

// The name of your BUT_REGULAR_DISPLAY image (if no img src, use value ""):
var imgName = "";

// If BUT_REGULAR_DISPLAY is a transparent image, provide its className (otherwise, use value ""):
var imgClass = "regDispBtn";

// The wording of your non-circulating items, or items for which you DO NOT want a Request link to appear (separate with a pipe "|"):
var noncirc = "(LIB USE ONLY|MISSING|LOST|PERDIDO|USO INTERNO)";

// In which column does your Status appear (or, which column holds the circ/noncirc wording)?
var colnum = 3;

// Choose the wording of the Request link (separating words with &nbsp; is recommended):
var reqText = "Request&nbsp;it";

// Assign a class to the Request link (optional):
var reqClass = "size80";

// NO NEED TO EDIT BEYOND THIS POINT.
var itemRow = getElementsByClassName(document, "tr", "bibItemsEntry");
if (itemRow.length == 0) {}
var navRow = getElementsByClassName(document, "div", "navigationRow")[0];
var urlStr = new String(document.location);
var reqLink, j, getBtn, holdBtn;
var nonReq = new RegExp(noncirc);
var language = isSpanish();
if (language == "Spanish") { reqText = "Reservarlo"; }
colnum = colnum - 1;
	if (!navRow) { // not bib_display; could be Additional Copies display. If so, create appropriate links.
		var copyNav = getElementsByClassName(document, "div", "additionalCopiesNav");
		var copyTab = getElementsByClassName(document, "div", "additionalCopies");
		if (copyNav.length == 0) {} // Not the "Additional Copies" page; do nothing.
		else if (copyNav.length > 0 && copyTab.length > 0) {
			if (imgName != "") {
				getImgs = copyNav[0].getElementsByTagName('img');
				for (var z=0; z<getImgs.length; z++) {
					if (getImgs[z].src.indexOf(imgName) != -1) {
						getBtn = getImgs[z];
					}
					else {}
				}
			}
			else {
				getBtn = getElementsByClassName(document, "img", imgClass)[0];
			}
//			var btnLink = getBtn.parentNode.getAttribute("href");
			holdBtn = getBtn.parentNode.getAttribute('href').replace(/frameset/,"request");
//			holdBtn = btnLink.replace(/frameset/,"request");
		}
		else {} // Request button is missing or suppressed, so do nothing;
	} 
	else if (navRow) {
		holdBtn = getBtnHref("request", "navigationRow");
		if (!holdBtn) {return;} // Request button is missing or suppressed, so exit;
	}
	reqLink = (" <span class='" + reqClass + "'>[&nbsp;<a href='" + holdBtn + "'>" + reqText + "</a>&nbsp;]</span>");
	for (j=0; j<itemRow.length; j++) {
		var itemCell = itemRow[j].cells;
		if (itemCell[colnum].innerHTML.search(nonReq) != -1) {}
		else {
			itemCell[colnum].innerHTML += reqLink;
			if (itemCell[colnum].getElementsByTagName("span").length > 1) {
				itemCell[colnum].removeChild(itemCell[colnum].lastChild);
			}
			else {}
		}
	}
}

// ***********************************************************
function getBtnHref(btn, locID) {
// Looks for text 'btn' in a link in the div 'locID' and returns
// the link's href.
var navEl = getElementsByClassName(document, "div", locID);
var navrow = navEl[0].getElementsByTagName("a");
var butname = new RegExp(".+" + btn + ".+");
	for (i=0; i<navrow.length; i++) {
		if (navrow[i].href.match(butname)) {return (navrow[i].href);}
		else {} //do nothing
	}
}
	
// ***********************************************************
function chgAuLink() {
// Changes the default search URL on Author names in the bib display
// to a basic author browse, rather than III's wierd URL.
var bibD = getElementsByClassName(document, "table", "bibDetail");
var auHref = new RegExp("\/search(.spi)?\/a");
for (var i=0; i<bibD.length; i++) {
	var aTag = bibD[i].getElementsByTagName("a");
	for (var j=0; j<aTag.length; j++) {
		if (aTag.length == 0) {}
		else if (aTag[j].href.search(auHref) == -1) {}
		else {
			var auSrch = aTag[j].href.lastIndexOf("/a");
			var revSrch = aTag[j].href.slice(0,auSrch);
			var revAu = revSrch.lastIndexOf('/a');
			var newSrch = revSrch.slice(0,revAu) + "/a?SEARCH=" + revSrch.slice(revAu + 2);
			aTag[j].href = newSrch;
		}
	}
}
} // end chgAuLink()

// ************************************************************
function langSwitch(theLink,toLang) {
// Takes the current URL and toggles it between English & Spanish.
var urlStr = new String(document.location);
var isspan = isSpanish();
var accI = unescape('%ED');
var accA = unescape('%E1');
	if (isspan == "Spanish") { // we're on a Spanish page;
		if (toLang == "Spanish") {}
		else if (toLang == "English") {
			if (urlStr.indexOf('*spi') != -1) {
			theLink.href = urlStr.replace(/\*spi(.*)/,"$1");
			}
			else if (urlStr.indexOf('_spi.html') != -1) {
			theLink.href = urlStr.replace(/_spi/,"");
			}
		}
	}
	else { // we're not on a Spanish page;
		var urlKey = urlStr.indexOf('.html');
		var spiURL;
		if (toLang == "Spanish") {
			if (urlStr.indexOf('/help_') != -1) {
				spiURL = urlStr.replace(/\/help_(.*)\.html/,"/help_$1_spi\.html");
			}
			else if (urlStr.indexOf('/search') != -1 || urlStr.indexOf('/selfreg') != -1 || urlStr.indexOf('/acquire') != -1 || urlStr.indexOf('patroninfo') != -1) {
				spiURL = urlStr.replace(/\/(search|selfreg|acquire|patroninfo)(.*)/,"/$1*spi$2");
			}
			else {
				spiURL = urlStr.substr(0,urlKey) + "_spi.html";
			}
			var ajaxOK = createAjaxObj();
				if (!ajaxOK) { }
				else if (ajaxOK) {
					ajaxOK.open("GET", spiURL);
					ajaxOK.onreadystatechange = function() {
					if (ajaxOK.readyState == 4) {
						if (ajaxOK.status == 200 && ajaxOK.responseText.indexOf('403 Forbidden') == -1) {
						theLink.href = spiURL;
						}
						else if (ajaxOK.responseText.indexOf('403 Forbidden') != -1) {
						alert("Nos sentimos, todav" + accI + "a no hemos traducido esta p" + accA + "gina.");
						theLink.href = "#";
						}
					}
				}
			ajaxOK.send(null);	
			}
		}
		else if (toLang == "English") {}
	}
}

// Used on pverify4_web to indicate nonrequestable items more
// clearly and do some minor formatting of the request table.
function evalMultiReq(lang) {
 	var listerr = getElem('listerrmsg');
	if (listerr) {}
	else {
		var msgdiv = getElem('nonreqMsg');
	 	var tabdiv = getElem('multiReqTable');
		var listrows = tabdiv.getElementsByTagName('tr');
		listrows[1].className = "multiReqHeader";
		if (lang == "Spanish") {
			listrows[1].cells[1].innerHTML = "Solicitar";
			listrows[1].cells[2].innerHTML = "T&#237;tulo";
		}
		else {
			listrows[1].cells[1].innerHTML = "Request";
			listrows[1].cells[2].innerHTML = "Title";
		}
		for (i=2; i<listrows.length; i++) {
			listrows[i].cells[0].style.textAlign = "center";
			var reqlinks = listrows[i].cells[2].getElementsByTagName('a')[0];
			if (!reqlinks || reqlinks.innerHTML.length < 62) {}
			else {
				var ellip = document.createTextNode('...');
				reqlinks.appendChild(ellip);
			}
			var reqcell = listrows[i].cells[1];
			if (reqcell.getElementsByTagName('input').length != 0) {}
			else {
				var errText, statText;
				if (lang == "Spanish") {
					errText = 'Hay ejemplares insolicitables en su lista. Si escoger&#237;a "Solicitar Todos" los ejemplares insolicitables no se incluyeron en su solicitud.';
					statText = 'Insolicitable';
				}
				else {
					errText = '<strong>Note:</strong> There are nonrequestable items in your list. If you select "Request All" the nonrequestable items will not be included in your request.';
					statText = 'Not requestable';
				}
				listrows[i].cells[1].innerHTML = "X";
				listrows[i].cells[1].className = "alertRed strong";
				listrows[i].cells[3].innerHTML = statText;
				listrows[i].cells[3].className = "alertRed";
				msgdiv.innerHTML = errText;
				msgdiv.className = "";
			}
		}
	}
 }

// ***********************************************************
// Converts the Adopt A Book form entries into a single value
// to be placed in the comments input.
function processAdopt() {
var url = new String(document.location);
	if (url.search(/adopt=/) == -1) { return; }
var adoptForm = document.finestable;
var adoptComm = adoptForm.comments;
var msg_v = adoptForm.adopt_honoree.value;
var sub_v = adoptForm.adopt_sub.value;
var honornm_v = adoptForm.honor_name.value;
var honorad1_v = adoptForm.honor_addr1.value;
var honorad2_v = adoptForm.honor_addr2.value;
var honorcit_v = adoptForm.honor_city.value;
var honorst_v = adoptForm.honor_state.value;
var honorzip_v = adoptForm.honor_zip.value;
var givenm_v = adoptForm.ccname.value;
var givead1_v = adoptForm.address1.value;
var givead2_v = adoptForm.address2.value;
var givecit_v = adoptForm.city.value;
var givest_v = adoptForm.state.value;
var givezip_v = adoptForm.zip.value;
var giveph_v = adoptForm.phone.value;
var giveeml_v = adoptForm.emailaddr.value;
var amt_v = adoptForm.amount.value;
//	for (var i=0; i<adoptForm.amount.length; i++) {
//		if (adoptForm.amount[i].checked) {
//			var amt_v = adoptForm.amount[i].value;
//		}
//	}
	for (var j=0; j<adoptForm.adopt_type.length; j++) {
		if (adoptForm.adopt_type[j].checked) {
			var type_v = adoptForm.adopt_type[j].value;
		}
	}
	if (honorad2_v != "") { honorad2_v = honorad2_v + "<br /> "; }
	if (givead2_v != "") { givead2_v = givead2_v + "<br /> "; }
//	if (remind_v == true) { remind_v = "Yes"; }
//	else { remind_v = "No"; }
adoptComm.value = "Amount: $" + amt_v + " <br /> " +
"Type: " + type_v + "<br />" +
"Name and Special Message: " + msg_v + " <br /> " +
"Subject: " + sub_v + " <br /><br /> " +
"Send notification to:<br />  " + honornm_v + "<br />  " + honorad1_v + "<br />  " + honorad2_v + honorcit_v + ", " + honorst_v + " " + honorzip_v + " <br /><br /> " +
"Adopt A Book is given by:<br />  " + givenm_v + "<br />  " + givead1_v + "<br />  " + givead2_v + givecit_v + ", " + givest_v + " " + givezip_v + "<br />  " + giveph_v + "<br />  " + giveeml_v + " <br /> ";
//"Remind me of my gift next year: " + remind_v;
}	

// ***********************************************************
// selfreg scripts
// Javascript form validation routines. Author: Stephen Poley
// All validation routines return true if executed by an older browser:
// in this case validation must be left to the server.
// ----------------------------------------------------------------------

var nbsp = 160;    // non-breaking space char
var node_text = 3; // DOM text node-type
var emptyString = /^\s*$/
var glb_vfld;      // retain vfld for timer thread

// -----------------------------------------
//                  strTrim
// Trim leading/trailing whitespace off string
// -----------------------------------------
function strTrim(str)
{
  return str.replace(/^\s+|\s+$/g, '')
};
function allTrim(str) {
	return str.replace(/\s/g,'');
}

// -----------------------------------------
//                  setfocus
// Delayed focus setting to get around IE bug
// -----------------------------------------
function setFocusDelayed()
{
  glb_vfld.focus()
}

function setfocus(vfld)
{
  // save vfld in global variable so value retained when routine exits
  glb_vfld = vfld;
  setTimeout( 'setFocusDelayed()', 100 );
}

// -----------------------------------------
//                  msg
// Display warn/error message in HTML element
// commonCheck routine must have previously been called
// -----------------------------------------
function msg(fld,     // id of element to display message in
             msgtype, // class to give element ("warn" or "errormessage")
             message) // string to display
{
  // setting an empty string can give problems if later set to a 
  // non-empty string, so ensure a space present. (For Mozilla and Opera one could 
  // simply use a space, but IE demands something more, like a non-breaking space.)
  var dispmessage;
  if (emptyString.test(message)) 
    dispmessage = String.fromCharCode(nbsp);    
  else  
    dispmessage = message;

  var elem = document.getElementById(fld);
  elem.firstChild.nodeValue = dispmessage;  
  
  if (elem.className !== null) { elem.className += " " + msgtype; }
  else { elem.className = msgtype; } // set the CSS class to adjust appearance of message
};

// -----------------------------------------
//            commonCheck
// Common code for all validation routines to:
// (a) check for older / less-equipped browsers
// (b) check if empty fields are required
// Returns true (validation passed), 
//         false (validation failed) or 
//         proceed (don't know yet)
// -----------------------------------------
var proceed = 2;  

function commonCheck    (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
	var thisurl = new String(document.location);
  if (!document.getElementById) 
    return true;  // not available on this browser - leave validation to the server
  var elem = document.getElementById(ifld);
  if (!elem.firstChild)
    return true;  // not available on this browser 
  if (elem.firstChild.nodeType != node_text)
    return true;  // ifld is wrong type of node  

  if (emptyString.test(vfld.value) || vfld.value === null) {
    if (reqd) {
	  if (thisurl.indexOf('*spi') != -1) { msg (ifld, "errormessage", "Esto es necesario."); }
	  else { msg (ifld, "errormessage", "This field is required."); }
      setfocus(vfld);
      return false;
    }
    else {
      msg (ifld, "warn", "");   // OK
      return true;  
    }
  }
  return proceed;
};

// -----------------------------------------
//            validatePresent
// Validate if something has been entered
// Returns true if so 
// -----------------------------------------
function validatePresent(vfld,   // element to be validated
                         ifld )  // id of element to receive info/error msg
{
  var stat = commonCheck (vfld, ifld, true);
  if (stat != proceed) { return stat; }
  else {
	  msg (ifld, "warn", "");  
	  return true;
  }
};

// -----------------------------------------
//               stripAddr
// Strip the data from City, State and ZIP
// fields, create a string, and enter it into
// the full_aaddress field.
// -----------------------------------------
function stripAddr() {
var doc = document.selfRegForm;
var getCity = doc.city.value;
var getState = doc.state.value;
var getZIP = doc.zip.value;
var addrString = getCity + ", " + getState + " " + getZIP;
document.selfRegForm.full_aaddress[1].value = addrString;
}

// -----------------------------------------
//             validateState
// Validate the 2-letter state code (must be
// capitalized)
// -----------------------------------------
function validateState (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = strTrim(vfld.value);  // value of field with whitespace trimmed off
  var stateAddr = /^CO$/
  if (!stateAddr.test(tfld)) {
    msg (ifld, "errormessage", "You must live in Colorado to use this service.");
    setfocus(vfld);
    return false;

  }
  else { msg (ifld, "warn", ""); }
return true;
};

// -----------------------------------------
//             validateZip
// Validate the 5-digit zip code
// -----------------------------------------
function validateZip (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = strTrim(vfld.value);  // value of field with whitespace trimmed off
  var zip = /^8[0-1][0-9]{3}$/
  if (!zip.test(tfld)) {
    msg (ifld, "errormessage", "Please enter a valid 5-digit Colorado ZIP code.");
    setfocus(vfld);
    return false;
  }
  else { msg (ifld, "warn", ""); }
  return true;
};

// -----------------------------------------
//            validateTelnr
// Validate telephone number
// Returns true if so (and also if could not be executed because of old browser)
// Requires a format of xxx-xxx-xxxx
// -----------------------------------------
function validateTelnr  (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = strTrim(vfld.value);  // value of field with whitespace trimmed off
  var telnr = /^#*\d{3}\-\d{3}\-\d{4}$/
  if (!telnr.test(tfld)) {
    msg (ifld, "errormessage", "This is not a valid telephone number. Please use the format xxx-xxx-xxxx.");
    setfocus(vfld);
    return false;
  }
  else { msg (ifld, "warn", ""); }
  return true;
};

// -----------------------------------------
//            validateBday
// Validate birthdate
// Returns true if so (and also if could not be executed because of old browser)
// Requires a format of mmddyyyy
// -----------------------------------------
function validateBday  (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = strTrim(vfld.value);  // value of field with whitespace trimmed off
  var bday = /^[0-1][0-9][0-3][0-9][1-2][0,9][0-9][0-9]$/
  if (!bday.test(tfld)) {
    msg (ifld, "errormessage", "This is not a valid birthdate. Please fill in all fields.");
    setfocus(vfld);
    return false;
  }
  else { msg(ifld, "warn", ""); }
  return true;
};

// -----------------------------------------
//            swapBday
// Convert dropdown menu values into a numeric string;
// Transfer that string to "F051birthdate" input for validation and submission.
// -----------------------------------------
function swapBday() {
  var doc = document.selfRegForm;
  var moSel = doc.ddMonth[doc.ddMonth.selectedIndex].value;
  var dySel = doc.ddDay[doc.ddDay.selectedIndex].value;
  var yrSel = doc.ddYear[doc.ddYear.selectedIndex].value;
  var bdayString = moSel + dySel + yrSel;
  document.selfRegForm.F051birthdate.value = bdayString;
};

// -----------------------------------------
//            validatePcode
// Validate pcode1
// Returns true if so (and also if could not be executed because of old browser)
// Requires a selection of Male or Female from the dropdown
// -----------------------------------------
function validatePcode  (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  var fldOpt = vfld.options;
  if (stat != proceed) return stat;
 
  if (fldOpt[fldOpt.selectedIndex].value == "-") {
    msg (ifld, "errormessage", "Please make a selection.");
    setfocus(vfld);
    return false;
  }
  else { msg(ifld, "warn", ""); }
  return true;
};

// -----------------------------------------
//               validateEmail
// Validate e-mail address
// Returns true if so (and also if could not be executed because of old browser)
// -----------------------------------------
function validateEmail  (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  vfld.value = vfld.value.replace(/\s/g,'');
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = strTrim(vfld.value);
  var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/
  if (!email.test(tfld)) {
    msg (ifld, "errormessage", "This is not a valid e-mail address.");
    setfocus(vfld);
    return false;
  }

  var email2 = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/
  if (!email2.test(tfld)) 
    msg (ifld, "warn", "Unusual e-mail address - please verify.");
  else
    msg (ifld, "warn", "");
  return true;
};

// -----------------------------------------
//            validateBarcode
// Validate patron barcode number
// Returns true if so (and also if could not be executed because of old browser)
// Requires a 14-digit number
// -----------------------------------------
function validateBarcode  (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = strTrim(vfld.value);  // value of field with whitespace trimmed off
  var barcode = /^\d{14}$/
  if (!barcode.test(tfld)) {
    msg (ifld, "errormessage", "Invalid library card number. Please re-enter.");
    setfocus(vfld);
    return false;
  }
  else {
  	msg (ifld, "warn", "");
  }
  return true;
} // end selfreg scripts

//*************************** Bib Display *********************************/
// Taken from bibdisplay.js, which is no longer used.
function contentDisplay(id) {
	document.getElementById("copySection").style.display = 'none';
	document.getElementById("similarSection").style.display = 'none';
	document.getElementById("fullSection").style.display = 'none';
	document.getElementById(id).style.display = 'block';
}

function bibTabChange(el) {
	menu = getElem('srchMenu');
	list = menu.getElementsByTagName('li');
	for (var i=0; i<list.length; i++) {
		list[i].className = "";
	}
	el.parentNode.className = "active";
}
//*************************** End Bib Display ******************************/

// *************************************
// showNav - can be attached to onclick event to unhide the
// navigation menu on catalog pages.
// As of 11/07, still needs fine-tuning.
function showNav() {
var headtags = document.getElementsByTagName('head');
var theHead;
	if (headtags.length > 1) {
		theHead = headtags[headtags.length - 1];
	}
	else { theHead = headtags[0]; }
var newStyle = document.createElement('link');
newStyle.setAttribute('href','/screens/show_menu.css');
newStyle.setAttribute('type','text/css');
newStyle.setAttribute('rel','stylesheet');
var iiiStyle = getElem('iii_stylesheet');
	if (!iiiStyle) {}
var navmenu = getElementsByClassName(document, 'div', 'menu');
var navShown = (navmenu[0].style.display != "block")? "none" : "block";
	if (navShown == "block") {}
	else {
		theHead.appendChild(newStyle);
	}
}

//*********************************
// Creates a printer-friendly patfunc list.
function print_patfunc(clname) {
// 1. To automatically invoke the printer dialog, set to 'true'. Otherwise, set 'false'.
var autoprint = "false";
// 2. Give the 'Print' and 'Regular Display' links an optional className from your stylesheet.
var butClass = "patFuncPrintButs";
// 3. Give the div that holds the 'Print' and 'Regular Display' buttons an optional className.
var divClass = "topDiv";
// 4. If you don't want to print the 'Mark' column of checkboxes, set to 'true'.
var hideCheckbox = "true";
// 5. Optional classNames you would also like to hide from printing (separate with a comma, no spaces - e.g., "header,footer"):
var hideClasses = "toplogoRight";

// NO NEED TO EDIT BEYOND HERE
// Create the 'hiding' style for the print preview display.
var pHead = document.getElementsByTagName('head');
var lastHead;
	if (pHead.length > 1) { lastHead = pHead[pHead.length - 1]; }
	else { lastHead = pHead[0]; }
var cssStr = '.' + clname + ' {display:none;}';
var style = document.createElement('style');
style.setAttribute('type','text/css');
	if (style.styleSheet) {// IE-friendly
		style.styleSheet.cssText = cssStr;
	} 
	else {// w3c
		var cssText = document.createTextNode(cssStr);
		style.appendChild(cssText);
	}
lastHead.appendChild(style);

// Aside from the patfunc table, hide as many elements as possible.
var bod = getElem('loggedin');
var alltags = bod.getElementsByTagName('*');
var pfunc = getElementsByClassName(document, 'div', 'patFuncArea')[0];
// If function buttons are default inputs, hide them;
var pforms = pfunc.getElementsByTagName('input');
	for (var f=0; f<pforms.length; f++) {
		if (pforms[f].type == 'submit') { pforms[f].style.display = "none"; }
		else {}
	}
// If function buttons are images, hide them;
var pimgs = pfunc.getElementsByTagName('img');
	for (var g=0; g<pimgs.length; g++) { 
		if (pimgs[g].src.indexOf('rate_my.gif') == -1) { pimgs[g].style.display = "none"; }
	}
// Get all tags that appear before the 'patFuncArea' div and hide them;
for (var i=0; i<alltags.length; i++) { 
	if (alltags[i].className != 'patFuncArea') {
		if (alltags[i].className === null) { alltags[i].className = clname; }
		else { alltags[i].className += ' ' + clname; }
	}
	if (alltags[i].className == 'patFuncArea') {
		break;
	}
}
// If there are additional classes from the hideClasses variable, find and hide them;
if (hideClasses != "") {
	hClass = hideClasses.split(',');
	for (var m=0; m<hClass.length; m++) {
		var getClasses = getElementsByClassName(document,'*',hClass[m]);
		for (var n=0; n<getClasses.length; n++) {
			if (getClasses.length == 0) {}
			else { getClasses[n].style.display = "none"; }
		}
	}
}
// Create the div that will hold the 'Print' and 'Regular Display' links.
var utilDiv = document.createElement('div');
utilDiv.className = divClass;
var newcl = document.createElement('a');
newcl.setAttribute('href','#');
newcl.setAttribute('onclick','window.location.reload(); return false;');
newcl.className = butClass;
var clText = document.createTextNode('Regular Display');
newcl.appendChild(clText);
utilDiv.appendChild(newcl);
bod.insertBefore(utilDiv,pfunc);

// If the hideCheckbox variable is set to 'true', hide the Mark column.
if (hideCheckbox == 'true') {
var pUrl = new String(document.location);
var funcHead = getElementsByClassName(document,'tr','patFuncHeaders')[0];
var funcRow = getElementsByClassName(document,'tr','patFuncEntry');
	if (funcHead && pUrl.indexOf('illreqs') == -1) { funcHead.cells[0].style.display = "none"; }
for (var j=0; j<funcRow.length; j++) { 
	if (pUrl.indexOf('illreqs') == -1) { funcRow[j].cells[0].style.display = "none"; }	
	if (pUrl.indexOf('readinghistory') != -1) {
		var ti = funcRow[j].cells[1].getElementsByTagName('a')[0];
		if (!ti) {}
		else {
			var tiSub = ti.innerHTML;
			if (tiSub.indexOf(' / ') == -1) {}
			else {
				ti.innerHTML = tiSub.slice(0,tiSub.indexOf(' / '));
			}
		}
	}
	if (pUrl.indexOf('getpsearches') != -1) {
		funcHead.style.display = "none";
		funcRow[j].cells[1].style.display = "none";
	}
}
}
// If the autoprint variable is true, invoke the print dialog; otherwise, make a 'Print' link.
if (autoprint == 'false') {
	var newpr = document.createElement('a');
	var prText = document.createTextNode('Print this list');
	newpr.setAttribute('href','#');
	newpr.setAttribute('onclick','window.print(); return false;');
	newpr.setAttribute('class',butClass);
	newpr.appendChild(prText);
	utilDiv.appendChild(newpr);
}
else {}
}// end print_patfunc();

function modLightbox(url,liteID,fadeID) {
//var bod = document.body;
$("body").css({height:"100%"});
document.searchtool.style.visibility = "hidden";
var lite = document.createElement('div');
var fade = document.createElement('div');
//bod.style.height = "100%";
lite.id = liteID;
fade.id = fadeID;
lite.className = "lite_content";
fade.className = "fade_overlay";
$("body").append(lite);
$("body").append(fade);
lite.style.display = "block";
fade.style.display = "block";
var modload = loadSnip(url,'limitSort',liteID);
}

//* Used on the srchmod.html page */
function shortSel() {
var sels = [];
sels[0] = document.getElementsByName('W')[0];
sels[1] = document.getElementsByName('M')[0];
sels[2] = document.getElementsByName('L')[0];
var i = sels.length;
while (i--) { sels[i].size = 4; }
}

function loadSnip(snipSrc, srcWrap, divID) {
var ajaxOK = createAjaxObj();
	if (!ajaxOK) {}
	else if (ajaxOK) {
		var obj = document.getElementById(divID);
		ajaxOK.open("GET", snipSrc);
		
		ajaxOK.onreadystatechange = function() {
			if (ajaxOK.readyState == 4 &&
			ajaxOK.status == 200) {
				var doc = ajaxOK.responseText;
				if (srcWrap != "") {
					var snipStart = doc.indexOf("<!-- Start " + srcWrap);
					var snipEnd = doc.indexOf("<!-- End " + srcWrap);
					var snipDiv = doc.slice(snipStart,snipEnd);
					obj.innerHTML += snipDiv;
				}
				else { obj.innerHTML = doc; }
			}
		}
		ajaxOK.send(null);	
	}
}
