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 + '"]');
    if(stagPopup.is('.show')) return false;
    else {
        let zIndex = $('.stag-popup.show[stag-popup-key]').last().css('z-index');
        if(zIndex) zIndex++; else zIndex = 100;
        stagPopup.css('z-index', zIndex);
    }
    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(_noEvent = false) {
    if(!stagPopupsQueue.length) return false;
    let popup = stagPopupsQueue[stagPopupsQueue.length - 1];
    let closeAll = !!popup.attr('close-all-with-self');
    popup.removeClass('show');
    stagPopupsQueue.splice(stagPopupsQueue.length - 1, 1);
    if(closeAll) {
        while(stagPopupsQueue.length) {
            closeStagPopup(true);
        }
    }
    else {
        if(popup.is('[update-parent]')) {
            if(stagPopupsQueue.length) {
                refreshDynamicStagPopup();
            }
            else {
                fastReload()
            }
        }
    }
    // if all closed
    if(!stagPopupsQueue.length) {
        $('html, body').removeClass('no-scroll');
        $(window.top.document.body).find('#stag_mcp_lhs').removeClass('no-scroll');
        if(!_noEvent) {
            $('body').trigger('stag-popup-closed');
        }
    }
    return false;
}
function openDynamicStagPopup(url, initer, title, updateParent) {
    url += (url.indexOf('?') !== -1 ? '&' : '?') + 'popupmode=1';
    showMask();
    window.noMc = true;
    $.get(url, (_data) => {
        let popup = $('.dynamic-popup[stag-popup-key="' + url + '"]');
        if(!popup.length) {
            $('main.stag-content').append(
                '<div class="stag-popup stag-popup-lg dynamic-popup mcp-theme-1" stag-popup-key="' + url + '">' +
                '<div class="stag-popup-content p-0">' +
                '<h3 class="stag-popup-title mb-0 mt-3 mx-3 pb-0 border-bottom-0"><span></span>' +
                '<a href="#" class="ml-auto text-secondary" onclick="return closeStagPopup()"><i class="fa fa-times-circle"></i></a>\n' +
                '</h3>' +
                '<div class="stag-popup-content-inner"></div>' +
                '</div>' +
                '</div>'
            );
            popup = $('.dynamic-popup[stag-popup-key="' + url + '"]');
        }
        popup.attr('mc-initer', initer);
        popup.find('.stag-popup-title>span').text(title);
        popup.find('.stag-popup-content-inner').html(_data);
        if(updateParent) {
            popup.attr('update-parent', 1);
        }
        else {
            popup.removeAttr('update-parent');
        }
        showStagPopup(url);
        if(initer) runMCInitializer(initer);
        runMCInitializer('pro-suggest');
        initMoes();
        hideMask();
    });
}
function isDynamicStagPopupPresent() {
    if(!stagPopupsQueue.length) return false;
    let popup = stagPopupsQueue[stagPopupsQueue.length - 1];
    if(popup.is('.dynamic-popup')) return true;
    return false;
}
function refreshDynamicStagPopup(_url = false) {
    if(!stagPopupsQueue.length) return false;
    let popup = stagPopupsQueue[stagPopupsQueue.length - 1];
    if(popup.is('.dynamic-popup')) {
        showMask();
        window.noMc = true;
        if(_url) {
            popup.attr('stag-popup-key', _url);
        }
        let url = popup.attr('stag-popup-key'),
            initer = popup.attr('mc-initer');
        $.get(url, (_data) => {
            popup.find('.stag-popup-content-inner').html(_data);
            if(initer) runMCInitializer(initer);
            runMCInitializer('pro-suggest');
            initMoes();
            hideMask();
        });
    }
    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(!window.moeClosedAt || (new Date()).getTime() - window.moeClosedAt > 1000) {
                        if(stagPopupsQueue.length) {
                            closeStagPopup();
                            return false;
                        }
                    }
                }
            });

        $(document)
            .off('click.open-in-stag-popup', 'a[open-in-stag-popup]')
            .on('click.open-in-stag-popup', 'a[open-in-stag-popup]', function() {
                openDynamicStagPopup(this.href, $(this).attr('mc-initer'), $(this).attr('title'), $(this).is('[update-parent]'));
                return false;
            });

    }
    addMCInitializer('stag-popups', window.initStagPopupEvents);
})();
