//////////////////// Global variables ////////////////////
var gDocRoot                     = '';
var gMediaDir                    = 'media';
var gCurrOpenTab                 = 'incident';
var gCurrMediaDiv                = 'incident';
var gMaxSelectedObservations     = 10;
var gSelectedObservations        = new Array;
var gSelectedFactors             = new Array;
var gCurrHighlightedObservations = new Array;
var gCurrHighlightedFactor       = '';
var gMaxFeedbackLevel            = 4;
var gCurrFeedbackLevel           = 1;
var gScenarioFinished            = 0;


// Pre-load tab images
incidentTab = new Image();
incidentTab.src = gMediaDir + "/incident_tab.gif";
incidentTabSelected = new Image();
incidentTabSelected.src = gMediaDir + "/incident_tab_selected.gif";
listenTab = new Image();
listenTab.src = gMediaDir + "/listen_tab.gif";
listenTabSelected = new Image();
listenTabSelected.src = gMediaDir + "/listen_tab_selected.gif";
readTab = new Image();
readTab.src = gMediaDir + "/read_tab.gif";
readTabSelected = new Image();
readTabSelected.src = gMediaDir + "/read_tab_selected.gif";
examineTab = new Image();
examineTab.src = gMediaDir + "/examine_tab.gif";
examineTabSelected = new Image();
examineTabSelected.src = gMediaDir + "/examine_tab_selected.gif";
observationsTab = new Image();
observationsTab.src = gMediaDir + "/observations_tab.gif";
observationsTabSelected = new Image();
observationsTabSelected.src = gMediaDir + "/observations_tab_selected.gif";
feedbackTab = new Image();
feedbackTab.src = gMediaDir + "/feedback_tab.gif";
feedbackTabSelected = new Image();
feedbackTabSelected.src = gMediaDir + "/feedback_tab_selected.gif";
if (gCurrModule == 'use') {
  itacTab = new Image();
  itacTab.src = gMediaDir + "/itac_tab_use.gif";
  itacTabSelected = new Image();
  itacTabSelected.src = gMediaDir + "/itac_tab_use_selected.gif";
}
if (gCurrModule == 'master') {
  itacTab = new Image();
  itacTab.src = gMediaDir + "/itac_tab_master.gif";
  itacTabSelected = new Image();
  itacTabSelected.src = gMediaDir + "/itac_tab_master_selected.gif";
}


/////////////// Functions to show/hide divs ///////////////
function reDo() {
  // Refreshes the page layout for browsers that don't do that automatically
  window.location.reload();
} // function reDo

window.onresize = reDo;

// Initialize global variables
var gBrowserSupport = null;
var gNewBrowser     = true;
var gInitOK         = false;

function init() {
  // Define globals for cross-browser support
  if (document.getElementById) {
    divRef="document.getElementById";
    styleSwitch=".style";
    visibleVar="visible";
    gBrowserSupport="dom1";
  }
  else if (document.layers) {
    divRef="document.layers";
    styleSwitch="";
    visibleVar="show";
    gBrowserSupport="ns4";
  }
  else if (document.all) {
    divRef="document.all";
    styleSwitch=".style";
    visibleVar="visible";
    gBrowserSupport="ie4";
  }
  else {
    gBrowserSupport="none";
    gNewBrowser=false;
  }

  // Show/Hide special page elements according to the current module
  if ((gCurrModule == "discover") || (gCurrModule == "master")) {
    // Show "Selected Observations" div, if it exists
    if (eval("document.getElementById('selected_observations')") != null) {
      document.getElementById('selected_observations').style.display = "block";
    }
  }

  gInitOK = true;
} // function init

function showDiv(divName) {
  if(gInitOK) {
    if (gBrowserSupport == "none") {
      return;
    }
    else if (gBrowserSupport == "dom1") {
      document.getElementById(divName).style.display = "block";
    }
    else {
      eval(divRef+'["'+divName+'"]'+styleSwitch+'.display = "block"');
    }
  }
  else {
    return;
  }
} // function showDiv

function hideDiv(divName) {
  if(gInitOK) {
    if (gBrowserSupport == "none") {
      return;
    }
    else if (gBrowserSupport == "dom1") {
      document.getElementById(divName).style.display="none";
    }
    else {
      eval(divRef+'["'+divName+'"]'+styleSwitch+'.display="none"');
    }
  }
  else {
    return;
  }
} // function hideDiv

function onLoad() {
  init();
}


/////////////// Functions for controlling tabs ///////////////
function displayNavButtons() {
  // "Home" button
  document.writeln('  <div id="navButtons">');
  document.writeln('    <a href="' + gDocRoot + '/home.html"');
  document.writeln('      onMouseOver="document.homeBtn.src=\'' + gMediaDir + '/banner/home_mo.gif\'"');
  document.writeln('      onMouseOut="document.homeBtn.src=\'' + gMediaDir + '/banner/home.gif\'"><img');
  document.writeln('      name="homeBtn" src="' + gMediaDir + '/banner/home.gif" width="50" height="38" alt="Home"></a><a');

  if (gCurrModule == "discover") {
    document.writeln('    href="' + gDocRoot + '/discover.html"><img');
    document.writeln('      name="discoverBtn" src="' + gMediaDir + '/banner/discover_mo.gif" width="95" height="38" alt="Discover Contributors"></a><a');
    document.writeln('    href="' + gDocRoot + '/use.html"');
    document.writeln('      onMouseOver="document.useBtn.src=\'' + gMediaDir + '/banner/use_mo.gif\'"');
    document.writeln('      onMouseOut="document.useBtn.src=\'' + gMediaDir + '/banner/use.gif\'"><img');
    document.writeln('      name="useBtn" src="' + gMediaDir + '/banner/use.gif" width="95" height="38" alt="Use Contributors"></a><a');
    document.writeln('    href="' + gDocRoot + '/master.html"');
    document.writeln('      onMouseOver="document.masterBtn.src=\'' + gMediaDir + '/banner/master_mo.gif\'"');
    document.writeln('      onMouseOut="document.masterBtn.src=\'' + gMediaDir + '/banner/master.gif\'"><img');
    document.writeln('      name="masterBtn" src="' + gMediaDir + '/banner/master.gif" width="95" height="38" alt="Master Contributors"></a><a');
  }
  else if (gCurrModule == "use") {
    document.writeln('    href="' + gDocRoot + '/discover.html"');
    document.writeln('      onMouseOver="document.discoverBtn.src=\'' + gMediaDir + '/banner/discover_mo.gif\'"');
    document.writeln('      onMouseOut="document.discoverBtn.src=\'' + gMediaDir + '/banner/discover.gif\'"><img');
    document.writeln('      name="discoverBtn" src="' + gMediaDir + '/banner/discover.gif" width="95" height="38" alt="Discover Contributors"></a><a');
    document.writeln('    href="' + gDocRoot + '/use.html"><img');
    document.writeln('      name="useBtn" src="' + gMediaDir + '/banner/use_mo.gif" width="95" height="38" alt="Use Contributors"></a><a');
    document.writeln('    href="' + gDocRoot + '/master.html"');
    document.writeln('      onMouseOver="document.masterBtn.src=\'' + gMediaDir + '/banner/master_mo.gif\'"');
    document.writeln('      onMouseOut="document.masterBtn.src=\'' + gMediaDir + '/banner/master.gif\'"><img');
    document.writeln('      name="masterBtn" src="' + gMediaDir + '/banner/master.gif" width="95" height="38" alt="Master Contributors"></a><a');
  }
  else if (gCurrModule == "master") {
    document.writeln('    href="' + gDocRoot + '/discover.html"');
    document.writeln('      onMouseOver="document.discoverBtn.src=\'' + gMediaDir + '/banner/discover_mo.gif\'"');
    document.writeln('      onMouseOut="document.discoverBtn.src=\'' + gMediaDir + '/banner/discover.gif\'"><img');
    document.writeln('      name="discoverBtn" src="' + gMediaDir + '/banner/discover.gif" width="95" height="38" alt="Discover Contributors"></a><a');
    document.writeln('    href="' + gDocRoot + '/use.html"');
    document.writeln('      onMouseOver="document.useBtn.src=\'' + gMediaDir + '/banner/use_mo.gif\'"');
    document.writeln('      onMouseOut="document.useBtn.src=\'' + gMediaDir + '/banner/use.gif\'"><img');
    document.writeln('      name="useBtn" src="' + gMediaDir + '/banner/use.gif" width="95" height="38" alt="Use Contributors"></a><a');
    document.writeln('    href="' + gDocRoot + '/master.html"><img');
    document.writeln('      name="masterBtn" src="' + gMediaDir + '/banner/master_mo.gif" width="95" height="38" alt="Master Contributors"></a><a');
  }

  // "Resources" button
  document.writeln('    href="' + gDocRoot + '/resources.html"');
  document.writeln('      onMouseOver="document.resourcesBtn.src=\'' + gMediaDir + '/banner/resources_mo.gif\'"');
  document.writeln('      onMouseOut="document.resourcesBtn.src=\'' + gMediaDir + '/banner/resources.gif\'"><img');
  document.writeln('      name="resourcesBtn" src="' + gMediaDir + '/banner/resources.gif" width="95" height="38" alt="Resources"></a>');
  document.writeln('  </div>');
} // function displayNavButtons

