﻿Ext.ns('OnCourse', 'OnCourse.pp', 'OnCourse.pp.data');

Ext.onReady(function(){ 

    var Cookies = Ext.util.Cookies;
    Ext.BLANK_IMAGE_URL = '/images/ext/default/s.gif';
    Ext.form.Field.prototype.msgTarget = 'under'; 

    var lastKnownUser = Cookies.get('PublicPortal-LUN') || '';

    var loginPanel = new Ext.FormPanel({
        enableOverflow: false,
        labelWidth: 70,
        labelAlign: 'top',
        monitorValid: true,
        baseCls: 'x-plain',
        autoHeight: true,
        defaultType: 'textfield',
        defaults: {
            validationEvent: false,
            validateOnBlur: false
        },
        items: [{
            id: 'userName',
            fieldLabel: 'Username',
            name: 'userName',
            width: 185,
            allowBlank: false,
            autoCreate: {
                tag: "input",
                type: "text",
                autocomplete: "on"
            }
        }, {
            id: 'password',
            fieldLabel: 'Password',
            name: 'password',
            width: 185,
            allowBlank: false,
            inputType: 'password'
        }],
        buttonAlign: 'center',
        buttons: [{
            id:'signin',
            text: 'Sign In',
            disabled: true,
            handler: doLogin,
            formBind: true
        }],
        keys: [{
            key: 13,
            fn: doLogin
        }]
    });
    
    var recoverPanel = new Ext.FormPanel({
        enableOverflow: false,
        labelWidth: 70,
        labelAlign: 'top',
        monitorValid: true,
        baseCls: 'x-plain',
        autoHeight: true,
        defaultType: 'textfield',
        items: [{
            id: 'email',
            fieldLabel: 'Email',
            name: 'email',
            width: 185,
            allowBlank: false,
            vtype: 'email',
            msgTarget: 'side'
        }],
        buttonAlign: 'center',
        buttons: [{
            id: 'recover',
            text: 'Send Email',
            disabled: true,
            handler: doRecover,
            formBind: true
        }, {
            text: 'Cancel',
            handler: doRecoverCancel
        }]
    });

    var panel = new Ext.Panel({
        layout:'table',
        layoutConfig:{columns:2},
        el: 'login-box',
        frame: true,
        border: false,
        autoHeight: true,
        items: [{
            xtype: 'box',
            el: 'info-box',
            colspan: 2,
            cellCls:'info-cell'
        },{
            xtype: 'box',
            width: 150,
            el: 'left-box',
            cellCls:'left-cell'
        },{
            xtype: 'container',
            layout: 'card',
            activeItem: 1,
            el: 'form-box',
            items: [loginPanel, recoverPanel]
        }]
    });
    panel.render();
    
    Ext.fly('recover-link').on('click', doRecoverShow);

    // HACK to remove the inline width on the button container that
    // causes the buttons to be cutoff in IE
    //var btnCt = loginPanel.getEl().child('.x-panel-btns');
    //btnCt.setStyle('width','');
    //btnCt.child('.x-panel-fbar').setStyle('width','');
    var formCt = panel.getEl().select('.x-form-label-top');
    formCt.setStyle('width', '');
    formCt.select('.x-form').setStyle('width', '');
    
    var btns = panel.getEl().select('.x-panel-btns');
    btns.setStyle('width', '');
    btns.select('.x-panel-fbar').setStyle('width','');

    function doLogin(){
        var form = loginPanel.getForm();
        var signin = Ext.getCmp('signin');
    
        if (form.isValid()) {
            Ext.getDom('logo').src = '/images/oclogo64-anim.gif';

            var o = form.getFieldValues();
            saveCookies(o);

            form.callFieldMethod('disable');
            signin.formBind = false;
            signin.disable();

            OnCourse.direct.PublicPortal.login({username:o.userName.trim(), password:o.password}, function(o, e){
                if (e.status === true && e.result && e.result.CurrentStatus == OnCourse.StatusCode.Success) {
                    window.location.href = e.result.ReturnValue;
                } else {
                    Ext.getDom('logo').src = '/images/oclogo64.gif';
                    form.callFieldMethod('enable');
                    signin.formBind = true;
                    signin.enable();
                    
                    Ext.get("instructions-ct").slideOut('t', {
                        callback: function(){
                            Ext.get("msg-ct").update(e.result ? e.result.Description : e.message).slideIn('t');
                        },
                        useDisplay: true,
                        duration: 0.2
                    });
                }
            });
        }
    };

    function saveCookies(o){
        var date = new Date();
        date.setFullYear(date.getFullYear() + 1);
        Cookies.set('PublicPortal-LUN', o.userName, date);
    }

    if (lastKnownUser) {
        loginPanel.items.get('userName').setValue(lastKnownUser);
        loginPanel.items.get('password').focus(true, true);
    } else {
        loginPanel.items.get('userName').focus(true, true);
    }
    
    function doRecoverCancel() {
        panel.items.items[2].getLayout().setActiveItem(0);
        Ext.get('recover-link').show();
        Ext.get("instructions-ct").update('Please provide your username and password to sign in.');
    }
    
    function doRecoverShow() {
        panel.items.items[2].getLayout().setActiveItem(1);
        Ext.get('recover-link').hide();
        Ext.get("instructions-ct").update('Enter your email address to have your password sent.');
    }
    
    function doRecover() {
        var form = recoverPanel.getForm();
        var button = Ext.getCmp('recover');
    
        if (form.isValid()) {
            Ext.getDom('logo').src = '/images/oclogo64-anim.gif';

            form.callFieldMethod('disable');
            button.formBind = false;
            button.disable();

            OnCourse.direct.PublicPortal.password_request({email:form.findField('email').getValue()}, function(o, e){
                Ext.getDom('logo').src = '/images/oclogo64.gif';

                form.callFieldMethod('enable');
                button.formBind = true;
                button.enable();

                var message = '';
                if (e.status === true && e.result && e.result.CurrentStatus == OnCourse.StatusCode.Success) {
                    message = 'Your password has been sent to the email address provided.';
                } else {
                    message = 'The email address entered is not registered to any user accounts.';
                }
                
                doRecoverCancel();
                    
                Ext.get("instructions-ct").slideOut('t', {
                    callback: function(){
                        Ext.get("msg-ct").update(message).slideIn('t');
                    },
                    useDisplay: true,
                    duration: 0.2
                });
                
            });
        }
    
    }

    doRecoverCancel();
    
});
