//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');
		
		if(!id_company)
			return;
		
		tables[id_company].draw();
	});
	
	$('#screen-sd').delegate('button.download-csv', 'click', function(e)
	{
		window.open('api/downloadCSV.php?id=' + $(this).data('id_company'));
	});
	
	setInterval(loadAllData, 60*1000);
}

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;
}