String.prototype.trim = function () {
	return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
};

//////////////////////////////////////////////////////////////////////////////
//
//  _formatPhone()
//
//////////////////////////////////////////////////////////////////////////////
function _formatPhone (string) {
	string = string.trim();
	var ov = string;
	var v = "";
	var x = -1;

	// is this phone number 'escaped' by a leading plus?
	if (0 < ov.length && '+' != ov.charAt(0)) { // format it
		// count number of digits
		var n = 0;
		if ('1' == ov.charAt(0)) {  // skip it
			ov = ov.substring(1, ov.length);
		}

		for (i = 0; i < ov.length; i++) {
			var ch = ov.charAt(i);

			// build up formatted number
			if ('0' <= ch && ch <= '9') {
				if      (n == 0) v += "(";
				else if (n == 3) v += ") ";
				else if (n == 6) v += "-";
				v += ch;
				n++;
			}
			// check for extension type section;
			// are spaces, dots, dashes and parentheses the only valid non-digits in a phone number?
			if (! ('0' <= ch && ch <= '9') &&
			    ch != ' ' &&
			    ch != '-' &&
			    ch != '.' &&
			    ch != '(' &&
			    ch != ')')
			{
				x = i;
				break;
			}
		}
		// add the extension
		if (0 <= x) {
			v += " " + ov.substring(x, ov.length);
		}

		// if we recognize the number, then format it
		if (n == 10 && v.length <= 40) {
			string = v;
		}
	}
	return string;
}

function formatPhone (field) {
	field.value = _formatPhone(field.value);
	return true;
};