// examPointCount.js  P.Conrad    Functions to count points in an HTML exam   10/08/2006
//
//   To use:
//       (1) Use abbreviations such as (5 pts)  or (10 pts)  or (1 pts)  to indicate point values.
//           The functions use the regular expression "([0-9]+ pts)" to look for point values.
// 
//       (2) Be sure your exam is well formatted HTML or XHTML.  
//           Use validator.w3.org to ensure this.  Otherwise, the JavaScript will not be able
//           to sucessfully parse your HTML and find the points.
//
//       Add more instructions here indicating how to mark where the point count goes, and
//       what to put in the opening body tag to be sure it gets updated.

function pointCount(n)
{
   var text = n.data;
   
   // look for (x pts) where x is some sequence of [0-9]+
   // save the result of [0-9]+ in result[1]
   
   var pointRegExp = /\(([0-9]+) pts\)/i;  
   var result = pointRegExp.exec(text);
   
   if (result) // if there was a match
   {
      return parseInt(result[1]); // this contains the numeric part
   }
   else
   {
     return 0; // otherwise, there weren't any points in this text element
   }
}

function countPoints(n) {                     // n is a Node 
    if (n.nodeType == 3 /*Node.TEXT_NODE*/)   // Check if n is a Text object
        return pointCount(n);                 // If so, parse its text and return number of points
    
	// Otherwise, iterate through n's children, totalling up the points
	var numpoints = 0; 
    for(var m = n.firstChild; m != null; m = m.nextSibling) 
	{
        numpoints += countPoints(m);  
    }
    return numpoints;   // Return total of all children's points
}

function updatePointCount()
{
  var whereToPutIt = window.document.getElementById("pointCount");
  whereToPutIt.innerHTML = ("Total Points: " + countPoints(document.body));
}

