/*
Uses ajax2.js
*/

function MDataTable(parent,W,H){
	this.self = this;
	this.width = W ? W : null;
	this.height = H ? H : 120;

	this.highColor1 = '#BBC1FF';
	this.highColor2 = '#8D81FF';
	this.selectedColor = '#8888BB';
	this.highlightedRows = Array();
	this.dataRows = Array();
	this.fixedColumns = Array();
	this.dataURL;
	this.loadCallback;
	this.selectedId;
	this.totalizeIx = Array();
	this.tableExpanded = false;

	this.container = document.createElement('DIV');
//	this.container.style.background = '#ffffff';
//	this.container.style.height = this.height + 'px';
//	if (document.all) {
		this.container.style.overflow = 'auto';
//	}

	if (parent) {
		this.parent = parent;
		this.parent.appendChild(this.container);
		this.container.style.height = this.parent.clientHeight + 'px';
		this.height = this.parent.clientHeight;	
	}
};

////////////////////////////////////////////////////////////////////////////////////

MDataTable.prototype.reload = function() {
	var self = this.self;
	this.clear();
	if (this.dataURL) {
		ajaxLoad(this.dataURL,function(httpObj){
			self.parseData(httpObj,this.loadCallback);
		},null,true);
	}
};


MDataTable.prototype.loadData = function(url,callback) {
	var self = this.self;
	this.clear();

	this.dataURL = url;
	this.loadCallback = callback;

	ajaxLoad(this.dataURL,function(httpObj){
		self.parseData(httpObj,callback);
	},null,true);
};

MDataTable.prototype.parseData = function(httpObj,callback) {
	var self = this.self;
	var str = httpObj.responseText;
	this.loadFromString(str);


	if (this.selectedId != null) {
		this.selectRowById(this.selectedId);
	}
	if (typeof callback == 'function') {
		callback(this,this.csvArray.length-1);
	}
};

MDataTable.prototype.loadFromString = function(str) {
	this.clear();

	if (str) {
		this.csvArray = str.split('\n');
		if (!this.csvArray[this.csvArray.length-1]) {
			this.csvArray.pop();
		}

		this.create();
	}
};

////////////////////////////////////////////////////////////////////////////////////


MDataTable.prototype.clear = function() {
	if (!this.dataTable) {
		return;
	}

	var objArray = this.dataTable.getElementsByTagName('TD');
	while (objArray.length > 0) {
		var removed = objArray[0].parentNode.removeChild(objArray[0]);
		removed = null;
	}
	objArray = null;

	var objArray = this.dataTable.getElementsByTagName('TR');
	while (objArray.length > 0) {
		var removed = objArray[0].parentNode.removeChild(objArray[0]);
		removed = null;
	}
	objArray = null;

	var objArray = this.dataTable.getElementsByTagName('TBODY');
	while (objArray.length > 0) {
		var removed = objArray[0].parentNode.removeChild(objArray[0]);
		removed = null;
	}
	objArray = null;

	var objArray = this.dataTable.getElementsByTagName('THEAD');
	while (objArray.length > 0) {
		var removed = objArray[0].parentNode.removeChild(objArray[0]);
		removed = null;
	}
	objArray = null;

	this.dataTable = null;
	this.tBody = null;

	if (this.summary) {
		var removed = this.container.removeChild(this.summary);
		removed = null;
	}

	this.highlightedRows = Array();
	this.dataRows = Array();
};


MDataTable.prototype.create = function() {
	this.dataTable = this.createTable();
	this.summary = this.createSummary();

	this.container.appendChild(this.summary);
	this.container.appendChild(this.dataTable);
};


MDataTable.prototype.createSummary = function() {
	var self = this.self;
	var sDiv = document.createElement('DIV');
	sDiv.innerHTML = '';
	sDiv.innerHTML += 'Unit count: ' + (this.csvArray.length - 1) + '<br>';

	for (var n = 0 ; n < this.totalizeIx.length ; n++ ) {
		var colIx = this.totalizeIx[n];
		var fName = this.fieldNames[colIx];
		var fValue = this.getSum(colIx);
		sDiv.innerHTML += fName + ': ' + fValue + '<br>';
	}

	sDiv.title = 'Click to toggle detail';
	sDiv.style.cursor = 'pointer';
	sDiv.style.font = 'normal 10px verdana';
	sDiv.style.padding = '2px';
	sDiv.style.borderTop = '1px solid white';
	sDiv.onclick = function() {self.toggleTable()};
	sDiv.onmouseover = function() {this.style.background = self.highColor1};
	sDiv.onmouseout = function() {this.style.background = ''};

	return sDiv;
};


