// JavaScript Document
/*
 PhoneNumber object copyright(c)2001 by Fox Mahoney.
 Permission for free use with this copyright notice (thank you).
*/

/*
 the PhoneNumber object can be initialized with defaults (no arguments)
or by
 passing the phone number and/or a number pattern string.

 the phone number may be incremented one number at a time -
 this object will format the number up to the last number entered

 the pattern may be programmatically changed [see <select> option values
in <body>]
*/

var pn = new PhoneNumber();


function
PhoneNumber(num, pat)
{

 this.pattern = pat || "(###) ###-#### x####";
 this.setPattern = function(s) { this.pattern = s; }
 this.number = num || 0;
 this.setNumber = function(n) { this.number = n; }
 this.formatted = "";
 this.format = function()
  {
   var tstr = "" + this.number;
   var findex = 0;    // format string index
   var nindex = 0;    // number string index

     // the following regexp may need to be modified
     // to accommodate other foreign formats -- can't think of any, though
   var re = /[ A-Za-z\+\(\)\-]/;
   var parts = tstr.split(re);

   tstr = parts.join("");

   this.formatted = "";

   while(nindex < tstr.length)
   {
    if(this.formatted.length == this.pattern.length) break; // we're done

    while(this.pattern.charAt(findex) != "#")
     {
      this.formatted += this.pattern.charAt(findex++);
     }
    findex++;
    this.formatted += tstr.charAt(nindex++);

   }

   return this.formatted;
  }


}

function
modifyEntry(elem)
{
 pn.setNumber(elem.value);
 elem.value =  pn.format();
}

function
resetNumPattern(sel)
{

 pn.setPattern(sel.options[sel.selectedIndex].value);
 sel.form.phone.value = "";
}
