// lib_clickgrab.js - Intercepts the onkeydown event so that user confirmation can be provided

// Requires: lib_core.js
if (!LIB_CORE_LOADED) {
  // Here is where you _could_ do something to alert the user to a problem, but we don't want to do that.
}

/* Prepare mechanism for predicting users' typing speed.
 * This attempts to correct a known bug, in which editing a value in the middle can cause the cursor to move
 * to the end of the field before input from the user is completed. This attempts to guess the user's average
 * typing speed, and allow for a long enough delay between keystrokes, before the mask function re-formats the
 * field value. This is by no means a final solution, and can still result in the known bug, but it should help.
 * Additionally, this can be used to determine the best time during input to submit AJAX requests to the server.
 */
var hTimeOut;
var keyInterval = new Array(3);
function resetKeypress() {
  keyInterval[0] = 0; // First keypress time
  keyInterval[1] = 0; // Recent keypress time
  keyInterval[2] = 0; // Total keypress count
  window.clearTimeout(hTimeOut);
}
resetKeypress();

function predictKeypress() {
  var thisInstant = new Date().getTime();
  if (keyInterval[0] == 0) {
     // Log first keypress time if none exists
    keyInterval[0] = thisInstant;
  }
  keyInterval[1] = thisInstant; // Update this keypress time
  keyInterval[2] = keyInterval[2] + 1; // Increment total keypress count
  if (keyInterval[2] > 1) {
    // Only average times if we have more than 1 keypress logged
    thisInterval = keyInterval[1] - keyInterval[0]; // Time since input started, until now
    avgWaitTime = thisInterval / keyInterval[2]; // Average time between keystrokes
  } else {
    avgWaitTime = 400; // Assume a default keystroke delay if no average available
  }
  return(avgWaitTime * 3); // Multiply the average time by some #, to allow for a small input delay
}
/* End predictive keypress timers */

/* Begin KeyPress Check */
var dblEnterTime; // Timer object for stopping multiple ENTER keypresses
function clearEnterAttempt() {
  enterAttempted = false;
  clearTimeout(dblEnterTime);
  hideStatus();
}

/* Check for special keypresses */
var TRAP_ENTER = true; // Special var to turn on/off ENTER key capture (default: on)
function keyDown(evt) {
  var whatKey;
  var whatObj;
  if (evt) {
    whatKey = evt.keyCode;
    whatObj = (evt.target) ? evt.target : evt.srcElement;
  } else {
    whatKey = event.keyCode;
    whatObj = (event.target) ? event.target : event.srcElement;
  }

  // If the user hits ENTER, run the main validation routine, goSubmit()
  if (whatKey == 13 && TRAP_ENTER) {
    if (document.getElementById('keypress') != null &&
        document.getElementById('keypress').value == "off") {
      // Turn off the "enter" keypress for pages that don't need it.
      return true;
    } else if (dialogActive) {
      // Disable the enter key (and/or do something else) for the custom dialog boxes.
      return true;
    } else {
      if (!enterAttempted) {
        enterAttempted = true;
        dblEnterTime = setTimeout('clearEnterAttempt()',3000);
        if (!whatObj || whatObj.type != "button") {
          // Only call this function if the focus of the ENTER key was NOT a button.
          goSubmit(); // This allows us to run extra stuff, instead of blindly submitting the form.
        }
      } else {
        window.status = "Please wait one moment before pressing ENTER again.";
        stopProcessing(evt);
        return false;
      }
    }
  }

  // If the user hits F12, show the diagnostic screen, if in debug mode
  if (whatKey == 123) {
    toggleDiagnostics("");
  }

  // If the user hits ESC during form submit, stop/hide the progress loading bar
  if (whatKey == 27) {
    if (document.getElementById("progress")) { ProgressDestroy(); }
    toggleDiagnostics("hide");
    return true;
  }

  // If the user hit backspace (8) or delete (46), reset our predictive keypress algorithm
  if (whatKey == 8 || whatKey == 46) {
    resetKeypress();
    return true;
  }
}
// Setup the event handler immediately (keydown used because keypress of F12 cannot be trapped in IE)
document.onkeydown = keyDown;

// Set a global flag that indicates this library has been loaded by the browser.
var LIB_KEYGRAB_LOADED = true;

// End library
