{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "ch08-preview-title",
   "metadata": {},
   "source": [
    "# Preview\n",
    "\n",
    "- Use these questions before class to check your familiarity with the chapter glossary and core terms.\n",
    "- Sign in from the account menu before you start answering the questions.\n",
    "- Multiple submissions are allowed. The highest score is kept.\n",
    "\n",
    "Review the [Chapter 8 glossary](../0800-probability-statistics.ipynb) before class. These ten questions mix multiple-choice and true/false: seven recognize terms and three connect related ideas. No calculations or code tracing are required.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch08-preview-quiz",
   "metadata": {},
   "source": [
    "<style>\n",
    ".ch08-preview-quiz { max-width: 900px; }\n",
    ".ch08-preview-question { border: 1px solid #d8dee4; border-radius: 6px; padding: 1rem; margin: 1rem 0; background: #fff; }\n",
    ".ch08-preview-question p { margin-top: 0; font-weight: 600; }\n",
    ".ch08-preview-question label { display: block; margin: 0.35rem 0; cursor: pointer; }\n",
    ".ch08-preview-question input { margin-right: 0.4rem; }\n",
    ".ch08-preview-actions { display: flex; gap: 0.75rem; align-items: center; margin: 1rem 0; flex-wrap: wrap; }\n",
    ".ch08-preview-actions button { border: 1px solid #176de8; border-radius: 6px; background: #176de8; color: white; padding: 0.55rem 0.9rem; cursor: pointer; font-weight: 600; }\n",
    ".ch08-preview-actions button.secondary { background: white; color: #176de8; }\n",
    ".ch08-preview-actions.is-locked { opacity: 0.55; }\n",
    ".ch08-preview-actions button:disabled { cursor: not-allowed; opacity: 0.65; }\n",
    ".ch08-preview-result { font-weight: 600; }\n",
    ".ch08-preview-feedback { margin-top: 0.65rem; font-weight: 600; }\n",
    ".ch08-preview-feedback.correct { color: #1a7f37; }\n",
    ".ch08-preview-feedback.incorrect { color: #cf222e; }\n",
    "</style>\n",
    "\n",
    "<div class='ch08-preview-quiz' id='ch08-preview-quiz' data-question-set-version='dsm-ch08-preview-2026-10-19-v2'>\n",
    "  <p>Earlier submissions and best scores are retained. If you already completed this Preview, you do not need to repeat it; you may retry the revised questions.</p>\n",
    "  <div id='ch08-preview-questions'></div>\n",
    "  <div class='ch08-preview-actions'>\n",
    "    <button type='button' id='ch08-preview-submit' disabled>Submit</button>\n",
    "    <button type='button' class='secondary' id='ch08-preview-reset'>Reset</button>\n",
    "    <span class='ch08-preview-result' id='ch08-preview-result' aria-live='polite'></span>\n",
    "  </div>\n",
    "</div>\n",
    "\n",
    "<script>\n",
    "(function () {\n",
    "  var quizId = 'ch08-preview';\n",
    "  var questionSetVersion = 'dsm-ch08-preview-2026-10-19-v2';\n",
    "  var answersUnlocked = false;\n",
    "  var attemptState = null;\n",
    "  var stateQueue = Promise.resolve();\n",
    "\n",
    "  function stateRequest(action, extra) {\n",
    "    return fetch('/api/v1/preview-options.php', {\n",
    "      method: 'POST', credentials: 'same-origin',\n",
    "      headers: { 'Content-Type': 'application/json' },\n",
    "      body: JSON.stringify(Object.assign({\n",
    "        assignment_id: quizId, version: questionSetVersion, action: action,\n",
    "        page: window.location.pathname.replace(/^\\/+/, '').replace(/\\.html$/, ''),\n",
    "        questions: authoredQuestions, legacy_questions: legacyQuestions, legacy_version: legacyVersion, historical_questions: historicalQuestions, historical_version: historicalVersion, token: attemptState && attemptState.token,\n",
    "        revision: attemptState && attemptState.revision\n",
    "      }, extra || {}))\n",
    "    }).then(function (response) {\n",
    "      return response.json().then(function (payload) {\n",
    "        if (!response.ok || !payload.ok) throw new Error(payload.error || 'Could not save Preview state.');\n",
    "        attemptState = payload.state;\n",
    "        return payload;\n",
    "      });\n",
    "    });\n",
    "  }\n",
    "\n",
    "  function draftAnswers(quiz) {\n",
    "    var answers = {};\n",
    "    questions.forEach(function (question) {\n",
    "      var input = quiz.querySelector('input[name=' + question.id + ']:checked');\n",
    "      if (input) answers[question.id] = input.value;\n",
    "    });\n",
    "    return answers;\n",
    "  }\n",
    "\n",
    "  function saveAnswers(quiz) {\n",
    "    var answers = draftAnswers(quiz);\n",
    "    stateQueue = stateQueue.catch(function () {}).then(function () {\n",
    "      return stateRequest('save', { answers: answers });\n",
    "    });\n",
    "    return stateQueue;\n",
    "  }\n",
    "  var questions = [\n",
    "  {\n",
    "    \"id\": \"q1\",\n",
    "    \"format\": \"multiple_choice\",\n",
    "    \"cognitive_level\": \"recognition\",\n",
    "    \"concepts\": [\n",
    "      \"Probability\",\n",
    "      \"Event\",\n",
    "      \"Outcome\",\n",
    "      \"Distribution\"\n",
    "    ],\n",
    "    \"prompt\": \"Which term names a numerical description of how likely a shipment is to arrive late?\",\n",
    "    \"choices\": {\n",
    "      \"A\": \"Event\",\n",
    "      \"B\": \"Outcome\",\n",
    "      \"C\": \"Distribution\",\n",
    "      \"D\": \"Probability\"\n",
    "    },\n",
    "    \"explanation\": \"Probability expresses likelihood as a number from 0 to 1. An outcome is a possible result, an event identifies results of interest, and a distribution describes the pattern across possible or observed values.\",\n",
    "    \"retry_hint\": \"Review the glossary entries for the language of chance, then reconsider what the question is asking you to name.\",\n",
    "    \"reading\": \"../0800-probability-statistics.html\"\n",
    "  },\n",
    "  {\n",
    "    \"id\": \"q2\",\n",
    "    \"format\": \"true_false\",\n",
    "    \"cognitive_level\": \"recognition\",\n",
    "    \"concepts\": [\n",
    "      \"Outcome\",\n",
    "      \"Sample space\"\n",
    "    ],\n",
    "    \"prompt\": \"True or false: For one randomly selected order, arriving on time can be one outcome.\",\n",
    "    \"choices\": {\n",
    "      \"A\": \"True\",\n",
    "      \"B\": \"False\"\n",
    "    },\n",
    "    \"explanation\": \"True. An outcome is one possible result of the process. Arriving on time is one possible result for the selected order; the sample space is the collection of all possible results in the model.\",\n",
    "    \"retry_hint\": \"Review the chance-model vocabulary before reconsidering this statement.\",\n",
    "    \"reading\": \"../0800-probability-statistics.html\"\n",
    "  },\n",
    "  {\n",
    "    \"id\": \"q3\",\n",
    "    \"format\": \"multiple_choice\",\n",
    "    \"cognitive_level\": \"recognition\",\n",
    "    \"concepts\": [\n",
    "      \"Chance model\",\n",
    "      \"Empirical distribution\"\n",
    "    ],\n",
    "    \"prompt\": \"Before generating any trial deliveries, an analyst represents a shipment as on time or late and assigns a chance to each possibility. What has the analyst specified?\",\n",
    "    \"choices\": {\n",
    "      \"A\": \"An empirical distribution\",\n",
    "      \"B\": \"A sample statistic\",\n",
    "      \"C\": \"A chance model\",\n",
    "      \"D\": \"A recorded observation\"\n",
    "    },\n",
    "    \"explanation\": \"A chance model specifies possible outcomes and their probabilities. The description gives a model, not a distribution of recorded deliveries. A simulation could use this model to generate trial deliveries later.\",\n",
    "    \"retry_hint\": \"Review the glossary distinction between a description of a random process and summaries of observations.\",\n",
    "    \"reading\": \"../0800-probability-statistics.html\"\n",
    "  },\n",
    "  {\n",
    "    \"id\": \"q4\",\n",
    "    \"format\": \"multiple_choice\",\n",
    "    \"cognitive_level\": \"recognition\",\n",
    "    \"concepts\": [\n",
    "      \"Empirical distribution\",\n",
    "      \"Chance model\",\n",
    "      \"Population\",\n",
    "      \"Simulation\"\n",
    "    ],\n",
    "    \"prompt\": \"A manager counts how frequently different delivery times occurred in last month's recorded shipments. What kind of distribution is being described?\",\n",
    "    \"choices\": {\n",
    "      \"A\": \"An empirical distribution\",\n",
    "      \"B\": \"A chance model specified before observing deliveries\",\n",
    "      \"C\": \"A population parameter\",\n",
    "      \"D\": \"A simulation procedure\"\n",
    "    },\n",
    "    \"explanation\": \"An empirical distribution is built from observed data. Here the recorded delivery times supply the values and their frequencies. The manager is summarizing those observations, rather than specifying a model or generating simulated deliveries.\",\n",
    "    \"retry_hint\": \"Review the distribution-related glossary entries and identify where the information in this question comes from.\",\n",
    "    \"reading\": \"../0800-probability-statistics.html\"\n",
    "  },\n",
    "  {\n",
    "    \"id\": \"q5\",\n",
    "    \"format\": \"multiple_choice\",\n",
    "    \"cognitive_level\": \"recognition\",\n",
    "    \"concepts\": [\n",
    "      \"Median\",\n",
    "      \"Mean\",\n",
    "      \"Standard deviation\",\n",
    "      \"Variance\"\n",
    "    ],\n",
    "    \"prompt\": \"Which summary locates the middle of an ordered list of customer waiting times?\",\n",
    "    \"choices\": {\n",
    "      \"A\": \"Mean\",\n",
    "      \"B\": \"Standard deviation\",\n",
    "      \"C\": \"Median\",\n",
    "      \"D\": \"Variance\"\n",
    "    },\n",
    "    \"explanation\": \"The median is the middle value after ordering the observations; with an even count, the usual numeric median averages the two middle values. The mean uses all values in an arithmetic average. Standard deviation and variance describe spread, not the ordered middle.\",\n",
    "    \"retry_hint\": \"Review the glossary entries for center and spread before choosing a summary.\",\n",
    "    \"reading\": \"../0800-probability-statistics.html\"\n",
    "  },\n",
    "  {\n",
    "    \"id\": \"q6\",\n",
    "    \"format\": \"true_false\",\n",
    "    \"cognitive_level\": \"recognition\",\n",
    "    \"concepts\": [\n",
    "      \"Variance\",\n",
    "      \"Standard deviation\"\n",
    "    ],\n",
    "    \"prompt\": \"True or false: Squaring a standard deviation gives its corresponding variance.\",\n",
    "    \"choices\": {\n",
    "      \"A\": \"True\",\n",
    "      \"B\": \"False\"\n",
    "    },\n",
    "    \"explanation\": \"True. Variance is the square of the corresponding standard deviation. Both describe spread; they are related quantities rather than alternative names for the same number.\",\n",
    "    \"retry_hint\": \"Review how the glossary relates the two measures of spread.\",\n",
    "    \"reading\": \"../0800-probability-statistics.html\"\n",
    "  },\n",
    "  {\n",
    "    \"id\": \"q7\",\n",
    "    \"format\": \"multiple_choice\",\n",
    "    \"cognitive_level\": \"recognition\",\n",
    "    \"concepts\": [\n",
    "      \"Sample\",\n",
    "      \"Population\",\n",
    "      \"Parameter\",\n",
    "      \"Statistic\"\n",
    "    ],\n",
    "    \"prompt\": \"A retailer studies 200 receipts selected from all of its receipts for the year. What is the collection of 200 selected receipts called?\",\n",
    "    \"choices\": {\n",
    "      \"A\": \"The population\",\n",
    "      \"B\": \"A sample\",\n",
    "      \"C\": \"A parameter\",\n",
    "      \"D\": \"A statistic\"\n",
    "    },\n",
    "    \"explanation\": \"The selected receipts are a sample: a subset drawn from the larger group of interest. All receipts for the year form the population in this question. A parameter or statistic would be a numerical summary, rather than the collection of receipts.\",\n",
    "    \"retry_hint\": \"Review the glossary entries for groups of observations and numerical summaries.\",\n",
    "    \"reading\": \"../0800-probability-statistics.html\"\n",
    "  },\n",
    "  {\n",
    "    \"id\": \"q8\",\n",
    "    \"format\": \"multiple_choice\",\n",
    "    \"cognitive_level\": \"connection\",\n",
    "    \"concepts\": [\n",
    "      \"Statistic\",\n",
    "      \"Parameter\",\n",
    "      \"Sample\",\n",
    "      \"Population\"\n",
    "    ],\n",
    "    \"prompt\": \"A manager calculates the average bill from 200 selected receipts, rather than from every receipt for the year. Because this average describes the selected sample, which term applies?\",\n",
    "    \"choices\": {\n",
    "      \"A\": \"Parameter\",\n",
    "      \"B\": \"Population\",\n",
    "      \"C\": \"Statistic\",\n",
    "      \"D\": \"Sample\"\n",
    "    },\n",
    "    \"explanation\": \"The average is a statistic because it is calculated from a sample. The same kind of numerical summary for the full population would be a parameter. The selected receipts are the sample; their calculated average is not itself a collection of receipts.\",\n",
    "    \"retry_hint\": \"Review how the glossary distinguishes a group of observations from its numerical summary, and a sample from a population.\",\n",
    "    \"reading\": \"../0800-probability-statistics.html\"\n",
    "  },\n",
    "  {\n",
    "    \"id\": \"q9\",\n",
    "    \"format\": \"true_false\",\n",
    "    \"cognitive_level\": \"connection\",\n",
    "    \"concepts\": [\n",
    "      \"Simulation\",\n",
    "      \"Uncertainty\"\n",
    "    ],\n",
    "    \"prompt\": \"True or false: Repeating a shipping simulation guarantees that we know whether the next real shipment will be late.\",\n",
    "    \"choices\": {\n",
    "      \"A\": \"True\",\n",
    "      \"B\": \"False\"\n",
    "    },\n",
    "    \"explanation\": \"False. Simulation uses repeated random trials to study possible outcomes. It can help us understand a model and its long-run behavior, but it does not remove uncertainty about the next individual real shipment.\",\n",
    "    \"retry_hint\": \"Review the purposes of simulation and the meaning of uncertainty before reconsidering the guarantee.\",\n",
    "    \"reading\": \"../0800-probability-statistics.html\"\n",
    "  },\n",
    "  {\n",
    "    \"id\": \"q10\",\n",
    "    \"format\": \"multiple_choice\",\n",
    "    \"cognitive_level\": \"connection\",\n",
    "    \"concepts\": [\n",
    "      \"Sampling variation\",\n",
    "      \"Statistic\",\n",
    "      \"Sample\"\n",
    "    ],\n",
    "    \"prompt\": \"Two independently selected random samples of 50 orders have different average waiting times, even though the underlying process has not changed. Which term describes this natural difference between sample summaries?\",\n",
    "    \"choices\": {\n",
    "      \"A\": \"A population parameter\",\n",
    "      \"B\": \"A sample space\",\n",
    "      \"C\": \"An individual outcome\",\n",
    "      \"D\": \"Sampling variation\"\n",
    "    },\n",
    "    \"explanation\": \"Sampling variation is the natural difference among statistics from different samples. Each sample contains different observations, so the averages need not match. A difference alone does not establish that the underlying process changed.\",\n",
    "    \"retry_hint\": \"Review the glossary entries for samples and sample summaries, focusing on comparisons across repeated samples.\",\n",
    "    \"reading\": \"../0800-probability-statistics.html\"\n",
    "  }\n",
    "];\n",
    "\n",
    "  var legacyQuestions = JSON.parse(JSON.stringify(questions));\n",
    "  var legacyVersion = questionSetVersion;\n",
    "  var historicalQuestions = [\n",
    "  {\n",
    "    \"id\": \"q1\",\n",
    "    \"prompt\": \"Which term matches this explanation? A number between 0 and 1 describing how likely an event is.\",\n",
    "    \"choices\": {\n",
    "      \"A\": \"Sample space\",\n",
    "      \"B\": \"Event\",\n",
    "      \"C\": \"Outcome\",\n",
    "      \"D\": \"Probability\"\n",
    "    },\n",
    "    \"format\": \"multiple_choice\",\n",
    "    \"cognitive_level\": \"recognition\",\n",
    "    \"concepts\": [\n",
    "      \"Probability\"\n",
    "    ],\n",
    "    \"reading\": \"../0800-probability-statistics.html\",\n",
    "    \"retry_hint\": \"Compare the related glossary entries and identify what the description refers to.\",\n",
    "    \"explanation\": \"Probability: A number between 0 and 1 describing how likely an event is.\"\n",
    "  },\n",
    "  {\n",
    "    \"id\": \"q2\",\n",
    "    \"prompt\": \"Which term matches this explanation? A possible result of a random process.\",\n",
    "    \"choices\": {\n",
    "      \"A\": \"Outcome\",\n",
    "      \"B\": \"Sample space\",\n",
    "      \"C\": \"Chance model\",\n",
    "      \"D\": \"Random variable\"\n",
    "    },\n",
    "    \"format\": \"multiple_choice\",\n",
    "    \"cognitive_level\": \"recognition\",\n",
    "    \"concepts\": [\n",
    "      \"Outcome\"\n",
    "    ],\n",
    "    \"reading\": \"../0800-probability-statistics.html\",\n",
    "    \"retry_hint\": \"Compare the related glossary entries and identify what the description refers to.\",\n",
    "    \"explanation\": \"Outcome: A possible result of a random process.\"\n",
    "  },\n",
    "  {\n",
    "    \"id\": \"q3\",\n",
    "    \"prompt\": \"Which term matches this explanation? A simplified representation of a random process.\",\n",
    "    \"choices\": {\n",
    "      \"A\": \"Probability\",\n",
    "      \"B\": \"Event\",\n",
    "      \"C\": \"Chance model\",\n",
    "      \"D\": \"Outcome\"\n",
    "    },\n",
    "    \"format\": \"multiple_choice\",\n",
    "    \"cognitive_level\": \"recognition\",\n",
    "    \"concepts\": [\n",
    "      \"Chance model\"\n",
    "    ],\n",
    "    \"reading\": \"../0800-probability-statistics.html\",\n",
    "    \"retry_hint\": \"Compare the related glossary entries and identify what the description refers to.\",\n",
    "    \"explanation\": \"Chance model: A simplified representation of a random process.\"\n",
    "  },\n",
    "  {\n",
    "    \"id\": \"q4\",\n",
    "    \"prompt\": \"Which term matches this explanation? A distribution built from observed data.\",\n",
    "    \"choices\": {\n",
    "      \"A\": \"Empirical distribution\",\n",
    "      \"B\": \"Event\",\n",
    "      \"C\": \"Outcome\",\n",
    "      \"D\": \"Probability\"\n",
    "    },\n",
    "    \"format\": \"multiple_choice\",\n",
    "    \"cognitive_level\": \"recognition\",\n",
    "    \"concepts\": [\n",
    "      \"Empirical distribution\"\n",
    "    ],\n",
    "    \"reading\": \"../0800-probability-statistics.html\",\n",
    "    \"retry_hint\": \"Compare the related glossary entries and identify what the description refers to.\",\n",
    "    \"explanation\": \"Empirical distribution: A distribution built from observed data.\"\n",
    "  },\n",
    "  {\n",
    "    \"id\": \"q5\",\n",
    "    \"prompt\": \"Which term matches this explanation? The middle value when observations are ordered.\",\n",
    "    \"choices\": {\n",
    "      \"A\": \"Event\",\n",
    "      \"B\": \"Probability\",\n",
    "      \"C\": \"Median\",\n",
    "      \"D\": \"Outcome\"\n",
    "    },\n",
    "    \"format\": \"multiple_choice\",\n",
    "    \"cognitive_level\": \"recognition\",\n",
    "    \"concepts\": [\n",
    "      \"Median\"\n",
    "    ],\n",
    "    \"reading\": \"../0800-probability-statistics.html\",\n",
    "    \"retry_hint\": \"Compare the related glossary entries and identify what the description refers to.\",\n",
    "    \"explanation\": \"Median: The middle value when observations are ordered.\"\n",
    "  },\n",
    "  {\n",
    "    \"id\": \"q6\",\n",
    "    \"prompt\": \"Which term matches this explanation? The squared version of standard deviation.\",\n",
    "    \"choices\": {\n",
    "      \"A\": \"Variance\",\n",
    "      \"B\": \"Probability\",\n",
    "      \"C\": \"Event\",\n",
    "      \"D\": \"Outcome\"\n",
    "    },\n",
    "    \"format\": \"multiple_choice\",\n",
    "    \"cognitive_level\": \"recognition\",\n",
    "    \"concepts\": [\n",
    "      \"Variance\"\n",
    "    ],\n",
    "    \"reading\": \"../0800-probability-statistics.html\",\n",
    "    \"retry_hint\": \"Compare the related glossary entries and identify what the description refers to.\",\n",
    "    \"explanation\": \"Variance: The squared version of standard deviation.\"\n",
    "  },\n",
    "  {\n",
    "    \"id\": \"q7\",\n",
    "    \"prompt\": \"Which term matches this explanation? A subset of observations drawn from a larger population.\",\n",
    "    \"choices\": {\n",
    "      \"A\": \"Probability\",\n",
    "      \"B\": \"Sample\",\n",
    "      \"C\": \"Event\",\n",
    "      \"D\": \"Outcome\"\n",
    "    },\n",
    "    \"format\": \"multiple_choice\",\n",
    "    \"cognitive_level\": \"recognition\",\n",
    "    \"concepts\": [\n",
    "      \"Sample\"\n",
    "    ],\n",
    "    \"reading\": \"../0800-probability-statistics.html\",\n",
    "    \"retry_hint\": \"Compare the related glossary entries and identify what the description refers to.\",\n",
    "    \"explanation\": \"Sample: A subset of observations drawn from a larger population.\"\n",
    "  },\n",
    "  {\n",
    "    \"id\": \"q8\",\n",
    "    \"prompt\": \"Which term matches this explanation? A numeric summary computed from a sample.\",\n",
    "    \"choices\": {\n",
    "      \"A\": \"Probability\",\n",
    "      \"B\": \"Event\",\n",
    "      \"C\": \"Statistic\",\n",
    "      \"D\": \"Outcome\"\n",
    "    },\n",
    "    \"format\": \"multiple_choice\",\n",
    "    \"cognitive_level\": \"recognition\",\n",
    "    \"concepts\": [\n",
    "      \"Statistic\"\n",
    "    ],\n",
    "    \"reading\": \"../0800-probability-statistics.html\",\n",
    "    \"retry_hint\": \"Compare the related glossary entries and identify what the description refers to.\",\n",
    "    \"explanation\": \"Statistic: A numeric summary computed from a sample.\"\n",
    "  },\n",
    "  {\n",
    "    \"id\": \"q9\",\n",
    "    \"prompt\": \"Which term matches this explanation? Using repeated random trials to study possible outcomes.\",\n",
    "    \"choices\": {\n",
    "      \"A\": \"Probability\",\n",
    "      \"B\": \"Simulation\",\n",
    "      \"C\": \"Event\",\n",
    "      \"D\": \"Outcome\"\n",
    "    },\n",
    "    \"format\": \"multiple_choice\",\n",
    "    \"cognitive_level\": \"recognition\",\n",
    "    \"concepts\": [\n",
    "      \"Simulation\"\n",
    "    ],\n",
    "    \"reading\": \"../0800-probability-statistics.html\",\n",
    "    \"retry_hint\": \"Compare the related glossary entries and identify what the description refers to.\",\n",
    "    \"explanation\": \"Simulation: Using repeated random trials to study possible outcomes.\"\n",
    "  },\n",
    "  {\n",
    "    \"id\": \"q10\",\n",
    "    \"prompt\": \"Which term matches this explanation? Limited knowledge about an outcome, parameter, or decision.\",\n",
    "    \"choices\": {\n",
    "      \"A\": \"Probability\",\n",
    "      \"B\": \"Outcome\",\n",
    "      \"C\": \"Event\",\n",
    "      \"D\": \"Uncertainty\"\n",
    "    },\n",
    "    \"format\": \"multiple_choice\",\n",
    "    \"cognitive_level\": \"recognition\",\n",
    "    \"concepts\": [\n",
    "      \"Uncertainty\"\n",
    "    ],\n",
    "    \"reading\": \"../0800-probability-statistics.html\",\n",
    "    \"retry_hint\": \"Compare the related glossary entries and identify what the description refers to.\",\n",
    "    \"explanation\": \"Uncertainty: Limited knowledge about an outcome, parameter, or decision.\"\n",
    "  }\n",
    "];\n",
    "  var historicalVersion = 'dsm-ch08-preview-before-2026-10-19';\n",
    "  var authoredQuestions = JSON.parse(JSON.stringify(questions));\n",
    "\n",
    "  function text(value) {\n",
    "    return document.createTextNode(value);\n",
    "  }\n",
    "\n",
    "  function getParams() {\n",
    "    var params = new URLSearchParams(window.location.search);\n",
    "    return {\n",
    "      canvas_course_id: params.get('canvas_course_id') || params.get('course_id') || '',\n",
    "      canvas_assignment_id: params.get('canvas_assignment_id') || params.get('assignment_id') || '',\n",
    "      canvas_user_id: params.get('canvas_user_id') || params.get('user_id') || '',\n",
    "      student_identifier: params.get('student_identifier') || params.get('student_id') || params.get('email') || ''\n",
    "    };\n",
    "  }\n",
    "\n",
    "  function loadSessionIdentity(identity, actions, submit, result) {\n",
    "    submit.disabled = true;\n",
    "    actions.classList.add('is-locked');\n",
    "    result.textContent = 'Sign in from the account menu to submit this assignment.';\n",
    "\n",
    "    return fetch('/api/v1/session.php', { credentials: 'same-origin' })\n",
    "      .then(function (response) { return response.ok ? response.json() : null; })\n",
    "      .then(function (payload) {\n",
    "        if (!payload || !payload.authenticated || !payload.identity) return identity;\n",
    "        identity.canvas_user_id = payload.identity.canvas_user_id || identity.canvas_user_id || '';\n",
    "        identity.student_identifier = payload.identity.student_identifier || identity.student_identifier || '';\n",
    "        submit.disabled = false;\n",
    "        actions.classList.remove('is-locked');\n",
    "        result.textContent = payload.identity.display_name ? 'Signed in as ' + payload.identity.display_name + '.' : 'Signed in.';\n",
    "        return identity;\n",
    "      })\n",
    "      .catch(function () { return identity; });\n",
    "  }\n",
    "\n",
    "  function renderQuestions(container) {\n",
    "    container.textContent = '';\n",
    "    questions.forEach(function (question, index) {\n",
    "      var card = document.createElement('div');\n",
    "      card.className = 'ch08-preview-question';\n",
    "      card.dataset.question = question.id;\n",
    "\n",
    "      var prompt = document.createElement('p');\n",
    "      prompt.appendChild(text((index + 1) + '. ' + question.prompt));\n",
    "      card.appendChild(prompt);\n",
    "\n",
    "      (attemptState ? attemptState.orders[question.id] : Object.keys(question.choices)).forEach(function (letter, position) {\n",
    "        var label = document.createElement('label');\n",
    "        var input = document.createElement('input');\n",
    "        input.type = 'radio';\n",
    "        input.name = question.id;\n",
    "        input.value = letter;\n",
    "        input.checked = !!(attemptState && attemptState.answers[question.id] === letter);\n",
    "        label.appendChild(input);\n",
    "        label.appendChild(text(String.fromCharCode(65 + position) + '. ' + question.choices[letter]));\n",
    "        card.appendChild(label);\n",
    "      });\n",
    "\n",
    "      var feedback = document.createElement('div');\n",
    "      feedback.className = 'ch08-preview-feedback';\n",
    "      feedback.setAttribute('aria-live', 'polite');\n",
    "      card.appendChild(feedback);\n",
    "      container.appendChild(card);\n",
    "    });\n",
    "  }\n",
    "\n",
    "  function collectAnswers(quiz) {\n",
    "    var answers = {};\n",
    "    questions.forEach(function (question) {\n",
    "      var selected = quiz.querySelector('input[name=' + question.id + ']:checked');\n",
    "      answers[question.id] = selected ? selected.value : '';\n",
    "    });\n",
    "    // Press stores this marker with the submitted answers; it is not a scored question.\n",
    "    answers.__question_set = attemptState ? attemptState.version : questionSetVersion;\n",
    "    if (attemptState) answers.preview_attempt = attemptState.token;\n",
    "    return answers;\n",
    "  }\n",
    "\n",
    "  function loadFeedbackPolicy() {\n",
    "    // Use the existing server release setting; a network failure must not unlock answers.\n",
    "    return fetch('/api/v1/assignment-settings.php?assignment_id=' + encodeURIComponent(quizId), {\n",
    "      credentials: 'same-origin'\n",
    "    })\n",
    "      .then(function (response) { return response.ok ? response.json() : null; })\n",
    "      .then(function (payload) {\n",
    "        answersUnlocked = !!(payload && payload.ok && payload.answers_unlocked === true);\n",
    "      })\n",
    "      .catch(function () { answersUnlocked = false; });\n",
    "  }\n",
    "\n",
    "  function applyFeedback(quiz, feedback) {\n",
    "    questions.forEach(function (question) {\n",
    "      var card = quiz.querySelector('[data-question=' + question.id + ']');\n",
    "      var message = card.querySelector('.ch08-preview-feedback');\n",
    "      var item = feedback[question.id];\n",
    "      message.className = 'ch08-preview-feedback';\n",
    "      var status = (!item || !item.submitted) ? 'No answer submitted.' :\n",
    "        (item.correct ? 'Correct.' : 'Review and try again.');\n",
    "      var guidance = answersUnlocked ? question.explanation : question.retry_hint;\n",
    "      message.textContent = status + ' ' + guidance;\n",
    "      var reading = document.createElement('a');\n",
    "      reading.href = question.reading || \"../0800-probability-statistics.html\";\n",
    "      reading.appendChild(text('Review this concept'));\n",
    "      message.appendChild(text(' '));\n",
    "      message.appendChild(reading);\n",
    "      message.classList.add(item && item.correct ? 'correct' : 'incorrect');\n",
    "    });\n",
    "  }\n",
    "\n",
    "  function initLegacyPreviewQuiz() {\n",
    "    var quiz = document.getElementById('ch08-preview-quiz');\n",
    "    if (!quiz || quiz.dataset.ready === 'true') return;\n",
    "    quiz.dataset.ready = 'true';\n",
    "\n",
    "    var identity = getParams();\n",
    "    var questionsContainer = document.getElementById('ch08-preview-questions');\n",
    "    var result = document.getElementById('ch08-preview-result');\n",
    "    var submit = document.getElementById('ch08-preview-submit');\n",
    "    var actions = quiz.querySelector('.ch08-preview-actions');\n",
    "    var reset = document.getElementById('ch08-preview-reset');\n",
    "\n",
    "    renderQuestions(questionsContainer);\n",
    "    loadSessionIdentity(identity, actions, submit, result);\n",
    "\n",
    "    submit.addEventListener('click', function () {\n",
    "      var answers = collectAnswers(quiz);\n",
    "      submit.disabled = true;\n",
    "      result.textContent = 'Submitting...';\n",
    "\n",
    "      fetch('/api/v1/quiz-attempts.php', {\n",
    "        method: 'POST',\n",
    "        headers: { 'Content-Type': 'application/json' },\n",
    "        credentials: 'same-origin',\n",
    "        body: JSON.stringify({\n",
    "          quiz_id: quizId,\n",
    "          question_set_version: questionSetVersion,\n",
    "          answers: answers,\n",
    "          student_identifier: identity.student_identifier || identity.canvas_user_id || '',\n",
    "          canvas_course_id: identity.canvas_course_id,\n",
    "          canvas_assignment_id: identity.canvas_assignment_id,\n",
    "          canvas_user_id: identity.canvas_user_id\n",
    "        })\n",
    "      })\n",
    "        .then(function (response) {\n",
    "          return response.text().then(function (text) {\n",
    "            var payload = null;\n",
    "            try {\n",
    "              payload = text ? JSON.parse(text) : null;\n",
    "            } catch (error) {\n",
    "              throw new Error('Server returned a non-JSON response (HTTP ' + response.status + '): ' + text.slice(0, 160));\n",
    "            }\n",
    "            if (!payload) {\n",
    "              throw new Error('Server returned an empty response (HTTP ' + response.status + '). Check that PHP is enabled for /api/v1/quiz-attempts.php.');\n",
    "            }\n",
    "            if (!response.ok || !payload.ok) {\n",
    "              throw new Error(payload.message || payload.error || 'Submission failed.');\n",
    "            }\n",
    "            return payload;\n",
    "          });\n",
    "        })\n",
    "        .then(function (payload) {\n",
    "          var best = (payload.best_score === null || typeof payload.best_score === 'undefined') ? payload.score : payload.best_score;\n",
    "          var attempt = (payload.attempt_count === null || typeof payload.attempt_count === 'undefined') ? '' : ' Attempt ' + payload.attempt_count + '.';\n",
    "          return loadFeedbackPolicy().then(function () {\n",
    "            applyFeedback(quiz, payload.feedback || {});\n",
    "            result.textContent = 'Submission saved.' + attempt + ' Score: ' + payload.score + ' / ' + payload.max_score + '. Best score: ' + best + ' / ' + payload.max_score + '. Canvas sync: ' + payload.canvas_sync_status + '.';\n",
    "            if (!answersUnlocked) result.textContent += ' Full explanations are available when answers are released.';\n",
    "          });\n",
    "        })\n",
    "        .catch(function (error) {\n",
    "          result.textContent = 'Could not save this attempt: ' + error.message;\n",
    "        })\n",
    "        .finally(function () {\n",
    "          submit.disabled = false;\n",
    "        });\n",
    "    });\n",
    "\n",
    "    reset.addEventListener('click', function () {\n",
    "      quiz.querySelectorAll('input[type=radio]').forEach(function (input) {\n",
    "        input.checked = false;\n",
    "      });\n",
    "      quiz.querySelectorAll('.ch08-preview-feedback').forEach(function (feedback) {\n",
    "        feedback.className = 'ch08-preview-feedback';\n",
    "        feedback.textContent = '';\n",
    "      });\n",
    "      result.textContent = '';\n",
    "    });\n",
    "  }\n",
    "\n",
    "\n",
    "  function initPreviewQuiz() {\n",
    "    // The legacy PHP host retains its existing fixed-order delivery until it migrates to Press.\n",
    "    if (!/(^|\\.)thinkpress\\.org$/.test(window.location.hostname) &&\n",
    "        !['localhost', '127.0.0.1'].includes(window.location.hostname)) return initLegacyPreviewQuiz();\n",
    "    var quiz = document.getElementById('ch08-preview-quiz');\n",
    "    if (!quiz || quiz.dataset.ready === 'true') return;\n",
    "    quiz.dataset.ready = 'true';\n",
    "\n",
    "    var identity = getParams();\n",
    "    var questionsContainer = document.getElementById('ch08-preview-questions');\n",
    "    var result = document.getElementById('ch08-preview-result');\n",
    "    var submit = document.getElementById('ch08-preview-submit');\n",
    "    var actions = quiz.querySelector('.ch08-preview-actions');\n",
    "    var reset = document.getElementById('ch08-preview-reset');\n",
    "\n",
    "    // Press owns this quiz's draft and option order; the generic runner must not restore older inputs over it.\n",
    "    quiz.classList.add('press-preview-managed');\n",
    "    var next = document.createElement('button');\n",
    "    next.type = 'button';\n",
    "    next.textContent = 'Start a new attempt';\n",
    "    next.hidden = true;\n",
    "    actions.appendChild(next);\n",
    "\n",
    "    function lockQuestions(locked) {\n",
    "      quiz.querySelectorAll('input[type=radio]').forEach(function (input) { input.disabled = locked; });\n",
    "      reset.disabled = locked;\n",
    "    }\n",
    "    function showState(payload) {\n",
    "      questions = attemptState.questions;\n",
    "      renderQuestions(questionsContainer);\n",
    "      lockQuestions(payload.completed);\n",
    "      submit.disabled = payload.completed;\n",
    "      next.hidden = !payload.completed;\n",
    "      if (!payload.completed) result.textContent = '';\n",
    "      if (attemptState.preserved_draft && !payload.completed) {\n",
    "        result.textContent = 'Resumed your saved answers with their original option order.';\n",
    "      }\n",
    "      if (payload.result) {\n",
    "        return loadFeedbackPolicy().then(function () {\n",
    "          applyFeedback(quiz, payload.result.feedback || {});\n",
    "          result.textContent = 'Saved attempt. Score: ' + payload.result.score + ' / ' + payload.result.max_score +\n",
    "            '. Best score: ' + payload.result.best_score + ' / ' + payload.result.max_score + '.';\n",
    "          if (!answersUnlocked) result.textContent += ' Full explanations are available when answers are released.';\n",
    "        });\n",
    "      }\n",
    "      return Promise.resolve();\n",
    "    }\n",
    "    renderQuestions(questionsContainer);\n",
    "    lockQuestions(true);\n",
    "    loadSessionIdentity(identity, actions, submit, result).then(function () {\n",
    "      if (submit.disabled) return;\n",
    "      submit.disabled = true;\n",
    "      result.textContent = 'Resuming your Preview...';\n",
    "      return stateRequest('resume').then(showState).catch(function (error) {\n",
    "        submit.disabled = true;\n",
    "        result.textContent = 'Could not resume this Preview: ' + error.message + ' Reload to retry.';\n",
    "      });\n",
    "    });\n",
    "\n",
    "    quiz.addEventListener('change', function (event) {\n",
    "      if (!event.target || event.target.type !== 'radio' || !attemptState) return;\n",
    "      saveAnswers(quiz).catch(function (error) { result.textContent = 'Answers not saved: ' + error.message; });\n",
    "    });\n",
    "\n",
    "    submit.addEventListener('click', async function () {\n",
    "      submit.disabled = true;\n",
    "      lockQuestions(true);\n",
    "      result.textContent = 'Submitting...';\n",
    "      try {\n",
    "        await saveAnswers(quiz);\n",
    "        var response = await fetch('/api/v1/quiz-attempts.php', {\n",
    "          method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'same-origin',\n",
    "          body: JSON.stringify({ quiz_id: quizId, answers: collectAnswers(quiz),\n",
    "            question_set_version: attemptState.version,\n",
    "            student_identifier: identity.student_identifier || identity.canvas_user_id || '',\n",
    "            canvas_course_id: identity.canvas_course_id, canvas_assignment_id: identity.canvas_assignment_id,\n",
    "            canvas_user_id: identity.canvas_user_id })\n",
    "        });\n",
    "        var payload = await response.json();\n",
    "        if (!response.ok || !payload.ok) throw new Error(payload.message || payload.error || 'Submission failed.');\n",
    "        await loadFeedbackPolicy();\n",
    "        applyFeedback(quiz, payload.feedback || {});\n",
    "        result.textContent = 'Submission saved. Attempt ' + payload.attempt_count + '. Score: ' + payload.score +\n",
    "          ' / ' + payload.max_score + '. Best score: ' + payload.best_score + ' / ' + payload.max_score + '.';\n",
    "        if (!answersUnlocked) result.textContent += ' Full explanations are available when answers are released.';\n",
    "        next.hidden = false;\n",
    "      } catch (error) {\n",
    "        result.textContent = 'Could not save this attempt: ' + error.message;\n",
    "        submit.disabled = false;\n",
    "        lockQuestions(false);\n",
    "      }\n",
    "    });\n",
    "\n",
    "    reset.addEventListener('click', function () {\n",
    "      submit.disabled = true;\n",
    "      stateQueue = stateQueue.catch(function () {}).then(function () { return stateRequest('clear'); });\n",
    "      stateQueue.then(function (payload) { result.textContent = ''; return showState(payload); })\n",
    "        .catch(function (error) { result.textContent = error.message; submit.disabled = false; });\n",
    "    });\n",
    "    next.addEventListener('click', function () {\n",
    "      next.disabled = true;\n",
    "      stateRequest('next').then(function (payload) { result.textContent = ''; return showState(payload); })\n",
    "        .catch(function (error) { result.textContent = error.message; })\n",
    "        .finally(function () { next.disabled = false; });\n",
    "    });\n",
    "  }\n",
    "\n",
    "  if (document.readyState === 'loading') {\n",
    "    document.addEventListener('DOMContentLoaded', initPreviewQuiz);\n",
    "  } else {\n",
    "    initPreviewQuiz();\n",
    "  }\n",
    "})();\n",
    "</script>"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
