function format_template(string, template) {
    var newstring = '';
    var length;

    length = string.length;
    if (length > template.length) {
        length = template.length;
    }
    // Strip out any non-numeric characters and make a properly formatted number                                               
    var t=0;
    var ch;
    for (i=0; i<length; i++) {
        ch = string.substring(i, i+1);
        if ((ch >= '0' && ch <= '9') || ch == '-' || ch == '(' || ch == ')' || ch == '.' || ch == '/') {
            while (template.substring(t, t+1) != 'X' && t < length) {
                newstring = newstring + template.substring(t, t+1);
                t++;
            }
            if (ch >= '0' && ch <= '9') {
                newstring = newstring + ch;
                t++;
            }
        }
    }
    return newstring;
}

function format_phone(id) {
    var template = '(XXX) XXX-XXXX';
    
    field = document.getElementById(id);
    phone = field.value;
    field.value = format_template(phone, template);
    setSelectionRange(field, field.value.length, field.value.length);
}
