Ext.namespace('InterActive.user')

InterActive.user.LoginPanel = function (config) {
    var internalConfig = {
        frame: true,
        title: 'Sign In',
        ctCls: 'loginBox',
        labelWidth: 80,
        width: 330,
        waitMsgTarget: true,
        loginAction: document.baseURI + 'user/login',
        redirectUrl: document.baseURI + 'dashboard',

        listeners: {
            actioncomplete: {
                fn: function(form, action){
                    /**
                     * Send authorization to moodle only for users with role='student'
                     * @see http://projects.itransition.com/browse/INTERACTIVE-197
                     */
                    if (action.result.role !== 'student') {
                        this.moodleLogin = false
                    }

                    var hasReturnUrl = typeof action.result.returnUrl !== 'undefined' && action.result.returnUrl !== null
                    var returnUrl = hasReturnUrl ? action.result.returnUrl : this.redirectUrl
                    var returnToApplication = function(){
                        // old way
                        if (window.location.pathname.indexOf('redirect/back') === -1) {
                            document.location = returnUrl
                            return
                        }

                        // new way
                        window.history.back()
                    }

                    if (!this.moodleLogin) {
                        returnToApplication()
                        return
                    }

                    // Cross-Login to Moodle
                    var loginData = this.getForm().getValues()
                    Ext.Ajax.request({
                        url: document.baseURI + 'moodle/login/index.php',
                        method: 'POST',
                        params: {
                            username: action.result.studentId,
                            password: loginData.password,
                            submit: 'Login',
                            testcookies: 1
                        },
                        success: returnToApplication,
                        failure: returnToApplication,
                        scope: this
                    })
                }
            },
            actionfailed: {
                fn: function(){
                    Ext.getCmp('infoBox').hide()
                    Ext.getCmp('errorBox').show()
                    Ext.getCmp('login-panel').doLayout()
                    this.focus()
                }
            }
        },

        items: [{
            id: 'infoBox',
            html: '<table class="errorBox"><tr><td class="icon"><div class="error-icon"></div></td><td class="error-text">You must log in to see this page.</td></tr></table>'
        }, {
            id: 'errorBox',
            html: '<table class="errorBox"><tr><td class="icon"><div class="error-icon"></div></td><td class="error-text">The information you entered does not match our records. Please enter a valid Username and Password combination.</td></tr></table>'
        }, {
            layout: 'form',
            items: [{
                xtype: 'textfield',
		    fieldLabel: 'Email',
		    name: 'email',
                width: 215,
                allowBlank:false,
                listeners:{
                    'specialkey': {
                        fn:function(field,e){
                            if (e.getKey() == Ext.EventObject.ENTER){
                                Ext.getCmp('sign-in-button').handler.call(this)
                            }
                        },
                        scope:this
                    }
                }
            }, {
                xtype: 'textfield',
                fieldLabel: 'Password',
                name: 'password',
                inputType: 'password',
                allowBlank:false,
                width: 215,
                listeners:{
                    'specialkey': {
                        fn:function(field,e){
                            if (e.getKey() == Ext.EventObject.ENTER){
                                Ext.getCmp('sign-in-button').handler.call(this)
                            }
                        },
                        scope:this
                    }
                }
            }]
        }, {
            layout: 'column',
            items: [{
                id:'passwordRecoveryBox',
                html:'<a href="user/password-recovery">Forgot password?</a>'
            }, {
                id:'guestBox',
                html:'&nbsp;|&nbsp;<a href="demo/sign-in">Sign up as guest</a>',
                hidden: true
            }, {
                id: 'buttonBox',
                layout: 'form',
                items: [{
                    xtype: 'button',
                    text: 'Sign In',
                    id: 'sign-in-button',
                    handler: function(){
                        var form = this.getForm()
                        if (form.isValid()){
                            form.submit(Ext.isIE6 ? {
                                url: this.loginAction
                            } : {
                                url: this.loginAction,
                                waitMsg: 'Please wait a second...'
                            })
                        }
                    },
                    scope: this
                }]
            }]
        }
        ]
    }

    config = config || {}
    Ext.applyIf(config, internalConfig)
    InterActive.user.LoginPanel.superclass.constructor.call(this, config)
}

Ext.extend(InterActive.user.LoginPanel, Ext.FormPanel, {
    initComponent: function () {
        InterActive.user.LoginPanel.superclass.initComponent.call(this)

        if (!Itransition.view.ViewState.getFlag('show-error-box')) {
            Ext.getCmp('errorBox').hide()
        }

        if (!Itransition.view.ViewState.getFlag('show-info-box')) {
            Ext.getCmp('infoBox').hide()
        }

        if (Itransition.view.ViewState.getFlag('show-guest-login-link')) {
            Ext.getCmp('guestBox').show()
        }
    }
});