MDataTable.prototype.toggleTable = function() {
	if (this.dataTable.style.display == 'none') {
		this.dataTable.style.display = '';
		this.tableExpanded = true;
	}
	else {
		this.dataTable.style.display = 'none';
		this.tableExpanded = false;
	}
};



MDataTable.prototype.createTable = function() {
	var table = document.createElement('TABLE');

	var tHead = document.createElement('THEAD');
	table.appendChild(tHead);

	var tFoot = document.createElement('TFOOT');
	table.appendChild(tFoot);


	var tBody = document.createElement('TBODY');
	table.appendChild(tBody);
	this.tBody = tBody;

	
//	if (!document.all) {
//		this.tBody.style.height = (this.height - 20) + 'px';
//		this.tBody.style.overflowY = 'auto';
//		this.tBody.style.overflowX = 'hidden';
//	}

	table.setAttribute('width','100%');
	if (document.all) {
//		table.setAttribute('width','90%');
	}
	table.style.marginLeft = 'auto';
	table.style.marginRight = 'auto';

	table.setAttribute('cellSpacing','1');
	table.setAttribute('cellPadding','1');

	var headers = this.csvArray[0];
	var row = this.createHeadRow(headers);
	tHead.appendChild(row);


	var row = this.createFootRow(headers);
	tFoot.appendChild(row);



	this.dataRows = Array();
	for (var n = 1 ; n < this.csvArray.length ; n++ ) {
		var row = this.createRow(this.csvArray[n],n-1);
		tBody.appendChild(row);
		this.dataRows.push(row);
	}

	if (!this.tableExpanded) {
		table.style.display = 'none';
	}
	return table;

};




MDataTable.prototype.getSum = function(colIx) {
	var sum = 0;
	for (var n = 1 ; n < this.csvArray.length ; n++ ) {
		var vals = this.csvArray[n].split(',');
		var val = parseFloat(vals[colIx]);
		sum += val;
	}
	sum += '';
	sum = sum.replace(/\d{1,3}(?=(\d{3})+(?!\d))/g,"$&,");

	return sum;
}


MDataTable.prototype.createFootRow = function(dataStr) {
	var row = document.createElement('TR');
	var cells = dataStr.split(',');
	var cellIx = 0;
	for (var n = 0 ; n < cells.length ; n++ ) {

		var val = '&nbsp;';
		if (this.totalizeIx.indexOf(n) > -1) {
			val = this.getSum(n);
		}
		
		// If a field name is prefixed with '_' then it's hidden
		if (!cells[n].match(/^_/)) { //hidden
			var cell = this.createFCell(val,cellIx);
			cellIx++;
			row.appendChild(cell);
		}
	}

	if (this.fixedColumns.length) {
		for (var n = 0 ; n < this.fixedColumns.length ; n++ ) {
			var cell = this.createHCell('&nbsp;',cellIx);
			cellIx++;
			row.appendChild(cell);
		}
	}

	return row;
};















MDataTable.prototype.createHeadRow = function(dataStr) {
	var row = document.createElement('TR');
	var cells = dataStr.split(',');
	this.fieldNames = Array();
	var cellIx = 0;
	for (var n = 0 ; n < cells.length ; n++ ) {
		this.fieldNames[n] = cells[n];
		// If a field name is prefixed with '_' then it's hidden
		if (!cells[n].match(/^_/)) { //hidden
			var cell = this.createHCell(cells[n],cellIx);
			cellIx++;
			row.appendChild(cell);
		}
	}

	if (this.fixedColumns.length) {
		for (var n = 0 ; n < this.fixedColumns.length ; n++ ) {
			var cell = this.createHCell('&nbsp;',cellIx);
			cellIx++;
			row.appendChild(cell);
		}
	}

//	if (!document.all) {
//		this.scrollHCell = this.createHCell('&nbsp',cellIx);
//		this.scrollHCell.style.background = '';
//		this.scrollHCell.style.border = 'none';
//		this.scrollHCell.style.width = '16px';
//		row.appendChild(this.scrollHCell);
//	}

	return row;
};


