/**
 * Copyright (c) 2015 XeroGrafiX
 */

( function() {
    'use strict';

    var commandDefinition = {
        readOnly: 1,
        preserveState: true,
        editorFocus: false,
        plusIconClass: 'glyphicon-plus-sign',
        minusIconClass: 'glyphicon-minus-sign',
        plusIconStyle : 'style="color: green; font-size: 14px; cursor: pointer;"',
        minusIconStyle: 'style="color: red; font-size: 14px; cursor: pointer;"',
        excludeTagsForIcons: 'a',

        exec: function( editor ) {
            this.toggleState();
            this.refresh( editor );
        },

        refresh: function ( editor ) {
            if (this.state == CKEDITOR.TRISTATE_ON) {
                // add buttons when command button is enabled

                this.addButtons ( editor);
            }
            else {
                // remove buttons when command button is disabled
                this.removeButtons( editor );
            }
        },

        removeButtons: function ( editor ) {
            var editorDocument = editor.editable().$;

            // remove all buttons
            $(editorDocument).find('span.' + this.plusIconClass).remove();
            $(editorDocument).find('span.' + this.minusIconClass).remove();

            // enable inlineEditing again
            //editor.execCommand('inlineEditing');

        },

        addButtons: function( editor ) {
            var editorDocument = editor.editable().$;

            var plusButtonClickHandler = function (ev) {
                // console.log('plus button click handler');
                editor.plusButton = this;
                editor.execCommand("templateEditorDialog");
            };

            var minusButtonClickHandler = function (ev) {
                // console.log('minus button click handler');
                var targetElement = $(ev.target).next();
                $(targetElement).remove();
                // remove plus/minus buttons and add them again
                // to avoid double plus buttons following each other
                editor.execCommand("templateEditor");
                editor.execCommand("templateEditor");
            };


            var plusButton = $('<span class="glyphicon ' + this.plusIconClass + ' templateEditor"' + this.plusIconStyle + '></span>');
            plusButton.bind ('click', plusButtonClickHandler);

            var minusButton = $('<span class="glyphicon ' + this.minusIconClass + ' templateEditor pull-right"' + this.minusIconStyle + '></span>');
            minusButton.bind('click', minusButtonClickHandler);

            // add plus after and before each element containing attribute contenteditable=true
            $(editorDocument).find('[contenteditable=true]').not(this.excludeTagsForIcons).before(plusButton.clone(true)).after(plusButton.clone(true));
            // add minus icon into each element containing attribute contenteditable=true
            //$(editorDocument).find('[contenteditable=true]').append(minusButton);
            $(editorDocument).find('[contenteditable=true]').not(this.excludeTagsForIcons).before(minusButton.clone(true));
            $(editorDocument).find('a.btn-xtlive').parent().after(plusButton.clone(true));
            $(editorDocument).find('a.btn-xtlive').parent().before(minusButton.clone(true));
            $(editorDocument).find('a.btn-xtlive-big').parent().after(plusButton.clone(true));
            $(editorDocument).find('a.btn-xtlive-big').parent().before(minusButton.clone(true));
            // remove plus icon following another glyphicon-plus (we do not need two glyphicons at the same place)
            $(editorDocument).find('span.' + this.plusIconClass + '.templateEditor+span.' + this.plusIconClass + '.templateEditor').remove();
            $(editorDocument).find('span.' + this.minusIconClass + '.templateEditor+span.' + this.minusIconClass + '.templateEditor').remove();
            // append plus icon to empty cols
            $(editorDocument).find('div[class*="col-"]:empty').append(plusButton.clone(true));
            // avoid plus buttons between image and figcaption
            $(editorDocument).find('img+span.templateEditor+figcaption').prev().remove();
            // disable inlineEditing temporary (to avoid manually removement of buttons)
            //$(editorDocument).find('[contenteditable=true]').attr('contenteditable', 'false');

            // remove glyphicons within <a> tags
            $(editorDocument).find('a > span.' + this.plusIconClass + '.templateEditor').remove();
            $(editorDocument).find('a > span.' + this.minusIconClass + '.templateEditor').remove();
        }
    };

    CKEDITOR.plugins.add( 'templateEditor', {
        icons: 'templateEditor',
        onLoad: function() {

        },
        init: function( editor ) {
            if ( editor.config.enableTemplateEditor) { // show templateEditor button & dialog only if config in editor is enabled
                // register templateEditor command
                var command = editor.addCommand( 'templateEditor', commandDefinition );
                command.canUndo = false;
                CKEDITOR.dialog.add( 'templateEditorDialog', this.path + 'dialogs/templateEditorDialog.js' );
                // register dialog command for templateEditor
                editor.addCommand( 'templateEditorDialog', new CKEDITOR.dialogCommand( 'templateEditorDialog' ) );

                if ( editor.config.startupTemplateEditor )
                    command.setState( CKEDITOR.TRISTATE_ON );

                // following command enables templateEditor Button in CKEDITOR toolbar
                /*editor.ui.addButton && editor.ui.addButton( 'TemplateEditor', {
                 label: 'Template editieren',
                 command: 'templateEditor',
                 toolbar: 'others'
                 } );*/
            }
        }
    } );
} )();