﻿//Saved the original validation function
var onsubmitFunctionArray = new Array();
$(function () {
    var forms = $("form");
    if (forms.length == 0) {
        return;
    }

    $.each(forms, function () {
        var onsubmitFunction = $(this).attr("onsubmit");
        onsubmitFunctionArray[this] = onsubmitFunction;
        if (onsubmitFunction != null && onsubmitFunction != "") {
            $(this).attr("onsubmit", "");
        }
    });

    $(forms).submit(function () {
        return CheckSpecialCharacter($(this), true);
    });


});

function CheckSpecialCharacter(form, executeOnSubmitFunction) {
    if (typeof (specialCharRegex) == undefined) {
        return;
    }

    var result = false;
    try {
        var inputs = $(form).find(":text,textarea,:password,input[type='email']");
        var allSpecialField = "";
        var allSepcialElements = new Array();
        $.each(inputs, function () {
            var match = $(this).val().match(specialCharRegex);
            if (match != null && match.length != "") {
                allSpecialField += $(this).attr("id") + " contains special char ( " + match + " ) that is not supported;\n";
                allSepcialElements[allSepcialElements.length] = this;
            }
        });

        if (allSepcialElements.length > 0 && confirm(allSpecialField + "\n\n" + "Do you confirm to replace it and submit?")) {
            $.each(allSepcialElements, function () {
                $(this).val(
                        $(this).val().replace(specialCharRegex, "")
                        );
            });
            result = true;
        }
        else if (allSepcialElements.length > 0) {
            // reset the variable for submit one time...
            if (typeof (submitCount) != undefined) {
                submitCount = 0;
            }
            // focus to this form
            $(allSepcialElements[0]).focus();
            result = false;
        }
        else {
            result = true;
        }
    }
    catch (ex) {
        result = true;
    }

    if (result == true && executeOnSubmitFunction) {
        if (onsubmitFunctionArray[form] == null || onsubmitFunctionArray[form] == "") {
            return result;
        }
        try {
            return eval("function x(){ " + onsubmitFunctionArray[form] + " }; x();")
        }
        catch (ex) {
            //alert(ex.Description + "\n" + ex.Message);
        }
    }
    else {
        return result;
    }
}

