//*** Example use on a form element:
//*** 
//*** 	<input type="text" onBlur="checkPhone(this, true)">
//*** 
//*** -- AND --
//*** 
//*** Example use inside the form validating function:
//*** 	
//*** 	if (!checkPhone(document.frmMain.phone, true)) {
//*** 		alert('This is an invalid phone number.  Please fix the problems below:\n\n' + phoneMessage);
//*** 		document.frmMain.phone.focus();
//*** 		document.frmMain.phone.select();
//*** 		return false;
//*** 	} else {
//*** 		document.frmMain.submit();
//*** 		return true;
//*** 	}
//*** 

var phoneMessage = '';

function checkPhone(obj, requiresAreaCode) {
	if (! validPhone(obj, requiresAreaCode)) {
		return false;
	} else {
		return true;
	}
}

function validPhone(obj, requiresAreaCode) {
	var sPhone = obj.value;
	var sDigits = '';
	
	//check if the phone number is empty
	if (sPhone.length < 1) {
		phoneMessage = '    Phone number cannot be empty';
		return false;
	}
	
	//remove all non-numeric values
	for (var i=0; i<sPhone.length; i++) {
		var chr = sPhone.substring(i, i+1);
		if (chr >= '0' && chr <= '9') {
			sDigits = sDigits + chr;
		}
	}
	
	//check for the appropriate number of digits
	if (requiresAreaCode) {
		if (sDigits.length < 10) {
			phoneMessage = '    Phone number must contain at least 10 digits';
			return false;
		}
	} else {
		if (sDigits.length < 7) {
			phoneMessage = '    Phone number must contain at least 7 digits';
			return false;
		}
	}
	
	//format the phone number.  Either "(555) 555-1212" or "555-1212"
	if (requiresAreaCode) {
		obj.value = '(' + sDigits.substring(0, 3) + ') ';
		obj.value += sDigits.substring(3, 6) + "-";
		obj.value += sDigits.substring(6, 10);
	} else {
		obj.value = sDigits.substring(0, 3) + "-";
		obj.value += sDigits.substring(3, 7);
	}
	
	//if they enter more than 10 digits, we'll just tack the extra digits to
	//the end of the formatted number with a space.  Ex: "(555) 555-1212 678"
	if (requiresAreaCode) {
		if (sDigits.length > 10) {
			obj.value += " " + sDigits.substring(10);
		}
	} else {
		if (sDigits.length > 7) {
			obj.value += " " + sDigits.substring(7);
		}
	}
	
	return true;
}