(function () {

if (!$$('.view_jdisc_availability select[name="servers"]').length) {
    return;
}

const devicesSize      = $$('.view_jdisc_availability input[name="devices-size"]')[0],
      btns             = $$('.view_jdisc_availability .btn'),
      ajaxURL          = $$('.view_jdisc_availability input[name="ajax-url"]')[0].getValue(),
      loadMoreBtn      = $$('.view_jdisc_availability button[name="load-more"]')[0],
      server           = $$('.view_jdisc_availability select[name="servers"]')[0],
      type             = $$('.view_jdisc_availability select[name="types"]')[0],
      onlyUnavailable  = $$('.view_jdisc_availability input[name="only-unavailable"]')[0],
      devicesProcessed = $$('.view_jdisc_availability input[name="devices-processed"]')[0],
      tbody            = $$('.view_jdisc_availability .mainTable tbody')[0],
      noDevicesMessage = $$('.view_jdisc_availability input[name="no-devices"]')[0].getValue(),
      controls         = btns.concat(server, onlyUnavailable, type);

server.on('change', function(e) {
    resetDevices();
    devicesProcessed.setValue(0);
});

type.on('change', function(e) {
    resetDevices();
    devicesProcessed.setValue(0);
});

if (onlyUnavailable) {
    onlyUnavailable.on('change', function(e) {
        resetDevices();
        devicesProcessed.setValue(0);
    });
}

for (let i = 0; i < btns.length; i++) {
    btns[i].on('click', function (e) {
        e.preventDefault();
        disabeControls();

        const btn = this;
        let parameters = {
            caller: this.name,
            server: server.getValue(),
            type: type.getValue(),
            onlyUnavailable: onlyUnavailable.getValue(),
            devicesProcessed: devicesProcessed.getValue(),
        };

        if (this.name == 'load') {
            parameters.devicesProcessed = 0;
        }

        new Ajax.Request(ajaxURL, {
            method:     'post',
            parameters: parameters,
            onComplete: function (response) {
                const data = response.responseJSON;
                if (200 !== response.status || !data || !data.success || !data.devices.length) {
                    resetDevices();
                    return;
                }

                if (data.caller == 'load') {
                    tbody.update();
                }

                if (data.devices.length) {
                    for (let j = 0; j < data.devices.length; j++) {
                        const device = data.devices[j];
                        if (device.title && device.jdisc) {
                            const link = new Element(
                                'a',
                                {
                                    className: 'dynamic-replacement quickinfo',
                                    'data-object-id': device.id,
                                    'href': window.www_dir + '?objID=' + device.id
                                }
                            ).update(device.title);

                            new Tip(
                                link,
                                '',
                                {
                                    ajax:      { url: window.www_dir + '?ajax=1&call=quick_info&objID=' + device.id },
                                    delay:     [{isys_usersettings::get('gui.quickinfo.delay', 0.5)}],
                                    className: 'objectinfo'
                                }
                            );

                            const tr = new Element('tr')
                                .insert(
                                    new Element('td').insert(link)
                                )
                                .insert(
                                    new Element(
                                        'td',
                                        { className: device.jdisc.class }
                                    ).update(device.jdisc.value)
                                );

                            tbody.insert(tr);
                        }
                    }

                    if (data.devicesProcessed) {
                        devicesProcessed.setValue(data.devicesProcessed);
                    }

                    if (data.devicesSize) {
                        devicesSize.setValue(data.devicesSize);
                    }

                    if (data.devicesProcessed != devicesSize.getValue()) {
                        loadMoreBtn.toggleClassName('hide', false);
                    } else {
                        loadMoreBtn.toggleClassName('hide', true);
                    }

                }
                enableControls();
            }
        });
    });
}

function disabeControls() {
    for (let i = 0; i < controls.length; i++) {
        controls[i].writeAttribute('disabled', 'disabled');
        if (controls[i].tagName == 'BUTTON') {
            controls[i].toggleClassName('form__items__field__btn_icon_update--loading', true);
        }
    }
}

function enableControls() {
    for (let i = 0; i < controls.length; i++) {
        controls[i].removeAttribute('disabled');
        if (controls[i].tagName == 'BUTTON') {
            controls[i].toggleClassName('form__items__field__btn_icon_update--loading', false);
        }
    }
}

function resetDevices() {
    tbody.update();
    tr = new Element('tr')
        .insert(
            new Element(
                'td',
                { colSpan: 2 }
            ).update(noDevicesMessage)
        );
    tbody.insert(tr);

    enableControls();
    loadMoreBtn.toggleClassName('hide', true);
}

})();
