(function () {
    'use strict';

    function qs(id) {
        return document.getElementById(id);
    }

    var sidebar = qs('erpSidebar');
    var backdrop = qs('erpSidebarBackdrop');
    var toggle = qs('erpSidebarToggle');

    function setOpen(open) {
        if (!sidebar) {
            return;
        }
        sidebar.classList.toggle('is-open', open);
        if (backdrop) {
            backdrop.classList.toggle('is-visible', open);
        }
        if (toggle) {
            toggle.setAttribute('aria-expanded', open ? 'true' : 'false');
        }
    }

    if (toggle) {
        toggle.addEventListener('click', function () {
            var open = !sidebar || !sidebar.classList.contains('is-open');
            setOpen(open);
        });
    }

    if (backdrop) {
        backdrop.addEventListener('click', function () {
            setOpen(false);
        });
    }

    window.addEventListener('resize', function () {
        if (window.matchMedia('(min-width: 992px)').matches) {
            setOpen(false);
        }
    });
})();
