(function ($, undefined) {

    var codemirrors = {},
        index = $('.js-form-field-container .js-form-field').length + 1,
        form = $('.js-form-serialize');

    $(function () {

        // Save content to textarea before serializing
        form.on('beforeserialize', function() {
            for(var id in codemirrors) {
                if (codemirrors.hasOwnProperty(id)) {
                    codemirrors[id].save();
                }
            }
        });

        // Define "twig" mode, a mode with html and twig
        // @todo figure out how to get jinja2 highlighting to work
        // inside multiplexer
        CodeMirror.defineMode("twig", function (config) {
            return CodeMirror.multiplexingMode(
                CodeMirror.getMode(config, "text/html"),
                { open: "{{", close: "}}", mode: CodeMirror.getMode(config, "jinja2"), parseDelimiters :  true },
                { open: "{#", close: "#}", mode: CodeMirror.getMode(config, "jinja2"), parseDelimiters :  true },
                { open: "{%", close: "%}", mode: CodeMirror.getMode(config, "jinja2"), parseDelimiters :  true }
            );
        });

        // Initialiseer CodeMirror
        $('textarea.codemirror[id][data-mode]').each(function () {
            var el = $(this), id = el.attr('id'), mode = el.attr('data-mode');
            codemirrors[id] = CodeMirror.fromTextArea(el[0], {
                theme: 'monokai',
                mode: mode,
                lineNumbers: true
            });
            codemirrors[id].setSize('100%', '600px');
        });

        // Handel wisselen van tabs af
        $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
            var panel = $($(e.target).attr('href'));
            panel.find('textarea.codemirror[id][data-mode]').each(function () {
                var el = $(this), id = el.attr('id');
                if (codemirrors[id] !== undefined) {
                    codemirrors[id].refresh();
                    codemirrors[id].setSize('100%', '600px');
                }
            });
        });

        /**
         * Bepaal tekstweergave voor veld
         *
         * @param {DOMElement} el 
         * @returns {String}
         */
        var getTextValue = function (el) {
            if (el.is('select')) {
                if (el.find('option:selected').length > 0) {
                    return el.find('option:selected').text();
                } else {
                    return '';
                }
            }
            return el.val();
        };

        /**
         * Voeg event listeners toe aan container
         *
         * @param {DOMElement} container
         */
        var addFieldListeners = function (container) {
            container.find('[data-source]').each(function () {
                var el = $(this), target = $(el.attr('data-source'));
                el.text(getTextValue(target));
                target.on('change keypress keyup', function () {
                    el.text(getTextValue(target));
                });
            });
        };

        /**
         * Update volgorde veld
         */
        var updateVolgorde = function () {
            var val = 1;
            $('.js-form-field-volgorde').each(function () {
                $(this).val(val).trigger('change');
                val++;
            });
        };

        // Update current items, add listeners
        updateVolgorde();
        $('.js-form-field').each(function () {
            addFieldListeners($(this));
        });

        // Make fields sortable
        $('.js-form-field-container').sortable({
            items: "> .js-form-field"
        });

        // Update volgorde after sorting
        $('.js-form-field-container').on('sortupdate', function () {
            updateVolgorde();
        });

        // Delete field
        $('.js-form-field-container').on('click', '.js-form-field-del', function (e) {
            var el = $(this), message = el.attr('data-confirm');
            e.preventDefault();
            if (confirm(message)) {
                el.parents('.js-form-field').remove();
                updateVolgorde();
                $('.js-form-field-container').sortable('refresh');
            }
        });

        // Add Field
        $('.js-form-field-add').on('click', function () {
            var container = $('.js-form-field-container'),
                    prototype = container.attr('data-prototype'),
                    $prototype;
            $prototype = $(prototype.replace(/__name__/g, index));
            index++;

            container.append($prototype);
            updateVolgorde();
            addFieldListeners($prototype);

            $('.js-form-field-container').sortable('refresh');
        });


        $('button[data-url][data-confirm][data-target]').on('click', function () {
            var el = $(this),
                    url = el.attr('data-url'),
                    target = el.attr('data-target'),
                    message = el.attr('data-confirm'),
                    xhr;

            if (codemirrors[target] == undefined) {
                return;
            }

            if (!confirm(message)) {
                return;
            }

            xhr = $.ajax({
                type: 'POST',
                url: url,
                data: form.serialize()
            });

            xhr.fail(function() {
                alert("Er is een fout opgetreden tijdens het laden van de HTML");
            });

            xhr.done(function (data) {
                if (data.html != undefined) {
                    codemirrors[target].setValue(data.html);
                }
            });


        });


    });

})(jQuery);