// Price automator

var PA = function() {
	return {

		cells: [ ],

		matrix: { },

		idCounter: 0,

		cell: function() {
			this.id = null,
			this.base = parseFloat(0.00),
			this.dom = null,
			this.column = 0,
			this.table = null
		},

		up: function(element, tagname) {
			var pa = element.parentNode;
			if (!pa) { return null; }
			while (pa.tagName.toLowerCase() != tagname.toLowerCase()) {
				pa = pa.parentNode;
				if (!pa) { return null; }
			}
			return pa;
		},

		initPricing: function() {

			// Make sure all tables have an id
			var tables = document.getElementsByTagName('table');
			for (var i=0;i<tables.length;i++) {
				if (!tables[i].id) {
					tables[i].id = 'pa_table_' + PA.idCounter;
					PA.idCounter++;
				}
			}

			// Make sure that that all browsers (IE) can use getElementsByClassName
			if (document.getElementsByClassName == undefined) {
				document.getElementsByClassName = function(className) {
					var hasClassName = new RegExp("(?:^|\\s)" + className + "(?:$|\\s)");
					var allElements = document.getElementsByTagName("*");
					var results = [];

					var element;
					for (var i = 0; (element = allElements[i]) != null; i++) {
						var elementClass = element.className;
						if (elementClass && elementClass.indexOf(className) != -1 && hasClassName.test(elementClass))
							results.push(element);
					}

					return results;
				}
			}

			var cells = document.getElementsByClassName('pricing-row');
			var numericRegex = /^[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$/;
			var colorRegex = /color(\d)/;
			for (var i=0;i<cells.length;i++) {
				if (cells[i].innerHTML.match(numericRegex)) {
					var cell = new PA.cell();
					cell.id = cells[i].id = 'pa' + i;
					cell.base = cells[i].innerHTML;
					cell.dom = cells[i];
					cell.table = PA.up(cells[i], 'table').id;
					var colorCol = cells[i].className.match(colorRegex);
					if (colorCol) {
						cell.column = colorCol[1];
					}
					PA.cells[PA.cells.length] = cell;
				}
			}
		},

		handleChange: function(cb) {
			var v = cb.value;
			var ownerTable = PA.up(cb, 'table').id;
			if (this.matrix[v]) {
				for (var i=0;i<PA.cells.length;i++) {
					var c = PA.cells[i];
					if (c.table == ownerTable) {
						var p = parseFloat(c.base) + parseFloat(this.matrix[v][0]);
						if (c.column > 1) {
							var indx = (c.column-1);
							if (this.matrix[v][indx]) {
								p = parseFloat(p) + parseFloat(this.matrix[v][indx]);
							}
						}
						c.dom.innerHTML = p.toFixed(2);
					}
				}
			}
		},

		setMatrix: function(matrix) {
			this.matrix = matrix;
		}
	};
}();

