var Users = (function () {
    var bindFunction = function(){

        window.options = [];

        $('[data-modal="user-role-modal"]').on('show.bs.modal', function (e) {
            var el      = $('select[id$="_subsite"]', $(this));
            var localesEl = $('select[id$="_defaultLocale"]', $(this));
            var selectValue =el.val();

            if (!selectValue) {
                localesEl.empty();
                toggleModalSubmit("disabled");
            } else {
                toggleModalSubmit("enabled");
            }
        });

        $(".cs_user_new").on("change", '[data-action="subsite-selection"]', function(){
            var _this   = $(this);
            var subsite = _this.val();

            if (!subsite) {
                toggleModalSubmit("disabled");

                return false;
            }

            $.ajax({
                url: Routing.generate("cs_common_cs_user_update_locales"),
                data: { subsite: subsite },
                method: "get",
                success: function(response) {
                    var select = _this.closest(".form-group").parent().find('[data-action="locale-selection"]');
                    var $options = $();
                    var defaultData = null;

                    $.each(response, function(k,v) {

                        if (!defaultData) {
                            defaultData = {id:k, text: v};
                        }

                        $options = $options.add(
                            $('<option>').attr('value', k).text(v)
                        );
                    });


                    select.select2("data", defaultData);
                    select.html($options);

                    toggleModalSubmit("enabled");
                }
            });
        });


        $('#comitiumsuite_bundle_cscommon_csuserbundle_csuser_email').on("change", function(){
            var email = $(this).val();
            $.ajax({
                async: false,
                url: Routing.generate("cs_utils_gravatar"),
                data: { email: email, s: 130 },
                success: function(response) {
                    $('.current-profile-picture').attr({
                        "src": response,
                        "alt": email,
                        "title": email
                    });
                    $("#comitiumsuite_bundle_cscommon_csuserbundle_csuser_avatar").val("");
                }
            });
        });

        $("body")
            .on("click", '[data-btn-type="save"]', function (e) {
                e.preventDefault();
                var newItem = $(".modal-body > .form-content");
                newItem.find("select").select2('destroy');
                var index = newItem.data('index');
                var element = $(this);
                var selected_role = newItem.find("select[id$='_role'] option:selected");
                var selected_defaultLocale = newItem.find("select[id$='_defaultLocale']");
                var role = {id: selected_role.val(), name: selected_role.html()};
                var defaultLocale = {id: selected_defaultLocale.val(), name: selected_defaultLocale.html()};

                if (element.hasClass('save-new-role')) {

                    var prototype = $(".user_rel_roles").data("prototype");
                    var table_roles_body = $(".table-roles").find("tbody");
                    var selected_subsites = newItem.find("select[id$='_subsite_array'] option:selected");

                    selected_subsites.each(function (k, v) {
                        var substie_option = $(v).val();
                        var newIndex = k + index;
                        var newForm = $(prototype.replace(/__name__/g, newIndex));

                        newForm.find("#comitiumsuite_bundle_cscommon_csuserbundle_csuser_rolesSubsites_" + newIndex + "_subsite option[value=" + substie_option + "]").prop("selected", true);
                        newForm.find("#comitiumsuite_bundle_cscommon_csuserbundle_csuser_rolesSubsites_" + newIndex + "_role option[value=" + role.id + "]").prop("selected", true);
                        //newForm.find("#comitiumsuite_bundle_cscommon_csuserbundle_csuser_rolesSubsites_" + newIndex + "_defaultLocale option[value=" + defaultLocale.id + "]").prop("selected", true);


                        var oldId   = selected_defaultLocale.attr("id");
                        var oldName = selected_defaultLocale.attr("name");
                        var newId   = oldId.replace(/(\d+)/g, newIndex);
                        var newName = oldName.replace(/(\d+)/g, newIndex);

                        selected_defaultLocale.attr({
                            "id": newId,
                            "name": newName
                        });

                        newForm.find("#comitiumsuite_bundle_cscommon_csuserbundle_csuser_rolesSubsites_" + newIndex + "_defaultLocale")
                            .replaceWith(selected_defaultLocale)
                        ;

                        newItem.html(newItem.html().replace(index, newIndex));

                        var site = $(v).parent().attr('label');
                        var span_site = $("<span></span>", {class: 'site'}).html(site);
                        var span_subsite = $("<span></span>", {
                            class: 'subsite',
                            "data-id": substie_option
                        }).html($(v).text());

                        var td_site = $("<td></td>").append(span_site).append(" - ").append(span_subsite);
                        var div_hidden = $("<div></div>", {class: 'hidden form-info'});
                        div_hidden.append(newForm.find(".form-group"));
                        td_site.append(div_hidden);
                        var td_role = $($("<td>" + role.name + "</td>"));
                        var td_actions = $($('<td><a class="btn btn-sm defaultBtn edit-role" href="#"><i class="fa fa-pencil"></i>' + Translator.trans("cs_core.action.edit.default") + '</a></td>'));

                        var tr = $($("<tr></tr>", {
                            "data-role-id": newIndex,
                            id: "comitiumsuite_bundle_cscommon_csuserbundle_csuser_rolesSubsites_" + newIndex
                        })).append(td_site).append(td_role).append(td_actions);

                        addSubsiteToArray(tr, 'delete');

                        table_roles_body.append(tr);

                    });
                    newItem.empty();
                } else if (element.hasClass('save-edit-role')) {
                    var current_tr = $("[data-role-id=" + element.data('role-id') + "]").closest("tr");
                    addSubsiteToArray(current_tr, 'add');
                    var selected_subsite = newItem.find("select[id$='_subsite'] option:selected");
                    var td_subsite = current_tr.find("td:nth-child(1)");
                    var td_role = current_tr.find("td:nth-child(2)");
                    var site = selected_subsite.parent().attr("label");
                    var subsite = selected_subsite.text();
                    td_role.html(role.name);
                    td_subsite.find(".subsite").html(subsite).data("id", parseInt(selected_subsite.val()));
                    td_subsite.find(".site").html(site);
                    current_tr.children().first().find(".form-info").append(newItem.find(".form-group")).addClass("hidden");
                    addSubsiteToArray(current_tr, 'delete');
                }
                $(".cs_user_new .table-scrollable").removeClass('hidden');

                var alert = ".cs_user_new .tab-pane .alert-";
                alert += ($(".tab-content > .alert-danger").length) ? "danger" : "info";
                $(alert).addClass('hidden');

                $("#basic").modal("hide");
            })
            .on("click", ".edit-role", function (e) {
                e.preventDefault();
                var current_tr = $(this).closest("tr");
                var user_role_id = $(this).closest("tr").data("role-id");
                var form_content = $(this).closest("tr").find(".form-info");
                form_content.removeClass("hidden");
                var form = form_content.find(".form-group");
                form.find("select[id$='_subsite_array']").closest('.form-group').hide();


                form
                  .find("select")
                  .select2({
                      width: 'element',
                      formatNoMatches: function () {
                          return Translator.trans('cs_core.messages.no_items_list');
                      }});




                $(".modal-body > .form-content").empty().prepend(form);
                $('[data-btn-type="save"]').removeClass("save-new-role").addClass("save-edit-role").data('role-id', user_role_id);

                $('[data-btn-type="cancel"]', '[data-modal="user-role-modal"]').addClass("restore-role");

                $('[data-btn-type="delete"]').show();
                setOptionsToSelect(form.find("select[id$='_subsite']"), current_tr.find(".subsite").html());
                $("#basic").modal("show");
            })
            .on("click", '[data-modal="user-role-modal"] [data-btn-type="cancel"]', function (e) {
                e.preventDefault();
                $("#basic").modal("hide");
            })
            .on("click", '[data-modal="user-role-modal"] [data-btn-type="delete"]', function (e) {
                e.preventDefault();
                $("#basic").modal("hide");
                var role_id = $(".save-edit-role").data('role-id');
                if (role_id) {
                    var current_tr = $("[data-role-id=" + role_id + "]").closest("tr");
                    current_tr.remove();
                    addSubsiteToArray(current_tr, 'add');
                    $(".modal-body > .form-content").empty();
                    if (!$(".cs_user_new .table-scrollable table tbody tr").length) {
                        $(".cs_user_new .table-scrollable").addClass('hidden');

                        var alert = ".cs_user_new .tab-pane .alert-";
                        alert += ($(".tab-content > .alert-danger").length) ? "danger" : "info";
                        $(alert).removeClass('hidden');
                    }
                }
            })
            .on("click", "tbody tr.warning td a span.fa", function (e) {
                e.preventDefault();

                var element = $(this);
                var event = 'slideUp';

                if (element.hasClass('fa-minus-square-o')) {
                    element.removeClass('fa-minus-square-o');
                    element.addClass("fa-plus-square-o");
                } else if (element.hasClass("fa-plus-square-o")) {
                    event = 'slideDown';
                    element.addClass('fa-minus-square-o');
                    element.removeClass("fa-plus-square-o");
                }

                element.closest('tbody').next()[event]("slow");
            })
        ;

        $("#basic").on('hidden.bs.modal', function (e) {
            if ($(this).find(".restore-role").length) {
                var role_id = $(".save-edit-role").data('role-id');
                var newItem = $(".modal-body > .form-content");
                var current_tr = $("[data-role-id=" + role_id + "]").closest("tr");
                current_tr.children().first().find(".form-info").addClass("hidden").append(newItem.find(".form-group"));
            }
        });

        $(".change-user-tab").on("click", function (e) {
            e.preventDefault();
            $(".nav-pills").find("a[href='" + $(this).attr("href") + "']").tab("show");
        });

        $('tbody.user_rel_roles').collection({
            button_template: '<button type="button" class="btn mainBtn">' + Translator.trans('cs_core.action.new.m', {"something": Translator.transChoice('cs_core.entity.role', 1)}) + '</button>',
            label: false,
            childrenFilter: "tr",
            insertButtonSelector: "#add_new_role",
            afterCreate: function (e) {
                var element = e.detail.element;
                element.find(".hidden").removeClass("hidden");
                var form = element.find(".form-group");

                form
                  .find("select")
                  .select2({
                      width: 'resolve',
                      formatNoMatches: function () {
                          return Translator.trans('cs_core.messages.no_items_list');
                    }});

                setOptionsToSelect(form.find("select[id$='_subsite_array']"));
                form.find("select[id$='_subsite']").closest('.form-group').hide();
                $(".modal-body > .form-content").empty().html(form).data('index', $(this).data('index'));
                $('[data-btn-type="save"]').addClass("save-new-role").removeClass("save-edit-role");
                $('[data-btn-type="cancel"]', '[data-modal="user-role-modal]').removeClass("restore-role");
                element.remove();
                $('[data-btn-type="delete"]').hide();
                $("#basic").modal("show");
            }
        });

        $(".select-user-picture img").on("click", function (e) {
            e.preventDefault();
            var src = $(this).attr("src");
            $(".current-profile-picture").attr("src", src);
            $("#comitiumsuite_bundle_cscommon_csuserbundle_csuser_avatar").val(src);
            $("#comitiumsuite_bundle_cscommon_csuserbundle_csuser_asset").val("");
        });

        $("input[id$='_all'], input[id$='permissions_all']").on('switchChange.bootstrapSwitch', function (event, state) {
            $(this).closest("tr").find("td:not(:last-child) input").bootstrapSwitch('state', state);
            if ($(this).attr("id").indexOf("permissions_all") > -1) {
                var current_td = $(this).closest("td");
                var col = current_td.parent().children().index(current_td);
                var current_tbody = $(this).closest("tbody");
                setCheckboxesStatus(current_tbody, state, col);
            }
        });

        $("input[id$='_read'], input[id$='_new'], input[id$='_update'], input[id$='_delete']").on('switchChange.bootstrapSwitch', function (event, state) {
            var current_tr = $(this).closest("tr");
            var current_td = $(this).closest("td");
            var col = current_td.parent().children().index(current_td);
            var view_all_select = current_tr.find("td:last-child input");
            var final_state = current_tr.find("td:not(:last-child) input").bootstrapSwitch('state');
            var current_tbody = $(this).closest("tbody");

            view_all_select.bootstrapSwitch("state", final_state, true);

            if ($(this).attr("id").indexOf("permissions") == -1) {
                findPreviousModuleTr(current_tbody, true, col);
            } else {
                setCheckboxesStatus(current_tbody, state, col);
            }

        });

        $("table > tbody").each(function (k, v) {

            if (!$(v).find(".warning").length) {
                for (var i = 1; i <= 4; i++) {
                    findPreviousModuleTr($(v), false, i);
                }
            }
        });

        $(".delete-user").on("click", function (e) {
            e.preventDefault();

            $.post($(this).attr("href"))
                .success(function () {
                    window.location.replace(Routing.generate('cs_common_cs_user_index'));
                })
                .fail(function (jqXHR) {
                    $(".alert-danger").show().find("span").html(jqXHR.responseText);
                })
        });
    };

    var toggleModalSubmit = function(action) {

        var el = $('[data-modal="user-role-modal"] [data-btn-type="save"]');
        var disabled = action === "disabled";

        if (disabled) {
            if (el.hasClass(action) === false) {
                el.addClass(action);
            }
        } else {
            el.removeClass("disabled");
        }
    };


    var getCurrentSubsites = function (action) {
        var tr = $("tbody > tr");
        tr.each(function (k, v) {
            addSubsiteToArray($(v), action);
        });
    };

    var setCheckboxesStatus = function(tbody, state, column) {

        tbody.next().children().each(function (k, v) {
            $(v).children().eq(column).find("input").bootstrapSwitch('state', state);
        });
    };

    var findPreviousModuleTr = function(tbody, exec, column) {

        var final_state = true;
        tbody.children().each(function (k, v) {
            var current_state = $(v).children().eq(column).find("input").bootstrapSwitch('state');
            if (current_state == false) {
                final_state = false;
            }
        });

        var current_tr = tbody.prev().find("tr");
        var view_all_select = current_tr.find("td:last-child input");
        current_tr.children().eq(column).find("input").bootstrapSwitch('state', final_state, true);
        var check_all_state = current_tr.find("td:not(:last-child) input").bootstrapSwitch('state');
        view_all_select.bootstrapSwitch("state", check_all_state, exec);
    };

    var addSubsiteToArray = function(tr, action) {
        var site = tr.find(".site").html();
        var subsite = tr.find(".subsite").html();
        var value = tr.find(".subsite").data("id");

        var option = $.grep(window.options, function (e) {
            return (e.subsite == subsite);
        });

        if (!option.length) {
            window.options.push({site: site, value: value, subsite: subsite, action: action});
        } else {
            option[0].action = action;
            $.merge(window.options, option[0]);
        }
    };

    var setOptionsToSelect = function(select, subsite) {
        $.each(window.options, function (k, v) {
            if (v.subsite != subsite) {
                if (v.action == 'delete') {

                    select.find("option").filter(function () {
                        return $(this).html() == v.subsite;
                    }).remove();
                } else if (v.action == 'add') {
                    var option = $("<option></option>", {value: v.value}).html(v.subsite);
                    var optgroup = select.find("optgroup[label='" + v.site + "']");
                    if (!optgroup.find("option[value='" + v.value + "']").length) {
                        optgroup.append(option);
                    }
                }
            }
        });
    };

    return {
        init: function() {
            bindFunction();
            getCurrentSubsites('delete');
        },
        paginationInit: function(){
            var paginator = createPagination($);
            paginator.setUrl(Routing.generate('cs_common_cs_user_page'));
            paginator.setDomSelector('.users_content ul.pagination li a');
            paginator.init();
        }
    };
})();
