/**************************************** Background *************************************************/
/*

File name: jsonbioGUID.js

This script was designed by David P. Shorthouse (davidpshorthouse@gmail.com) and acts as a client front-end
to Rod Page's bioGUID's (http://bioguid.info) reference parsing service.
*/
/**************************************** Set-up Instructions ****************************************/
/*
Place this jsonbioGUID.js file in the HEAD portion of your page where jsonbioGUID.js points to a local copy:
<script type="text/javascript" src="jsonbioGUID.js"></script>

Format references on your page as follows:
<p><span class="article">Paik, K. Y. 1957. On fifteen unrecorded spiders from Korea.  <i>Korean J. Biol.</i> <b>2:</b> 43-47.</span></p>
etc.
*/

/*************************************** Span Recognition ******************************************/
// change this if you wish to use a different name for the span (e.g. if you have some css and don't want to change your mark-up)

var bioGUIDspanName = "reference";

/*************************************** Icons *****************************************************/

//Adjust these to suit your local copies. Obtain from http://www.box.net/shared/685i4nyxxj#1:7066241

var bioGUIDiconURL = "http://www.nhm.ac.uk/resources/research-curation/projects/solanaceaesource/global/images/references/";

var bioGUIDicon = new Array();
bioGUIDicon[0] = bioGUIDiconURL + "magnifier.gif"; //search icon
bioGUIDicon[1] = bioGUIDiconURL + "ajax-loader.gif"; //loading or working icon
bioGUIDicon[2] = bioGUIDiconURL + "page_white_acrobat.png"; //pdf icon
bioGUIDicon[3] = bioGUIDiconURL + "world_go.png"; //htm or html icon
bioGUIDicon[4] = bioGUIDiconURL + "world_go.png"; //doi icon
bioGUIDicon[5] = bioGUIDiconURL + "world_go.png"; //handle icon
bioGUIDicon[6] = bioGUIDiconURL + "error.png"; //nothing found
bioGUIDicon[7] = bioGUIDiconURL + "delete.png"; //not understood
bioGUIDicon[8] = bioGUIDiconURL + "clock_red.png "; //timeout
bioGUIDicon[9] = bioGUIDiconURL + "g_scholar.png"; //Google icon

/*************************** bioGUID JSON Reference Parser base URL ************************/ 

var bioGUIDurl = "http://bioguid.info/cgi-bin/parser.cgi?format=json&q=";

/**************************************** Load Initial Icons *******************************/

// function from Dustin Diaz: http://www.dustindiaz.com/getelementsbyclass/

function getElementsByClass(searchClass) {
	var classElements = new Array();
	var els = document.getElementsByTagName('*');
	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;
}

// create icons on page load

var bioGUIDicons = {
	init: function() {
		try {
  			document.execCommand("BackgroundImageCache", false, true);
			} catch(err) {}
		if(typeof window.addEventListener != 'undefined'){
			window.addEventListener('load', this.buildIcons, false);
			}
		else if(typeof document.addEventListener != 'undefined'){
			document.addEventListener('load', this.buildIcons, false);
			}
		else if(typeof window.attachEvent != 'undefined'){
			window.attachEvent('onload', this.buildIcons);
			}
		else{
			if(typeof window.onload == 'function'){
				var existing = onload;
				window.onload = function(){
					existing();
					bioGUIDicons.buildIcons();
				};
				}
			else{
				window.onload = this.buildIcons;
				}
			}

	},
	buildIcons: function () {
		var imgholder = new Image();
		imgholder.src = bioGUIDicon[0];
		var aSpans = getElementsByClass(bioGUIDspanName);
		for(i=0;i<aSpans.length;i++){
			aSpans[i].setAttribute('id','bioGUIDref_'+i);
			var refspan = document.getElementById('bioGUIDref_'+i);
			var parent = refspan.parentNode;
			var res = document.createElement('span');
			res.setAttribute('class','bioGUIDres');
			res.setAttribute('id','bioGUIDres_'+i);
			res.innerHTML = '<a href="#" onclick="bioGUIDOpenURL(\'bioGUIDref_'+i+'\',\'bioGUIDres_'+i+'\');return false"><img id="bioGUIDimg_'+i+'" style="border:0px;height:16px;width:16px" alt="Search!" title="Search!"></a>';
			var appendIcons = parent.appendChild(res);
			document.getElementById('bioGUIDimg_'+i).src=imgholder.src;
		}	
	}
};

/************************************ Build JSON Calls *************************************/ 

var loader = new Object;
loader.callQueue = new Array();

