// Function Collapse Update
function collapseUpdate(id,reset) {
    if (reset) {
        $(".collapse-async").collapse("hide");
    }
    
    if ($("#"+id).attr("class").indexOf("show") !== -1) {
        $("#"+id).collapse("hide");
    }
    else {
        $("#"+id).collapse("show");
    }
}

// Function Show Password
function passwordEye(input_id,eye_id,replace_icon = false) {
    if (replace_icon == false) {
        if ($("#"+input_id).attr("type") == "password") {
            $("#"+input_id).attr("type","text");
            $("#"+eye_id).addClass("text-primary");
        }
        else {
            $("#"+input_id).attr("type","password");
            $("#"+eye_id).removeClass("text-primary");
        }
    }
    else {
        if ($("#"+input_id).attr("type") == "password") {
            $("#"+input_id).attr("type","text");
            
            if ($("#"+eye_id).children("span").length > 0) {
                $("#"+eye_id).children("span").html("visibility");
            }
            else {
                $("#"+eye_id).children("i").addClass("bi-eye");
                $("#"+eye_id).children("i").removeClass("bi-eye-slash");
            }
        }
        else {
            $("#"+input_id).attr("type","password");
            
            if ($("#"+eye_id).children("span").length > 0) {
                $("#"+eye_id).children("span").html("visibility_off");
            }
            else {
                $("#"+eye_id).children("i").addClass("bi-eye-slash");
                $("#"+eye_id).children("i").removeClass("bi-eye");
            }
        }
    }
}

// Function Show Alert
function alertMessage(id,msg,type,modal_hide_id) {
    $("#modalAlert_icon").attr("class","bi");
    $("#modalAlert_btn").attr("class","btn btn-lg w-100");
    $("#modalAlert_btn").attr("data-bs-target","");
    $("#modalAlert_btn").attr("data-bs-toggle","");
    
    if (modal_hide_id !== undefined && modal_hide_id !== null) {
        $("#"+modal_hide_id).modal("hide");
        $("#modalAlert_btn").attr("data-bs-target","#"+modal_hide_id);
        $("#modalAlert_btn").attr("data-bs-toggle","modal");
    }

    if (Number(type) === 0) {
        $("#modalAlert_icon").addClass("bi-check-lg");
        $("#modalAlert_icon").addClass("text-light-green-2");

        $("#modalAlert_title").html("Sucesso!");
        $("#modalAlert_msg").html(msg);

        $("#modalAlert_btn").addClass("btn-light-green-2");
    }
    else if (type == 1) {
        $("#modalAlert_icon").addClass("bi-x-lg");
        $("#modalAlert_icon").addClass("text-danger");

        $("#modalAlert_title").html("Erro!");
        $("#modalAlert_msg").html(msg);

        $("#modalAlert_btn").addClass("btn-danger");
    }
    else if (type == 2) {
        $("#modalAlert_icon").addClass("bi-exclamation-triangle");
        $("#modalAlert_icon").addClass("text-warning");

        $("#modalAlert_title").html("Alerta!");
        $("#modalAlert_msg").html(msg);

        $("#modalAlert_btn").addClass("btn-warning");
    }
    else if (type == 3) {
        $("#modalAlert_icon").addClass("bi-info-circle");
        $("#modalAlert_icon").addClass("text-info");

        $("#modalAlert_title").html("Info!");
        $("#modalAlert_msg").html(msg);

        $("#modalAlert_btn").addClass("btn-info")
    }

    $("#"+id).modal("show");
}

//Function Alert Message Toast
function alertMessageToast(id,msg,type,bottom) {
    $("#toastAlert").attr("class","toast align-items-center text-white border-0");
    $("#toastAlert_divMessage").html(msg);
    if (type == 0) {
        $("#toastAlert").addClass("bg-light-green");
    }
    else if (type == 1) {
        $("#toastAlert").addClass("bg-light-red");
    }
    else if (type == 2) {
        $("#toastAlert").addClass("bg-warning");
    }
    else if (type == 3) {
        $("#toastAlert").addClass("bg-info");
    }
    
    $("#toastAlert").toast("show");
}

