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

window.onload = function()
{
    http = getHTTPObject();
		if (http) {
			
			//alert(http.getResponseHeader("PHP_AUTH_USER"));
			
        var anchors = document.getElementsByTagName("a");
            for (var foo = 0; foo < anchors.length; foo++) {
                if (anchors[foo].className == "httpauth") {
                    createForm(anchors[foo]);
                }
            }
    }
}

function login()
{
    var username = document.getElementById(this.id + "-username").value;
    var password = document.getElementById(this.id + "-password").value;
    http.open("get", this.action, false, username, password);
    http.send("");
    if (http.status == 200) {
        document.location = '/students/';
    } else {
        alert('Incorrect username or password');
    }
    return false;
}

function createForm(jshttpauth)
{
    var form = document.createElement("form");
    form.action = jshttpauth.href;
    form.method = "get";
    form.onsubmit = login;
    form.id = jshttpauth.id;
    var username = document.createElement("label");
    var usernameInput = document.createElement("input");
    usernameInput.name = "username";
    usernameInput.type = "text";
    usernameInput.id = jshttpauth.id + "-username";
    username.appendChild(document.createTextNode("Username:"));
    username.appendChild(usernameInput);
    var password = document.createElement("label");
    var passwordInput = document.createElement("input");
    passwordInput.name = "password";
    passwordInput.type = "password";
    passwordInput.id = jshttpauth.id + "-password";
    password.appendChild(document.createTextNode("Password:"));
    password.appendChild(passwordInput);
    var submit = document.createElement("input");
    submit.type = "submit";
    submit.value = "Log in";
    form.appendChild(username);
    form.appendChild(password);
    form.appendChild(submit);
    jshttpauth.parentNode.replaceChild(form, jshttpauth);
}