window.stagPopupsQueue = [];
function showStagPopup(_key, _noAutoFocus) {
    /*$('html, body').addClass('no-scroll');
    $(window.top.document.body).find('#stag_mcp_lhs').addClass('no-scroll');*/
    let stagPopup = $('[stag-popup-key="' + _key + '"]');
    stagPopup.addClass('show');
    stagPopup.find('[moe][initialized]').removeAttr('initialized');
    initMoes();
    if(!_noAutoFocus) {
        window.setTimeout(function() {
            stagPopup.find('input[type="text"]:not([readonly]):visible,select:visible').first().focus();
        }, 150);
    }
    stagPopupsQueue.push(stagPopup);
    return false;
}
function submitStagPopup(_form) {
    if(!_form[0].checkValidity()) {
        _form[0].reportValidity();
        return false;
    }
    showMask();
    $.post(_form.attr('action'), _form.serialize(), function(_data) {
        stagPopupsQueue = [];
        fastReload();
    });
    return false;
}
function closeStagPopup() {
    if(!stagPopupsQueue.length) return false;
    let popup = stagPopupsQueue[stagPopupsQueue.length - 1];
    popup.removeClass('show');
    stagPopupsQueue.splice(stagPopupsQueue.length - 1, 1);
    // if all closed
    if(!stagPopupsQueue.length) {
        $('html, body').removeClass('no-scroll');
        $(window.top.document.body).find('#stag_mcp_lhs').removeClass('no-scroll');
        $(document).trigger('stag-popup-closed');
    }
    return false;
}
(function() {
    window.initStagPopupEvents = function () {
        $(document)
            .off('click.stag-popup-discard', '.stag-popup')
            .on('click.stag-popup-discard', '.stag-popup', function(_e) {
                if($(_e.target).is('.stag-popup')) {
                    closeStagPopup();
                    return false;
                }
            });
        // catch ESC and discard any visible popups
        $(document)
            .off('keydown.stag-popup-escape')
            .on('keydown.stag-popup-escape', function (e) {
                if(e.which === 27) {
                    if(stagPopupsQueue.length) {
                        closeStagPopup();
                        return false;
                    }
                }
            });
    }
    addMCInitializer('stag-popups', window.initStagPopupEvents);
})();
