

function initApi() {

    var searchParams = new URLSearchParams(location.search);

    apikey = searchParams.get('k') || localStorage.getItem('apikey');

    if (!apikey || apikey === 'null') {
        window.location.href = '/pwa/login.html';
        return;
    }

    localStorage.setItem('apikey', apikey);

    // Test if connection is working
    let url = 'http://' + location.host + '/api/' + apikey;

    jQuery.ajax({
        url: url,
//      async: false,
        complete: function(jqXHR) {
            if (jqXHR.status !== 200) {
                localStorage.removeItem('apikey');
                window.location.href = '/pwa/login.html';
            } else if (apikey !== localStorage.getItem('apikey')) {
                localStorage.setItem('apikey', apikey);
            }
        }
    });
}
