var MAX_TIMEOUT = 10000;

/**
 * Sends the selected update channel to gateway.
 */
function submitUpdateChannel() {
    var updatechannel;
    $("#updateChannelForm input:checked").each(function() {
        updatechannel = $(this).val();
    });

    if (!updatechannel) {
        console.log('invalid udate channel.');
        return;
    }

    var out = { 'updatechannel': updatechannel };

    $.ajax({
        url: 'api/' + apikey + '/config',
        type: 'PUT',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(out),
        dataType: 'json',
        cache: false,
        headers: { 'Accept': apiversion },
        success: function(data) {
            showAlert('alert-success', '<b>OK!</b> Set update channel to <i>' + updatechannel + '</i>.');
        },
        error: function(jqXHR, textStatus, errorThrown) {
            showAlert('alert-error', '<b>Error!</b> Failed to set update channel to <i>' + updatechannel + '</i>.');
        },
        timeout: MAX_TIMEOUT
    });
}

/**
 * Updates all forms with current configuration values.
 */
function showConfiguration() {

    switch (config.config.updatechannel)
    {
    case 'stable':
        $('#updateChannelStable').attr('checked', true);
        break;

    case 'beta':
        $('#updateChannelBeta').attr('checked', true);
        break;

    case 'alpha':
        $('#updateChannelAlpha').attr('checked', true);
        break;

    default:
        break;
    }
}

function loadConfig() {
    $.ajax({
        url: 'api/' + apikey,
        dataType: 'json',
        type: 'GET',
        cache: false,
        contentType: 'application/json; charset=utf-8',
        headers: {
            'Accept': apiversion
        },
        success: function(json, status, xhr) {
            config = json;
            config.etag = xhr.getResponseHeader("ETag");

            showConfiguration();
        },
        error: function(jqXHR, textStatus, errorThrown) {
            switch (jqXHR.status) {
            case 403:
                window.location.assign("/pwa/login.html");
                break;

            default:
                showAlert('alert-error', '<b>Error!</b> Could not load config (' + textStatus + ')');
                break;
            }
        },
        timeout: MAX_TIMEOUT
    });
}

// init fastclick
$(document).ready(function() {
    FastClick.attach(document.body);

    // prevent default sending of form
    $('form').submit(function(e){
        e.preventDefault();
        return false;
    });

    loadConfig();
});