loader.getJSON = function(objReference,objCallBackFnc,jsonUrl)
{
	var _index = loader.callQueue.length;
	loader.callQueue[_index] = new jsHandler(objReference,objCallBackFnc,_index);
    	
	var elem = document.createElement("script");
	elem.id = "script" + _index;
	elem.src = jsonUrl + "&noCacheIE=" + (new Date()).getTime() + "&callback=loader.callQueue[" + _index +"].transferOO";
	document.body.appendChild(elem);
}  
 
function jsHandler()
{
	this.objReference = arguments[0];
	this.callBackFnc = arguments[1];
	this.scriptId = arguments[2];
}

jsHandler.prototype.transferOO = function()
{
	this.objReference.json = arguments[0];
	this.callBackFnc.call(this.objReference,arguments[0]);
	document.body.removeChild(document.getElementById("script" + this.scriptId));
	this.objReference = null;
	this.callBackFnc = null;
}

var bioGUID = new Object();

bioGUID.getDetails = function(ref)
{
	this.apiURL = bioGUIDurl + ref;
}

bioGUID.getDetails.prototype.load = function()
{
	var _ref = this;
	var _url = this.apiURL;
	loader.getJSON(_ref,_ref.displayResult,_url);
	var spinnerTimeout = setTimeout(function(){
		if (document.getElementById(_ref.outputId).getElementsByTagName("img")[0].src == bioGUIDicon[1]){
			document.getElementById(_ref.outputId).innerHTML = "<img src='" + bioGUIDicon[6] + "' style='border:0px;height:16px;width:16px' alt='Timeout - please try again later' title='Timeout - please try again later'>";
		}
		else{}
	},15000);
}

bioGUID.getDetails.prototype.displayResult = function()
{
	var _output = "";
	try{
		this.report = this.json.record;
		
		var doi = this.report.doi;
		var hdl = this.report.hdl;
		var url2 = this.report.url;
		var atitle = this.report.atitle;
		var glink = "http://scholar.google.com/scholar?q="+escape(atitle)+"&as_subj=bio";
	
		if (doi == null && hdl == null && url2 == null && atitle != null) {
			_output = '<a href="' + glink + '"><img src="'+bioGUIDicon[9]+'" style="border:0px;height:16px;width:16px" alt="Search Google Scholar" title="Search Google Scholar"></a>';
		}
		else {		
			if (doi != null) {
				var link = "http://dx.doi.org/"+doi;
			
				_output = '<a href="'+link+'"><img src="'+bioGUIDicon[4]+'" style="border:0px;height:16px;width:16px" alt="To publisher..." title="To publisher..."></a>';
			}
			if (hdl != null) {
				var link = "http://hdl.handle.net/"+hdl;

				_output = '<a href="'+link+'"><img src="'+bioGUIDicon[5]+'" style="border:0px;height:16px;width:16px" alt="To publisher..." title="To publisher..."></a>';
			}
			if (url2 != null) {
				var ext = Right(url2,4);
				var img = bioGUIDicon[3];
				var alt = "HTML";
				
				if (ext == ".pdf") {
					img = bioGUIDicon[2];
					alt = "PDF";
				}						
			
				_output = '<a href="'+url2+'"><img src="'+img+'" style="border:0px;height:16px;width:16px" alt="' + alt + '" title="' + alt + '"></a>';
			}
		}
        }
	catch(e){
		 _output = "<img src=" + bioGUIDicon[7]+ " style='border:0px;height:16px;width:16px' alt='Reference not Understood' title='Reference not Understood'>";
	}
	document.getElementById(this.outputId).innerHTML = _output;
}

function Right(str, n){
    if (n <= 0) {
       return "";
    }
    else if (n > String(str).length) {
       return str;
    }
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}

function bioGUIDOpenURL(ref,id)
{
	// browser check from: http://blog.coderlab.us/2006/04/18/the-textcontent-and-innertext-properties/
	var hasInnerText = (document.getElementsByTagName("body")[0].innerText !== undefined) ? true : false;
	var reftext = document.getElementById(ref);
		
	if(!hasInnerText) {
		var refurl = escape(reftext.textContent);
	}
	else {
		var refurl = escape(reftext.innerText);
	}

	//check length of escaped reference
	if (refurl.length >= 700) {
		alert('Sorry, this reference is too long.');
		return;
	}

	document.getElementById(id).innerHTML = '<img src="'+bioGUIDicon[1]+'" style="border:0px;height:16px;width:16px" alt="Finding reference..." title="Finding reference...">';
	var bioGUIDNew = new bioGUID.getDetails(refurl);
	bioGUIDNew.outputId = id;
	bioGUIDNew.load();
}

//Initialize

bioGUIDicons.init();