function openUrlWindow(type,id) {
	var page = "/common/openUrl.jsp?type=" + type + "&id=" + id;
	var windowPrefs = "toolbar=no,directories=no,status=yes,menubar=yes,scrollbars=yes,resizable=yes,width=500,height=320";
	var urlWindow = window.open(page, "openUrl", windowPrefs);
	urlWindow.focus();
}

function saveToMyArchive() {
	document.forms['StorableObjectForm'].submit();
}

function deleteAll(msg, url) {
	if (confirm(msg))
		window.location = url;
}

function endSession(a){if ( confirm('Are you sure you want to end your session?') ) location=a;}

/*///////// NEW DOM FUNCTIONS START HERE //////////*/

/* Add Event function taken from http://www.dustindiaz.com/rock-solid-addevent/ */

function addEvent( obj, type, fn ) {
	if (obj.addEventListener) {
		obj.addEventListener( type, fn, false );
		EventCache.add(obj, type, fn);
	}
	else if (obj.attachEvent) {
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
		EventCache.add(obj, type, fn);
	}
	else {
		obj["on"+type] = obj["e"+type+fn];
	}
}

/* add Array.push if needed (ie5) */
if(Array.prototype.push == null){
	Array.prototype.push = function(){
		for(var i = 0; i < arguments.length; i++){
			this[this.length] = arguments[i];
		};
		return this.length;
	};
};

/*	EventCache Version 1.0
	Copyright 2005 Mark Wubben

	Provides a way for automagically removing events from nodes and thus preventing memory leakage.
	See <http://novemberborn.net/javascript/event-cache> for more information.
	
	This software is licensed under the CC-GNU LGPL <http://creativecommons.org/licenses/LGPL/2.1/>
*/
	
var EventCache = function(){
	var listEvents = [];
	return {
		listEvents : listEvents,
		add : function(node, sEventName, fHandler){
			listEvents.push(arguments);
		},
		flush : function(){
			var i, item;
			for(i = listEvents.length - 1; i >= 0; i = i - 1){
				item = listEvents[i];
				if(item[0].removeEventListener){
					item[0].removeEventListener(item[1], item[2], item[3]);
				};
				if(item[1].substring(0, 2) != "on"){
					item[1] = "on" + item[1];
				};
				if(item[0].detachEvent){
					item[0].detachEvent(item[1], item[2]);
				};
				item[0][item[1]] = null;
			};
		}
	};
}();

// Show/hide search options for books and periodicals on search page

function searchShowHideOptions(){
	if(!document.getElementsByTagName) return false;
	if (!document.getElementById('doctype1') && !document.getElementById('doctype2')) { return false };
	allRadio = document.getElementById('doctype1');
	bookRadio = document.getElementById('doctype2');
	periodicalRadio = document.getElementById('doctype3');
	bookOptions = document.getElementById('booksoptions');
	periodicalOptions = document.getElementById('periodicalsoptions');
	allRadio.onclick = function(){
		bookOptions.style.display = '';
		periodicalOptions.style.display = '';
	}
	bookRadio.onclick = function(){
		bookOptions.style.display = '';
		periodicalOptions.style.display = 'none';
	}
	periodicalRadio.onclick = function(){
		bookOptions.style.display = 'none';
		periodicalOptions.style.display = '';
	}
}

// doTheLinks manages all links in document with specific class names - popUpSmall, popUpMedium, popUpLarge & externalLink 

