/*
	the CartUpdater class takes a table ID and initializes an object
	that can update the shopping cart depicted in that table
*/

var CartUpdater = Class.create();
CartUpdater.prototype = {

	// initialize the updater from a table ID
	initialize: function(tableID) {
		this.table = $(tableID);
		this.totalRow = this.table.lastChild.getElementsByTagName('TR')[0];
		this.parseRow(this.totalRow);
		this.totalAmount = 0;
		this.grandTotal = 0;
		this.updateRows(this.table.tBodies[0].getElementsByTagName('TR'));
		this.updateCell(this.totalRow.amount, this.totalAmount, '#', '');
		this.updateCell(this.totalRow.total, this.grandTotal, '## ##0,00', '&#8364; ');
	},

	parseRow: function(row) {
		for (var i = 0; i < row.childNodes.length; i++) {
			var cell = row.childNodes[i];
			if (cell.className) {
				row[cell.className] = { element: cell, data: this.parseCell(cell) };
			}
		}
	},

	parseCell: function(cell) {
		return cell.firstChild.nodeValue
			? cell.firstChild.nodeValue
			: parseFloat(cell.firstChild.value);
	},

	updateCell: function(cell, data, format, prefix) {
		cell.data = data;
		cell.element.firstChild.value = data;
		cell.element.lastChild.innerHTML = prefix + formatNumber(data, format);
	},

	updateRows: function(rows) {

		for (var i = 0; i < rows.length; i++) {
			var row = rows[i];
			this.parseRow(row);
			if (row.price) {
				this.updateCell(row.total, row.price.data * row.amount.data, '## ##0,00', '&#8364; ');
				this.totalAmount += parseInt(row.amount.data);
			}
			this.grandTotal += parseFloat(row.total.data);
		}
	}
};

