function ajaxFunction(){
	var ajaxRequest		// The variable that makes Ajax possible!
	
	try{
		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest()
		if (!ajaxRequest)
			throw new Exception("trying again")
	} catch (e){
		// Internet Explorer Browsers
		try{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP")
			if (!ajaxRequest)
				throw new Exception("trying again")
		} catch (e) {
			try{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP")
				if (!ajaxRequest)
					throw new Exception("trying again")
			} catch (e) {
				return false
			}
		}
	}
	return ajaxRequest
}

var bibhook={
	oldinit:window.onload,
	initfunc:function() {
		bibhook.init()
	},
	init:function() {
		if (typeof this.oldinit == 'function')
			this.oldinit()
		var bibentries=document.getElementById('bibentries')
		if (!bibentries)
			return
		var biballlinks=bibentries.getElementsByTagName('a')
		for (var i=0; i!=biballlinks.length; ++i) {
			var anchor=biballlinks[i]
			if (anchor.className=='bibtexlink') {
				anchor.onclick=function(){
					ajaxRequest=ajaxFunction()
					if (! ajaxRequest)
						return true
					ajaxRequest.attachednode=this
					ajaxRequest.action=function() {
						var newelement=document.createElement('li')
						var bibtexlabel=document.createElement('b')
						bibtexlabel.appendChild(document.createTextNode('BibTeX:'))
						var bibtextext=document.createElement('div')
						//bibtextext.setAttribute("class", "bibtexentry")
						//bibtextext.className="bibtexentry"
						bibtextext.style.marginLeft="2em"
						// Note: This used to use responseText instead of responseXML
						var chunks=this.responseXML.getElementsByTagName('entity').item(0).firstChild.data.split("\n")
						for (var i=0; i!=chunks.length; ++i) {
							if (i!=0)
								bibtextext.appendChild(document.createElement('br'))
							bibtextext.appendChild(document.createTextNode(chunks[i]))
						}
						newelement.appendChild(bibtexlabel)
						newelement.appendChild(bibtextext)
						this.attachednode.parentNode.replaceChild(newelement, this.attachednode)
					}
					ajaxRequest.onreadystatechange=function() {
						if (ajaxRequest.readyState!=4)
							return false
						if (ajaxRequest.status==200) {
							ajaxRequest.action()
						} else {
							document.open(ajaxRequest.attachednode.getAttribute('href'), "_self", false)
						}
					}
					var anchortext=this.getAttribute('href')
					var mark=anchortext.substr(anchortext.indexOf('#')+1)
					ajaxRequest.open("GET", "bibentry.php?"+mark, true)
					ajaxRequest.send(null)
					return false
				}
			}
		}
	}
}
window.onload=bibhook.initfunc