function displayTabs() {
  // Tabs common to all modules
  document.writeln('    <div id="tabs">');
  document.writeln('      <a href="javascript:void(0);" onClick="toggleTab(\'incident\')"><img name="incident" id="incident_open"');
  document.writeln('      src="' + gMediaDir + '/incident_tab_selected.gif" width="39" height="72" border="0" alt="Incident"></a>');
  document.writeln('      <a href="javascript:void(0);" onClick="toggleTab(\'listen\')"><img name="listen" id="listen_closed"');
  document.writeln('      src="' + gMediaDir + '/listen_tab.gif" width="39" height="62" border="0" alt="Listen"></a>');
  document.writeln('      <a href="javascript:void(0);" onClick="toggleTab(\'read\')"><img name="read" id="read_closed"');
  document.writeln('      src="' + gMediaDir + '/read_tab.gif" width="39" height="58" border="0" alt="Read"></a>');
  document.writeln('      <a href="javascript:void(0);" onClick="toggleTab(\'examine\')"><img name="examine" id="examine_closed"');
  document.writeln('      src="' + gMediaDir + '/examine_tab.gif" width="39" height="80" border="0" alt="Examine"></a>');

  if (gCurrModule == 'discover') {
    document.writeln('      <a href="javascript:void(0);" onClick="toggleTab(\'observations\')"><img name="observations" id="observations_closed"');
    document.writeln('      src="' + gMediaDir + '/observations_tab.gif" width="39" height="105" border="0" alt="Observations"></a>');
    document.writeln('      <a href="javascript:void(0);" onClick="toggleTab(\'feedback\')"><img name="feedback" id="feedback_closed"');
    document.writeln('      src="' + gMediaDir + '/feedback_tab.gif" width="39" height="81" border="0" alt="Feedback"></a>');
  }
  else if (gCurrModule == 'use') {
    document.writeln('      <a href="javascript:void(0);" onClick="toggleTab(\'itac\')"><img name="itac" id="itac_closed"');
    document.writeln('      src="' + gMediaDir + '/itac_tab_use.gif" width="39" height="92" border="0" alt="ITAC Form"></a>');
  }
  else if (gCurrModule == 'master') {
    document.writeln('      <a href="javascript:void(0);" onClick="toggleTab(\'observations\')"><img name="observations" id="observations_closed"');
    document.writeln('      src="' + gMediaDir + '/observations_tab.gif" width="39" height="105" border="0" alt="Observations"></a>');
    document.writeln('      <a href="javascript:void(0);" onClick="toggleTab(\'itac\')"><img name="itac" id="itac_closed"');
    document.writeln('      src="' + gMediaDir + '/itac_tab_master.gif" width="39" height="88" border="0" alt="ITAC Form"></a>');
  }
  document.writeln('    </div>');
} // function displayTabs

function displayInstructions() {
// Displays the scenario instructions for each module
  if (gCurrModule == "discover") {
    document.writeln('      <div class="tab_body" style="text-align: left;">');
    document.writeln('        <p>Examine the materials available to you and select all observations,');
    document.writeln('        within the categories under the Observations tab, that you believe may');
    document.writeln('        have contributed to the reported incident.</p>');
    document.writeln('        <p>When you have finished selecting your observations, check your');
    document.writeln('        answers by clicking the "Submit Observations" button. You will have');
    document.writeln('        three tries to find all relevant observations.</p>');
    document.writeln('        <p>Select a tab on the left to begin.</p>');
    document.writeln('      </div>');
  }
  else if (gCurrModule == "use") {
    document.writeln('      <div class="tab_body" style="text-align: left;">');
    document.writeln('        <p>Examine the materials available to you and determine which ESTHER');
    document.writeln('        human error contributors apply to the reported incident. Mark your');
    document.writeln('        answers on the ITAC tab.</p>');
    document.writeln('        <p>You will have three tries to find all relevant human error');
    document.writeln('        contributors—if you are unsuccessful, you will be directed to work this');
    document.writeln('        scenario in the Discover Contributors module.</p>');
    document.writeln('        <p>Select a tab on the left to begin.</p>');
    document.writeln('      </div>');
  }
  else if (gCurrModule == "master") {
    document.writeln('      <div class="tab_body" style="text-align: left;">');
    document.writeln('        <p>Examine the materials available to you and select all observations,');
    document.writeln('        within the categories under the Observations tab, that you believe may');
    document.writeln('        have contributed to the reported incident.</p>');
    document.writeln('        <p>When you have finished selecting your observations, check your');
    document.writeln('        answers by clicking the "Submit Observations" button. You will have');
    document.writeln('        three tries to find all relevant observations.</p>');
    document.writeln('        <p>Select a tab on the left to begin.</p>');
    document.writeln('      </div>');
  }
} // function displayInstructions

function toggleTab(tab) {
  var currID = eval("document." + tab + ".id");
  var tabImage = '';

  if ((gCurrOpenTab) && (gCurrMediaDiv)) {
    // Hide content and media associated with currently open tab
    hideDiv(gCurrOpenTab + "_tab_contents");
    hideDiv(gCurrOpenTab + "_media_description");
    hideDiv(gCurrOpenTab + "_media_instructions");
    hideDiv(gCurrOpenTab + "_media");

    // Hide media that was last displayed
    hideDiv(gCurrMediaDiv + "_media_description");
    if (gScenarioFinished && eval("document.getElementById('" + gCurrMediaDiv + "_answers_media')") != null) {
      // Show media with highlighted answers, if it's available
      hideDiv(gCurrMediaDiv + "_answers_media");
    }
    else {
      hideDiv(gCurrMediaDiv + "_media");
    }

    // Hide audio and question icons and questions and answers, if needed
    if (/^listen\d+/.test(gCurrMediaDiv)) {
      hideDiv(gCurrMediaDiv + "_audio");

      if (gCurrModule == "master") {
        hideDiv(gCurrMediaDiv + "_questions");
        hideDiv('questions');
        hideDiv('answers');
      }
    }

    // Clear out gCurrMediaDiv
    gCurrMediaDiv = '';
  }

  if (/_closed/.test(currID)) {
    if (gCurrOpenTab) {
      // Close currently opened tab
      eval("document." + gCurrOpenTab + ".id = '" + gCurrOpenTab + "_closed'");

      // Display unselected tab image
      document.getElementById(gCurrOpenTab + "_closed").src = eval(gCurrOpenTab + "Tab.src");
    }

    // Open specified tab
    eval("document." + tab + ".id = '" + tab + "_open'");

    // Display selected tab image
    document.getElementById(tab + "_open").src = eval(tab + "TabSelected.src");

    // Show content and media associated with the specified tab
    showDiv(tab + "_tab_contents");
    showDiv(tab + "_media_instructions");
    showDiv(tab + "_media_description");
    showDiv(tab + "_media");

    // Save current opened tab
    gCurrOpenTab = tab;
    gCurrMediaDiv = tab;
  }
  else if ((/_open/.test(currID)) && (tab == gCurrOpenTab)) {
    // Close the specified tab
    eval("document." + tab + ".id = '" + tab + "_closed'");

    // Display unselected tab image
    document.getElementById(tab).src = eval(tab + "Tab.src");

    // All tabs are closed - Show blank content and media
    showDiv("blank_tab_contents");
    showDiv("blank_media_description");
    showDiv("blank_media_instructions");
    showDiv("blank_media");

    // Reset current opened tab
    gCurrOpenTab = '';
    gCurrMediaDiv = '';
  }
} // function toggleTab

