// generateID.js
/*  A couple of things here.
 *  (1) Uses a self-executing function to eliminate all globals.
 *  (2) Generates a static variable (genId.id) as a property of
 *      a function object.
 *
 *  Tested in IE7, FF2, Op9, and Sa3.
 *  Some browsers treat double-clicks on the button as single clicks.
 *
 *  HTML of the web page:
 *  <body>
 *    <p><button>Generate ID</button></p>
 *    <p>You have not generated any IDs yet.</p>
 *  </body>
 *
 *  ccv 2008-03-01
 */
  (function() //  Anonymous self-executing function
  {
    var b = null;
    var p = null;
    //  genId()
    //  ------------------------------------------------------------
    /*  Returns the next value in a sequence on successive calls.
     */
      function genId()
      {
        //  Create static variable if it does not exist yet.
        if (!genId.id) genId.id = 0;
        return ++genId.id;
      }
      //  handler()
      //  ----------------------------------------------------------
      /*  Click hander for the button. Gets the next ID and displays
       *  it.
       */
      function handler(e)
      {
        var id = genId();
        p.firstChild.nodeValue = "Your ID is " + "0000".substring(0, 4 - Math.ceil(Math.log(id+1)/Math.log(10))) + id + ".";
      }
      //  window.onload handler
      //  ---------------------------------------------------------
      /*  Sets up the onclick handler for the button.
       */
      window.onload = function()
      {
        b = document.getElementsByTagName('button')[0];
        p = document.getElementsByTagName('p')[1];
        if (b && p)
        {
          b.onclick = handler;
        }
      }
  })(); //  End the function definition and execute it.

