/* 
 * Login Communication Application
 */
 
 
Ext.namespace('contentcard.login'); 

contentcard.login.execute = function (service, identifer, password, cookie, successCallback, failureCallback)
                            {
                                if (cookie == undefined || parseInt(cookie) != 1)
                                {
                                    cookie = 0;
                                }
                                
                                if (identifer.length < 1 || password.lenth < 1)
                                {
                                    failureCallback();
                                }
                                else
                                {
                                    Ext.Ajax.request(
                                                     {
                                                       url:     service,
                                                       success: successCallback,
                                                       failure: failureCallback,
                                                       params:  { 
                                                                    Id: identifer, 
                                                                    Password: password, 
                                                                    Mode: 'Login', 
                                                                    Cookie: cookie 
                                                                }
                                                     }
                                                    );
                                }
                            };   
                            
contentcard.login.dialog = function (service, identifer, cookie, successCallback, failureCallback, beforeExecuteCallback)
                           {
                                var IdentiferField = new Ext.form.TextField(
                                                                       {    
                                                                          fieldLabel: contentcard.translation.get('_IDF_USER'),
                                                                          width:      150,
                                                                          xtype:      'textfield',
                                                                          id:         'idfSystemIdentifer',
                                                                          xtype:      'textfield',
                                                                          allowBlank: false,
                                                                          listeners:  { 
                                                                                         'specialkey': LoginExecuter_OnEnter
                                                                                      }                                              
                                                                        }
                                                                      );
                                                                      
                                                                      
                                var PasswordField = new Ext.form.TextField(
                                                                      {
                                                                        fieldLabel: contentcard.translation.get('_IDF_PASSWORD'),
                                                                        width:      150,
                                                                        xtype:      'textfield',
                                                                        inputType:  'password',
                                                                        id:         'idfSystemPassword',
                                                                        allowBlank: false,
                                                                        listeners:  { 
                                                                                        'specialkey': LoginExecuter_OnEnter 
                                                                                    }
                                                                       }
                                                                      );                                  
                                                                      
                                 var LoginButton = new Ext.Button({
                                                                     text:      contentcard.translation.get('_IDF_LOGIN_BUTTON'),
                                                                     id:        'idfSystemLoginButton',
                                                                     autoShow:  true,
                                                                     listeners: { 
                                                                                    'click': LoginExecuter
                                                                                }
                                                                  });
                                                                  
                                 var CancelButton = new Ext.Button({
                                                                     text:      contentcard.translation.get('_IDF_CANCEL_BUTTON'),
                                                                     id:        'idfSystemCancelButton',
                                                                     autoShow:  true,
                                                                     listeners: { 
                                                                                    'click': function () 
                                                                                             {
                                                                                                idfLoginWindow.close();
                                                                                             }
                                                                                }
                                                                  });
                                                                  
                                function LoginExecuter_OnEnter(Sender, EventArgs)
                                {
                                    if (EventArgs.getCharCode() == EventArgs.ENTER)
                                    {
                                         LoginExecuter();
                                    }
                                }
                                                                  
                                function LoginExecuter(executeCallback)
                                {
                                    if (IdentiferField.isValid() && PasswordField.isValid())
                                    {
                                        if (typeof beforeExecuteCallback == 'function')
                                        {
                                            beforeExecuteCallback();
                                        }
                                        contentcard.login.execute(service, IdentiferField.getValue(), PasswordField.getValue(), 0, successCallback, failureCallback);
                                    }
                                }
                                                                      

                                 var idfSystemLoginPanel = new Ext.FormPanel(
                                                                            {
                                                                                labelWidth: 75, 
                                                                                frame:      true,
                                                                                region:     'center',
                                                                                bodyStyle:  'padding: 5px 5px 0',
                                                                                width:       270,
                                                                                items: [IdentiferField, PasswordField],
                                                                                buttons: [LoginButton, CancelButton]
                                                                            }
                                                                        );
                                                                        
                                if (identifer != undefined && identifer != null && identifer.length > 0)
                                {
                                    IdentiferField.setValue(identifer);
                                    IdentiferField.setDisabled(true);
                                }
                                
                                PasswordField.setValue('');
                                PasswordField.reset();
                                PasswordField.focus(false, 50);

                                var idfLoginWindow = new Ext.Window(
                                                                    {    
                                                                        title:      contentcard.translation.get('_IDF_LOGIN_TITLE'),
                                                                        closable:   true,
                                                                        width:      270,
                                                                        height:     140,
                                                                        modal:      true,
                                                                        closable:   true,
                                                                        resizable:  false,
                                                                        draggable:  false,
                                                                        layout:     'fit',
                                                                        items:      [idfSystemLoginPanel]
                                                                    }
                                                                  ); 
                                return idfLoginWindow;
                            }
 