function loadMedia(divBaseName) {
// Replaces the content currently in the media and media description
// fields with that associated with the specified link.
  if (gCurrMediaDiv) {
    // Hide media for the current div
    hideDiv(gCurrMediaDiv + "_media_description");

    if (gScenarioFinished && eval("document.getElementById('" + gCurrMediaDiv + "_answers_media')") != null) {
      // Show media with highlighted answers, if it's available
      hideDiv(gCurrMediaDiv + "_answers_media");
    }
    else {
      hideDiv(gCurrMediaDiv + "_media");
    }

    // Hide audio and question icon
    if (/^listen/.test(gCurrMediaDiv)) {
      hideDiv(gCurrMediaDiv + "_audio");

      if (gCurrModule == "master") {
        hideDiv(gCurrMediaDiv + "_questions");
      }
    }
  }

  // Show media for the specified div
  showDiv(divBaseName + "_media_description");
  if (gScenarioFinished && eval("document.getElementById('" + divBaseName + "_answers_media')") != null) {
    // Show media with highlighted answers, if it's available
    showDiv(divBaseName + "_answers_media");
  }
  else {
    showDiv(divBaseName + "_media");
  }

  // Show audio and question icons if the Listen tab is open
  if (/^listen/.test(divBaseName)) {
    showDiv(divBaseName + "_audio");

    // Is this a Master Contributors scenario?
    if (gCurrModule == "master") {
      showDiv(divBaseName + "_questions");

      // Hide questions and answers if they are currently showing
      hideDiv('questions');
      hideDiv('answers');
    }
  }

  // Save current div
  gCurrMediaDiv = divBaseName;
} // function loadMedia


/////////////// Functions for observation selection ///////////////
function buildObservationCategories() {
// Writes the HTML for each of the observation category lists
  // Observation categories only apply to the "discover" and "master" modules
  if (gCurrModule == 'use') {
    return;
  }

  // Build HTML
  document.writeln('<div id="observations1_media_description" class="media_description" style="display: none;">');
  document.writeln('  ' + gScenarioTitle);
  document.writeln('</div>');
  document.writeln('');
  document.writeln('<div id="observations1_media" class="media" style="display: none;">');
  document.writeln('  <div class="observation_category">');
  document.writeln('    <div class="observation_category_heading">Data Flow Observations</div>');
  document.writeln('    <div class="observation_list">');
  for(i = 0; i < totalCategory1Observations; i++) {
    document.writeln('      <a id="ol' + i + '" class="ol_unselected" href="javascript:selectObservation(' + i + ')">' + gObservations[i] +  '</a><br>');
  }
  document.writeln('    </div>');
  document.writeln('  </div>');
  document.writeln('</div>');
  document.writeln('');
  document.writeln('<div id="observations2_media_description" class="media_description" style="display: none;">');
  document.writeln('  ' + gScenarioTitle);
  document.writeln('</div>');
  document.writeln('');
  document.writeln('<div id="observations2_media" class="media" style="display: none;">');
  document.writeln('  <div class="observation_category">');
  document.writeln('    <div class="observation_category_heading">Work Setting Observations</div>');
  document.writeln('    <div class="observation_list">');
  for(i = 0; i < totalCategory2Observations; i++) {
    j = i + totalCategory1Observations;
    document.writeln('      <a id="ol' + j + '" class="ol_unselected" href="javascript:selectObservation(' + j + ')">' + gObservations[j] +  '</a><br>');
  }
  document.writeln('    </div>');
  document.writeln('  </div>');
  document.writeln('</div>');
  document.writeln('');
  document.writeln('<div id="observations3_media_description" class="media_description" style="display: none;">');
  document.writeln('  ' + gScenarioTitle);
  document.writeln('</div>');
  document.writeln('');
  document.writeln('<div id="observations3_media" class="media" style="display: none;">');
  document.writeln('  <div class="observation_category">');
  document.writeln('    <div class="observation_category_heading">Work Planning/Control Observations</div>');
  document.writeln('    <div class="observation_list">');
  for(i = 0; i < totalCategory3Observations; i++) {
    j = i + totalCategory1Observations + totalCategory2Observations;
    document.writeln('      <a id="ol' + j + '" class="ol_unselected" href="javascript:selectObservation(' + j + ')">' + gObservations[j] +  '</a><br>');
  }
  document.writeln('    </div>');
  document.writeln('  </div>');
  document.writeln('</div>');
  document.writeln('');
  document.writeln('<div id="observations4_media_description" class="media_description" style="display: none;">');
  document.writeln('  ' + gScenarioTitle);
  document.writeln('</div>');
  document.writeln('');
  document.writeln('<div id="observations4_media" class="media" style="display: none;">');
  document.writeln('  <div class="observation_category">');
  document.writeln('    <div class="observation_category_heading">Employee Readiness Observations</div>');
  document.writeln('    <div class="observation_list">');
  for(i = 0; i < totalCategory4Observations; i++) {
    j = i + totalCategory1Observations + totalCategory2Observations + totalCategory3Observations;
    document.writeln('      <a id="ol' + j + '" class="ol_unselected" href="javascript:selectObservation(' + j + ')">' + gObservations[j] +  '</a><br>');
  }
  document.writeln('    </div>');
  document.writeln('  </div>');
  document.writeln('</div>');
} // function buildObservationCategories

function buildObservationSelectionList() {
// Generates a list of links for each observation specified in the
// gObservations array
  // Observation categories only apply to the "discover" and "master" modules
  if (gCurrModule == 'use') {
    return;
  }

  for (var i = 0; i < gTotalObservations; i++) {
    document.writeln('<div id="observation' + i + '" class="unselected"><input type="checkbox" name="cb' + i + '"> ' + gObservations[i] + '</div>');
  }
} // function buildObservationSelectionList

function selectObservation(observationNumber) {
// Adds the selected observation to the user's selection list
  // Is the scenario already finished?
  if (gScenarioFinished) {
    // Observations can't be selected after the scenario is finished
    return;
  }

  // Check number of selected observations
  if (gSelectedObservations.length == gMaxSelectedObservations) {
    alert("You may only select " + gMaxSelectedObservations + " observations\nYou must delete some observations from your list before selecting others.");
    return;
  }

  // Make sure this observation isn't already selected
  if (!gSelectedObservations.exists(observationNumber)) {
    // Add this observation to the list of selected observations
    gSelectedObservations.push(observationNumber);

    // Adds the specified observation to the selection list
    document.getElementById("observation" + observationNumber).className = "selected";
  }

  // Sort selection list
  gSelectedObservations.sort(byNumber);

  // Make sure "Delete checked items" link is visible
  showDiv("delete_items_link");

  // Enable "Check Observations" button
  enableCheckObservationsButton();

  // Highlight selected observation in observation category list
  document.getElementById("ol" + observationNumber).className = "ol_selected";
} // function selectObservation

function deselectObservations() {
// Removes all checked observations from the selection list
  var updatedList = new Array;

  for(i = 0; i < gSelectedObservations.length; i++) {
    if (eval("document.observationForm.cb" + gSelectedObservations[i] + ".checked")) {
      // Hide checked observation
      document.getElementById("observation" + gSelectedObservations[i]).className = "unselected";

      // Uncheck the checkbox associated with this observation
      eval("document.observationForm.cb" + gSelectedObservations[i] + ".checked = false");

      // Unhighlight selected observation in observation category list
      document.getElementById("ol" + gSelectedObservations[i]).className = "ol_unselected";
    }
    else {
      // Add only unchecked observations to the updated selection list
      updatedList.push(gSelectedObservations[i]);
    }
  }
  gSelectedObservations = updatedList;

  // Enable "Check Observations" button
  enableCheckObservationsButton();
} // function deselectObservations

function enableCheckObservationsButton() {
  if (gCurrFeedbackLevel <= gMaxFeedbackLevel) {
    document.getElementById("submitBtn").style.display = "block";
    document.observationForm.submit.disabled = false;
  }
} // function enableCheckObservationsButton

