var Categories = (function () {

    var bindFunction = function (element) {

        element.find(".status i").on("click", function () {
            var element = $(this);
            var category_id = element.closest(".dd-item").data("id");
            $.post(Routing.generate("cs_common_cs_category_change_status", {id: category_id}))
                .success(function () {

                    if (element.hasClass('fa-dot-circle-o')) {
                        element.removeClass('fa-dot-circle-o');
                        element.addClass('fa-circle-o');
                        showToastrNotification('success', Translator.trans('cs_categories.messages.category.disabled'));
                    } else {
                        element.removeClass('fa-circle-o');
                        element.addClass('fa-dot-circle-o')
                        showToastrNotification('success', Translator.trans('cs_categories.messages.category.enabled'));
                    }
                });
        });

        element.nestable({
            dropCallback: function (e) {
                var element = e.sourceEl;
                var elem_index = element.data('index');
                var elem_parent = element.data('parent');
                var elem_prop = element.data('property');
                var dest_index = element.index() + 1;

                var dest_prop = 'parent';
                var dest_parent = e.destId;

                if (!e.destId) {
                    dest_parent = element.closest('.nestable_list').data("group-id");
                    dest_prop = 'group';
                }

                var parent_origin_position = elem_index;
                var origin_position = elem_index;
                var dest_position = dest_index;

                if (elem_index > dest_index) {
                    origin_position = dest_index;
                    dest_position = elem_index;
                }

                var new_order = [];
                var destParent = $(e.destParent[0]);

                if (elem_parent != dest_parent || elem_prop != dest_prop) {
                    dest_position = destParent.find('ol').first().children().length;
                    var selector = (elem_prop == 'group') ? "[data-group-id='" + elem_parent + "'] > ol > li" : "[data-id='" + elem_parent + "']";
                    var parentChildren = $(selector).toArray();

                    for (var j = parent_origin_position - 1, parentChildrenLength = parentChildren.length; j < parentChildrenLength; j++) {
                        var childrenElement = $(parentChildren[j]);

                        childrenElement.data('index', j+1);
                        new_order[childrenElement.data('id')] = {
                            'position': j + 1,
                            'prop': childrenElement.data('property'),
                            'parent': childrenElement.data('parent')
                        };
                    }
                }

                var children = destParent.find("ol").children().toArray();
                for (var i = origin_position - 1; i < dest_position; i++) {
                    var elem = $(children[i]);

                    elem.data('index', i+1);
                    elem.data('parent', dest_parent);
                    elem.data('property', dest_prop);
                    new_order[elem.data('id')] = {'position': i + 1, 'prop': dest_prop, 'parent': dest_parent};
                }

                $.post(Routing.generate("cs_common_cs_category_change_order", {
                        new_order: new_order
                    }
                ))
            }
        });
    };

    return {
        init: function () {

            $('[data-action="load-categories"]').on("click", function(e){
                e.preventDefault();

                var _this = $(this);
                var group = _this.data("group");


                $.ajax({
                    url: Routing.generate("cs_common_cs_category_load_categories", {categoryGroup: group }),
                    method: "post",
                    type: "html",
                    success: function(response){
                        var _el = $('.nestable_list[data-group-id="'+group+'"]');
                        _el.html(response);
                        _this.off("click");
                        bindFunction(_el);
                    }
                });
            });


            //bindFunction();
        },
        initWidget: function() {

            var selectors = $("[data-categories-selector]");

            var format = function(object) {
                var originalOption = $(object.element);
                var extended = originalOption.data('extended');
                var el = '<div>' + object.text;

                if(!extended) {
                    extended = '';
                }

                if(!originalOption.data('enabled')) {
                    var text = originalOption.data('enabled-text') ? originalOption.data('enabled-text') : Translator.trans('cs_core.label.disabled');
                    extended = '<strong>' + text + '</strong> '+extended;
                }

                if(extended) {
                    el = el + '<span>' + extended + '</span>';
                }

                return el + '</div>';
            };

            var formatSelection = function(object) {
                var content = $(object.element).data('extended');
                return '<div class="popovers"  data-container="body" data-placement="bottom"  data-content="'+ content +'" data-trigger="hover" data-enabled="' + $(object.element).data('enabled') +'">' + object.text + '</div>';
            };

            var formatResultCssClass = function(object) {
                if(!$(object.element).data('enabled')) {
                    return 'disabled';
                }
            };

            var updateSelected = function() {
                var results = $(this.data('select2').containerSelector).find('.select2-search-choice');
                results.each(function(i, e) {
                    var $this = $(e);

                    $this.find('.popovers').popover({html : true});

                    if(!$this.find('[data-enabled]').data('enabled')) {
                        $this.addClass('disabled');
                    }
                });
            };

            selectors.each(function(i,e) {
                var catSelector = $(e);

                catSelector.select2({
                    allowClear: true,
                    formatResult: format,
                    formatSelection: formatSelection,
                    formatResultCssClass: formatResultCssClass,
                    formatNoMatches: Translator.trans('cs_core.pagination.no_results'),
                    escapeMarkup: function(m) { return m; }
                });

                catSelector.on('change', function(e) {
                    if(e.added) {
                        var element = e.added.element;
                        e.added.css = 'class';
                        if(!$(element).data('enabled')) {
                            $(element).addClass('disabled');
                        }
                    }
                });


                catSelector.on('select2-close', updateSelected.bind(catSelector));
                updateSelected.call(catSelector);

            });
        }
    }
})();

$(function () {
    var parent_select = $("#admin_category_type_parent");
    var group_select  = $("#admin_category_type_group");

    group_select.on("change", function () {
        var id = $(this).val();

        parent_select.data("placeholder", Translator.trans("cs_common_base.form.type.parent.placeholder"));
        parent_select.html("").select2();

        if (id) {
            $.post(Routing.generate('cs_common_cs_category_categories_of_group', {
                id: $(this).val(),
                'category-id': $(this).data('category-id')
            }))
                .success(function (data) {
                    parent_select.html(data).select2("destroy").select2({
                        allowClear: true,
                        formatNoMatches: function () {
                            return Translator.trans('cs_core.messages.no_items_list');
                        }
                    })
                });
        }
    });

    Pagination.onChange.add(function () {
        Categories.init();
    });

    Categories.initWidget();

    $('.popovers').popover({html : true});
});