function doTheLinks() {
	if (!document.getElementsByTagName) return false;
	var links = document.getElementsByTagName("a");
	for (var i=0; i < links.length; i++) {
		if (links[i].className && links[i].className.match("popUp")) {
			hideSpan = document.createElement('span');
			hideSpan.className = 'hidden';
			hideText = document.createTextNode(' this link will open in a new window');
			hideSpan.appendChild(hideText);
			links[i].setAttribute("title", "This link will open in a new window");
			links[i].appendChild(hideSpan);
			if(!links[i].ownerDocument) {
				blankImg = document.createElement('img');
				blankImg.src = '/images/blank.gif';
				blankImg.className = 'borderNone';
				links[i].appendChild(blankImg);
			}
		}
		if (links[i].className && links[i].className.match("externalLink")) {
			hideSpan = document.createElement('span');
			hideSpan.className = 'hidden';
			hideText = document.createTextNode(' link to external site, this link will open in a new window');
			hideSpan.appendChild(hideText);
			links[i].setAttribute("title", "Link to external site, this link will open in a new window");
			links[i].appendChild(hideSpan);
			if(!links[i].ownerDocument) {
				blankImg = document.createElement('img');
				blankImg.src = '/images/blank.gif';
				blankImg.className = 'borderNone';
				links[i].appendChild(blankImg);
			}
		}
		// attributes if small popup - named 'popUpSmall'
		if (links[i].className && (' ' + links[i].className + ' ').indexOf(' popUpSmall ') != -1) {
			links[i].onclick = function() {
				window.open(this.href,'PQLGPopUpSmall','width='+(screen.availWidth/2.0)+',height='+(screen.availHeight/2.0)+',resizable=1,toolbar=1,location=0,directories=0,addressbar=1,scrollbars=1,status=0,menubar=1,top=0,left=0,screenX=0,screenY=0');
				return false;
			}
		} 
		// attributes if medium popup - named 'PopUpMedium'
		else if (links[i].className && (' ' + links[i].className + ' ').indexOf(' popUpMedium ') != -1 || (' ' + links[i].className + ' ').indexOf(' externalLink ') != -1) {
			links[i].onclick = function() {
				window.open(this.href,'PQLGPopUpMedium','width='+(screen.availWidth/1.5)+',height='+(screen.availHeight/1.5)+',resizable=1,toolbar=1,location=1,directories=0,addressbar=1,scrollbars=1,status=0,menubar=1,top=0,left=0,screenX=0,screenY=0');
				return false;
			}
		} 
		// attributes if large popup - named 'PopUpLarge'
		else if (links[i].className && (' ' + links[i].className + ' ').indexOf(' popUpLarge ') != -1) {
			links[i].onclick = function() {
				window.open(this.href,'PopUpLarge','width='+(screen.availWidth-90)+',height='+(screen.availHeight-100)+',resizable=1,toolbar=1,location=1,directories=0,addressbar=1,scrollbars=1,status=0,menubar=1,top=0,left=0,screenX=0,screenY=0');
				return false;
			}
		}
	}
}

//Function to append durableURL to H1

function moveDurableURL(){
		if(!document.getElementsByTagName) { return false };
		if (!document.getElementById('durlspan')) { return false };
		var theSpan = document.getElementById('durlspan');
		var theParent = theSpan.parentNode;
		var theHeader = document.getElementsByTagName('h1')[0];
		var spanClone = theSpan.cloneNode(true);
		theHeader.appendChild(spanClone);
//	Can't use this because IE6 sucks, nothing new there
//		theParent.removeChild(theSpan);
		addClassToElem(theSpan,'novis');
}

// Function to resize FT pages to fit images

function resizeThePage(){
	if(!document.getElementById('theMainImage')) return false;
	// Set up refs to the FT img and it's width
	var imageRef = document.getElementById('theMainImage');
	var imageWidth = imageRef.offsetWidth;
	var testWidth;
	// Don't need to resize if width is less than 521
	if(imageWidth < 521 ) return;
	// Set new width and add px for setStyle
	var newWidth = testWidth = imageWidth+210;
	var availBrowser = getBrowserDimensions();
	var availBrowserWidth = availBrowser[0];
	//alert("New width = " + newWidth + ", available browser width = " + availBrowserWidth);
	newWidth += 'px';
	// Set #wrapper width to fit FT img
	setStyle('wrapper','width',newWidth);
	// The following commented out code block is a part solution to the problem of page navigation
	// moving off-screen at the FT level, when an image is resized. Please see /jscript/js-readme.txt
	// for more details . . .
	/*
	var secondnavlist = document.getElementById('secondarynav');
	if(testWidth > availBrowserWidth){
		var widthToUse = (availBrowserWidth - 230);
		widthToUse += 'px';
	} else {
		widthToUse = '100%';
	}
	secondnavlist.style.width = widthToUse;
	*/
}

function toggleTocColour(){
	if(!document.getElementById('pdftoc')) return false;
	var toc = document.getElementById('pdftoc');
	var tocChecks = toc.getElementsByTagName('input');
	for(i=0;i<tocChecks.length;i++){
		tocChecks[i].onclick = function(){
			var gPop = this.parentNode.parentNode.parentNode;
			if(jscss('check',gPop,'tochighlight')){
				jscss('remove',gPop,'tochighlight');
			} else {
				jscss('add',gPop,'tochighlight');
			}
		}
	}
}

