Ext.define('TradePortal.controller.Login', {
	extend : 'Ext.app.Controller',

	stores : [ 'Config', 'Register', 'Login', 'createCart', 'isPriceBookEnabled' ],

	views : [ 'login.Panel', 'login.FormPanel', 'login.RegisterPanel' ],

	models : [ 'Config', 'Valid', 'Login', 'Session', 'isPriceBookEnabled' ],

	init : function() {
		if (typeof console !== "undefined") {
			console.log('Initialized Login!');
		}

		this.control({
			'viewport > panel' : {
				render : this.onPanelRendered
			},
			'#login_ok' : {
				click : this.onLogin
			},
			'#Username' : {
				specialkey : this.onEnterLogin
			},
			'#Password' : {
				specialkey : this.onEnterLogin
			},
			'#login_register' : {
				click : this.onRegister
			},
			'#register_ok' : {
				click : this.onConfirmRegister
			},
			'#register_cancel' : {
				click : this.onCancelRegister
			}
		});
	},
	onPanelRendered : function() {
		if (typeof console !== "undefined") {
			console.log('Login panel was rendered');
		}
	},
	onLogin : function() {
		Ext.getCmp('viewport').setLoading('Loading...');
		Ext.getStore('Login').load({
			params : {
				userid : Ext.getCmp('Username').getValue(),
				password : Ext.getCmp('Password').getValue()
			}
		});
	},
	onEnterLogin : function(f, e) {
		if (e.getKey() == e.ENTER) {
			this.onLogin();
		}
	},
	onRegister : function() {
		Ext.getCmp('login_form').hide();
		Ext.getCmp('register_form').show();
	},
	onConfirmRegister : function() {
		if (Ext.getCmp('Register_Account').getValue() != '' && Ext.getCmp('Register_Date').getValue() != '' && Ext.getCmp('Register_Statement').getValue() != '' && Ext.getCmp('Register_Email').getValue() != '' && Ext.getCmp('Register_Firstname').getValue() != '' && Ext.getCmp('Register_Username').getValue() != '' && Ext.getCmp('Register_Password').getValue() != '' && Ext.getCmp('Confirm_Password').getValue() != '' && Ext.getCmp('Confirm_Password').getValue() == Ext.getCmp('Register_Password').getValue() && !isNaN(parseInt(Ext.getCmp('Register_Account').getValue()))){
			Ext.getCmp('viewport').setLoading('Loading...');
			Ext.getStore('Register').load({
				params : {
					tpa : 'tportal',
					companyID : Ext.getStore('Config').data.last().data.company_id,
					customerID : Ext.getCmp('Register_Account').getValue(),
					statementDate : Ext.getCmp('Register_Date').getValue(),
					statementReference : Ext.getCmp('Register_Statement').getValue(),
					emailAddress : Ext.getCmp('Register_Email').getValue(),
					nameFirst : Ext.getCmp('Register_Firstname').getValue(),
					nameLast : Ext.getCmp('Register_Lastname').getValue(),
					userName : Ext.getCmp('Register_Username').getValue(),
					password : Ext.getCmp('Register_Password').getValue()
				}
			});
		}
		else{
			Ext.Msg.alert('Alert','All fields are mandatory.',Ext.emptyFn);
		}
	},
	onCancelRegister : function() {
		Ext.getCmp('register_form').down('form').getForm().reset();
		Ext.getCmp('register_form').hide();
		Ext.getCmp('login_form').show();
	}
});
