//for closure compiler to ensure it gets exported
window['loadApp'] = loadApp;

var router = window['router'];

var user;



function loadApp()
{
	initializeRoutes();

	
	if(!user)
		router('/');
	else
		router.reload();

	//login and logout
	$('form.form-signin').submit(login);
	
	//when a bootstrap tab is shown, then trigger a redraw of its table
	$('#screen-sd').delegate('a[data-toggle="tab"]', 'shown.bs.tab', function(e)
	{
		var id_company = $(this).closest('li').data('id_company');
		
		tables[id_company].draw();
	});
}

function login(e)
{
	e.preventDefault();
	
	$('#login-error').text(null);
	
	
	$.post('api/login.php',
	{
		'email': $('#email').val(),
		'password': $('#password').val()
	})
	.done(function(response)
	{
		user = response;
		$('.user_name').text(user['name']);
		
		router('/sd');
	})
	.fail(function(err, xhr, text)
	{
		console.error(err.responseText);
		
		$('#login-error').text(err.responseText);
	});
	
	return false;
}