// lib_clickgrab.js - Intercepts the onclick event so that user confirmation can be provided

// Requires: lib_core.js, lib_ajax.js
if (!LIB_CORE_LOADED || !LIB_AJAX_LOADED) {
  // Here is where you _could_ do something to alert the user to a problem, but we don't want to do that.
}

/* Do not set these variables manually! */
var dblClickTime;             // Timer object for stopping multiple clicks
var ignoreFieldChangeReq = false; // Whether to skip requirement that fields must have changed

function clearClickAttempt() {
  clickAttempted = false;
  clearTimeout(dblClickTime);
  hideStatus();
} // clearClickAttempt

function handleClicks(evt) {
  // Get handles to the objects that caused this event.
  var whatObj;
  var whatParent;
  if (evt.target) { // Non-IE
    lastCaughtEvent = evt;
    whatObj = (evt.target) ? evt.target : evt.srcElement;
  } else { // IE Only
    lastCaughtEvent = event;
    whatObj = (event.target) ? event.target : event.srcElement;
  }
  if (whatObj.parentElement) { // IE Only
    whatParent = whatObj.parentElement;
  } else { // IE5+, NS6+
    whatParent = whatObj.parentNode;
  }

  // Figure out if the action is "safe" (ie. does not normally require user intervention before proceeding).
  // Safe links should only be used for objects that would not cause the user to leave the page or lose changes.
  // NOTE: Special links are different from Safe links, though a special link makes it a safe link.
  // Special links are used in built-in site features, like context-sensitive help or the fancy alert messages.
  var isSafe = false;
  var whatObjId;
  var specialLink = false;
  if (whatObj && whatObj.tagName == "A") {
    isSafe = (whatObj.getAttribute('safelink') == "yes") || false; // Primary check for safe links.
    whatObjId = whatObj.getAttribute('id');
    if (whatObjId == "Field Help" ||
        whatObjId == "openRepriceWindow" ||
        whatObjId == "trueBtn" ||
        whatObjId == "falseBtn" ||
        whatObjId == "closeBtn") { specialLink = true; }
    if (specialLink) { isSafe = true; } // Backup check for special links.
  }
  if (whatParent && whatParent.tagName == "A") {
    isSafe = (whatParent.getAttribute('safelink') == "yes") || false;
    whatObjId = whatParent.getAttribute('id');
    if (whatObjId == "anchor1" || whatObjId == "anchor2") { isSafe = true; }
  }
  if (whatObj && whatObj.tagName == "INPUT" && whatObj.type == "button") { isSafe = true; }

  // Always check if the user actually changed any form fields.
  var availableForms = new Array(watchFormForChanges);
  var formHasChanged = false; // This gets reset on every click.
  if (watchFormForChanges == "") {
    // This may pick up unwanted forms, so it's best to specifically set watchFormForChanges when possible.
    availableForms = getForms();
  }
  for (var i=0; i<availableForms.length; i++) {
    // Loop through all available forms, checking if any have changed since the page was loaded.
    // checkFieldChange() in lib_formval.js, different from checkReprice() in lib_loanfuncs.js
    if (checkFieldChange(availableForms[i])) {
      formHasChanged = true; // User actually clicked on a link of some type, AND the page data has changed.
// alert("detected form change - lib_clickgrab.js: " + availableForms[i].name + " : " + checkFieldChange(availableForms[i]));
    }
  }

  // Prepare to prompt the user before proceeding.
  // inProductAdvisor and inLoanAction defined in lib_core.js
  var retVal;
  var promptUser = false;
  if ((whatObj.tagName == "A" || whatObj.onclick != null || regexCheck(whatParent,/^(http|javascript).*$/)) &&
      whatObj.tagName != "INPUT") { promptUser = true; } // User actually clicked on a link of some type.

  // Immediately proceed if the user clicked on a special link.
  if (specialLink) {
    clearClickAttempt();
    promptUser = false;
  } // specialLink

  // If the page data has not changed or the user clicked on a safe link, don't stop them from proceeding.
  // And only stop the user if they are NOT in the middle of a process (like the PA flow or Loan Import),
  // and only if we've already detected that we need to stop them from performing a prompt-worthy action.
  if (promptUser && (isSafe || (!formHasChanged && !ignoreFieldChangeReq))) {
    // If the link was "safe" or the form hasn't changed, then proceed as the user wanted.
    if (!clickAttempted) {
      // If this is the FIRST time the user has clicked an object, just proceed like normal.
      clickAttempted = true;
      dblClickTime = setTimeout('clearClickAttempt()',5000);
      window.status = "Please wait one moment before clicking again.";
      promptUser = false;
    } else {
      // Otherwise, stop the user from clicking multiple times before we figure out what to do.
      window.status = "Please wait one moment before clicking again.";
      stopProcessing(evt);
      return false;
    }
  }

  // Now find out if we should prompt the user that they may lose any unsaved changes.
  if (promptUser) {
    if (stopWait) { stopWait(); }
    // At this point, the user is doing something which may cause them to lose changes--stop them if necessary!
    // By default we'll only prompt the user if the form has changed, and there is a message ready to display.
    if (msgBoxText != "") {
      retVal = confirm(msgBoxText); // Actually displays message to user, "you are about to lose changes, blah blah blah"
    } else {
      retVal = true; // Just proceed, but perform the proper click-stopping logic if applicable.
    }

    // If the user clicked OK (true), then we're safe to proceed with taking them where they want to go.
    if (retVal) {
      // Check if the reprice window is open and attempt to close
      try {
        // Insert code to close any child windows here.
      } catch(e) { /* Die Quietly */ }

      // If we interrupted the user chosing a menu link, proceed where they left off
      if (pendingLink != "") {
        navtoPage(pendingLink);
        pendingLink = "";
      }

      // User should proceed on their way at this point
    } else {
      // Otherwise (false), we need to stop the user cold so they don't lose their entered data
      pendingLink = "";
      clearClickAttempt();
      stopProcessing(evt);
      return false;
    } // end retVal check
  } // promptUser
  if (!promptUser && pendingLink != "") {
    navtoPage(pendingLink);
    pendingLink = "";
  }
} // handleClicks

function releaseClicks() {
  if (document.addEventListener) {
    // Non-IE Browsers
    document.removeEventListener('click', handleClicks, false);
  } else if (document.all) {
    // IE Browsers
    document.detachEvent('onclick', handleClicks);
  } else {
    // Older Browsers
    document.onclick = null;
  }
  // For use with the menu system--enables the onclick event.
  trapLinks = false;
  clearClickAttempt();
} // releaseClicks

function catchClicks() {
  if (document.addEventListener) {
    // Non-IE Browsers
    document.addEventListener('click', handleClicks, true);
  } else if (document.attachEvent) {
    // IE Browsers
    document.attachEvent('onclick', handleClicks);
  } else {
    // Older Browsers
    document.onclick = handleClicks;
  }
  // For use with the menu system--disables the onclick event.
  trapLinks = true;
  clearClickAttempt();
} // catchClicks


// Set a global flag that indicates this library has been loaded by the browser.
var LIB_CLICKGRAB_LOADED = true;

// End library