/* exported beginAuthorization, authorizeGoogleSilently, popupGoogleAuthorization, authorizeBilling, handleAuthResult, handleReAuthResult, billingAuthorizationFailed */
/* exported logout */

var token_google;
var token_api;



function toLogin()
{
	showPage('login');
	
	var email = $('#email').val();
	
	if(email || email.length > 0)
		$('#password').focus();
	else
		$('#email').focus();
}

function login(e)
{
	e.preventDefault();
	
	var email = $('#email').val();
	var password = $('#password').val();
	
	//clear the error message
	$('#login-error-message').html('&nbsp;');
	
	//set processing
	$('#form-login')
		.removeClass('error')
		.addClass('processing');
	
	//attempt to validate
	api['auth'].create('local', { 'email': email, 'password': password }).done(function(creds)
	{
		if(!creds)
		{
			console.log('no credentials');
			return;
		}
		
		credentials = creds;
		token = credentials['token'];

		//store credentials locally
		localStorage['credentials']		= JSON.stringify(credentials);

		$('.user_name_first').html(creds['user']['name_first']);

		//store inside API
		api['opts']['token'] = credentials['token'];
		
		//make sure app page is visible
		$('#app').show();
		
		//reload router
		router.reload();
		
		//fade away the login screen
		$('#form-login').fadeOut();
	})
	.fail(function(xhr)
	{
		var msg = xhr.responseText;

		$('#login-error-message').html(msg);
		$('#form-login').addClass('error');
		$('#password').val('').focus();
	})
	.always(function()
	{
		$('#form-login').removeClass('processing');
	});
	
	return false;
}

function logout(e)
{
	console.log('logout');
	
	//clear the local session
	localStorage['credentials'] = null;
	
	//fade in the login screen
	showPage('login');
	
	$('.user_name_first').html('[User]');
	
	if(table_properties)
		table_properties.clear().draw();
	
	if(table_dashboard_properties)
		table_dashboard_properties.clear().draw();
	
	//TODO: clear data lists

	e.preventDefault();
	return false;
}