function checkObservations(scenario) {
// Compares selected observations with those in the list of correct
// observations for this scenario
  var feedback            = '';
  var incorrect           = false;
  var missing             = false;
  var missingObservations = new Array;

  // Make sure list of correct observations is sorted
  gCorrectObservations.sort(byNumber);

  // Compare selected list with correct list
  if (gSelectedObservations.compareArrays(gCorrectObservations)) {
    // The user got all observations correct
    highlightCorrectObservations(gSelectedObservations);

    // Display a congratulations message
    feedback  = "<h4>Good job!</h4>";
    feedback += "You have correctly identified all observations that apply to this scenario.<br>";

    // Set feedback level to highest level
    gCurrFeedbackLevel = gMaxFeedbackLevel;
  }
  else {
    // Not all observations are correct
    // Highlight selected observations appropriately
    for (var i = 0; i < gSelectedObservations.length; i++) {
      var observation = "observation" + gSelectedObservations[i];
      if (gCurrFeedbackLevel > 1) {
        if (gCorrectObservations.exists(gSelectedObservations[i])) {
          document.getElementById(observation).className = "correct";
        }
        else {
          document.getElementById(observation).className = "incorrect";
          incorrect = true;
        }
      }
      else if (!gCorrectObservations.exists(gSelectedObservations[i])) {
        incorrect = true;
      }
    }

    // Check for missing observations
    for (var i = 0; i < gCorrectObservations.length; i++) {
      if (!gSelectedObservations.exists(gCorrectObservations[i])) {
        missing = true;

        // Add this observation to the list of missing observations
        missingObservations.push(gCorrectObservations[i]);
      }
    }

    // Generate appropriate feedback message
    feedback += "<div class='feedback_block'><h3>Response Feedback:</h3>\n<div class='feedback_content'>";
    if (incorrect) {
      feedback += "Some selected observations are not relevant to this scenario.\n";
    }
    if (missing) {
      feedback += "One or more relevant observations are missing.\n";
    }

    // Display feedback message
    if (gCurrFeedbackLevel == 1) {
      feedback += "Keep trying and you'll find all of the relevant observations.<br>\n";
    }
    else if (gCurrFeedbackLevel == 2) {
      // Display general hints
      feedback += "Make your corrections and continue to review the material to complete the list.<br>\n";
    }
    else if (gCurrFeedbackLevel == 3) {
      // Display more specific hints
      feedback += "Keep trying. Review the evidence again to find any other relevant observations.<br>\n";
    }
    else if (gCurrFeedbackLevel == 4) {
      feedback += "<br>\n";
    }
  }

  if (gCurrFeedbackLevel > 1) {
    // Display feedback for each selected observation
    feedback += getgObservationFeedback();
    feedback += "</div>\n</div>\n";

    if ((missing) && (gCurrFeedbackLevel < gMaxFeedbackLevel)) {
      // Get hints for the missing factors
      feedback += "<div class='feedback_block'><h3>Hints:</h3>\n<div class='feedback_content'>";
      var hints = new Array;
      hints = getHints('Observation', gCurrFeedbackLevel, missingObservations);
      for (i = 0; i < hints.length; i++) {
        feedback += "<li>" + hints[i] + "</li>\n";
      }
      feedback += "</div>\n</div>\n";
    }
  }
  else {
    feedback += "</div>\n</div>\n";
  }

  if (gCurrFeedbackLevel == gMaxFeedbackLevel) {
    // Display reference to highlighted notes
    feedback += "<div class='feedback_block'><h3>Notes:</h3>\n<div class='feedback_content'>";
    feedback += "Inspect the material in the tabs to see the relevant evidence highlighted with notes.\n";
    feedback += "</div>\n</div>\n";

    // Display a link to the ITAC form for the current scenario
    feedback += "<div class='feedback_block'><h3>ITAC:</h3>\n<div class='feedback_content'>";
    feedback += "View the final answers for this scenario displayed on a representation of a <a href='discover_itac/" + scenario + "_itac.html'>completed ITAC form.</a>\n";
    feedback += "</div>\n</div>\n";

    // Scenario is complete. Display the highlighted notes in the media files.
    gScenarioFinished = 1;
  }

  // Increment feedback level
  gCurrFeedbackLevel++;

  // Write feedback to stage area
  document.getElementById('feedback_media').innerHTML = feedback;

  // Open the Feedback tab
  if ((gCurrModule == 'discover') && (gCurrOpenTab != 'feedback')) {
    toggleTab('feedback');
  }

  // Hide "Delete checked items" link and submit button after the scenario
  // is finished and the media notes are displayed
  if (gScenarioFinished) {
    hideDiv("delete_items_link");
    document.getElementById('submitBtn').style.display = "none";
  }
  else {
    // Disable "Check Observations" button
    document.observationForm.submit.disabled = true;
  }
} // function checkObservations

function getgObservationFeedback() {
  var feedback = '';

  // Show comments for each observation in the user's selection list
  for (i = 0; i < gSelectedObservations.length; i++) {
    // Display selected observation
    feedback += '<br><span style="';
    if (gCorrectObservations.exists(gSelectedObservations[i])) {
      feedback += "color: green;";
    }
    else {
      feedback += "color: red;";
    }
    feedback += '">' + gObservations[gSelectedObservations[i]] + '</span> - ';

    // Display corresponding observation feedback
    if (gObservationFeedback[gSelectedObservations[i]] == 'NA') {
      feedback += "This does not apply";
    }
    else if (gObservationFeedback[gSelectedObservations[i]] == 'NE') {
      feedback += "There is no evidence of this";
    }
    else {
      feedback += gObservationFeedback[gSelectedObservations[i]];
    }
  }

  return feedback;
} // function getgObservationFeedback

function highlightCorrectObservations(selectedObservations) {
// Highlights all observations in the specified array to indicate they're correct
  for (var i = 0; i < selectedObservations.length; i++) {
    var observation = "observation" + selectedObservations[i];
    document.getElementById("observation" + selectedObservations[i]).className = "correct";
  }
} // function highlightCorrectObservations

function highlightCorrectFactors(selectedFactors) {
// Highlights all factors in the specified array to indicate they're correct
  for (var i = 0; i < selectedFactors.length; i++) {
    var factor = "factor" + selectedFactors[i];
    document.getElementById("factor" + selectedFactors[i]).className = "itac_correct";
  }
} // function highlightCorrectFactors

function getHints(module, feedbackLevel, missingItems) {
// Builds a list of hints for all missing observations or factors
// Note: module = "discover", "use", or "master"
  var hints = new Array;

  for (i = 0; i < missingItems.length; i++) {
    if (feedbackLevel == 2) {
      // Display general hints at feedback level 2
      hints.push(eval("gGeneral" + module + "Hint" + [missingItems[i]]) + "\n");
    }
    else if (feedbackLevel == 3) {
      // Display specific hints at feedback level 3
      hints.push(eval("gSpecific" + module + "Hint" + [missingItems[i]]) + "\n");
    }
  }

  // Remove duplicate hints from list
  hints = hints.removeDuplicates();

  return hints;
} // function getHints


/////////////// Functions for audio clips ///////////////
function playSound(file) {
  // IE Only
  document.all['BGSOUND_ID'].src=file;
} // function playSound

function stopSound() {
  // IE Only
  document.all['BGSOUND_ID'].src='silence.mid';
} // function stopSound


/////////// Functions for Module 3 Questions ////////////
function showQuestions(divBaseName) {
  var questions = "";

  var backLinkStr = '<div class="close"><a href="javascript:hideDiv(' + "'questions'" + '); hideDiv(' + "'answers'" + ');">Back to testimony</a></div>';
  var intro = backLinkStr;
  intro += '<div style="font: bold 15px Arial, Helvetica, sans-serif;">Questions</div>';
  intro += 'Click on the question(s) you wish to ask and a corresponding answer will be displayed:<br>';

  for (var i = 0; i < gQAList.length; i++) {
    if (!(i % 2)) {
      // This is a question
      // Get index of associated answer
      var a = i + 1;

      // Print question link
      questions += '<br>&bull; <a href="javascript:showAnswer(' + a + ')">' + gQAList[i] + "</a>\n";
    }
  }

  // Write intro text
  document.getElementById('questions').innerHTML = intro;

  // Write list of questions
  document.getElementById('questions').innerHTML += questions;

  // Show the questions pop-up
  showDiv('questions');

} // function showQuestions

function showAnswer(index) {
  var backLinkStr = '<div class="close"><a href="javascript:hideDiv(' + "'questions'" + '); hideDiv(' + "'answers'" + ');">Back to testimony</a></div>';
  var answer = backLinkStr;
  answer += '<div style="font: bold 15px Arial, Helvetica, sans-serif;">Answer:</div>';
  answer += gQAList[index];

  // Display answer to associated question
  document.getElementById('answers').innerHTML = answer;

  // Show the answer pop-up
  showDiv('answers');
} // function showAnswer


////////////////// ITAC Form Functions //////////////////
function itacBuildCorrectObservationsList() {
  for (var i = 0; i < gCorrectObservations.length; i++) {
    document.writeln('<div id="observation' + gCorrectObservations[i] + '" class="itac_unselected_observation" onClick="itacHighlightFactor(\'observation' + gCorrectObservations[i] + '\')">' + gObservations[gCorrectObservations[i]] + '</div>');
  }
} // function itacBuildCorrectObservationsList


