var AssetAdvancedFilter = (function () {

    var _selectAll = function(){
        if (AssetAdvancedFilter.countElements() == 0) {
            $.each(AssetAdvancedFilter.widget.find(AssetAdvancedFilter.elementSelector), function(){
                _selectElement($(this));
            });
        } else {
            $.each(AssetAdvancedFilter.widget.find(AssetAdvancedFilter.elementSelector), function(){
                _unSelectElement($(this));
            });
        }

    };

    var _selectElement = function(element) {

        AssetAdvancedFilter.addElement(element, function(element){
            element.find(AssetAdvancedFilter.checkerSelector).prop('checked', true).parent().addClass('checked');
            element.addClass('selected');
        });

        _updateSelectButton();
    };

    var _unSelectElement = function(element,callback) {
        AssetAdvancedFilter.removeElement(element, function(element){
            element.find(AssetAdvancedFilter.checkerSelector).prop('checked', false).parent().removeClass('checked');
            element.removeClass('selected');

            if (typeof callback == 'function') {
                callback.call();
            }

        });

        _updateSelectButton();
    };

    var _updateSelectButton = function() {
        if (AssetAdvancedFilter.countElements() > 0) {
            var text = Translator.trans('cs_assets.advanced_filter.buttons.unselect', {'count':AssetAdvancedFilter.countElements()});
            _toggleAdvanced(true);
            AssetAdvancedFilter.applyButton.attr('disabled',false);
        } else {
            var text = Translator.trans('cs_assets.advanced_filter.buttons.select_all');
            AssetAdvancedFilter.applyButton.attr('disabled',true);
        }

        AssetAdvancedFilter.selectAllButton.text(text);
    };

    var _reorderPositions = function() {
        $.each(AssetAdvancedFilter.widget.find(AssetAdvancedFilter.elementSelector), function(k,e){
            $(e).find(AssetAdvancedFilter.positionSelector).val(k+1)
            $(e).find('.gf-spinner').spinner("value",k+1);
        })
    };

    var _moveToPosition = function(element, position,callBack) {

        var pos = parseInt(position);
        var childrenLength = $(AssetAdvancedFilter.selectedContainerSelector).children().length;

        if (pos < 1) {
            pos = 1;
        }

        if (pos > childrenLength) {
            pos = childrenLength;
        }

        var target = $(AssetAdvancedFilter.selectedContainerSelector).children().eq(pos - 1);

        if (target.length == 0) {
            return;
        }

        target = $(target[0]);

        var targetPos  = parseInt(target.find(AssetAdvancedFilter.positionSelector).val());
        var elementPos = parseInt(element.index()) + 1;

        if (pos == 1) {
            element.insertBefore(target);
        } else if (pos == childrenLength){
            element.insertAfter(target);
        } else {

            if (elementPos < targetPos) {
                element.insertAfter(target);
            } else {
                element.insertBefore(target);
            }
        }

        //AssetAdvancedFilter.signals.onElementMoved.dispatch(element);

        if (typeof callBack == 'function') {
            callBack.call(this,element);
        }
    };

    var _toggleAdvanced = function(onlyShow) {
        var advancedOptions = $('#advanced-options');

        if (onlyShow) {
            advancedOptions.slideDown(400, function(){
                _updateAdvancedButton(advancedOptions.css('display') == 'none');
            });
        } else {
            advancedOptions.slideToggle(400, function(){
                _updateAdvancedButton(advancedOptions.css('display') == 'none');
            });
        }
    }

    var _updateAdvancedButton = function(show) {
        var advancedOptionsButton = $('#toggle-advanced');
        if (show) {
            advancedOptionsButton.html('<i class="fa fa-caret-down"></i> ' + Translator.trans('cs_assets.advanced_filter.buttons.main'));
        } else {
            advancedOptionsButton.html('<i class="fa fa-caret-up"></i> ' + Translator.trans('cs_assets.advanced_filter.buttons.main_hide'));
        }
    }

    var _apply = function(){
        var assets = [];

        $.each(AssetAdvancedFilter.getElements(), function(k,e){

            var element =  $('#' + e);

            assets.push({
                id: element.attr('data-id-content'),
                title: AssetAdvancedFilter.bulk.title,
                description: AssetAdvancedFilter.bulk.description,
                author: AssetAdvancedFilter.bulk.author
            });

            if (AssetAdvancedFilter.bulk.title) {
                element.find('[data-entity="title"]').val(AssetAdvancedFilter.bulk.title);
            }
        });

        $.ajax({
            url: Routing.generate('admin_assets_advanced_filters'),
            method: 'post',
            data: {'assets':assets}
        });

    };

    var _pulsate = function(element, options) {

        var options = options||{color: "#399bc3", speed: 1000, pause: 100, repeat: false};

        element.pulsate(options);
    }

    var _bindEvents = function(widget) {
        // Select|Unselect checkboxes
        $(widget).find(AssetAdvancedFilter.checkerSelector).on('click', function(){

            var element = $(this).parents(AssetAdvancedFilter.elementSelector);

            if ($(this).prop('checked')) {
                _selectElement(element);
            } else {
                _unSelectElement(element);
            }
        });

        // Single positions
        $(widget).find('.gf-spinner').each(function(k,el){
            $(el)
                .find('input')
                .on('blur', function(e){
                    var parent = $(e.target).parents(AssetAdvancedFilter.elementSelector);
                    AssetAdvancedFilter.signals.onElementMoved.dispatch(parent);
                    parent.find(AssetAdvancedFilter.positionSelector).trigger('change')
                });

            $(el)
                .find('button')
                .on('click', function(e){
                    var parent = $(e.target).parents(AssetAdvancedFilter.elementSelector);
                    AssetAdvancedFilter.signals.onElementMoved.dispatch(parent);
                    parent.find(AssetAdvancedFilter.positionSelector).trigger('change')
                });

            $(el).spinner({
                    value:k+1,
                    min: 1,
                    max: 9999
                });
                //.on('changed', function(e) {
                //    $(e.target).find(AssetAdvancedFilter.positionSelector).trigger('change');
                //});
        });

        $(widget).find(AssetAdvancedFilter.positionSelector)
            .on('change', function(e){
                var element = $(this).parents(AssetAdvancedFilter.elementSelector);
                var pos = $(this).val();
                _moveToPosition(element,pos, function(element){
                    $("#sortable_portlets", widget).trigger('sortupdate');
                });
        });
    };

    return {
        init: function(widget) {
            var _this = this;

            this.selectAllButton = $(widget.context).find('a[data-action="select-all"]');
            this.applyButton     = $(widget.context).find('a[data-action="apply"]');

            this.selectAllButton.on('click', function(e){
                e.preventDefault();
                _selectAll();
            });

            this.applyButton.on('click', function(e) {
                e.preventDefault();
                _apply();
            });


            $("#sortable_portlets", widget).on('sortupdate', function (e) {
                _reorderPositions();
            });

            $('#toggle-advanced', widget).on('click', function(){
                _toggleAdvanced();
            });

            // Append / Prepend insert
            $('[data-insert]', widget).on('click',function(e){
                var element = $(e.target);
                widget.data('insert',element.attr('data-insert'));
            })

            $(widget).find('[id*="_advanced_"]').on('change', function(e){
                var element = $(e.target);

                if (element.attr('data-bulk')) {
                    var prop = element.attr('data-bulk');

                    if (prop == 'title') {
                        AssetAdvancedFilter.bulk.title = element.val();
                    }

                    if (prop == 'author') {
                        AssetAdvancedFilter.bulk.author = element.val();
                    }

                }
            });

            if (CKEDITOR.instances['asset_advanced_filter_description']){
                CKEDITOR.instances['asset_advanced_filter_description'].on('blur', function() {
                    AssetAdvancedFilter.bulk.description = this.getData();
                });
            }

            AssetsHelper.signals.onNewAfterRemove.add(function(widget, element) {
                _unSelectElement(element, function(){
                    _reorderPositions();
                });
            });
            AssetsHelper.signals.onNewAdd.add(function(widget, element) {
                _bindEvents(widget);
                _reorderPositions();
                _selectElement(element);
            });
            AssetsHelper.signals.onLibraryAdd.add(function(widget, origElement, element) {
                _bindEvents(widget);
                _reorderPositions();
                _selectElement(element);
            });
            AssetsHelper.signals.afterLibraryRemove.add(function(element) {
                _unSelectElement(element, function(){
                    element.remove();
                    _reorderPositions();
                })
            });
            this.signals.onElementMoved.add(function(element) {
                _pulsate(element);
            });

            this.widget = $(widget);
            this.widget.data('insert', $('.active[data-insert]', widget).data('insert'));
            this.widget.data('is_advanced', true);

            _bindEvents(widget);


        },
        elements: [],
        addElement: function(element, callBack) {
            var index = $.inArray(element[0]['id'],this.elements);

            if (index == -1) {
                this.elements.push(element[0]['id']);
            }

            if (typeof callBack == 'function') {
                callBack.call(this,element);
            }
        },
        removeElement: function(element, callBack) {

            var id = Array.isArray(element) ? element[0]['id'] : element.attr('id');
            var index = $.inArray(id, this.elements);
            this.elements.splice(index, 1);

            if (typeof callBack == 'function') {
                callBack.call(this,element);
            }
        },
        getElements: function() {
            return this.elements;
        },
        countElements: function() {
            return this.elements.length;
        },
        elementSelector: '.cs-selected-assets [data-id-content]',
        checkerSelector: '[data-action="select"]',
        positionSelector: '[data-action="position"]',
        selectedContainerSelector: '.cs-selected-assets',
        widget: null,
        selectAllButton: null,
        applyButton: null,
        bulk: {
            title: '',
            description: '',
            author: ''
        },
        signals: {
            onElementMoved: new signals.Signal()
        }

    }
})();
