(function () {
        var results = document.getElementById('nexdirectory-archive-results');
        if (!results) {
            return;
        }
        var allowed = ['2', '3', '4'];
        var storageKey = 'nexdirectory_archive_columns';
        var selects = Array.prototype.slice.call(document.querySelectorAll('.nexdirectory-archive-columns-select'));
        var colInputs = Array.prototype.slice.call(document.querySelectorAll('.nexdirectory-archive-cols-input'));
        var readStored = function () {
            try {
                return String(window.localStorage.getItem(storageKey) || '');
            } catch (err) {
                return '';
            }
        };
        var persist = function (value) {
            try {
                window.localStorage.setItem(storageKey, value);
            } catch (err) {}
        };
        var applyColumns = function (value) {
            var normalized = String(value || '').trim();
            if (allowed.indexOf(normalized) === -1) {
                normalized = '3';
            }
            results.setAttribute('data-nexdirectory-cols', normalized);
            selects.forEach(function (select) {
                if (select && select.value !== normalized) {
                    select.value = normalized;
                }
            });
            colInputs.forEach(function (input) {
                if (input && input.value !== normalized) {
                    input.value = normalized;
                }
            });
            persist(normalized);
        };

        var initial = String(results.getAttribute('data-nexdirectory-cols') || '').trim();
        if (allowed.indexOf(initial) === -1) {
            var stored = readStored();
            initial = allowed.indexOf(stored) >= 0 ? stored : '3';
        }
        applyColumns(initial);

        selects.forEach(function (select) {
            if (!select) {
                return;
            }
            select.addEventListener('change', function (event) {
                applyColumns(event && event.target ? event.target.value : '3');
            });
        });

        document.addEventListener('nexdirectory:archiveResultsUpdated', function () {
            var stored = readStored();
            if (allowed.indexOf(stored) >= 0) {
                applyColumns(stored);
            }
        });
    })();
