document.addEventListener('DOMContentLoaded',function() {

    const nav = document.getElementsByClassName('js-nav')[0],
          hamburger = document.getElementsByClassName('js-hamburger')[0];

    const init = function() {

        const hideMenu = function() {
            nav.classList.remove('is-visible');
            
            document.removeEventListener('click', clickOutside);
            
            setTimeout(function() {
                nav.classList.remove('is-block');
                nav.classList.remove('is-animated');
            }, 400);
            
            if (window.innerWidth <= 1140) {
                enableBodyScroll(menu);
            }
        };

        const showMenu = function() {

            setTimeout(function() {
                nav.classList.add('is-visible');
                document.addEventListener('click', clickOutside);
            }, 100);
        };


        const toggleMenu = function(e) {
            nav.classList.contains('is-visible') ? hideMenu() : showMenu();
        };

        
        hamburger.addEventListener('click', toggleMenu);
        
        const clickOutside = function(e) {
            if (!e.target.closest('.js-nav')) {
                hideMenu();
        	}
        };
        

        // Hide menu on ESC

        document.addEventListener('keydown', function(evt) {
            // evt = evt || window.event;
            var isEscape = false;
            if ("key" in evt) {
                isEscape = (evt.key == "Escape" || evt.key == "Esc");
            } else {
                isEscape = (evt.keyCode == 27);
            }
            if (isEscape) {
                hideMenu();
            }
        });
        
    };

    nav ? init() : false;

}, false);