function itacHighlightObservations(factor) {
  // Return if no factor object was specified
  if (!factor) {
    return;
  }

  // Get factor ID
  // (NOTE: The factor ID is not passed directly to this function so that
  // editing the scenario ITAC file will be easier for non-programmers.)
  var factorID = factor.id;

  // Unhighlight current factor and observations
  itacUnhighlight();

  // Highlight the current factor
  document.getElementById(factorID).className = "itac_selected_factor";

  // Highlight each observation associated with this contributing factor
  for (var i = 0; i < eval(factorID + "Observations.length"); i++) {
    var observationID = "observation" + eval(factorID + "Observations[" + i + "]");
    document.getElementById(observationID).className = "itac_selected_observation";
    gCurrHighlightedObservations.push(observationID);
  }

  // Display description associated with this contributing factor
  itacDisplayDescription(factorID);

  // Save current factor
  gCurrHighlightedFactor = factorID;
} // function itacHighlightObservations

function itacHighlightFactor(observationID) {
  // Unhighlight current factor and observations
  itacUnhighlight();

  // Highlight the current observation
  document.getElementById(observationID).className = "itac_selected_observation";

  // Highlight the contributing factor associated with this observation
  var factorID = "factor" + eval(observationID + "Factor");
  document.getElementById(factorID).className = "itac_selected_factor";

  // Display description associated with this contributing factor
  itacDisplayDescription(factorID);

  // Save current factor and observations
  gCurrHighlightedFactor = factorID;
  gCurrHighlightedObservations.push(observationID);
} // function itacHighlightFactor

function itacDisplayDescription(factorID) {
  var description = "<b>Description:</b><br>\n";
  description += eval(factorID + "Description");

  document.getElementById('itac_description').innerHTML = description;
} // function itacDisplayDescription

function itacUnhighlight () {
  // Unhighlight current factor and observations
  if (gCurrHighlightedFactor) {
    document.getElementById(gCurrHighlightedFactor).className = "itac_unselected_factor";
  }
  if (gCurrHighlightedObservations) {
    for (var i = 0; i < gCurrHighlightedObservations.length; i++) {
      document.getElementById(gCurrHighlightedObservations[i]).className = "itac_unselected_observation";
    }
    delete gCurrHighlightedObservations;
  }
  gCurrHighlightedObservations = new Array;
} // function itacUnhighlight

