﻿/* 
    Global Form Validation Routines for BDK
    
    A two-stage process that uses a "validation gate" (input type-level validation), and data-specific validation routines, patching into
    a RESX file for aggregating any error codes and messages to return to the presentation layer.
    
    Form inputs covered: INPUT, SELECT, and TEXTAREA.
    
    INPUT Convention: Type and Class (class="context_required" where the first part indicates the context of the field, i.e. 'phone') 
    TEXTAREA & SELECT Conventions: Class (class="context_required" where the first part indicates the context of the field, i.e. 'phone')
*/

$(document).ready(function() {
    var context = false;
    var type = '';
    var required = false;
    var errors = []; // Error container array.
});

    function isdefined(variable) {
        return (typeof (window[variable]) == "undefined") ? false : true;
    }

    // Validation Gate: SELECT & TEXTAREA
    function validateOnFocus(containingElement) {
        $(containingElement + " textarea").live('focusout', function() {
            if (($(this).attr('class').split("_")[0] == 'required' || $(this).attr('class').split("_")[1] == 'required') && $(this).val().length == 0) {
                $(this).parents(".errorContainer").children(".error").text("This is a required field.");
            } else {
                $(this).parents(".errorContainer").children(".error").html("");
            }

            if ((isdefined(eval("'" + $(this).attr("class").split("_")[0] + "'")) == true) && (typeof eval($(this).attr('class').split("_")[0]) == 'function')) {
                eval($(this).attr('class').split("_")[0])($(this), $(this).val());
            }
        });

        $(containingElement + " select").focusout(function() {
            if ($(this).attr('class').split("_")[0] == 'required' || $(this).attr('class').split("_")[1] == 'required') {
                if ($(this).children("option:selected").val() == '999' || $(this).children("option:selected").val() == '') {
                    $(this).parents(".errorContainer").children(".error").html("This is a required field.");
                } else {
                    $(this).parents(".errorContainer").children(".error").html("");
                }
            }

            if ((isdefined(eval("'" + $(this).attr("class").split("_")[0] + "'")) == true) && (typeof eval($(this).attr('class').split("_")[0]) == 'function')) {
                eval($(this).attr('class').split("_")[0])($(this), $(this).val());
            }
        });

        // Validation Gate: INPUT

        $(containingElement + " input[type=text]").focusout(function() {
            if (($(this).attr('class').split("_")[0] == 'required' || $(this).attr('class').split("_")[1] == 'required') && $(this).val().length == 0) {
                $(this).parents(".errorContainer").children(".error").html("This is a required field.");
            } else {
                $(this).parents(".errorContainer").children(".error").html("");
            }

            if ((isdefined(eval("'" + $(this).attr("class").split("_")[0] + "'")) == true) && (typeof eval($(this).attr('class').split("_")[0]) == 'function')) {
                eval($(this).attr('class').split("_")[0])($(this), $(this).val());
            }
        });

        $(containingElement + " input[type=checkbox]").click(function() {
            if (($(this).attr('class').split("_")[0] == 'required' || $(this).attr('class').split("_")[1] == 'required') && (!this.checked)) {
                $(this).parents(".errorContainer").children(".error").html("This is a required field.");
            } else {
                $(this).parents(".errorContainer").children(".error").html("");
            }

            if ((isdefined(eval("'" + $(this).attr("class").split("_")[0] + "'")) == true) && (typeof eval($(this).attr('class').split("_")[0]) == 'function')) {
                eval($(this).attr('class').split("_")[0])($(this), $(this).val());
            }
        });

        $(containingElement + " input[type=password]").focusout(function() {
            if (($(this).attr('class').split("_")[0] == 'required' || $(this).attr('class').split("_")[1] == 'required') && $(this).val().length == 0) {
                $(this).parents(".errorContainer").children(".error").html("This is a required field.");
            } else {
                $(this).parents(".errorContainer").children(".error").html("");
            }

            if ((isdefined(eval("'" + $(this).attr("class").split("_")[0] + "'")) == true) && (typeof eval($(this).attr('class').split("_")[0]) == 'function')) {
                eval($(this).attr('class').split("_")[0])($(this), $(this).val());
            }
        });      

//        $(containingElement + " input[type=radio]").focusout(function() {
//            if ($("input[type=radio]").val().length == 0) {
//                $(this).after("<div style='float: right;'><p>This is a required field.</p></div>");
//            }

//            if ((isdefined(eval("'" + $(this).attr("class").split("_")[0] + "'")) == true) && (typeof eval($(this).attr('class').split("_")[0]) == 'function')) {
//                eval($(this).attr('class').split("_")[0])($(this), $(this).val());
//            }
//        });

        $(containingElement + " input[type=file]").focusout(function() {
            if (($(this).attr('class').split("_")[0] == 'required' || $(this).attr('class').split("_")[1] == 'required') && $(this).val().length == 0) {
                $(this).after("<div style='float: right;'><p>This is a required field.</p></div>");
            }

            if ((isdefined(eval("'" + $(this).attr("class").split("_")[0] + "'")) == true) && (typeof eval($(this).attr('class').split("_")[0]) == 'function')) {
                eval($(this).attr('class').split("_")[0])($(this), $(this).val());
            }
        });

        $(containingElement + "input[type=password]").focusout(function() {
            if ($(this).val().length < 6) {
                $(this).parents(".errorContainer").children(".error").html("This is a required field.");
            } else {
                $(this).parents(".errorContainer").children(".error").html("");
            }

            if ((isdefined(eval("'" + $(this).attr("class").split("_")[0] + "'")) == true) && (typeof eval($(this).attr('class').split("_")[0]) == 'function')) {
                eval($(this).attr('class').split("_")[0])($(this), $(this).val());
            }
        });
    }

    // Data-Specific Validation Routines

    function addressValidation() {
            var addressValidationErrors = 0;
            $(".addressValidation").each(
                function(i) {
                    if ($(this).val() == "") {
                        addressValidationErrors++;
                        //alert($(this).attr("id"));
                    }
                }
            );
                if (addressValidationErrors > 0) {
                    $(".addressValidationError").html("Address 1, City, State and Zip are required fields.");
                }
        }
    
    function phone(element, val) {
        // Accommodates phone number formats w/optional ext.
        // Expand to a switch/case format if overseas countries are added as cultures.
        var patt = /^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$/;
        if (patt.test(val) == false) {
            $(this).parents(".errorContainer").children(".error").html("This is a required field.");
            return 1;
        } else {
        $(this).parents(".errorContainer").children(".error").html("");
            return 0;
        }
    }

    function email(element, val) {
        // Handles email addresses inc 4-char TLDs and limited special chars in the name (pre-@).
        var patt = /^[a-zA-Z0-9._+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
        if (patt.test(val) == false) {
            $(element).parents(".errorContainer").children(".error").html("Please enter a valid email address.");
            return 1;
        } else {
            $(element).parents(".errorContainer").children(".error").html("");
            return 0;
        }
    }

    function date(element, val) {
        switch (culture) {
            case "en-US":
                var patt = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/;
                if (patt.test(val) == false) $(this).after("<div style='float: right;'><p>Please enter a valid date in the following format(s): MM/DD/YYYY or MM-DD-YYYY.</p></div>");
                break;
            case "en-CA":
                var patt = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/;
                if (patt.test(val) == false) $(this).after("<div style='float: right;'><p>Please enter a valid date in the following format(s): MM/DD/YYYY or MM-DD-YYYY.</p></div>");
                break;
            case "fr-CA":
                var patt = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/;
                if (patt.test(val) == false) $(this).after("<div style='float: right;'><p>Please enter a valid date in the following format(s): MM/DD/YYYY or MM-DD-YYYY.</p></div>");
                break;
            case "es-MX":
                var patt = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/;
                if (patt.test(val) == false) $(this).after("<div style='float: right;'><p>Please enter a valid date in the following format(s): DD/MM/YYYY or DD-MM-YYYY.</p></div>");
                break;
            default:
        }
    }

    function zipcode(element, val) {
        switch (culture) {
            case "en-US":
                var patt = /^\d{5}([\-]\d{4})?$/; // Covers ZIP+4
                if (patt.test(val) == false) $(this).after("<div style='float: right;'><p>Please enter a valid ZIP code.</p></div>");
                break;
            case "en-CA":
                var patt = /^([ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ])\ {0,1}(\d[ABCEGHJKLMNPRSTVWXYZ]\d)$/;
                if (patt.test(val) == false) $(this).after("<div style='float: right;'><p>Please enter a valid postal code.</p></div>");
                break;
            case "fr-CA":
                var patt = /^([ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ])\ {0,1}(\d[ABCEGHJKLMNPRSTVWXYZ]\d)$/;
                if (patt.test(val) == false) $(this).after("<div style='float: right;'><p>Please enter a valid postal code.</p></div>");
                break;
            case "es-MX":
                var patt = /^\d{5}?$/; // Max. 5 Digits
                if (patt.test(val) == false) $(this).after("<div style='float: right;'><p>Please enter a valid postal code.</p></div>");
                break;
            default:
        }
    }

    function wordfilter(element, val) {
    }

    function modelnumber(element, val) {
    }

    function serialnumber(element, val) {
    }

    function namesRequired(element, val) {
        if (val.length > 0) {
            $(element).parents(".errorContainer").children(".error").html("");
            return 0;
        } else {
            $(element).parents(".errorContainer").children(".error").html("This is a required field.");
            return 1;
            
        }
    }

    function imageupload(element, val) {
        var match = false;
        $.each(["jpg", "png", "gif"], function(index, value) {
            if (val.split(".")[1].toLowerCase() == value) {
                match = true;
                return false; // Break the loop.
            }
        });
        if (match == false) {
            $(this).after("<div style='float: right;'><p>Please upload an image in any of the following formats: JPG, GIF, or PNG.</p></div>");
        }
    }

    function fileupload(element, val) {
        var match = false;
        $.each(["pdf", "zip", "txt"], function(index, value) {
            if (val.split(".")[1].toLowerCase() == value) {
                match = true;
                return false; // Break the loop.
            }
        });
        if (match == false) $(this).after("<div style='float: right;'><p>Please upload an image in any of the following formats: *Name Formats Here.*</p></div>");
    }

    // Error Message Generation, Formatting, and Return Path

    function loginHeader() {
        /*
        var emailHeader = $("#txtEmail").val();
        var passwordHeader = $("#txtPassword").val();
        var patt = /^[a-zA-Z0-9._+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
        if (patt.test(emailHeader) == false || passwordHeader.length < 6) {
        $("#myBlackAndDeckerLoginFormContainer .headerError").html("Both fields are required.");
        } else {
        $("#myBlackAndDeckerLoginFormContainer .headerError").html("");
        }
        */

    }

    function validateOnSubmit(containingElement) {//This function should be called during the submit process of a form and pass in a jquery identifier
        var currentErrors = 0;

        $(containingElement + " TEXTAREA").each( //We will then loop through the element finding elements that are required
            function(i) {
                if (($(this).attr('class').split("_")[0] == 'required' || $(this).attr('class').split("_")[1] == 'required') && $(this).val().length == 0) {
                    if ($(this).attr('id') != "pluckStepBody_STEP_NUM") {
                        $(this).parents(".errorContainer").children(".error").text("This is a required field.");
                        currentErrors++;
                    }
                }

                if ((isdefined(eval("'" + $(this).attr("class").split("_")[0] + "'")) == true) && (typeof eval($(this).attr('class').split("_")[0]) == 'function')) {
                    currentErrors = currentErrors + eval($(this).attr('class').split("_")[0])($(this), $(this).val());
                }
            }
        );
            
        $(containingElement + " select").each( //We will then loop through the element finding elements that are required
            function(i) {
                if ($(this).attr('class').split("_")[0] == 'required' || $(this).attr('class').split("_")[1] == 'required') {
                    if ($(this).children("option:selected").val() == '999' || $(this).children("option:selected").val() == '') {
                        $(this).parents(".errorContainer").children(".error").html("This is a required field.");
                        currentErrors++;
                    }

                    if ((isdefined(eval("'" + $(this).attr("class").split("_")[0] + "'")) == true) && (typeof eval($(this).attr('class').split("_")[0]) == 'function')) {
                        eval($(this).attr('class').split("_")[0])($(this), $(this).val());
                    }
                }
            }
        );

            $(containingElement + " input[type=text]").each( //We will then loop through the element finding elements that are required
            function(i) {
                if (($(this).attr('class').split("_")[0] == 'required' || $(this).attr('class').split("_")[1] == 'required') && $(this).val().length == 0) {
                    if ($(this).attr('id') != "pluckStepTitle_STEP_NUM") {
                        $(this).parents(".errorContainer").children(".error").html("This is a required field.");
                        currentErrors++;
                    }


                    if ((isdefined(eval("'" + $(this).attr("class").split("_")[0] + "'")) == true) && (typeof eval($(this).attr('class').split("_")[0]) == 'function')) {
                        currentErrors = currentErrors + eval($(this).attr('class').split("_")[0])($(this), $(this).val());
                    }
                }
            }
        );

            $(containingElement + " input[type=radio]").each( //We will then loop through the element finding elements that are required
            function(i) {
                if (($(this).attr('class').split("_")[0] == 'required' || $(this).attr('class').split("_")[1] == 'required')) {
                    var currentName = $(this).attr("name");
                    if (!$("input[@name='name']:checked").val()) {
                        $(this).parents(".errorContainer").children(".error").html("This is a required field.");
                        currentErrors++;
                    } else {
                        $(this).parents(".errorContainer").children(".error").html("");
                    }
                }

                if ((isdefined(eval("'" + $(this).attr("class").split("_")[0] + "'")) == true) && (typeof eval($(this).attr('class').split("_")[0]) == 'function')) {
                    currentErrors = currentErrors + eval($(this).attr('class').split("_")[0])($(this), $(this).val());
                }
            }
        );

        $(containingElement + " input[type=checkbox]").each( //We will then loop through the element finding elements that are required
            function(i) {
                if (($(this).attr('class').split("_")[0] == 'required' || $(this).attr('class').split("_")[1] == 'required') && (!this.checked)) {
                    $(this).parents(".errorContainer").children(".error").html("This is a required field.");
                    currentErrors++;
                }

                if ((isdefined(eval("'" + $(this).attr("class").split("_")[0] + "'")) == true) && (typeof eval($(this).attr('class').split("_")[0]) == 'function')) {
                    eval($(this).attr('class').split("_")[0])($(this), $(this).val());
                }
            }
        );

            $(containingElement + " input[type=hidden]").each(
            function(i) {
                
                if (($(this).attr('class').split("_")[0] == 'required' || $(this).attr('class').split("_")[1] == 'required') && $(this).val() == 0) {
                    if ($(this).attr('id') != "pluckStepTitle_STEP_NUM") {
                        $(this).parents(".errorContainer").children(".error").html("This is a required field.");
                        currentErrors++;
                    }


                    if ((isdefined(eval("'" + $(this).attr("class").split("_")[0] + "'")) == true) && (typeof eval($(this).attr('class').split("_")[0]) == 'function')) {
                        currentErrors = currentErrors + eval($(this).attr('class').split("_")[0])($(this), $(this).val());
                    }
                }
            }
        );

            $(containingElement + " DIV.required").each(
            function(i) {
                if (this.innerHTML == ("&nbsp;" || "")) {
                    $(this).parents(".errorContainer").children(".error").text("This is a required field.");
                    currentErrors++;
                }
            }
        );

        $(containingElement + " IMG.required").each(
            function(i) {
                imgSRC = this.src;
                imgSRC = imgSRC.substring(imgSRC.length - 3);
                imgSRC = imgSRC.toLowerCase();
                if (imgSRC != "jpg" && imgSRC != "gif" && imgSRC != "png") {
                    $(this).parents(".errorContainer").children(".error").text("This is a required field.");
                    currentErrors++;
                }
            }
        );
            
        return currentErrors;
    }
