(function( $ ) {
    'use strict';

    var toggleSampleCode = function() {
        var toggler = $( this ),
            textarea = toggler.siblings( 'textarea' );

        if ( textarea.is( ':visible' ) ) {
            textarea.slideUp();
            toggler.addClass('close');
        } else {
            textarea.slideDown();
            toggler.removeClass('close');
        }
    },

        addSampleCode = function() {
            var samples = $('.doc8-attachments'),
                newsample = samples.first().clone();

            // Close all previous sample codes
            samples.find( '.doc8-toggle' ).each( function() {
                var toggler = $(this);

                if ( toggler.is('.close') ) {
                    return true;
                }

                toggler.trigger( 'click' );
            });

            newsample.find( 'select, textarea' ).val('');
            newsample.find('.doc8-toggle').removeClass('close');
            newsample.find('textarea').attr('style', '');
            newsample.insertAfter( samples.last() );
        },

        removeSampleCode = function() {
            var button = $(this),
                div = button.parents('.doc8-attachments');

            div.slideUp(function() {
                div.remove();
            });
        };


    $(document).on( 'click', '.doc8-toggle', toggleSampleCode )
        .on( 'click', '.doc8-add button', addSampleCode )
        .on( 'click', '.doc8-remove', removeSampleCode );

})(jQuery);