function xhr()
{
    if (typeof XMLHttpRequest != 'undefined')
        return new XMLHttpRequest();
    try {
        return new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            return new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {
        }
    }
    return null;
}

function xhrloginform(targetURI)
{
    var x = xhr();
    if (!x)
        return;
    var httplogin = document.getElementById('httplogin');
    if (httplogin)
        httplogin.style.display = 'none';
    document.write('<form id="xhrlogin">'
                  +  '<p><label>Username: <input type="text" name="username" id="username" class="line" /></label></p>'
                  +  '<p><label>Password: <input type="password" name="password" id="password" class="line" /></label></p>'
                  +  '<p><input type="submit" value="Log in" /></p>'
                  +  '<div id="status"><p></p></div>'
                  +'</form>');
    document.getElementById('username').focus();
    var s = document.getElementById('status');
    function loginStatus(c, h) {
        s.className = c;
        s.innerHTML = "<p>" + h + "</p>";
    };
    document.getElementById('xhrlogin').onsubmit = function() {
        x.abort();
        function doxhr(user, pass, cont) {
            x.open('GET', targetURI, true, user, pass);
            x.onreadystatechange = function() {
                if (x.readyState == 4)
                    cont();
            };
            x.send(null);
        };
        var username = document.getElementById('username').value;
        var password = document.getElementById('password').value;
        if (username == "" || password == "") {
            loginStatus('error', 'Please enter your username and your password.');
            return false;
        }
        loginStatus('inprogress', 'Logging in...');
        doxhr("logout!", "logout", function() {
            doxhr(username, password, function() {
                if (x.status == 200 || x.status == 304) {
                    loginStatus('success', 'Logged in.  Refreshing page...');
                    location.replace(location.href);
                } else if (x.status == 403) {
                    loginStatus('error', 'The username or password you entered is incorrect.');
                } else {
                    loginStatus('error', 'An error occurred when attempting to log in.  The following information may help us troubleshoot this problem: (HTTP ' + x.status + ' ' + x.statusText + ')');
                }
            });
        });
        return false;
    };
}
