function toCurrency (v) {
	var w = Math.floor(v * 100 + .999) / 100;
	var x = w.toString(); w = x.indexOf(".");
	if (w == -1) {
	    x += ".00";
	} else {
	    if (w == x.length - 2)
	    	x += "0";
	}
	return x;
}

function getProduct (elem, name, num) {
	if (!num) num = elem.name.charAt(elem.name.indexOf("_") - 1);
	return elem.form.elements["product" + num + "_" + name];
}

function calculateTotal (elem) {
    with (elem.form) {
	var subtotal = 0, units = 0, i;

	for (i = 1; i <= numProducts.value; i++) {
	    var check = getProduct(elem, "check", i),
		qty   = getProduct(elem, "qty", i),
		tot   = getProduct(elem, "total", i),
		cost  = getProduct(elem, "cost", i);

	    if (qty.value < 1) {
		qty.value = 0;
		if (check) check.checked = false;
	    } else {
	    	qty.value = Math.floor(qty.value);
	    	if (check) check.checked = true;
	    }

	    tot.value = toCurrency( qty.value * cost.value );
	    units += parseInt(qty.value); subtotal += parseFloat(tot.value);
	}

	tax.value = toCurrency((state.options[state.selectedIndex].value.toUpperCase()
	    == salesState.value.toUpperCase()) ? subtotal * salesTax.value : 0);

	if (shipping.options[shipping.selectedIndex].value) { 
 	    extra.value = toCurrency( units > 1 ? (units - 1) * unitExtra.value : 0 );
	    total.value = toCurrency( units ? 1 * subtotal + 1 * tax.value + 
	        1 * extra.value + 1 * shipping.options[shipping.selectedIndex].value : 0 );
	}
    }
    return true;
}

function toggleProduct (check) {
    var qty = getProduct(check, "qty");
    if (check.checked) {
	if (qty.value < 1) qty.value = qty.defaultValue || 1;
    } else {
	qty.defaultValue = qty.value;
	qty.value = 0;
    }
    return calculateTotal(check);
}

function MM_validateForm() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
    if (val) { nm=val.name; if ((val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
        if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
      } else if (test!='R') { num = parseFloat(val);
        if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
  } if (errors) alert('The following field(s) must be completed:\n'+errors);
  document.MM_returnValue = (errors == '');
}

