/* Javascript for text2bib, at http://services.uzeweb.com/
*/

// Create togglers
var instructionsToggler = new Toggler("instructions", "Show instructions", "Hide instructions");
var libraryToggler = new Toggler("library", "Show format library", "Hide format library");

//// Activate code library
if (document.getElementsByTagName) {
	activateCodeLibrary();
}

function activateCodeLibrary() {
	// Create the linkObject
	var linkObject = document.createElement('A');
	linkObject.href = 'javascript:void(0);';
	
	// Find library object
	var libraryObject = document.getElementById('library')
	
	// Add the 'Add all' link just before the OL
	var olObject = getFirstChildOfType(libraryObject, 'OL');
	
	var t = linkObject.cloneNode(true);
	t.innerHTML = 'Add entire library to format field';
	t.onclick = insertEntireCodeLibrary;
	libraryObject.insertBefore(t, olObject);
	
	
	// Find the first LI in the library OL
	liNode = getFirstChildOfType(olObject, 'LI');
	
	// Loop through all LIs and turn their innerHTML into links
	while (liNode.nodeName == 'LI') {
		// Create link
		var t = linkObject.cloneNode(true);
		t.innerHTML = liNode.innerHTML;
		t.onclick = function() { insertCodeLibrary(this) };

		// Insert link; assume the previous node is the node to turn into a link
		liNode.replaceChild(t, liNode.firstChild);
		
		// Go to next LI
		liNode = getNextSiblingOfType(liNode, 'LI');
	}
}

function insertCodeLibrary(self) {
	// Ensure the format field currently ends in a \n
	var str = document.getElementById('format').value;
	if (str.length > 0 && str.charAt(str.length-1) != "\n") {
		str += "\n";
	}
	
	// Find link text
	var linkText = self.innerText;	// IE
	if (!linkText) {
		linkText = self.text;	// Mozilla
	}
	
	// Add self.text to the format string
	document.getElementById('format').value = str + linkText + "\n";
	
}

function insertEntireCodeLibrary() {
	// Ensure the format field currently ends in a \n
	var str = document.getElementById('format').value;
	if (str.length > 0 && str.charAt(str.length-1) != "\n") {
		str += "\n";
	}
	
	// Find the first LI in the library OL
	liNode = getFirstChildOfType(getFirstChildOfType(document.getElementById('library'), 'OL'), 'LI');
	
	// Loop through all LIs
	while (liNode.nodeName == 'LI') {
		// Find link text
		var linkText = liNode.firstChild.innerText;	// IE
		if (!linkText) {
			linkText = liNode.firstChild.text;	// Mozilla
		}
		
		// Store link text
		str += linkText + "\n";
		
		// Go to next LI
		liNode = getNextSiblingOfType(liNode, 'LI');
	}
	
	// Add all link text to the format string
	document.getElementById('format').value = str + "\n";
}

function getFirstChildOfType(node, type) {
	if (node.firstChild.nodeName==type) return node.firstChild;
	return getNextSiblingOfType(node.firstChild, type);
}

function getNextSiblingOfType(now, type) {
	var next = now.nextSibling;
	if (!next) return 0;
	if (next.nodeName==type) return next;
	return getNextSiblingOfType(next, type);
}

