/**
 * @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;
}

// This is the get_cookie script;
function Get_Cookie(name) {
    var start = document.cookie.indexOf(name+"=");
    var len = start+(name.length + 1);
    if ((!start) && (name != document.cookie.substring(0,name.length))) return null;
    if (start == -1) return null;
    var end = document.cookie.indexOf(";",len);
    if (end == -1) end = document.cookie.length;
    return unescape(document.cookie.substring(len,end));
}

// Determines whether or not user is logged in (NOT part of a function);
var logged_in = false;
if (Get_Cookie('PAT_LOGGED_IN')) { logged_in = 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 (isSpanish) {
			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();
}

// Looks for an element on the page with a specific ID, returns boolean value;
function has(elID) {
return ($("#" + elID).is('*'));
}


// 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 moveNewSrch_OLD() {
// Moves the 'New Search' button, which is hidden in the toplogo, to the first
// button position of navigationRow in briefcit and bib_display.
// Replaced 5/12/09 with jquery function.
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;
	else {
		var newbtn = $("#startoverBtn").html();
		$(".navigationRow").children("form").prepend(newbtn);
	}
/**	else if (has("#briefcit_table")==true) { //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;}
}

/***********************
 * insert_rr_terms()
 * Inserts the search terms in the RightResult header next to the relevancy ranking.
***********************/
function insert_rr_terms() {
// Assign a className to style the user's terms in the header;
var rrClass = "strong-em";

// If you also want to put the user's terms in the browser title bar, change these 3 variables;
var chgTitle = 1; // Off by default; change to '1' to turn it on;
var lib_or_cat_name = "Aurora Public Library - search results for "; // This is your library or catalog name, and should match whatever currently appears in your browser's title bar;
var title_suff = "" // This text will appear in the title bar after the user's terms;

// No need to edit beyond here;
if (!document.getElementsByName('searcharg')[0]) {return;}
var rrForm = document.getElementsByName('searcharg')[0];
var termArr = new Array("rrTerm1","rrTerm2","rrTerm3","rrTerm4","rrTerm5");
	for (var i=0; i<3; i++) {
		var termID = document.getElementById(termArr[i]);
		if (!termID) {}
		else {
			termID.innerHTML = rrForm.value;
			termID.className = rrClass;
		}
	}
	for (var i=3; i<termArr.length; i++) {
		var termID = document.getElementById(termArr[i]);
		if (!termID) {}
		else {
			newval = rrForm.value.replace(/^\s+|\s+$/g,"");
			newval = newval.replace(/\s/g," AND ");
			termID.innerHTML = newval;
			termID.className = rrClass;
		}
	}
if (chgTitle == 1) { document.title = lib_or_cat_name + "'" + rrForm.value + "'" + title_suff; }
}
// end insert_rr_terms();

