Ext.onReady(function()
{
    var errorLabel = new Ext.form.Label({
        id: 'formErrorMsg',
        hidden: true
    });

    var submitFn = function()
    {
        var loadMask = new Ext.LoadMask("loginForm", { msg: 'Please wait...' });
        loadMask.show();
        formPanel.getForm().submit({
            url: 'ajax/loginHandler.jsp',
            method: 'POST',
            success: function(form, action)
            {
                loadMask.hide();
                if (action.result.loginSuccess == true)
                {
                    //The user is now logged in -- redirect to the appropriate page.
                    if (action.result.role == "student")
                    {
                        //students go directly to their schedules
                        window.location = 'planner.jsp';
                    }
                    else if (action.result.role == "advisor")
                    {
                        //advisors go to the 'select student' page
                        window.location = 'adminPage.jsp';
                    }
                }
                else
                {
                    //The login failed -- print an error message. 
                    var error = action.result.loginError;
                    errorLabel.setText(error);
                    errorLabel.show();
                }
            },
            failure: function(form, action)
            {
                loadMask.hide();
                var msg = action.failureType;
                if (msg == 'client')
                    errorLabel.setText('Invalid input.');
                else
                    errorLabel.setText(
                        'There was an error with the server or ' +
                        'the connection. Try again');
                errorLabel.show();
            }
        });
    }

    var formPanel = new Ext.form.FormPanel({
        defaultType: 'textfield',
        id: 'formPanel',
        items: [ 
            errorLabel,
            new Ext.form.TextField ({
                fieldLabel: 'Username',
                name: 'username',
                allowBlank: false
            }),
            new Ext.form.TextField ({
                fieldLabel: 'Password',
                inputType: 'password',
                name: 'password',
                allowBlank: false
            })
        ],
        buttons: [
            {
                text: 'Log In',
                handler: submitFn
            }
        ],
        keys: [
            {
                key: Ext.EventObject.ENTER,
                handler: submitFn
            }
        ]
    });

    formPanel.render('loginForm');
});

