/**
 * app.login 
 * 
 */

Ext.require([
    'Ext.direct.*',
    'Ext.form.*',
    'Ext.tip.QuickTipManager'
]);

Ext.onReady(function(){    

    Ext.app.REMOTING_API.enableBuffer = 100;
    Ext.direct.Manager.addProvider(Ext.app.REMOTING_API);
    
    // provide feedback for any errors
    Ext.tip.QuickTipManager.init();
	
	var Cookies = Ext.util.Cookies;
	app.lastKnownUser = Cookies.get('icsLastUser') || '';

    var loginForm = Ext.create('Ext.form.Panel', {
		 id: 'applogin'
		,renderTo: Ext.get('loginWrap')
        ,autoHeight: true
        //,width: 400
        ,border: false
        ,bodyPadding: 3
		,api: {
			submit: authenticateService.handlelogin
        }
        ,paramOrder: ['username', 'password']
        ,defaults: {
            anchor: '100%'
        }
        ,doLogin: function(){

            var  f = this
                ,v = f.getForm().getValues()
                ,o
                ,b = Ext.get('positioner')
                ,goBtn = Ext.getCmp('goBtn');
              //  ,msk = new Ext.LoadMask(Ext.getBody(), {msg: app.i18n.authenticatingText });
                
                b.mask(app.i18n.authenticatingText);

                goBtn.formBind = false;
                goBtn.disable();
                

                var autoDelay = new Ext.util.DelayedTask(function() {       
                    if (f.getForm().isValid()) {
                        
                        f.getForm().submit({
                            params: {
                                sessionid: app.sessionid
                            }
                            ,success: function(form,action){ 
                                o = f.getForm().getFieldValues();
                                saveCookies(o);
                                window.location.href = app.url; 
                                
                            }
                            ,failure: function(form,action){ 

                                if(action.result.success === true){
                                   window.location.href = app.url; 
                                } else {
                                    var msg = action && action.result.errormessage ? action.result.errormessage : 'Unknown Error. Please try again.'
                                    msg = app.i18n.loginFailedText + ' ' + msg;
    
                                    Ext.ux.Toast.msg(app.i18n.msgWarning, msg, '', '');
                                    Ext.get("msg-ct").update(msg).slideIn('t');
                                    goBtn.formBind = true;
                                    goBtn.enable();
                                    b.unmask();
                                }    
                             }  
                          });                 
                      }
                      
   
                    });
                    autoDelay.delay(700);
                            
        }   
        
        ,listeners: {
            afterRender: function(thisForm, options){
                this.keyNav = Ext.create('Ext.util.KeyNav', this.el, {                    
                    enter: this.doLogin,
                    scope: this
                });
            }
        }
        ,items: [{
                 xtype: 'fieldcontainer'
                ,id: 'login-field-container'
				,combineErrors: true
                ,msgTarget : 'side'
                ,layout: 'hbox'
                ,defaults: {
                     flex: 1
                    ,hideLabel: true
					,fontSize: 25
                }
                ,items: [{
                         xtype: 'textfield'
						,id: 'loginUsername'
                        ,name      : 'loginUsername'
						,emptyText: app.i18n.userNameText
                        ,margin: '0 5 0 0'
                        ,flex: 0.38
						,allowBlank: false
                    }
                    ,{
                         xtype     : 'textfield'
						,id: 'loginPassword' 
                        ,name      : 'loginPassword'
                        ,allowBlank: false
						,inputType: 'password'
						//,style: 'font-size: 20px;width: 215px;'
						,flex: 0.38
						,emptyText: app.i18n.passwordText
                    }
					,{
                         xtype     : 'button'
                        ,id      : 'goBtn'
                        ,text: app.i18n.signinText
						,flex: 0.24
						,style: 'margin-left: 15px; font-size: 20px;'
						//,cls: 'login-btn'
                        ,handler: function() {
                            var f = Ext.getCmp('applogin');
		                        if (f.getForm().isValid()) { f.doLogin(); }
		                }
                    }]
            }]
    });
    
	
    // rpc call
    // TestAction.doEcho('sample');
	
  function getTimeOffset(){
    var date = new Date();
      date.setFullYear(date.getFullYear() + 1);
    return ((new Date().getTimezoneOffset() / 60) * -1) * 1000 * 60 * 60;
  }

  function saveCookies(o){
    var date = new Date();
    date.setFullYear(date.getFullYear() + 1);
    Cookies.set('icsLastUser', o.loginUsername, date);
  }

  var cnt = Ext.getCmp('login-field-container');
  
  if (app.lastKnownUser){
     cnt.items.get('loginUsername').setValue(app.lastKnownUser);
     cnt.items.get('loginPassword').focus(true, true);
  } else {
     cnt.items.get('loginUsername').focus(true, true);
  }
	
});


