// Javascript phone number filter 
// returns false if the phone number is GOOD, otherwise returns
// an error string explaining what the problem is.
// usage:
//    if ( msg = invalid_phone(form.area.value, form.phone.value, country, "home") ) {
//        alert(msg);
//    }
// 4th arg is optional location string (such as "home", "work", "cell"
// if provided, the return string includes this.

function invalid_phone(area_code, phone_number, country, loc_str) {

    area_code       = String(area_code);    
    phone_number    = String(phone_number);
    phone_number    = phone_number.replace(/[\-]/g, "");
    
    if (!loc_str) {
        loc_str = "";
    }
    else {
        loc_str += " ";
    }

    var upperCase   = loc_str.substring(0,1).toUpperCase();
    var uloc_str    = upperCase + loc_str.substring(1, loc_str.length) + " ";

    if (phone_number == "" || area_code == "") {
        return uloc_str + "phone number and area code are required.\n";
    }
        
    if (country == 'United States' || country == 'Canada' || country == '') {

        if (area_code.length != 3) {
            return uloc_str + "area code must be 3 digits in length.\n";
        }
    
        if (phone_number.length != 7) {
            return uloc_str + "phone number must be 7 digits in length.\n";
        }
    
        var strNumbs = "0123456789";
    
        for (i=0; i < area_code.length; i++) {     
            var strChar = area_code.charAt(i);
            if (strNumbs.indexOf(strChar) == -1) { 
                return uloc_str + "area code must be numeric (no letters or other characters).\n";
            }
         }
    
        for (i=0; i < phone_number.length; i++) {     
            var strChar = phone_number.charAt(i);
            if (strNumbs.indexOf(strChar) == -1) { 
                return uloc_str + "phone number must be numeric (no letters or other characters).\n";
            }
         } 
    
        var regexstring = /([0-1][0-9][0-9]|[0-9]11|[2-9]22|[2-9]33|[2-9]44|[2-9]55|[2-9]66|[2-9]77|[2-9]88|[2-9]99|[2-9]00|37[0-9]|96[0-9])/;
    
        if ( area_code.match(regexstring) )  { 
            return uloc_str + "area code is not valid for residential or commercial use in the US.\n";
        }
     
        var prefix = phone_number.substr(0, 3);
    
        regexstring = /^(555|0[0-9][0-9])/;
    
        if ( prefix.match(regexstring) ) { 
            return "The exchange (2nd three numbers) of the " + loc_str + "phone number is not valid for residential or commercial use in the US.\n";
        }

    }

    return false;
}

