// $Id: validation.js 27 2011-11-10 17:27:12Z erik $

// trim zeros
function trimZeroes(theField) {
    var num;
    if (theField.value.length == 2 && theField.value.charAt(0) == "0") {
        num = theField.value.charAt(1);
        theField.value = num;
    }
}

// checks for valid email address formatting
function isValidLogin(theField) {
    theField.value = theField.value.toLowerCase();

    //ensure @ and .
    if (theField.value.indexOf("@", 0) == -1 || theField.value.indexOf(".", 0) == -1) { return false; }

    //ensure no illegal characters
    var bad = " :;'#~`,()$^&*!{}[]"
    for (i = 1; i < theField.value.length; i++) {
        if (bad.indexOf(theField.value.charAt(i)) != -1) {
            return false;
        }
    }
    return true;
}

// ensure valid login
function validateLogin(theField) {
    //generates error message
    if (!isValidLogin(theField)) {
        alert('The field "' + theField.vName + '" requires an email address \nin the form user@domain.com');
        return false;
    }
    return true;
}

// checks for valid email address formatting
function isValidEmail(theField) {
    theField.value = theField.value.toLowerCase();

    //ensure @ and .
    if (theField.value.indexOf("@", 0) == -1 || theField.value.indexOf(".", 0) == -1) { return false; }

    //ensure valid domain
    var theDomain = theField.value.substring(theField.value.indexOf('@') + 1, theField.value.length);
    if ((theDomain == 'fastfloors.com') || (theDomain == 'catalfamogallery.com') || (theDomain == 'tonger.com')) { return false; }

    //ensure no illegal characters
    var bad = " :;'#~`,()$^&*!{}[]<>!%?|\\/"
    for (i = 1; i < theField.value.length; i++) {
        if (bad.indexOf(theField.value.charAt(i)) != -1) {
            return false;
        }
    }
    return true;
}

// checks for valid email
function validateEmail(theField) {
    //generates error message
    if (!isValidEmail(theField)) {
        alert('The field "' + theField.vName + '" requires an email address \nin the form user@domain.com');
        return false;
    }
    return true;
}

// checks for valid URL formatting, requiring http://...
function isValidURL(theField) {
    var bad = " ;'@\\"
    if (theField.value.indexOf("http://", 0) == -1 || theField.value.indexOf(".", 0) == -1) {
        return false;
    }
    for (i = 1; i < theField.value.length; i++) {
        if (bad.indexOf(theField.value.charAt(i)) != -1) {
            return false;
        }
    }
    return true;
}

// validates URL
function validateURL(theField) {
    //generates error message
    if (!isValidURL(theField)) {
        alert('The field "' + theField.vName + '" requires a URL \nin the form http://www.mycompany.com');
        theField.value = '';
        return false;
    }
    return true;
}

// checks for valid URL formatting for relative links
function isValidURL2(theField) {
    var bad = " ;'@\\"
    if (theField.value.indexOf("/", 0) == -1) {
        return false;
    }
    for (i = 1; i < theField.value.length; i++) {
        if (bad.indexOf(theField.value.charAt(i)) != -1) {
            return false;
        }
    }
    return true;
}

// validates relative url
function validateURL2(theField) {
    //generates error message
    if (!isValidURL(theField)) {
        alert('The field "' + theField.vName + '" requires a relative URL \nsuch as \'/folder/file.htm\'');
        theField.value = '';
        return false;
    }
    return true;
}

// checks for valid numeric
function validateNumeric(theField) {
    var tmp = fnCleanDecimal(theField.value);
    if (isNaN(parseFloat(tmp))) {
        alert('The field "' + theField.vName + '" requires a number.');
        theField.value = 0;
        return false
    }
    theField.value = tmp;
    return true;
}

// checks for valid integer
function validateInteger(theField) {
    var tmp = fnCleanNumber(theField.value);
    if (isNaN(parseFloat(tmp))) {
        alert('The field "' + theField.vName + '" requires an integer.');
        theField.value = 0;
        return false
    }
    theField.value = tmp;
    return true;
}

