$(document).ready(function() {
    $("#frm_login").submit(function() { login(); return false; });
    jQuery.extend({
        'Q' : window.location.search.length <= 1 ? {}
            : function(a){
                var i = a.length, 
                    r = /%25/g,  // Ensure '%' is properly represented 
                    h = {};      // (Safari auto-encodes '%', Firefox 1.5 does not)
                while(i--) {
                    var p = a[i].split('=');
                    h[ p[0] ] = r.test( p[1] ) ? decodeURIComponent( p[1] ) : p[1];
                }
                return h;
            }(window.location.search.substr(1).split('&'))
    });
    
});

function login() {
    /* Grab the username and password */
    username = $("#username");
    password = $("#password");

    /* Send the data */
    $.post("/account/api/login/",
        {
            username: username.val(),
            password: password.val() 
        },
        function(json) {
            if (json["success"]) {
                username.val("");
                password.val("");

                // check to see if they are going to be sent to a site that a
                // person who is logged in shouldn't be going to. If they are
                // force they see the dashboard first.
                refsplit = document.referrer.split('/');
                rel = refsplit[refsplit.length-2];
                rel2 = refsplit[refsplit.length-3];
                if (rel == "register" || rel2 == "register") {
                    window.location = "/account/dashboard/";
                    return false;
                } else if (rel == "activate" || rel2 == "activate") {
                    window.location = "/account/dashboard/";
                    return false;
                }

                // Send them from where they came.
                if (typeof $.Q["next"] != "undefined") {
                    window.location = $.Q["next"];
                    return false;
                } else {
                    if (document.referrer.length > 0) {
                        try {
                            window.location = document.referrer;
                        } catch(error) {
                            window.location = "/account/dashboard/";
                        }
                    } else {
                        window.location = "/account/dashboard/";
                    }
                    return false;
                }
                return false;
            }
            alert(json["message"]);
            password.val("");
        },
        "json"
    );
    return false;
}

