//By Raymond Martens
// http://www.howtocreate.co.uk/emails/RaymondMartensList/

function togglePlusMinusButton(element) {
	//we take the last 8 characters of the source and compare it to plus_.gif and minus.gif
	var strLength = element.src.length;
	var imgSource = element.src.substr(strLength - 9, 9);
	var index = element.parentNode.parentNode.getElementsByTagName( 'ul' )[0].MWJuniqueID;
	var bookElement = document.getElementById( 'bookImage' + index );

	if (imgSource == 'minus.gif') {
		element.src = '../images/toc/plus_.gif';
		bookElement.src = '../images/toc/closedbook.jpg';
	}
	else if (imgSource == 'plus_.gif') {
		element.src = '../images/toc/minus.gif';
		bookElement.src = '../images/toc/openedbook.jpg';
	}
}

function getLastChildElementOfType(parentElement, tagName) {
	var lastChildNode = parentElement.lastChild;

	while (lastChildNode != null) {
		if (lastChildNode.nodeType == 1 && lastChildNode.tagName.toLowerCase() == tagName) {
			return lastChildNode;
		}
		lastChildNode = lastChildNode.previousSibling;
	}
	return null;
}

function setUpListTree(listRoot) {
	if( !document.createElement || !document.childNodes ) {
		return;
	}

	var listRoot = document.getElementById(listRoot);
	var liElements = listRoot.getElementsByTagName('li');

	for (var i = 0; i < liElements.length; i++) {
		var liBeforeElement = document.createElement('span');
		liBeforeElement.className = 'liBefore';

		var imgElementOne = document.createElement('img');

		//check if this element is it's parent's last child:
		if (getLastChildElementOfType(liElements[i].parentNode, 'li') == liElements[i]) {
			//adjust the classname to emulate a css 'li:last-child' 
			liElements[i].className = liElements[i].className + ' liLastChild';

			//adjust the content to emulate a css 'li:last-child:before'
			imgElementOne.src = '../images/toc/last_child.gif';
		}
		//or the parent's first child:
		else if (i == 0) {
			imgElementOne.src = '../images/toc/first_child.gif';
		}
		else {
			imgElementOne.src = '../images/toc/i_th_child.gif';
		}

		var imgElementTwo = document.createElement('img');
		imgElementTwo.src = '../images/toc/closedbook.jpg';

		liBeforeElement.appendChild(imgElementOne);
		liBeforeElement.appendChild(imgElementTwo);

		liElements[i].insertBefore(liBeforeElement, liElements[i].firstChild);

		var plusImage = liBeforeElement.parentNode.getElementsByTagName( 'a' )[0];

		if( plusImage ) {
			var nextBook = liBeforeElement.parentNode.getElementsByTagName( 'ul' )[0];

			if( nextBook ) {
				imgElementTwo.id = 'bookImage' + nextBook.MWJuniqueID;
			}
		}
	}
}