// checks for whole number
function validateWholeNumber(theField) {
    var tmp = (theField.value);
    var numbers = "0123456789";
    for (q = 0; q < tmp.length; q++) {
        if (numbers.indexOf(tmp.charAt(q)) == -1) {
            alert('The field "' + theField.vName + '" requires a whole number.');
            theField.value = 0;
            return false
        }
    }
    theField.value = tmp;
    return true;
}

// checks for valid US phone number
function validatePhone(dataField) {
    var format = "(###) ###-####";
    var tmp = dataField.value;
    var tmp3 = fnCleanNumber(tmp)
    if (tmp3.charAt(0) == 1) {
        tmp3 = tmp3.substring(1, tmp3.length);
        dataField.value = tmp3;
    }
    if (tmp3.length == 10) {
        fnFormat(dataField, format);
    }
    else {
        alert("Please Enter Phone Number in This Format (###) ###-####");
        dataField.value = '';
    }
}

function isValidPhone(dataField) {
    // checks for valid US phone number
    var format = "(###) ###-####";
    var tmp = dataField.value;
    var tmp3 = fnCleanNumber(tmp)
    if (tmp3.charAt(0) == 1) {
        tmp3 = tmp3.substring(1, tmp3.length);
        dataField.value = tmp3;
    }
    if (tmp3.length == 10) {
        fnFormat(dataField, format);
        return true;
    }
    else {
        return false;
    }
}

function validateZipCode(dataField) {
    var format = "#####-####";
    var tmp = new String(dataField.value);
    if (true) {

        if ((tmp.length == 9) && (tmp.indexOf("-") < 0)) {
            // check the zip if length=9
            for (i = 0; i < tmp.length; i++) {

                if ((tmp.charAt(i) < "0") || (tmp.charAt(i) > "9")) {
                    alert("Please Enter the Zip Code in the format ##### or #####-####");
                    dataField.value = '';
                    return false;
                }
            }
            // put in the dash
            fnFormat(dataField, format);
            return true;
        }
        else if ((tmp.length == 10) && (tmp.charAt(5) != "-")) {
            // check the zip if 10 long
            alert("Please Enter the Zip Code in the format ##### or #####-####");
            dataField.value = '';
            return false;
        }
        else if (tmp.length < 5 || tmp.length > 5 && tmp.length < 10 || tmp.length > 10) {
            // check the zip if not 5 long, or 10 long
            alert("Please Enter the Zip Code in the format ##### or #####-####");
            dataField.value = '';
            return false;
        }

        for (i = 0; i < tmp.length; i++) {
            if (((tmp.charAt(i) < "0") || (tmp.charAt(i) > "9")) && !((tmp.charAt(i) == "-") && (i == 5))) {
                alert("Please Enter the Zip Code in the format ##### or #####-####");
                dataField.value = '';
                return false;
            }
        }
    }
}

function isValidZip(dataField) {
    // checks if valid zip code
    var format = "#####-####";
    var Can_format = "######";
    var tmp = new String(dataField.value);

    // check the zip if length=9
    if ((tmp.length == 9) && (tmp.indexOf("-") < 0)) {
        for (i = 0; i < tmp.length; i++) {
            if ((tmp.charAt(i) < "0") || (tmp.charAt(i) > "9")) {
                return false;
            }
        }
        // put in the dash
        fnFormat(dataField, format);
        return true;
    }

    // check the zip if 10 long
    else if ((tmp.length == 10) && (tmp.charAt(5) != "-")) {
        return false;
    }

    // Check Canadian Zip
    else if ((tmp.length == 6) && (tmp.indexOf("-") < 0)) {
        var ZipValue = /^\D{1}\d{1}\D{1}\-?\d{1}\D{1}\d{1}$/;
        if (!ZipValue.test(tmp)) {
            return false;
        }
        // put in the dash
        fnFormat(dataField, Can_format);
        return true;
    }
    else if (tmp.length == 7) {
        if ((tmp.indexOf("-") != 3) && (tmp.indexOf(" ") != 3)) {
            return false;
        }
        else {
            var ZipValue = /^\D{1}\d{1}\D{1}\-?\d{1}\D{1}\d{1}$/;
            if ((tmp.indexOf(" ") == 3) || (tmp.indexOf("-") == 3)) {
                tmp = tmp.substring(0, 3) + tmp.substring(4);
                dataField.value = tmp;
            }
            if (!ZipValue.test(tmp)) {
                return false;
            }
            fnFormat(dataField, Can_format);
            return true;
        }
    }

    // check the zip if not 5 long, or 10 long
    else if (tmp.length < 5 || tmp.length > 5 && tmp.length < 10 || tmp.length > 10) {
        return false;
    }

    if (tmp.length != 7) {
        for (i = 0; i < tmp.length; i++) {
            if (((tmp.charAt(i) < "0") || (tmp.charAt(i) > "9")) && !((tmp.charAt(i) == "-") && (i == 5))) {
                return false;
            }
        }
    }
    return true;
}

