;( function($, window, document, undefined)
{
    "use strict";

    var pluginName = "igniteEditor",
        defaults = {
            csrfToken: '',
            templateCode: '',
            datetimepicker: {
                selector: '.datepicker',
                options: {format: 'YYYY-MM-DD HH:mm:ss'}
            },
            summernote: {
                selector: '.editor',
                toolbar: [
                    ['style', ['style', 'bold', 'italic', 'underline', 'clear']],
                    ['font', ['strikethrough', 'superscript', 'subscript']],
                    ['para', ['ul', 'ol', 'paragraph']],
                    ['insert', ['picture', 'link']],
                    ['misc', ['fullscreen', 'codeview', 'undo', 'redo', 'help']],
                    ['custom', ['template']]
                ]
            }
        };

    function Plugin (element, options) {
        this.element = element;
        this.settings = $.extend({}, defaults, options);
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
    }

    $.extend(Plugin.prototype, {
        init: function() {
            this.initDateTimePickers();
            this.initWysiwyg();
            this.initProtection();
            this.initCodeGenerator();
        },
        initCodeGenerator: function() {
            var $title = $('#form-content-title');
            var $code = $('#form-content-code');

            if ($code.attr('disabled') || $code.attr('readonly')) {
                return;
            }

            $title.on('keyup', function() {
                $code.val(
                    $.trim($title.val())
                    .toLowerCase()
                    .replace(/[^a-z0-9]+|\s+/gmi, '-')
                    .replace(/[\-]+$/g, '')
                );
            });
        },
        initProtection: function() {
            var $isProtected = $('#form-content-is-protected');
            var $allowedGroups = $('#form-content-allowed-groups');

            $isProtected.on('change', function(evt) {
                var $checkbox = $(this);
                if ($checkbox.is(':checked')) {
                    $allowedGroups.removeClass('hide');
                } else {
                    $allowedGroups.addClass('hide');
                }
            });
        },
        initDateTimePickers: function() {
            return $(this.settings.datetimepicker.selector)
                .datetimepicker(this.settings.datetimepicker.options);
        },
        initWysiwyg: function() {
            var self = this;
            var $editor = $(this.settings.summernote.selector);
            $editor.summernote({
                dialogsInBody: true,
                toolbar: this.settings.summernote.toolbar,
                callbacks: {
                    onImageUpload: function(files) {
                        $.each(files, function(idx, file) {
                            var formData = new FormData();
                            formData.append('myfile', file);
                            $.ajax({
                                method: "POST",
                                data: formData,
                                url: '/admin/cms/pages/api/upload',
                                contentType: false,
                                processData: false,
                                headers: {
                                    'X-CSRF-TOKEN': self.settings.csrfToken
                                }
                            }).done(function (url) {
                                $editor.summernote('insertImage', url);
                            });
                        });
                    }
                },
                buttons: {
                    template: function(context) {
                        return self.getTemplateButton.apply(this, [context, $editor, self]);
                    }
                }
            });
            $(this.element).on('submit', function(e) {
                if ($editor.summernote('codeview.isActivated')) {
                    $editor.summernote('codeview.deactivate');
                }
            });

            return $editor;
        },
        getTemplateButton: function (context, $editor, self) {
            var ui = $.summernote.ui;
            var templates = {};
            var button = ui.button({
                contents: '<i class="fa fa-file-text"/>',
                tooltip: 'Content Templates',
                click: function () {
                    var $modal = $('#template-modal');
                    var $selector = $('#template-selector');
                    var $errors = $('#template-errors');
                    var $selected = $('#template-selected');
                    var $fields = $('#template-fields');

                    $.ajax({
                        method: "POST",
                        data: {code: self.settings.templateCode},
                        url: $modal.attr('data-source'),
                        dataType: "json",
                        headers: {
                            'X-CSRF-TOKEN': self.settings.csrfToken
                        }
                    }).done(function (data) {
                        if ($.isArray(data)) {
                            $errors.removeClass('hide');
                            $fields.addClass('hide');
                            $modal.modal('show');
                            $selected.addClass('hide');
                            return;
                        }

                        $errors.addClass('hide');
                        $fields.removeClass('hide');
                        $selected.removeClass('hide');
                        $selector.empty().focus();

                        for (var key in data) {
                            var template = data[key];
                            $selector.append(
                                $('<option></option>').attr('value', key).html(template.name)
                            );
                            templates[key] = template.copy;
                        }

                        $selected.one('click', function(evt) {
                            evt.preventDefault();
                            if (window.confirm('Inserting the template will erase the existing content. Are you sure you want to continue?')) {
                                var key = $selector.val();
                                if (templates.hasOwnProperty(key)) {
                                    $editor.summernote('code', templates[key]);
                                    $modal.modal('hide');
                                }
                            }
                        });
                        $modal.modal('show');
                    });
                }
            });

            return button.render();
        }
    });

    $.fn[pluginName] = function(options) {
        return this.each( function() {
            if (!$.data(this, "plugin_" + pluginName)) {
                $.data(this, "plugin_" + pluginName, new Plugin(this, options));
            }
        });
    };

} )(jQuery, window, document);