(function () {

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

    const devicesSize = $$('.view_jdisc_delete_devices input[name="devices-size"]')[0],
        deleteBtn = $$('.view_jdisc_delete_devices button[name="delete"]')[0],
        btns = $$('.view_jdisc_delete_devices .btn').filter((btn) => btn != deleteBtn),
        ajaxURL = $$('.view_jdisc_delete_devices input[name="ajax-url"]')[0].getValue(),
        loadMoreBtn = $$('.view_jdisc_delete_devices button[name="load-more"]')[0],
        server = $$('.view_jdisc_delete_devices select[name="servers"]')[0],
        type = $$('.view_jdisc_delete_devices select[name="types"]')[0],
        devicesProcessed = $$('.view_jdisc_delete_devices input[name="devices-processed"]')[0],
        tbody = $$('.view_jdisc_delete_devices .mainTable tbody')[0],
        noDevicesMessage = $$('.view_jdisc_delete_devices input[name="no-devices"]')[0].getValue(),
        deleteDevicesConfirmationMessage = $$('.view_jdisc_delete_devices input[name="delete-devices-confirmation"]')[0].getValue(),
        deleteDevicesFailedMessage = $$('.view_jdisc_delete_devices input[name="delete-devices-failed"]')[0].getValue(),
        deleteDevicesSuccessMessage = $$('.view_jdisc_delete_devices input[name="delete-devices-success"]')[0].getValue(),
        allDevices = $$('.view_jdisc_delete_devices .all-devices input')[0],
        controls = btns.concat(server, type);

    deleteBtn.on('click', function deleteDevices(e) {
        e.preventDefault();
        deleteBtn.disable();
        const checkedValues = $$('.view_jdisc_delete_devices .mainTable tbody input[type=checkbox]:checked').map(checkbox => checkbox.value);
        if (confirm(deleteDevicesConfirmationMessage)) {
            const parameters = {
                'devices[]': checkedValues,
                callback: 'deleteDevices',
                server: server.getValue(),
            };
            new Ajax.Request(ajaxURL, {
                method: 'post',
                parameters: parameters,
                onComplete: function deleteDevicesResponseHandler(response) {
                    deleteBtn.enable();
                    const data = response.responseJSON;
                    if (200 !== response.status || !data || !data.success) {
                        idoit.Notify.error(deleteDevicesFailedMessage);
                        return;
                    }

                    if (data.remainingDevices) {
                        checkedValues.filter(device => !data.remainingDevices.some(remainingDevice => remainingDevice.id === device));
                    }

                    for (let i = 0; i < checkedValues.length; i++) {
                        $$('.view_jdisc_delete_devices .mainTable tbody')[0]
                            .removeChild(
                                $('device_' + checkedValues[i])
                            );
                    }
                    allDevices.checked = false;
                    updateDeleteButtonState();

                    idoit.Notify.success(deleteDevicesSuccessMessage);
                }
            });
        }
        return false;
    })

    allDevices.on('click', function toggleAllDevicesCheckbox(e) {
        const allDevicesStatus = this.checked;
        $$('.view_jdisc_delete_devices .mainTable tbody input[type=checkbox]').each(function (checkbox) {
            checkbox.checked = allDevicesStatus;
            checkbox.parentNode.parentNode.toggleClassName('tr-selected', allDevicesStatus);
        });
        updateDeleteButtonState();
    });

    $$('.view_jdisc_delete_devices .mainTable tbody')[0].on('click', 'input[type=checkbox]', function toggleDeviceCheckbox(e, checkbox) {
        updateDeleteButtonState();
        updateAllDevicesState();
        checkbox.parentNode.parentNode.toggleClassName('tr-selected', checkbox.checked);
    });

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

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

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

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

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

            new Ajax.Request(ajaxURL, {
                method: 'post',
                parameters: parameters,
                onComplete: function loadDevicesResponseHandler(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: 0.5,
                                        className: 'objectinfo'
                                    }
                                );

                                const tr = new Element('tr', { id: 'device_' + device.jdisc.id })
                                    .insert(
                                        new Element('td').update(
                                            '<input type="checkbox" name="devices[]" value="' + device.jdisc.id + '" />'
                                        )
                                    )
                                    .insert(
                                        new Element('td').insert(link)
                                    )

                                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);
    }

    function updateDeleteButtonState() {
        const atLeastOneChecked = $$('.view_jdisc_delete_devices .mainTable tbody input[type=checkbox]:checked').length > 0;
        if (atLeastOneChecked) {
            deleteBtn.enable();
        } else {
            deleteBtn.disable();
        }
    }

    function updateAllDevicesState() {
        const checkedCheckboxes = $$('.view_jdisc_delete_devices .mainTable tbody input[type=checkbox]:checked').length;
        const allCheckboxes = $$('.view_jdisc_delete_devices .mainTable tbody input[type=checkbox]').length;
        allDevices.checked = checkedCheckboxes == allCheckboxes;
    }

})();
