var RelatedContent = function () {

    var addRelated = function(related) {

        var index = RelatedContent.relatedElements.indexOf(_generateRelatedIndex(related));

        if (index == -1) {
            addCollection(related, function(){
                RelatedContent.relatedElements.push(_generateRelatedIndex(related));
                showHideNoResults();
                initEditables();

                RelatedContent.signals.onRelatedRemoved.dispatch();
            });
        } else {
            showToastrNotification('error',Translator.trans('related_content.elements.duplicate_related'));
            var elem = $('[data-contend-search-id="'+_generateRelatedIndex(related)+'"]').find('[data-plugin="editable"]');
            elem.css('color','#F00');
            setTimeout(function() {
                elem.css('color','');
            }, 5000);
        }
    };

    var removeRelated = function(object) {
        object.fadeOut(400, function(){

            var contentSearchId = $(this).attr('data-contend-search-id');
            var index = RelatedContent.relatedElements.indexOf(contentSearchId);

            RelatedContent.relatedElements.splice(index, 1);

            $(this).remove();

            showHideNoResults();

            RelatedContent.signals.onRelatedRemoved.dispatch();
        });
    };

    var addCollection = function(contentSearch, callback) {

        var isFromOtherSubSite = contentSearch.subSite.acronym != $("html").data("subsite");
        var index      = RelatedContent.wrapper.data('index');
        var prototype  = RelatedContent.wrapper.data('prototype');
        var newElement = prototype.replace(/__name__/g, index);
        var relatedCount = "";

        if (contentSearch.relatedContentCount > 0) {
            relatedCount += "("+$.trim(contentSearch.relatedContentCount)+" "+Translator.transChoice('cs_core.label.relations', contentSearch.relatedContentCount)+")";
        }

        if (isFromOtherSubSite) {
            relatedCount += '<span class="subsite">'+contentSearch.subSite.name+'</span>';
        }

        RelatedContent.wrapper.append($(newElement));

        var ne = RelatedContent.wrapper.find('#' + $(newElement).attr('id'));

        ne.attr('data-contend-search-id',contentSearch.id);
        ne.find('[data-set-related-id]').html(contentSearch.entityId);
        ne.find('[data-set-type]').html(contentSearch.icon_html);
        ne.find('[data-set-type-responsive]').addClass(contentSearch.icon);
        ne.find('[data-set-related-uuid]').val(contentSearch.uuid);
        ne.find('[data-set-related-class]').val(contentSearch.entityClass);
        ne.find('[data-set-title]').html(contentSearch.title).next().val(contentSearch.title);
        ne.find('[data-set-related-count]').html(relatedCount);
        ne.find('[data-preview-url]').attr("href",(contentSearch.publicUrl));
        ne.find('[data-edit-url]').attr({
            "href":contentSearch.editUrl,
            "disabled": isFromOtherSubSite
        });
        ne.find('[data-set-publish-at]').html(contentSearch.publishedAt);

        var stateElement = $("<span></span>", {
            class: "text-center status " + contentSearch.state.name,
            text: Translator.trans("workflow.states." + contentSearch.state.name)
        });

        ne.find('[data-set-state]').html(stateElement);


        if ($.inArray(contentSearch.entityType, RelatedContent.disabledBidirectionalityTypes) != -1) {
            ne.find('[data-action="bidirectional"]').attr('disabled', true);
        }

        RelatedContent.wrapper.data('index', index +1);

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

    var showHideNoResults = function() {

        var elements = countRelated();

        if (elements == 0) {
            RelatedContent.noContentMessageNode.removeClass('hidden');
        } else {
            RelatedContent.noContentMessageNode.addClass('hidden');
        }
    };

    var countRelated = function() {
        return $(document).find('[data-collection="related-content"]').length;
    };

    var bidirectionalAction = function(wrapper, isBidirectional, callBack) {

        if (typeof callBack == 'function') {
            var state = true;
            callBack.call(this, state);
        }
    };

    var orderElements = function() {
        $('[data-position="related-position"]').each(function(k){
            $(this).find('[id$="position"]').val(k);
        });
    };

    var initEditables = function() {
        $(document)
            .find('[data-plugin="editable"]').editable({
                validate: function (value) {
                    if ($.trim(value) == '') {
                        return Translator.trans('cs_common_base.form.messages.errors.required');
                    }
                    else{
                        $('#'+$(this).data('for')).val(value);
                    }
                },
                mode: 'inline',
                inputclass: 'input-small'
            })
            .on('click', function(){
                $('.editable-input :first-child').select().addClass('form-control');
            })
        ;
    };

    var _initSearch = function(data, callBack) {

        if (RelatedContent.ajaxCall === true) {

            RelatedContent.ajaxCall = $.ajax({
                url: Routing.generate('content_search_related_content_tab_results'),
                dataType: "html",
                data:data,
                beforeSend: function() {
                    RelatedContent.signals.onInitSearch.dispatch();
                },
                success: function( data ) {

                    RelatedContent.resultsInput.html(data);

                    _showResults();

                    RelatedContent.signals.onFetchResults.dispatch();

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

    var _updateRelatedTitle = function() {
        var count = RelatedContent.relatedElements.length;
        var text = Translator.transChoice('related_content.elements.header_title', count > 0 ? 2:1, {'count': count});
        $('#related-header-title').text(text);
    };

    var _showResults = function() {
        _hideAutoComplete();
        RelatedContent.resultsInput.fadeIn();
    };

    var _hideResults = function() {
        _hideAutoComplete();
        RelatedContent.resultsInput.fadeOut();
        RelatedContent.input.removeClass('spinner');
    };

    var _hideAutoComplete = function() {
        RelatedContent.input.autocomplete("close");
    };

    var _searchResults = function(data, callBack) {
        $.ajax({
            url: Routing.generate('content_search_related_content_suggest'),
            dataType: "json",
            data: data,
            beforeSend: function() {
                RelatedContent.input.addClass('spinner');
            },
            success: function( data ) {

                RelatedContent.signals.onFetchResults.dispatch();

                if (typeof callBack == 'function') {
                    callBack.call(this, data);
                }
            }
        });
    }
    
    var _generateRelatedIndex = function (related) {
        return related.selfContentType + "-" + related.id
    }

    var initComponents = function() {
        $('#suggest-dropdown-items li a').on('click', function(e){

            e.preventDefault();

            var contentType = $(this).data('suggest-filter');

            $('#suggest-button').html($(this).html());

            RelatedContent.contentType = contentType;

        });

        $(document).on('click', '[data-action="remove-related"]', function(e){

            e.preventDefault();

            var wrapper = $(this).closest('[data-collection="related-content"]');

            removeRelated(wrapper);
        });

        $(document).on('click', '[data-action="bidirectional"]', function(e){

            e.preventDefault();

            var $this = $(this);
            var isBidirectional = $this.attr('data-is-bidirectional');
            var wrapper = $(this).closest('[data-collection="related-content"]');

            bidirectionalAction(wrapper, isBidirectional, function() {
                $this.attr('data-is-bidirectional', isBidirectional == '1' ? '0' : '1');
                $this.attr('title', isBidirectional == '1' ? Translator.trans('related_content.elements.bidirectional-active') : Translator.trans('related_content.elements.bidirectional-disabled'));
                $this.toggleClass('active');
                $this.next().val(isBidirectional == '1' ? '0' : '1');
            })
        });

        initEditables();

        $('form').on('submit', function() {
            orderElements();
        });

        $(document).on('click', '[data-action="add-related"]', function(e){
            e.preventDefault();
            var object = $(this).parents('tr').data('object');
            addRelated(object);
        });

        $(document).on('click', '[data-action="filter-type"] a', function(e) {
            e.preventDefault();

            RelatedContent.signals.onTapping.dispatch();

            _initSearch({
                exclude_entity_id: RelatedContent.input.data("entity-id"),
                q :RelatedContent.input.val(),
                type: parseInt($(this).data('type')),
                order: $('#search-order').val()
            });
        });

        RelatedContent.input
            .on('keypress', function(e){

                var code = e.keyCode || e.which;
                var term = $(e.target).val();

                if (code == 13) {
                    e.preventDefault();
                    e.stopPropagation();
                    if (term != '') {
                        _initSearch({
                            q:term,
                            exclude_entity_id: $(e.target).data("entity-id"),
                            limit:5,
                            order: $('#search-order').val()
                        });
                    }
                } else {
                    RelatedContent.signals.onTapping.dispatch();
                }

                if (term == '') {
                    _hideResults();
                }
            })
            .autocomplete({
                source: function( request, response ) {
                    _searchResults({
                        q: request.term,
                        exclude_entity_id: RelatedContent.input.data("entity-id"),
                        order: $('#search-order').val()
                    }, function(data){
                        response(data);
                    });
                },
                minLength: 3,
                focus: function(event, ui) {
                    ui.item.label = ui.item.title;
                    ui.item.value = ui.item.title;
                },
                select: function(event, ui) {
                    RelatedContent.signals.onSelectedItem.dispatch();
                    addRelated(ui.item);
                },
                create: function() {
                    var _$thisAutocomplete = $(this).data("ui-autocomplete");

                    _$thisAutocomplete._renderItem = function( ul, item ) {

                        var title = item.title.replace(new RegExp(this.term, "gi"), "<strong>$&</strong>");
                        var html  = $('<a></a>', {
                            "href": "javascript: void(0);",
                            "title": item.title,
                            "html": '<span class="info-icon"></span><i class="'+ item.icon + '"></i> ' + title
                        });

                        if (!(item.subSite.acronym == $("html").data("subsite"))) {
                            html.append('<span class="subsite">'+item.subSite.name+'</span>');
                        }

                        return $( "<li>" )
                            .append(html)
                            .appendTo( ul );
                    };

                    _$thisAutocomplete._renderMenu = function( ul, items ) {
                        var $this = this;

                        $.each( items, function( index, item ) {
                            $this._renderItemData( ul, item );
                        });

                        $(ul).addClass('cs_global_search');
                        $(ul).css('max-width', RelatedContent.input.css('width'));
                    };

                    // Remove helper
                    $(this).prev('span').remove();
                }
            });
    };

    return {
        init: function (entity_id, entity_type) {
            initComponents();

            PortletDraggable.init();

            if (countRelated() > 0) {
                $(document).find('[data-collection="related-content"]').each(function(k,v){
                    var contentSearchId = $(v).attr('data-contend-search-id');
                    RelatedContent.relatedElements.push(contentSearchId);
                });
            }

            RelatedContent.entity_id   = entity_id;
            RelatedContent.entity_type = entity_type;
            RelatedContent.wrapper.data('index', countRelated());

            this.signals.onSelectedItem.add(function() {
                RelatedContent.ajaxCall = false;
                _updateRelatedTitle();
                _hideResults();
            });

            this.signals.onTapping.add(function() {
                RelatedContent.ajaxCall = true;
            });

            this.signals.onInitSearch.add(function() {
                RelatedContent.input.trigger('blur');
                RelatedContent.input.addClass('spinner');
                RelatedContent.resultsInput.find('.cs-module-spinner').show();
            });

            this.signals.onRelatedAdded.add(function() {
                RelatedContent.input.val('');
                _updateRelatedTitle();
            });

            this.signals.onRelatedRemoved.add(function() {
                _updateRelatedTitle();
            });

            this.signals.onFetchResults.add(function() {
                RelatedContent.input.removeClass('spinner');
                RelatedContent.resultsInput.find('.cs-module-spinner').hide();
            });

        },
        form: null,
        setForm: function(f) {
            this.form = f;
        },
        contentType: 0,
        noContentMessageNode: $('#related-content-no-results'),
        relatedElements: [],
        wrapper: $('#related-content-wrapper'),
        entity_id: null,
        entity_type: null,
        disabledBidirectionalityTypes: [101,115,118,119],
        input: $("#suggest-input"),
        resultsInput: $('#content-search-results'),
        searchEnabled: true,
        signals: {
            onSelectedItem: new signals.Signal(),
            onInitSearch : new signals.Signal(),
            onTapping : new signals.Signal(),
            onRelatedAdded: new signals.Signal(),
            onRelatedRemoved: new signals.Signal(),
            onFetchResults: new signals.Signal()
        },
        ajaxCall: true
    };
}();