function addPeriodicalIssueClicks(){
	if(!document.getElementById('browse')) return false;
	var allH3 = document.getElementById('browse').getElementsByTagName('h3');
	if(allH3.length > 0){
		for(i=0;i<allH3.length;i++){
			if (allH3[i].className && (' ' + allH3[i].className + ' ').indexOf(' periodicalissue ') != -1) {
				allH3[i].onclick = function(){
					var h3Children = this.childNodes;
					for(j=0;j<h3Children.length;j++){
						if(h3Children[j].nodeName == 'A' && h3Children[j].getAttribute('href')){
							var aNumber = j;
						}
					}
					var theUrl = this.childNodes[aNumber].getAttribute('href');
					window.location.href = theUrl;
				}
			}
		}
	}
}

function pushBackToDown(){
	if(!document.getElementById('backtonav')){ return false; }
	var backToNav = document.getElementById('backtonav');
	var btnHeight = backToNav.offsetHeight;
	var btnPos = findPos(backToNav);
	if(btnPos[1]<451){
		backToNav.style.marginTop = (451-btnPos[1]) + 'px';
	}
}

function changeHelpBackToClass(){
	if(!document.getElementById('helpWindow')){ return false; }
	var wrapper = document.getElementById('helpWindow');
	var backTos = getElementsByClass('backtonav',wrapper,'div');
	var lastBackTo = backTos[(backTos.length-1)];
	lastBackTo.id = 'backtonav';
	if (backTos.length > 1){
		for(i=0;i<(backTos.length-1);i++){
			backTos[i].style.backgroundImage = 'none';
			/*backTos[i].style.backgroundColor = 'transparent';*/
		}
	}
}

/* Taken from http://www.quirksmode.org/js/findpos.html with many thanks to PPK */

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

/* Adapted from http://www.quirksmode.org/viewport/compatibility.html with many thanks to PPK */

function getBrowserDimensions(){
	var browserWidth,browserHeight;
	if (self.innerHeight){
		// all except Explorer
		browserWidth = self.innerWidth;
		browserHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight){
		// Explorer 6 Strict Mode
		browserWidth = document.documentElement.clientWidth;
		browserHeight = document.documentElement.clientHeight;
	} else if (document.body){ 
		// other Explorers
		browserWidth = document.body.clientWidth;
		browserHeight = document.body.clientHeight;
	}
	return [browserWidth,browserHeight];
}

/* Taken from http://onlinetools.org/articles/unobtrusivejavascript/cssjsseparation.html

This function takes four parameters:

a defines the action you want the function to perform.
o the object in question.
c1 the name of the first class
c2 the name of the second class

Possible actions are:

swap replaces class c1 with class c2 in object o.
add adds class c1 to the object o.
remove removes class c1 from the object o.
check test if class c1 is already applied to object o and returns true or false.*/ 
	
function jscss(a,o,c1,c2){
  switch (a){
    case 'swap':
      o.className=!jscss('check',o,c1)?o.className.replace(c2,c1):o.className.replace(c1,c2);
    break;
    case 'add':
      if(!jscss('check',o,c1)){o.className+=o.className?' '+c1:c1;}
    break;
    case 'remove':
      var rep=o.className.match(' '+c1)?' '+c1:c1;
      o.className=o.className.replace(rep,'');
    break;
    case 'check':
      return new RegExp('\\b'+c1+'\\b').test(o.className)
    break;
  }
}

// Return array of all elements with a specific class assigned to them

function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

// Change class function to change class of a given element (id)

function changeIdClass(theId, theClass){
	x = document.getElementById(theId);
   	x.className = theClass;
}

// Add a class to a given element

function addClassToElem(element,name) {
  if (!element.className) {
    element.className = name;
  } else {
    element.className+= " ";
    element.className+= name;
  }
}

// Set style function to change style of a given elelement (id)

function setStyle(theId, theStyle, theValue){
	x = document.getElementById(theId);
	x.style[theStyle] = theValue;
}

// Set attribute function to change attribute of a given element (id)

function setAtt(theElement, theAttribute, theValue){
  	x = document.getElementById(theElement);
  	x.setAttribute(theAttribute, theValue);
}

function toggle(obj) {
	var el = document.getElementById(obj);
	el.style.display = (el.style.display != 'none' ? 'none' : '' );
}

function doFocus() {
	window.focus();
}

/* Calls for above functions */

addEvent(window,'load',doTheLinks);
addEvent(window,'load',searchShowHideOptions);
addEvent(window,'load',moveDurableURL);
addEvent(window,'load',resizeThePage);
addEvent(window,'load',changeHelpBackToClass);
addEvent(window,'load',pushBackToDown);
addEvent(window,'load',toggleTocColour);
addEvent(window,'load',addPeriodicalIssueClicks);
addEvent(window,'resize',resizeThePage);
addEvent(window,'unload',EventCache.flush);