var MD5 = new MD5();

var Mplus = {
    switchUser: null,
	login: null,

    remote: function(sendObj, callback, authenticate, hint) {
        this.login = $E(".widget_login").widget;
        var authObj = {};
        var timeleft = this.login.expires - $time();
        var call = [];
        var key = this.login.loginObj["mplus.directory.login"].key;

        authenticate = authenticate || false;
        hint = hint || null;

        if(!key || authenticate || timeleft < 1000) {
            call = ["mplus.directory.login"];
            if(hint) {
                call.push(":", hint);
            }
            authObj = {};

            if(this.login.pass && this.login.pass.length > 0) {
                authObj[call.join("")] = {
                    "user": this.login.user,
                    "pass": this.login.pass,
                    "authenticate": authenticate
                };
            } else {
                authObj[call.join("")] = {
                    "authenticate": authenticate
                };
            }
        } else {
            call = ["mplus.directory.resume"];
            if(hint) {
                call.push(":", hint);
            }
            authObj = {};
            authObj[call.join("")] = {
                "object": this.login.loginObj["mplus.directory.login"].object,
                "pass": MD5.hex_md5(key + timeleft.toString()),
                "remainder": timeleft
            };
        }
        if(Mplus.switchUser) {
            authObj["mplus.directory.switch"] = Mplus.switchUser;
        }

        // make sure login/resume succeeded before doing the callback
        var verify = function(res) {
			var login = $E(".widget_login").widget;
            if(call[0] == "mplus.directory.resume") {
                if(res[call.join("")].error) {
                    // resume failed, fall back on login
                    login.expires = 0;
                    login.key = null;
                    return Mplus.remote(sendObj, callback, authenticate, hint);
                }
            } else if(call[0] == "mplus.directory.login") {
                if(res[call.join("")].error) {
                    // login failed altogether, kick the user out
                    window.location.href = window.location.href;
                    return;
                } else {
                    // success, update the expiration
                    var timeout = res[call.join("")].timeout;
                    var key = res[call.join("")].key;
                    login.expires = timeout + $time();
                    login.key = key;
                }
            }
            // all is well, hand off to the callback
            callback(res);
        };
        return Warp.remote($merge(authObj, sendObj), verify,
						   "/authenticated/handleajaj");
    }
};