Ext.onReady(function()
{
    // Login Form Interface (LFI) 
    // ---------------------------------------------------------------------------------------------------------------------------------------- //
    
    var catchEnterPressOnLoginTextField =   function (Sender, EventArgs)
                                            {
                                               if (EventArgs.getCharCode() == EventArgs.ENTER && Username.isValid() && Password.isValid())
                                               {
                                                   LoginButton.fireEvent('click');
                                               }
                                            }

    var Username = new Ext.form.TextField(
                                          {    
                                              baseCls:   'x-plain',
                                              //allowBlank: false,
                                              applyTo: 'Username',
                                              width:      200,
                                              autoCreate: {tag: "input", type: "text", size: "20", autocomplete: "on"},
                                              listeners: { 
                                                            'specialkey': catchEnterPressOnLoginTextField 
                                                         }                                                  
                                           }
                                          );

     var Password = new Ext.form.TextField(
                                            {   
                                                baseCls:   'x-plain',
                                                inputType: 'password',
                                                applyTo: 'Password',
                                                //allowBlank: false,
                                                width:      200,
                                                listeners: { 
                                                                'specialkey': catchEnterPressOnLoginTextField 
                                                           }
                                                
                                            }
                                           );   

     var LoginButton = new Ext.Button({
                                            text:     '<b>'+contentcard.translation.get('_IDF_LOGIN_BUTTON')+'</b>',
                                            renderTo: 'LoginButton',
                                            width:     50,
                                            autoShow:  true,
                                            listeners: { 
                                                         'click': function () 
                                                                  { 
                                                                     if (Username.isValid() && Password.isValid())
                                                                     {
                                                                         Account(Username.getValue(), Password.getValue()); 
                                                                     }
                                                                  } 
                                                       }
                                          });
    // Login Grid Interface (LGI)
    // ---------------------------------------------------------------------------------------------------------------------------------------- //
    
    var LoginServiceURL = contentcard.config.get('LoginAPI');
    var LoginMask;
    var LoginGridWindowIsInPosition = false;
    var LoginDirectWindowIsInPosition = false;    
    var LoginRequiredWindow;
    var LoginJsonStore = new Ext.data.JsonStore(
                                                 {
                                                    root: 'Data',
                                                    url:  LoginServiceURL,
                                                    fields: [ 'System', 'Username', 'Customer', 'Valid', 'Type' ]
                                                 }
                                                );
                                                

                                                
    function createLoadingMask(msg)
    {
        if (typeof LoginMask == 'object')
        {
            LoginMask.hide();
            LoginMask = null;
        }
        LoginMask = new Ext.LoadMask(Ext.getBody(), {msg: msg});
    }
    
    function showLoadingMask()
    {
        LoginMask.show();
    }
    
    function hideLoadingMask()
    {
        LoginMask.hide();
    }
    
    function LoginGridRowRenderer(msg)
    {
        return '<div style="font-size: 11px; height: 25px; cursor: pointer;">'+msg+'</div>';
    }
    
    function LoginGridCustomerRenderer(msg)
    {
        if (msg == undefined || msg.length == 0)
        {
            msg = contentcard.translation.get('_IDF_NO_CUSTOMERNO');
        }
        return '<div style="font-size: 11px; height: 25px; cursor: pointer;">'+msg+'</div>';
    }

    function LoginGridHeaderRenderer(msg)
    {
        return '<span style="font-size: 11px; font-weight: bold;">'+msg+'</span>';
    }

    function LoginGridTypeRenderer(type)
    {
        return ((type == '1') ? '<img src="'+contentcard.config.get('Path')+'/images/loginCustomer.png" />' : '<img src="'+contentcard.config.get('Path')+'/images/loginSystem.png" />');
    }

    var LoginGrid = new Ext.grid.GridPanel(
                                            {
                                                store:  LoginJsonStore,
                                                region: 'center',
                                                listeners: { rowclick: function(Object, RowId, Event) 
                                                                       {
                                                                           // user is allowed to login immediately
                                                                           if (LoginJsonStore.getAt(RowId).get('Valid') == '1')
                                                                           {
                                                                                LoginGridWindow.hide();
                                                                                createLoadingMask(contentcard.translation.get('_IDF_LOGIN_WAIT'));
                                                                                showLoadingMask();
                                                                                LoginService(LoginJsonStore.getAt(RowId).get('Username'), Password.getValue(), 0, SingleLoginSuccess, SingleLoginFailure);
                                                                           }
                                                                           // additional login is required
                                                                           else
                                                                           {
                                                                                LoginRequiredWindow = contentcard.login.dialog(LoginServiceURL, LoginJsonStore.getAt(RowId).get('Username'), 0, directLoginSuccess, directLoginFailure, executeLoginWait); 
                                                                                LoginRequiredWindow.on('close', function () { LoginGridWindow.show(); });
                                                                                
                                                                                LoginRequiredWindow.show();
                                                                                LoginRequiredWindow.setPosition(LoginRequiredWindow.getPosition()[0], LoginRequiredWindow.getPosition()[1]-100);
                                                                                LoginGridWindow.hide();
                                                                           }
                                                                       }  
                                                            },
                                                columns: [
                                                            { name: 'Type',     header: LoginGridHeaderRenderer(contentcard.translation.get('_IDF_TYPE')),       width: 35,  fixed: true, resizable: false, menuDisabled: true, sortable: false, renderer: LoginGridTypeRenderer, dataIndex: 'Type'     },
                                                            { name: 'System',   header: LoginGridHeaderRenderer(contentcard.translation.get('_IDF_SYSTEM')),     width: 200, fixed: true, resizable: false, menuDisabled: true, sortable: false, renderer: LoginGridRowRenderer,  dataIndex: 'System'   },
                                                            { name: 'Username', header: LoginGridHeaderRenderer(contentcard.translation.get('_IDF_USER')),       width: 160, fixed: true, resizable: false, menuDisabled: true, sortable: false, renderer: LoginGridRowRenderer,  dataIndex: 'Username' },
                                                            { name: 'Customer', header: LoginGridHeaderRenderer(contentcard.translation.get('_IDF_CUSTOMERNO')), width: 105, fixed: true, resizable: false, menuDisabled: true, sortable: false, renderer: LoginGridCustomerRenderer,  dataIndex: 'Customer' }
                                                          ],
                                                stripeRows: true,
                                                autoHeight: true,
                                                width: 504
                                              }
                                           );
                                           
        var LoginGridWindow = new Ext.Window(
                                             {
                                                title:       contentcard.translation.get('_IDF_SELECT_LOGIN'),
                                                closable:    true,
                                                width:       504,
                                                modal:       true,
                                                resizable:   false,
                                                draggable:   false,
                                                closeAction: 'hide',
                                                layout:      'fit',
                                                items:       [LoginGrid]
                                             }
                                            );
                                            
        var showLoginGridWindow =    function ()
                                    {
                                        LoginGridWindow.show();
                                        
                                        if (!LoginGridWindowIsInPosition)
                                        {
                                            LoginGridWindow.setPosition(LoginGridWindow.getPosition()[0], LoginGridWindow.getPosition()[1]-130);
                                            LoginGridWindowIsInPosition = true;
                                        }
                                    }                           

    // Login Verification
    // ---------------------------------------------------------------------------------------------------------------------------------------- //
    
        function Account(identifer, password)
        {
            if (identifer.length && password.length)
            {
                LoginJsonStore.removeAll();
                createLoadingMask(contentcard.translation.get('_IDF_LOGIN_WAIT'));
                showLoadingMask();
                LoginJsonStore.load(
                                    {  
                                        params: 
                                                { 
                                                    Id: identifer, 
                                                    Password: password, 
                                                    Mode: 'List' 
                                                },
                                        callback: AccountResultHandler
                                    }
                                   );    
            }
        }
        
        function AccountResultHandler(record, options, success)
        {
            Ext.get('LoginMessage').update('');

            if (success)
            {
                // Multi logins
                if (LoginJsonStore.getTotalCount() > 1)
                {
                    hideLoadingMask();
                    showLoginGridWindow();
                }
                // Single login
                else if (LoginJsonStore.getTotalCount() == 1)
                {
                    LoginService(LoginJsonStore.getAt(0).get('Username'), Password.getValue(), 0, SingleLoginSuccess, SingleLoginFailure);
                }
                // Invalid login
                else
                {
                    hideLoadingMask();
                    Username.markInvalid();
                    Password.markInvalid();
                    Ext.get('LoginMessage').update(contentcard.translation.get('_IDF_LOGIN_INVALID'));
                }
            }
            else
            {
                hideLoadingMask();
                Ext.get('LoginMessage').update(contentcard.translation.get('_IDF_LOGIN_ERROR'));
            }
        }
        
        function LoginService(identifer, password, cookie, successCallback, failureCallback)
        {
            contentcard.login.execute(LoginServiceURL, identifer, password, cookie, successCallback, failureCallback);
        }
        
        function SingleLoginSuccess(data)
        {
            if (data.responseText == '1')
            {
                $('CreateLogin').submit();
            }
            else
            {
                LoginGridWindow.hide();
                Ext.get('LoginMessage').update(contentcard.translation.get('_IDF_LOGIN_ERROR'));
            }
        }
        
        function SingleLoginFailure()
        {
            LoginGridWindow.hide();
            hideLoadingMask();
            Ext.get('LoginMessage').update(contentcard.translation.get('_IDF_LOGIN_ERROR'));
        }
        
        function executeLoginWait()
        {
            createLoadingMask(contentcard.translation.get('_IDF_LOGIN_WAIT'));
            showLoadingMask();
            LoginRequiredWindow.hide();
        }

        function directLoginSuccess(data)
        {
            if (data.responseText == '1')
            {
                $('CreateLogin').submit();
            }
            else
            {
                hideLoadingMask();
                LoginGridWindow.hide();
                LoginRequiredWindow.show();
                Ext.getCmp('idfSystemPassword').markInvalid();
            }
        }
          
        function directLoginFailure(data)
        {
            hideLoadingMask();
            LoginRequiredWindow.show();
            Ext.getCmp('idfSystemPassword').markInvalid();
        }
        
    
    
});