/**
 * Handle a key press from a text field that can automatically calculate a
 * derived value. Basically, enter normal mathematical formula like
 * "5 * .03 =". When you press the equal ("=") key, the value in the text field
 * will be replaced with the calculated value. If the value can't be
 * calculated, it is left unchanged.
 *
 * @param e the event
 * @param precision the decimal precision to round to.
 */
function processCalculatorKeyPress(e, precision) {
  var targ;
  if (!e) var e = window.event;
  if (e.target) targ = e.target;
  else if (e.srcElement) targ = e.srcElement;
  if (targ.nodeType == 3) // defeat Safari bug
	targ = targ.parentNode;

  if (e.keyCode) code = e.keyCode;
  else if (e.which) code = e.which;

  if (code == 61) { // '='
    var expression;
    var result;
    expression = targ.value;

    try {    
      // calculate, evaluating arithmetic expression
      result = eval(expression);
    
      if (typeof result == "number") {
        // round, if necessary
        if (typeof precision == "number") {
          if (precision > 0) {
            if (result.toFixed) {
              result = result.toFixed(precision);
            } else {
              var factor = Math.pow(10,precision);
              result = Math.round(result * factor) / factor;
            }
          }
        }
    
        targ.value = result;
    
        // don't display key that triggered the calculation
        if (e.preventDefault) {
          e.preventDefault();
        } else {
          e.returnValue = false; // IE
        }
      }
    } catch (e) {
      // expression wasn't an arithmetic expression, let normal text be displayed
    }
  }

  // var character = String.fromCharCode(code);
  // alert('Code was: ' + code + ' Character was: [' + character + '] targ: [' + targ.value + ']');

  return false;
}

