define(['jquery'], function ($) {
    return function () {

        // Let's do some stuff with the DOM when it's ready
        // Say, is this Safari by any chance?
        var isSafari = /constructor/i.test(window.HTMLElement) || (function (p) {
            return p.toString() === "[object SafariRemoteNotification]";
        })(!window['safari'] || safari.pushNotification);

        // Grab all inputs with a custom validity message
        var inputs = $('input[data-validity], textarea[data-validity]');

        inputs.each(function (index, input) {
            // Prevent errors if the browser doesn't support HTML5 validation
            if (!input.setCustomValidity || !input.willValidate) {
                return;
            }

            // Set the validation messages when the user submits something invalid
            $(input).on('invalid', function (event) {
                $(event.target).parents('.form-group').addClass('has-error');
                event.target.setCustomValidity($(event.target).data('validity'));

                // Show a growl message with the error
                cla.showMessage($(event.target).data('validity'), null, true);
            });

            // Reset the message when the user starts modifying the value
            $(input).on('input', function (event) {
                var valid = input.validity && !(input.validity.typeMismatch || input.validity.patternMismatch);

                // Test the pattern for textarea elements; browsers don't do this natively
                if (event.target.type === 'textarea' && $(event.target).attr('pattern')) {
                    var pattern = new RegExp($(event.target).attr('pattern'));

                    if (pattern) {
                        valid = pattern.test($(event.target).val());
                    }
                }

                // Only remove the validation message if the new value is valid
                if (!valid) {
                    $(event.target).parents('.form-group').addClass('has-error');
                    event.target.setCustomValidity($(event.target).data('validity'));
                } else {
                    $(event.target).parents('.form-group').removeClass('has-error');
                    event.target.setCustomValidity('');
                }
            });
        });

        // Workaround for Safari submitting forms regardless of validity
        if (isSafari) {
            var forms = $('form');

            forms.each(function (index, form) {
                form.noValidate = true;

                $(form).on('submit', function (event) {
                    if (!event.target.checkValidity()) {
                        event.preventDefault();
                    }
                });
            });
        }
    }
});
