﻿//-----------------------------------------------------------------------------
// Validation.js
//
// General purpose form submission validation routines


//-----------------------------------------------------------------------------
// constants
var DEFAULT_COLOR = "#FFFFFF";
var WARNING_COLOR = "#FAED32";




//-----------------------------------------------------------------------------
// getBaseErrorMsg()
//
// Get the starting error message
//
function getBaseErrorMsg() {
    var msg = "";
    msg += "_____________________________________________________\n\n";
    msg += "The form was not submitted because of the following error(s).\n";
    msg += "Please correct these error(s) and re-submit.\n";
    msg += "_____________________________________________________\n\n";

    return msg;
}


//-----------------------------------------------------------------------------
// appendError()
//
// Append error messages destined for dialog box using this function
//
function appendError(msg, strErr) {
    return msg + "* " + strErr + "\n";

} // end of appendError()


//-----------------------------------------------------------------------------
// isEmpty()
//
function isEmpty(str) {
    // is it empty?
    if (str == null || str == "")
        return true;
    else
        return false;

} // end of isValidEmailAddress()


//-----------------------------------------------------------------------------
// isValidEmailAddress()
//
function isValidEmailAddress(strAdr) {
    // this is magic
    var regexp = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
    if (strAdr.match(regexp))
        return true;
    else
        return false;

} // end of isValidEmailAddress()


//-----------------------------------------------------------------------------
// isNumeric()
//
function isNumeric(s) {
    var i;
    for (i = 0; i < s.length; i++) {
        // ensure each character is a digit
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    return true;

} // end of isNumeric()

//-----------------------------------------------------------------------------
// isDecimal()
//Checks that an input string is a decimal number, with an optional +/- sign character.
function isDecimal(s) {
//    var isDecimal_re = /^\s*(\+|-)?((\d+(\.\d+)?)|(\.\d+))\s*$/;
    //    return String(s).search(isDecimal_re) != -1;

    var i;
    for (i = 0; i < s.length; i++) {
        // ensure each character is a digit
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) {
            if (c!="." && c!=",") 
            return false;
        }
    }
    return true;
} // end of isDecimal()

//-----------------------------------------------------------------------------
// hasLength()
//
// Returns true if the string passed is exactly as long as the length passed
//   in. Useful for zip codes and phone numbers.
//
function hasLength(str, len) {
    return str.length == len

} // end of hasLength()



//-----------------------------------------------------------------------------
// isValidPhoneHard()
//
// Strict NNN-NNN-NNNN style phone number validation:
//   - no field can be empty
//   - each field must contain digits
//   - each field must contain the proper number of digits
//
// Arguments: 
//   msg - a reference to an array containing one string, the dialog error 
//   pp1 - the form element representing the first triplet of the number
//   pp2 - the form element representing the second triplet of the number
//   pp3 - the form element representing the last quadruplet of the number
//
// Returns: 
//   boolean - true if the number is valid, else false
// 
function isValidPhoneHard(msg, pp1, pp2, pp3) {
    if (isEmpty(pp1.value) || isEmpty(pp2.value) || isEmpty(pp3.value)) {
        pp1.value = "";
        pp2.value = "";
        pp3.value = "";
        pp1.style.backgroundColor = WARNING_COLOR;
        pp2.style.backgroundColor = WARNING_COLOR;
        pp3.style.backgroundColor = WARNING_COLOR;
        msg[0] = appendError(msg[0], "A valid phone number, with area code, must be provided");
        return false;
    }
    else if (!isNumeric(pp1.value) || !isNumeric(pp2.value) || !isNumeric(pp3.value)) {
        pp1.value = "";
        pp2.value = "";
        pp3.value = "";
        pp1.style.backgroundColor = WARNING_COLOR;
        pp2.style.backgroundColor = WARNING_COLOR;
        pp3.style.backgroundColor = WARNING_COLOR;
        msg[0] = appendError(msg[0], "A phone number may only contain digits");
        return false;
    }
    else if (!hasLength(pp1.value, 3) || !hasLength(pp2.value, 3) || !hasLength(pp3.value, 4)) {
        pp1.value = "";
        pp2.value = "";
        pp3.value = "";
        pp1.style.backgroundColor = WARNING_COLOR;
        pp2.style.backgroundColor = WARNING_COLOR;
        pp3.style.backgroundColor = WARNING_COLOR;
        msg[0] = appendError(msg[0], "A phone number must be of the form NNN-NNN-NNNN");
        return false;
    }

    // looks ok
    return true;

} // end of isValidPhoneHard()

