
// Declaring required variables
var digits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";
// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = phoneNumberDelimiters + "+";
// Minimum no of digits in an international phone no.
//var minDigitsInIPhoneNumber = 10;

function isInteger(s)
{   var i;
    for (i = 0; i < s.length; i++)
    {           
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    return true;
}

function stripCharsInBag(s, bag)
{   var i;
    var returnString = "";
    //strips out spaces + - (). leaves letters and numbers, and all other chars
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

//function checkInternationalPhone(strPhone)
//{
//    //s = stripCharsInBag (strPhone, validWorldPhoneChars);
//    if (isInteger(s) && s.length >= minDigitsInIPhoneNumber)
//    {
//        return true;
//    }
//    else
//    {
//        return false;
//    }
//}

function textBoxIsPhone(sID)
{
    var sErr = "";
	var sPhone = document.getElementById(sID).value;
	//strip out spaces + - (). Leave letters and numbers, and all other chars
	sPhone = stripCharsInBag (sPhone, validWorldPhoneChars);   
	//be sure is not ""
	if ((sPhone==null)||(sPhone==""))
    {
        sErr = "Number is blank";
        return sErr;
	}
	//be sure is all numbers
	if (isInteger(sPhone) == false)
    {
        sErr = "Number cannot contain non-numeric characters.";
        return sErr;
    }
	//be sure length is appropriate
	if (sPhone.length > 10)
	{
	    //Phone.length > 10 is ok only if this is an international number
	    //From Andy Han, total number of digits is not over 13, and always starts with 011
	    //Dial    Country         City            Tel:
        //011    1-3 digit        1-4 digit       5-8 digit.
        var sFirst3 = sPhone.substring(0, 3);
	    if (sFirst3 == "011")
	    {
	        if (sPhone.length > 13)
            {
                sErr = "A valid international number must be less than 14 digits long.";
                return sErr;
	        }	        
	    }
	    else
	    {
	        sErr = "International numbers must start with 011. Others must be 10 digits long.";
            return sErr;
	    }        
	}
	else
	{
	    //cannot be < 10
	    if (sPhone.length != "10")
	    {
	        sErr = "Number must be 10 digits long.";
            return sErr;
	    }	    
	    //cannot start with a 1 or 9
	    //var sFirst = sPhone.substring(0, 1);
	    //if (sFirst == "1" || sFirst == "9")
	    //{
	    //    sErr = "Number cannot start with 1 or 9.";
            //return sErr;
	    //}	         	    	    
	}
    return "";
    
 }//textBoxIsPhone