MDataTable.prototype.createRow = function(dataStr,ix) {
	var self = this.self;
	var rowDataStr = 'rowData = {';
	var row = document.createElement('TR');

	var cells = dataStr.split(',');
	var cellIx = 0;
	for (var n = 0 ; n < cells.length ; n++ ) {
		// If a field name is prefixed with '_' then it's hidden
		if (!this.fieldNames[n].match(/^_/)) { //hidden
			var cell = this.createCell(cells[n],cellIx);
			cellIx++;
			row.appendChild(cell);
		}
		var fieldName = this.fieldNames[n].replace(/^_/,'');
		rowDataStr += '"' + fieldName + '":"' + cells[n] + '",';

		if (fieldName == 'rowColor') {
			row.style.background = cells[n];
			row.style.color = 'white';
		}
		else {
			row.style.background = '#eeeeee';
		}

		if (fieldName == 'archived' && cells[n] == 1) {
			row.style.color = '#aaaaaa';
		}
	
	
	}


	if (this.fixedColumns.length) {
		for (var n = 0 ; n < this.fixedColumns.length ; n++ ) {
			var cellData = this.createFixedCellContent(this.fixedColumns[n].type);
			var cell = this.createCell(cellData,cellIx);
			cell.style.width = '16px';
			cellIx++;
			cell.type = this.fixedColumns[n].type;
			cell.clickEventHandler = this.fixedColumns[n].onclick;
			row.appendChild(cell);
		}
	}




	rowDataStr = rowDataStr.replace(/,$/,'');
	rowDataStr += '}';

	row.ix = ix;
	row.selected = false;
	row.rowData = eval(rowDataStr);
	row.onclick = function(){self.rowClicked(this)};

	row.defaultColor = row.style.color;
	row.defaultBackground = row.style.background;
	return row;
};


MDataTable.prototype.setFixedColumns = function(addCols) {
	this.fixedColumns = addCols;
};

MDataTable.prototype.createFixedCellContent = function(type) {
	var html = '';
	if (type == 'DEL') {
		html += '<img width="16" height="16" src="/images/delete.png" title="Delete...">';
	}
	if (type == 'EDIT') {
		html += '<img width="16" height="16" src="/images/edit.png" title="Edit...">';
	}
	if (type == 'ARC') {
		html += '<img width="16" height="16" src="/images/archive.png" title="Archive/unarchive trip">';
	}

	
	
	return html;
};


MDataTable.prototype.createFCell = function(cellData,ix) {
	var self = this.self;

	var cell = document.createElement('TH');
	cell.innerHTML = cellData;
	cell.style.background = '#bbbbbb';
	cell.style.border = '1px solid gray';
	cell.style.font = 'bold 10px verdana';
//	cell.style.cursor = 'pointer';
	cell.ix = ix;
//	cell.onclick = function(){self.sortTable(this)};
	
	return cell;
};


MDataTable.prototype.createHCell = function(cellData,ix) {
	var self = this.self;

	var cell = document.createElement('TH');
	cell.innerHTML = cellData;
	cell.style.background = '#bbbbbb';
	cell.style.border = '1px solid gray';
	cell.style.font = 'bold 10px verdana';
	cell.style.cursor = 'pointer';
	cell.ix = ix;
	cell.onclick = function(){self.sortTable(this)};
	
	return cell;
};

MDataTable.prototype.createCell = function(cellData,ix) {
	var self = this.self;
	var cell = document.createElement('TD');
	cell.style.cursor = 'pointer';
//	cell.style.borderBottom = '1px solid gray';
	cell.style.font = 'normal 10px verdana';

	cell.style.textAlign = 'left';
	cell.val = cellData;
	if (this.totalizeIx.indexOf(ix) > -1) {
		cell.style.textAlign = 'right';
		cellData = cellData.replace(/\d{1,3}(?=(\d{3})+(?!\d))/g,"$&,");
	}

	cell.innerHTML = cellData;


	cell.ix = ix;
	cell.onclick = function(ev){self.cellClicked(ev,this)};
	return cell;
};


