(function($) {
    "use strict";
    $("#exporo-tabs").find(".cmb-type-title").on("click", function () {
        var id = $(this).find('h3').attr("id");
        var url = window.location.href;
        if(url.indexOf('&tab=') != -1) {
            let newUrl = new URL(document.location);
            let params = newUrl.searchParams;
            params.set('tab', 'cmb2-id-' + id);
            url = newUrl;
        } else {
            url = url + "&tab=cmb2-id-" + id;
        }
        history.pushState({}, null, url);
        $("#exporo-tabs").find(".cmb-type-title").removeClass('active');
        $(this).addClass('active');
        $("#exporo-tab-boxes").find(".exporo-tab-content").removeClass('active');
        $("#exporo-tab-boxes").find(".exporo-tab-content").each(function(index, value) {
            var contentId = $(this).attr("data-id");
            if (contentId == id) {
                $(this).addClass('active');
                return false;
            }
        });
    });
    $("#exporo-clear-cache").on("click", function () {
        var btn = $(this);
        var data = {
            'action': 'exporoClearCache',
            'nonce': exporoGenParams.nonce
        };
        $.ajax({
            url : exporoGenParams.ajaxurl,
            data : data,
            type : 'POST',
            beforeSend: function ( xhr ) {
                btn.prop('disabled', true);
            },
            success: function(data){
                if (data == 'error') {
                    alert(exporoGenParams.wrong);
                } else {
                    alert(exporoGenParams.filesDeleted);
                }
            },
            error: function(jqXHR,error, errorThrown) {
                alert(error + ': ' + errorThrown);
                btn.prop('disabled', false);
            }
        }).done(function() {
            btn.prop('disabled', false);
        });
    });
    $(document).ready(function () {
        var newUrl = new URL(document.location);
        var params = newUrl.searchParams;
        if(params.get("tab")) {
            $("#exporo-tabs").find(".cmb-type-title").each(function(index, value) {
                if ($(this).hasClass(params.get("tab"))) {
                    $(this).trigger('click');
                    return false;
                }
            });
        }
    });
})(jQuery);