var contentSelected = function () {
    //@TODO Agrupar funcionalitats de processat de dades molt semblants.
    //@TODO Canviar accions de tal manera que en un modul concret es pugin sobreescriure.
    function processParams(url, formsCollection, paramsCollection) {
        var form = $('<form>');

        if (typeof paramsCollection === 'undefined') {
            paramsCollection = [];
        }

        if (typeof formsCollection !== 'undefined') {

            for (var i = 0; i < formsCollection.length; i++) {
                    paramsCollection = paramsCollection.concat($(formsCollection[i]).serializeArray());
            }
        }

        for (var i = 0; i < paramsCollection.length; i++) {
            $('<input>')
                .attr('type', 'hidden')
                .attr('name', paramsCollection[i].name)
                .val(paramsCollection[i].value)
                .appendTo(form);
        }

        form.prop('action', url)
            .prop('target', '_blank')
            .prop('method', 'POST');

        return form;
    }

    window.getParams = function(forms) {

        var paramsCollection = [];

        if (typeof forms !== 'undefined') {
            var length = forms.length;

            for (var i = 0; i < length; i++) {

                var values = $(forms[i]).serializeArray();

                for(value in values) {
                    paramsCollection[value] = values[value];
                }

            }
        }

        return paramsCollection;
    };

    window.postParams = function(forms) {

        var paramsCollection = {};

        if (typeof forms !== 'undefined') {
            var length = forms.length;

            for (var i = 0; i < length; i++) {

                var values = $(forms[i]).serializeArray();

                for(value in values) {
                    paramsCollection[values[value]['name']] = values[value]['value'];
                }

                //paramsCollection = $.extend(paramsCollection, values);

            }
        }

        return paramsCollection;
    };

    function exportFormDoSubmit(form) {
        form.appendTo('body')
            .submit()
            .remove();
    }

    function ajaxFormSubmit(form, promise) {
        var url = form.prop('action');
        $.post(url, form.serialize())
            .success(function () {
                promise.resolve(url);
            })
            .fail(function (jqXHR) {
                promise.reject(new Error(jqXHR.responseText));
            });
    }

    function deleteEntities(d, params) {
        //var d = Q.defer();

        var paramsCollection = [];
        if (contentSelected.allSelected === 1 && contentSelected.contentUnselected.length === 0) {
            paramsCollection.push({name: "allSelected", value: 1});
        }
        else {
            var elements = ( contentSelected.allSelected === 0 ) ? contentSelected.contentSelected : contentSelected.contentUnselected;
            paramsCollection = paramsCollection.concat([{
                name: "allSelected",
                value: contentSelected.allSelected
            }, {name: 'ids', value: elements}])
        }

        if (paramsCollection.length > 0) {
            ajaxFormSubmit(processParams(params.url, contentSelected.formsCollection, paramsCollection), d);
        }

        return d.promise;
    }

    var bindFunction = function (selector, urls) {
        $('body').on('click', selector, function () {
            var item = $(this);
            //If we need select items without parent.
            if (typeof $(this).data('id-content') === 'undefined') {
                item = $(this).parents('[data-id-content]:first');
            }

            if (item.hasClass('selected')) {
                item.removeClass('selected');
                $(this).removeClass('checked');
                contentSelected.removeItem(item.data('id-content'));
            }
            else {
                item.addClass('selected');
                $(this).addClass('checked');
                contentSelected.addItem(item.data('id-content'));
            }
        });

        $('#select-all').on('click', function (event) {
            event.preventDefault();

            if ($(this).attr('disabled')) {
                return false;
            }

            contentSelected.reset();
            contentSelected.setAllSelected(1);
            contentSelected.selectElements();

            $('#select-all-listed').attr('disabled',false).parent().removeClass('disabled');
            $(this).attr('disabled',true).parent().addClass('disabled');

        });

        $('#select-all-listed').on('click', function (event) {
            event.preventDefault();

            if ($(this).attr('disabled')) {
                return false;
            }

            contentSelected.reset();
            contentSelected.setAllSelected(0);

            $(contentSelected.selector).each(function () {
                var item = $(this);
                //If we need select items without parent.
                if (typeof $(this).data('id-content') === 'undefined') {
                    item = $(this).parents('[data-id-content]:first');
                }

                if (contentSelected.allSelected === 1) {
                    contentSelected.removeUnselectedItem(item.data('id-content'));
                }
                else {
                    contentSelected.addItem(item.data('id-content'));
                }
            });


            contentSelected.selectElements();

            $('#select-all').attr('disabled',false).parent().removeClass('disabled');
            $(this).attr('disabled',true).parent().addClass('disabled');
        });

        $('#export-selected').on('click', function (event) {
            event.preventDefault();
            if( !$(this).parent().hasClass('disabled') )
            {
                var url = urls.export;

                if( contentSelected.allSelected === 1 && contentSelected.contentUnselected.length === 0 ) {
                    var paramsCollection = [{name: "allSelected", value:1}];

                }
                else {
                    var elements = ( contentSelected.allSelected === 0 ) ? contentSelected.contentSelected : contentSelected.contentUnselected;
                    var paramsCollection = [{name: "allSelected", value: contentSelected.allSelected}, {
                        name: 'ids',
                        value: elements
                    }];
                }

                exportFormDoSubmit( processParams( url, contentSelected.formsCollection, paramsCollection ) );
            }
        });

        $('#unselect-list').on('click', function(e){
            e.preventDefault();
            contentSelected.reset();
        });

        $('#delete-selected').data('url', urls.delete);

        $deleteAction
            .setSelector('#delete-selected')
            .setCheckAllowProcess(function(){
                return !$('#delete-selected').parent().hasClass('disabled');
            })
            .setUrl(urls.delete)
            .on('success', function() {
                window.location.reload();
            })
            .on('check', function(d, params) {

                var nItems = this.contentSelected._getTotalSelected();

                params.title = Translator.transChoice(params.title, nItems, { count: nItems });
                params.message = Translator.transChoice(params.message, nItems, { count: nItems });

                var ids = ( contentSelected.allSelected === 0 ) ? contentSelected.contentSelected : contentSelected.contentUnselected;

                var postParameters = $.extend({
                    ids: ids.join(','),
                    allSelected: contentSelected.allSelected
                }, postParams(contentSelected.formsCollection));

                $deleteAction.addParamToUrl(params, $.param(postParameters));

                params.postParams = postParameters;

                params.managed = true;

            })
            .init();

        $("#publish-selected").on('click', function (event) {
            event.preventDefault();

            if (!$(this).parent().hasClass('disabled')) {

                var postParameters = $.extend({
                    ids: contentSelected.contentSelected.join(','),
                    allSelected: contentSelected.allSelected
                }, postParams(contentSelected.formsCollection));

                $.post(urls.publish, postParameters)
                    .success(function(){
                        window.location.reload();
                    }
                );
            }

        });

        $("#duplicate-selected").on('click', function (event) {
            event.preventDefault();

            if (!$(this).parent().hasClass('disabled')) {

                var ids = ( contentSelected.allSelected === 0 ) ? contentSelected.contentSelected : contentSelected.contentUnselected;

                var postParameters = $.extend({
                    ids: ids.join(','),
                    allSelected: contentSelected.allSelected
                }, postParams(contentSelected.formsCollection));

                $.post(urls.clone, postParameters)
                    .success(function(){
                        window.location.reload();
                    }
                );
            }

        });


        $modifyContentAction
            .setSelector('[data-content-action]')
            .on('_get', function(d, params) {

                if (params.element.parent().hasClass('disabled')) {
                    params.managed = true;

                    return;
                }

                var ids = ( contentSelected.allSelected === 0 ) ? contentSelected.contentSelected : contentSelected.contentUnselected;

                var postParameters = $.extend({
                    ids: ids.join(','),
                    allSelected: contentSelected.allSelected
                }, postParams(contentSelected.formsCollection));

                params.url = params.url + '&' + $.param(postParameters);
                params.postParams = $.param(postParameters);

            })
            .on('_success', function(params) {
                params.managed = true;
                window.location.reload();
            })
            .init()
        ;


        //$("[data-content-action]").on('click', function (event) {
        //    event.preventDefault();
        //
        //    var _this = $(this);
        //    if (!_this.parent().hasClass('disabled')) {
        //
        //        var postParameters = $.extend({
        //            ids: contentSelected.contentSelected.join(','),
        //            allSelected: contentSelected.allSelected
        //        }, postParams(contentSelected.formsCollection));
        //
        //        $.post(_this.attr('href'), postParameters)
        //            .success(function(){
        //                window.location.reload();
        //            }
        //        );
        //    }
        //
        //});
    };

    return {
        init: function (selector, forms, urls) {
            var self = this;

            Pagination.onChange.add(function () {
                contentSelected.selectElements();
            });

            Pagination.onChange.add(contentSelected.setTotalItems);

            bindFunction(selector, urls);
            contentSelected.setTotalItems();
            this.selector = selector;

            if (typeof forms !== 'undefined') {
                if (typeof forms === 'string') {
                    forms = [forms];
                }

                this.formsCollection = $.merge(this.formsCollection, forms);
            }

            $('#dropdown-actions li.disabled a').each(function() {
                self.canDisableSelectors.push("#"+$(this).attr('id'));
            });
        },
        allSelected: 0,
        contentSelected: [],
        contentUnselected: [],
        selector: null,
        addItem: function (id) {
            if (this.allSelected === 1) {
                this.removeUnselectedItem(id);
            }
            else {
                if (this.contentSelected.indexOf(id) === -1) {
                    if (this.allSelected === 0) {
                        this.contentSelected.push(id);
                    }
                }
            }

            this.changeStateOfActions();
        },
        removeItem: function (id) {
            if (this.allSelected === 1) {
                if (this.contentUnselected.indexOf(id) === -1) {
                    this.contentUnselected.push(id);
                }
            }
            else {
                var index = this.contentSelected.indexOf(id);
                this.contentSelected.splice(index, 1);
            }

            this.changeStateOfActions();
        },
        removeUnselectedItem: function (id) {
            var index = this.contentUnselected.indexOf(id);
            if (this.existUnselectedItem(id)) {
                this.contentUnselected.splice(index, 1);
            }
        },
        existItem: function (id) {
            return this.contentSelected.indexOf(id) !== -1;
        },
        existUnselectedItem: function (id) {
            return this.contentUnselected.indexOf(id) !== -1;
        },
        setAllSelected: function (allSelected) {
            if ( allSelected === 1 || allSelected === 0)
            {
                this.allSelected = allSelected;
                this.contentSelected = [];
                this.changeStateOfActions();
            }
        },
        selectElements: function () {

            if ( this.haveContentSelected() ) {
                var self = this;
                $(this.selector).each(function () {
                    var item = $(this);
                    if (typeof $(this).data('id-content') === 'undefined') {
                        item = $(this).parents('[data-id-content]:first');
                    }

                    if (self.allSelected === 1) {
                        if (( !self.existUnselectedItem(item.data('id-content')) && !item.hasClass('selected') )) {
                            $(this).trigger('click');
                        }
                    }
                    else {
                        if (self.existItem(item.data('id-content')) && !item.hasClass('selected')) {
                            $(this).trigger('click');
                        }
                    }
                });
            }
        },
        setTotalItems: function() {
            var data = $('[data-total-items]').data();
            if( typeof  data !== 'undefined')
            {
                this.totalItems = data.totalItems;
            }
        },
        reset: function () {
            this.contentSelected = [];
            this.contentUnselected = [];
            this.allSelected = 0;
            this.changeStateOfActions();
            this.updateTotalItemsText(0);
            $(this.selector).removeClass('checked selected').parents('[data-id-content]').removeClass('selected');
            $('#select-all-listed, #select-all').removeAttr('disabled').parent().removeClass('disabled');
            $('#unselect-list').hide();
        },
        updateTotalItemsText : function() {

            var selectedText = this._getTotalSelected() > 0 ? $('#selected-text').attr('data-selected') : $('#selected-text').attr('data-unselect');

            $('#selected-text').text(selectedText);

            var counterText = this._getTotalSelected() >= this.getMaxCountable() ? "*" : this._getTotalSelected();

            $('#selected-counter').html( this._getTotalSelected() > 0 ? '<strong>('+ counterText +')</strong>' : '');

            this._getTotalSelected() > 0 ? $('#unselect-list').show() : $('#unselect-list').hide();
        },
        _getTotalSelected: function() {
            var total = this.allSelected ? this.getMaxCountable() : this.contentSelected.length;

            return parseInt(total);
        },
        formsCollection: [],
        totalItems: 0,
        updateButtons: function( enable ) {

            var dropDownButton = $('#dropdown-actions-button');

            for( var i = 0; i < this.canDisableSelectors.length; i++ ) {
                if( enable )
                {
                    $(this.canDisableSelectors[i]).parents('li:first').removeClass('disabled');
                }
                else
                {
                    $(this.canDisableSelectors[i]).parents('li:first').addClass('disabled');
                }
            }

            if (this._getTotalSelected() > 0) {
                dropDownButton.removeClass('disabled');
            } else {
                dropDownButton.addClass('disabled');
            }
        },
        haveContentSelected: function() {
            return this.allSelected === 1 || (this.allSelected === 0 && this.contentSelected.length > 0);
        },
        changeStateOfActions: function() {
            var enable = false;
            if( this.haveContentSelected() )
            {
                enable = true;
            }

            this.updateButtons( enable );
            this.updateTotalItemsText();
        },
        getMaxCountable: function () {
            return 9999;
        },
        canDisableSelectors: []
    }
}();

$deleteAction = new DeleteContentActivity();
$modifyContentAction = new ModifyContentActivity();
//$SelectModifiyAction = new ModifyContentActivity();
