﻿
Ext.apply(Ext.form.VTypes, {

    confirmpasswordText: 'Les mots de passe ne sont pas identiques...',

    confirmpassword: function(val, field) {
    
        if (field.initialPasswordField) {
        
            var pwd = Ext.getCmp(field.initialPasswordField);
            return (val == pwd.getValue());
        }
        
        return true;
    }
      
});

Ext.ux.SlickCardLayout = Ext.extend(Ext.layout.CardLayout, {

    setActiveItem : function(item) {
        item = this.container.getComponent(item);
        if (this.activeItem != item){
            if (this.activeItem) {
                this.activeItem.hide();
            }
            this.activeItem = item;
            this.layout();
            item.show();
            item.doLayout();
            item.getEl().slideIn('r', {duration: 0.5, easing: 'easeOutStrong'});
        }
    }
});

Ext.Container.LAYOUTS.slickcard = Ext.ux.SlickCardLayout;

Ext.BLANK_IMAGE_URL = '../img/blank.gif';

Ext.form.BasicForm.prototype.method = 'GET';
Ext.form.FieldSet.prototype.autoHeight = true;
Ext.form.FieldSet.prototype.anchor = '100%';

Ext.form.Field.prototype.msgTarget = 'under';
Ext.form.Field.prototype.anchor = '100%';
Ext.form.Field.prototype.validationEvent = 'blur';

Ext.form.TextField.prototype.blankText = socioscope.defaultFieldBlankText;

// Insures that combo dropdown list is over everything, except Windows...
Ext.form.ComboBox.prototype.listClass = 'combolist';

Ext.layout.FormLayout.prototype.labelSeparator = ' :';

// TODO : transférer en CSS

Ext.Panel.prototype.bodyStyle = "padding: 5px 5px 5px 5px;";
Ext.form.FormPanel.prototype.bodyStyle = 'padding: 10px 10px 0px 10px;';
    
