var C_FILTER_ALL_ACCOUNT_REPORT = "751";

//column index -> direction. The server pre-sorts by Company Name (column 2) ascending.
var allaccountreport_sort = { 2 : "asc" };

function filterAllAccountReport() {
	LoadingScreen("show");
	var data = { "type" : C_FILTER_ALL_ACCOUNT_REPORT };
	var url  = "request.pzx?c=" + all_account_report_url + "&d=" + new Date().getTime() ;
	callServer(url,"json",data,onAllAccountReportResponse,null) ;
	return false;
}

//=====================================

function onAllAccountReportResponse(obj,resp) {
	LoadingScreen("hide");
	if (resp.status != C_OK) {
		swal.fire("Warning", resp.mesg, "warning");
		return false;
	}

	if (resp.type == C_FILTER_ALL_ACCOUNT_REPORT) {
		allaccountreport_sort = { 2 : "asc" };
		$('#allaccountreport-table').html('');
		$('#allaccountreport-table').html(resp.data);
	}
}

function sortAllAccountReport(col) {
	var $tbody = $('#allaccountreport-table tbody');
	var rows   = $tbody.find('tr').not('.no-records').get();
	if (rows.length == 0)
		return;

	var dir = (allaccountreport_sort[col] == "asc") ? "desc" : "asc";
	allaccountreport_sort = {};
	allaccountreport_sort[col] = dir;

	rows.sort(function(a,b) {
		var x = $(a).children('td').eq(col).text().trim().toLowerCase();
		var y = $(b).children('td').eq(col).text().trim().toLowerCase();

		if (x == y)  return 0;
		if (x == "") return 1;	//keep blanks at the bottom whichever way we sort
		if (y == "") return -1;
		if (dir == "asc")
			return (x < y) ? -1 : 1;
		return (x < y) ? 1 : -1;
	});

	$tbody.append(rows);
	renumberAllAccountReport();

	$('#allaccountreport-table thead th i').attr('class','fa');
	$('#allaccountreport-table thead th').eq(col).find('i')
		.attr('class', (dir == "asc") ? 'fa fa-sort-up' : 'fa fa-sort-down');
}

//S/N is a running row count, so it stays 1..n top to bottom after every sort
function renumberAllAccountReport() {
	$('#allaccountreport-table tbody tr').not('.no-records').each(function(i) {
		$(this).children('td').eq(0).text(i + 1);
	});
}