MDataTable.prototype.cellClicked = function(ev,cellObj) {
	var self = this.self;

	if (typeof cellObj.clickEventHandler == 'function') {
		try{ev.stopPropagation()}catch(e){event.cancelBubble=true};
		cellObj.clickEventHandler(cellObj.parentNode.rowData);
	}
};

MDataTable.prototype.rowClicked = function(rowObj) {
	var self = this.self;

	if (rowObj.selected == true) {
		this.selectRow(null);
	}
	else {
		this.selectRow(rowObj.ix);
	}

	if (typeof(this.onRowClick) == 'function') {
		this.onRowClick(rowObj);
	}
};
MDataTable.prototype.selectRow = function(ix) {
	for (var n = 0 ; n < this.dataRows.length ; n++ ) {
		this.dataRows[n].style.color = this.dataRows[n].defaultColor;
		this.dataRows[n].style.background = this.dataRows[n].defaultBackground;
		this.dataRows[n].selected = false;
	}
	if (ix != null) {
		this.dataRows[ix].selected = true;
		this.selectedId = this.dataRows[ix].rowData.ID;
		this.dataRows[ix].style.background = this.selectedColor;
	}
};

MDataTable.prototype.selectRowById = function(id) {
	for (var n = 0 ; n < this.dataRows.length ; n++ ) {
		if (this.dataRows[n].rowData.ID == id) {
			this.selectRow(n);
		}
	}
};



MDataTable.prototype.sortTable = function(headCell) {

	function compare(rowA, rowB) {
		return rowA.sortValue - rowB.sortValue;
	} 

	function strCompare(rowA, rowB) {
		var a = rowA.sortValue;
		var b = rowB.sortValue;

		if (a < b) {
			return -1;
		}
		else {
			if (a > b) {
				return 1;
			}
			else {
				return 0;
			}
		}
	}
/*
	function compareDate(a, b) {
	  datA = new Date(a);
	  datB = new Date(b);
	  if (datA < datB) { return -1; }
	  else {
		if (datA > datB) { return 1; }
		else { return 0; }
	  }
	}
*/

	var ix = headCell.ix;

	headCell.sortDirection = headCell.sortDirection == 'ASC' ? 'DESC' : 'ASC';
	var rows = this.tBody.childNodes;
	var rowsArray = Array();
	var archived = Array();

	var isNumeric = true;
	while (rows.length > 0) {
		rows[0].sortValue = rows[0].childNodes[ix].val.toLowerCase();

		if (rows[0].sortValue.match(/[^0-9.]/)) {
			isNumeric = false;
		}

		var removed = this.tBody.removeChild(rows[0]);
		if (removed.rowData.archived == 1) {
			archived.push(removed);
		}
		else {
			rowsArray.push(removed);
		}
	}

	if (isNumeric) {
		rowsArray.sort(compare);
	}
	else {
		rowsArray.sort(strCompare);
	}

	if (headCell.sortDirection == 'DESC') {
		rowsArray.reverse();
	}

	for (var n = 0 ; n < rowsArray.length ; n++ ) {
		this.tBody.appendChild(rowsArray[n]);
	}

	for (var n = 0 ; n < archived.length ; n++ ) {
		this.tBody.appendChild(archived[n]);
	}




};



MDataTable.prototype.highlightRow = function(ix) {
	for (var n = 0 ; n < this.highlightedRows.length ; n++ ) {
		var hix = this.highlightedRows[n];
		this.dataRows[hix].style.background = '';
	}
	this.highlightedRows = Array();
	if (ix != null) {
		this.dataRows[ix].style.background = this.highColor2;

/*
		var scrollDist = this.dataRows[ix].offsetTop - this.containerB.scrollTop;
		if (scrollDist < 0 || scrollDist > containerB.clientHeight) {
			this.dataRows[ix].scrollIntoView(false);
		}

*/
		this.dataRows[ix].scrollIntoView(false);
		this.highlightedRows.push(ix);
	}
};



