﻿function enableSimpleFormValidation() {

    // find any <form>s of the class "form-validate" and modify their
    // submit event to validate its fields
    $("form.form-validate").submit(function(e) {
        
        // prevent default submit action
        if (e.preventDefault) { e.preventDefault(); e.stopPropagation(); } else { e.returnValue = false; e.cancelBubble = true; }

        // validate the form
        if (validateForm(this) == true) {
            this.submit();
            return true;
        } else {
            //alert("There is a problem with the information you have entered.");
            setFocusOnError();
            return false;
        }
    });
}

function setFocusOnError() {
    // if the server returned any form errors on the current
    // page, set kb focus to the first instance of an error
    if ($("select,input").filter(".error").size() > 0) {
        var frm = $("#content").find("form").get(0);
        for (var i = 0; i < frm.elements.length; i++) {
            if ($(frm.elements[i]).is(".error")) {
                frm.elements[i].focus();
                break;
            }
        }
    }
}

function validateForm(frm) {
    var formIsValid = true;

    // find all elements that contain the class "validate-*"
    $("*[@class*='validate-'][@disabled='']", frm).each(function() {
        formIsValid = (validateField(this)) ? formIsValid : false;
    });

    $("*[@class*='validateconditional-'][@disabled='']", frm).each(function() {
        formIsValid = (validateConditionalField(this)) ? formIsValid : false;
    });

    return formIsValid;
}

function validateField(e) {

    return validateFieldInd(e, "validate-");
}
function validateConditionalField(e) {
    //pull out function name
    var conditional;
    var isValid = true;
    
    var classArray = e.className.split(" ");
    
    for (var i = 0; i < classArray.length; i++) {
        if (classArray[i].indexOf("validateconditional-") > -1) {

            var validatorArray = classArray[i].split("-");

            conditional = validateFieldInd(e, "validate-");
            
            //conditional = eval(validatorArray[1]);
            //indicator=validatorArray[2];
            
            if (conditional) {
                isValid = (conditional(e)) ? isValid : false
            }
        }
    }


    return isValid; // set this conditional="international" (the function name)

}

function displayError(e, msg) {
    $(e).addClass("error"); 	// add the class ".error" to the input element that generated the error
    $("label[@for='" + e.id + "']").addClass("error"); // find the label for e.id, and add the class ".error"

    // see if an error, or a container for an error already exists.
    // error divs have IDs in the form "<formElementName>-error"
    if (document.getElementById(e.name + "-error")) {
        // the error already exists update its content with the new error msg
        var error = document.getElementById(e.name + "-error");
        msg = (error.title) ? error.title : msg; // if the error has a title, use it as a custom error msg
        $(document.getElementById(e.name + "-error")).html("<p>" + msg + "</p>");
        $(document.getElementById(e.name + "-error")).show();

    } else {
        // the error does not exist, create it
        if (e.type == "checkbox") {		// special case for displaying errors on checkboxes
            $("label", e.parentNode).after("<div id='" + e.name + "-error' class='error checkbox'><p>" + msg + "</p></div>");
        } else {
            //alert("creating div id='" + e.name + "-error'");
            $(e).after("<div id='" + e.name + "-error' class='error'><p>" + msg + "</p></div>");
        }
    }
}

function removeError(e) {
    // hide the error's container and clear out its message
    $(document.getElementById(e.name + "-error")).html("").hide();
    $(e).removeClass("error");
    $("label[@for='" + e.id + "']").removeClass("error");
}

