// lib_dialogs.js - Provides custom javascript dialog boxes (alert, confirm, prompt, etc)
// Code was originally taken from http://slayeroffice.com/code/custom_alert/
// NOTE: Titles and button labels can be set on a per-dialog basis.

// Requires: lib_core.js, lib_formval.js
if (!LIB_CORE_LOADED || !LIB_FORMVAL_LOADED) {
  // Here is where you _could_ do something to alert the user to a problem, but we don't want to do that.
}

// General size vars for all dialog types.
var DIALOG_WIDTH = 520; // You may override this in the calling function if desired
var BUTTON_WIDTH = 50;  // Always calculated automatically (overrides have no effect)

// Constants to define the title of the alert and button text.
var ALERT_TITLE = "Alert";
var ALERT_BUTTON_TEXT = "OK";

// over-ride the alert method only if this a newer browser.
if (showFancyAlert && document.getElementById) {
  window.alert = function(txt) {
    createCustomAlert(txt);
  }
}

function createCustomAlert(txt) {
  // signal that a dialog box is in use now
  dialogActive = true;

  // shortcut reference to the document object
  d = document;

  // replace any newlines with BR's
  txt = txt.replace(/\n/g, "<br/>");

  // if the modalContainer object already exists in the DOM, bail out.
  if (d.getElementById("modalContainer")) return;

  // create the modalContainer div as a child of the BODY element
  mObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
  mObj.id = "modalContainer";
   // make sure its as tall as it needs to be to overlay all the content on the page
  mObj.style.height = document.documentElement.scrollHeight + "px";

  // create the DIV that will be the alert
  alertObj = mObj.appendChild(d.createElement("div"));
  alertObj.id = "custAlertBox";
  // MSIE doesnt treat position:fixed correctly, so this compensates for positioning the alert
  if (d.all && !window.opera) alertObj.style.top = document.documentElement.scrollTop + "px";
  // center the dialog box
  if (DIALOG_WIDTH > 0) alertObj.style.width = DIALOG_WIDTH + "px";
  alertObj.style.left = (d.documentElement.scrollWidth - alertObj.offsetWidth)/2 + "px";

  // create an H1 element as the title bar
  h1 = alertObj.appendChild(d.createElement("h1"));
  h1.appendChild(d.createTextNode(ALERT_TITLE));

  // create a paragraph element to contain the txt argument
  msg = alertObj.appendChild(d.createElement("div"));
  msg.id = "alertText";
  // msg.appendChild(d.createTextNode(txt));
  msg.innerHTML = txt;

  // determine maximum button size
  BUTTON_WIDTH = ALERT_BUTTON_TEXT.length * 10;
  if (BUTTON_WIDTH < 50) BUTTON_WIDTH = 50;

  // create a box that will float at the bottom of the window.
  bbox = alertObj.appendChild(d.createElement("div"));
  bbox.id = "buttonBox";
  // force the button to stay centered on the window.
  bbox = bbox.appendChild(d.createElement("center"));
  // create an anchor element to use as the confirmation button.
  btn = bbox.appendChild(d.createElement("a"));
  btn.id = "closeBtn";
  btn.appendChild(d.createTextNode(ALERT_BUTTON_TEXT));
  btn.href = "#";
  // set up the onclick event to remove the alert when the anchor is clicked
  btn.onclick = function() { removeCustomAlert(); return false; }
  // determine button size, set defaults as needed
  BUTTON_WIDTH = (ALERT_BUTTON_TEXT.length * 8) + 10; // 8px per character, plus padding
  if (BUTTON_WIDTH < 50) BUTTON_WIDTH = 50; // default size should be about 50 pixels
  btn.style.width = BUTTON_WIDTH + "px";

  alertObj.scrollIntoView();
}

// removes the custom alert from the DOM
function removeCustomAlert() {
  dialogActive = false;
  document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer"));
}

// Constants to define the title of the confirm and button text.
var CONFIRM_TITLE = "Confirm";
var CONFIRM_TRUE_BUTTON_TEXT = "YES";
var CONFIRM_FALSE_BUTTON_TEXT = "NO";
var CONFIRM_RESPONSE = null;

