/**
 * Login form panel used in login screen.
 *
 * @author Interface
 * @created 2009-10-28
 * @version 1.0
 * 
 * @param labels - customized instance of Ron.Properties
 *
 * @known_issues 
 *		- 
 *		
 */

Ext.namespace("Ron");

Ron.LoginForm = Ext.extend(Ext.FormPanel, {
	id:'login-form',
	// Constructor Defaults, can be overridden by user's config object
	initComponent : function() {
		
		var accountRecord = Ext.data.Record.create([
		   {name: 'ID'},
		   {name: 'Name'}
		]);
		
		var accountReader = new Ext.data.XmlReader({
	    	record: "Account",
	   		id: "ID",
	   		totalRecords: 'TotalRecords'
		}, accountRecord);
		
		var accountStore = new Ext.data.Store({
            reader: accountReader,
            url: custom_labels.HANDLER_URL,
            baseParams: {Action: window.lookup_codes.LOGIN_ACCOUNTID_PARAM_ACTION_VALUE, IsLoginPage: true},
            autoLoad: true,
		    remoteSort: true,
		    listeners: {
            	load: function(){
            		parseXMLResult(this.reader.xmlData);
            	}
            }
        });
        
		var loginErrorMessage = "";
		
		// Config object has already been applied to 'this' so properties can
		// be overriden here or new properties (e.g. items, tools, buttons)
		// can be added, eg:
		Ext.apply(this, {
			url : 'j_spring_security_check',
			standardSubmit: true,
			bodyStyle : 'padding:20px 14px 0',
			bodyBorder: false,
			keys: [{
				key: [Ext.EventObject.ENTER],
			    fn: this.submitLoginForm			    
	     	}],
			items : [{
				xtype: "box",
				id: 'login-form-msg-area',
				hidden: false,
				autoEl: {tag: 'div', href: '#', html: loginErrorMessage},
				cls: 'loginMessage'
			},{
				xtype : 'fieldset',
				id : 'login-form-fieldset',
				title : this.custom_labels.LoginFormPanel_loginInformation,
				bodyStyle : 'padding:10px 5px 0',
				labelWidth : 105,
				collapsible : false,
				width : 390,
				height: 120,
				items : [{
					fieldLabel : this.custom_labels.LoginFormPanel_username,
					name : 'UserName',
					id : 'UserName',
					xtype : 'textfield',
					maskRe: /[a-zA-Z0-9._\-@]/,
					vtype: 'loginusername',
					width : 200,
					hidden: false,
					allowBlank : false
				},{
					fieldLabel : this.custom_labels.LoginFormPanel_password,
					name : 'Password',
					id : 'Password',
					xtype : 'textfield',
					inputType: 'password',
					width : 200,
					autoCreate:{tag: "input", type: "password", autocomplete: "on"},
					vtype: 'passwordchecker',
					allowBlank: false
				},{
					fieldLabel: custom_labels.LoginFormPanel_AccountId,
					xtype: "combo",
					name: 'loginAccountID',
					hiddenName: 'AccountID',
					id: 'loginAccountID',
					width : 200,
					store: accountStore,
					displayField: 'Name',
        			valueField: 'ID',
        			triggerAction: 'all',
        			mode: 'local',
        			editable: false,
					allowBlank: false,
					resizable: true
				}]
			}],
			
			buttons : [{
				text: this.custom_labels.LoginFormPanel_loginButton,
				handler: this.submitLoginForm
			},{
				text: this.custom_labels.LoginFormPanel_clearButton,
				handler: function(){
					Ext.getCmp('login-form').getForm().reset();
				}
			}]
		});
		// Call parent (required)
		Ron.LoginForm.superclass.initComponent.apply(this, arguments);
		
		this.getForm().errorReader = new Ext.form.XmlErrorReader();
	},
	
	// Override other inherited methods
	onRender : function() {
        var accountid = '';
		var querystring = window.location.search.substring(0);
		if (querystring != "")
		{
		   var keyvalue = querystring.split("?")
		   if(keyvalue != "")
		   {
			   var splitkeyvalue = keyvalue[1].split("=");
			   accountid = splitkeyvalue[0].toLowerCase();
			   var accountno = splitkeyvalue[1];
		   }		   
		}
		if(accountid=="accountid" && accountno){			//if accountID passed as query string in URL hide combo box.
			Ext.getCmp('loginAccountID').hideLabel = true;
			Ext.getCmp('loginAccountID').hide();
		} else {
			Ext.getCmp('loginAccountID').show();
			Ext.getCmp('loginAccountID').hideLabel = false;
		}
		// Call parent (required)
		Ron.LoginForm.superclass.onRender.apply(this, arguments);
	},
	
	getAccountno: function(){
	    var accountid = '';
		var querystring = window.location.search.substring(0);
		if (querystring != "")
		{
		   var keyvalue = querystring.split("?")
		   if(keyvalue != "")
		   {
		   var splitkeyvalue = keyvalue[1].split("=");
		   accountid = splitkeyvalue[0].toLowerCase();
		   var accountno = splitkeyvalue[1];
		   }		   
		}
		if(accountid=="accountid")
		{
			return accountno;
		}
},
	
	submitLoginForm: function() {
		var loginForm = Ext.getCmp('login-form').getForm();
		var accountno = Ext.getCmp('login-form').getAccountno();
		hidAcctId = new Ext.form.Hidden({ id: 'AccountID', name: 'AccountID' });
		loginForm.add(hidAcctId);
		if(!Ext.getCmp('loginAccountID').isVisible()){
				Ext.getCmp('loginAccountID').setValue(accountno);
		}
		if (loginForm.isValid()){
			var requestParams = {};
			requestParams.onAction = 'LOGIN-ACTION';
			requestParams.Action = window.lookup_codes.LOGIN_PARAM_ACTION_VALUE;
			
			// submit floor form form
			loginForm.submit({
				url: custom_labels.HANDLER_URL,
				params: requestParams,
				success: function(form, action) {
					if(parseXMLResult(form.errorReader.xmlData)){
						var isAccountActive = Ext.DomQuery.selectValue('IsActive', form.errorReader.xmlData);
						if(isAccountActive == '1') {
							var isSuperAccount = Ext.DomQuery.selectValue('SuperAccount', form.errorReader.xmlData);
							if(isSuperAccount.toUpperCase() == 'TRUE'){
								document.location.href = custom_labels.ACCOUNTS_URL;
							} else {
								document.location.href = custom_labels.HOME_URL + '?AccountID=' + Ext.getCmp('loginAccountID').getValue();
							}
						} else {
							document.location.href = custom_labels.ACCOUNT_EXPIRED_PAGE_URL;
						}
					}
				}
			});
		}else {
		    Ext.Msg.alert('Error', custom_labels.validationFailure);
		    return false;
		}
	}
});

// register xtype to allow for lazy initialization
Ext.reg('loginform', Ron.LoginForm);

//Set focus to username field after window load
function setFieldFocus() {
	if(Ext.getCmp('UserName')) {
	  	Ext.getCmp('UserName').focus();
  	}
}

window.onload = setFieldFocus;

