$(document).ready(function(){
    $("#loginform").submit(function(event){
        $("#ajax-loader-top").show();
        event.preventDefault();
        errors = new Array();
        if ($.trim($("#username").val()) == "") {
            $("#username").css("border-color", "#EE4400");
            errors += "Please fill in your username."
        }
        if ($.trim($("#password").val()) == "") {
            $("#pasword").css("border-color", "#EE4400");
            errors += "Please fill in your password."
        }
        if (errors.length > 0) {
            alert("There were errors: " + errors);
            $("#ajax-loader-top").hide();
        } else {
            un = $("#username").val();
            $.post("/users/getsaltseed/", { username: un }, function(saltseed){
                if (saltseed != false) {
                    salt = saltseed[0];
                    seed = saltseed[1];
                    pw = $("#password").val();
                    pwhash = hex_sha1(pw);
                    hash = hex_sha1(salt + pwhash);
                    seedhash = hex_sha1(seed + hash);
                    $.post("/users/login_check/", { username: un, fullhash: seedhash }, function(data){
                        if (data == true) {
                            location.href = "/";
                        } else {
                            $("#ajax-loader-top").css("display", "none");
                            alert(data);
                        }
                    }, "json");
                } else {
                    id = Math.round(Math.random()*100);
                    while (document.getElementById(id.toString())) {
                        id = Math.round(Math.random()*1000);
                    }
                    $("#header").append('<div class="absolutebox" id="' + id.toString() + '"><a class="close_x"><span class="ui-icon ui-icon-closethick">x</span></a></div>');
                    $("#" + id.toString()).append('<div class="alertbox-header">' + gettext("Login failed!") + '</div><div class="alertbox-content">' + gettext("This user doesn't exist.") + '</div>');
                    $("#ajax-loader-top").hide(200);
                    $(".close_x").click(function(){
                        $(this).parent().hide(300).remove();
                    })
                }
            });
        }
    });
});
