Ext.onReady(function () {
    /**
     * Initialize var
     */
    var loginFormPanel, loginAction, loginField, passwordField, rememberField, forgotAction;

    /**
     * Define submit button
     */
    loginAction = new Ext.Action({
        text : 'Connexion',
        iconCls : 'user_go',
        formBind : true,
        handler : function () {
            // Display wait message
            Ext.Msg.wait('Identification en cours...', 'Identification', { interval : 100 });

            // Get form
            var form  = loginFormPanel.getForm();

            // Set a new connection
            var connection = new Ext.data.Connection({
                url : './doo/user/login/'
            });

            // Send data
            connection.request({
                params : form.getValues(),
                success : function (response) {
                    Ext.Msg.hide();
                    var responseObject = Ext.decode(response.responseText);
                    if (responseObject.success) {
                        loginPanel.close();
                        var loc = 'index.php';
                        if(window.location.search != "") {
                            loc += window.location.search;
                        }
                        window.location = loc;
                    }
                    else {
                        Ext.MessageBox.show({
                            title: 'Identification',
                            msg: responseObject.message,
                            buttons: Ext.MessageBox.OK,
                            fn: function () {
                                loginField.focus();
                            },
                            icon: Ext.MessageBox.ERROR
                        });
                    }
                }
            });
        }
    });

    /**
     * Define forgot password button
     */
    forgotAction = new Ext.Action({
        text : "J'ai oublié mon mot de passe",
        iconCls : 'help',
        handler : function() {
            forgotPanel.show();
        }
    });

    /**
     * Define cancel forgot password button
     */
    cancelForgotAction = new Ext.Action({
        text : 'Annuler',
        iconCls : 'delete',
        handler : function() {
            forgotPanel.hide();
        }
    });

    /**
     * Define send password button
     */
    sendPassAction = new Ext.Action({
        text : 'Envoyer',
        iconCls : 'email',
        handler : function() {
            // Display wait message
            Ext.Msg.wait('Vérification du courriel...', 'Vérification', { interval : 100 });

            // Get form
            var form  = forgotFormPanel.getForm();

            // Set a new connection
            var connection = new Ext.data.Connection({
                url : './doo/user/sendPassword/'
            });

            // Send data
            connection.request({
                params : form.getValues(),
                success : function (response) {
                    Ext.Msg.hide();
                    var responseObject = Ext.decode(response.responseText);
                    if (responseObject.success) {
                        Ext.MessageBox.show({
                            title: 'Identification',
                            msg: 'Votre mot de passe vous a été envoyé.',
                            buttons: Ext.MessageBox.OK,
                            fn: function () {
                                emailField.reset();
                                forgotPanel.hide();
                                loginField.focus();
                            },
                            icon: Ext.MessageBox.INFO
                        });
                    }
                    else {
                        Ext.MessageBox.show({
                            title: 'Identification',
                            msg: 'Le courriel n\'a pas été trouvé.',
                            buttons: Ext.MessageBox.OK,
                            fn: function () {
                                emailField.focus();
                            },
                            icon: Ext.MessageBox.ERROR
                        });
                    }
                }
            });
        }
    });

    /**
     * Define login field
     */
    loginField = new Ext.form.TextField({
        fieldLabel : 'Identifiant',
        name : 'login',
        allowBlank : false,
        value : '',
        selectOnFocus : true,
        listeners : {
            render : {
                delay : 100,
                fn : function () {
                    this.focus();
                }
            }
        }
    });

    /**
     * Define password field
     */
    passwordField = new Ext.form.TextField({
        fieldLabel : 'Mot de passe',
        name : 'password',
        inputType : 'password',
        allowBlank : false,
        value : '',
        selectOnFocus : true
    });

    /**
     * Define email field
     */
    emailField = new Ext.form.TextField({
        fieldLabel : 'Courriel',
        name : 'email',
        allowBlank : false,
        value : '',
        selectOnFocus : true,
        vtype : 'email',
        listeners : {
            render : {
                delay : 100,
                fn : function () {
                    this.focus();
                }
            }
        }
    });

    /**
     *
     */
    rememberField = new Ext.form.Checkbox({
        fieldLabel : 'Mémoriser',
        name : 'remember',
        value : true,
        width : 150
    });

    /**
     * Define form panel
     */
    loginFormPanel = new Ext.form.FormPanel({
        header : false,
        monitorValid : true,
        bodyStyle : {
            padding : '6px'
        },
        defaults : {
            anchor : '100%'
        },
        items : [
            loginField,
            passwordField,
            rememberField
        ],
        keys : [{
            key : Ext.EventObject.ENTER,
            fn : function () {
                var form = loginFormPanel.getForm();
                if (form.isValid()) {
                    loginAction.execute(loginAction);
                }
            }
        }],
        buttonAlign : 'right',
        buttons : [loginAction],
        listeners : {
            render : {
                delay : 100,
                fn : function () {
                    var connection = new Ext.data.Connection({
                        url : './doo/user/getCookies/'
                    });

                    // Send data
                    connection.request({
                        success : function (response) {
                            var responseObject = Ext.decode(response.responseText);
                            if (responseObject.login != '' && responseObject.password != '') {
                                loginField.setValue(responseObject.login);
                                passwordField.setValue(responseObject.password);
                                rememberField.setValue(true);
                            }
                        }
                    });

                    loginFormPanel.getForm().isValid();
                }
            }
        }
    });

    /**
     * Define login window
     */
    loginPanel = new Ext.Window({
        title : 'Identification',
        iconCls : 'key',
        closable : false,
        resizable : false,
        draggable : false,
        width : 300,
        border : false,
        bodyBorder : false,
        constrain : true,
        bodyStyle : {
            padding : '3px'
        },
        items : [loginFormPanel],
        bbar : [forgotAction]
    });
    loginPanel.show();



    /**
     * Define form panel
     */
    forgotFormPanel = new Ext.form.FormPanel({
        header : false,
        monitorValid : true,
        bodyStyle : {
            padding : '6px'
        },
        defaults : {
            anchor : '100%'
        },
        items : [
            emailField
        ],
        keys : [{
            key : Ext.EventObject.ENTER,
            fn : function () {
                var form = forgotFormPanel.getForm();
                if (form.isValid()) {
                    //loginAction.execute(loginAction);
                }
            }
        }],
        buttonAlign : 'right',
        buttons : [cancelForgotAction, sendPassAction],
        listeners : {
            render : {
                delay : 100,
                fn : function () {
                    forgotFormPanel.getForm().isValid();
                }
            }
        }
    });

    /**
     * Define forgot password window
     */
    forgotPanel = new Ext.Window({
        title : "J'ai oublié mon mot de passe",
        iconCls : 'help',
        closable : true,
        resizable : false,
        draggable : false,
        modal : true,
        width : 400,
        border : false,
        bodyBorder : false,
        closeAction : 'hide',
        constrain : true,
        bodyStyle : {
            padding : '3px'
        },
        items : [forgotFormPanel]
    });

    /**
     * Center windows when browser is rezised
     */
    Ext.EventManager.onWindowResize(loginPanel.center, loginPanel);
    Ext.onUnload(function () {
        Ext.EventManager.removeResizeListener(loginPanel.center, loginPanel);
    });

    Ext.EventManager.onWindowResize(forgotPanel.center, forgotPanel);
    Ext.onUnload(function () {
        Ext.EventManager.removeResizeListener(forgotPanel.center, forgotPanel);
    });
});