Ext.namespace("LP.forms");



LP.forms.LoginForm = Ext.extend(Ext.Panel, {



	// TODO: check for existing element ids for user/pass. if existing, then
	// bind the textfields to them. otherwise create new
	msgComponentId : null,



	setMessage : function(s) {
		Ext.getCmp(this.msgComponentId).setText(s);
	},



	onRender : function(a, b) {
		LP.forms.LoginForm.superclass.onRender.call(this, a, b);
		this.map = new Ext.KeyMap(this.id, [{
			key : [10, 13],
			scope : this,
			fn : this.doLoginForm
		}]);
	},



	initComponent : function() {

		Ext.apply(this, {
			width : 400,
			height : 250,
			border : true,
			labelAlign : 'top',
			bodyStyle : 'padding: 10px 25px 10px 25px;',
			frame : true,
			layout: 'form',
			monitorValid : true,
			defaultType : 'textfield',
			defaultButton: 'username',
			items : [{
				id : 'username',
				el : 'username',
				anchor : '100%',
				allowBlank : false,
				fieldLabel : "User Name"
			}, {
				id : 'password',
				el : 'password',
				fieldLabel : 'Password',
				anchor : '100%',
				allowBlank : false
			}, {
				xtype : 'label',
				id : this.msgComponentId = Ext.id(),
				style : 'height: 20px;display:block; color:red; text-align:center; padding:2px;'
			}],
			buttons : [{
				text : 'Login',
				type : 'submit',
				scope : this,
				handler : function(button, event) {
					this.doLoginForm();
				}
			}]
		});
		LP.forms.LoginForm.superclass.initComponent.call(this);
	},



	doLoginForm : function() {

		Ext.Ajax.request({

			method : 'POST',
			params : {
				a : LP.Application.SERVICE_ACTIONS.LOGIN,
				username: Ext.getCmp('username').getValue(),
				password: Ext.getCmp('password').getValue()
			},
			url : LP.Application.SERVICE_URL,
			waitTitle : 'Connecting',
			waitMsg : 'Logging in ...',
			scope : this,

			success : function (response, action) {

				var responseObject;
				try {
					responseObject = Ext.util.JSON.decode(response.responseText);
				} catch (err) {
					this.setMessage("Unrecognized response.");
				}

				if (responseObject && responseObject.sessionID) {
					LP.app.setSessionID(responseObject.sessionID);
					if (this.success) {
						this.success();
					}
				} else {
					if (responseObject && responseObject.msg) {
						this.setMessage(responseObject.msg);
					} else {
						this.setMessage("Server failures.");
					}
				}
			},

			failure : function(response, action) {

				var responseObject;
				try {
					responseObject = Ext.util.JSON.decode(response.responseText);
				} catch (err) {
					this.setMessage("Unrecognized response.");
				}

				if (responseObject && responseObject.msg) {
					this.setMessage(responseObject.msg);
				} else {
					this.setMessage("Server failure.");
				}
			}

		});

	}



});
Ext.reg('LP.forms.LoginForm', LP.forms.LoginForm);