function fnFormat(string, format) {
    // formats string (used by zipcode, etc.)
    var string2 = string.value;
    var tmp = "";
    if (format == "######") {
        tmp = string2;
    }
    else// if (format=="#####-####")
    {
        tmp = fnCleanNumber(string2);
    }
    var newstring = "";

    for (i = 0, j = 0; i < format.length; i++) {
        if (format.charAt(i) == "#") {
            newstring += tmp.charAt(j);
            j++;
        }
        else {
            newstring += format.charAt(i);
        }
        string.value = newstring.toUpperCase();
    }
}

//clean integer
function fnCleanNumber(string) {
    var numbers = "0123456789";
    var newstring = "";
    for (i = 0; i < string.length; i++) {
        if (numbers.indexOf(string.charAt(i)) == -1) {
        }
        else {
            newstring += string.charAt(i);
        }
    }
    return (newstring);
}

//clean decimal
function fnCleanDecimal(string) {
    var numbers = "0123456789.";
    var newstring = "";
    for (i = 0; i < string.length; i++) {
        if (numbers.indexOf(string.charAt(i)) == -1) {
        }
        else {
            newstring += string.charAt(i);
        }
    }
    return (newstring);
}

//clean negative integer
function fnCleanNegInteger(string) {
    var numbers = "0123456789-";
    var newstring = "";
    for (i = 0; i < string.length; i++) {
        if (numbers.indexOf(string.charAt(i)) == -1) {
        }
        else {
            newstring += string.charAt(i);
        }
    }
    return (newstring);
}

function isBlank(s, lf) {
    // utility function
    // returns true if contains only whitespace characters
    if (s == "undefined") return true;

    var tmpbad = " \t";
    if (lf == false) tmpbad += "\r\n";

    for (var i = 0; i < s.length; i++) {
        if (tmpbad.indexOf(s.charAt(i)) == -1) return false
    }
    return true;
}

