// DHTML phone number validation script.
// Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)

// 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 = 7;

// Minimum no of digits in an italian mobile phone no.
var minDigitsInItMobilePhoneNumber = 9;

// Maximum no of digits in an italian mobile phone no.
var maxDigitsInItMobilePhoneNumber = 11;

function isInteger( s ) {

	var i;
    for ( i = 0; i < s.length; ++i ) {
    
        // Check that current character is number.
        var c = s.charAt( i );
        if( ( ( c < "0" ) || ( c > "9" ) ) ) return false;
    }
    
    // All characters are numbers.
    return true;
}

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 checkInternationalPhone( strPhone, mobile ) {

	s = stripCharsInBag( strPhone, validWorldPhoneChars );

	if( mobile ) {
	
	    if( isInteger( s ) ) {
	    
	        if( s.length >= minDigitsInItMobilePhoneNumber + 3 &&
					3 == s.charAt( 0 ) && 9 == s.charAt( 1 ) )
   				s = s.substr( 2, s.length - 2 )
	        else if( s.length >= minDigitsInItMobilePhoneNumber + 4 &&
		  			 0 == s.charAt( 0 ) && 0 == s.charAt( 1 ) &&
					 3 == s.charAt( 2 ) && 9 == s.charAt( 3 ) )
	            s = s.substr( 4, s.length - 4 )

			if( s.length >= minDigitsInItMobilePhoneNumber &&
					s.length <= maxDigitsInItMobilePhoneNumber && 3 == s.charAt( 0 ) )
				return true;
			else
			    return false;

		} else
		    return false;

	} else
		return ( isInteger( s ) && s.length >= minDigitsInIPhoneNumber );
}

