// DOM Scripting by Jeremy Keith pg136
function insertAfter(newElement,targetElement) {
	var parent = targetElement.parentNode;
	if (parent.lastChild == targetElement) {
		parent.appendChild(newElement);
	} else {
		parent.insertBefore(newElement,targetElement.nextSibling);
	}
}

function preparePlaceholder(galleryList,imgId,firstImg,firstImgAlt,descriptionId,descriptionText) {
	if (!document.createElement) return false;
	if (!document.createTextNode) return false;
	if (!document.getElementById) return false;
	if (!document.getElementById(galleryList)) return false;
	var placeholder = document.createElement("img");
	placeholder.setAttribute("id",imgId);
	placeholder.setAttribute("src",firstImg);
	placeholder.setAttribute("alt",firstImgAlt);
	var description = document.createElement("p");
	description.setAttribute("id",descriptionId);
	var desctext = document.createTextNode(descriptionText);
	description.appendChild(desctext);
	var gallery = document.getElementById(galleryList);
	insertAfter(description,gallery);
	insertAfter(placeholder,description);
}

function prepareGallery(galleryList,imgId,descriptionId) {
	// make sure the browser understands getElementsByTagName
	if (!document.getElementsByTagName) return false;
	// make sure the browser understands getElementById
	if (!document.getElementById) return false;
	// make sure that ul we're pulling data from exists
	if (!document.getElementById(galleryList)) return false;
	// loop through all the links in the list of images
	var gallery = document.getElementById(galleryList);
	var links = gallery.getElementsByTagName("a");
	for (var i=0; i<links.length; i++) {
		links[i].onclick = function() {
			// proceeding from this point is dependant on the boolean true/false returned from the showPic function
			return showPic(this,imgId,descriptionId);
		}
	}
}

function showPic(whichpic,imgId,descriptionId) {
	// check for the placeholder element, we want to follow the link even if the placeholder doesn't exist
	if (!document.getElementById(imgId)) return true;
	// use the href from the link as the source of the image being shown
	var source = whichpic.getAttribute("href");
	var placeholder = document.getElementById(imgId);
	placeholder.setAttribute("src",source);
	// check for the description element
	if (!document.getElementById(descriptionId)) return false;
	// check for the title attribute, if it exists use it as the description, otherwise insert an empty string into the description field
	var text = whichpic.getAttribute("title") ? whichpic.getAttribute("title") : "";
	var description = document.getElementById(descriptionId);
	// make sure the first child of description is a text node; if so insert the title into that node
	if (description.firstChild.nodeType == 3) {
		description.firstChild.nodeValue = text;
	}
	return false;
}
