// SCORM 1.2 API Wrapper
var scormAPI = null;
var initialized = false;

function findAPI(win) {
  var attempts = 0;
  while (win.API == null && win.parent != null && win.parent != win) {
    attempts++;
    if (attempts > 7) break;
    win = win.parent;
  }
  return win.API;
}

function getAPI() {
  var api = findAPI(window);
  if (api == null && window.opener != null) {
    api = findAPI(window.opener);
  }
  return api;
}

function initSCORM() {
  scormAPI = getAPI();
  if (scormAPI == null) return false;
  var result = scormAPI.LMSInitialize("");
  if (result == "true" || result === true) {
    initialized = true;
    scormAPI.LMSSetValue("cmi.core.lesson_status", "incomplete");
    return true;
  }
  return false;
}

function setSCORMValue(key, value) {
  if (!initialized || scormAPI == null) return;
  scormAPI.LMSSetValue(key, value);
  scormAPI.LMSCommit("");
}

function finishSCORM(score, maxScore) {
  if (!initialized || scormAPI == null) return;
  var pct = Math.round((score / maxScore) * 100);
  scormAPI.LMSSetValue("cmi.core.score.raw", pct);
  scormAPI.LMSSetValue("cmi.core.score.min", "0");
  scormAPI.LMSSetValue("cmi.core.score.max", "100");
  scormAPI.LMSSetValue("cmi.core.lesson_status", pct >= 70 ? "passed" : "failed");
  scormAPI.LMSCommit("");
  scormAPI.LMSFinish("");
}

window.addEventListener("load", function() { initSCORM(); });
window.addEventListener("beforeunload", function() {
  if (initialized && scormAPI != null) scormAPI.LMSFinish("");
});
