var phoneNumberDelimiters = "()- ";
var digits = "1234567890";

function reformat (s)
{
    var arg;
    var sPos = 0;
    var resultString = "";

    for (var i = 1; i < reformat.arguments.length; i++) {
       arg = reformat.arguments[i];
       if (i % 2 == 1) resultString += arg;
       else {
           resultString += s.substring(sPos, sPos + arg);
           sPos += arg;
       }
    }
    return resultString;
}

function isInteger (s)
{   var i;

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);

        if (!isDigit(c)) return false;
    }

    return true;
}

function isDigit (c)
{ return ((c >= "0") && (c <= "9")) }

function stripCharsNotInBag (s, bag)

{   var i;
    var returnString = "";

    // Search through string's characters one by one.
    // If character is in bag, append to returnString.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) != -1) returnString += c;
    }

    return returnString;
}

function stripCharsInBag (s, bag)
{   var i;
    var returnString = "";

    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }

    return returnString;
}

function isUSPhoneNumber (s)
{ return (isInteger(s) && s.length == 10) }

function warnInvalid (theField, s)
{   alert(s)
    return "";
}

function reformatUSPhone (USPhone)
{ return (reformat (USPhone, "(", 3, ") ", 3, "-", 4)) }

function checkUSPhone (theField)
{
  var normalizedPhone = stripCharsInBag(theField, phoneNumberDelimiters);
       return reformatUSPhone(normalizedPhone)
}

function checkUSPhone (theField)
{
  var normalizedPhone = stripCharsInBag(theField, phoneNumberDelimiters)
     if (!isUSPhoneNumber(normalizedPhone, false)) 
        return warnInvalid ("", 'You have entered an invalid phone number.\nPlease make sure it is 10 digits long.');
     else 
        return reformatUSPhone(normalizedPhone)
}
