var info = {
    name        : 'Listen to OpenID requests',
    description : 'http://norman.rasmussen.co.za/107/xmpp-auth-for-openid/',
    version     : '1.0.1',
    author      : 'Massimiliano Mirra <bard [at] hyperstruct [dot] net>',
    license     : 'GPL2',
    home        : 'http://sameplace.cc'
};


var ns_http_auth = 'http://jabber.org/protocol/http-auth';

var channel;


function init() {
    channel = XMPP.createChannel();
       
    channel.on({
        event     : 'message',
        direction : 'in',
        stanza    : function(s) { return s.ns_http_auth::confirm != undefined; }},
        function(message) {
            if(!isMostRecentWindow())
                return;
            
            requestedConfirmation(message);
        });
}

function finish() {
    channel.release();
}

function requestedConfirmation(requestMessage) {
    var account = requestMessage.account;
    var request = requestMessage.stanza;
    var response = (
        <message to={request.@from}>
        <confirm
        xmlns={ns_http_auth}
        method={request.ns_http_auth::confirm.@method}
        url={request.ns_http_auth::confirm.@url}
        id={request.ns_http_auth::confirm.@id}/>
        </message>
        );

    if(!window.confirm(
           'Someone (possibly you) tried to identify as ' + request.@to + '\n' +
           'on ' + request.ns_http_auth::confirm.@url + ', ' +
           'with transaction identifier "' + request.ns_http_auth::confirm.@id + '".\n' +
           'Should this request be authorized?')) {
        response.@type = 'error';
        response.error =
            <error code="401" type="auth">
            <not-authorized xmlns="urn:ietf:params:xml:xmpp-stanzas"/>
            </error>;
    }

    XMPP.send(account, response);
}

function isMostRecentWindow() {
    return top == Cc['@mozilla.org/appshell/window-mediator;1']
        .getService(Ci.nsIWindowMediator)
        .getMostRecentWindow('navigator:browser');
}
