Ext.onReady(function() {
	
	var baseURL = 'http://www.melrosehomes.co.uk';
	
	var form = new Ext.form.FormPanel({
		baseCls: 'x-plain',
		layout:'absolute',
		defaultType: 'textfield',
		items: [
			new Ext.form.FieldSet({
				title: 'Login',
				autoHeight: true,
				defaultType: 'textfield',
				items: [{
						fieldLabel: 'Username',
						id: 'firstID',
						name: 'first',
						width:190,
						value: ''
					}, {
						fieldLabel: 'Password',
						name: 'last',
						inputType: 'password',
						width:190,
						value: ''
					}]
		})]
	});

	var loginWindow = new Ext.Window({
		title: 'Melrose Homes - Login',
		width: 350,
		iconCls: 'windowLogo',
		height:170,
		minWidth: 350,
		minHeight: 170,
		closable: false,
		layout: 'fit',
		plain:true,
		bodyStyle:'padding:5px;',
		buttonAlign:'center',
		items: form,

		buttons: [{
			text: 'Login',
			handler: function(){
				form.getForm().submit({
					method:'POST',
					url: baseURL + '/cgi-bin/admin/app/login.pl',
					success:function(form, action){
						obj = Ext.util.JSON.decode(action.response.responseText);
						var url = obj.redirect;
						window.location = url;
					},
					failure:function(form, action){
						if(action.failureType == 'server'){
							obj = Ext.util.JSON.decode(action.response.responseText);
							Ext.Msg.alert('Error', obj.errors.reason);
						}
						else {
							Ext.Msg.alert('Error', 'Authentication server is unreachable');
						}
					}
				});
			}
		},{
			text: 'Cancel',
			handler: function(){
				window.location = baseURL + '/mpl/';			
			}
		}]
	});

	loginWindow.on('show', function() { var f = Ext.get('firstID'); f.focus.defer(100, f); });
	loginWindow.show();

	var nav = new Ext.KeyNav(form.getForm().getEl(), {
		'enter': function(e) {
			this.getForm().submit({
				method:'POST',
				url: baseURL + '/cgi-bin/admin/app/login.pl',
				success:function(form, action){
					obj = Ext.util.JSON.decode(action.response.responseText);
					var url = obj.redirect;
					window.location = url;
				},
				failure:function(form, action){
					if(action.failureType == 'server'){
						obj = Ext.util.JSON.decode(action.response.responseText);
						Ext.Msg.alert('Error', obj.errors.reason);
					}
					else {
						Ext.Msg.alert('Error', 'Authentication server is unreachable');
					}
				}
			});
		},
		'scope': form
	});
});
