// JavaScript Document
(function(){
  // Validation constants
  var ErrorBlurClassName = 'dr_inputErrorBlur';
  var ErrorFocusClassName = 'dr_inputErrorFocus';
  var QtyErrorSpanId = 'qty_error_span';
  // Get a reference to the quantity field
  var qtyField = document.getElementById('quantity');
  // Returns true when the quantity is a positive integer
  function validQty(qty) {
    return /^[1-9]\d*$/.test(qty);
  }
  // Switch the class when the quantity is invalid
  function setQtyFocus() {
    if (!validQty(qtyField.value)) {
      qtyField.className = ErrorFocusClassName;
    }
  }
  // Resets the quantity field class when the user tabs off the field
  function setQtyBlur() {
    // Trim leading/trailing white space
    qtyField.value = qtyField.value.replace(/^\s+|\s+$/g, '');
    // Hide the error message and set the field back to normal
    if (validQty(qtyField.value)) {
      document.getElementById(QtyErrorSpanId).innerHTML = '';
      qtyField.className = '';
      return true;
    }
    else {
      // Switch the class if the quantity is invalid
      qtyField.className = ErrorBlurClassName;
      return false;
    }
  }
  // Attach onfocus, onblur, and onkeydown events to the quantity field
  qtyField.onfocus = setQtyFocus;
  qtyField.onblur = setQtyBlur;
  qtyField.onkeydown = function(e){
    e = e || window.event;
    var keyNum = (window.event) ? e.keyCode : e.which;
    return ((keyNum == 8) // backspace
        || (keyNum == 9) // tab
        || (keyNum == 13) // carriage return
        || (keyNum == 35) // end key
        || (keyNum == 36) // home key
        || (keyNum == 37) // left arrow
        || (keyNum == 39) // right arrow
        || (keyNum == 46) // delete
        || ((keyNum >= 96) && (keyNum <= 105)) // 0-9 on the keypad
        || (!e.shiftKey && (keyNum >= 48) && (keyNum <= 57)));
  };
  // Valides the quantity field upon form submission
  qtyField.form.onsubmit = function(){
    if (setQtyBlur()) {
      return true;
    }
    else {
      // Displays an "Invalid Quantity" message in the dr_error span below the quantity field
      document.getElementById(QtyErrorSpanId).innerHTML = "Invalid Quantity";
      setQtyFocus();
      return false;
    }
  };
})();
