{% extends 'djedi/plugins/txt/editor.html' %}

{% block editor %}
    <textarea name="data" class="form-control md-source"></textarea>
{% endblock editor %}

{% block plugin_script %}
    <script>
        var RENDER_TIMEOUT = 400; // ms

        new window.Editor({
            uri: '{{ uri }}',
            initialize: function () {
                editor = this

                editor.renderTimeoutId = undefined;

                editor.$textarea = $('textarea');

                editor.$textarea.on('keydown', function(e) {
                    if(e.keyCode === 9) { // tab was pressed
                        // ### Get caret position/selection
                        var start = this.selectionStart;
                            end = this.selectionEnd;

                        var $this = $(this);

                        // ### Set textarea value to: text before caret + tab + text after caret
                        $this.val($this.val().substring(0, start)
                                    + "\t"
                                    + $this.val().substring(end));

                        // ### Put caret at right position again
                        this.selectionStart = this.selectionEnd = start + 1;

                        // ### Prevent the focus lose
                        return false;
                    }
                });

                editor.$textarea.on('input', function () {
                    editor.setState('dirty');
                    if (editor.renderTimeoutId != null) {
                      clearTimeout(editor.renderTimeoutId);
                    }
                    editor.renderTimeoutId = setTimeout(function() {
                      editor.renderTimeoutId = undefined;
                      editor.onFormChange();
                    }, RENDER_TIMEOUT);
                });
            },
            render: function (node) {
                editor.$textarea.val(node.data);
            },
            onFormChange: function() {
                if (editor.renderTimeoutId == null) {
                  clearTimeout(editor.renderTimeoutId);
                }
                editor.renderContent(editor.$textarea.val(), true);
            }
        });
    </script>
{% endblock plugin_script %}