function buildITACForm() {
// Writes the table for the ITAC form in the "Discover Contributors" and
// "Use Contributors" scenarios, depending on the specified module
  if (gCurrModule == 'discover') {
    var correctFactorStr   = "          class=\"itac_unselected_factor\"\n";
    correctFactorStr      += "          onClick=\"itacHighlightObservations(this)\"><img\n";
    correctFactorStr      += "          src=\"" + gMediaDir + "/checkbox_checked.gif\" width=\"13\" height=\"13\">";

    var incorrectFactorStr = "          class=\"itac_grayed_out_factor\"\n";
    incorrectFactorStr    += "          onClick=\"itacHighlightObservations()\"><img\n";
    incorrectFactorStr    += "          src=\"" + gMediaDir + "/checkbox_disabled.gif\" width=\"13\" height=\"13\">";

    document.writeln('      <tr bgcolor="#dddddd">');
    document.writeln('        <th scope="col" width="150"><b>Data Flow</b></th>');
    document.writeln('        <th scope="col" width="150"><b>Work Setting</b></th>');
    document.writeln('        <th scope="col" width="150"><b>Work Planning/Control</b></th>');
    document.writeln('        <th scope="col" width="150"><b>Employee Readiness</b></th>');
    document.writeln('      </tr>');
    document.writeln('      <tr valign="top">');
    document.writeln('        <td id="factor0"');
    document.writeln('          title=\'Can be considered as "information available" vs "information acquired." It is the broadest of the information-related conditions.\'');
    gCorrectFactors.exists(0) ? document.writeln(correctFactorStr) : document.writeln(incorrectFactorStr);
    document.writeln('          Information');
    document.writeln('        </td>');

    document.writeln('        <td id="factor4"');
    document.writeln('          title="Events external to the worker"');
    gCorrectFactors.exists(4) ? document.writeln(correctFactorStr) : document.writeln(incorrectFactorStr);
    document.writeln('          Distractions');
    document.writeln('        </td>');

    document.writeln('        <td id="factor9"');
    document.writeln('          title="Many jobs are associated with various kinds of pressures; the key is to discover if these are too great for a particular worker at this point in time."');
    gCorrectFactors.exists(9) ? document.writeln(correctFactorStr) : document.writeln(incorrectFactorStr);
    document.writeln('          Job Pressure');
    document.writeln('        </td>');

    document.writeln('        <td id="factor19"');
    document.writeln('          title="Mental focus of the individual during performance of a security task."');
    gCorrectFactors.exists(19) ? document.writeln(correctFactorStr) : document.writeln(incorrectFactorStr);
    document.writeln('          Preoccupation/Inattention');
    document.writeln('        </td>');
    document.writeln('      </tr>');

    document.writeln('      <tr valign="top">');
    document.writeln('        <td id="factor1"');
    document.writeln('          title="A type of information inadequacy that focuses on formal procedures and official directives or guidance."');
    gCorrectFactors.exists(1) ? document.writeln(correctFactorStr) : document.writeln(incorrectFactorStr);
    document.writeln('          Procedures/Directions');
    document.writeln('        </td>');

    document.writeln('        <td id="factor5"');
    document.writeln('          title="Needed but unavailable or otherwise inadequate equipment or support"');
    gCorrectFactors.exists(5) ? document.writeln(correctFactorStr) : document.writeln(incorrectFactorStr);
    document.writeln('          Material/Resources');
    document.writeln('        </td>');

    document.writeln('        <td id="factor10"');
    document.writeln('          title="Clock/calendar variables are a type of job pressure"');
    gCorrectFactors.exists(10) ? document.writeln(correctFactorStr) : document.writeln(incorrectFactorStr);
    document.writeln('          Time Factors');
    document.writeln('        </td>');

    document.writeln('        <td id="factor20"');
    document.writeln('          title="Levels that are problematically high for a given individual and/or circumstance."');
    gCorrectFactors.exists(20) ? document.writeln(correctFactorStr) : document.writeln(incorrectFactorStr);
    document.writeln('          Stress/Anxiety');
    document.writeln('        </td>');
    document.writeln('      </tr>');

    document.writeln('      <tr valign="top">');
    document.writeln('        <td id="factor2"');
    document.writeln('          title="A type of information inadequacy in less formal information exchanges (but that could include, for example, written and verbal content)."');
    gCorrectFactors.exists(2) ? document.writeln(correctFactorStr) : document.writeln(incorrectFactorStr);
    document.writeln('          Communication');
    document.writeln('        </td>');

    document.writeln('        <td id="factor6"');
    document.writeln('          title="Indoor and outdoor workplace arrangements and conditions"');
    gCorrectFactors.exists(6) ? document.writeln(correctFactorStr) : document.writeln(incorrectFactorStr);
    document.writeln('          Environment');
    document.writeln('        </td>');

    document.writeln('        <td id="factor11"');
    document.writeln('          title="Many jobs are complex; the key is to determine if these are unusually so for a particular worker and/or under certain work conditions."');
    gCorrectFactors.exists(11) ? document.writeln(correctFactorStr) : document.writeln(incorrectFactorStr);
    document.writeln('          Task Difficulty');
    document.writeln('        </td>');

    document.writeln('        <td id="factor21"');
    document.writeln('          title="Includes both short- or long-term conditions"');
    gCorrectFactors.exists(21) ? document.writeln(correctFactorStr) : document.writeln(incorrectFactorStr);
    document.writeln('          Fatigue/Boredom');
    document.writeln('        </td>');
    document.writeln('      </tr>');

    document.writeln('      <tr valign="top">');
    document.writeln('        <td id="factor3"');
    document.writeln('          title="A type of information inadequacy that focuses on formal mechanisms intended to inform workers about existing conditions."');
    gCorrectFactors.exists(3) ? document.writeln(correctFactorStr) : document.writeln(incorrectFactorStr);
    document.writeln('          System Status/Feedback');
    document.writeln('        </td>');

    document.writeln('        <td id="factor7"');
    document.writeln('          title="Formal management processes and tools"');
    gCorrectFactors.exists(7) ? document.writeln(correctFactorStr) : document.writeln(incorrectFactorStr);
    document.writeln('          Management Systems');
    document.writeln('        </td>');

    document.writeln('        <td id="factor12"');
    document.writeln('          title="Individuals differ in their interpretation and response to conditions; some may dislike a given task that is acceptable to others."');
    gCorrectFactors.exists(12) ? document.writeln(correctFactorStr) : document.writeln(incorrectFactorStr);
    document.writeln('          Task Aversion');
    document.writeln('        </td>');

    document.writeln('        <td id="factor22"');
    document.writeln('          title="Includes temporary and chronic conditions as well as permanent disabilities."');
    gCorrectFactors.exists(22) ? document.writeln(correctFactorStr) : document.writeln(incorrectFactorStr);
    document.writeln('          Illness/Injury');
    document.writeln('        </td>');
    document.writeln('      </tr>');

    document.writeln('      <tr valign="top">');
    document.writeln('        <td>&nbsp;</td>');
    document.writeln('        <td id="factor8"');
    document.writeln('          title="Security views and behaviors within the organization"');
    gCorrectFactors.exists(8) ? document.writeln(correctFactorStr) : document.writeln(incorrectFactorStr);
    document.writeln('          Security Practices');
    document.writeln('        </td>');

    document.writeln('        <td id="factor13"');
    document.writeln('          title="Associated with changes initiated by the individual or the organization and perceived as positive or adverse."');
    gCorrectFactors.exists(13) ? document.writeln(correctFactorStr) : document.writeln(incorrectFactorStr);
    document.writeln('          Change in Routine');
    document.writeln('        </td>');

    document.writeln('        <td id="factor23"');
    document.writeln('          title="Includes alcohol, legal prescription, non-prescription, and illegal drugs."');
    gCorrectFactors.exists(23) ? document.writeln(correctFactorStr) : document.writeln(incorrectFactorStr);
    document.writeln('          Drug Side Effects');
    document.writeln('        </td>');
    document.writeln('      </tr>');

    document.writeln('      <tr valign="top">');
    document.writeln('        <td></td>');
    document.writeln('        <td></td>');
    document.writeln('        <td id="factor14"');
    document.writeln('          title="Planning of security tasks before taking action. Determination of breaches is possible only if such planning is required by formal procedure or policy."');
    gCorrectFactors.exists(14) ? document.writeln(correctFactorStr) : document.writeln(incorrectFactorStr);
    document.writeln('          Task Planning');
    document.writeln('        </td>');

    document.writeln('        <td id="factor24"');
    document.writeln('          title="Incorrect detection or identification of visual, auditory, or tactile information."');
    gCorrectFactors.exists(24) ? document.writeln(correctFactorStr) : document.writeln(incorrectFactorStr);
    document.writeln('          Misperception');
    document.writeln('        </td>');
    document.writeln('      </tr>');

    document.writeln('      <tr valign="top">');
    document.writeln('        <td></td>');
    document.writeln('        <td></td>');
    document.writeln('        <td id="factor15"');
    document.writeln('          title="Includes supervisory practices and responsibilities"');
    gCorrectFactors.exists(15) ? document.writeln(correctFactorStr) : document.writeln(incorrectFactorStr);
    document.writeln('          Management');
    document.writeln('        </td>');

    document.writeln('        <td id="factor25"');
    document.writeln('          title="Including, for example, inability to recall, inability to recall correctly, and inability to recall correctly in the required timeframe."');
    gCorrectFactors.exists(25) ? document.writeln(correctFactorStr) : document.writeln(incorrectFactorStr);
    document.writeln('          Memory');
    document.writeln('        </td>');
    document.writeln('      </tr>');

    document.writeln('      <tr valign="top">');
    document.writeln('        <td></td>');
    document.writeln('        <td></td>');
    document.writeln('        <td id="factor16"');
    document.writeln('          title="Ability diminished or lacking because of enduring physical or cognitive characteristics."');
    gCorrectFactors.exists(16) ? document.writeln(correctFactorStr) : document.writeln(incorrectFactorStr);
    document.writeln('          Ability');
    document.writeln('        </td>');

    document.writeln('        <td id="factor26"');
    document.writeln('          title=\'Rational thought or "intuition."\'');
    gCorrectFactors.exists(26) ? document.writeln(correctFactorStr) : document.writeln(incorrectFactorStr);
    document.writeln('          Reasoning/Judgment');
    document.writeln('        </td>');
    document.writeln('      </tr>');

    document.writeln('      <tr valign="top">');
    document.writeln('        <td></td>');
    document.writeln('        <td></td>');
    document.writeln('        <td id="factor17"');
    document.writeln('          title="Experience relates to an individual\'s degree of familiarity with a task. Skill relates to the level of proficiency attained."');
    gCorrectFactors.exists(17) ? document.writeln(correctFactorStr) : document.writeln(incorrectFactorStr);
    document.writeln('          Experience/Skill');
    document.writeln('        </td>');

    document.writeln('        <td id="factor27"');
    document.writeln('          title="An individual\'s principles, convictions, and/or feelings"');
    gCorrectFactors.exists(27) ? document.writeln(correctFactorStr) : document.writeln(incorrectFactorStr);
    document.writeln('          Values/Attitudes');
    document.writeln('        </td>');
    document.writeln('      </tr>');

    document.writeln('      <tr valign="top">');
    document.writeln('        <td></td>');
    document.writeln('        <td></td>');
    document.writeln('        <td id="factor18"');
    document.writeln('          title=\'The amount of information or degree of learning possessed by an individual. One might generally consider this as "information acquired" vs "information available."\'');
    gCorrectFactors.exists(18) ? document.writeln(correctFactorStr) : document.writeln(incorrectFactorStr);
    document.writeln('          Knowledge');
    document.writeln('        </td>');
    document.writeln('        <td>&nbsp;</td>');
    document.writeln('      </tr>');
  }

  else if ((gCurrModule == 'use') || (gCurrModule == 'master')) {
    document.writeln('        <form name="itacForm">');
    document.writeln('        <table id="itac_table" border="1" cellspacing="0" cellpadding="3">');
    document.writeln('          <tr bgcolor="#dddddd">');
    document.writeln('            <th scope="col" width="150"><b>Data Flow</b></th>');
    document.writeln('            <th scope="col" width="150"><b>Work Setting</b></th>');
    document.writeln('            <th scope="col" width="150"><b>Work Planning/Control</b></th>');
    document.writeln('            <th scope="col" width="150"><b>Employee Readiness</b></th>');
    document.writeln('          </tr>');
    document.writeln('          <tr valign="top">');
    document.writeln('            <td id="factor0"');
    document.writeln('              class="itac_unselected_factor"');
    document.writeln('              title=\'Can be considered as "information available" vs "information acquired." It is the broadest of the information-related conditions.\'>');
    document.writeln('              <input type="checkbox" onClick="enableCheckFactorsButton()" name="cb0">');
    document.writeln('              Information');
    document.writeln('            </td>');
    document.writeln('            <td id="factor4"');
    document.writeln('              class="itac_unselected_factor"');
    document.writeln('              title="Events external to the worker">');
    document.writeln('              <input type="checkbox" onClick="enableCheckFactorsButton()" name="cb4">');
    document.writeln('              Distractions');
    document.writeln('            </td>');
    document.writeln('            <td id="factor9"');
    document.writeln('              class="itac_unselected_factor"');
    document.writeln('              title="Many jobs are associated with various kinds of pressures; the key is to discover if these are too great for a particular worker at this point in time.">');
    document.writeln('              <input type="checkbox" onClick="enableCheckFactorsButton()" name="cb9">');
    document.writeln('              Job Pressure');
    document.writeln('            </td>');
    document.writeln('            <td id="factor19"');
    document.writeln('              class="itac_unselected_factor"');
    document.writeln('              title="Mental focus of the individual during performance of a security task.">');
    document.writeln('              <input type="checkbox" onClick="enableCheckFactorsButton()" name="cb19">');
    document.writeln('              Preoccupation/Inattention');
    document.writeln('            </td>');
    document.writeln('          </tr>');
    document.writeln('          <tr valign="top">');
    document.writeln('            <td id="factor1"');
    document.writeln('              class="itac_unselected_factor"');
    document.writeln('              title="A type of information inadequacy that focuses on formal procedures and official directives or guidance.">');
    document.writeln('              <input type="checkbox" onClick="enableCheckFactorsButton()" name="cb1">');
    document.writeln('              Procedures/Directions');
    document.writeln('            </td>');
    document.writeln('            <td id="factor5"');
    document.writeln('              class="itac_unselected_factor"');
    document.writeln('              title="Needed but unavailable or otherwise inadequate equipment or support">');
    document.writeln('              <input type="checkbox" onClick="enableCheckFactorsButton()" name="cb5">');
    document.writeln('              Material/Resources');
    document.writeln('            </td>');
    document.writeln('            <td id="factor10"');
    document.writeln('              class="itac_unselected_factor"');
    document.writeln('              title="Clock/calendar variables are a type of job pressure">');
    document.writeln('              <input type="checkbox" onClick="enableCheckFactorsButton()" name="cb10">');
    document.writeln('              Time Factors');
    document.writeln('            </td>');
    document.writeln('            <td id="factor20"');
    document.writeln('              class="itac_unselected_factor"');
    document.writeln('              title="Levels that are problematically high for a given individual and/or circumstance.">');
    document.writeln('              <input type="checkbox" onClick="enableCheckFactorsButton()" name="cb20">');
    document.writeln('              Stress/Anxiety');
    document.writeln('            </td>');
    document.writeln('          </tr>');
    document.writeln('          <tr valign="top">');
    document.writeln('            <td id="factor2"');
    document.writeln('              class="itac_unselected_factor"');
    document.writeln('              title="A type of information inadequacy in less formal information exchanges (but that could include, for example, written and verbal content).">');
    document.writeln('              <input type="checkbox" onClick="enableCheckFactorsButton()" name="cb2">');
    document.writeln('              Communication');
    document.writeln('            </td>');
    document.writeln('            <td id="factor6"');
    document.writeln('              class="itac_unselected_factor"');
    document.writeln('              title="Indoor and outdoor workplace arrangements and conditions">');
    document.writeln('              <input type="checkbox" onClick="enableCheckFactorsButton()" name="cb6">');
    document.writeln('              Environment');
    document.writeln('            </td>');
    document.writeln('            <td id="factor11"');
    document.writeln('              class="itac_unselected_factor"');
    document.writeln('              title="Many jobs are complex; the key is to determine if these are unusually so for a particular worker and/or under certain work conditions.">');
    document.writeln('              <input type="checkbox" onClick="enableCheckFactorsButton()" name="cb11">');
    document.writeln('              Task Difficulty');
    document.writeln('            </td>');
    document.writeln('            <td id="factor21"');
    document.writeln('              class="itac_unselected_factor"');
    document.writeln('              title="Includes both short- or long-term conditions">');
    document.writeln('              <input type="checkbox" onClick="enableCheckFactorsButton()" name="cb21">');
    document.writeln('              Fatigue/Boredom');
    document.writeln('            </td>');
    document.writeln('          </tr>');
    document.writeln('          <tr valign="top">');
    document.writeln('            <td id="factor3"');
    document.writeln('              class="itac_unselected_factor"');
    document.writeln('              title="A type of information inadequacy that focuses on formal mechanisms intended to inform workers about existing conditions.">');
    document.writeln('              <input type="checkbox" onClick="enableCheckFactorsButton()" name="cb3">');
    document.writeln('              System Status/Feedback');
    document.writeln('            </td>');
    document.writeln('            <td id="factor7"');
    document.writeln('              class="itac_unselected_factor"');
    document.writeln('              title="Formal management processes and tools">');
    document.writeln('              <input type="checkbox" onClick="enableCheckFactorsButton()" name="cb7">');
    document.writeln('              Management Systems');
    document.writeln('            </td>');
    document.writeln('            <td id="factor12"');
    document.writeln('              class="itac_unselected_factor"');
    document.writeln('              title="Individuals differ in their interpretation and response to conditions; some may dislike a given task that is acceptable to others.">');
    document.writeln('              <input type="checkbox" onClick="enableCheckFactorsButton()" name="cb12">');
    document.writeln('              Task Aversion');
    document.writeln('            </td>');
    document.writeln('            <td id="factor22"');
    document.writeln('              class="itac_unselected_factor"');
    document.writeln('              title="Includes temporary and chronic conditions as well as permanent disabilities.">');
    document.writeln('              <input type="checkbox" onClick="enableCheckFactorsButton()" name="cb22">');
    document.writeln('              Illness/Injury');
    document.writeln('            </td>');
    document.writeln('          </tr>');
    document.writeln('          <tr valign="top">');
    document.writeln('            <td>&nbsp;</td>');
    document.writeln('            <td id="factor8"');
    document.writeln('              class="itac_unselected_factor"');
    document.writeln('              title="Security views and behaviors within the organization">');
    document.writeln('              <input type="checkbox" onClick="enableCheckFactorsButton()" name="cb8">');
    document.writeln('              Security Practices');
    document.writeln('            </td>');
    document.writeln('            <td id="factor13"');
    document.writeln('              class="itac_unselected_factor"');
    document.writeln('              title="Associated with changes initiated by the individual or the organization and perceived as positive or adverse.">');
    document.writeln('              <input type="checkbox" onClick="enableCheckFactorsButton()" name="cb13">');
    document.writeln('              Change in Routine');
    document.writeln('            </td>');
    document.writeln('            <td id="factor23"');
    document.writeln('              class="itac_unselected_factor"');
    document.writeln('              title="Includes alcohol, legal prescription, non-prescription, and illegal drugs.">');
    document.writeln('              <input type="checkbox" onClick="enableCheckFactorsButton()" name="cb23">');
    document.writeln('              Drug Side Effects');
    document.writeln('            </td>');
    document.writeln('          </tr>');
    document.writeln('          <tr valign="top">');
    document.writeln('            <td></td>');
    document.writeln('            <td></td>');
    document.writeln('            <td id="factor14"');
    document.writeln('              class="itac_unselected_factor"');
    document.writeln('              title="Planning of security tasks before taking action. Determination of breaches is possible only if such planning is required by formal procedure or policy.">');
    document.writeln('              <input type="checkbox" onClick="enableCheckFactorsButton()" name="cb14">');
    document.writeln('              Task Planning');
    document.writeln('            </td>');
    document.writeln('            <td id="factor24"');
    document.writeln('              class="itac_unselected_factor"');
    document.writeln('              title="Incorrect detection or identification of visual, auditory, or tactile information.">');
    document.writeln('              <input type="checkbox" onClick="enableCheckFactorsButton()" name="cb24">');
    document.writeln('              Misperception');
    document.writeln('            </td>');
    document.writeln('          </tr>');
    document.writeln('          <tr valign="top">');
    document.writeln('            <td></td>');
    document.writeln('            <td></td>');
    document.writeln('            <td id="factor15"');
    document.writeln('              class="itac_unselected_factor"');
    document.writeln('              title="Includes supervisory practices and responsibilities">');
    document.writeln('              <input type="checkbox" onClick="enableCheckFactorsButton()" name="cb15">');
    document.writeln('              Management');
    document.writeln('            </td>');
    document.writeln('            <td id="factor25"');
    document.writeln('              class="itac_unselected_factor"');
    document.writeln('              title="Including, for example, inability to recall, inability to recall correctly, and inability to recall correctly in the required timeframe.">');
    document.writeln('              <input type="checkbox" onClick="enableCheckFactorsButton()" name="cb25">');
    document.writeln('              Memory');
    document.writeln('            </td>');
    document.writeln('          </tr>');
    document.writeln('          <tr valign="top">');
    document.writeln('            <td></td>');
    document.writeln('            <td></td>');
    document.writeln('            <td id="factor16"');
    document.writeln('              class="itac_unselected_factor"');
    document.writeln('              title="Ability diminished or lacking because of enduring physical or cognitive characteristics.">');
    document.writeln('              <input type="checkbox" onClick="enableCheckFactorsButton()" name="cb16">');
    document.writeln('              Ability');
    document.writeln('            </td>');
    document.writeln('            <td id="factor26"');
    document.writeln('              class="itac_unselected_factor"');
    document.writeln('              title=\'Rational thought or "intuition."\'>');
    document.writeln('              <input type="checkbox" onClick="enableCheckFactorsButton()" name="cb26">');
    document.writeln('              Reasoning/Judgment');
    document.writeln('            </td>');
    document.writeln('          </tr>');
    document.writeln('          <tr valign="top">');
    document.writeln('            <td></td>');
    document.writeln('            <td></td>');
    document.writeln('            <td id="factor17"');
    document.writeln('              class="itac_unselected_factor"');
    document.writeln('              title="Experience relates to an individual\'s degree of familiarity with a task. Skill relates to the level of proficiency attained.">');
    document.writeln('              <input type="checkbox" onClick="enableCheckFactorsButton()" name="cb17">');
    document.writeln('              Experience/Skill');
    document.writeln('            </td>');
    document.writeln('            <td id="factor27"');
    document.writeln('              class="itac_unselected_factor"');
    document.writeln('              title="An individual\'s principles, convictions, and/or feelings">');
    document.writeln('              <input type="checkbox" onClick="enableCheckFactorsButton()" name="cb27">');
    document.writeln('              Values/Attitudes');
    document.writeln('            </td>');
    document.writeln('          </tr>');
    document.writeln('          <tr valign="top">');
    document.writeln('            <td></td>');
    document.writeln('            <td></td>');
    document.writeln('            <td id="factor18"');
    document.writeln('              class="itac_unselected_factor"');
    document.writeln('              title=\'The amount of information or degree of learning possessed by an individual. One might generally consider this as "information acquired" vs "information available."\'>');
    document.writeln('              <input type="checkbox" onClick="enableCheckFactorsButton()" name="cb18">');
    document.writeln('              Knowledge');
    document.writeln('            </td>');
    document.writeln('            <td>&nbsp;</td>');
    document.writeln('          </tr>');
    document.writeln('        </table>');
    document.writeln('        </form>');
  }
} // function buildITACForm

