var editors = [];
var rows = {};


function initializeRoutes()
{
	router('/login',		routes['login']);
	router('/logout',		routes['logout']);
	router('/sd',			routes['sd']);
	
	router('/',				routes['login']);
	router('*',				routes['login']);
}


//add a 'firstLoad' setup function into the route's middleware chain


var routes =
{
	login: function()
	{
		showPage('login');
	},
	
	logout: function()
	{
		$.post('api/logout.php');

		router('/');
	},
	
	sd: function()
	{
		showPage('sd');
		
		loadAllData();
	}
};

function showPage(page)
{
	console.log('show page', page);
	
	var $page_old = $('.screen.active');
	var $page_new = $('#screen-' + page);
	
	//do nothing if we are already on the page
	if($page_old.is($page_new))
		return;
	
	$('body').attr('class', 'screen-' + page);
	
	
	//put new page on top of old
	$page_new.insertAfter('.screen.active');

	//slide it to the right while crossfading
	$page_old
		.one('animationend', function(event) //jshint ignore:line, unused
		{
			$(this).hide();
		}) //TODO: add detect webkitanimationend or animationend
		.removeClass('active');

	//slide from left while crossfading
	$page_new
		.show()
		.off('animationend')
		.addClass('active')
		.focus();  //this needs to be used in conjunction with a "tabindex" field on the html object to maintain keyboard focus
}


function loadAllData()
{
	console.log('requesting data');
	
	$.get('api/getRows.php', 'json')
	.done(function(companies)
	{
		console.log('received data');
		
		//go through each company and add a tab if one isn't present
		
		if(!companies.length)
			return;
		
		for(var c = 0; c < companies.length; c++)
		{
			var company = companies[c];
			var id_company = company['id_company'];
			
			
			if(company['file_rows'])
				for(var r = 0; r < company['file_rows'].length; r++)
				{
					var id_file_row = company['file_rows'][r]['id_file_row'];
					rows[id_file_row] = company['file_rows'][r];
				}
			
			
			drivers_by_company[id_company] = {}
			
			for(var i = 0; company['drivers'] && i < company['drivers'].length; i++)
			{
				var driver = company['drivers'][i];
				var id_driver = driver['id_driver'];
				
				drivers_by_company[id_company][id_driver] = driver;
			}

			
			//if the company's tab doesn't exist, create it
			if(!tables[id_company])
			{
				//add tab
				$('<li><a data-toggle="tab" href="#table-' + id_company + '-container">' + company['name'] + '</a></li>')
					.data('id_company', id_company)
					.insertBefore('#audit-tab-parent');
				
				//add table
				$('<div id="table-' + id_company + '-container" class="tab-pane fade in">'
					+ '<table id="table-' + id_company + '" class="table table-striped editable" width="100%"></table>'
					+ '<button class="download-csv" data-id_company="' + id_company + '">Download CSV</button>'
				+ '</div>')
				.appendTo('#screen-sd .tab-content');
				
				$('<h1>' + company['name'] + '</h1>'
				+ '<table id="table-updates-' + id_company + '" class="table table-striped editable" width="100%"></table>')
					.appendTo('#audit-content');

				//create the datatable
				tables[id_company] = createTable(id_company, '#screen-sd #table-' + id_company);
				table_updates[id_company] = createUpdatesTable(id_company, '#screen-sd #table-updates-' + id_company);
			}
			else
			{
				tables[id_company].clear();
				table_updates[id_company].clear();
			}
			
			//load the data into the data
			tables[id_company].rows.add(company['file_rows']).draw();
			table_updates[id_company].rows.add(company['row_updates']).draw();
		}
		
		if($('#screen-sd ul.nav-tabs > li.active').length === 0)
			$('#screen-sd ul.nav-tabs > li:eq(0) a').click();
	})
	.fail(function(err, xhr, text)
	{
		console.error(err['responseText']);
	});
}

function loadCompanies()
{
	$.post('api/getCompanies.php')
	.done(function(response)
	{
		
	})
	.fail(function(err, xhr, text)
	{
		console.error(err.responseText);
	});
}