function validateForm(f, errs) {
    // carry out form validation
    // displays errors
    // returns true if everything is ok

    var msg;
    var empty_fields = "";
    var errors = "";
    var value = 0;

    if (!((errs == null) || (errs == ""))) {
        errors = errors + errs;
    }

    for (var i = 0; i < f.length; i++) {
        var e = f.elements[i];
        var lf = e.type == "textarea";
        var req = (e.vReq == "true") ? (e.display != "none") : false;
        if (e.vName != '' && e.vName != undefined) {

            if ((e.type == "text") || (e.type == "textarea") || (e.type == "select-one") || (e.type == "radio") || (e.type == "password")) {
                value = e.value;

                //scrub string for invalid characters
                if (((e.type == "text") || (e.type == "textarea")) && (!((value == null) || (value == "") || isBlank(value, lf)))) {
                    var tmpvalue = value;
                    var tmpallowed = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%&*()[],.?/-_\x3d ";
                    if (e.type == "textarea") tmpallowed += ":;'<>\r\n{}";
                    var tmpclean = "";
                    for (tmpi = 0; tmpi < tmpvalue.length; tmpi++) {
                        if (tmpallowed.indexOf(tmpvalue.charAt(tmpi)) == -1) { }
                        else { tmpclean += tmpvalue.charAt(tmpi); }
                    }
                    e.value = tmpclean;
                }

                //first check if the field is empty
                if (eval(req) && ((value == null) || (value == "") || isBlank(value, lf)) && (!(e.type == "select-one"))) {
                    empty_fields += "\n         " + e.vName;
                    continue;
                }

                //Check for email addresses
                if ((e.vType == "email") && (!((value == null) || (value == "") || isBlank(value, lf)))) {
                    if (!(isValidEmail(e)))
                        errors += " - Please enter a valid email address in " + e.vName + " (i.e., yourname@yourcompany.com).\n";
                }

                //Check for URL requiring http://
                if ((e.vType == "URL") && (!((value == null) || (value == "") || isBlank(value, lf)))) {
                    if (!(isValidURL(e)))
                        errors += " - Please enter a valid URL in " + e.vName + " (i.e., http://www.yourcompany.com).\n";
                }

                //Check for URL2: relative URLs
                if ((e.vType == "URL2") && (!((value == null) || (value == "") || isBlank(value, lf)))) {
                    if (!(isValidURL2(e)))
                        errors += " - Please enter a valid URL in " + e.vName + " (i.e., /folder/file.htm).\n";
                }

                //Check for phone number
                if ((e.vType == "phone") && (!((value == null) || (value == "") || isBlank(value, lf)))) {
                    if (!(isValidPhone(e)))
                        errors += " - Please enter a valid phone number in " + e.vName + ".\n";
                }

                //Check for zipcode
                if ((e.vType == "zipcode") && (!((value == null) || (value == "") || isBlank(value, lf)))) {
                    if (!(isValidZip(e)))
                        errors += " - Please enter a valid zipcode in " + e.vName + " (i.e., 30332 or 30332-1234 or A1S-2D3 or A1S 2D3).\n";
                }

                //check for IP address
                if ((e.vType == "ip") && ((e.vMin != null) || (e.vMax != null))) {

                    if ((e.type == "text") || (e.type == "textarea")) {
                        value = parseFloat(e.value)
                    } else if (e.type == "select-one") {
                        value = parseFloat(e.selectedIndex)
                    }

                    var v = value;

                    if (isNaN(v) ||
						((e.vMin != null) && (v < e.vMin)) ||
						((e.vMax != null) && (v > e.vMax))) {

                        errors += " - The field " + e.vName + " must be an IP address in which each octet is between 0 and 255.\n";
                    }
                }

                //Now check for fields that are numeric
                if (eval(req) || (!((value == null) || (value == "") || isBlank(value, lf)))) {

                    //check for integer
                    if ((e.vType == "integer") && (!((e.type == "select-one") || (e.type == "radio")))) {
                        //check integer if min/max not set
                        prob = '0';
                        tmp = (e.value);
                        numbers = "0123456789";
                        for (q = 0; q < tmp.length; q++) {
                            if (numbers.indexOf(tmp.charAt(q)) == -1) {
                                prob = '1';
                            }
                        }
                        if (prob == '1') {
                            if ((e.vName == '') || (e.vName == 'undefined')) { e.vName = e.name; }
                            errors += " - " + e.vName + " must be an integer.\n";
                        }
                        prob = '0';
                    }
                    //check for decimal value
                    if ((e.vType == "numeric") && (!((e.type == "select-one") || (e.type == "radio")))) {
                        //check numeric if min/max not set
                        prob = '0';
                        tmp = (e.value);
                        numbers = "0123456789.";
                        var cntNumDecimals = 0;
                        for (q = 0; q < tmp.length; q++) {
                            if (numbers.indexOf(tmp.charAt(q)) == -1) {
                                prob = '1';
                            }
                            if (tmp.charAt(q) == ".") {
                                cntNumDecimals += 1;
                            }
                        }
                        if ((prob == '1') || (cntNumDecimals > 1)) {
                            errors += " - " + e.vName + " must be numeric.\n";
                        }
                        prob = '0';
                    }
                    //check for negative integer
                    if ((e.vType == "integer2") && (!((e.type == "select-one") || (e.type == "radio")))) {
                        //check integer if min/max not set
                        var q, tmp, prob;
                        prob = '0';
                        tmp = (e.value);
                        var numbers = "0123456789-";
                        for (q = 0; q < tmp.length; q++) {
                            if (numbers.indexOf(tmp.charAt(q)) == -1) {
                                prob = '1';
                            }
                        }
                        if (prob == '1') {
                            errors += " - " + e.vName + " must be an integer.\n";
                        }
                        prob = '0';
                    }
                    //check min/max
                    if ((e.vType == "numeric") || (e.vType = "integer")) {
                        var nMin = isNaN(e.vMin) ? 0 : eval(e.vMin);
                        var nMax = isNaN(e.vMax) ? 0 : eval(e.vMax);

                        if (nMin > 0 || nMax > 0) {
                            var blnPicklistAlert = "false";
                            var valueBlank = 1;

                            if ((e.type == "text") || (e.type == "textarea")) {
                                value = parseFloat(e.value);
                            }
                            else if (e.type == "select-one") {
                                value = parseFloat(e.selectedIndex);
                                valueBlank = e[e.selectedIndex].value;
                            }

                            var v = value;
                            if (isNaN(v) || ((nMin > 0) && (v < nMin)) || ((nMax > 0) && (v > nMax))) {
                                errors += " - The field " + e.vName;
                                if (e.type == "select-one") {
                                    if (nMin > 0) {
                                        errors += " must have a value selected";
                                        blnPicklistAlert = "true";
                                    }
                                }
                                else {
                                    errors += " must be a number";
                                    if (nMax > 0 && nMin > 0) {
                                        errors += " between " + e.vMin + " and " + e.vMax;
                                    }
                                    else if (nMin > 0) {
                                        errors += " greater than " + e.vMin;
                                    }
                                    else if (nMax > 0) {
                                        errors += " less than " + e.vMax;
                                    }
                                }
                                errors += ".\n";
                            }
                        }
                        //hack for StateProvince
                        if ((!(eval(blnPicklistAlert))) && eval(req) && (eval(e.vMin) > 0) && (valueBlank == '000') && (e.type == "select-one")) {
                            errors += " - The field " + e.vName + " must have a value selected.\n";
                        }
                    }
                }
            } //end if e.type
        } //end if e.vName != undefined
    } //end for

    // display errors
    if (!empty_fields && !errors) {
        if (f.customValidation) {
            return (f.customValidation(f))
        }
        else {
            return true;
        }
    }

    msg = "_______________________________________________\n\n";
    msg += "   P L E A S E    N O T E:\n";
    msg += "   This form contains errors. Please correct\n";
    msg += "   the errors and then re-submit the form.\n";
    msg += "_______________________________________________\n\n";

    if (empty_fields) {
        msg += " - The following required fields are empty:" + empty_fields + "\n";
        if (errors) msg += "\n";
    }

    msg += errors;
    alert(msg);
    return false;
    //	return confirm(msg+"\nSave anyway?");
}

