jQuery.fn.autoformatphonefield = function() {
  return this.each(function(){

      $(this).bind('keyup', function(e){

        //Skip autoformatting when user hits DELETE
        if(e.keyCode == 8)
            return true;

        var origval = $(this).val();
        var dt = $(this).val().replace(/[^\d]/g, '');

        var s = origval;
        if(dt.length == 3)
            s = '(' + dt + ') ';
        if(dt.length == 6)
            s = '(' + dt.substr(0,3) + ') ' + dt.substr(3,3) + '-'; 
        if(dt.length == 10)
            s = '(' + dt.substr(0,3) + ') ' + dt.substr(3,3) + '-' + dt.substr(6,4); 

        $(this).val(s);
       
        //Cancel event bubbling unless <RETURN>
        if(e.keyCode != 13) 
            return false;
      });
  });
};