function enableCheckFactorsButton() {
  if (gCurrFeedbackLevel <= gMaxFeedbackLevel) {
    document.checkFactorsBtnForm.checkFactorsBtn.disabled = false;
  }
} // function enableCheckFactorsButton

function checkFactors(scenario) {
// Compares selected contributing factors with those in the list of correct
// factors for this scenario
  var allFactorsCorrect = 0;
  var feedback          = '<b>Feedback:</b> ';
  var incorrect         = false;
  var missing           = false;
  var missingFactors    = new Array;

  // Clear out current list of selected factors
  gSelectedFactors = new Array;

  // Build list of selected factors
  for(var i = 0; i < gTotalFactors; i++) {
    if (eval("document.itacForm.cb" + i + ".checked")) {
      gSelectedFactors.push(i);
    }
    else {
      // Unhighlight this factor, if needed
      document.getElementById("factor" + i).className = "itac_unselected_factor";
    }
  }

  // Sort selection list
  gSelectedFactors.sort(byNumber);

  // Make sure list of correct factors is sorted
  gCorrectFactors.sort(byNumber);

  // Compare selected list with correct list
  if (gSelectedFactors.compareArrays(gCorrectFactors)) {
    // The user got all factors correct
    highlightCorrectFactors(gSelectedFactors);
    allFactorsCorrect = 1;

    // Display a congratulations message
    feedback += "Good job! You have correctly identified all contributing factors that apply to this scenario.<br>";

    // Set feedback level to highest level
    gCurrFeedbackLevel = gMaxFeedbackLevel;
  }
  else {
    // Not all factors are correct
    // Highlight selected factors appropriately
    for (i = 0; i < gSelectedFactors.length; i++) {
      var factor = "factor" + gSelectedFactors[i];
      if (gCurrFeedbackLevel > 1) {
        if (gCorrectFactors.exists(gSelectedFactors[i])) {
          document.getElementById(factor).className = "itac_correct";
        }
        else {
          document.getElementById(factor).className = "itac_incorrect";
          incorrect = true;
        }
      }
      else if (!gCorrectFactors.exists(gSelectedFactors[i])) {
        incorrect = true;
      }
    }

    // Check for missing factors
    for (i = 0; i < gCorrectFactors.length; i++) {
      if (!gSelectedFactors.exists(gCorrectFactors[i])) {
        missing = true;

        // Add this factor to the list of missing factors
        missingFactors.push(gCorrectFactors[i]);
      }
    }

    // Generate appropriate feedback message
    if (incorrect) {
      feedback += "Some selected factors are not relevant to this scenario.\n";
    }
    if (missing) {
      feedback += "One or more relevant factors are missing.\n";
    }

    // Display feedback message
    if (gCurrFeedbackLevel == 1) {
      feedback += "Keep trying and you'll find all of the relevant factors.\n";
    }
    else if (gCurrFeedbackLevel == 2) {
      // Display general hints
      feedback += "Make your corrections and continue to review the material to complete the list.\n";
    }
    else if (gCurrFeedbackLevel == 3) {
      // Display more specific hints
      feedback += "Keep trying. Review the evidence again to find any other relevant factors.\n";
    }
    else if (gCurrFeedbackLevel == 4) {
      feedback += "\n";
    }
  }

  if (gCurrFeedbackLevel > 1) {
    // Display hints for unselected factors
    if ((missing) && (gCurrFeedbackLevel < gMaxFeedbackLevel)) {
      feedback += "<b><i>Hint: </i></b>";
      // Get hints for the missing factors
      var hints = new Array;
      hints = getHints('Factor', gCurrFeedbackLevel, missingFactors);
      for (i = 0; i < hints.length; i++) {
        feedback += hints[i];
      }
    }
  }

  if (gCurrFeedbackLevel == gMaxFeedbackLevel) {
    // Did the user get all factors correct?
    if (allFactorsCorrect) {
      // Display reference to highlighted notes
      feedback += "Inspect the material in the tabs to see the relevant evidence highlighted with notes.\n";

      // Scenario is complete. Display the highlighted notes in the media files.
      gScenarioFinished = 1;
    }
    else {
      // Refer the user back to the "Discover Contributors" version of this scenario
      feedback += "Nice try, but you were not able to find all of the relevant ESTHER contributors for this scenario.\n";
      feedback += "You may want to <a href=\"" + gRelatedDiscoveryScenario + "\">work through this scenario in Discovery mode</a>.\n";
    }
  }

  // Increment feedback level
  gCurrFeedbackLevel++;

  // Write feedback
  document.getElementById('itac_feedback').innerHTML = feedback;

  // Disable "Check Factors" button
  document.checkFactorsBtnForm.checkFactorsBtn.disabled = true;
} // function checkFactors


