$(document).ready(function() {
    // Set the login box position according to the size of the box.
    window.onload = function() {
        w = $('#content_panel').width();
        h = $('#content_panel').height();

        var marleft = -(w/2) + 'px';
        var martop = -(h/2) + 'px';

        $('.loginpanel').css({
            'margin-left': marleft,
            'margin-top': martop
        });

        w1 = $('#login_fields').width();
        var mleft = (w - w1)/2;
        $('.loginfields').css({
            'margin-left': mleft,
        });
    };

    $('#login_submit').click(function(e) {
        $('#forcedlogin').val('False');

        return true;
    });

    $('#forcedlogin_submit').click(function(e) {
        $('#forcedlogin').val('True');

        return true;
    });

    if ($('#forcedlogin_submit').length > 0)
    {
        // Fill the original user name back to the user field if necessary.
        if ($('#id_username').val() == "")
        {
            $('#id_username').val( $('#preusername').val() )
            $('#id_password').focus();
        }
        document.onkeypress = checkEnterKey;
    }

    function checkEnterKey(e) {
        if(!e) {
            e = window.event;
        }

        var code = 0;
        if(e.keyCode) {
            code = e.keyCode;
        }
        else if(e.which) {
            code = e.which;
        }

        if(code == 13) {
            if( $('#id_username').val() == $('#preusername').val() ) {
                // If the username is unchanged, the Enter key will dafult to the Forced Login submit.
                // Setting the focus didn't change the submit button across browsers, so try a click button after it.
                $('#forcedlogin_submit').focus();
                $('#forcedlogin_submit').click();
            }
            else {
                // If the username is changed, the Enter key will dafult to the normal Login submit.
                $('#login_submit').focus();
                $('#login_submit').click();
            }
            return false;
        }

        return true;
    }
});