function onFormatField(e) {
    // format the data in the field
    var dataType = new String(e.vType);
    var controlType = new String(e.type);
    var lf = e.type = "textarea" ? true : false;

    if (e.vMaxsize != null) {
        if (e.value.length > e.vMaxsize) {
            alert("The value in " + e.vName + " is too long and will be truncated.");
            e.value = e.value.slice(0, e.vMaxsize - 1)
        }
    }

    // if it is a text input....
    if ((controlType.toUpperCase() == "TEXT") && (!isBlank(e.value, lf))) {

        if (dataType.toUpperCase() == "PHONE") {
            fnPhoneNo(e);
        } else if (dataType.toUpperCase() == "ZIPCODE") {
            fnZipCode(e);
        } else if (dataType.toUpperCase() == "STRING") {
            e.value = e.value;
        } else if (dataType.toUpperCase() == "DOMAINNAME") {
            e.value = e.value;
        } else if (dataType.toUpperCase() == "NUMERIC") {
            validateNumeric(e);
        } else if (dataType.toUpperCase() == "IP") {
            validateNumeric(e);
        } else if (dataType.toUpperCase() == "LOGIN") {
            validateLogin(e);
        } else if (dataType.toUpperCase() == "EMAIL") {
            validateEmail(e);
        }
    }
}
