window.AttributeVisibility = Class.create({
    config: {},
    
    initialize: function(config, options) {
        this.config = config;
    
        this.options = {
            categoryConstant: '',
            parentElementType: 'tr',
            selectedAttributeFromConfig: 'uId',
            searchPattern: 'input[name="%s"]',
            fuzzySearchPattern: 'input[name*="%s"]',
            itemNamePattern: '%s'
        };
    
        Object.extend(this.options, options || {});
    },
    
    ajaxHideAttributes: function() {
        new Ajax.Request(window.www_dir + 'system/ajaxAttributeVisibility/loadConfig', {
            method:     'post',
            parameters: {
                categoryConstant: this.options.categoryConstant
            },
            onSuccess:  function (transport) {
                var json = transport.responseJSON;

                if (!is_json_response(transport, true)) {
                    return;
                }

                if (json.data) {
                    this.config = json.data;
                    this.hideAttributes();
                }
            }.bind(this)
        });
    },
    
    hideAttributes: function() {
        let item, itemName, itemElement, type, searchPattern;
        
        this.config.forEach((item) => {
            itemName = this.options.itemNamePattern;
            searchPattern = this.options.searchPattern;
            itemElement = $('scroller').down(searchPattern.replace('%s', itemName.replace('%s', item[this.options.selectedAttributeFromConfig])));
            
            // @see ID-9026 Only use a 'fuzzy' search that matches part of the name, if no exact match was found.
            if (!itemElement) {
                searchPattern = this.options.fuzzySearchPattern;
                itemElement = $('scroller').down(searchPattern.replace('%s', itemName.replace('%s', item[this.options.selectedAttributeFromConfig])));
            }
            
            if (itemElement) {
                if (itemElement.up(this.options.parentElementType)) {
                    itemElement.up(this.options.parentElementType).hide();
                } else {
                    itemElement.up().hide();
                }
            }
        });
    },
});