var AgencyArticle = (function() {

    var searchFormSelector = '[name="cms_agency_article_advanced_search"]';
    var agencySelector     = $('#cms_agency_article_advanced_search_agency');
    var fromSearchSelector = $('#cms_agency_article_advanced_search_from_search');
    var modalSelector      = "#agency-article-modal";
    var forceState         = false;

    var initialize = function() {
        $('.cs_agency_article').on('click', '[data-toggle="tab"]', function(e){
            var agency = $(this).attr('data-type-id');
            _setFromSearch(0);
            _setTypeToSearchForm(agency);
            _updateTypeSelect(agency);
        });
    };

    var _setFromSearch = function(data) {
      fromSearchSelector.val(data);
    };

    var _setTypeToSearchForm = function(agency) {
        if (agencySelector.length > 0) {
            agencySelector.val(agency);
        }
    };

    var _updateTypeSelect = function(agency) {
        agencySelector
            .val(agency)
            .change();
    };

    var bindModal = function() {
        // Modal events
        $('[href="#slide"]').on("click", function(e){
            e.preventDefault();

            forceState = false;

            // Get advanced form data to initial filtering
            var params = $(searchFormSelector).serializeArray();

            params.push({
                name:"page",
                value:$(this).data("page")
            });

            params.push({
                name:"entityId",
                value:$(this).data("id")
            });

            sendRequest(params, function(response){
                appendModal(response);
            });
        });
    };

    var sendRequest = function(params, callback) {
        $.ajax({
            url: Routing.generate("cs_cms_agency_article_slide"),
            data: params,
            dataType: "html",
            method: "get",
            beforeSend: function() {
                ComitiumUtils.showSpinner();
            },
            complete: function() {
                ComitiumUtils.hideSpinner();
            },
            success: function(response) {
                if (typeof callback === "function") {
                    callback.call(this, response);
                }
            }
        });
    };

    var appendModal = function(html) {
        $(modalSelector).remove();
        $("body").append(html);
        bindModalActions(function(){
            $(modalSelector)
                .modal({
                    show: true
                });
        });
    };

    var refreshModal = function(html) {
        $(".modal-backdrop").remove();

        $(modalSelector).replaceWith(html);

        bindModalActions(function(){
            $(modalSelector)
                .modal({
                    show: true
                });
        });
    };

    var buildStateParam = function(stateId) {
        var state = stateId||$('[data-action="state-filter"]').val();

        return {
            workflow_state: {
                state: state
            }
        };
    };

    var bindModalActions = function(callback) {

        $('[data-action="paginate"]', modalSelector).on("click", function(){
            var params = {};

            if (forceState) {
                params = $.extend(
                    buildStateParam(),
                    {page:$(this).data("page")}
                );
            } else {
                // Get advanced form data to initial filtering
                params = $(searchFormSelector).serializeArray();

                params.push({
                    name:"page",
                    value:$(this).data("page")
                });

                params.push({
                    name:"entityId",
                    value:$(this).data("id")
                });
            }

            sendRequest(params, function(response){
                refreshModal(response);
            });
        });

        $('[data-action="state-filter"]', modalSelector).on("change", function(){
            forceState = true;

            var params = $.extend(
                buildStateParam($(this).val()),
                {
                    page: 1
                }
            );

            sendRequest(params, function(response){
                refreshModal(response);
            });
        });

        $('[data-action="discard"]').on("click", function(){
            $.ajax({
                url: Routing.generate("cs_cms_agency_article_discard", {id: $(this).data("id")}),
                dataType: "json",
                method: "post",
                success: function () {
                    goToNext();
                }
            });
        });

        $('[data-action="processed"]').on("click", function(){
            $.ajax({
                url: Routing.generate("cs_cms_agency_article_processed", {id: $(this).data("id")}),
                dataType: "json",
                method: "post",
                success: function () {
                    goToNext();
                }
            });
        });

        $(modalSelector).on('hidden.bs.modal', function (e) {
            $(".modal-backdrop").remove();
            $(searchFormSelector).change();
        });

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

    var goToNext = function() {
        if ($(".nav-next", modalSelector).length === 1) {
            $(".nav-next", modalSelector).trigger("click");
        } else {
            $('[data-dismiss="modal"]', modalSelector).trigger("click");
        }
    };

    return {
        init: function() {
            initialize();
            bindModal();
        },
        reBind: function() {
            bindModal();
            _setFromSearch(1);
        }
    };
})();