function createTable(id_company, table_dom)
{
	var table = $(table_dom).DataTable(
	{
		'data': [],
		'order': [[0, 'row_number']],
		'columns':
		[
			{ 'title': 'Division', 'data': 'division', 'defaultContent': '', 'className': 'division' },
			{ 'title': 'Consignee', 'data': 'consignee', 'defaultContent': '', 'className': 'consignee' },
			{ 'title': 'Called&nbsp;In', 'data': 'date_called_in', 'defaultContent': '', 'className': 'date_called_in' },
			{ 'title': 'Dispatch&nbsp;#', 'data': 'dispatch_number', 'defaultContent': '', 'className': 'dispatch_number' },
			{ 'title': 'Shipper', 'data': 'shipper', 'defaultContent': '', 'className': 'shipper' },
			{ 'title': 'Ready', 'data': 'date_ready', 'defaultContent': '', 'className': 'date_ready' },
			
			{ 'title': 'Driver', 'data': 'id_driver', 'defaultContent': '', 'className': 'id_driver',
				'render': function(data, type, row)
				{
					var id_driver = row['id_driver'];
					
					if(!id_driver)
						return '';
					
					return drivers_by_company[id_company][id_driver]['name'];
				}
			},
			{ 'title': 'Trailer', 'data': 'trailer', 'defaultContent': '', 'className': 'trailer' },

			{ 'title': 'Address&nbsp;1', 'data': 'address_1', 'address_1': '', 'className': 'address_1' },
			{ 'title': 'Address&nbsp;2', 'data': 'address_2', 'address_2': '', 'className': 'address_2' },
			{ 'title': 'City', 'data': 'city', 'defaultContent': '', 'className': 'city' },
			{ 'title': 'State', 'data': 'state', 'defaultContent': '', 'className': 'state' },
			{ 'title': 'Zip', 'data': 'zip', 'defaultContent': '', 'className': 'zip' },
			{ 'title': 'Phone', 'data': 'phone', 'defaultContent': '', 'className': 'phone' },
			
			{ 'title': 'Ready&nbsp;Time', 'data': 'time_ready', 'defaultContent': '', 'className': 'time_ready' },
			{ 'title': 'Close&nbsp;Time', 'data': 'time_close', 'defaultContent': '', 'className': 'time_close' },
			
			{ 'title': 'Authorization&nbsp;#', 'data': 'dispatch_reference', 'defaultContent': '', 'className': 'dispatch_reference' },

			{ 'title': 'Ctns', 'data': 'ctns', 'defaultContent': '', 'className': 'ctns' },
			{ 'title': 'Weight', 'data': 'weight', 'defaultContent': '', 'className': 'weight' },
			{ 'title': 'Cube', 'data': 'cube', 'defaultContent': '', 'className': 'cube' },
			
			{ 'title': 'Pickup&nbsp;Time', 'data': 'time_pickup', 'defaultContent': '&nbsp;', 'className': 'time_pickup' },
			{ 'title': 'Depart&nbsp;Time', 'data': 'time_depart', 'defaultContent': '&nbsp;', 'className': 'time_depart' },
			{ 'title': 'BOL&nbsp;Delivered', 'data': 'bol_delivered', 'defaultContent': '&nbsp;', 'className': 'bol_delivered' },
			{ 'title': 'Acknowledged', 'data': 'date_processed', 'defaultContent': '&nbsp;', 'className': 'date_processed' },
			{ 'title': '', 'data': 'date_canceled', 'defaultContent': '&nbsp;', 'className': 'date_canceled',
				'render': function(data, type, row)
				{
					//if the row is already completed, then don't show any buttons
					if(row.time_pickup && row.time_depart && row.bol_delivered)
						return '';
					
					//if it's been canceled, show the restore button
					if(row.date_canceled)
						return '<button class="restore"><img src="media/undo-variant.png"/></button>';
					
					//show the cancel button
					return '<button class="cancel"><img src="media/close.png"/></button>';
				}
			}
		],
		'language':
		{
			'search': '',
			'searchPlaceholder': "Search Active"
		},
		'deferRender': true,
		'lengthChange': false,
		'scrollX': true,
		'fixedColumns':
		{
			'leftColumns': 0,
			'rightColumns': 5
		},
		'pageLength': 200,
/*		'buttons': [{
			text: 'Completed',
			action: function(e, dt, node, config)
			{
				$(e.currentTarget).toggleClass('checked');
				
				if($(e.currentTarget).hasClass('checked'))
				{
					
				}
				
				dt.draw();
			}
		}],
		'dom': 'Bfrtip'
*/
	});
	
	
	var driver_options = [
	{
		"value": "",
		"label": "None"
	}];
	
	
	for(var id_driver in drivers_by_company[id_company])
	{
		var driver = drivers_by_company[id_company][id_driver];

		driver_options.push(
		{
			"value": id_driver,
			"label": driver.name
		});
	}
	
	
	var editor = new $.fn.dataTable.Editor(
	{
		idSrc: 'id_file_row',
		table: table_dom,
		fields:
		[{
			label: "Pickup Time:",
			name: "time_pickup",
			type: "datetime",
			format: 'MM/DD/YYYY hh:mm A'
		},
		{
			label: "Depart Time:",
			name: "time_depart",
			type: "datetime",
			format: 'MM/DD/YYYY hh:mm A'
		},
		{
			label: "BOL Delivered:",
			name: "bol_delivered",
			type: "datetime",
			format: 'MM/DD/YYYY hh:mm A'
		},
		{
			label: "Trailer:",
			name: "trailer",
			type: "text"
		},
		{
			label: "Driver:",
			name: "id_driver",
			type: "select",
			options: driver_options
		}],
		ajax: function(method, url, d, success, error)
		{
			if(d['action'] === 'edit')
			{
				//just get the first row
				var id_file_row;
					for(id_file_row in d['data']);
					
				var row_partial = d['data'][id_file_row];
				
				
				var properties_auditable = ['time_pickup', 'time_depart', 'bol_delivered'];
				var is_auditable = false;

				
				//go thru all the properties on the object
				for(var property in row_partial)
				{
					var value = row_partial[property];
					
					//update our master record
					rows[id_file_row][property] = value;
					
					//check if this is an auditable property
					if(properties_auditable.indexOf(property) !== -1)
						is_auditable = true;
				}

				
				if(is_auditable)
				{
					//send the update up to the server thru api
					$.post('api/createRowUpdate.php?id_file_row=' + id_file_row, row_partial)
						.done(function(response)
						{
							console.log(response);
							
							//report to the datatable a full updated row
							success({ "data": [ rows[id_file_row] ] });
						})
						.fail(function(err, xhr, text)
						{
							console.log(err['responseText']);
							
							//TODO: handle error
						});
				}
				else
				{
					$.post('api/updateRowImmediate.php?id_file_row=' + id_file_row, row_partial)
						.done(function(response)
						{
							console.log(response);
							
							//report to the datatable a full updated row
							success({ "data": [ rows[id_file_row] ] });
						})
						.fail(function(err, xhr, text)
						{
							console.log(err['responseText']);
						});
				}
			}
		}
	});
	
	
	
	//attach the editor
	$(table_dom).on('click', 'td.time_pickup', function(e) {
		editor.bubble(this, 'time_pickup');
	});

	$(table_dom).on('click', 'td.time_depart', function(e) {
		editor.bubble(this, 'time_depart');
	});

	$(table_dom).on('click', 'td.bol_delivered', function(e) {
		editor.bubble(this, 'bol_delivered');
	});
	
	$(table_dom).on('click', 'td.id_driver, td.trailer', function(e) {
		editor.bubble(this, ['trailer', 'id_driver']);
	});
	
	
	$(table_dom).on('click', 'td.date_canceled button.cancel', function(e)
	{
		var row = table.row($(this).closest('tr')).data();
		var id_file_row = row.id_file_row;
		
		if(confirm('Are you sure you want to cancel that row?'))
		{
			$.post('api/updateRowImmediate.php?id_file_row=' + id_file_row, { date_canceled: 1 })
				.done(function(response)
				{
					row.date_canceled = new Date();
					
					table.rows().invalidate('data').draw(false);
				})
				.fail(function(err, xhr, text)
				{
					console.log(err['responseText']);
				});
		}
	});
	
	$(table_dom).on('click', 'td.date_canceled button.restore', function(e)
	{
		var row = table.row($(this).closest('tr')).data();
		var id_file_row = row.id_file_row;
		
		if(confirm('Are you sure you want to restore that canceled row?'))
		{
			$.post('api/updateRowImmediate.php?id_file_row=' + id_file_row, { date_canceled: 0 })
				.done(function(response)
				{
					row.date_canceled = null;
					
					table.rows().invalidate('data').draw(false);
				})
				.fail(function(err, xhr, text)
				{
					console.log(err['responseText']);
				});
		}
	});
	
	/*
	$(table_dom).on('click', 'td.time_pickup, td.time_depart, td.bol_delivered', function(e) {
		editor.bubble(this, [ 'time_pickup', 'time_depart', 'bol_delivered' ]);
	});
	*/
	
	return table;
}


