//phone format code
var areacodeLength  = 3;
var firstThree      = 3;
var previousLength  = null;
var thisInput       = null;
var originalLength  = null;
var thisAreacode    = null;
var thisFirstThree  = null;
var thisLastFour    = null;
var phone_test      = false;
var international   = false;
function autoFormat(input,type) {
  //lock out NS4
  if (!document.layers) {
    //var temp_selection = input.selectionStart;
    //alert("selectionStart=" + input.selectionStart);
    var addFirstParen   = false;
    var addSecondParen  = false;
    var addDash         = false;
    thisInput           = input.value.replace(/[. ()-\/]/gi,'');
    //if first input is a "+" assume its an international number and do not format
    if (input.value.length == 1 && input.value == '+') { international = true; return true;}
    else if (input.value.length == 1 && input.value == '(') { previousLength = 1; return true;}
    //dont do anything on backspace
    else if (input.value.length >= previousLength && international == false) {
      thisAreacode    = thisInput.substr(0,3);
      thisFirstThree  = thisInput.substr(3,3);
      thisLastFour    = thisInput.substr(6,4);
      
      //add '('
      if (thisInput.length > 0) { addFirstParen = true; }
      //add ') '
      if (thisAreacode.length == areacodeLength) { addSecondParen = true; }
      //add '-'
      if (thisFirstThree.length == firstThree) { addDash = true; }
      
      //add everything, assign to field
      if (addFirstParen) { thisAreacode = '(' + thisAreacode; }
      if (addSecondParen) { thisAreacode += ') '; }
      if (addDash) { thisFirstThree += '-'; }
      if (phone_test) { alert('writing'); }
      input.value = thisAreacode + thisFirstThree + thisLastFour;
    }
    previousLength = input.value.length
  }
}