// ***********************************************************
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 oclc = "http://0-firstsearch.oclc.org.odyssey.aurora.lib.co.us/fsip?dbname=WorldCat;done=referer";
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;
	oclc = "http://www.worldcat.org/search?q=ti%3A" + keyterms;
	break;
	case "a":
	acquire = "/acquire?author=" + keyterms;
	oclc = "http://www.worldcat.org/search?q=au%3A" + keyterms;
	break;
	case "i":
	shop = "https://apl.mylibrarybookstore.com/MLB/actions/searchHandler.do?key=" + keyterms + "&amp;NextPage=bookDetails&amp;parentNum=11684";
	oclc = "http://www.worldcat.org/isbn/" + keyterms;
	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 oclcText = "<a href='" + oclc + "' class='block bold' title='Searching WorldCat'>Searching for \"" + fieldterm + "\" in WorldCat</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 + wcat;
		}
	}
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 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.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);
			}
			if (jackImg[0].src.indexOf('Product=&') != -1) {
				jackImg[0].src = '/screens/images/imgmissing.gif';
			}
		}
	}
	}
}

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 (isSpanish) { 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 navrow = $("."+locID+" 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 = $("table.bibDetail")
var auHref = new RegExp("\/search(~S[0-9](.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()

// ************************************************************

// Used on pverify4_web to indicate nonrequestable items more
// clearly and do some minor formatting of the request table.
function evalMultiReq(lang) {
	if ($("#listerrmsg").length > 0) {}
	else {
//		var msgdiv = getElem('nonreqMsg');
//	 	var tabdiv = getElem('multiReqTable');
		var listrows = $("#multiReqTable tr");
		var row1 = $("#multiReqTable tr:eq(1)");
		$("#multiReqTable table").addClass("multReq");
		$(row1).addClass("multiReqHeader");
		$(row1).children("td:eq(1)").html("Request");
		$(row1).children("td:eq(2)").html("Title");
		if (isSpanish) {
			$(row1).children("td:eq(1)").html("Solicitar");
			$(row1).children("td:eq(2)").html("T&#237;tulo");
		}
		$(".multReq tr td[align='right']").attr('align','center');
		for (i=2; i<listrows.length; i++) {
			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;
				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';
				if (isSpanish) {
					errText = 'Hay ejemplares insolicitables en su lista. Si escoger&#237;a "Solicitar Todos" los ejemplares insolicitables no se incluyeron en su solicitud.';
					statText = 'Insolicitable';
				}
				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";
				$("#nonreqMsg").html(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;
}	

//*********************** Bib Display Functions **************************/
// We don't use III's bibdisplay.js.
function contentDisplay(el,id) {
	$("#copySection, #similarSection, #fullSection").css('display','none');
	$(id).css('display','block');
	$("#srchMenu li").removeClass('active');
	$(el).parent().addClass('active');
	return false;
}

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()
//************************ End Bib Display Functions **********************/

//*********************************
// 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();

// The loadSnip function needs to be replaced by jQuery's load()
// function wherever it occurs. 6/5/09
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);	
	}
}

(function($) {
	$.fn.patronize = function(settings) {
		settings = $.extend({
			// the className that is attached to each of your briefcit rows;
			briefcitClass: 'briefcitRow',
			// the tag type that loads when a patron is logged in;
			loggedInElement: 'div',
			// the ID of the above tag type;
			loggedInID: 'loggedin',
			// the ID attached to your 'Patron Record' button;
			buttonID: 'patRecBtn',
			// show if an item is currently checked out to this patron;
			showCheckout: true,
			// show if an item is currently on hold for this patron;
			showHold: true,
			// show if an item is in this patron's Reading History;
			showHistory: true,
			// the className of the element wrapping your <!--{fieldset:Fb081}--> token in briefcit.html;
			recordNumberClass: 'bib-record-num',
			// include a link to this patron's checkouts, holds, history, etc.;
			showAccountLink: true,
			// the className of the element the checkout messages will appear in;
			chkContainerClass: 'my-checkout',
			// the className of the element the holds messages will appear in;
			holdContainerClass: 'my-holds',
			// the className of the element the history messages will appear in;
			histContainerClass: 'my-history'
		}, settings);
		alert("hi")
		var bnum, bstatus;
		// get the patron's id
		var pinfo = $("#" + buttonID).parent().attr('href');
		var pbase = pinfo.replace(/(\/patroninfo([^\/])*\/[0-9]{7}\/).*/,'$1'); // sets the base account URL;
		var pckout = pbase + "items/"; // sets the Checkouts URL;
		var pren = pckout + "renewsome=TRUE&"; // sets the base renewal URL;
		var phold = pbase + "holds/"; // sets the Holds URL;
		var phist = pbase + "readinghistory/"; // sets the Reading History URL;
		return $(this).each(function(){
		if(!$(loggedInElement + "#" + loggedInID).length) { return; }
		// load checkout detail from patron record & grab the bib number and due date;
		if (showCheckout) {
			$("body").append("<div id=\"putCheckouts\" class=\"hidden\"></div>");
//			$(this).after("<div id=\"putCheckouts\" class=\"hidden\"></div>");
			$("#putCheckouts").load(pckout + " .patFuncEntry .patFuncTitle a, .patFuncEntry .patFuncStatus",function(){
				$("#putCheckouts a").each(function(i, el){
					bnum = $(el).attr('href').replace(/[^&]*&([0-9]{7})/,'$1');
					bstatus = $(el).next("td").html();
					bstatus = bstatus.replace(/DUE ([0-9]{2}\-[0-9]{2}\-[0-9]{2}).*/,'$1');
					$("#putCheckouts").append("<span class=\"numonly\"><span class=\"bnum\">" + bnum + "</span><span class=\"bstatus\">" + bstatus + "</span></span>");
					$("." + recordNumberClass).each(function(e){
						var ih = this.innerHTML.replace(/\s/g,'')
						if (bnum == ih) { $("." + chkContainerClass + ":eq(" + e + ")").html("This item is currently checked out to you. Due: " + bstatus).show(); }
					});
				});
			});
		}

		// load holds detail from patron record & grab bib number and hold position;
		if (showHolds) {
//			$("body").append("<div id=\"putHolds\" class=\"hidden\"></div>");
			$(this).after("<div id=\"putHolds\" class=\"hidden\"></div>");
			$("#putHolds").load(phold + " .patFuncEntry .patFuncTitle a, .patFuncEntry .patFuncStatus",function(){
				$("#putHolds a").each(function(i, el){
					bnum = $(el).attr('href').replace(/[^&]*&([0-9]{7})/,'$1');
					bstatus = $(el).next("td").html();
					$("#putHolds").append("<span class=\"numonly\"><span class=\"bnum\">" + bnum + "</span><span class=\"bstatus\">" + bstatus + "</span></span>");
					$("." + recordNumberClass).each(function(e){
						var ih = this.innerHTML.replace(/\s/g,'')
						if (bnum == ih) { $("." + holdContainerClass + ":eq(" + e + ")").html("You have placed this item on hold: " + bstatus).show(); }
					});
				});
			});
		}
		// load reading history detail from patron record and grab bib number and date;
		if (showHistory){
//			$("body").append("<div id=\"putHistory\" class=\"hidden\"></div>");
			$(this).after("<div id=\"putHistory\" class=\"hidden\"></div>");
			$("#putHistory").load(phist + " .patFuncEntry .patFuncTitle a, .patFuncEntry .patFuncDate",function(){
				$("#putHistory a").each(function(i, el){
					bnum = $(el).attr('href').replace(/[^=]*=b([0-9]{7}).*/,'$1');
					bstatus = $(el).next("td").html();
					$("#putHistory").append("<span class=\"numonly\"><span class=\"bnum\">" + bnum + "</span><span class=\"bstatus\">" + bstatus + "</span></span>");
					$("." + recordNumberClass).each(function(e){
						var ih = this.innerHTML.replace(/\s/g,'')
						if (bnum == ih) { $("." + histContainerClass + ":eq(" + e + ")").html("This item is in your Reading History. You checked it out on " + bstatus + ".").show(); }
					});
				});
			});
		}	
		});
	}
})(jQuery);



$(function(){
// The maximum number of item rows you want to show on briefcit.html; 
// Set to 0 to replace the items table with a link;
// Set to "all" (not recommended) to display all items;
var maxItems = 6;
// The className attached to your briefcit items table ("bibItems" is the default, but that may change);
var bibTableClass = "bibItems";
// The className to give the 'more copies' link (for styling purposes);
var moreClass = "moreCopies";
// The text of the 'more copies' link;
var moreText = "View all copies";

$(".briefcitRow").each(function(n){
	// Get the bib record number and strip out extra spaces;
	var recnum = $(".bib-record-num:eq(" + n + ")").html();
	recnum = recnum.replace(/\s/g,'');
	// Set the base URL;
	var getUrl = loc.replace(/^([^\?]+)\?.*$/,'$1');
	if (getUrl.charAt(getUrl.length - 1) == "/") {
		getUrl = getUrl.slice(0,getUrl.length - 1);
	}
	// Create the URL to the Holdings display;
	var allItems = getUrl + "/.b" + recnum + "/.b" + recnum + "/1,1,1,B/holdings~" + recnum;
	// Find briefcit rows that have more than 3 attached items;
	if (maxItems == 0) {
		$("." + bibTableClass).replaceWith("<a href=\"" + allItems + "\" class=\"" + moreClass + "\" title=\"" + moreText + "\">" + moreText + "</a>");
		$("em:contains('There are additional')").remove();
		return;
	}
	// Define variable for maxItems (ie, all rows vs. some rows);
	var itemRows = (maxItems == "all") ? " tr" : " tr:lt(" + (maxItems + 1) + ")";
	if ($(".briefcitRow:eq(" + n + ") table").html().match(/There are additional.*/)) {
		$("table." + bibTableClass + ":eq(" + n + ")")
			// Create a new table to hold the full Holdings display;
			.after("<table class=\"injectItems\"></table>")
			.next(".injectItems").hide() // temporarily hide our new table;
			// Get the Holdings display rows (up to maxItems) and load them into our new table;
			.load(allItems + itemRows,function(data){
				$(this).prev("table").remove(); // delete the original items table;
				$(".injectItems").show() // show the new table;
				// Replace the "View additional..." text message with a link to the full Holdings display;
				$(this).next("table").replaceWith('<a href="' + allItems + '" class="' + moreClass + '" title="' + moreText + '">' + moreText + '</a>');					
			});
	}
});
$(".injectItems").addClass(bibTableClass);


//$("#briefcit_table").patronize();
});