let ace_editor_list = [];
jQuery(document).ready(function($){
    $('button.collapsible').on('click', function(){
        let collapsible_name = $(this).attr('data-collapsible');
        let linked_div = $('div.collapsible_content[data-collapsible="' + collapsible_name + '"]');
        // Make slide down effect
        if (linked_div[0].style.maxHeight){
            linked_div[0].style.maxHeight = null;
            //Switch to + icon
            $('svg path', this).attr('d', 'M352 128C352 110.3 337.7 96 320 96C302.3 96 288 110.3 288 128L288 288L128 288C110.3 288 96 302.3 96 320C96 337.7 110.3 352 128 352L288 352L288 512C288 529.7 302.3 544 320 544C337.7 544 352 529.7 352 512L352 352L512 352C529.7 352 544 337.7 544 320C544 302.3 529.7 288 512 288L352 288L352 128z');
        } else {
            linked_div[0].style.maxHeight = linked_div[0].scrollHeight + "px";
            //Switch to - icon
            $('svg path', this).attr('d', 'M128 288C110.3 288 96 302.3 96 320C96 337.7 110.3 352 128 352L512 352C529.7 352 544 337.7 544 320C544 302.3 529.7 288 512 288L128 288z');
        }
        return false;
    });

    $('.ace-editor').each(function(){
        let editor = ace.edit($(this).attr('id'));
        let mode = $(this).attr('data-mode');
        let element = $(this).attr('data-element');
        editor.setTheme("ace/theme/chrome");
        editor.setShowPrintMargin(false);
        editor.getSession().setMode(`ace/mode/${mode}`);
        editor.getSession().setValue(jQuery(`#${element}`).val());
        editor.resize();

        ace_editor_list.push({id: element, editor: editor});
    });

    $('#w2pshop_settings_form').on('submit', function(e) {
        for(let x = 0; x < ace_editor_list.length; x++){
            jQuery(`#${ace_editor_list[x].id}`).val(ace_editor_list[x].editor.getValue());
        }
    });

    $(document).bind("keydown", function(e) {
        //Save setting form on Ctrl+S
        if (e.which == 83 && e.ctrlKey) {
            $('input[name="save_w2pshop_settings"]').click();
            return false;
        }
    });
});
