/*
 * ReplaceText.js
 * 
 * Replaces text or elements inside of an element with new text
 * 
 * Requires an implementation of DOM Level 1 or higher
 */

/*
 * replaceElement() - Replaces all child nodes in an element with 
 * a new element
 * 
 * element - element whose child nodes will be replaced
 * newElement - new element to replace child nodes
 * 
 * returns success
 */
function replaceElement(element, newElement) {
	
	/* DOM required */
	if (!checkForDOM()) {
		return false;
	}
	
	/* Remove all child nodes */
	while (element.lastChild != null) {
		element.removeChild(element.lastChild);
	}
	
	return appendElement(element, newElement);
}

/*
 * checkForDOM() - checks for an implementation of the DOM
 * 
 * returns success
 */
function checkForDOM() {
	
	/* Check to see if a DOM is implemented */
	if (document.implementation) {
		return true;
	} else {
		return false;
	}
}

/*
 * appendElement() - appends a new element to the hierachial node
 * structure of an existing element
 * 
 * element - existing element whose structure will be changed
 * newElement - new element to be appended
 * 
 * returns success
 */
function appendElement(element, newElement) {
	
	var node = null;
	
	/* DOM required */
	if (!checkForDOM()) {
		return false;
	}
	
	node = element.appendChild(newElement);
	
	/* Check to make sure the element was appended */
	if (node != null) {
		return true;
	} else {
		return false;
	}
}

/*
 * replaceText() - Replaces text inside an element with new text
 * 
 * element - existing element to be modified
 * text - replacement text
 * 
 * returns success
 */
function replaceText(element, text) {
	
	/* DOM required */
	if (!checkForDOM()) {
		return false;
	}
	
	var t = document.createTextNode(new String());
	replaceElement(element, t);
	appendText(element, text);
}


/*
 * appendText() - Appends a text node to the hierarchial structure of
 * an element
 * 
 * element - existing element to be modified
 * text - text to be appended
 * 
 * returns success
 */
function appendText(element, text) {
	
	/* DOM required */
	if (!checkForDOM()) {
		return false;
	}
	
	var p = document.createElement("p");
	
	var t = document.createTextNode(text);
	
	if (p != null && t != null) {
		p.appendChild(t);
		return appendElement(element, p);
	} else {
		return false;
	}
}

