(function ($) {
    'use strict';

    var dirty = false;
    var submitting = false;
    var cfg = window.macaMenulistAdminNav || {};
    var message = cfg.unsavedMessage || 'You have unsaved changes. Leave this page without saving?';

    function setDirty() {
        if (!submitting) {
            dirty = true;
        }
    }

    function bindForm($form) {
        $form.on('input change', 'input, textarea, select', setDirty);
        $form.on('submit', function () {
            submitting = true;
            dirty = false;
        });
    }

    function confirmLeave() {
        if (!dirty || submitting) {
            return true;
        }

        if (window.confirm(message)) {
            dirty = false;
            submitting = false;
            return true;
        }

        return false;
    }

    $(function () {
        var $forms = $('form.maca-admin-record-form');

        if (!$forms.length) {
            return;
        }

        $forms.each(function () {
            bindForm($(this));
        });

        $(document).on('click', 'a.maca-admin-record-nav-link', function (event) {
            if (!confirmLeave()) {
                event.preventDefault();
            }
        });

        $(window).on('beforeunload', function () {
            if (dirty && !submitting) {
                return message;
            }
        });
    });
}(jQuery));
