$().ready(function () {
    if ($('.style.manageStaticBlock').length > 0) {
        var type_chosen = $('#type').val();
        update_edit(type_chosen);
        checkIfAnotherInstanceAllowed();

        $(document).on('change', '#type', function () {
            var type_chosen = $('#type').val();
            update_edit(type_chosen);
        });

        $('.manageStaticBlock').on('click', '.js_addNewInstance', function () {
            $.ajax({
                type: 'post',
                url: '/plugins/StaticBlocks/admin/ajax.php',
                data: {
                    ajax: true,
                    action: 'add_instance'
                },
                dataType: 'json',
                success: function (data) {
                    if (data.status == 'ok') {
                        $('.dynamic_content').append(data.html);
                        var type_chosen = $('#type').val();
                        update_edit(type_chosen);
                        init_tinymce();
                        checkIfAnotherInstanceAllowed();
                    }
                }
            })
        });
    }
});

/**
 * Function hides unnecessary options based on currenlty selected block type
 * and shows the currently selected one instead.
 * Called upon page load and select change
 *
 * @param  string    chosen class name of currenlty selected block type
 * @return undefined
 */
function update_edit(chosen) {
    $('.dynamic_content .row').hide();
    $('.dynamic_content .' + chosen).show();
}

function checkIfAnotherInstanceAllowed () {
    if ($('.dynamic_content .instance').length < $('#js_max_block_count').val()) {
        $('.js_addNewInstance').show();
    } else {
        $('.js_addNewInstance').hide();
    }
}