﻿/*
To Use tcvalidation.js:

verifyField(string clientFieldID, string type)

Boolean response : true (for valid) or false (for invalid)

about the parameters:

clientFieldID (string) - this must be the exact ID of the field to be validated. NOTE: under ASP.NET, the ID you see in the source (server) is frequently NOT the same as the ID you (and more importantly javascript) will see in the client rendered page.  For this reason, it is recommended that you "view source" of the generated page to inspect the field ID values, as they will be seen by the client web browser/javascript enviroment.

type (string) - this must be one of the following:
    name - must contain a space - intended for a person with at least 2 names, first and last. ;)
    phone - US / North America format : (308)-135-7895 or 308-135-7895 or 308135-7895 or 3081357895
    email - any email address which sould have an "@" symbol and end in a "." plus 2 to 4 characters (i.e. ".us", ".com", ".dork")
    url - any number of characters ("http://" or "https://" will be stripped away if present), must end in a "." plus 2 to 4 characters (i.e. ".us", ".com", ".dork")
    zip - either a 5, or a 5+4 (XXXXX or XXXXX-XXXX). Note: for a plus4, the hyphen is reqiuired
    taxid - includes social security or Employer ID
    string - generic alphanumeric

If a field comes back from verifyField  with a failure, the input field will be accompanied (redrawn) with the message.
the message text displayed uses the "err" CSS class to set the color of the error message

*/
//verifications
function verifyField(which, type) {

    var retBool = false;
    var findStr = "#" + which;
    clearErrors(findStr);
    if (checkForilleagals(findStr)) {
        switch (type) {
            case "name":
                if ($(findStr).val().length < 3) {
                    writeInputErr("Your name appears suspiciously short.", findStr);
                } else if ($(findStr).val().indexOf(" ") == -1) {
                    writeInputErr("Please provide your first <i>and</i> last name.", findStr);
                } else {
                    retBool = true;
                }
                break;
            case "phone":
                if (!validatePhoneNumber($(findStr).val())) {
                    writeInputErr("Invalid phone number", findStr);
                } else {
                    retBool = true;
                }

                break;
            case "email":
                if (!validateEmail($(findStr).val())) {
                    writeInputErr("Invalid email address", findStr);
                } else {
                    retBool = true;
                }
                break;
            case "url":
                if ($(findStr).val().indexOf("http://") != -1) {
                    var cleanUrl = $(findStr).val().subString($(findStr).val().indexOf("http://"))
                    $(findStr).val(cleanUrl);
                }
                if ($(findStr).val().indexOf("https://") != -1) {
                    var cleanUrl = $(findStr).val().subString($(findStr).val().indexOf("https://"))
                    $(findStr).val(cleanUrl);
                }
                if (!validateUrl($(findStr).val())) {
                    writeInputErr("Invalid URL", findStr);
                } else {
                    retBool = true;
                }
                break;
            case "zip":
                if (!validateZipCode($(findStr).val())) {
                    writeInputErr("Invalid zip code", findStr);
                } else {
                    retBool = true;
                }
                break;
            case "taxid":
                if ((!validateEID($(findStr).val()))&&(!validateSS($(findStr).val()))) {
                    writeInputErr("Invalid Federal EIN (XX-XXXXXXX)<br/>or SSN (XXX-XX-XXXX)", findStr);
                } else {
                    retBool = true;
                }
                break;
            case "string":
                //proceed
                if (!validateString($(findStr).val())) {
                    writeInputErr("Invalid entry", findStr);
                } else {
                    retBool = true;
                }
                break;
            case "ccv":
                //proceed
                if (!validateCCV($(findStr).val())) {
                    writeInputErr("Invalid Card Code Verification number", findStr);
                } else {
                    retBool = true;
                }
                break;
            case "password": 
                //proceed
                if (!validatePassword($(findStr).val())) {
                    writeInputErr("Invalid password", findStr);
                } else {
                    retBool = true;
                }
                break;
            case "dropdown":
                //proceed
                if ($(findStr).val() < 1) {
                    writeInputErr("Make a selection", findStr);
                } else {
                    retBool = true;
                }
                break;
            default:
                alert("Validation not set up for " + type + " yet.");
                break;
        }
    }
    return retBool;

}

function checkForilleagals(which) {
    var retBool = false;
    if (
        ($(which).val().indexOf("<") == -1) &&
        ($(which).val().indexOf(">") == -1) &&
        ($(which).val().indexOf("(") == -1) &&
        ($(which).val().indexOf(")") == -1) &&
        ($(which).val().indexOf("*") == -1) &&
        ($(which).val().indexOf("\\") == -1) &&
        ($(which).val().indexOf("/") == -1) &&
        ($(which).val().indexOf("\"") == -1) 
        ) {
        retBool = true;
    } else {
        writeInputErr("Invalid character or sequence", which);
    }
    return retBool;
}

function clearErrors(which) {
    $(which).css("border", "")
    $(which).parent().children('.err').empty();
}

function writeInputErr(msg, which) {
    $(which).parent().children('.err').empty();
    $(which).css("border", "1px solid #ff9900");
    $(which).parent().append("<b class='err'><br/>" + msg + "</b>");
    $(which).focus();
}

function validateString(elementValue) {
    if (elementValue.length < 2) {
        return false;
    } else {
        return true;
    }
}
function validateUrl(elementValue) {
    if (elementValue == "localhost") {
        return true;
    } else {
        var urlPattern = /^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
        return urlPattern.test(elementValue);
    }
}
function validateEmail(elementValue){  
    var emailPattern = /^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;  
    return emailPattern.test(elementValue);
}
function validatePhoneNumber(elementValue) {
    var phoneNumberPattern = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/;
    return phoneNumberPattern.test(elementValue);
}
function validateEID(elementValue) {
    var EIDPattern = /^[1-9]\d?-\d{7}$/;
    return EIDPattern.test(elementValue);
}
function validateSS(elementValue) {
    var SSPattern = /^\d{3}-\d{2}-\d{4}$/;
    return SSPattern.test(elementValue);
}
function validateZipCode(elementValue){
    var zipCodePattern = /^\d{5}$|^\d{5}-\d{4}$/;
    return zipCodePattern.test(elementValue);
}
function validateCCV(elementValue) {
    var digits = elementValue.length; //TODO for Visa, MC and Discover the length is 3. For AMEX it is 4. Update code to do proper length validation for type of card selected.
    var regExp = new RegExp('[0-9]{' + digits + '}');
    return (digits >= 3 && regExp.test(elementValue));
}
function validatePassword(elementValue) {
    //minimum of six letters, include at least one number.
    //no special characters or symbols required, but allowed.
    var length = elementValue.length;
    var regExp = new RegExp('[0-9]');  
    var containsNumber = regExp.test(elementValue);
    return (length > 5 && containsNumber);
}
