// Non-digit characters which are allowed in phone numbers
var allowedChars = "()- +";
// Minimum no of digits in an international phone no.
var minDigitsInIPhoneNumber = 10;

// Function to check the email with given IDs for the textbox and warning div
function checkPhoneEx(pBoxID){
	phoneBoxID = pBoxID;
	return checkPhone();
}

// Function to check the phone number
function checkPhone(){
	var input = document.getElementById(phoneBoxID).value;
	if (input == "" || !checkInternationalPhone(input)){
		return false;
	}
	return true;
}

// Check to see if a string consists of just integers
function isInteger(s) {
	return (s.toString().search(/^[0-9]+$/) == 0);
}

// Trim function to remove whitespace
function trim(s){
	return s.split(" ").join("");
}

function removeAllowedChars(s, allowed)
{   
	var i;
    var returnString = "";
    // If character is not in allowed list, add to returnString
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is allowed
        var c = s.charAt(i);
        if (allowed.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

// Check the international phone 'pattern' is ok
function checkInternationalPhone(strPhone){
	// Get rid of whitespace
	strPhone=trim(strPhone);
	// Leading plus is ok, otherwise not
	if(strPhone.indexOf("+") > 1) return false;
	// First bracket should appear at position 3 (e.g. +44(0)208...)
	var bracket = 3;
	// Unless we're using '-' (e.g. +44-(0)-208...)
	if(strPhone.indexOf("-") != -1) bracket++;
	// If the bracket is too far in, give up
	if(strPhone.indexOf("(") != -1 && strPhone.indexOf("(") > bracket) return false;
	// Return bracket should appear 2 further on than first bracket
	var bracketPosition = strPhone.indexOf("(");
	if(strPhone.indexOf("(") != -1 && strPhone.charAt(bracketPosition + 2) != ")") return false;
	// If the bracket isn't closed, give up
	if(strPhone.indexOf("(") == -1 && strPhone.indexOf(")") != -1) return false;
	// Strip out our allowed characters if we've got this far
	strPhone = removeAllowedChars(strPhone, allowedChars);
	// If the final string is all integers and is greater than or equal to our min length, return true, else false
	return (isInteger(strPhone) && strPhone.length >= minDigitsInIPhoneNumber);
}