// Function Show Alert Confirm
function alertConfirmMessage(id,msg,type,modal_hide_id,buttonConfirmEvent) {
    $("#modalConfirm_icon").attr("class","bi");
    $("#modalConfirm_btn").attr("onclick",buttonConfirmEvent);
    
    if (modal_hide_id !== undefined && modal_hide_id !== null) {
        $("#"+modal_hide_id).modal("hide");
        $("#modalConfirm_btn").attr("data-bs-target","#"+modal_hide_id);
        $("#modalConfirm_btn").attr("data-bs-toggle","modal");
    }

    if (type == 0) {
        $("#modalConfirm_icon").addClass("bi-check-lg");
        $("#modalConfirm_icon").addClass("text-light-green-2");

        $("#modalConfirm_title").html("Confirmação");
        $("#modalConfirm_msg").html(msg);
    }
    else if (type == 1) {
        $("#modalConfirm_icon").addClass("bi-x-lg");
        $("#modalConfirm_icon").addClass("text-danger");

        $("#modalConfirm_title").html("Confirmação");
        $("#modalConfirm_msg").html(msg);
    }
    else if (type == 2) {
        $("#modalConfirm_icon").addClass("bi-exclamation-triangle");
        $("#modalConfirm_icon").addClass("text-warning");

        $("#modalConfirm_title").html("Confirmação");
        $("#modalConfirm_msg").html(msg);
    }
    else if (type == 3) {
        $("#modalConfirm_icon").addClass("bi-info-circle");
        $("#modalConfirm_icon").addClass("text-info");

        $("#modalConfirm_title").html("Confirmação");
        $("#modalConfirm_msg").html(msg);
    }

    $("#"+id).modal("show");
}

// Function Show Alert Empty
function alertMessageEmpty(id,msg) {
    $("#modalAlertEmpty_divMessage").html(msg);

    $("#"+id).modal("show");
}

// Function Infinite Line Menu Category
function selectedCategory(divClass,collapse_class,beat = 1) {
    $("."+divClass+" div").each(function () {
        if ($(this).attr("id") != "seeMoreCategory") {
            $(this).on("click", function () {
                $("."+divClass+" div").each(function () {
                    div_id = $(this).attr("id");
                    $("#"+div_id+" i,"+"#"+div_id+" img").each(function () {
                        $(this).removeClass("fa-beat");
                    })
                    $(this).removeClass("active");
                })
                
                div_id = $(this).attr("id");
                $("#"+div_id).addClass("active");
                if (beat == 1) {
                    $("#"+div_id+" i,"+"#"+div_id+" img").addClass("fa-beat");
                }
            })
        }
    })
}

function collapseItemState(divClass,id,element_class) {
    /*if (element_class !== null) {
        $("."+element_class).collapse("show");
        return;
    }*/
    
    $("."+divClass+" div").each(function () {
        div_id = $(this).attr("id");
        
        if (typeof(div_id) != "undefined") {
            ids = div_id.split("_");
            
            if (id === 0 && $("#itemCategory_"+ids[2]).attr("data-any") === undefined) {
                $("#itemCategory_"+ids[2]).collapse("show");
            }
            else {
                if (div_id != ("id_il_"+id)) {
                    $("#itemCategory_"+ids[2]).collapse("hide");
                }
                else {
                    $("#itemCategory_"+id).collapse("show");
                }
            }
        }
    })
}

function collapseCloseAll(divClass) {
    $("."+divClass+" div").each(function () {
        div_id = $(this).attr("id");
        ids = div_id.split("_");
        
        if (div_id.indexOf("reset") === -1) {
            $("#itemCategory_"+ids[2]).collapse("hide");
        }
    })
}

function collapseState(element_class,action) { // action = 0 (Close all), 1 (Open all)
    aff = $("."+element_class).attr("id");
    alert(aff);
    if (action == '0') {
        $("."+element_class).collapse("hide");
    }
    else if (action == 1) {
        $("."+element_class).collapse("show");
    }
}

