$(function(){
	$('#loading').ajaxStart(function(){
		$(this).show('fast');
	}).ajaxStop(function(){
		$(this).hide('fast');
	});
	
	//Instantiate APE Client
	var client = new APE.Client();

	//Load APE Core
	client.load();
	
	//Intercept 'load' event. This event is fired when the Core is loaded and ready to connect to APE Server
	client.addEvent('load', function() {
		//We're ready to start chatting, display the username form
		$('#name_form').show('fast');
	});
	
	client.addEvent('ready', function(){
		console.log('Client connected');
		console.log('joining channel'+client._uname);
		client.core.join(client._uname);
	});
	
	$('#name_form').submit(function(e){
		e.preventDefault();
		$.post('/process.php', $(this).serialize(), function(data){
			if(data != 'fail'){
				$('#username').text(data.username_display).show('slow');
				//$(this).hide('slow');
				
				//Call core start function to connect to APE Server, user the uniqid we got back as the name
			    client.core.start();
				client._uname = data.username_internal;
			} else {
				$('#username').text('An error occured').show('slow').delay(1000).hide('slow');
			}
		}, 'json');
	})
});