socioscope.userModule = function() {

    var authCookieName = 'socioscope_auth';
    var minimumPasswordLength = 8;
    var minimumPasswordLengthMessage= 'Votre mot de passe doit avoir un minimum de 8 caractères...';

    var strAppUrl = socioscope.appUrl;

    var stateProvider;

    var profileWindow;
    
    var loginBtnId = 'login_btn';
    var logoutBtnId = 'logout_btn';
    var profileBtnId = 'profile_btn';
    
    var hasSession = false;
    var username;
    
    var interval = 1; // en minutes...
    
    var taskRunner = new Ext.util.TaskRunner();
    
    var checkSessionTask = {
        run: function(){
            checkSession();
        },
        interval: interval * 1000 * 60
    };
    
    var showLoginWindow = function() {
    
        if (!hasSession) {
        
            loginWindow.buttons[0].show();
            loginWindow.buttons[1].show();
            loginWindow.buttons[2].hide();
            
            loginWindow.doLayout();

        
            loginWindow.show(loginBtnId);
            loginWindow.getLayout().setActiveItem(0);
        
        }
                
    };
    
    var beforeShowLoginWindow = function()  {
    
    };
    
    var hideLoginWindow = function() {
    

        loginWindow.getBottomToolbar().clearStatus();           
        loginWindow.hide();
        
        Ext.each(loginWindow.findByType('form'), function(obj, index, items) {
        
            var form = obj.getForm();
            
            form.reset();
            form.clearInvalid();

        });
                
    };
    
    var updateInterface = function(hasSession) {
    
        logMessage(hasSession);
    
        if (hasSession) {
                
            Ext.get(loginBtnId).addClass('x-disabled');
            Ext.get(logoutBtnId).removeClass('x-disabled');
            Ext.get(profileBtnId).removeClass('x-disabled');
            
        } else {
        
            if (taskRunner) {
                taskRunner.stop(checkSessionTask);
            }
        
            Ext.get(loginBtnId).removeClass('x-disabled');
            Ext.get(logoutBtnId).addClass('x-disabled');
            Ext.get(profileBtnId).addClass('x-disabled');
        
        }
        
    };
    
    var checkSession = function() {
    
            Ext.Ajax.request({
            method: 'GET',
            url: strAppUrl + 'services/api.ashx',
            params: { method: 'user.checkSession' },
            success: function(response, params) {
               
                var doc;
                
                logMessage(response.responseText);
        
                if (window.ActiveXObject) {
                    doc = new ActiveXObject("Microsoft.XMLDOM");
                    doc.async = "false";
                    doc.loadXML(response.responseText);
                } else {
                    doc = new DOMParser().parseFromString(response.responseText, "text/xml");
                }
                
                var isLoggedIn = toBoolean(doc.getElementsByTagName('response')[0].getAttribute('success'));
                
                if (!isLoggedIn && hasSession) {
                
//                    Ext.MessageBox.show({
//                        title: 'Information',
//                        msg: 'Votre session de travail a expiré à ' + new Date().format('G:i') + '.',
//                        icon: Ext.MessageBox.INFO,
//                        buttons: Ext.MessageBox.OK           
//                    });
                    
                    logMessage('Session has expired');
                    
                }
                   
                hasSession = isLoggedIn;
                updateInterface(hasSession);
                
                logMessage('Check login completed...');
                
                return hasSession;

            },
            
            failure: function(response, params) {
            
                logMessage('Check login failure');
                
            }
            
        });
    
    };
    
    var doLogout = function() {
    
        Ext.Ajax.request({
            method: 'GET',
            url: strAppUrl + 'services/api.ashx',
            params: { method: 'user.logout' }
        });
        
        hasSession = false;
        updateInterface(false);
    
    };
    
    var handleRadioGroupChange = function(obj, value) {
    
        logMessage(value);

        var form = (loginWindow.findById('loginForm').getForm());
        
        var confirmPasswordField = form.findField('confirmpassword');
        
        confirmPasswordField.clearInvalid();
        confirmPasswordField.setDisabled(!value);
        
        if (value) {
            confirmPasswordField.container.up('div').removeClass('x-disabled'); 
        } else {
            confirmPasswordField.container.up('div').addClass('x-disabled');
        }

    };
    
    var handleFailure = function(form, action) {
    
        logMessage('request failure');
        loginWindow.getBottomToolbar().clearStatus();
        
    };
    
    var handleSuccess = function(form, action) {
    
    	loginWindow.getBottomToolbar().clearStatus();
    	
    	var panel = loginWindow.getLayout().activeItem;
        
        switch(panel.id) {
        
            case 'loginForm':
            
                logMessage('login success');
                hasSession = true;

                taskRunner.start(checkSessionTask);
                updateInterface(true);

                hideLoginWindow();
            
                break;
        
            case 'registerForm':
            
                loginWindow.buttons[0].hide();
                loginWindow.buttons[1].hide();
                loginWindow.buttons[2].show();
                loginWindow.getLayout().setActiveItem(3);
                break;
                
            case 'resetPasswordForm':
            
                loginWindow.buttons[0].hide();
                loginWindow.buttons[1].hide();
                loginWindow.buttons[2].show();
                loginWindow.getLayout().setActiveItem(4);
                break;
                
            default:
            
                hideLoginWindow();

        }

    };
    
    var nextBtnHandler = function() {
       
        var panel = loginWindow.getLayout().activeItem;
        var form = panel.getForm();
        var statusBar = loginWindow.getBottomToolbar();
        
        var username;
        
        if (form.isValid()) {
        
            switch(panel.id) {
            
                case 'loginForm':
                 
                    username = form.findField('user').getValue(); 
                    
            	    if (form.getValues().hasPassword == 1) {
                    
                        statusBar.showBusy('Nous vérifions votre identité...');     
                        form.submit({url: strAppUrl + 'services/api.ashx', params: {'method': 'user.login'}, success: handleSuccess.createDelegate(this), failure: handleFailure.createDelegate(this), scope: this}); 
                        
                    } else {
                    
                        var passwordField = form.findField('password');
                        var userField = form.findField('user');
                        
                        panel.getEl().mask();
                        statusBar.showBusy('Un instant...');

                        form.submit({url: strAppUrl + 'services/api.ashx', params: {'method': 'user.login', 'checkonly': true},
                        
                            failure: function() {
                            
                                passwordField.enable();
                                statusBar.clearStatus();
                                panel.getEl().unmask();
                        
                                if (userField.validate()) {
                                
                                    loginWindow.getLayout().setActiveItem(1);
                                    loginWindow.getLayout().activeItem.doLayout();
                                                           
                                }
                        
                            }, 
                            
                            success: function() {
                            
                                userField.markInvalid('Ce courriel est déjà inscrit dans notre base de données: peut-être avez-vous déjà un mot de passe?');
                    
                                passwordField.enable();
                                statusBar.clearStatus();
                                panel.getEl().unmask();
                                
                            }
                            
                        }); 
                                                                            
                    }
                    
                
                    break;   
                     
                case 'registerForm':
                
                    username = loginWindow.getComponent(0).getForm().findField('user').getValue();
                    var password = loginWindow.getComponent(0).getForm().findField('password').getValue();
                    var confirmPassword = loginWindow.getComponent(0).getForm().findField('confirmpassword').getValue();
                
                    statusBar.showBusy('Nous traitons votre demande...');
                    form.submit({url: strAppUrl + 'services/api.ashx', success: handleSuccess.createDelegate(this), failure: handleFailure.createDelegate(this), params: {'method': 'user.register', 'user': username, 'password': password, 'confirmpassword': confirmPassword}}); 

                    break;
                    
                case 'resetPasswordForm':
                
                    username = loginWindow.getComponent(0).getForm().findField('user').getValue();

                    statusBar.showBusy('Nous traitons votre demande...');
                    form.submit({url: strAppUrl + 'services/api.ashx', success: handleSuccess.createDelegate(this), failure: handleFailure.createDelegate(this), params: {'method': 'user.resetpassword', 'user': username}}); 

                    break;
                  
                default:
                
                    loginWindow.hide();

            }
        
        }
	    
    };
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    var errorReader = new Ext.data.XmlReader(
        {record : 'error', success: '@success'}, ['id', 'msg']
    );
    
    var userInfoReader = new Ext.data.XmlReader(
        {record : 'user', success: '@success'}, ['name', 'secretquestion']
    );

    var loginWindow = new Ext.Window({
        width: 450,
        height: 470,
        closeAction:'hide',
        hideMode: 'visibility',
        plain: true,
        closable: false,
        resizable: false,
        draggable: true,
        shadow: 'frame',
        shadowOffset: 6,
        hidden: true,
        layout: 'card',
        bodyStyle: 'padding: 0px;',
        activeItem: 0,
        items: [
                {xtype: 'form', id: 'loginForm', title: 'Ouverture de session', frame: true, errorReader: errorReader, items: [
                        {xtype: 'fieldset', title: 'Quelle est votre adresse courriel ?', autoHeight: true, items: [
                                {xtype: 'textfield', hideLabel: true, allowBlank: false, id: 'user', name: 'user', vtype: 'email', vtypeText: socioscope.incorrectEmailMessage}
                            ]
                        },
                        {xtype: 'fieldset', title: 'Possédez-vous déjà un mot de passe?', autoHeight: true, items: [
                                {xtype: 'panel', bodyStyle: 'padding: 0px; margin-bottom: 20px;', items: [
                                        {xtype: 'radio', boxLabel: '<b>Oui</b>', hideLabel: true, name: 'hasPassword', inputValue: 1, checked: true},
                                        {xtype: 'radio', boxLabel: '<b>Non</b>, je suis un nouvel utilisateur, et je désire m\'inscrire...', hideLabel: true, name: 'hasPassword', inputValue: 0, listeners: {'check': {fn: handleRadioGroupChange, scope: this}} }                                 
                                    ]
                                },
                                {xtype: 'textfield', id: 'password', inputType: 'password', minLength: this.minimumPasswordLength, minLengthText: this.minimumPasswordLengthMessage, fieldLabel: 'Mot de passe', allowBlank: false, name: 'password'},
                                {xtype: 'textfield', id: 'confirmpassword', inputType: 'password', itemCls: 'x-disabled', fieldLabel: 'Confirmer', name: 'confirmpassword', disabled: true, allowBlank: false, vtype: 'confirmpassword', initialPasswordField: 'password'}
                            ]
                        },
                        {xtype: 'panel', html: '<a id="resetPasswordBtn" href="#">(vous avez oublié votre mot de passe ?)</a>'}

                    ]
                },
                    
                {xtype: 'form', id: 'registerForm', title: 'Question secrète', frame: true, errorReader: errorReader, items: [
                        {xtype: 'panel', html: '<div><p>Vous devez maintenant définir une question secrète, de même que la réponse appropriée, qui nous permettra éventuellement de vous identifier si vous oubliez votre mot de passe.</p><br/></div>'},
                        {xtype: 'fieldset', items: [
                                {xtype: 'textarea', fieldLabel: 'Votre question', allowBlank: false, emptyText: 'Par exemple : Quel est le nom de fille de ma mère?', name: 'secretquestion'},
                                {xtype: 'textfield', fieldLabel: 'Votre réponse', allowBlank: false, name: 'secretanswer'}
                            ]
                        }
                    ]
                },
                    
                {xtype: 'form', id: 'resetPasswordForm', title: 'Récupération du mot de passe', frame: true, reader: userInfoReader, errorReader: errorReader, waitMsgTarget: true, listeners: {'show': {fn: function(obj) {loginWindow.getBottomToolbar().showBusy('Récupération de vos informations...'); obj.getEl().mask(); obj.getForm().load({url: strAppUrl + 'services/api.ashx?method=user.getprofile&user=' + loginWindow.getComponent(0).getForm().findField('user').getValue(), success: function(form, action) {obj.getEl().unmask(); loginWindow.getBottomToolbar().clearStatus();} });}}}, items: [
                        {xtype: 'panel', html: '<div><p>Afin que nous puissions vous assigner un nouveau mot de passe, vous devez répondre correctement à votre question secrète.</p><br/></div>'},
                        {xtype: 'fieldset', items: [
                                {xtype: 'textarea', fieldLabel: 'Votre question', readOnly: true, name: 'secretquestion'},
                                {xtype: 'textfield', fieldLabel: 'Votre réponse', allowBlank: false, name: 'secretanswer'}
                            ]
                        }
                    ]
                },
                
                {xtype: 'panel', id: 'registerConfirmPanel', title: 'Félicitations !', frame: true, items: [
                        {xtype: 'panel', html: '<div><p>La première phase de votre inscription a été effectuée avec succès.</p><p>Vous recevrez bientôt par courriel des informations qui vous permettront de compléter ce processus.</p><br/></div>'}
                    ]
                },
                
                {xtype: 'panel', id: 'resetPasswordConfirmPanel', title: 'Félicitations !', frame: true, items: [
                        {xtype: 'panel', html: '<div><p>Votre mot de passe a été remplacé.</p><p>Vous recevrez bientôt par courriel des informations qui vous permettront d\'accéder à nouveau au site.</p><br/></div>'}
                    ]
                }

                    
            ],
            
            buttons: [
                    {
                        text: 'Annuler',
                        handler: function() {
                            hideLoginWindow();
                        }
                    },
                    {
                        text: 'Continuer',
                        handler: nextBtnHandler.createDelegate(this)
                    },
                    {
                        text: 'Terminé',
                        handler: function() {
                            hideLoginWindow();
                        },
                        hidden: true
                    }
                ],
                
                                bbar: new Ext.StatusBar({
                    defaultText: '',
                    id: 'loginWindowStatusbar'
                    }
                )
                
                
            });
            
            loginWindow.setPosition(280, 150);
            
            loginWindow.on('beforeshow', function() {Ext.get('content').mask();}, this);
            loginWindow.on('hide', function() {Ext.get('content').unmask();}, this);
            
    var resetPasswordBtnHandler = function(evt, target, options) {
    
        var statusBar = loginWindow.getBottomToolbar();
        
            var userField = loginWindow.getLayout().activeItem.getForm().findField('user');
            var passwordField = loginWindow.getLayout().activeItem.getForm().findField('password');
            var confirmPasswordField = loginWindow.getLayout().activeItem.getForm().findField('confirmpassword');
            
            var layout = loginWindow.getLayout();
            var panel = layout.activeItem;
           
            var form = layout.activeItem.getForm();
            
            passwordField.disable();
            confirmPasswordField.disable();
            
            panel.getEl().mask();
            statusBar.showBusy('Un instant...');

            form.submit({url: strAppUrl + 'services/api.ashx', params: {'method': 'user.login', 'checkonly': true},
            
                success: function() {
        
                    passwordField.enable();
                    statusBar.clearStatus();
                    panel.getEl().unmask();
            
                    if (userField.validate()) {
                                                    
                        layout.setActiveItem(2);
                        layout.activeItem.doLayout();
                        
                    }
            
                }, 
                
                failure: function() {
                             
                    passwordField.enable();
                    statusBar.clearStatus();
                    panel.getEl().unmask();
                    
                }
                
            }); 
                           
        };
    
    return {
    
        hasSession: function() {
            return hasSession;
        },
        
        init: function() {

            loginWindow.on('show', function(obj) {
                Ext.get('resetPasswordBtn').on('click', function() {resetPasswordBtnHandler();}, this, {preventDefault: true}); 
            }, this, {single: true});
            
            Ext.get(loginBtnId).on('click', function(evt, target, options) {showLoginWindow();}, this, {preventDefault: true}); 
//            Ext.get(profileBtnId).on('click', function(evt, target, options) {showProfileWindow();}, this, {preventDefault: true});  
            Ext.get(logoutBtnId).on('click', function(evt, target, options) {doLogout();}, this, {preventDefault: true}); 
            
            taskRunner.start(checkSessionTask);
                      
            Ext.fly('session_tools').setVisible(true);
                                 
            logMessage('Socioscope user module started...');
            
        }
        
    };

}();

Ext.onReady(socioscope.userModule.init, socioscope.userModule);


