
String.prototype.trim = function() {
  return this.replace(/^\s+|\s+$/g, '');
}

String.prototype.isPositiveInteger = function() {
  var i = parseInt(this);
  if (isNaN(i)) return false;
  if (i < 0) return false;
  return i.toString()==this;
}

var isIE = !(!document.all);

function recalcPrice(e) {
  try {
    if (e && !priceIsValid(e)) return;
    var o = calcPrice();
    setValue('SubTotal', o.subtotal);
    setValue('Postage', o.postage);
    setValue('Total', o.total);
  }
  catch(ex) {
    // swallow errors
  }
}

function recalcPostage(e) {
  try {
    var o = calcPrice();
    setValue('SubTotal', o.subtotal);
    setValue('Postage', o.postage);
    setValue('Total', o.total);
  }
  catch(ex) {
    // swallow errors
  }
}

function priceIsValid(e) {
  var s = e.value.trim();
  if (s.length==0) return true;
  if (s.isPositiveInteger()) return true;
  alert('Quantities must be blank or a whole number greater than zero');
  e.value = '';
  return false;
}

function calcPrice() {
  var t = 0;
  var n = 0;
  var c = document.forms['products'].elements;
  var e, q, p, o = 0;
  for (var i=0; i < c.length; i++) {
    e = c[i];
    switch (e.type) {
    case 'text':
      q = e.value;
      p = e.getAttribute('price');
      if (p && q) {
        t += parseFloat(p) * parseInt(q);
        n += parseInt(q);
      }
      break;
    case 'checkbox':
      o = (e.checked ? 0.55 : 0);
    }
  }
  p = (n ? (o + n + 1.95) : 0);
  return {
    subtotal: t,
    postage: p,
    total: (t + p)
  }
}

function setValue(name, value) {
  var e = document.getElementById(name);
  if (!e) return;
  var s = (Math.round(value * 100) / 100).toString();
  var n = s.length - 1;
  var i = s.indexOf('.');
  switch (i) {
    case -1:
      s += '.00';
      break;
    case n:
      s += '00';
      break;
    case n - 1:
      s += '0';
  }
  if (isIE) {
    e.innerText = s;
  }
  else {
    while (e.hasChildNodes()) e.removeChild(e.firstChild);
    e.appendChild(document.createTextNode(s));
  }
}

window.onload = function() {
  if (document.forms[0].overseas.type !== 'hidden') setTimeout(recalcPrice, 100);
}
