var loaded = false;     // page fully loaded yet?

/* counts the number of school links in this document whose hostname 
 * component matches the pattern specified in regex
 */
function countSchools(regex) {
  var count = 0;
  for (var i = 0; i < document.links.length; i++)
    regex.test(document.links[i].hostname) && count++;
  return count;
}


/* waits for the current page to fully load, then emits a count of the 
 * number of school links in this document that match a given pattern.
 *
 * writeMessage - whether to emit the sentence in which the count will be 
 *                embedded: should only be true the 1st time this function 
 *                is called
 */
function emitCount(writeMessage) {

  /* browsers that don't support W3C DOM Level 1 need to be weeded out.
   * Annoyingly, we can't use the browser's presence of a definition for 
   * document.getElementById as proof of its ability to dynamically 
   * parse/modify a document's nodes because Opera 6 (spit) defines this 
   * method without implementing it properly. Instead we have to test if 
   * the browser can return the first child of an element that must exist 
   * (e.g. head) as a more thorough test of what we propose to do.
   */
  //if (!document.getElementById) return;
  if (!document.getElementsByTagName('head')[0].firstChild) return;

  if (writeMessage)
    document.write('There are currently <strong id="nHertsSchools">' 
        + '&lt;counting&gt;</strong> schools listed whose web sites are hosted on the Hertfordshire Grid for Learning.');

  // if this page hasn't fully loaded yet, try again in 1000 milliseconds
  if (!loaded)
    setTimeout('emitCount(false)', 2000);

  else {        // HTML tree has fully loaded: now we can start counting
    var pattern = /\.herts\.sch\.uk/;
    document.getElementById("nHertsSchools").firstChild.nodeValue = 
        countSchools(pattern);
  }
}


