(function(){
  F = {
    defaults: {
      input: "Element116",
      message: "Please fill in a complete phone number."
    },

    getOptions: function() {
      for(key in F.defaults) {
        F[key] = F.defaults[key];
        if(F.options && F.options[key]) F[key] = F.options[key];
      }
    },
    
    inputObj: function() {return document.getElementsByName(F.input)[0]},
    
    format: function() {
      var re = /^\D*[0-1]*\D*([2-9]\d{2})\D*(\d{0,3})\D*(\d{0,4})\s*(\S*)$/;
      this.value = this.value.replace(re,'($1) $2-$3 $4');
      this.value = this.value.replace(/\)*\s*-*\s*$/,'');
    },
    
    validate: function() {
      var re = /^\D*[0-1]*|\D*/g;
      var numLength = this.value.replace(re,'').length;
      if(numLength && numLength < 10) {
        if(this.value != this.lastValue) {
          alert(F.message);
          setTimeout("FormatPhone.setFocus()",0);
        }
      }
      this.lastValue = this.value;
    },
    
    setFocus: function() {
      this.inputObj().focus();
    },
    
    initEvent: function() {
      F.getOptions();
      var thisObj = F.inputObj();
      if (thisObj) {
        thisObj.onkeyup = F.format;
        thisObj.onblur = F.validate;
      }
    },
  
    init: function () {
      if (window.addEventListener) window.addEventListener("load", this.initEvent, false);
      else if (window.attachEvent) window.attachEvent("onload", this.initEvent);
    }
  }
  
  window['FormatPhone'] = F;
})();

FormatPhone.init();