// Set up a dummy function to be overridden later.
function confirmResponse(lastResponse) {
  return(lastResponse);
}

function createCustomConfirm(txt) {
  // signal that a dialog box is in use now
  dialogActive = true;

  CONFIRM_RESPONSE = null; // Reset the last confirmation result.

  // shortcut reference to the document object
  d = document;

  // replace any newlines with BR's
  txt = txt.replace(/\n/g, "<br/>");

  // if the modalContainer object already exists in the DOM, bail out.
  if (d.getElementById("modalContainer")) return;

  // create the modalContainer div as a child of the BODY element
  mObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
  mObj.id = "modalContainer";
   // make sure its as tall as it needs to be to overlay all the content on the page
  mObj.style.height = document.documentElement.scrollHeight + "px";

  // create the DIV that will be the alert
  confirmObj = mObj.appendChild(d.createElement("div"));
  confirmObj.id = "custConfirmBox";
  // MSIE doesnt treat position:fixed correctly, so this compensates for positioning the alert
  if (d.all && !window.opera) confirmObj.style.top = document.documentElement.scrollTop + "px";
  // center the dialog box
  if (DIALOG_WIDTH > 0) confirmObj.style.width = DIALOG_WIDTH + "px";
  confirmObj.style.left = (d.documentElement.scrollWidth - confirmObj.offsetWidth)/2 + "px";
  halfWidth = (parseInt(confirmObj.style.width) / 2) - 12;

  // create an H1 element as the title bar
  h1 = confirmObj.appendChild(d.createElement("h1"));
  h1.appendChild(d.createTextNode(CONFIRM_TITLE));

  // create a paragraph element to contain the txt argument
  msg = confirmObj.appendChild(d.createElement("div"));
  msg.id = "alertText";
  // msg.appendChild(d.createTextNode(txt));
  msg.innerHTML = txt;

  // create a box that will float at the bottom of the window.
  bbox1 = confirmObj.appendChild(d.createElement("div"));
  bbox1.id = "buttonBoxLeft";
  bbox1.style.width = halfWidth + "px";
  // force the button to stay centered on the window.
  bbox1 = bbox1.appendChild(d.createElement("center"));
  // create an anchor element to use as the TRUE confirmation button.
  btn1 = bbox1.appendChild(d.createElement("a"));
  btn1.id = "trueBtn";
  // determine button size, set defaults as needed
  BUTTON_WIDTH = (CONFIRM_TRUE_BUTTON_TEXT.length * 8) + 10; // 8px per character, plus padding
  if (BUTTON_WIDTH < 50) BUTTON_WIDTH = 50; // default size should be about 50 pixels
  if (BUTTON_WIDTH > halfWidth) BUTTON_WIDTH = halfWidth - 16; // max size, minus padding
  btn1.style.width = BUTTON_WIDTH + "px";
  btn1.innerHTML = CONFIRM_TRUE_BUTTON_TEXT;
  btn1.href = "#";
  // set up the onclick event to remove the confirm when the anchor is clicked
  btn1.onclick = function() { removeCustomConfirm(true); return false; }

  // create a box that will float at the bottom of the window.
  bbox2 = confirmObj.appendChild(d.createElement("div"));
  bbox2.id = "buttonBoxRight";
  bbox2.style.width = halfWidth + "px";
  // force the button to stay centered on the window.
  bbox2 = bbox2.appendChild(d.createElement("center"));
  // create an anchor element to use as the FALSE confirmation button.
  btn2 = bbox2.appendChild(d.createElement("a"));
  btn2.id = "falseBtn";
  // determine button size, set defaults as needed
  BUTTON_WIDTH = (CONFIRM_FALSE_BUTTON_TEXT.length * 8) + 10; // 8px per character, plus padding
  if (BUTTON_WIDTH < 50) BUTTON_WIDTH = 50; // default size should be about 50 pixels
  if (BUTTON_WIDTH > halfWidth) BUTTON_WIDTH = halfWidth - 16; // max size, minus padding
  btn2.style.width = BUTTON_WIDTH + "px";
  btn2.innerHTML = CONFIRM_FALSE_BUTTON_TEXT;
  btn2.href = "#";
  // set up the onclick event to remove the confirm when the anchor is clicked
  btn2.onclick = function() { removeCustomConfirm(false); return false; }

  confirmObj.scrollIntoView();
}

