/**
 * myscript.js: enumerates the paragraphs in a document, based on a  
 *              placeholder value.
 *              The top-level function, doEnumeration, contains a 
 *              Counter class, which holds the value of the counter,
 *              a rpl_value function, which searches the document 
 *              recursively for text nodes whose content matches the
 *              match value defined in the function.  The nodes that 
 *              satisfy the match condition are replaced with a count
 *              value and then the count value is incremented.
 * 
 **/



function doEnumeration(top_node)
{

	// Define a counter class - we need to pass it through different 
	// recursion levels of the rpl_value function, so we can't just set up 
	// an accumulator variable in the function. 

	// Class definition.
	function Counter(initialValue)
	{
		// Constructor - initialise the counter
		this.value = initialValue
	}
	// Create and discard a Counter object for the benefit of Javascript 1.1 
	// environments.
	new Counter(0);

	function getCount()
	{
		return this.value
	}
	Counter.prototype.getCount = getCount;

	function incrementCount()
	{
		this.value++;
	}
	Counter.prototype.incrementCount = incrementCount;

	// End of class definition.

    // Function definition.
	function rpl_value(node, count) 
	{
	// This is the value to be replaced 
	match_value = "parnum";
	if (node.nodeType == 3 /* Node.TEXT_NODE */) 
		{
			if (node.data == match_value)
				{
					var newNode = document.createTextNode(count.getCount());
					var parent = node.parentNode;
					parent.replaceChild(newNode, node);
					count.incrementCount();
				}
		}
	else
		{
			var children = node.childNodes;
			for(var i = 0; i < children.length; i++) 
			{
			    rpl_value(children[i], count);
			}
		}
	}
	// End of function definition.
	
	// Run the code - make a counter and call the function.
	counter = new Counter(1);
    rpl_value(top_node, counter);
}
