var HtmlTemplate = (function() {
    var groupValidation = {
        name: false,
        type: false
    };

    var initEditor = function (textareaElement) {
        this.cssEditor = new AceEditor();
        this.cssEditor.init(textareaElement, "html");
    };

    var resolveContentEditor = function (contentElement) {
        var _aceEditor = contentElement.data("aceEditor");
        _aceEditor.getSession().setMode("ace/mode/html");
        _aceEditor.codeElement = contentElement;

        var helper = new AceEditorSyncHelper(_aceEditor);
        helper.bindWithPreview();
    };

    var initTemplateGroupModal = function (groupInput) {
        var newGroupRoute = Routing.generate('admin_html_template_group_new');

        bindTemplateGroupValidation();

        $('[data-create-template-group]').click(function() {
            var modal = bootstrap.createModal();

            $.post( newGroupRoute, {} , function(data) {
                modal = modal.show(
                    Translator.trans('admin_html_template.group.title'),
                    data.html,
                    Translator.trans('admin_html_template.group.button')
                );

                modal.find("[data-dismiss='modal']").on("click", function () {
                    modal.modal("hide");
                    modal.remove();
                });

                modal.find("[data-btn-type='save']").on("click", function () {
                    $.post(newGroupRoute, modal.find("form:first").serialize(), function(data, textStatus, xhr) {
                        if(xhr.status === 200) {
                            modal.find(".modal-body").html(data.html);
                        } else if (xhr.status === 201) {
                            $("[name='admin_html_template[group]']")
                                .append($("<option>", {
                                    value: data.id,
                                    text: data.text,
                                    "data-group-type": data.types

                                }))
                                .val(data.id)
                                .trigger("change.select2");

                            toggleReplacements(groupInput);

                            modal.modal("hide");
                            modal.remove();
                        }
                    });
                });

                toggleTemplateGroupSubmit();
            });
        });
    };

    var bindTemplateGroupValidation = function () {
        var $body = $("body");

        $body.on("input", "#admin_html_template_group_name", function () {
            groupValidation.name = $(this).val().length > 0;

            toggleTemplateGroupSubmit();
        });

        $body.on("change", "[name^='admin_html_template_group[type]']", function () {
            groupValidation.type = $("[name^='admin_html_template_group[type]']:checked").length > 0;

            toggleTemplateGroupSubmit();
        });
    };

    var isTemplateGroupValid = function () {
        return groupValidation.name === true && groupValidation.type === true;
    };

    var toggleTemplateGroupSubmit = function () {
        $("[data-btn-type='save']").prop("disabled", !isTemplateGroupValid());
    };

    var bindCollapsableItems = function () {
        $('[data-collapsable]').each(function(){
            var collapseBtn     = $('[data-collapsable-trigger]', $(this)),
                collapseElement = $('[data-collapsable-element]', $(this)),
                slideTime       = 200;

            collapseBtn.on('click', function() {
                if(collapseElement.is(':visible')) {
                    collapseElement.slideUp(slideTime);
                    collapseBtn.removeClass('is-opened');
                    collapseBtn.addClass('is-closed');
                }
                if(collapseElement.is(':hidden')) {
                    collapseElement.slideDown(slideTime);
                    collapseBtn.removeClass('is-closed');
                    collapseBtn.addClass('is-opened');
                }
            });
        });
    };

    var bindContentWidthButtons = function () {
        $("[data-width]").on("click", function (event) {
            event.preventDefault();
            var iframe = $("iframe", $("[data-role='preview-placeholder']")),
                width = $(this).data("width");

            $("[data-width]").removeClass("active");
            $(this).addClass("active");

            if (width === -1) {
                iframe
                    .attr("width", "")
                    .css("width", "");
            } else {
                iframe
                    .attr("width", width)
                    .css("width", width);
            }
        });
    };

    var showReplacements = function (groups) {
        for (var i = 0; i < groups.length; i++) {
            $("[data-mailing-replacements='"+groups[i]+"']").show();
        }
    };

    var toggleReplacements = function (selectInput) {
        $("[data-mailing-replacements]").hide();

        showReplacements(getSelectedGroupType(selectInput));
    };

    var getSelectedGroupType = function (selectInput) {
        return selectInput.find("option:selected").data("group-type");
    };

    var bindReplacements = function (selectInput) {
        toggleReplacements(selectInput);

        selectInput.on("change", function () {
            toggleReplacements($(this));
        });
    };

    return {
        init: function (contentElement, groupInput) {
            initEditor(contentElement);
            resolveContentEditor(contentElement);
            initTemplateGroupModal(groupInput);
            bindContentWidthButtons();
            bindReplacements(groupInput);
        },
        bindCollapsable: function () {
            bindCollapsableItems();
        }
    };
})();