function createUpdatesTable(id_company, table_dom)
{
	var table = $(table_dom).DataTable(
	{
		'data': [],
		'order': [[0, 'date_modified']],
		'columns':
		[
			{ 'title': 'Date', 'data': 'date_modified', 'defaultContent': '&nbsp;', 'className': 'date_modified' },
			{ 'title': 'User', 'data': 'user_name', 'defaultContent': '&nbsp;', 'className': 'user_name' },
			
			{ 'title': 'Dispatch&nbsp;#', 'data': 'dispatch_number', 'defaultContent': '', 'className': 'dispatch_number' },
			{ 'title': 'Authorization&nbsp;#', 'data': 'dispatch_reference', 'defaultContent': '', 'className': 'dispatch_reference' },
			
			{ 'title': 'Pickup&nbsp;Time', 'data': 'time_pickup', 'defaultContent': '&nbsp;', 'className': 'time_pickup' },
			{ 'title': 'Depart&nbsp;Time', 'data': 'time_depart', 'defaultContent': '&nbsp;', 'className': 'time_depart' },
			{ 'title': 'BOL&nbsp;Delivered', 'data': 'bol_delivered', 'defaultContent': '&nbsp;', 'className': 'bol_delivered' }
		],
		'language':
		{
			'search': '',
			'searchPlaceholder': "Search Updates"
		},
		'deferRender': true,
		'lengthChange': false
	});
	
	return table;
}