// Function Add/Remove Amount Item
function amountAddRemove(input_id,action,min_max,type = 0) {
    amount = $("#"+input_id).val();
    if (type == 0) { // Quantidade normal (número inteiro)
        if (action == "add" && Number(amount)+1 <= min_max) {
            $("#"+input_id).val(Number(amount)+1);
            angular.element($('#'+input_id)).triggerHandler('input');
        }
        else if (action == "rem" && Number(amount)-1 >= min_max) {
            $("#"+input_id).val(Number(amount)-1);
            angular.element($('#'+input_id)).triggerHandler('input');
        }
    }
    else if (type == 1) { // Quantidade por peso (número fluante com 3 casas decimais)
        if (action == "add" && (parseFloat(amount) + 0.100).toFixed(3) <= min_max) {
            $("#"+input_id).val((parseFloat(amount) + 0.100).toFixed(3));
            angular.element($('#'+input_id)).triggerHandler('input');
        }
        else if (action == "rem" && (parseFloat(amount) - 0.100).toFixed(3) >= min_max) {
            $("#"+input_id).val((parseFloat(amount) - 0.100).toFixed(3));
            angular.element($('#'+input_id)).triggerHandler('input');
        }
    }
    
    $("#"+input_id).change();
}

function btnEnableDisable(btn,type,msg_default) {
    if ($(btn).length > 0) {
        if (type == 1) {
            $(btn).removeClass("disabled");
            $(btn).children("span").remove();
            //$(btn).children("b").removeClass("visually-hidden");
            
            // Remove largura/altura fixas (inline)
            //$(btn).css({ width: '', height: '' });

            // Remove largura/altura fixas (inline)
            if ($(btn).prop("tagName").toLowerCase() !== 'div') {
                $(btn).css({ width: '', height: '' });
            }
            
            $(btn).children(':not(.spinner-border)').removeClass("visually-hidden");
            
            //$(btn).html(msg_default);
            return;
        }

        $(btn).addClass("disabled");
        $(btn).width($(btn).width());
        $(btn).height($(btn).height());
        $(btn).prepend('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>');
        //$(btn).children('b').addClass("visually-hidden");
        $(btn).children(':not(.spinner-border)').addClass("visually-hidden");
        //$(btn).html("AGUARDE...");
    }
}

// Function return value param (GET URL)
function getParamURL(param) {
    const urlParams = new URLSearchParams(window.location.search);
    const myParam = urlParams.get(param);
    return myParam;
}







// States
stateNames = [
    "Acre", "Alagoas", "Amapá", "Amazonas", "Bahia", "Ceará", 
    "Distrito Federal", "Espírito Santo", "Goiás", "Maranhão", 
    "Mato Grosso", "Mato Grosso do Sul", "Minas Gerais", "Pará",
    "Paraíba", "Paraná", "Pernambuco", "Piauí", "Rio de Janeiro", 
    "Rio Grande do Norte", "Rio Grande do Sul", "Rondônia", "Roraima", 
    "Santa Catarina", "São Paulo", "Sergipe", "Tocantins"
];

// Close Modal Click Back Button
window.onpopstate = function(event) {
    $(".modal").modal("hide");
    
    /*const urlParams = new URLSearchParams(window.location.search);
    const myParam = urlParams.get('modal');
    console.log(myParam);*/
}

// Function Add KeyPress Event
function addEventKeyPress(id,key_press_code,exeFuncName,FuncArg,elementClick) {
    $('#'+id).keypress(function(event){
        var keycode = (event.keyCode ? event.keyCode : event.which);
        if(keycode == key_press_code){
            if (elementClick !== undefined && elementClick !== null) {
                $(elementClick).click();
                return;
            }
            window[exeFuncName](FuncArg);
        }
    });
}

// Function Select Div Option
function selectDivOption(classDiv,element) {
    $("."+classDiv).each(function () {
        $(this).removeClass("active");
    })
    $(element).addClass("active");
}

function collapseLastScrollPageAfterShown(id) {
    var myCollapsible = document.getElementById(id)
    myCollapsible.addEventListener('shown.bs.collapse', function () {
        var heightPage = document.body.scrollHeight;
        window.scrollTo(0 , heightPage);
    })
}

// Function Close All Collapse
function collapseCloseAllExcept(collapseClass,ExceptID) {
    $("#"+collapseClass+" div.collapse").each(function () {
        if (ExceptID === undefined || ExceptID === null || $(this).attr("id") != ExceptID) {
            if ($(this).attr("class").indexOf("show") != -1) {
                $(this).collapse("hide");
            }
        }
    });
}