// removes the custom alert from the DOM
function removeCustomConfirm(confirmResult) {
  dialogActive = false;
  document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer"));
  CONFIRM_RESPONSE = confirmResult; // Save the result into a variable as well.
  confirmResponse(confirmResult); // Call the followup function.
}

// Constants to define the title of the prompt and button text.
var PROMPT_TITLE = "Prompt";
var PROMPT_TRUE_BUTTON_TEXT = "SUBMIT";
var PROMPT_FALSE_BUTTON_TEXT = "CANCEL";
var PROMPT_RESPONSE = null;
var PROMPT_VALIDATION = "FreeForm"; // See RegEx definitions in formval.js
var PROMPT_BADVALMSG = "Please enter a valid value.";
var PROMPT_INPUT = "single"; // Options: single/multiple
var PROMPT_VALUE = null;
var fieldObj; // Public handle to the input field within the dialog
var errorBox; // Public handle to the error message within the dialog

// Set up a dummy function to be overridden later.
function promptResponse(lastResponse) {
  return(lastResponse);
}

function createCustomPrompt(txt) {
  // signal that a dialog box is in use now
  dialogActive = true;

  PROMPT_RESPONSE = null; // Reset the last prompt result.
  PROMPT_VALUE = null; // Reset the last prompt value.

  // shortcut reference to the document object
  d = document;

  // replace any newlines with BR's
  txt = txt.replace(/\n/g, "<br/>");

  // if the modalContainer object already exists in the DOM, bail out.
  if (d.getElementById("modalContainer")) return;

  // create the modalContainer div as a child of the BODY element
  mObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
  mObj.id = "modalContainer";
   // make sure its as tall as it needs to be to overlay all the content on the page
  mObj.style.height = document.documentElement.scrollHeight + "px";

  // create the DIV that will be the alert
  promptObj = mObj.appendChild(d.createElement("div"));
  promptObj.id = "custConfirmBox";
  // MSIE doesnt treat position:fixed correctly, so this compensates for positioning the alert
  if (d.all && !window.opera) promptObj.style.top = document.documentElement.scrollTop + "px";
  // center the dialog box
  if (DIALOG_WIDTH > 0) promptObj.style.width = DIALOG_WIDTH + "px";
  promptObj.style.left = (d.documentElement.scrollWidth - promptObj.offsetWidth)/2 + "px";
  halfWidth = (parseInt(promptObj.style.width) / 2) - 12;

  // create an H1 element as the title bar
  h1 = promptObj.appendChild(d.createElement("h1"));
  h1.appendChild(d.createTextNode(PROMPT_TITLE));

  // create a div element to contain the txt argument
  msg = promptObj.appendChild(d.createElement("div"));
  msg.id = "alertText";
  // msg.appendChild(d.createTextNode(txt));
  msg.innerHTML = txt;

  // create a form element to contain the input field(s)
  formObj = msg.appendChild(d.createElement("form"));
  formObj.name = "promptForm";
  formObj.id = "promptForm";
  if (PROMPT_INPUT == "single") {
    fieldObj = formObj.appendChild(d.createElement("input"));
    fieldObj.type = "text";
    fieldObj.size = parseInt(promptObj.style.width) / 10;
  }
  if (PROMPT_INPUT == "multiple") {
    fieldObj = formObj.appendChild(d.createElement("textarea"));
    fieldObj.rows = "4";
    fieldObj.cols = parseInt(promptObj.style.width) / 10;
  }
  fieldObj.name = "promptField";
  fieldObj.id = "promptField";

  // create a small div to be used to hold an error condition
  errorBox = msg.appendChild(d.createElement("div"));
  errorBox.id = "promptError";

  // create a box that will float at the bottom of the window.
  bbox1 = promptObj.appendChild(d.createElement("div"));
  bbox1.id = "buttonBoxLeft";
  bbox1.style.width = halfWidth + "px";
  // force the button to stay centered on the window.
  bbox1 = bbox1.appendChild(d.createElement("center"));
  // create an anchor element to use as the TRUE confirmation button.
  btn1 = bbox1.appendChild(d.createElement("a"));
  btn1.id = "trueBtn";
  // determine button size, set defaults as needed
  BUTTON_WIDTH = (PROMPT_TRUE_BUTTON_TEXT.length * 8) + 10; // 8px per character, plus padding
  if (BUTTON_WIDTH < 50) BUTTON_WIDTH = 50; // default size should be about 50 pixels
  if (BUTTON_WIDTH > halfWidth) BUTTON_WIDTH = halfWidth - 16; // max size, minus padding
  btn1.style.width = BUTTON_WIDTH + "px";
  btn1.innerHTML = PROMPT_TRUE_BUTTON_TEXT;
  btn1.href = "#";
  // set up the onclick event to remove the confirm when the anchor is clicked
  btn1.onclick = function() { removeCustomPrompt(true); return false; }

  // create a box that will float at the bottom of the window.
  bbox2 = promptObj.appendChild(d.createElement("div"));
  bbox2.id = "buttonBoxRight";
  bbox2.style.width = halfWidth + "px";
  // force the button to stay centered on the window.
  bbox2 = bbox2.appendChild(d.createElement("center"));
  // create an anchor element to use as the FALSE confirmation button.
  btn2 = bbox2.appendChild(d.createElement("a"));
  btn2.id = "falseBtn";
  // determine button size, set defaults as needed
  BUTTON_WIDTH = (PROMPT_FALSE_BUTTON_TEXT.length * 8) + 10; // 8px per character, plus padding
  if (BUTTON_WIDTH < 50) BUTTON_WIDTH = 50; // default size should be about 50 pixels
  if (BUTTON_WIDTH > halfWidth) BUTTON_WIDTH = halfWidth - 16; // max size, minus padding
  btn2.style.width = BUTTON_WIDTH + "px";
  btn2.innerHTML = PROMPT_FALSE_BUTTON_TEXT;
  btn2.href = "#";
  // set up the onclick event to remove the confirm when the anchor is clicked
  btn2.onclick = function() { removeCustomPrompt(false); return false; }

  promptObj.scrollIntoView();
}

