/* 
 * 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 CaptchaPanel=new Ext.Panel({
       border: false,
       renderTo: 'LoginCaptcha',
       hidden: true
    });
    
    var hiddenPanel=new Ext.Panel({
       border: false,
       renderTo: 'LoginCaptchaHidden',
       hidden: true
    });
    
    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 () 
                                                { 
                                                    var captchaResponse, captchaChallenge;
                                                     
                                                    if (Username.isValid() && Password.isValid())
                                                    {
                                                        if (Ext.get('captcha_response_field')!=null)
                                                        {
                                                            captchaResponse=Ext.get('captcha_response_field').dom.value;
                                                            captchaChallenge=Ext.DomQuery.selectNode('input[name=captcha_challenge_field]').value;
                                                        }
                                                                 
                                                        Account(Username.getValue(), Password.getValue(), captchaResponse, captchaChallenge); 
                                                             
                                                        Ext.get('LoginMessage').update('');
                                                    }
                                                }
                                            }
                                          });
    // Login Grid Interface (LGI)
    // ---------------------------------------------------------------------------------------------------------------------------------------- //
    
    var LoginServiceURL = contentcard.config.get('LoginAPI');
    var LoginMask;
    var LoginGridWindowIsInPosition = false;
    var LoginDirectWindowIsInPosition = false;    
    var LoginRequiredWindow;
    var LoginConnection=new Ext.data.Connection({
        timeout: 30000,
        url:  LoginServiceURL
    });
    
    var LoginJsonStore = new Ext.data.JsonStore(
                                                 {
                                                    root: '',
                                                    mode: 'local',
                                                    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(identifier, password, captchaResponseValue, captchaChallengeValue)
        {
            if (identifier.length && password.length)
            {
                LoginJsonStore.removeAll();
                createLoadingMask(contentcard.translation.get('_IDF_LOGIN_WAIT'));
                showLoadingMask();
               
                LoginConnection.request({
                    autoAbort: true,
                    params: {
                        Id: identifier,
                        Password: password,
                        Mode: 'List',
                        captcha_response_field: captchaResponseValue,
                        captcha_challenge_field: captchaChallengeValue
                    },
                    success: function (resp, opt)
                    {
                        var oData=Ext.decode(resp.responseText);
                       
                        var captcha_challenge=oData.captcha_challenge;
                        
                        LoginJsonStore.loadData(oData.Data);
                        
                        // check if we have valid logins
                        if (LoginJsonStore.getTotalCount() > 1)
                        {
                            hideLoadingMask();
                            // Multi-Login, so show selection
                            showLoginGridWindow();
                        }
                        else if (LoginJsonStore.getTotalCount()===1)
                        {
                            // single-Login, so do Login
                            LoginService(LoginJsonStore.getAt(0).get('Username'), Password.getValue(), SingleLoginSuccess, SingleLoginFailure);
                        }
                        else
                        {
                            hideLoadingMask();
                            // set focus to username field
                            //Username.focus();
                            
                            // no valid logins, so check if we have to show captcha
                            switch (captcha_challenge)
                            {
                                case "requestFailed":
                                case "noChallenge":
                                    // show invalid login message
                                    Ext.get('LoginMessage').update(contentcard.translation.get('_IDF_LOGIN_INVALID'));
                                    // empty captcha panel
                                    CaptchaPanel.getEl().update('');
                                    Ext.get('login_box').removeClass('login_captcha');
                                    Ext.get('login_box').addClass('login');                                   
                                   
                                    break;
                                default:
                                    // show captcha, if provided
                                    if (captcha_challenge.length>0)
                                    {
                                        showCaptcha(captcha_challenge);
                                    }
                                    else
                                    {
                                       Ext.get('LoginMessage').update(contentcard.translation.get('_IDF_LOGIN_INVALID'));
                                    }
                                    break;
                            }
                        }
                    },
                    failure: function (resp, opt)
                    {
                        hideLoadingMask();
                        Ext.get('LoginMessage').update(contentcard.translation.get('_IDF_LOGIN_ERROR'));
                    }
                });
                
                
            }
        }
        
        /*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();
                    
                    options.params.captcha_challenge_field
                    
                    Username.markInvalid();
                    Password.markInvalid();
                    
                    // no valid logins, so check if we have to show captcha
                    switch (captcha_challenge)
                    {
                        case "requestFailed":
                        case "noChallenge":
                            // show invalid login message
                            Ext.get('LoginMessage').update(contentcard.translation.get('_IDF_LOGIN_INVALID'));
                            // empty captcha panel
                            CaptchaPanel.getEl().update('');
                            break;
                        default:
                            // show captcha, if provided
                            if (captcha_challenge.length>0)
                            {
                                showCaptcha(captcha_challenge);
                            }
                            else
                            {
                                 Ext.get('LoginMessage').update(contentcard.translation.get('_IDF_LOGIN_INVALID'));
                            }
                            break;
                    }
                }
            }
            else
            {
                hideLoadingMask();
                Ext.get('LoginMessage').update(contentcard.translation.get('_IDF_LOGIN_ERROR'));
            }
        }*/
        
        function LoginService(identifer, password, successCallback, failureCallback)
        {
            contentcard.login.execute(LoginServiceURL, identifer, password, 0, 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();
        }
        
        function catchEnterCaptchaField(evt)
        {
            if (!evt)
                evt=window.event;
            
            if (evt.keyCode==13)
            {
                LoginButton.fireEvent('click');
            }
        }
        
        /**
         * shows captcha from captcha-service in container for error messages
         * @param string sCaptcha - html-code captcha
         * @return void 
         */
        function showCaptcha(sCaptcha)
        {
            hiddenPanel.getEl().update(sCaptcha);

            Ext.get('login_box').removeClass('login');
            Ext.get('login_box').addClass('login_captcha');
            
            var node = Ext.query('input[name=captcha_challenge_field]', hiddenPanel.getEl().dom);
            var challenge = node[0].value;

            var node = Ext.query('img[id=captcha_image]', hiddenPanel.getEl().dom);
            var image = node[0].src;
            
            var html = '<style>.captchatable {\n	border: 0px !important;\n}\n\n.captchatable .captcha_image_cell {\n padding: 0px 0px 2px 0px !important;\}\n\n.captchatable .captcha_response_field {\n border: 1px solid black !important;\n margin: 2px -1px 0px 0px !important;\n}\n.captchatable .captcha_input_area_text {\n margin-left: 0px !important;\n font-family: Tahoma,Verdana, Helvetica, sans-serif !important;\n font-size: 11px !important;\n}\n<\/style>\n\n<input name=\"captcha_challenge_field\" type=\"hidden\" value=\"'+challenge+'\">\n<table id=\"captchatable\" class=\"captchatable\">\n    <tr><td class=\"captcha_image_cell\">\n        <img id=\"captcha_image\" class=\"captcha_image\" width=\"300\" height=\"57\" alt=\"\" src=\"'+image+'\">\n        <\/td><\/tr>\n    <tr>\n        <td>\n             <div class=\"captcha_input_area\">\n                <label for=\"captcha_response_field\" id=\"captcha_instructions\" class=\"captcha_input_area_text\"><font color=\"red\">Bitte geben Sie die beiden Worte ein<\/font><\/label><br>\n                <input name=\"captcha_response_field\" id=\"captcha_response_field\" class=\"captcha_response_field\" type=\"text\" autocomplete=\"off\" style=\"width: 302px;\"\/>\n            <\/div>\n        <\/td>\n    <\/tr>\n<\/table>\n\r\n';
            
            CaptchaPanel.getEl().update(html);
            CaptchaPanel.show();
            
            if (Ext.get('captcha_response_field')!=null)
            {
                Ext.get('captcha_response_field').addClass("x-form-text x-form-text-field");
                Ext.get('captcha_response_field').dom.onkeydown=catchEnterCaptchaField.createDelegate(null, window.event);
            }
               
        }
        
    
    
});