function expandOffcanvas(id) {
    if ($("#"+id).attr("class").indexOf("expand-offcanvas") !== -1) {
        $("#"+id).removeClass("expand-offcanvas");
        $("#"+id).addClass("decrease-offcanvas");
    }
    else {
        $("#"+id).removeClass("decrease-offcanvas");
        $("#"+id).addClass("expand-offcanvas");
    }
}



function previousList(classElement = null, classPagination = null, classItem = null) {
    if (currentPage > 0) {
        currentPage--;
        //paginationFadeOutAll('divListOrder','divListOrder_'+currentPage);
        paginationFadeOutAll((classElement !== null ? classElement : 'divListOrder'),(classElement !== null ? classElement : 'divListOrder')+'_'+currentPage);
        pageItemSelect($("li#page_"+currentPage+(classItem !== null ? "."+classItem : "")),classPagination);
    }
}

function nextList(classElement = null, classPagination = null, classItem = null) {
    if (currentPage < pagesOrderTotal-1) {
        currentPage++;
        //paginationFadeOutAll('divListOrder','divListOrder_'+currentPage);
        paginationFadeOutAll((classElement !== null ? classElement : 'divListOrder'),(classElement !== null ? classElement : 'divListOrder')+'_'+currentPage);
        pageItemSelect($("li#page_"+currentPage+(classItem !== null ? "."+classItem : "")),classPagination);
    }
}

function pageItemSelect(element,className = null) {
    $((className !== null ? "."+className+" " : "")+".pagination li").each(function () {
        $(this).removeClass("active");
    })
    $(element).addClass("active");

    id = $(element).attr("id").split("_");
    currentPage = Number(id[1]);
}

function paginationFadeOutAll(className,ExceptID = null) {
    var objFadeIn = null;
    $('.'+className).each(function () {
        if (ExceptID === null || $(this).attr("id") != ExceptID) {
            var divID = $(this).attr("id");
            $(this).addClass('removeElementPagination');
            $(this).removeClass('addElementPagination');
        }
        else {
            objFadeIn = $(this);
        }
    })
    setTimeout(function () {
        objFadeIn.addClass('addElementPagination');
        clearTimeout(this);
    }, 500);
}

function validFields(classElement) {
    var valid = true;
    $("."+classElement+" input, select").each(function () {
        if ($(this).attr("data-required") !== undefined && $(this).attr("data-required") == "true" && $(this).val() == "") {
            alertMessage('modalAlert','Preencha os campos!',3);
            valid = false;
            return false;
        }
    });
    if (valid === false) {
        return false;
    }
    return true;
}

function checkAll(obj,dNone = null) {
    var $this = $(obj);
    $(obj).children("label").each(function () {
        $(this).children("input").each(function () {
            var input_all = $(obj).children("label").children("input.input-check-all");
            input_all.attr("disabled","true");
            if ($(obj).children("label").children("input.input-check-all").is(":checked")) {
                $(this).prop('checked',true);
                if (dNone == 1 && $(this).attr("class").indexOf("input-check-all") == -1) {
                    $(this).parent().addClass("removeElement");
                    var label = $(this).parent();
                    setTimeout(function () {
                        label.css("display","none");
                        input_all.removeAttr("disabled");
                    }, 1000);
                }
            }
            else {
                $(this).prop('checked',false);
                $(this).parent().css("display","");
                if (dNone == 1 && $(this).attr("class").indexOf("input-check-all") == -1) {
                    var label = $(this).parent();
                    $(this).parent().fadeIn("slow", function(){ 
                        label.removeClass("removeElement");
                        label.addClass("addElement");
                    });
                    setTimeout(function () {
                        input_all.removeAttr("disabled");
                    }, 1000);
                }
            }
            $(this).change();
        })
    })
}








// Config Graphics
var graphicBGColor = [
    'rgb(255, 99, 132)',
    'rgb(54, 162, 235)',
    'rgb(255, 205, 86)',
    'rgb(155, 0, 0)',
    'rgb(7, 97, 0)',
    'rgb(7, 0, 89)',
    'rgb(230, 118, 12)',
    'rgb(119, 199, 12)',
    'rgb(119, 199, 122)',
    'rgb(119, 120, 201)',
    'rgb(201, 120, 201)',
    'rgb(201, 120, 120)',
    'rgb(90, 43, 120)',
    'rgb(90, 43, 254)',
    'rgb(52, 255, 254)',
    'rgb(52, 135, 254)'
];

