﻿function removeAll (needles, haystack) {
    var needle, index, returnme;
    returnme = haystack;
    for (var i = 0; needle = needles[i]; i++)
    {
        while ((index = returnme.indexOf(needle)) > -1)
        {
            returnme = returnme.substring(0, index) + returnme.substring(index + 1);
        }
    }
    return returnme;
}

function isPhoneNumber (input) {
    var codes, code;
    input = removeAll(['(', ')', '.', '-', ' '], input);
    
    if (input.length == 0)
        return false;
        
    if (input.length == 10)
        if (input.charAt(0) != '+')
            input = '+1' + input;
            
    if (input.length == 11)
        switch (input.charAt(0))
        {
            case '0':
            {
                if( input.charAt(1) == '7' ) 
                    input = "+44" + input.substring(1, input.length);
                else
                    return false; 
                break;
            }
            case '1':
                input = '+' + input;
                break;
            case '+':
                if (input.charAt(1) != '1')
                    input = '+1' + input.substring(1);
                else if( startsWith("+4407", input ) )
                    input = "+44" + input.substring(4, input.length);
                break;
         }
    
    if (input.charAt(0) != '+')
        return false;
        
    if (!/^\+[\d]{8,}$/.test(input))
        return false;
        
    // is north american
    if (input.length == 12)
        if (startsWith('+1', input))
            return true;
           
    // is international 
    codes = { '440' : '44', '610' : '61', '640' : '64' }
    for (code in codes)
    {
        if (!startsWith(code, input))
            continue;
            
        input = codes[code] + input.substring(codes[code].length);
        break;
    }
        
    return true;
}

function startsWith (needle, haystack) {
    return haystack.substring(0, needle.length) == needle;
}