function validateFieldInd(e, indicator) {
    // NOTE - validators are applied in the order they are specified in the field's class declaration
    
    var classArray = e.className.split(" ");
    var fieldIsValid = true;
    var errorMsg = "";
    for (var i = 0; i < classArray.length; i++) {
        if (classArray[i].indexOf(indicator) > -1) {
            var validator = classArray[i].substring(indicator.length);
            
            switch (validator) {
                case ("required"):
                    // ################# VALIDATOR FOR REQUIRED FIELDS #####################
                    switch (e.tagName) {
                        case "INPUT":
                            //alert(e.type);
                            if (e.type == "checkbox") {
                                if (e.checked != true) {
                                    errorMsg = "This checkbox is required.";
                                    fieldIsValid = false;
                                }
                            } else if (e.value.length < 1) {
                                errorMsg = "This field is required.";
                                fieldIsValid = false;
                                                           }
                            break;
                        case "TEXTAREA":
                            if (e.value.length < 1) {
                                errorMsg = "This field is required.";
                                fieldIsValid = false;
                            }
                            break;
                        case "SELECT":
                            if (e.selectedIndex == 0 && e.name != "cardMonthDropDownList") {
                                errorMsg = "Please make a selection.";
                                fieldIsValid = false;
                               
                            }
                            else if (e.name == "cardMonthDropDownList" && e.selectedIndex == 0) {
                               
                            }
                            break;
                    }
                    break;
                case ("email"):
                    // ##################### EMAIL ADDRESS VALIDATOR #####################
                    var regex = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
                    if (!(e.value.match(regex))) {
                        errorMsg = "Please enter a valid email address.";
                        fieldIsValid = false;
                    }
                    break;

                case ("phone"):
                    // ##################### PHONE NUMBER VALIDATOR #####################
                    //var regex = /^\(?\d{3}\)?\s|-\d{3}-\d{4}$/; //(###-###-####)
                    var regex = /^\(?\d{3}\)?(\s|-|\.)?\d{3}?(\s|-|\.)?\d{4}$/; // ###-###-####, (###) ###-####, ###.###.####, ### ### ####
                    if (!(e.value.match(regex)) && e.name != "mobilePhoneTextBox") {
                        errorMsg = "Please enter a valid phone number (###-###-#### or (###) ###-####).";
                        fieldIsValid = false;
                    }
                    break;

                case ("zip"):
                    // ##################### ZIP CODE VALIDATOR #####################
                    var regex = /\d{5}(-\d{4})?|[A-Z]\d[A-Z]\s\d[A-Z]\d/; // validates US ZIP Codes (#####, #####-####)
                    if (!(e.value.match(regex))) {							// and Canadian ZIP codes (A#A #A#)
                        errorMsg = "Please enter a valid ZIP Code (#####) or Postal Code (A#A #A#).";
                        fieldIsValid = false;
                    }
                    break;

                case ("currency"):
                    // ##################### CURRENCY VALIDATOR #####################
                    var regex = /^\s*[$]?\s*\d+(\.\d{2})?\s*$/; // Validates US currency strings ($12, 12, 12.34)
                    if (!(e.value.match(regex))) {
                        errorMsg = "Please enter a valid currency amount.";
                        fieldIsValid = false;
                    }
                    break;
                case ("isbn"):
                    var regex = /(?=.{13}$)\d{1,5}([-])\d{1,7}\1\d{1,6}\1(\d|X)$|(^\d{9}[0-9xX]{1}$)/;
                    var regex2 = /([\d]{10}|[\d]{9}[xX])|([\d]{13})$/;
                    if (!(e.value.match(regex) || e.value.match(regex2))) {
                        errorMsg = "Please enter a valid IBSN.";
                        fieldIsValid = false;
                    }
                    break;

                /*var regex = /(?=.{13}$)\d{1,5}([-])\d{1,7}\1\d{1,6}\1(\d|X)$|(^\d{9}[0-9xX]{1}$)/;
                if (!(e.value.match(regex))) {
                errorMsg = "Please enter a valid IBSN.";
                fieldIsValid = false;
                }
                break;*/ 
            }
        }

        // stop checking for other validators of this field has already failed one of them
        if (fieldIsValid == false) {
            break;
        };
    }

    if (fieldIsValid == false) {
        displayError(e, errorMsg);
    } else {
        if ($(e).is(".error") == true) {
            removeError(e);
        }
    }
    return fieldIsValid;

}
