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

var router = window['router'];

var user;

var tables = [];
var table_updates = [];

var drivers_by_company = {};



function loadApp()
{
	initializeRoutes();

	
	$.fn.dataTable.ext.search.push(
	function(settings, search_data, index, row, search_counter)
	{
		if($("#show-completed").prop('checked'))
			return true;
		
		return (!row.time_pickup || !row.time_depart || !row.bol_delivered) && !row.date_canceled;
	});
	
	$("#show-completed").change(function()
	{
		//redraw all tables
		for(var i in tables)
			tables[i].draw();
	});


	//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);
	
	
	if(!user)
		router('/');
	else
		router.reload();
}

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