/////////////// General Utility Functions ///////////////
function byNumber(a,b){
// Used by the array sort method to sort numerically
  return(a-b)
}

function changeCSS(myclass, element, value) {
// Modifies the value of the specified element in the specified class
// NOTE: This currently only modifies elements in the first stylesheet
//       defined in the current web page.
  var CSSRules;
  if (document.all) {
    CSSRules = 'rules';
  }
  else if (document.getElementById) {
    CSSRules = 'cssRules';
  }

  for (var i = 0; i < document.styleSheets[0][CSSRules].length; i++) {
    if (document.styleSheets[0][CSSRules][i].selectorText == myclass) {
      document.styleSheets[0][CSSRules][i].style[element] = value;
    }
  }
} // function changeCSS

function openScenario(scenarioURL, width, height) {
// Opens a new window containing the specified scenario and resizes that
// window to the specified width and height

  // Open scenario window
  scenarioWin = window.open(scenarioURL, "scenarioWin", "scrollbars=yes,menubar=yes,toolbar=no,location=no,directories=no,status=no,resizable=no");

  // Resize scenario window only if the specified width and height will fit the
  // user's current resolution
  if ((width <= screen.availWidth) && (height <= screen.availHeight)) {
    scenarioWin.moveTo(0,0);

    if (document.all) {
      scenarioWin.resizeTo(width, height);
    }
    else if (document.layers || document.getElementById) {
      if (scenarioWin.outerHeight < height || scenarioWin.outerWidth < width) {
        scenarioWin.outerHeight = height;
        scenarioWin.outerWidth = width;
      }
    }
  }
} // function openScenario

function myPlaySound(soundFile) {
// This method of embedding and playing audio files is more compatible with modern browsers
  document.getElementById("soundFileContainer").innerHTML =
    "<embed src='" + soundFile + "' hidden=true autostart=true loop=false>";
} // function myPlaySound


/////////////////// Method Prototypes ///////////////////
Array.prototype.compareArrays = function(arr) {
// Returns true if both arrays are identical
// Usage: array1.compareArrays(array2)
  if (this.length != arr.length) return false;
  for (var i = 0; i < arr.length; i++) {
    if (this[i].compareArrays) { // likely a nested array
      if (!this[i].compareArrays(arr[i])) return false;
      else continue;
    }
    if (this[i] != arr[i]) return false;
  }
  return true;
}

Array.prototype.exists = function (x) {
// Returns true if the specified value is an element of the specified array
// Usage: array1.exists(somevalue)
  for (var i = 0; i < this.length; i++) {
    if (this[i] == x) return true;
  }
  return false;
}

Array.prototype.removeDuplicates = function() {
// Removes duplicate elements from a given array
// Requires Array.prototype.indexOf
// Usage: Usage: array1 = array1.removeDuplicates()
  var found = new Array();
  for ( var i = 0; i < this.length; i++ ) {
    if ( found.indexOf( this[i] ) == -1 ) found.push( this[i] );
  }
  return found;
}

Array.prototype.indexOf = function(item) {
// Finds the index of the first occurence of item in the array, or -1 if not found
  for (var i = 0; i < this.length; i++) {
    if (this[i] == item) {
      return i;
    }
  }
  return -1;
}

