Ext.onReady(function()
{
    var TDO = Framework.Setting.Translation; 
    var LoginServiceURL = Framework.Setting.Path.Root+'/index.php/mpath/services_Login';
    var LoginMask;
    var LoginGridWindowIsInPosition = false;
    var LoginDirectWindowIsInPosition = false;    
    var LoginRequiredWindow;
    var LoginJsonStore = new Ext.data.JsonStore(
                                                 {
                                                    root: 'Data',
                                                    url:  Framework.Setting.Path.Root+'/index.php/mpath/services_Login',
                                                    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 LoginGridHeaderRenderer(msg)
    {
        return '<span style="font-size: 11px; font-weight: bold;">'+msg+'</span>';
    }

    function LoginGridTypeRenderer(type)
    {
        return ((type == '1') ? '<img src="'+Framework.Setting.Path.Root+'/images/loginCustomer.png" />' : '<img src="'+Framework.Setting.Path.Root+'/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(TDO._IDF_LOGIN_WAIT);
                                                                                showLoadingMask();
                                                                                LoginService(LoginJsonStore.getAt(RowId).get('Username'), Password.getValue(), $F('setCookie'), SingleLoginSuccess, SingleLoginFailure);
                                                                           }
                                                                           // additional login is required
                                                                           else
                                                                           {
                                                                                LoginRequiredWindow = brodos.login.dialog(TDO, LoginServiceURL, LoginJsonStore.getAt(RowId).get('Username'), $F('setCookie'), 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(TDO._IDF_TYPE),       width: 35,  fixed: true, resizable: false, menuDisabled: true, sortable: false, renderer: LoginGridTypeRenderer, dataIndex: 'Type'     },
                                                            { name: 'System',   header: LoginGridHeaderRenderer(TDO._IDF_SYSTEM),     width: 200, fixed: true, resizable: false, menuDisabled: true, sortable: false, renderer: LoginGridRowRenderer,  dataIndex: 'System'   },
                                                            { name: 'Username', header: LoginGridHeaderRenderer(TDO._IDF_USER),       width: 160, fixed: true, resizable: false, menuDisabled: true, sortable: false, renderer: LoginGridRowRenderer,  dataIndex: 'Username' },
                                                            { name: 'Customer', header: LoginGridHeaderRenderer(TDO._IDF_CUSTOMERNO), width: 105, fixed: true, resizable: false, menuDisabled: true, sortable: false, renderer: LoginGridRowRenderer,  dataIndex: 'Customer' }
                                                          ],
                                                stripeRows: true,
                                                autoHeight: true,
                                                width: 504
                                              }
                                           );

        var LoginGridWindow = new Ext.Window(
                                             {
                                                title:       TDO._IDF_SELECT_LOGIN,
                                                closable:    true,
                                                width:       504,
                                                modal:       true,
                                                resizable:   false,
                                                draggable:   false,
                                                closeAction: 'hide',
                                                layout:      'fit',
                                                items:       [LoginGrid]
                                             }
                                            );
        
        function showLoginGridWindow()
        {
            LoginGridWindow.show();
            
            if (!LoginGridWindowIsInPosition)
            {
                LoginGridWindow.setPosition(LoginGridWindow.getPosition()[0], LoginGridWindow.getPosition()[1]-130);
                LoginGridWindowIsInPosition = true;
            }
        }
        
        if ($('LoginButton'))
        {
             var LoginButton = new Ext.Button({
                                                text:     TDO._IDF_LOGIN_BUTTON,
                                                renderTo: 'LoginButton',
                                                autoShow:  true,
                                                listeners: { 
                                                             'click': function () 
                                                                      { 
                                                                         if (Username.isValid() && Password.isValid())
                                                                         {
                                                                             Account(Username.getValue(), Password.getValue()); 
                                                                         }
                                                                      } 
                                                           }
                                              });
        }
        
        function Account(identifer, password)
        {
            if (identifer.length && password.length)
            {
                LoginJsonStore.removeAll();
                createLoadingMask(TDO._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(), $F('setCookie'), SingleLoginSuccess, SingleLoginFailure);
                }
                // Invalid login
                else
                {
                    hideLoadingMask();
                    Ext.get('LoginMessage').update(TDO._IDF_LOGIN_INVALID);
                }
            }
            else
            {
                hideLoadingMask();
                Ext.get('LoginMessage').update(TDO._IDF_LOGIN_ERROR);
            }
        }
        
        function LoginService(identifer, password, cookie, successCallback, failureCallback)
        {
            brodos.login.execute(LoginServiceURL, identifer, password, cookie, successCallback, failureCallback);
        }
        
        function SingleLoginSuccess(data)
        {
            if (data.responseText == '1')
            {
               $('LoginForm').submit();
            }
            else
            {
                LoginGridWindow.hide();
                Ext.get('LoginMessage').update(TDO._IDF_LOGIN_ERROR);
            }
        }
        
        function SingleLoginFailure()
        {
            LoginGridWindow.hide();
            hideLoadingMask();
            Ext.get('LoginMessage').update(TDO._IDF_LOGIN_ERROR);
        }
        
        function executeLoginWait()
        {
            createLoadingMask(TDO._IDF_LOGIN_WAIT);
            showLoadingMask();
            LoginRequiredWindow.hide();
        }

        function directLoginSuccess(data)
        {
            if (data.responseText == '1')
            {
                $('LoginForm').submit();
            }
            else
            {
                hideLoadingMask();
                LoginGridWindow.hide();
                LoginRequiredWindow.show();
                Ext.getCmp('idfSystemPassword').markInvalid();
            }
        }
          
        function directLoginFailure(data)
        {
            hideLoadingMask();
            LoginRequiredWindow.show();
            Ext.getCmp('idfSystemPassword').markInvalid();
        }
        
        
        
        // -------------------------------------------------------------------------------------------------------------------------------- //
        
        
        function catchEnterPressOnLoginTextField(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:      170,
                                                  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:      170,
                                                    listeners: { 
                                                                    'specialkey': catchEnterPressOnLoginTextField 
                                                               }
                                                    
                                                }
                                               );                          
        if (Username.getValue().length > 0)
        {
            Password.focus();
        }

        if (Username.getValue().length == 0)
        {
            Username.focus();
        }
});