function printContent(el) {
    var restorepage = $('body').html();
    var printcontent = $('#' + el).clone();
    $('body').empty().html(printcontent);
    window.print();
    $('body').html(restorepage);
}

function colorToneDec(hexColor, percent) {
    // Remove o símbolo # se existir
    hexColor = hexColor.replace("#", "");

    // Converte a cor de hexadecimal para RGB
    let r = parseInt(hexColor.substring(0, 2), 16);
    let g = parseInt(hexColor.substring(2, 4), 16);
    let b = parseInt(hexColor.substring(4, 6), 16);

    // Calcula a nova cor diminuindo o tom
    r = Math.round(r - (r * percent / 100));
    g = Math.round(g - (g * percent / 100));
    b = Math.round(b - (b * percent / 100));

    // Assegura que os valores estejam dentro do intervalo válido (0 a 255)
    r = Math.max(0, Math.min(255, r));
    g = Math.max(0, Math.min(255, g));
    b = Math.max(0, Math.min(255, b));

    // Converte de volta para hexadecimal e garante que sempre tenha 2 dígitos
    const newHexColor = `#${r.toString(16).padStart(2, '0').toUpperCase()}${g.toString(16).padStart(2, '0').toUpperCase()}${b.toString(16).padStart(2, '0').toUpperCase()}`;

    return newHexColor;
}





// Solicita Permissão para envio de notificações
/*Notification.requestPermission(function(status) {
    console.log('Notification permission status:', status);
});*/
function requestPermissionNotification() {
    document.body.removeEventListener("click", requestPermissionNotification);
    Notification.requestPermission(function(status) {
        console.log('Notification permission status:', status);
    });
}

if (Notification.permission !== "granted") {
    window.addEventListener("load", (event) => {
        document.body.addEventListener("click", requestPermissionNotification);
    });
}

// Envia as notificações
function displayNotification(message) {
    if (Notification.permission == 'granted') {
        navigator.serviceWorker.getRegistration().then(function(reg) {
            reg.showNotification(message);
        });
    }
}

// Solicta Permissão Para envio Push
function subscribeUser() {
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.ready.then(function(reg) {

      reg.pushManager.subscribe({
        userVisibleOnly: true,
        applicationServerKey: urlBase64ToUint8Array('BGPAoMgRUXs7TlnaGp-HMk7Od5Snppg1rfJp93rkkwxfWRSgcMWu5ftuRamqnAwc-15h1NObP5u3YeP9GLbJsiI')
      }).then(function(sub) {
        console.log('Endpoint URL: ', sub.endpoint);
      }).catch(function(e) {
        if (Notification.permission === 'denied') {
          console.warn('Permission for notifications was denied');
        } else {
          console.error('Unable to subscribe to push', e);
        }
      });
    })
  }
}






// Baixa o PWA
function installPWAApp() {
    console.log("installPWAApp exec");
    console.log(deferredPrompt);
    
    // Show the prompt
    deferredPrompt.prompt();
    setupButton.disabled = true;
    // Wait for the user to respond to the prompt
    deferredPrompt.userChoice
        .then((choiceResult) => {
            if (choiceResult.outcome === 'accepted') {
                console.log('PWA setup accepted');
                // hide our user interface that shows our A2HS button
                setupButton.style.display = 'none';
            } else {
                console.log('PWA setup rejected');
            }
            deferredPrompt = null;
        }).catch(function() {
            console.log("add");
          });;
}








function number_format(number, decimals, dec_point, thousands_sep) {
  // Strip all characters but numerical ones.
  number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
  var n = !isFinite(+number) ? 0 : +number,
      prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
      sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
      dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
      s = '',
      toFixedFix = function (n, prec) {
        var k = Math.pow(10, prec);
        return '' + Math.round(n * k) / k;
      };
  // Fix for IE parseFloat(0.55).toFixed(0) = 0;
  s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
  if (s[0].length > 3) {
    s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
  }
  if ((s[1] || '').length < prec) {
    s[1] = s[1] || '';
    s[1] += new Array(prec - s[1].length + 1).join('0');
  }
  return s.join(dec);
}

function degrees_to_radians(degrees) {
    var pi = Math.PI;
    return degrees * (pi/180);
}

