if (document.querySelectorAll('a[data-lang]') != null) {
    document.querySelectorAll('a[data-lang]').forEach(function (item) {
        item.addEventListener('click', (e) => {
            var code = e.currentTarget.getAttribute("data-lang");
            var formData = new FormData();
            formData.append("language", code);
            request('/auth/change-lang', formData, function (data) {
                try {
                    data = JSON.parse(data);
                    if ((data instanceof Object)) {
                        if (data['status']) {
                            location.reload();
                        }
                    }
                } catch (e) {
                    console.log("An unexpected error occurred");
                }
            });
        });
    });
}

/*----------------------------
    XMLHttpRequest POST Function
------------------------------ */
function request(url, data, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', url, true);
    xhr.addEventListener('readystatechange', function () {
        if (xhr.readyState === 4) {
            if (callback) {
                callback(xhr.response);
            }
        }
    });

    var formdata = data ? (data instanceof FormData ? data : new FormData(document.querySelector(data))) : new FormData();

    var checkboxes = document.querySelectorAll('input[type=checkbox]');
    for (i = 0; i < checkboxes.length; i++) {
        var checkbox = checkboxes[i];
        if (!checkbox.checked) {
            formdata.append(checkbox.getAttribute("name"), 0);
        } else {
            formdata.append(checkbox.getAttribute("name"), 1);
        }
    }

    var csrfMetaTag = document.querySelector('meta[name="csrf_token"]');
    if (csrfMetaTag) {
        formdata.append('csrf_token', csrfMetaTag.getAttribute('content'));
    }

    xhr.send(formdata);
}