// removes the custom alert from the DOM
function removeCustomPrompt(promptResult) {
  dialogActive = false;
  PROMPT_RESPONSE = promptResult; // Save the result into a variable as well.
  // If the user is continuing, then evaluate the value they entered.
  if (PROMPT_RESPONSE) {
    if (fieldObj) {
      PROMPT_VALUE = fieldObj.value;
      // We should have a real value now, so validate the datatype.
      if (!regexCheck(PROMPT_VALUE,eval(PROMPT_VALIDATION))) {
        if (errorBox) {
          // By default we want to show the message in-line with the dialog.
          errorBox.innerHTML = '<span class="error">' + PROMPT_BADVALMSG + '</span>';
        } else {
          // In case we can't show the message in-line, use an alert.
          alert(PROMPT_BADVALMSG);
        }
        // Exit on error--don't close the dialog yet.
        return false;
      } else if (!validateCustomPrompt(PROMPT_VALUE)) {
        if (errorBox) {
          // By default we want to show the message in-line with the dialog.
          errorBox.innerHTML = '<span class="error">' + PROMPT_BADVALMSG + '</span>';
        } else {
          // In case we can't show the message in-line, use an alert.
          alert(PROMPT_BADVALMSG);
        }
        // Exit on error--don't close the dialog yet.
        return false;
      }
    } else {
      // Just in case we cannot grab the user's input, act like the user cancelled the prompt.
      PROMPT_RESPONSE = false;
      showErrMsg("There was an error while capturing the prompt value.");
    }
  }
  document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer"));
  promptResponse(promptResult); // Call the followup function.
}

// Stub for callback function (override in your own code)
function validateCustomPrompt(inputResult) { return true; }

// Set a global flag that indicates this library has been loaded by the browser.
var LIB_DIALOGS_LOADED = true;

// End library