/**
 * Push badges to backpack.
 */
function addtobackpack(event, args) {
    var badgetable = Y.one('#issued-badge-table');
    var errordiv = Y.one('#addtobackpack-error');
    var errortext = M.util.get_string('error:backpackproblem', 'badges');
    var errorhtml = '<div id="addtobackpack-error" class="box boxaligncenter notifyproblem">' + errortext + '</div>';

    if (typeof OpenBadges !== 'undefined') {
        OpenBadges.issue([args.assertion], function(errors, successes) { });
    } else {
        // Add error div if it doesn't exist yet.
        if (!errordiv) {
            var badgerror = Y.Node.create(errorhtml);
            badgetable.insert(badgerror, 'before');
        }
    }
}

/**
 * Check if website is externally accessible from the backpack.
 */
function check_site_access() {
    var add = Y.one('#check_connection');

    var callback = {
            method: "GET",
            on: {
                success: function(id, o, args) {
                            var data = Y.JSON.parse(o.responseText);
                            if (data.code == 'http-unreachable') {
                                add.setHTML(data.response);
                                add.removeClass('hide');
                            }
                        },
                failure: function(o) { }
            }
        };

    Y.use('io-base', function(Y) {
        Y.io('ajax.php', callback);
    });

    return false;
}

/*
 * Update the status indicator to show connection progress.
 */
function badges_set_connection_progress(status) {
    switch (status) {
    case 'connecting':
        var connecting = M.util.get_string('connecting', 'badges');
        var imageurl = M.util.image_url('i/loading_small', 'moodle');
        var loading = Y.Node.create(connecting + '&nbsp;<img src="'+imageurl+'" width="16" height="16" alt="'+connecting+'"/>');
        Y.one('#connection-status').removeClass('notconnected').addClass('connecting').setHTML(loading);
        break;
    case 'notconnected':
        var notconnected = M.util.get_string('notconnected', 'badges');;
        Y.one('#connection-status').removeClass('connecting').addClass('notconnected').setHTML(notconnected);
        break;
    default:
        // Unknown status, do nothing.
    }
}

/*
 * Print an error message at the top of the page.
 */
function badges_set_error_message(messagekey, param) {
    var errortext = M.util.get_string(messagekey, 'badges', param);
    Y.one('#connection-error').setHTML(errortext);
}

/*
 * Handle the assertion generated by the Persona dialog.
 */
function badges_handle_assertion(assertion) {

    if (!assertion) {
        var noassertionstr = M.util.get_string('error:noassertion', 'badges');
        badges_set_error_message('error:backpackloginfailed', noassertionstr);
        return;
    }

    badges_set_connection_progress('connecting');

    Y.io("backpackconnect.php", {
        method: "POST",
        data: "assertion="+assertion+"&sesskey="+M.cfg.sesskey,
        on: {
            success: function (id, result) {
                // Reload page to display connected email address.
                window.location.href = "mybackpack.php";
            },
            failure: function (id, result) {
                try {
                    var parsedResponse = Y.JSON.parse(result.response);
                } catch (e) {
                    badges_set_connection_progress('notconnected');
                    var badjsonstr = M.util.get_string('error:badjson', 'badges');
                    badges_set_error_message('error:backpackloginfailed', badjsonstr);
                    return;
                }
                badges_set_connection_progress('notconnected');
                badges_set_error_message('error:backpackloginfailed', parsedResponse.reason);
                return;
            }
        }
    });
}

/**
 * Create and bind the persona login button.
 */
function badges_init_persona_login_button() {
    // Create the login button and add to the page via Javascript.
    var imageurl = M.util.image_url('i/persona_sign_in_black', 'moodle');
    var imagealt = M.util.get_string('signinwithyouremail', 'badges');
    var button = Y.Node.create('<img id="persona_signin" src="'+imageurl+'" width="202" height="25" alt="'+imagealt+'"/>');
    Y.one('#persona-container').append(button);

    // Bind a click event to trigger login when clicked.
    button.on('click', function() {
        Y.one('#connection-error').empty();
        navigator.id.get(badges_handle_assertion);
    });
}
