var Article = (function() {
    var fromSearchSelector = $('#cms_article_advanced_search_from_search');

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

    var _setTypeToSearchForm = function(articleType) {
        var formField = $('#cms_article_advanced_search_type');

        if (formField.length > 0) {
            formField.val(articleType);
        }
    };

    var _updateTypeSelect = function(articleType) {
        $('#cms_article_advanced_search_type').val(articleType).change();
    };

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

    var _bindForm = function () {
        $('input[data-fill-name]').each(function (i, e) {
            var input       = $(e);
            var mirrorValue = $(this).data('fill-name');
            var mirror      = $(mirrorValue);

            if (mirror.length === 0) {
                return true;
            }

            input.on('change', function () {
                mirror.val(input.val());
            });
        });
    };

    var _bindSubscriptionForm = function () {
        var subscriptionsSection = $("[data-role='paywallOptions']");

        MultiCheckBox.handle(
            $("input:not([data-disabled], [value='all'])", subscriptionsSection),
            $("[data-role='allPaywallOptions']", subscriptionsSection)
        );
    };

    return {
        init: function() {
            _initialize();
        },
        resetFromSearch: function() {
            _setFromSearch(1);
        },
        initForm: function() {
            _bindForm();
        },
        initSubscriptionsForm: function() {
            _bindSubscriptionForm();
        }
    };
})();
