var addListener = function() {
    if ( window.addEventListener ) {
        return function(el, type, fn) {
            el.addEventListener(type, fn, false);
        };
    } else if ( window.attachEvent ) {
        return function(el, type, fn) {
            var f = function() {
                fn.call(el, window.event);
            };
            el.attachEvent('on'+type, f);
        };
    } else {
        return function(el, type, fn) {
            element['on'+type] = fn;
        }
    }
}();

function initMultiAdd() {
	var maForm = document.getElementById("ma-of");
	if (!maForm){ return false; }
	var tables = maForm.getElementsByTagName("table");
	for (var i = 0, j = tables.length; i < j; i++) {
		if (tables[i].className == "sc-ma-product-table") {
			var tds = tables[i].getElementsByTagName("td");
			for (var q = 0, r = tds.length; q < r; q++) {
				if (tds[q].className == "qty-cell") {
					var ins = tds[q].getElementsByTagName("input");
					for (var u = 0, v = ins.length; u < v; u++){
						if (ins[u].id) {
							var hidIn = ins[u];
							var num = ins[u].id.match(/^vwitem(\d)$/);
							num = (num)? num[1] : num;
							if (num) {
								var chkIn = document.createElement("input");
								chkIn.setAttribute("type", "checkbox");
								chkIn.setAttribute("value", hidIn.getAttribute("value"));
								chkIn.setAttribute("class", "ma-chk-box");
								hidIn.parentNode.replaceChild(chkIn, hidIn);
								chkIn.setAttribute("name", hidIn.getAttribute("name"));
								chkIn.setAttribute("id", hidIn.getAttribute("id"));
								
								var qtyIn = document.getElementById('vwquantity' + num);
								if (qtyIn) {
									try {
										addListener(chkIn, "click", toggleQtyVal);
										qtyIn.value = "0";
										addListener(qtyIn, "keyup", toggleChkVal);
										addListener(qtyIn, "blur", adjustQtyVal);
									} catch (e) {};
								}
							}
						}
					}
				}
			}
		}
	}
}

function toggleQtyVal() {
	var num = this.id.match(/^vwitem(\d)$/);
	num = (num)? num[1] : num;
	if (num) {
		var qtyIn = document.getElementById('vwquantity' + num);
		if (qtyIn) {
			if (this.checked) {
				qtyIn.focus();
				qtyIn.value = '1';
			} else {
				qtyIn.value = 0;
			}
		}
	}
}

function toggleChkVal() {
	var num = this.id.match(/^vwquantity(\d)$/);
	num = (num)? num[1] : num;
	if (num) {
		var chkIn = document.getElementById('vwitem' + num);
		if (chkIn) {
			var val = this.value;
			if ((val != 0) && (val != '')) {
				if (chkIn) chkIn.checked = true;
			} else {
				if (chkIn) chkIn.checked = false;
			}
		}
	}
}

function adjustQtyVal() {
	var val = this.value;
	if (!val) {
		this.value = 0;
	}
}

initMultiAdd();
