(function ($, undefined) {

    $(function () {

        var setSelectClone;

        /**
         * Escape characters in string for usage in regular expressions
         *
         * @param {String} Input string
         *
         * @returns {String} Escaped string
         */
        function escapeRegExp(str) {
            return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
        }

        var container = $('.js-meta-tag-container'),
                codemirrors = {},
                index = 0,
                form_name = container.attr('data-form-name'),
                regex = new RegExp(escapeRegExp(form_name) + '\\[([0-9]+)\\].+');

        /**
         * Scan the Indexes used for the MetaTags. This is used to make
         * sure the add MetaTag indexes don't overwrite existing MetaTags
         * The index is neved decreased/reset to cope with removed MetaTags
         *
         * @returns {undefined}
         */
        function resetIndex() {
            $('input[name],textarea[name],select[name]').each(function () {
                var name = $(this).attr("name");
                if (!regex.test(name)) {
                    return;
                }
                var n_index = parseInt(regex.exec(name)[1]);
                if (n_index >= index) {
                    index = n_index + 1;
                }
            });
        }
        resetIndex();


        /**
         * Update the visibility of the set selector based on the sets already included
         *
         * @returns {undefined}
         */
        function updateSetVisibility() {
            var select = $('.js-available-sets');
            if (setSelectClone === undefined) {
                setSelectClone = select.clone();
            }
            select.find('option[value!=""]').remove();
            setSelectClone.find('option[value!=""]').each(function () {
                var $this = $(this),
                        id = $this.attr('value');
                if ($('*[data-tag-set="' + id + '"]').length == 0) {
                    select.append($this.clone());
                }

            });
        }
        updateSetVisibility();

        // Handler for adding a new set
        $('.js-meta-tag-addset').on('click', function () {

            var select = $('.js-available-sets');

            // Check if an set was selected
            if (select.val() == '') {
                alert("Kies eerst een set");
                return;
            }

            // Determine ajax URL
            var url = select.find('option:selected').attr('data-url');

            // Fetch HTML for MetaTags in MetaTagSet
            $.get(url, function (data) {

                var div = $(data),
                        n_form_name = div.attr('data-form-name'),
                        n_regex = new RegExp('(' + escapeRegExp(n_form_name) + '\\[([0-9]+)\\]).+');


                // Make sure the names of the inputs match the expected names
                // this is needed because the form is injected into an unknown external
                // form.
                div.find('input[name],textarea[name],select[name]').each(function () {
                    var name = $(this).attr("name"),
                            matches, n_index;
                    if (!n_regex.test(name)) {
                        return;
                    }

                    // matches[1] = part of the name that must be replaces
                    // matches[2] = index
                    matches = n_regex.exec(name);

                    // Make sure the index is increased with base index
                    n_index = parseInt(matches[2]) + index;
                    $(this).attr("name", name.replace(matches[1], form_name + '[' + n_index + ']'));
                });


                // Append fetched and updated div contents to the contaienr
                div.contents().appendTo(container);

                // Update content settings within the MetaTag
                updateSetVisibility();
                $('input[type="checkbox"][data-toggle-codemirror]').each(updateCodeMirror);
                $('input[type="checkbox"]').each(updateCheckboxHideShow);
                
                // Reset the index
                resetIndex();
            });



        });

        // Delete Meta Tag sets
        container.on('click', '.js-meta-tag-set-del', function () {
            var $this = $(this),
                    confirm_message = $this.attr('data-confirm'),
                    item = $this.parents('.meta-tag-set').first();
            if (confirm(confirm_message)) {
                item.remove();
                updateSetVisibility();
            }
        });


        /**
         * Show/Hide contents based on checkbox
         *
         * @returns {undefined}
         */
        function updateCheckboxHideShow() {
            var id = $(this).attr('id'),
                    selected = $(this).is(':checked');
            if (selected) {
                $('*[data-show-on="' + id + '"]').toggleClass('hide', false);
                $('*[data-show-on="' + id + '"]').find('input,select,textarea').removeAttr('disabled');
                $('*[data-hide-on="' + id + '"]').toggleClass('hide', true);
                $('*[data-hide-on="' + id + '"]').find('input,select,textarea').attr('disabled', 'disabled');
            } else {
                $('*[data-show-on="' + id + '"]').toggleClass('hide', true);
                $('*[data-show-on="' + id + '"]').find('input,select,textarea').attr('disabled', 'disabled');
                $('*[data-hide-on="' + id + '"]').toggleClass('hide', false);
                $('*[data-hide-on="' + id + '"]').find('input,select,textarea').removeAttr('disabled');
            }
        }
        ;


        $('input[type="checkbox"]').each(updateCheckboxHideShow);
        container.on('click', 'input[type="checkbox"]', updateCheckboxHideShow);

        /**
         * Enable/Disable CodeMirror on input fields
         * @returns {undefined}
         */
        function updateCodeMirror() {
            var $this = $(this),
                checked = $this.is(':checked'),
                textarea_id = $this.attr('data-toggle-codemirror'),
                textarea = $('#' + textarea_id);

            if (checked && codemirrors[textarea_id] == undefined) {
                codemirrors[textarea_id] = CodeMirror.fromTextArea(textarea[0], {
                    theme: "monokai",
                    mode: {name: "javascript"}
                });
                codemirrors[textarea_id].setSize('100%', '175px');
            } else if (!checked && codemirrors[textarea_id] != undefined) {
                codemirrors[textarea_id].toTextArea();
                codemirrors[textarea_id] = undefined;
            }
        }
        $('input[type="checkbox"][data-toggle-codemirror]').each(updateCodeMirror);
        container.on('click', 'input[type="checkbox"][data-toggle-codemirror]', updateCodeMirror);

        // Refresh the appearance of code mirror 
        container.find('.panel').on('shown.bs.collapse', function () {
            $(this).find('input[type="checkbox"][data-toggle-codemirror]').each(function() {
                var $this = $(this),
                    textarea_id = $this.attr('data-toggle-codemirror');
                if (codemirrors[textarea_id] !== undefined) {
                    codemirrors[textarea_id].refresh();
                }
            });
        });

    });

})(jQuery);