function getDistance(lat1, lon1, lat2, lon2) {
    lat1 = degrees_to_radians(lat1);
    lat2 = degrees_to_radians(lat2);
    lon1 = degrees_to_radians(lon1);
    lon2 = degrees_to_radians(lon2);
    
    var dist = (6371 * Math.acos( Math.cos( lat1 ) * Math.cos( lat2 ) * Math.cos( lon2 - lon1 ) + Math.sin( lat1 ) * Math.sin(lat2) ) );
    dist = number_format(dist, 2, '.', '');
    
    return dist;
}

async function getRouteDistanceGoogleMaps(lat1, lng1, lat2, lng2) {
    return new Promise((resolve, reject) => {
        var directionsService = new google.maps.DirectionsService();

        var request = {
            origin: new google.maps.LatLng(lat1, lng1),
            destination: new google.maps.LatLng(lat2, lng2),
            travelMode: google.maps.TravelMode.DRIVING
        };

        directionsService.route(request, function(response, status) {
            if (status === google.maps.DirectionsStatus.OK) {
                var route = response.routes[0];
                var distance = 0;

                for (var i = 0; i < route.legs.length; i++) {
                    distance += route.legs[i].distance.value; // distance in meters
                }

                distance = distance / 1000; // convert to kilometers
                //console.log("Distance in route: " + distance + " km");
                resolve(distance);
            } else {
                console.error("Directions request failed due to " + status);
                // Em caso de problemas, utiliza a função em linha reta
                resolve(getDistance(lat1, lng1, lat2, lng2));
            }
        });
    });
}













function compareVersions(version1, version2) {
    // Divide as versões em partes individuais
    const v1Parts = version1.split('.').map(Number);
    const v2Parts = version2.split('.').map(Number);

    // Determina o número máximo de partes a comparar
    const maxLength = Math.max(v1Parts.length, v2Parts.length);

    for (let i = 0; i < maxLength; i++) {
        // Obtém cada parte, ou considera 0 se a parte não existir
        const v1 = v1Parts[i] || 0;
        const v2 = v2Parts[i] || 0;

        // Compara as partes numericamente
        if (v1 < v2) {
            return -1; // version1 é menor
        }
        if (v1 > v2) {
            return 1; // version1 é maior
        }
        // Se as partes são iguais, continua para a próxima parte
    }

    return 0; // As versões são iguais
}























function applyCKEditorTheme(editorId) {
    const isDark = document.documentElement.getAttribute('data-bs-theme') === 'dark';
    const backgroundColor = isDark ? '#121212' : '#ffffff';
    const textColor = isDark ? '#f8f9fa' : '#212529';
    const uiColor = isDark ? '#1e1e1e' : '#f5f5f5';

    const editorInstance = CKEDITOR.instances[editorId];
    if (editorInstance) {
        // Altera o conteúdo do editor
        /*const editorDoc = editorInstance.document;
        if (editorDoc) {
            const body = editorDoc.getBody();
            body.setStyle('background-color', backgroundColor);
            body.setStyle('color', textColor);
        }*/

        // Altera a interface visual do CKEditor
        editorInstance.setUiColor(uiColor);
        
        // Se estiver no modo "source"
        if (editorInstance.mode === 'source') {
            const textarea = editorInstance.container.$.querySelector('textarea.cke_source');
            if (textarea) {
                textarea.style.backgroundColor = backgroundColor;
                textarea.style.color = textColor;
            }
        } else if (editorInstance.document) {
            // Editor visual (WYSIWYG)
            const body = editorInstance.document.getBody();
            body.setStyle('background-color', backgroundColor);
            body.setStyle('color', textColor);
        }
    }
}


function initEditor(editorId, onlyCodeEditPlugin = false) {
    var parameters = {
        on: {
            instanceReady: function () {
                applyCKEditorTheme(editorId);
                
                const editor = CKEDITOR.instances[editorId];
                editor.on('mode', function () {
                    applyCKEditorTheme(editorId);
                });
            }
        }
    };
    
    if (onlyCodeEditPlugin) {
        Object.assign(parameters, {
            removePlugins: 'elementspath,resize',
            extraPlugins: 'sourcearea',
            toolbar: [
                { name: 'mode', items: ['Source'] }
            ],
            allowedContent: true,
            startupMode: 'source'
        });
    }
    
    CKEDITOR.replace(editorId, parameters);
}