//-----------------------------------------------------------------------------
// isValidPhoneSoft()
//
// Lenient NNN-NNN-NNNN style phone number validation:
//   - all fields can be empty
//   - if not all empty, each field must contain digits
//   - if not all empty, each field must contain the proper number of digits
//
// Arguments: 
//   msg - a reference to an array containing one string, the dialog error 
//   pp1 - the form element representing the first triplet of the number
//   pp2 - the form element representing the second triplet of the number
//   pp3 - the form element representing the last quadruplet of the number
//
// Returns: 
//   boolean - true if the number is valid, else false
// 
function isValidPhoneSoft(msg, pp1, pp2, pp3) {
    if (!isEmpty(pp1.value) || !isEmpty(pp2.value) || !isEmpty(pp3.value)) {
        if (!isNumeric(pp1.value) || !isNumeric(pp2.value) || !isNumeric(pp3.value)) {
            pp1.value = "";
            pp2.value = "";
            pp3.value = "";
            pp1.style.backgroundColor = WARNING_COLOR;
            pp2.style.backgroundColor = WARNING_COLOR;
            pp3.style.backgroundColor = WARNING_COLOR;
            msg[0] = appendError(msg[0], "A phone number may only contain digits");
            return false;
        }
        else if (!hasLength(pp1.value, 3) || !hasLength(pp2.value, 3) || !hasLength(pp3.value, 4)) {
            pp1.value = "";
            pp2.value = "";
            pp3.value = "";
            pp1.style.backgroundColor = WARNING_COLOR;
            pp2.style.backgroundColor = WARNING_COLOR;
            pp3.style.backgroundColor = WARNING_COLOR;
            msg[0] = appendError(msg[0], "A phone number must be of the form NNN-NNN-NNNN");
            return false;
        }
    }

    // looks ok
    return true;

} // end of isValidPhoneSoft()


//-----------------------------------------------------------------------------
// isValidZipHard()
//
// Lenient NNNNN-NNNN style zip code number validation:
//   - first field (quintet) must be filled
//   - if second field is filled (quartet), then first must be filled
//   - only digits are allowed
//   - each field must contain the proper number of digits
//
// Arguments: 
//   msg - a reference to an array containing one string, the dialog error 
//   zip1 - the form element representing the first triplet of the number
//   zip2 - the form element representing the second triplet of the number
//
// Returns: 
//   boolean - true if the number is valid, else false
// 
function isValidZipHard(msg, zip1, zip2) {
    // first field must be filled
    if (isEmpty(zip1.value)) {
        zip1.value = "";
        zip2.value = "";
        zip1.style.backgroundColor = WARNING_COLOR;
        zip2.style.backgroundColor = WARNING_COLOR;
        msg[0] = appendError(msg[0], "A zip code must be provided");
        return false;
    }
    else {
        if (!isNumeric(zip1.value) || !hasLength(zip1.value, 5)) {
            zip1.value = "";
            zip2.value = "";
            zip1.style.backgroundColor = WARNING_COLOR;
            zip2.style.backgroundColor = WARNING_COLOR;
            msg[0] = appendError(msg[0], "The zipcode must be five digits long");
            return false;
        }

        if (!isEmpty(zip2.value)) {
            if (!isNumeric(zip2.value) || !hasLength(zip2.value, 4)) {
                zip1.value = "";
                zip2.value = "";
                zip1.style.backgroundColor = WARNING_COLOR;
                zip2.style.backgroundColor = WARNING_COLOR;
                msg[0] = appendError(msg[0], "The zipcode suffix must be four digits long");
                return false;
            }
        }
    }

    // must be ok
    return true;

} // end of isValidZipHard()


//-----------------------------------------------------------------------------
// getRadioValue()
//
function getRadioValue(r) {
    var rad_val = null;
    var rad = document.getElementsByName(r)

    for (var i = 0; i < rad.length; i++) {
        if (rad[i].checked) {
            rad_val = rad[i].value;
        }
    }
    
    return rad_val;
}

//-----------------------------------------------------------------------------
// replaceEmpty()
//
function replaceEmpty(str, newStr) {
    // is it empty?
    if (str == null || str == "") {
        return newStr;
    }
    else {
        return str;
    }
}

// function CurrencyFormatted()
function CurrencyFormatted(amount) {
    var i = parseFloat(amount);
    if (isNaN(i)) { i = 0.00; }
    var minus = '';
    if (i < 0) { minus = '-'; }
    i = Math.abs(i);
    i = parseInt((i + .005) * 100);
    i = i / 100;
    s = new String(i);
    if (s.indexOf('.') < 0) { s += '.00'; }
    if (s.indexOf('.') == (s.length - 2)) { s += '0'; }
    s = minus + s;
    return s;
}
// end of function CurrencyFormatted()

function CommaFormatted(amount) {
    var delimiter = ","; // replace comma if desired
    var a = amount.split('.', 2)
    var d = a[1];
    var i = parseInt(a[0]);
    if (isNaN(i)) { return ''; }
    var minus = '';
    if (i < 0) { minus = '-'; }
    i = Math.abs(i);
    var n = new String(i);
    var a = [];
    while (n.length > 3) {
        var nn = n.substr(n.length - 3);
        a.unshift(nn);
        n = n.substr(0, n.length - 3);
    }
    if (n.length > 0) { a.unshift(n); }
    n = a.join(delimiter);
    if (d.length < 1) { amount = n; }
    else { amount = n + '.' + d; }
    amount = minus + amount;
    return amount;
}
// end of function CommaFormatted()


function CheckNum(n) {
    if (isNaN(n.value)) {
        alert("Invalid entry.  Values must be numeric.");
        n.focus()
        return false;
    }
    else return true;
}