Ext.onReady(function() {
	var validate = function() {
		var user = Ext.get('username');
		var pwd = Ext.get('password');
		
		if (!user.getValue()) {
			Ext.Msg.alert('Error', '<b>'+localeEmptyUser+'</b>');
			return;
		}
		
		if (!pwd.getValue()) {
			Ext.Msg.alert('Error', '<b>'+localeEmptyPass+'</b>');
			return;
		}
		
		Ext.get('loading').show();
		
		var conn = new Ext.data.Connection();
		conn.request({
			url: '/beta/login/',
			method: 'POST',
			params: {
				username: user.getValue(),
				password: pwd.getValue(),
				language: Ext.get('language-select').dom.value
			},
			success: function(response) {
				Ext.get('loading').hide();
				try {
					var obj = Ext.util.JSON.decode(response.responseText);
					if (obj.success) {
						Ext.get('all').hide();
						Ext.get('footer').hide();
						var redirect = '/beta/mail/';
						window.location = redirect;
					}
					else {
						showInvalid(obj.message);
					}
				} 
				catch (e) {
					showInvalid();
				}
			},
			failure: function(response) {
				Ext.get('loading').hide();
				showInvalid();
			}
		});
	}
	
	var showInvalid = function(msg) {
		if (!msg) {
			var msg = localeUnknown+' '+localeError;
		}
		Ext.FancyMsg.msg(localeAuthInvalid, msg);
	}
	
	Ext.get('username').focus(false, 500);
	Ext.get('login').addListener('click', validate);
	
	//Create event for key enter
	var nav = new Ext.KeyNav(document, {
		'enter': validate,
		scope: this
	});
});
