// Price automator

var PA = function() {
	return {

		cells: [ ],

		matrix: { },

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

		initPricing: function() {

			// 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];
					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;
			if (this.matrix[v]) {
				for (var i=0;i<PA.cells.length;i++) {
					var c = PA.cells[i];
					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;
		}
	};
}();
