(function( $ ){
    'use strict';

    var createEditor = function( container, lang ) {
            var Editor,
                textarea  = container.find( '[data-code="' + lang + '"]' ),
                editor_id = textarea.attr( 'id' ) + '-editor',
                div = $( '<div />', {
                    class: 'doc8-editor',
                    id: editor_id
                } );

            // Remove previous editor instance if there's any
            container.find( '.doc8-editor' ).remove();

            div.insertAfter( textarea );

            Editor = ace.edit( editor_id );
            Editor.setTheme( 'ace/theme/monokai' );
            Editor.session.setMode( 'ace/mode/' + lang );
            Editor.setReadOnly(true);
            Editor.setShowPrintMargin(false);
            Editor.setValue( textarea.val() );
            Editor.gotoLine(1);
        },

        enableEditor = function() {
            var elem = $( this ),
                siblings = elem.siblings(),
                container = elem.parents( '.code-attachments' ),
                tab = elem.find( 'a' ),
                lang = tab.data( 'lang' );

            siblings.removeClass('active');
            elem.addClass('active');

            createEditor( container, lang );

            return false;
        };

    $( '.code-item li', '.code-attachments' ).on( 'click', enableEditor );

    // Trigger active tab
    $( '.code-item .active', '.code-attachments' ).each( enableEditor );
})(jQuery);