/*jslint browser: true, devel: true, nomen: true, plusplus: true, regexp: true, unparam: true, todo: true, indent: 4 */
var default_config = {
settings: {
shuffle_sections: false,
shuffle_questions: true,
shuffle_choices: true,
passing_score: 80,
id_prefix: 'q',
id_digits: 3,
time_limit: 0,
time_limit_mode: 'total',
tag_visible: true,
show_correct_answer: true,
show_instant_result: true,
show_seigo_count: true,
hide_result_summary: false,
hide_result_detail: false,
hide_mark_button: true,
hide_list_button: false,
hide_pagination: false,
title: 'Quiz',
ignore_case: true,
ignore_whitespace_count: true,
ignore_whitespace: false,
ignore_zenhan: true,
trim: true,
width: false,
height: false,
bgcolor: false,
player_bgcolor: false,
finish_at_result_page: true,
movable: false,
mode: 'master',
layout: 'normal',
master_count: 2,
weak_count: 5,
restartable: true,
scorm: 'auto',
scale: 1,
student_response_align: 'center',
flexible_resultpage: false,
version: '5.11.0',
remove_powered_by: false,
sound: false,
math: true,
certificate: false,
pass: false,
score_weighting: false,
suspendable: false,
suspendable_count: -1,
show_suspendable_button: true,
partial_score: false,
autoplay: false,
use_number_type_for_input: true,
fill_in_max_length: '',
messages: {
passed: '全問正解',
incomplete: '学習中',
failed: '攻略中',
sankaku: '部分点',
completed: '採点待',
correct: '正解！',
incorrect: '不正解',
neutral: '採点待',
not_selected: '解答を選択してください',
not_filled: '解答を入力してください',
intro: '開始ボタンをクリックするとクイズが始まります',
answer_true: '全問正解',
answer_false: '攻略中',
not_sorted: '並び替えをおこなってください',
confirm_midstream_mark: '未解答の設問があります。途中終了して採点処理を行いますがよろしいですか？',
confirm_mark: '終了して採点処理を行います。よろしいですか？',
passed_title: false,
passed_body: false,
failed_title: false,
failed_body: false
}
},
questions: [
{
question: '<b>What are in the picture?</b> <br>[[images/dice.png]]',
choice: ['dice', 'maze', 'pen'],
answer: 'dice',
type: 'button',
section: 0
},
{
question: '<b>What are in the picture?</b> <br>[[images/dice.png]]',
choice: ['dice', 'maze', 'pen'],
answer: 'dice',
type: 'button',
section: 0
},
{
question: '<b>What are in the picture?</b> <br>[[images/dice.png]]',
choice: ['dice', 'maze', 'pen'],
answer: 'dice',
type: 'button',
section: 0
}
]
};
var scorm12 = { correct: 'correct', incorrect: 'wrong', neutral: 'neutral' },
scorm2004 = {
correct: 'correct',
incorrect: 'incorrect',
neutral: 'neutral'
},
single_choice_template,
single_choice_box_template,
multi_choice_template,
button_template,
input_template,
input_math_template,
textarea_template,
fill_in_multi_template,
true_false_template,
sort_template,
match_template,
wordbank_template,
result_detail_template1,
result_detail_template2,
position = 0,
cq,
origProgress,
suspend_data_version = '0010',
suspend_data_body,
suspend_data_body_unknown,
pushed_state,
state = 'loading',
last_button_value = '',
dragging = false,
pc_flg = false,
change_sort_flg = false,
change_list_scale_height = 0,
change_page_scale_height = 0,
finished = false,
_cfg,
suspended = false,
autoStartRunner,
timeLeft = false,


previousPosition = 0,

oneTimeAudioCount = -1,

currentSuspendCount = -1,

suspendDataInitialTimeLimit = null,


studyLogArray = [];

window.layout = {
ua: window.navigator.userAgent.toLowerCase(),
os: null,
version: null,
browser: null,
page_quiz: false,
checkBrowser: function () {
if (this.ua.indexOf('msie') !== -1 || this.ua.indexOf('trident') !== -1) {
document.body.classList.add('is-IE');
return 'ie';
}
if (this.ua.indexOf('edge') !== -1) {
document.body.classList.add('is-Edge');
return 'edge';
}
if (this.ua.indexOf('chrome') !== -1) {
document.body.classList.add('is-Chrome');
return 'chrome';
}
if (this.ua.indexOf('safari') !== -1) {
document.body.classList.add('is-Safari');
return 'safari';
}
if (this.ua.indexOf('firefox') !== -1) {
document.body.classList.add('is-Firefox');
return 'firefox';
}
},
checkOS: function () {
if (this.ua.indexOf('windows nt') !== -1) {
document.body.classList.add('windows');
return 'windows';
}
if (this.ua.indexOf('android') !== -1) {
document.body.classList.add('android');
return 'android';
}
if (this.ua.indexOf('iphone') !== -1 || this.ua.indexOf('ipad') !== -1) {
document.body.classList.add('iOS');
return 'iOS';
}
if (this.ua.indexOf('macintosh') > -1 && 'ontouchend' in document) {
document.body.classList.add('iPadOS');
return 'iPadOS'
}
if (this.ua.indexOf('mac os x') !== -1) {
document.body.classList.add('macOS');
return 'macOS';
}
},
checkOSVersion: function () {
const version = this.ua.match(/os (.+?) like/)[1];
return parseFloat(version.replace('_', '.'));
},

fixViewHeight: function () {
if (this.os === 'iOS' && this.version <= 13) {
const t = document.querySelector('#contents_wrapper');
const angle = window.orientation;
const screenAdjustNumber = 0.9;
const vh = angle === 0 ? screen.height : screen.width;
const height = vh * screenAdjustNumber;
const questionType = cq.type;
const choices = document.querySelector('#choices');
const question = document.querySelector('#question');
t.style.height = height + 'px';
if (questionType === 'pulldown') {
question.style.width = height + 'px';
} else {
question.style.width = null;
}
if (questionType === 'true-false' || questionType === 'match') {
choices.style.width = height + 'px';
} else {
choices.style.width = null;
}
}
},
choicesAreaWidthAdjust: function () {
const contentWidth = document.querySelector('#contents_wrapper').clientWidth;
const questionWidth = document.querySelector('#question_statement').clientWidth;
const choicesWidth = contentWidth - questionWidth;


const adjustNumber = 30;
const choices = document.querySelector('#choices');
choices.style.height = choicesWidth - adjustNumber + 'px';
},
switchChoicesAreaWidthAdjust: function () {
if (cq.type === 'match' && (this.browser === 'chrome' || this.browser === 'safari')) {
this.choicesAreaWidthAdjust();
window.onresize = this.choicesAreaWidthAdjust;
return;
}
const choices = document.querySelector('#choices');
choices.style.height = '';
window.onresize = null;
},
questionFirstScrolling: function () {
const t = document.querySelector('#question_statement');


if (this.os === 'iOS' || this.browser === 'firefox' || this.browser === 'safari') {
t.scrollLeft = 0;
return;
}
t.scrollLeft = t.scrollWidth;
},
convertTextToAttrDataText: function () {
const nodeList = document.querySelectorAll('.btn-match');
nodeList.forEach(function (t) {
const text = t.innerText;
t.dataset.text = text;
});
},

fixIERendering: function () {
const c = document.querySelector('#choices');
c.style.display = 'none';
c.style.display = 'block';
},
examFunc: function () {
window.document.body.id = cq.type;
this.fixViewHeight();
},
examVerticalFunc: function () {
this.examFunc();
const os = this.os;
const browser = this.browser;


if (!this.page_quiz) {
this.page_quiz = true;
setTimeout(function () {
window.layout.switchChoicesAreaWidthAdjust();
}, 10)
} else {
this.switchChoicesAreaWidthAdjust();
}

this.questionFirstScrolling();

if (cq.type === 'button' && browser === 'ie') {
this.fixIERendering();
}


if (cq.type === 'match' && (os === 'iOS' || os === 'iPadOS' || browser === 'safari')) {
this.convertTextToAttrDataText();
}
},
createAlertPortrait: function () {
const html = '<div id="alert-portrait" class="alert alert-warning alert-dismissible" role="alert">スマートフォンは横向きでの学習を推奨します<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button></div>';

document.querySelector('#page_intro').insertAdjacentHTML('afterbegin', html);
},
init: function () {
this.os = this.checkOS();
this.browser = this.checkBrowser();
if (this.os === 'iOS') {
this.version = this.checkOSVersion();
}

const isSP = this.os === 'iOS' || this.os === 'iPadOS' || this.os === 'android';
if (isSP) {
this.createAlertPortrait();
}
window.addEventListener('orientationchange', this.fixViewHeight);
}
}

$(function () {

init_quiz();
if (_cfg.settings.layout.indexOf('exam') > -1) {
window.layout.init();
window.document.body.classList.add('layout-exam');
window.document.body.classList.add(_cfg.settings.layout);
}
});

function init_quiz() {

var elem, i;
cstate('intro');
save_templates();
load_config();

if (_cfg.settings.suspendable) {
setSuspendButtonVisibility(_cfg.settings.show_suspendable_button);
} else {
setSuspendButtonVisibility(false);
}
fit_to_frame();
init_scorm();
if (!_cfg.settings.remove_powered_by) {
$('#intro_wrapper').before(
'<div class="col-12" style="margin-top:-20px;"><kbd style="font-size:11px;" class="float-right">Powered by <a href="https://quizgenerator.net" target="_blank" style="color:white;">QuizGenerator' +
_cfg.settings.version +
'</a></kbd></div>'
);
}

for (elem in _cfg.settings.messages) {
if (_cfg.settings.messages.hasOwnProperty(elem)) {
if (_cfg.settings.messages[elem]) {
$('#' + elem).html(convert_image_tags(_cfg.settings.messages[elem], 'not_sa-box'));
}
}
}
if (!_cfg.settings.show_instant_result) {
$('#result_table1 .result').hide();
}


if (_cfg.settings.layout === 'exam-vertical') {
$('#js-movable-btn-container').addClass('flex-row-reverse');

const angleRight = 'fa-angle-right';
const angleLeft = 'fa-angle-left';

const $prevBtn = $('#display_prev_quiz');
$prevBtn.addClass('right-radius').removeClass('left-radius');
$prevBtn.find('i').addClass(angleRight).removeClass(angleLeft);

$('#display_next_quiz, #check_answer_next_button, #not_disp_answer_next_button').addClass('left-radius').removeClass('right-radius');
$('#display_next_quiz').find('i').addClass(angleLeft).removeClass(angleRight);
}

if (!_cfg.settings.movable) {
$('th.button,td.button').hide();
}
if (!_cfg.settings.restartable) {
$('#restart_button').hide();
}
document.title = _cfg.settings.title;
$('#start_quiz_button_not_answerd').parent().hide();
$('#start_quiz_button_review').parent().hide();
$('#start_quiz_button_weak').parent().hide();
$('#start_quiz_button').hide();
$('#completion_rate_wrapper').hide();
switch (_cfg.settings.mode) {
case 'master':
$('#completion_rate').html(get_completion_rate());

if (
count_correctly_answered_questions() >
_cfg.settings.master_count * _cfg.questions.length
) {
$('#completion_rate_label_wrapper').addClass('text-success');
}

origProgress = get_completion_rate();
if (
count_correctly_answered_questions() >=
_cfg.settings.master_count * _cfg.questions.length
) {
$('#start_quiz_button_not_answerd')
.prop('disabled', true)
.css('pointer-events', 'none');
$('#start_quiz_button_not_answerd')
.parent('div')
.css('cursor', 'not-allowed');
$('#stamp').show();
} else {
$('#start_quiz_button_not_answerd')
.prop('disabled', false)
.css('pointer-events', 'auto');
$('#start_quiz_button_not_answerd')
.parent('div')
.css('cursor', 'pointer');
$('#start_quiz_button_not_answerd')
.parent('div')
.tooltip('disable');
$('#stamp').hide();
}
if (
count_correctly_answered_questions() <
_cfg.settings.master_count * _cfg.questions.length
) {
$('#start_quiz_button_review')
.prop('disabled', true)
.css('pointer-events', 'none');
$('#start_quiz_button_review')
.parent('div')
.css('cursor', 'not-allowed');
} else {
$('#start_quiz_button_review')
.prop('disabled', false)
.css('pointer-events', 'auto');
$('#start_quiz_button_review')
.parent('div')
.css('cursor', 'pointer');
$('#start_quiz_button_review')
.parent('div')
.tooltip('disable');
}

$('#start_quiz_button_not_answerd').parent().show();
$('#start_quiz_button_review').parent().show();
$('#start_quiz_button_weak').parent().show();
$('#completion_rate_wrapper').show();
break;
default:
$('#start_quiz_button').show();
}

if (_cfg.settings.hasOwnProperty('question_count_array')) {
_cfg.settings.question_count = 0;

let sectionQuizMaxArray = getSectionQuizMaxArray(_cfg.questions);

for (i = 0; i < _cfg.settings.question_count_array.length; i++) {

if (_cfg.settings.question_count_array[i] > sectionQuizMaxArray[i]) {
_cfg.settings.question_count_array[i] = sectionQuizMaxArray[i];
}
_cfg.settings.question_count += _cfg.settings.question_count_array[i];
}
} else if (!_cfg.settings.hasOwnProperty('question_count')) {
_cfg.settings.question_count = _cfg.questions.length;
}
_cfg.settings.question_count = Math.min(
_cfg.questions.length,
_cfg.settings.question_count
);
prepare_questions();
updateLinkTarget();
if (_cfg.settings.skip_intro_page) {
autoStartRunner = setInterval(waitAndAutostart, 5);
} else {
show('#page_intro');
}
}

function waitAndAutostart() {
if (typeof MathJax !== 'undefined') {
clearInterval(autoStartRunner);
if (_cfg.settings.mode == 'master') {
start_quiz('review');
} else {

let isExistSuspendData = suspend_data_array && suspend_data_array.questions;
let isSuspendSetting = _cfg.settings.suspendable === true || _cfg.settings.suspendable === 'true_resume';

if (isExistSuspendData && isSuspendSetting) {
start_quiz('resume');
} else {
start_quiz();
}
}
}
}

function save_templates() {

single_choice_template = $('#choice').html();
single_choice_box_template = $('#choice_box').html();
multi_choice_template = $('#multi_choice').html();
button_template = $('#button').html();
input_template = $('#input').html();
before_question_template = $('#before').html();
input_math_template = $('#input_math').html();
fill_in_multi_template = $('#fill_in_multi').html();
textarea_template = $('#textarea').html();
true_false_template = $('#true_false').html();
sort_template = $('#sort').html();
wordbank_template = $('#wordbank').html();
match_template = $('#match').html();
result_detail_template1 = $('#result_table1 .result_detail');
result_detail_template2 = $('#result_table2 .result_detail');
}

window.onresize = function (event) {
fit_to_frame();
};

function fit_to_frame() {
$('body').css('margin-top', '0');
$('body').css('margin-left', '0');
$('body').css('margin-right', '0');
$('body').css('margin-bottom', '0');
$('body').css('padding', '0');
$('html').css('width', $(window).width() - 2);
$('html').css('height', $(window).height() - 2);
$('html').css('width', '100%');
$('html').css('height', '100%');
$('body').css('width', '100%');
$('body').css('height', '100%');
}

function load_config() {
var i;
if (typeof config !== 'undefined') {
delete default_config.questions;
_cfg = merge(config, default_config);
} else {
_cfg = default_config;
}
for (i = 0; i < _cfg.questions.length; i++) {
_cfg.questions[i].iid = i;


_cfg.questions[i].media_count = 0;

_cfg.questions[i].media_history = [];

_cfg.questions[i].change_count = 0;

_cfg.questions[i].prev_latency = 0;
}
}

function prepare_questions() {

var i, feedback, q, j, shuffle_flg;
for (i = 0; i < _cfg.questions.length; i++) {
feedback = false;
q = _cfg.questions[i];
if (
q.hasOwnProperty('type') &&
(q.type === 'fill-in' ||
q.type === 'textarea' ||
q.type === 'textarea-enquete' ||
q.type === 'textarea-report' ||
q.type === 'sort' ||
q.type === 'match' ||
q.type === 'wordbank' ||
q.type === 'fill-in-plus' ||
q.type === 'fill-in-multi' ||
q.type === 'pulldown')
) {
q.type = String(q.type); //Nothing to do
} else if (
(q.hasOwnProperty('type') && q.type === 'ma') ||
(!q.hasOwnProperty('type') && typeof q.answer === 'object')
) {
q.type = 'ma';
} else if (
(q.hasOwnProperty('type') &&
(q.type === 'sa' || q.type === 'sa-box' || q.type === 'button' || q.type === 'true-false')) ||
(!q.hasOwnProperty('type') && typeof q.answer === 'string')
) {
if (!q.hasOwnProperty('type') && typeof q.answer === 'string' && q.type !== 'sa-box') {
q.type = 'sa';
}
if (q.type === 'true-false') {
q.choice = ['true', 'false'];
}
if (typeof q.answer === 'string') {
q.answer = [q.answer];
}
q.feedback_map = {};
for (j = 0; j < q.choice.length; j++) {
if (q.hasOwnProperty('feedback')) {
if (typeof q.feedback === 'string') {
feedback = q.feedback;
} else if (j < q.feedback.length) {
feedback = q.feedback[j];
}
}
q.feedback_map[q.choice[j]] = feedback;
}
} else {
alert('the setting file is broken');
}
delete q.feedback;
if (_cfg.settings.shuffle_choices) {

if (q.type === 'sa' || q.type === 'sa-box' || q.type === 'ma' || q.type === 'button') {
q.choice.shuffle();
}
}
if (q.type === 'pulldown') {
for (j = 0; j < q.choice.length; j++) {
q.choice[j].shuffle();
}
}
if (q.type === 'sort' || q.type === 'wordbank') {
if (q.choice.length > 1) {
shuffle_flg = false;
while (!shuffle_flg) {
q.choice.shuffle();
shuffle_flg = is_shuffle(q.choice, q.answer);
}
}
}
if (q.type === 'match') {
if (q.choice.length > 1) {
shuffle_flg = false;
while (!shuffle_flg) {
q.choice.shuffle();
shuffle_flg = is_shuffled_match(q.choice, q.answer, q.match_key);
}
}
}


if (q.hasOwnProperty('quiz_id')) {
_cfg.questions[i].id = _cfg.questions[i].quiz_id;
} else {
_cfg.questions[i].id = String(i + 1);
while (_cfg.questions[i].id.length < _cfg.settings.id_digits) {
_cfg.questions[i].id = '0' + _cfg.questions[i].id;
}
_cfg.questions[i].id = _cfg.settings.id_prefix + _cfg.questions[i].id;
}
}
}

function load_suspend_data_body() {
for (i = 0; i < suspend_data_body.length; i += 4) {
if (_cfg.questions[i / 4]) {
_cfg.questions[i / 4].correct_count = parseInt(
suspend_data_body.substring(i, i + 2),
10
);
_cfg.questions[i / 4].incorrect_count = parseInt(
suspend_data_body.substring(i + 2, i + 4),
10
);
try {
_cfg.questions[i / 4].unknown_flag = parseInt(
suspend_data_body_unknown.substring(i / 4, i / 4 + 1),
10
); //unknown
} catch (e) {
_cfg.questions[i / 4].unknown_flag = 0;
}
}
}
}

var suspend_data_array;
function load_suspend_data() {

var i;
var suspend_data;
var recoveryData;
if (lbLocalStorage) {
recoveryData = lbLocalStorage.getItem("2cc349fb69929838af8c918603ea37900be522cc_recovery_data");
}
if (recoveryData == null) {
suspend_data = getValue('cmi.suspend_data');
} else {
suspend_data = recoveryData;
}
if (suspend_data && suspend_data.substring(0, 3) === '000') {

suspend_data_body = suspend_data.substring(4);
load_suspend_data_body();
} else if (suspend_data && suspend_data.substring(0, 1) === '{') {

suspend_data_array = JSON.parse(suspend_data);
suspend_data_body = suspend_data_array['counts'];
suspend_data_body_unknown = suspend_data_array['counts_unknown'];
load_suspend_data_body();
if (suspend_data_array && suspend_data_array.hasOwnProperty('position')) {

$('#start_quiz_button').css('visibility', 'hidden');
$('#resume_quiz_button').show();

if (_cfg.settings.suspendable === true) {
$('#restart_quiz_button').show();
}
if (suspend_data_array.hasOwnProperty('timeLeft')) {
suspendDataInitialTimeLimit = suspend_data_array.timeLeft;
}
} else {
$('#resume_quiz_button').hide();
$('#restart_quiz_button').hide();
}
} else {
suspend_data_body = '';
for (i = 0; i < _cfg.questions.length; i++) {
suspend_data_body += '0000';
}
}
for (i = 0; i < _cfg.questions.length; i++) {
if (!_cfg.questions[i].hasOwnProperty('correct_count')) {
_cfg.questions[i].correct_count = 0;
_cfg.questions[i].incorrect_count = 0;
}
}
}

function save_suspend_data() {
setValue('cmi.suspend_data', generate_suspend_data(false));
}

function generate_suspend_data(localStorageMode) {
var i;
var counts = '';
var counts_unknown = '';
var suspend_data;
var cc = [];
var ic = [];
var uc = [];
for (i = 0; i < suspend_data_body.length; i += 4) {
cc[i / 4] = suspend_data_body.substring(i, i + 2);
ic[i / 4] = suspend_data_body.substring(i + 2, i + 4);
try {
uc[i / 4] = suspend_data_body_unknown.substring(i / 4, i / 4 + 1);
} catch (e) {
uc[i / 4] = 0;
}
}
for (i = 0; i < _cfg.questions.length; i++) {
cc[_cfg.questions[i].iid] = format99(_cfg.questions[i].correct_count);
ic[_cfg.questions[i].iid] = format99(_cfg.questions[i].incorrect_count);
uc[_cfg.questions[i].iid] = _cfg.questions[i].unknown_flag ? '1' : '0';
}
for (i = 0; i < cc.length; i++) {
counts += cc[i] + ic[i];
counts_unknown += uc[i];
}
suspend_data = {
version: suspend_data_version,
counts: counts,
counts_unknown: counts_unknown
};
if (
_cfg.settings.mode == 'normal' &&
(_cfg.settings.suspendable === true || _cfg.settings.suspendable === 'true_resume') &&
(state === 'quiz' || state === 'list' || state === 'suspended')
) {
suspend_data.state = state;
suspend_data.suspend_count = currentSuspendCount;
suspend_data.questions = _cfg.questions;
suspend_data.position = position;
suspend_data.timeLeft = timeLeft;
}


suspend_data.studyLog = studyLogArray;

return str = JSON.stringify(suspend_data);
}

function format99(num) {

if (num < 10) {
return '0' + num;
}
if (num < 100) {
return String(num);
}
return '99';
}

function sortSectionArray(originalSortOrder, sortArray) {
return originalSortOrder.map(function (index) {
return sortArray[index]
});
}


function randomSection() {

let sectionArray = [];
let tempArray = [];
for (let i = 0; i < _cfg.questions.length; i++) {
if (_cfg.questions[i + 1]) {
if (_cfg.questions[i].section == _cfg.questions[i + 1].section) {

tempArray.push(_cfg.questions[i]);
} else {


tempArray.push(_cfg.questions[i]);
sectionArray.push(tempArray);
tempArray = [];
}
} else {


tempArray.push(_cfg.questions[i]);
sectionArray.push(tempArray);
}
}


for (let i = sectionArray.length - 1; i > 0; i--) {
let random = Math.floor(Math.random() * (i + 1));
let temp = sectionArray[i];
sectionArray[i] = sectionArray[random];
sectionArray[random] = temp;
}


let convertSectionArray = [];
convertSectionArray = Array.prototype.concat.apply([], sectionArray);


let originalOrderArray = [];

convertSectionArray.forEach(function (element) {
originalOrderArray.push(element.section);
});


originalOrderArray = originalOrderArray.filter(function (value, index, self) {
return self.indexOf(value) === index;
});


let section = 0;
for (let i = 0; i < convertSectionArray.length; i++) {
let currentSection = convertSectionArray[i].section
convertSectionArray[i].section = section;
if (convertSectionArray[i + 1] && currentSection != convertSectionArray[i + 1].section) {
section++;
}
}


_cfg.questions = convertSectionArray


_cfg.settings.section_name_array = sortSectionArray(originalOrderArray, _cfg.settings.section_name_array);
_cfg.settings.non_section_array = sortSectionArray(originalOrderArray, _cfg.settings.non_section_array);
_cfg.settings.section_tag_array = sortSectionArray(originalOrderArray, _cfg.settings.section_tag_array);
_cfg.settings.question_tag_array = sortSectionArray(originalOrderArray, _cfg.settings.question_tag_array);
_cfg.settings.question_count_array = sortSectionArray(originalOrderArray, _cfg.settings.question_count_array);
}

/**
* questionに対して各種情報を追加する
* @param {number} qi questions index
* @param {number} si section index
* @return {void}
*/
function formattedQuestion(qi, si) {
if (_cfg.settings.hasOwnProperty('section_name_array')) {
_cfg.questions[qi].section_name =
_cfg.settings.section_name_array[si];
}
if (_cfg.settings.hasOwnProperty('non_section_array')) {
_cfg.questions[qi].non_section = _cfg.settings.non_section_array[si];
}
if (_cfg.settings.hasOwnProperty('section_tag_array')) {
_cfg.questions[qi].section_tag = _cfg.settings.section_tag_array[si];
}
if (_cfg.settings.hasOwnProperty('question_tag_array')) {
_cfg.questions[qi].question_tag =
_cfg.settings.question_tag_array[si];
}
}


function order_by_section() {
'user strict';


const minSectionLength = 2;
if (_cfg.settings.shuffle_sections && minSectionLength <= _cfg.settings.section_name_array.length) {
randomSection();
}


_cfg.questions.forEach(function (question) {
question.sort = 9999;
});

_cfg.settings.question_count_array.forEach(function (_count, si) {

const questionsNumber = _cfg.questions.filter(function(question) {
return question.section == si;
}).length;


const isRequiredRandom = questionsNumber > Number(_cfg.settings.question_count_array[si]);
const hasSection = _cfg.settings.non_section_array.indexOf(false) > -1;


_cfg.settings.question_count_array[si] = Math.min(
_cfg.settings.question_count_array[si],
questionsNumber
);

if (!hasSection && !_cfg.settings.shuffle_questions) {
_cfg.questions.forEach(function(question, i) {
if (question.section != si) return;
formattedQuestion(i, si);
})
return;
}

let qi = 0;
while (_cfg.settings.question_count_array[si] > 0) {
if (isRequiredRandom) {
qi = Math.floor(Math.random() * _cfg.questions.length);
}

if (_cfg.questions[qi].sort == 9999) {

if (_cfg.questions[qi].section == si) {
_cfg.questions[qi].sort = si;
if (_cfg.settings.shuffle_questions) {
_cfg.questions[qi].sort += Math.random();
}
formattedQuestion(qi, si);
_cfg.settings.question_count_array[si]--;
}
}
if (!isRequiredRandom) {
qi += 1;
}
}
});

_cfg.questions.sort(function (a, b) {
return a.sort - b.sort;
});
}


function order_by_correct_answer_minus_incorrect_answer() {

_cfg.questions.sort(function (a, b) {
return (
a.correct_count -
a.incorrect_count -
(b.correct_count - b.incorrect_count)
);
});
}

function order_by_question_id() {

_cfg.questions.sort(function (a, b) {
return a.iid - b.iid;
});
}


function filter_by_correct_answer_count(limit) {

var i;
if (i === undefined) {
i = 0;
}
for (i = 0; i < _cfg.questions.length; i++) {
if (_cfg.questions[i].correct_count > limit) {
_cfg.questions.splice(i, 1);
i--;
}
}
}

function filter_by_status(limit) {

var i, is_weak;
for (i = 0; i < _cfg.questions.length; i++) {
is_weak = true;
if (_cfg.questions[i].correct_count > limit) {
is_weak = false;
console.log('correct enough');
}
if (
_cfg.questions[i].incorrect_count + _cfg.questions[i].correct_count ==
0
) {
is_weak = false;
console.log('no attempt');
}
if (is_weak === false) {
_cfg.questions.splice(i, 1);
i--;
}
}
}

function count_correctly_answered_questions() {

var count = 0,
i;
for (i = 0; i < _cfg.questions.length; i++) {
count += _cfg.questions[i].correct_count;
}
return count;
}

function count_not_correctly_answered_questions_float1(limit) {

var count = 0,
i;
for (i = 0; i < _cfg.questions.length; i++) {
if (!_cfg.questions[i].hasOwnProperty('correct_count')) {
count += 1;
} else if (_cfg.questions[i].correct_count <= limit) {
count += 1 - _cfg.questions[i].correct_count / limit;
}
}
return count;
}

function count_not_correctly_answered_questions_float2() {

var count = 0,
i;
for (i = 0; i < _cfg.questions.length; i++) {
if (!_cfg.questions[i].hasOwnProperty('correct_count')) {
count += 1;
} else {
count += 1 - _cfg.questions[i].correct_count;
}
}
return count;
}

function get_completion_rate() {

if (
count_correctly_answered_questions() <=
_cfg.settings.master_count * _cfg.questions.length
) {
return String(
Math.round(
(1 -
count_not_correctly_answered_questions_float1(
_cfg.settings.master_count
) /
_cfg.questions.length) *
100
)
);
} else {
return String(
Math.round(
((1 -
count_not_correctly_answered_questions_float2() /
_cfg.questions.length) /
_cfg.settings.master_count) *
100
)
);
}
}

let pagination = null;
function start_quiz(mode) {

startTime = new Date().getTime();
$('#page_intro video,#page_intro audio,#page_intro iframe').remove();
if (mode !== undefined) {
if (mode === 'not_answerd') {
filter_by_correct_answer_count(_cfg.settings.master_count - 1);
} else if (mode === 'weak') {
if (
count_correctly_answered_questions() >=
_cfg.settings.master_count * _cfg.questions.length
) {
_cfg.settings.shuffle_questions = false;
order_by_correct_answer_minus_incorrect_answer();
_cfg.questions = _cfg.questions.slice(0, _cfg.settings.weak_count);
} else {
_cfg.settings.shuffle_questions = false;
order_by_correct_answer_minus_incorrect_answer();
filter_by_correct_answer_count(_cfg.settings.master_count - 1);
}
} else if (mode === 'review') {
_cfg.settings.shuffle_questions = true;
} else if (mode === 'resume') {
position = suspend_data_array.position;
setTimeout(function () {
var new_state = suspend_data_array.state;
if (new_state == 'suspended') {
new_state = 'quiz';
}
cstate(new_state);
}, 50);
_cfg.questions = suspend_data_array.questions;
}
_cfg.actionmode = mode;
}
_cfg.settings.question_count = Math.min(
_cfg.questions.length,
_cfg.settings.question_count
);
$('#question_count').html(_cfg.settings.question_count);
if (mode !== 'resume') {
order_by_section();    // タグ付け以降、order_by_sectionでランダム出題なども対応
}


settingSuspendOption(mode);

cstate('quiz');
display_quiz();
init_timer();
show('#page_quiz');


if (_cfg.settings.movable && !_cfg.settings.hide_pagination && !pagination) {
pagination = new Pagination('#pagination', _cfg.questions);

if (mode === 'resume') {
pagination.allQuestionToggleAnswerState();
}

$('#question_count_wrapper').hide();
} else {
$('#question_count_wrapper+.tooltip-common').remove();
}
}

function settingSuspendOption(mode){
if (_cfg.settings.suspendable) {

_cfg.settings.suspendable_count = Math.floor(_cfg.settings.suspendable_count);

if (1 <= _cfg.settings.suspendable_count && _cfg.settings.suspendable_count <= 99) {
if (suspend_data_array && suspend_data_array.hasOwnProperty('suspend_count') && mode == 'resume') {


currentSuspendCount = suspend_data_array['suspend_count'] + 1;
} else {

currentSuspendCount = 1;
}
if (_cfg.settings.suspendable_count <= (currentSuspendCount - 1)) {

$('#suspend_button').removeClass('btn-outline-warning');
$('#suspend_button').addClass('btn-blue-grey');
$('#suspend_button').html('<span>中断:' + _cfg.settings.suspendable_count + '/' + _cfg.settings.suspendable_count + '</span>');
$('#suspend_button').prop('disabled', true);
$("#suspend_button").removeAttr("onclick");
$('.suspend_tooltip').text('これ以上、中断することはできません');
} else {

$('#suspend_button').html('<span>中断:' + (currentSuspendCount - 1) + '/' + _cfg.settings.suspendable_count + '</span>');
}
}
setSuspendButtonVisibility(_cfg.settings.show_suspendable_button);
} else {
setSuspendButtonVisibility(false);
}
}

function setSuspendButtonVisibility(isVisible) {
const $btn = $('#suspend_button')
const $tooltip = $btn.closest('.tooltip-wrapper');
if (isVisible) {
$tooltip.show();
} else {
$tooltip.hide();
$btn.removeAttr("onclick");
}
}

function init_timer() {

if (_cfg.settings.time_limit) {
if (_cfg.settings.time_limit_mode == 'question') {
$('.list').hide();
$('.timer_wrapper').css('right', '5px');
}
$('.timer').countdown('destroy');



let timeLimit = (suspendDataInitialTimeLimit === null ? _cfg.settings.time_limit : suspendDataInitialTimeLimit) * 1000;
suspendDataInitialTimeLimit = null;

$('.timer:first').countdown({
until: new Date(new Date().getTime() + timeLimit),
format: 'HMS',
onTick: checkTimeLimit,
tickInterval: 1,
compact: true
});
$('.timer:not(:first)').countdown({
until: new Date(new Date().getTime() + timeLimit + 100),
format: 'HMS',
tickInterval: 1,
compact: true
});
} else {

$('#timer_wrap_quiz').remove();
$('#timer_wrap_list').remove();
}
}
function checkTimeLimit(t) {

var i;
if (finished) {
return;
}
window.timeLeft = t[6] + t[5] * 60 + t[4] * 3600;
var width = (timeLeft / _cfg.settings.time_limit) * 100;
$('.progress-bar.bg-success').css('width', width.toPrecision(4) + '%');
var div = 30;
for (i = 0; i < div; i++) {
var timeLeft = t[6] + t[5] * 60 + t[4] * 3600 - i / div;
var width = (timeLeft / _cfg.settings.time_limit) * 100;
setTimeout(
'$(".progress-bar.bg-success").css("width", ' +
width.toPrecision(4) +
' + "%")',
(i / div) * 1000
);
}
for (i = 0; i < 7; i++) {
if (t[i] !== 0) {
return;
}
}
if (_cfg.settings.time_limit_mode == 'total') {
$('.ui-draggable-dragging').remove(); // Timelimit for all questions
check_answer(false, true, true);
show_result();

helpToolTipHide();
} else if (_cfg.settings.time_limit_mode == 'question') {

check_answer(false, true, true);
helpToolTipHide();
}
}


function isNumber(answerArray, type) {

const regEXP = (type === 'fill-in-plus') ? /^[-+,\d]+$/ : /^[-+\d]+$/;
let isNumber = true;

for (var i = 0; i < answerArray.length; i++) {
if (answerArray[i].match(regEXP) == null) {
isNumber = false;
}
}
return isNumber;
}


function addFillInLengthLimitEvent(target, limitNum, index) {
$(document).on('keyup change blur', target, function (event) {

if (event.type == 'focusout') {
$('.input_limit_error_message').hide();
return;
}

let value = $(this).val();


if (cq.hasOwnProperty('previousLimitValue') && cq.previousLimitValue == value) {
return;
}
if (cq.hasOwnProperty('previousLimitValueArray') && cq.previousLimitValueArray[index] == value) {
return;
}

if (value.length > limitNum) {

$(this).val(value.slice(0, limitNum));

$('.input_limit_error_message').show();

if (cq.hasOwnProperty('previousLimitValueArray')) {
cq.previousLimitValueArray[index] = $(this).val();
} else {
cq.previousLimitValue = $(this).val();
}
} else {

$('.input_limit_error_message').hide();
}
});
}


function settingMultipleFillInLimitEvent(settingValue) {
cq.previousLimitValueArray = [];
for (let i = 0; i < cq.answer.length; i++) {
classPos = '.pos' + i;

let strLength = 0;

if (settingValue != null) {
strLength = settingValue;
} else {

const lengthArray = cq.answer[i].split('::').map(function (answer) {
return answer.length;
});

strLength += Math.max.apply(null, lengthArray);
}


addFillInLengthLimitEvent('.input' + '.fill_in_multi' + classPos, strLength, i);
}
}


function settingFillInLengthLimit() {
let isNumberInput = _cfg.settings.use_number_type_for_input;
let settingValue = _cfg.settings.fill_in_max_length;

if (isNumberInput) {
if (settingValue == 'auto') {
let strLength = 0;

if (cq.type == 'fill-in') {

let answerLengthArray = cq.answer.map(function (answer) {
return answer.length;
})

strLength = Math.max.apply(null, answerLengthArray);
} else if (cq.type == 'fill-in-plus') {

for (let i = 0; i < cq.answer.length; i++) {

const lengthArray = cq.answer[i].split(',').map(function (answer) {
return answer.length;
});

strLength += Math.max.apply(null, lengthArray);
}

strLength += cq.answer.length - 1;
}
addFillInLengthLimitEvent('#input_line', strLength);
} else if (settingValue.match(/^([1-9]\d*)$/) && 0 < settingValue) {
addFillInLengthLimitEvent('#input_line', settingValue);
}
}
}


function settingFillInMultiLengthLimit() {
let isNumberInput = _cfg.settings.use_number_type_for_input;
let settingValue = _cfg.settings.fill_in_max_length;
let classPos = '';

if (isNumberInput) {
if (settingValue == 'auto') {
settingMultipleFillInLimitEvent(null);
} else if (settingValue.match(/^([1-9]\d*)$/) && 0 < settingValue) {
settingMultipleFillInLimitEvent(settingValue)
}
}
}


function settingFilInPermitOnlyNumber() {

if (_cfg.settings.use_number_type_for_input) {

if (isNumber(cq.answer, cq.type)) {
cq.previousValue = '';
let descriptionEvent = addFillInNumberEvent(null, null);
cq.descriptionEventList.push(descriptionEvent);
}
}
}


function settingFillInMultiPermitOnlyNumber() {

if (_cfg.settings.use_number_type_for_input) {

if (isNumber(cq.answer, cq.type)) {
cq.previousValueArray = [];
for (let i = 0; i < cq.answer.length; i++) {
cq.previousValueArray[i] = '';
const targetPosClass = '.pos' + i;
const descriptionEvent = addFillInNumberEvent(targetPosClass, i);
cq.descriptionEventList.push(descriptionEvent);
}
}
}
}


function resetFillInEvent(answerNum)
{
$(document).off('keyup change blur', '#input_line');
for (let i = 0; i < answerNum; i++){
$(document).off('keyup change blur', '.input.fill_in_multi.pos' + i);
}
}

var answerMathField;
var tempSecTag = [];
var tempQuesTag = [];

function display_quiz() {
var i,
cq_question,
input_html,
choice_value,
choice_html,
scale,
match_list_width,
drag_list,
dropDownFunc;
storeRecoveryData();
setTimeout(function () {
window.scrollTo(0, 0);
if (isIOS() && !API.hasOwnProperty('dummy')) {
parent.scrollTo(0, 0);
}
}, 50);


oneTimeAudioCount = -1;


if (pagination) {
pagination.toggleAnswerState(cq, previousPosition);
}


if (cq && cq.descriptionEventList) {
cq.descriptionEventList.forEach(function (event) {
event.off('keyup change');
});
}


cq = _cfg.questions[position];


cq.descriptionEventList = [];


if (_cfg.settings.hide_list_button) {
$('#hide_list_button').hide();
} else {
$('#hide_list_button').show();
}


if (_cfg.settings.tag_visible) {
$('.tag_visible').show();
} else {
$('.tag_visible').hide();
}

$('#position').html(position + 1);
$('#instant_feedback_msg').html('');
if (cq.hasOwnProperty('section_name')) {
if (cq.non_section == false) {
$('#section_name').html(h(htmlspecialchars_decode(cq.section_name, 'ENT_QUOTES')));
$('#section_name').removeClass();
$('#section_name').addClass('section_name_' + (cq.section % 6));
$('#section_name').addClass('card card-body');
} else {
$('#section_name')
.parent()
.empty();
}
if (cq.section_name == undefined || cq.section_name == '') {
$('#section_name').hide();
} else {
$('#section_name').show();
}
if ($('#section_tag').has('span')) {
$('#section_tag').empty();
}
for (var i = 0; i < cq.section_tag.length; i++) {
if (cq.section_tag[i] != '') {
$('#section_tag').append(
'<span class="section_tag_' +
(i + 1) +
'"' +
'style="font-size: 12px; color: white; background-color: #007E33; padding: 0 4px; margin: 0 3px; border-radius: 3px">' +
h(htmlspecialchars_decode(cq.section_tag[i], 'ENT_QUOTES')) +
'</span>'
);
}
}
if ($('#question_tag').has('span')) {
$('#question_tag').empty();
}
for (i in cq.question_tag) {
if (i == cq.iid) {
tempSecTag[i] = [];
tempQuesTag[i] = [];
for (var j = 0; j < cq.section_tag.length; j++) {
tempSecTag[i][j] = [];
tempSecTag[i][j] = cq.section_tag[j];
}
for (var k = 0; k < cq.question_tag[i].length; k++) {
tempQuesTag[i][k] = [];
tempQuesTag[i][k] = cq.question_tag[i][k];
$('#question_tag').append(
'<span class="question_tag_' +
i +
'_' +
(k + 1) +
'"' +
'style="font-size: 12px; color: white; background-color: #00b549; padding: 0 4px; margin: 0 3px; border-radius: 3px">' +
h(htmlspecialchars_decode(cq.question_tag[i][k], 'ENT_QUOTES')) +
'</span>'
);
}
}
}
setTimeout(update_seigo_counts, 10); // wait until section name width is updated
} else {
update_seigo_counts();
}
$('#choices').empty();
$('#instant_answer_msg').empty();
$('#instant_response_disp').hide();
$('#instant_response_disp_none').hide();
$('#instant_result_wrapper').hide();
$('#instant_answer_wrapper').hide();
$('#instant_feedback_wrapper').hide();
$('#instant_response_container').hide();
$('#instant_response_background').hide();
$('#answer_mark_correct').hide();
$('#answer_mark_incorrect').hide();
if (has_next_quiz() && _cfg.settings.movable) {
$('#display_next_quiz').css('display', 'block');
} else {
$('#display_next_quiz').css('display', 'none');

$('#display_next_quiz+span').css('display', 'none');
}
if (has_prev_quiz() && _cfg.settings.movable) {
$('#display_prev_quiz').css('display', 'block');
} else {
$('#display_prev_quiz').css('display', 'none');

$('#display_prev_quiz+span').css('display', 'none');
}
if (_cfg.settings.show_instant_result) {
$('#not_disp_answer_next_button').hide();
$('#not_disp_answer_mark_button').hide();
if (cq.type !== 'button' && cq.type !== 'true-false' && state != 'quiz_review') {
$('#check_answer_button').show();
} else {
$('#check_answer_button').hide();
}
$('#check_answer_next_button')
.hide()
.attr('disabled', true);
} else {
$('#check_answer_button').hide();
if (!_cfg.settings.movable) {
$('#display_next_quiz').css('display', 'none');
$('#display_prev_quiz').css('display', 'none');
$('#not_disp_answer_mark_button').css('margin-left', '5px');
if (has_next_quiz()) {
if (cq.type == 'button' || cq.type == 'true-false') {
$('#not_disp_answer_next_button').hide();
} else {
$('#not_disp_answer_next_button').show();
}
} else {
$('#not_disp_answer_next_button').hide();
}
} else {
$('#not_disp_answer_next_button').hide();
}
if (_cfg.settings.hide_mark_button && has_next_quiz()) {
$('#not_disp_answer_mark_button').hide();
} else {
if (cq.type == 'button' || cq.type == 'true-false') {
$('#not_disp_answer_mark_button').hide();
} else {
$('#not_disp_answer_mark_button').show();
}
}
}
if ($(':focus').attr('id') === 'check_answer_next_button') {
$('#check_answer_next_button').blur();
}
cq_question = cq.question;
if (cq.type === 'wordbank') {
cq_question = convert_drop_list(cq_question);
}
if (cq.type === 'pulldown') {
cq_question = convert_pulldown(cq_question);
}
cq_question = convert_image_tags(cq_question, 'not_sa-box');
$('#question').html(cq_question);

if (cq.before_question) {
let convertBeforeQuestion = convert_image_tags(cq.before_question);
$('#choices').append(before_question_template);
$('#before_question').html(convertBeforeQuestion);
}
if (cq.type === 'fill-in' || cq.type === 'fill-in-plus') {
input_html = '<div class="choice">' + input_template + '</div>';


resetFillInEvent(cq.answer.length);

settingFilInPermitOnlyNumber();

settingFillInLengthLimit();

$('#choices').append(input_html);

$('#choices .input').attr('value', cq.student_response);
setTimeout(function () {
if (
$('#choices input')
.get(0)
.getBoundingClientRect().bottom <
window.innerHeight - 20
) {
$('#choices input')[0].focus();
}
}, 100);
} else if (cq.type === 'fill-in-multi') {
input_html = '<div class="choice">' + fill_in_multi_template + '</div>';


resetFillInEvent(cq.answer.length);

settingFillInMultiPermitOnlyNumber();

settingFillInMultiLengthLimit();

$('#choices').append(input_html);

$('#choices .input').hide();
for (var i = 0; i < cq.answer.length; i++) {
$('#choices .pos' + i).show();
if (cq.label && cq.label[i]) {

$('#choices div.pos' + i).html(htmlencode(cq.label[i]));
}
}
if (cq.student_response) {
for (var i = 0; i < cq.answer.length; i++) {
$('#choices input.input.pos' + i).val(cq.student_response[i]);
}
}
setTimeout(function () {
if (
$('#choices input')
.get(0)
.getBoundingClientRect().bottom <
window.innerHeight - 20
) {
$('#choices input')[0].focus();
}
}, 100);
} else if (
cq.type === 'textarea' ||
cq.type === 'textarea-enquete' ||
cq.type === 'textarea-report'
) {
input_html = '<div class="choice">' + textarea_template + '</div>';
$('#choices').append(input_html);
$('#choices textarea').text(cq.student_response);
setTimeout(function () {
$('#choices textarea')[0].focus();
}, 100);
} else if (cq.type === 'button') {
for (i = 0; i < cq.choice.length; i++) {
choice_value = convert_image_tags(cq.choice[i]);
choice_html = button_template;
choice_html = choice_html.replace(/\[\[choice\]\]/g, choice_value);
choice_html = choice_html.replace(
/\[\[choice_key\]\]/g,
htmlencode(cq.choice[i])
);
choice_html = choice_html.replace(
/\[\[choice_key_js_escaped\]\]/g,
htmlencode(jsencode(cq.choice[i]))
);
choice_html = choice_html.replace(
/\[\[choice_id\]\]/g,
'choice_' + position + '_' + i
);
choice_html = '<div class="choice">' + choice_html + '</div>';
$('#choices').append(choice_html);
}
if (_cfg.settings.pass) {
choice_value = '分からない';
choice_html = button_template;
choice_html = choice_html.replace(/\[\[choice\]\]/g, choice_value);
choice_html = choice_html.replace(/\[\[choice_key\]\]/g, '分からない');
choice_html = choice_html.replace(
/\[\[choice_key_js_escaped\]\]/g,
htmlencode(jsencode('分からない'))
);
choice_html = choice_html.replace(
/\[\[choice_id\]\]/g,
'choice_' + position + '_' + i
);
choice_html = '<div class="choice">' + choice_html + '</div>';
$('#choices').append(choice_html);
}
} else if (cq.type === 'true-false') {
$('#choices').append(true_false_template);
} else if (cq.type === 'sort') {
setDragDropList();
setDragDropEvent();
setTimeout(function () {
setDivHeight();
}, 10);
} else if (cq.type === 'match') {
setDragDropList();
setDragDropEvent();
setTimeout(function () {
setDivHeight();
}, 10);
if (pc_flg) {
scale = _cfg.settings.scale;
match_list_width =
$('.drag-choice')
.css('width')
.replace('px', '') * scale;
$('.drag-choice,.drop-choice-key').css('width', match_list_width);
}
} else if (cq.type === 'pulldown') {
if (cq.student_response) {
for (i = 0; i < cq.student_response.length; i++) {
$($('select')[i]).val(cq.student_response[i]);
}
}
} else if (cq.type === 'wordbank') {
for (i = 0; i < cq.choice.length; i++) {
choice_value = cq.choice[i];
choice_html = wordbank_template;
choice_html = choice_html.replace(
/\[\[choice\]\]/g,
convert_image_tags(choice_value)
);
choice_html = choice_html.replace(
/\[\[choice_key\]\]/g,
htmlencode(cq.choice[i])
);
choice_html = choice_html.replace(/\[\[choice_idx\]\]/g, i);
$('#choices').append(choice_html);
}
setDragDropEvent();
if (cq.student_response) {
dropDownFunc = function () {
if (
$(this)
.find('.drag-value')
.attr('value') === cq.student_response[i]
) {
drag_list = $(this).children('.drag-choice-wordbank');
drag_list.parent('#choices .drop-choice-list').css('display', 'none');
$('#question .drop-choice-wordbank')
.eq(i)
.append(drag_list);
drag_list.prevAll('.wordbank-key').css('display', 'none');
}
};
for (i = 0; i < cq.student_response.length; i++) {
if (cq.student_response[i] !== '未選択') {
$('.drop-choice-list').each(dropDownFunc);
}
}
}
} else {

if (cq.type === 'sa-box') {
flex_sa_wrapper = '<div class="row flex-sa-wrapper"></div>';
$('#choices').append(flex_sa_wrapper);
}
for (i = 0; i < cq.choice.length; i++) {
choice_value = convert_image_tags(cq.choice[i]);
choice_html = '';
if (cq.type === 'ma') {
choice_html = multi_choice_template;
} else if (cq.type === 'sa') {
choice_html = single_choice_template;
} else if (cq.type === 'sa-box') {
choice_html = single_choice_box_template;
}
choice_html = choice_html.replace(/\[\[choice\]\]/g, choice_value);
choice_html = choice_html.replace(
/\[\[choice_key\]\]/g,
htmlencode(cq.choice[i])
);
choice_html = choice_html.replace(
/\[\[choice_id\]\]/g,
'choice_' + position + '_' + i
);

if (cq.type === 'sa-box') {
choice_html = '<div class="choice col-12 col-md-6 sa-box-choice">' + choice_html + '</div>';
$('.flex-sa-wrapper').append(choice_html);
} else {
choice_html = '<div class="choice">' + choice_html + '</div>';
$('#choices').append(choice_html);
}
}
if (_cfg.settings.pass) {
if (cq.type === 'sa-box') {
flex_sa_wrapper = '<div class="row flex-sa-wrapper"></div>';
$('#choices').append(flex_sa_wrapper);
}
choice_value = '分からない';
choice_html = '';
if (cq.type === 'ma') {
choice_html = multi_choice_template;
} else if (cq.type === 'sa') {
choice_html = single_choice_template;
} else if (cq.type === 'sa-box') {
choice_html = single_choice_box_template;
}
choice_html = choice_html.replace(/\[\[choice\]\]/g, choice_value);
choice_html = choice_html.replace(/\[\[choice_key\]\]/g, '分からない');
choice_html = choice_html.replace(
/\[\[choice_id\]\]/g,
'choice_' + position + '_' + i
);
if (cq.type === 'sa-box') {
choice_html = '<div class="choice col-12 col-md-6 sa-box-choice">' + choice_html + '</div>';
$('.flex_sa_wrapper').append(choice_html);
} else {
choice_html = '<div class="choice">' + choice_html + '</div>';
$('#choices').append(choice_html);
}
}
$('.choice_checkbox').each(function () {
if (
cq.student_response &&
array_contain([$(this).attr('value')], cq.student_response)
) {
$(this).attr('checked', 'checked');
}
if (cq.limit) {
$(this).on('click', checkSelectionLimit);
}
});

$('.choice_radio').each(function () {
if (
cq.student_response &&
array_contain([$(this).attr('value')], cq.student_response)
) {
$(this).attr('checked', 'checked');


window.checkedValue = $('.choice_radio:checked').val();
}
$(this).on('click', removeChecked);
});
setTimeout(function () {
if (
$('#choices input')
.get(0)
.getBoundingClientRect().bottom <
window.innerHeight - 20
) {
$('#choices input')[0].focus();
}
}, 100);
}
if (cq.result) {
if (state === 'quiz_review') {
check_answer(false, false, true);
} else {
check_answer(true, true, true);
}
}
applyMathJax();


addMediaEvent(true);

if (_cfg.settings.autoplay) {

if ($('#contents_wrapper audio.autoplay:first').length > 0) {
$('#contents_wrapper audio.autoplay:first')[0].play();
}
}

cq.time = getCurrentTimeForSCORM12();
if (state === 'quiz_review' && _cfg.settings.show_instant_result === false) {
$('#show_result').show();
$('#not_disp_answer_next_button').hide();
$('#not_disp_answer_mark_button').hide();
}


if (pagination) {
pagination.updateActivePosition(position);
}


helpToolTipHide();

if (_cfg.settings.layout === 'exam') {
window.layout.examFunc();
}

if (_cfg.settings.layout === 'exam-vertical') {
window.layout.examVerticalFunc();
}
}


function pushMediaLog(event) {
if (event.target.controls) {

_cfg.questions[position].media_count++;

_cfg.questions[position].media_history.push(event.target.src.split('/').pop());
}
}


function pauseMediaExcludeSelf(own, videos, audios) {
for (let i = 0; i < videos.length; i++) {
if (videos[i] != own) {
videos[i].pause();
}
}
for (let i = 0; i < audios.length; i++) {
if (audios[i] != own) {
audios[i].pause();
}
}
}


function pauseAllMedias(videos, audios) {
if (videos == null) {
videos = document.querySelectorAll('video');
}
if (audios == null) {
audios = document.querySelectorAll('audio');
}

for (let i = 0; i < videos.length; i++) {
videos[i].pause();
}
for (let i = 0; i < audios.length; i++) {
audios[i].pause();
}
}


function addMediaEvent(isPauseMedia) {
const videos = document.querySelectorAll('video');
const audios = document.querySelectorAll('audio');

if (isPauseMedia) {

pauseAllMedias(videos, audios);
}


for (i = 0; i < videos.length; i++) {
videos[i].addEventListener('play', function (event) {
pauseMediaExcludeSelf(this, videos, audios);
pushMediaLog(event)
});
}


for (i = 0; i < audios.length; i++) {
audios[i].addEventListener('play', function (event) {
pauseMediaExcludeSelf(this, videos, audios);
pushMediaLog(event)
});
}
}

function updateLinkTarget() {
$('a').prop('target', '_blank');
}

function update_seigo_counts() {
if (_cfg.settings.show_seigo_count) {
if (isQuizUIVisible()) {
$('#correct-count >.num').html(cq.correct_count);
$('#incorrect-count >.num').html(cq.incorrect_count);
}
} else {
$('#correct-count').hide();
$('#incorrect-count').hide();
}
}


var applyMathJaxStopper = false;
var imgSize = {};



function applyMathJax() {

if (applyMathJaxStopper) return;
applyMathJaxStopper = true;
setTimeout(function () {
applyMathJaxStopper = false;
}, 50);
updateLinkTarget();
$('img').on('load', function () {
var img = new Image();
img.src = $(this).attr('src');
img.originalSrc = $(this).attr('data-original-src');

img.onload = function () {
var width = img.width;
var height = img.height;
imgSize[img.originalSrc] = width + "x" + height;
initPhotoSwipeFromDOM('.my-gallery');
}
});

if (typeof MathJax !== 'undefined' && _cfg.settings.math) {
MathJax.Callback.Queue(
['Typeset', MathJax.Hub, 'preview'],
[
function () {
setDivWidth();
}
]
);
}
}


function addFillInNumberEvent(targetPosClass, index) {
let selector = '';
if (targetPosClass == null) {
selector = '#input_line';
} else {
selector = ".fill_in_multi" + targetPosClass;
}

return $(document).on('keyup change', selector, function () {

let value = null;
let regExp = null;

if (cq.hasOwnProperty('previousValue')) {

value = $('#input_line').val();

regExp = (cq.type == 'fill-in-plus') ? /[^-+, 　\d]+/g : /[^-+\d]+/g;
} else {

value = $(".fill_in_multi" + targetPosClass).val();
regExp = /[^-+\d]+/g;
}

if (cq.hasOwnProperty('previousValue') && value == cq.previousValue) {
return;
}

if (cq.hasOwnProperty('previousValueArray') && value == cq.previousValueArray[index]) {
return;
}


let isReplace = false;
value = value.replace(regExp, function () {
isReplace = true;
return '';
});

isReplace ? $('.numeric_error_message').show() : $('.numeric_error_message').hide();


if (cq.hasOwnProperty('previousValue')) {
cq.previousValue = value;
$('#input_line').val(value);
} else {
cq.previousValueArray[index] = value;
$(".fill_in_multi" + targetPosClass).val(value);
}
});
}


function zeroPadding(num, len) {
return (Array(len).join('0') + num).slice(-len);
}


function getDate() {
let dt = new Date();
let date = dt.getFullYear() + '/' + zeroPadding((dt.getMonth() + 1), 2) + '/' + zeroPadding(dt.getDate(), 2);
return date;
}


function getTime() {
let dt = new Date();
let time = zeroPadding(dt.getHours(), 2) + ':' + zeroPadding(dt.getMinutes(), 2) + ':' + zeroPadding(dt.getSeconds(), 2);
return time;
}


function getAnswer() {

let answer = 'unanswered';
if (cq.student_response.length !== 0) {
if (Array.isArray(cq.student_response)) {

answer = cq.student_response.concat();

for (i = 0; i < answer.length; i++) {
if (cq.type == 'fill-in-multi') {

if (answer[i] === '') {
answer[i] = 'unanswered';
}
} else {

if (answer[i] === '未選択') {
answer[i] = 'unselected';
}
}
}
} else {
answer = cq.student_response;
}
}
return answer;
}


function getResultMessage() {
let resultMessage = 'incorrect';

if (cq.hasOwnProperty('result') && cq.result) {
resultMessage = cq.result
} else if (cq.hasOwnProperty('tempResult') && cq.tempResult) {
resultMessage = cq.tempResult;
}


if (cq.type == 'textarea-report') {
resultMessage = 'scoring_pending';
}

return resultMessage;
}


function getCorrectness() {
if (_cfg.questions[position].hasOwnProperty('correctness')) {
return _cfg.questions[position].correctness;
} else {
return [_cfg.questions[position].answer.length, 0];
}
}


function getScoreRate(correctness) {
if (cq.type == 'textarea-report') {
return 'scoring_pending'
} else {

return round2ndDecimal((correctness[1] / correctness[0]) * 100);
}
}


function getScore(weight, correctness) {
if (cq.type == 'textarea-report') {
return 'scoring_pending'
} else {

return round2ndDecimal(fraction.toDouble(fraction.mul([1, weight], correctness)));
}
}


function updateStudyLogInfo() {
for (i = studyLogArray.length - 1; 0 <= i; i--) {
if (cq.id == studyLogArray[i]['quiz_id']) {
studyLogArray[i]['last_answer_flag'] = '';

if (cq.type == 'textarea-report') {
studyLogArray[i]['result'] = '';
studyLogArray[i]['score_rate'] = '';
studyLogArray[i]['score'] = '';
studyLogArray[i]['scoring_pending_flag'] = false;
}
break;
}
}
}


function saveOperationLog() {

if (state != 'quiz' && state != 'list') { return; }


if (JSON.stringify(_cfg.questions[position].prev_student_response) !== JSON.stringify(cq.student_response)) {

_cfg.questions[position].change_count++;

updateStudyLogInfo();

let weight = _cfg.settings.score_weighting ? cq.weight : 100 / _cfg.settings.question_count;

let correctness = getCorrectness();

let isScoringPending = false;
if (cq.type == 'textarea-report') {
isScoringPending = true;
}


let logData = {
quiz_id: cq.id,
answer_count: _cfg.questions[position].change_count,
last_answer_flag: 'TRUE',
scoring_pending_flag: isScoringPending,
problem_statement: cq.question,
answer: getAnswer(),
media_operation_count: _cfg.questions[position].media_count,
media_operation_history: _cfg.questions[position].media_history,
result: getResultMessage(),
point_allocation: round2ndDecimal(weight),
score_rate: getScoreRate(correctness),
score: getScore(weight, correctness),
duration: formatTimeIntervalForSCORM12((cq.latency - _cfg.questions[position].prev_latency) * 100),
answer_time: getDate() + ' ' + getTime(),
}

studyLogArray.push(logData);


_cfg.questions[position].prev_student_response = cq.student_response;

_cfg.questions[position].prev_latency = cq.latency;

_cfg.questions[position].media_count = 0;

_cfg.questions[position].media_history = [];
}
}

function display_prev_quiz() {

if (has_prev_quiz()) {

check_answer(false, true, false);

previousPosition = position;
position--;
display_quiz();
}
}

var blockDuplicatedMove = false;
function display_next_quiz() {

if (has_next_quiz()) {
if (blockDuplicatedMove) {
return;
}
blockDuplicatedMove = true;
setTimeout(function () {
blockDuplicatedMove = false;
}, 100);

check_answer(false, true, false);

previousPosition = position;
position++;
display_quiz();
}
if (_cfg.settings.time_limit_mode == 'question') {
init_timer();
}
}

function has_prev_quiz() {

return position > 0;
}

function has_next_quiz() {

return position < _cfg.settings.question_count - 1;
}

function getMediaData(a, b, isWidth) {

if (isWidth == null) { isWidth = true; }

let bArray = b.split(/ +/);
let style = '';
let alt = '';

for (let i = 1; i < bArray.length; i++) {
let vals = bArray[i].split('=');
let key = vals[0];
let value = vals[1];
if (key == 'width' && isWidth) style += 'width:' + value + 'px;';
if (key == 'height') style += 'height:' + value + 'px;';
if (key == 'alt') alt += value;
}


let array = {
'style': style,
'url': bArray[0],
'alt': alt,
};

return array;
}


function playSpecifiedTimesAudio(count) {
if (_cfg.questions[position]['one_time_audio_' + count] == false) {

let $audio = $("#one_time_audio_" + count).get(0);
$audio.pause();
$audio.currentTime = 0;
$audio.play();

_cfg.questions[position]['one_time_audio_limit_' + count]--;


if (_cfg.questions[position]['one_time_audio_limit_' + count] <= 0) {
$("#one_time_audio_button_" + count).prop("disabled", true);
_cfg.questions[position]['one_time_audio_' + count] = true;
}
}
}


function loadAudio(count, limitNum) {

if (_cfg.questions[position]['one_time_audio_' + count]) {
$('#one_time_audio_button_' + count).prop("disabled", true);
}

if (_cfg.questions[position]['one_time_audio_' + count] == null) {
_cfg.questions[position]['one_time_audio_' + count] = false;
_cfg.questions[position]['one_time_audio_limit_' + count] = limitNum;
}
}

function getPlayAudioLimitNum(group) {

let limitNum = 1;


if (group.match(/.+.mp3::{(\d+)}/)) {

limitNum = group.match(/.+.mp3::{(\d+)}/)[1];
}

return limitNum;
}

function convert_image_tags(str, cq_question_img_flag) {


if (_cfg.settings.autoplay) {
str = str.replace(
/\[\[\[((.+?.mp3).*?)\]\]\]/g, function (all, group1, group2) {

oneTimeAudioCount++;

let limitNum = getPlayAudioLimitNum(group1);

return '<span>' +
'<audio id="one_time_audio_' + oneTimeAudioCount + '" class="audio audio_with_controls" src="' + group2 + '" preload onloadstart="loadAudio(' + oneTimeAudioCount + ',' + limitNum + ')" onloadeddata="playSpecifiedTimesAudio(' + oneTimeAudioCount + ')" />' +
'</span>'
}
);
} else {
str = str.replace(
/\[\[\[((.+?.mp3).*?)\]\]\]/g, function (all, group1, group2) {

oneTimeAudioCount++;

let limitNum = getPlayAudioLimitNum(group1);

return '<span>' +
'<audio id="one_time_audio_' + oneTimeAudioCount + '" class="audio audio_with_controls" src="' + group2 + '" preload onloadstart="loadAudio(' + oneTimeAudioCount + ',' + limitNum + ')" />' +
'<input id="one_time_audio_button_' + oneTimeAudioCount + '" type="button" value="音声再生" onClick="playSpecifiedTimesAudio(' + oneTimeAudioCount + ')">' +
'</span>'
});
}

if (isEdge() || isIE()) {
str = str.replace(
/\[\[([^[]*?[.]mp3)\]\]/g,
'<audio class="audio audio_with_controls autoplay" src="$1" preload controls controlslist="nodownload" onclick="this.play()"/>'
);
} else {
str = str.replace(
/\[\[([^[]*?[.]mp3)\]\]/g,
'<audio class="audio audio_with_controls autoplay" src="$1" preload controls controlslist="nodownload"/>'
);
}


str = str.replace(/\[\[([^\]]*?\.mp4[^\]]*?)\]\]/g, function (match, p1) {
let mediaData = getMediaData(match, p1, false);
return '<video src="' + mediaData['url'] + '" style="' + mediaData['style'] + ' max-width:100%" controls></video>';
});


str = str.replace(/\[\[LINK title="(.+?)" href="(.+?)" icon="(.+?)"\]\]/g, function (all, title, href, icon) {
const contentsURL = unescapeHtml(href);
return '\
<a class="btn btn-primary btn-rounded btn-sm waves-effect waves-light related-contents-btn" target="_blank" href="' + contentsURL + '">\
<i class="' + icon + ' related-contents-icon"></i>\
<span class="related-contents-title">' + title + '</span>\
</a>\
';
});

str = str.replace(
/\{\{([^\}]*?)\}\}/g,
'<img src="$1" class="thumnaildefault" style="margin: 0px;"/>'
);
str = str.replace(/\[\[([^\]]*?)\]\]/g, function (match, p1) {
let mediaData = getMediaData(match, p1);
let imgTag = "";
if (mediaData['alt']){
imgTag = '<img src="' + mediaData['url'] + '" data-original-src="' + mediaData['url'] + '" alt="' + mediaData['alt'] + '" data-qgsrc="' + mediaData['url'] + '" style="' + mediaData['style'] + '">';
} else {
imgTag = '<img src="' + mediaData['url'] + '" data-original-src="' + mediaData['url'] + '" alt="' + mediaData['url'] + '" data-qgsrc="' + mediaData['url'] + '" style="' + mediaData['style'] + '">';
}
let saBoxTag = '<div class="sa-box-img waves-effect waves-light">' + imgTag + '</div>';
let myGalleryTag = '<div class="my-gallery">' + '<figure>' + '<a href="' + mediaData['url'] + '" data-size="600x400" class="imglink">' + imgTag + '</a>' + '</figure>' + '</div>';

if (cq_question_img_flag !== 'not_sa-box' && cq.type === 'sa-box') {
return (saBoxTag);
} else {
return (myGalleryTag);
}
});

return str;
}

function convert_drop_list(str) {

return str.replace(
/\{([^\}]{1,2})\}/g,
'<span class = "drop-choice-wordbank"><span class="wordbank-key">（$1）</span></span>'
);
}

function convert_pulldown(str) {

return str.replace(/\{([^\}]{1,2})\}/g, function (i, j) {
var list = cq['choice'][j - 1],
ret = '',
k;
ret += "<select class='mdb-select' data-number='" + (j - 1) + "'>";
ret += "<option value=''>   </option>";
for (k = 0; k < list.length; k++) {
if (list[k].match(/\[\[(.*)\]\]/) != null) {
ret +=
'<option value="' +
htmlencode(list[k].match(/\[\[(.*)\]\]/)[1]) +
'">' +
htmlencode(list[k].match(/\[\[(.*)\]\]/)[1]) +
'</option>';
} else {
ret +=
'<option value="' +
htmlencode(list[k]) +
'">' +
htmlencode(list[k]) +
'</option>';
}
}
ret += '</select>';
return ret;
});
}

function button_click(value) {


last_button_value = value;
check_answer(true, true, true);
}

function store_answer(isAlert) {

var checked_answer, student_response, selected;
const $choices = $('#choices');
if (state === 'quiz' || state === 'unload_check_answer') {
if (cq.hasOwnProperty('result')) {
return;
}
if (cq.type === 'sa' || cq.type === 'sa-box' || cq.type === 'ma') {
checked_answer = $('.choice_radio:checked');
student_response = [];
if (checked_answer.length === 0) {
checked_answer = $('.choice_checkbox:checked');
}
if (checked_answer.length === 0) {
if (isAlert) {
qalert(_cfg.settings.messages.not_selected);
return;
}
} else {
checked_answer.each(function () {
student_response.push($(this).attr('value'));
});
}
} else if (
cq.type === 'fill-in' ||
cq.type === 'fill-in-plus' ||
cq.type === 'textarea' ||
cq.type === 'textarea-enquete' ||
cq.type === 'textarea-report'
) {
if (cq.type === 'fill-in' || cq.type === 'fill-in-plus') {
student_response = $('#input_line').val();
} else {
student_response = $('#form-textarea').val();
}
if (student_response.length === 0) {
if (isAlert) {
qalert(_cfg.settings.messages.not_filled);
return;
}
}
} else if (cq.type === 'fill-in-multi') {
student_response = [];
$choices.find('input.js-fill-in-multi-input').each(function () {
if (student_response.length < cq.answer.length) {
student_response.push($(this).val());
}
});
var flag = true;
for (var i = 0; i < student_response.length; i++) {
if (student_response[i].length == 0) {
flag = false;
}
}
if (flag == false) {
if (isAlert) {
qalert(_cfg.settings.messages.not_filled);
return;
}
}
} else if (cq.type === 'button' || cq.type === 'true-false') {
student_response = last_button_value;
last_button_value = '';
} else if (cq.type === 'sort' || cq.type === 'match') {
student_response = [];
$('.drag-choice').each(function () {
student_response.push(
$(this)
.find('.drag-value')
.attr('value')
);
});
if (!change_sort_flg && !is_shuffle(cq.choice, student_response)) {
student_response = [];
if (isAlert) {
qalert(_cfg.settings.messages.not_sorted);
return;
}
}
} else if (cq.type === 'wordbank') {
student_response = [];
selected = true;
$('.drop-choice-wordbank').each(function () {
if ($(this).children('.drag-choice-wordbank').length === 0) {
selected = false;
if (isAlert) {
qalert(_cfg.settings.messages.not_selected);
return false;
}
student_response.push('未選択');
return true;
}
student_response.push(
$(this)
.find('.drag-value')
.attr('value')
);
});
if (!selected && isAlert) {
return;
}
} else if (cq.type === 'pulldown') {
student_response = [];
selected = true;
$('select').each(function (i, j) {
if (!$(j).val()) {
selected = false;
if (isAlert) {
qalert(_cfg.settings.messages.not_selected);
return false;
}
student_response[$(j).data('number')] = '未選択';
return true;
}
student_response[$(j).data('number')] = $(j).val();
});
if (!selected && isAlert) {
return;
}
}
cq.student_response = student_response;
storeRecoveryData();
}
}

function storeRecoveryData() {
if (_cfg.settings.suspendable) {
if (lbLocalStorage) {
try {
lbLocalStorage.setItem("2cc349fb69929838af8c918603ea37900be522cc_recovery_data", generate_suspend_data(true));
} catch (e) {
console.log('storeRecoveryData failed.');
}
}
}
}

/**
* 「択一」「画像選択」「複数選択」の正解情報を設定
*/
function settingSaCorrectInfo(isResult, studentResponse, correctInfo) {
correctInfo.isCorrect = array_equal(studentResponse, cq.answer);

correctInfo.isCorrect ? correctInfo.correctCount++ : correctInfo.incorrectCount++;

if (isResult && isQuizUIVisible()) {
for (let i = 0; i < cq.choice.length; i++) {
if (cq.answer.indexOf(cq.choice[i]) >= 0) {

if (_cfg.settings.show_correct_answer) {
$('.choice').eq(i).find('.choice_body').addClass('correct-answer-choice');
}
$('.choice').eq(i).find('label').css('display', 'block');
}
}
}
cq.unknown_flag = studentResponse == '分からない';
}

/**
* 「択一クイック」「正誤〇×」の正解情報を設定
*/
function settingButtonCorrectInfo(studentResponse, correctInfo) {
correctInfo.isCorrect = studentResponse === cq.answer[0];

correctInfo.isCorrect ? correctInfo.correctCount++ : correctInfo.incorrectCount++;
cq.unknown_flag = studentResponse == '分からない';
}

/**
* 「記述」「textarea」の正解情報を設定
*/
function settingTextareaCorrectInfo(isAlert, studentResponse, correctInfo) {
if (isAlert && studentResponse.length === 0) {
qalert(_cfg.settings.messages.not_filled);
return;
}

correctInfo.isCorrect = array_contain([studentResponse], cq.answer);

correctInfo.isCorrect ? correctInfo.correctCount++ : correctInfo.incorrectCount++;
}

/**
* 「レポート記述」の正解情報を設定
*/
function settingTextareaReportCorrectInfo(isAlert, studentResponse, correctInfo) {
if (isAlert && studentResponse.length === 0) {
qalert(_cfg.settings.messages.not_filled);
return;
}
correctInfo.isCorrect = undefined;
correctInfo.undefinedCount++;
}

/**
* 「アンケート記述」の正解情報を設定
*/
function settingTextareaEnqueteCorrectInfo(isAlert, studentResponse, correctInfo) {
if (studentResponse.length === 0) {
if (isAlert) {
qalert(_cfg.settings.messages.not_filled);
return;
}
correctInfo.isCorrect = false;
correctInfo.incorrectCount++;
} else {
correctInfo.isCorrect = true;
correctInfo.correctCount++;
}
}

/**
* 「複数記述」の正解情報を設定
*/
function settingFillInMultiCorrectInfo(isAlert, isResult, studentResponse, correctInfo) {
let flag = true;

for (let i = 0; i < studentResponse.length; i++) {
if (studentResponse[i] == '') {
flag = false;
}
}

if (isAlert && !flag) {
qalert(_cfg.settings.messages.not_filled);
return;
}

if (!studentResponse || studentResponse.length === 0) {
correctInfo.isCorrect = false;
correctInfo.incorrectCount++;
} else {
correctInfo.isCorrect = true;
cq.resultArray = [];

let hasCorrectAnswer = null;
let answerArray = null;

for (let i = 0; i < cq.answer.length; i++) {
hasCorrectAnswer = false;
answerArray = cq.answer[i].split('::');
for (let j = 0; j < answerArray.length; j++) {
if (is_equal(studentResponse[i], answerArray[j])) {
hasCorrectAnswer = true;
}
}
cq.resultArray[i] = hasCorrectAnswer;
if (!hasCorrectAnswer) {
if (isResult) {
$('.fill_in_multi').eq(i).css('color', 'red');
}
correctInfo.isCorrect = false;
correctInfo.incorrectCount++;
} else {
if (isResult) {
$('.fill_in_multi').eq(i).css('color', 'green');
}
correctInfo.correctCount++;
}
}
}
}

/**
* 「記述+」の正解情報を設定
*/
function settingFillInPlusCorrectInfo(isAlert, studentResponse, correctInfo) {
if (isAlert && studentResponse.length === 0) {
qalert(_cfg.settings.messages.not_filled);
return;
}

correctInfo.isCorrect = array_contain_fillin_plus([studentResponse], cq.answer);

correctInfo.isCorrect ? correctInfo.correctCount++ : correctInfo.incorrectCount++;
}

/**
* 「並び替え」の正解情報を設定
*/
function settingSortCorrectInfo(isResult, studentResponse, correctInfo) {
if (isResult) {
disableDragDrop($('.drag-choice'), $('.drop-choice'));
}
if (studentResponse.length === 0) {
correctInfo.isCorrect = false;
correctInfo.incorrectCount++;
} else {
correctInfo.isCorrect = true;
for (let i = 0; i < studentResponse.length; i++) {
if (studentResponse[i] !== cq.answer[i]) {
correctInfo.isCorrect = false;
break;
}
}

correctInfo.isCorrect ? correctInfo.correctCount++ : correctInfo.incorrectCount++;
}
}

/**
* 「組み合わせ」の正解情報を設定
*/
function settingMatchCorrectInfo(isResult, studentResponse, correctInfo) {
if (isResult) {
disableDragDrop($('.drag-choice'), $('.drop-choice'));
}
if (studentResponse.length === 0) {
correctInfo.isCorrect = false;
} else {
correctInfo.isCorrect = true;
for (let i = 0; i < studentResponse.length; i++) {
if (
_cfg.settings.show_instant_result &&
_cfg.settings.show_correct_answer
) {
if (
cq.match_key[
cq.answer.findIndex(function (j) {
return j == studentResponse[i];
})
] == cq.match_key[i]
) {
if (isResult) {
$('#choice_' + i).find('li').css('color', 'green');
}

correctInfo.correctCount++;
} else if (studentResponse[i] == cq.answer[i]) {
if (isResult) {
$('#choice_' + i).find('li').css('color', 'green');
}
correctInfo.correctCount++;
} else {
if (isResult && $('#choice_' + i).find('.disp_correct').length === 0) {
$('#choice_' + i)
.find('li')
.css('color', 'red');
$('#choice_' + i)
.find('li')
.append(
"<span class='disp_correct' style='color:green'>（" +
convert_image_tags(cq.answer[i]) +
'）</span>'
);
}
correctInfo.isCorrect = false;
correctInfo.incorrectCount++;
}
} else {
if (
cq.match_key[
studentResponse.findIndex(function (j) {
return j == cq.answer[i];
})
] == cq.match_key[i]
) {
correctInfo.correctCount++;
} else {
correctInfo.isCorrect = false;
correctInfo.incorrectCount++;
}
}
}
}
}

/**
* 「穴埋め」の正解情報を設定
*/
function settingWordBankCorrectInfo(isResult, studentResponse, correctInfo) {
if (isResult) {
disableDragDrop($('.drag-choice-wordbank'), $('.drop-choice-wordbank'));
}
if (studentResponse.length === 0) {
correctInfo.isCorrect = false;
} else {
correctInfo.isCorrect = true;
for (let i = 0; i < studentResponse.length; i++) {
if (
_cfg.settings.show_instant_result &&
_cfg.settings.show_correct_answer
) {
if (studentResponse[i] === cq.answer[i]) {
if (isResult) {
$('#question .drag-choice-wordbank').eq(i).css('color', 'green');
}
correctInfo.correctCount++;
} else {
if (isResult && $('#question .drag-choice-wordbank').eq(i).children('.disp_correct').length === 0) {
$('#question .drag-choice-wordbank')
.eq(i)
.css('color', 'red');
$('#question .drag-choice-wordbank')
.eq(i)
.append(
"<span class='disp_correct' style='color:green'>（" +
convert_image_tags(cq.answer[i]) +
'）</span>'
);
}
correctInfo.isCorrect = false;
correctInfo.incorrectCount++;
}
} else {
if (studentResponse[i] === cq.answer[i]) {
correctInfo.correctCount++;
} else {
correctInfo.isCorrect = false;
correctInfo.incorrectCount++;
}
}
}
}
}

/**
* 「プルダウン」の正解情報を設定
*/
function settingPulldownCorrectInfo(isResult, studentResponse, correctInfo) {
if (isResult) {
$('option:not(:selected)').attr('disabled', true);
}
if (studentResponse.length === 0) {
correctInfo.isCorrect = false;
} else {
correctInfo.isCorrect = true;

let pulldownAnswer = null;

for (let i = 0; i < studentResponse.length; i++) {
if (cq.answer[i].match(/\[\[(.*)\]\]/) != null) {
pulldownAnswer = htmlencode(cq.answer[i].match(/\[\[(.*)\]\]/)[1]);
} else {
pulldownAnswer = cq.answer[i];
}
if (
_cfg.settings.show_instant_result &&
_cfg.settings.show_correct_answer
) {
if (studentResponse[i] !== pulldownAnswer) {
correctInfo.isCorrect = false;
if (isResult) {
$('select[data-number=' + i + ']').css('color', 'red');
$('select[data-number=' + i + ']').after(
'<span style="color:green">' + htmlencode(pulldownAnswer) + '</div>'
);
}
correctInfo.incorrectCount++;
} else {
if (isResult) {
$('select[data-number=' + i + ']').css('color', 'green');
}
correctInfo.correctCount++;
}
} else {
if (studentResponse[i] !== pulldownAnswer) {
correctInfo.isCorrect = false;
correctInfo.incorrectCount++;
} else {
correctInfo.correctCount++;
}
}
}
}
}

/**
* 正解情報(正誤, 正解数, 不正解数, 未定義数)を取得
*/
function getCorrectInfo(isAlert, isResult, studentResponse) {

let correctInfo = {
isCorrect: null,
correctCount: 0,
incorrectCount: 0,
undefinedCount: 0,
};

switch (cq.type) {
case 'sa':
case 'sa-box':
case 'ma':
settingSaCorrectInfo(isResult, studentResponse, correctInfo);
break;

case 'button':
case 'true-false':
settingButtonCorrectInfo(studentResponse, correctInfo);
break;

case 'fill-in':
case 'textarea':
settingTextareaCorrectInfo(isAlert, studentResponse, correctInfo);
break;

case 'textarea-report':
settingTextareaReportCorrectInfo(isAlert, studentResponse, correctInfo);
break;

case 'textarea-enquete':
settingTextareaEnqueteCorrectInfo(isAlert, studentResponse, correctInfo);
break;

case 'fill-in-multi':
settingFillInMultiCorrectInfo(isAlert, isResult, studentResponse, correctInfo);
break;

case 'fill-in-plus':
settingFillInPlusCorrectInfo(isAlert, studentResponse, correctInfo);
break;

case 'sort':
settingSortCorrectInfo(isResult, studentResponse, correctInfo);
break;

case 'match':
settingMatchCorrectInfo(isResult, studentResponse, correctInfo);
break;

case 'wordbank':
settingWordBankCorrectInfo(isResult, studentResponse, correctInfo)
break;

case 'pulldown':
settingPulldownCorrectInfo(isResult, studentResponse, correctInfo)
break;
}


return correctInfo;
}

/**
* 全解答を合算した値を返す
*/
function getCountAllAnswers() {
return count_incorrect_answers() + count_correct_answers() + count_neutral_answers();
}

/**
* 問題種別に応じた初期化方法を返す
*/
function getStudentResponseInitType() {
const typeArrayTbl = [
'sa', 'sa-box', 'ma', 'sort', 'match',
'wordbank', 'fill-in-multi', 'pulldown'
];
return (typeArrayTbl.indexOf(cq.type) >= 1) ? [] : '';
}

/**
* 正解数を分数で取得する
*/
function getCorrectnessCount(correctInfo) {
let correctness = null;
if (_cfg.settings.partial_score) {
if (correctInfo.correctCount == 0) {
correctness = [1, 0];
} else {
correctness = [correctInfo.correctCount + correctInfo.incorrectCount, correctInfo.correctCount];
}
} else {
correctness = correctInfo.isCorrect ? [1, 1] : [1, 0];
}
if (correctInfo.undefinedCount && correctInfo.undefinedCount > 0) {
correctness = undefined;
}
return correctness;
}

/**
* 解答の結果を設定する
*/
function settingResult(isResult, correctInfo) {
if (isResult) {
if (_cfg.settings.time_limit_mode == 'question') {
$('.timer').countdown('pause');
}

$('.input').attr('disabled', true);
$('.choice_radio').attr('disabled', true);
$('.choice_checkbox').attr('disabled', true);

$('.md-textarea').attr('readonly', true);

setResult(correctInfo.isCorrect);
} else {

setTempResult(correctInfo.isCorrect);
}
}

/**
* 正誤関連のUI表示設定
*/
function settingQuizUI() {

if (_cfg.settings.show_instant_result) {
show_feedback();
if ($('#instant_feedback_msg').html()) {
let height = window.parent.screen.height;
if ($('body').height() < height) {
height = $('body').height();
}
$('#instant_response_disp').css('top', height * 0.6 - 40);
} else {
$('#instant_response_disp').css('top', 150 - 40);
}

if (isQuizUIVisible()) {
$('#instant_response_container').show(1);
$('#instant_response_background').show();
$('#instant_response_container').scrollTop(0);
}

let isNextQuiz = getCountAllAnswers() < _cfg.settings.question_count;

if (isNextQuiz) {
if (has_next_quiz()) {
if (isQuizUIVisible()) {
$('#check_answer_next_button').show();
$('#check_answer_next_button').removeAttr('disabled');
}
}
setTimeout(function () {
document.querySelector('#check_answer_next_button').scrollIntoView(false);
$('#check_answer_next_button').focus();
}, 100);
} else {
if (isQuizUIVisible()) {
$('#show_result').show();
$('#abort_quiz').hide();
setTimeout(function () {
document.querySelector('#show_result').scrollIntoView(false);
$('#show_result').focus();
}, 100);
applyMathJax();
}
}
$('#check_answer_button').hide();
}
}

/**
* 解答の正誤を判定
* @param {boolean} isAlert true = アラートを表示  false = アラートを非表示
* @param {boolean} isStore true = 解答を保存する  false = 解答を保存しない
* @param {boolean} isResult true = 解答結果を使用してCSSなどを画面に反映  false = 解答結果の情報のみcqに設定
* @return {void}
*/
function check_answer(isAlert, isStore, isResult) {



if (isAlert == null) { isAlert = true; }
if (isStore == null) { isStore = true; }
if (isResult == null) { isResult = true; }

let student_response;
let isNextQuiz = getCountAllAnswers() < _cfg.settings.question_count;

if (isStore) {
store_answer(isAlert);
}


if (!cq.hasOwnProperty('student_response')) {
cq.student_response = getStudentResponseInitType();
}
student_response = cq.student_response;


if (!isAlert || (student_response && student_response.length)) {

let correctInfo = getCorrectInfo(isAlert, isResult, student_response);

settingResult(isResult, correctInfo);

cq.correctness = getCorrectnessCount(correctInfo);

saveOperationLog();

if (!isResult) { return; }

settingQuizUI();

if (state === 'quiz') {
applyMathJax();
}
}


update_seigo_counts();
storeRecoveryData();


if (!_cfg.settings.show_instant_result && !_cfg.settings.movable) {

if (cq.type == 'button' || cq.type == 'true-false') {
if (isNextQuiz) {
if (has_next_quiz()) {
display_next_quiz();
} else {
mark_quiz();
}
} else {
$('#show_result').show();
}
}
}
helpToolTipHide();
}

function check_all_answers() {

var i;
store_answer(false);
for (i = 0; i < _cfg.settings.question_count; i++) {
cq = _cfg.questions[i];
check_answer(false, false, true);
}
}

function array_equal(a1, a2) {

return array_contain(a1, a2) && array_contain(a2, a1);
}

function array_contain(a1, a2) {

var i, j;
for (i = 0; i < a1.length; i++) {
for (j = 0; j < a2.length; j++) {
if (is_equal(a1[i], a2[j])) {
break;
}
}
if (j === a2.length) {
return false;
}
}
return true;
}

function array_contain_fillin_plus(a1, a2) {

var j, k, subcorrect, answers;
var answers = clone(a2);
for (j = 0; j < answers.length; j++) {
answers[j] = answers[j].split(',');
}
var responseArray = a1[0].split(/[ 　,、，	]+/);
for (j = 0; j < responseArray.length; j++) {
subcorrect = false;
for (k = 0; k < answers.length; k++) {
if (array_contain([responseArray[j]], answers[k])) {
answers.splice(k, 1);
subcorrect = true;
break;
}
}
if (subcorrect == false) return false;
}
return answers.length == 0;
}

function is_equal(a1, a2) {

if (cq.type === 'sa' || cq.type === 'sa-box' || cq.type === 'ma') {
return a1 === a2;
}
if (_cfg.settings.ignore_case) {
a1 = a1.toLowerCase();
a2 = a2.toLowerCase();
}
if (_cfg.settings.ignore_whitespace) {
a1 = a1.replace(/[\s　]+/g, '');
a2 = a2.replace(/[\s　]+/g, '');
}
if (_cfg.settings.ignore_whitespace_count) {
a1 = a1.replace(/[\s　]+/g, ' ');
a2 = a2.replace(/[\s　]+/g, ' ');
}
if (_cfg.settings.ignore_zenhan) {
a1 = hankana2zenkana(zen2han(a1));
a2 = hankana2zenkana(zen2han(a2));
}
if (_cfg.settings.trim) {
a1 = a1.replace(/^[\s　]+|[\s　]+$/g, '');
a2 = a2.replace(/^[\s　]+|[\s　]+$/g, '');
}
a1 = a1.replace(/&#0*58;/g, ':');
a2 = a2.replace(/&#0*58;/g, ':');
return a1 === a2;
}

function zen2han(str, tilde, mark, hankana, space, alpha, num) {
if (alpha !== false) {
str = str.replace(/[Ａ-Ｚａ-ｚ]/g, function (s) {
return String.fromCharCode(s.charCodeAt(0) - 65248);
});
}
if (num !== false) {
str = str.replace(/[０-９]/g, function (s) {
return String.fromCharCode(s.charCodeAt(0) - 65248);
});
}
if (mark !== false) {
var reg = /[！＂＃＄％＆＇（）＊＋，－．／：；＜＝＞？＠［＼］＾＿｀｛｜｝]/g;
str = str
.replace(reg, function (s) {
return String.fromCharCode(s.charCodeAt(0) - 65248);
})
.replace(/[‐－―]/g, '-');
}
if (tilde !== false) {
str = str.replace(/[～〜]/g, '~');
}
if (space !== false) {
str = str.replace(/　/g, ' ');
}
if (hankana === true) {
var map = { '。': '｡', '、': '､', '「': '｢', '」': '｣', '・': '･' };
var reg = new RegExp('(' + Object.keys(map).join('|') + ')', 'g');
str = str.replace(reg, function (match) {
return map[match];
});
}

str = str.replace(/‘/g, "'");
str = str.replace(/’/g, "'");
return str;
}
var hankana2zenkana = function (str) {
var kanaMap = {
ｶﾞ: 'ガ',
ｷﾞ: 'ギ',
ｸﾞ: 'グ',
ｹﾞ: 'ゲ',
ｺﾞ: 'ゴ',
ｻﾞ: 'ザ',
ｼﾞ: 'ジ',
ｽﾞ: 'ズ',
ｾﾞ: 'ゼ',
ｿﾞ: 'ゾ',
ﾀﾞ: 'ダ',
ﾁﾞ: 'ヂ',
ﾂﾞ: 'ヅ',
ﾃﾞ: 'デ',
ﾄﾞ: 'ド',
ﾊﾞ: 'バ',
ﾋﾞ: 'ビ',
ﾌﾞ: 'ブ',
ﾍﾞ: 'ベ',
ﾎﾞ: 'ボ',
ﾊﾟ: 'パ',
ﾋﾟ: 'ピ',
ﾌﾟ: 'プ',
ﾍﾟ: 'ペ',
ﾎﾟ: 'ポ',
ｳﾞ: 'ヴ',
ﾜﾞ: 'ヷ',
ｦﾞ: 'ヺ',
ｱ: 'ア',
ｲ: 'イ',
ｳ: 'ウ',
ｴ: 'エ',
ｵ: 'オ',
ｶ: 'カ',
ｷ: 'キ',
ｸ: 'ク',
ｹ: 'ケ',
ｺ: 'コ',
ｻ: 'サ',
ｼ: 'シ',
ｽ: 'ス',
ｾ: 'セ',
ｿ: 'ソ',
ﾀ: 'タ',
ﾁ: 'チ',
ﾂ: 'ツ',
ﾃ: 'テ',
ﾄ: 'ト',
ﾅ: 'ナ',
ﾆ: 'ニ',
ﾇ: 'ヌ',
ﾈ: 'ネ',
ﾉ: 'ノ',
ﾊ: 'ハ',
ﾋ: 'ヒ',
ﾌ: 'フ',
ﾍ: 'ヘ',
ﾎ: 'ホ',
ﾏ: 'マ',
ﾐ: 'ミ',
ﾑ: 'ム',
ﾒ: 'メ',
ﾓ: 'モ',
ﾔ: 'ヤ',
ﾕ: 'ユ',
ﾖ: 'ヨ',
ﾗ: 'ラ',
ﾘ: 'リ',
ﾙ: 'ル',
ﾚ: 'レ',
ﾛ: 'ロ',
ﾜ: 'ワ',
ｦ: 'ヲ',
ﾝ: 'ン',
ｧ: 'ァ',
ｨ: 'ィ',
ｩ: 'ゥ',
ｪ: 'ェ',
ｫ: 'ォ',
ｯ: 'ッ',
ｬ: 'ャ',
ｭ: 'ュ',
ｮ: 'ョ',
'｡': '。',
'､': '、',
ｰ: 'ー',
'｢': '「',
'｣': '」',
'･': '・'
};

var reg = new RegExp('(' + Object.keys(kanaMap).join('|') + ')', 'g');
return str
.replace(reg, function (match) {
return kanaMap[match];
})
.replace(/ﾞ/g, '゛')
.replace(/ﾟ/g, '゜');
};


function show_feedback() {
show_ox_fb();
show_sa_fb();


addMediaEvent(_cfg.settings.sound == false);
}

function show_sa_fb() {

if (cq.type === 'sa' || cq.type === 'sa-box' || cq.type === 'button' || cq.type === 'true-false') {
if (cq.feedback_map[cq.student_response]){
$('#instant_feedback_msg').html(
convert_image_tags(cq.feedback_map[cq.student_response])
);
$('#instant_feedback_wrapper').show();
} else {

$('#instant_feedback_wrapper').hide();
}
}
}

function show_ox_fb() {

if (cq.result === 'correct') {
if (cq.hasOwnProperty('feedback_tf') && cq.feedback_tf[0]) {
$('#instant_feedback_msg').html(convert_image_tags(cq.feedback_tf[0]));
$('#instant_feedback_wrapper').show();
}
} else {
if (cq.hasOwnProperty('feedback_tf') && cq.feedback_tf[1]) {
$('#instant_feedback_msg').html(convert_image_tags(cq.feedback_tf[1]));
$('#instant_feedback_wrapper').show();
}
}
}

function play_correct_sound() {

if (_cfg.settings.sound) {
document.getElementById('correct_sound').load();
document.getElementById('correct_sound').play();
}
}

function play_incorrect_sound() {

if (_cfg.settings.sound) {
document.getElementById('incorrect_sound').load();
document.getElementById('incorrect_sound').play();
}
}

function play_dragged_sound() {

if (_cfg.settings.sound) {
document.getElementById('dragged_sound').load();
document.getElementById('dragged_sound').play();
}
}

function setTempResult(is_correct) {

if (!cq.hasOwnProperty('result')) {
if (is_correct === undefined) {
cq.tempResult = 'neutral';
} else {
cq.tempResult = is_correct ? 'correct' : 'incorrect';
}
}
}

function setResult(is_correct) {

if (is_correct === undefined) {
if (_cfg.settings.show_instant_result) {
response_disp(true);
$('#instant_result_msg').html(_cfg.settings.messages.correct);
$('#instant_result_wrapper').show();
}
if (!cq.hasOwnProperty('result')) {
cq.result = 'neutral';
}
} else if (is_correct) {
if (_cfg.settings.show_instant_result) {
response_disp(true);
$('#instant_result_msg').html(_cfg.settings.messages.correct);
$('#instant_result_wrapper').show();
if (isQuizUIVisible()) {
$('#answer_mark_correct').show();
}
if (!cq.hasOwnProperty('result')) {
play_correct_sound();
}
}
if (!cq.hasOwnProperty('result')) {
cq.result = 'correct';
cq.correct_count++;
}
} else {
if (_cfg.settings.show_instant_result) {
response_disp(true);
$('#instant_result_msg').html(_cfg.settings.messages.incorrect);
$('#instant_result_wrapper').show();
if (isQuizUIVisible()) {
$('#answer_mark_incorrect').show();
}
if (!cq.hasOwnProperty('result')) {
play_incorrect_sound();
}
if (_cfg.settings.show_correct_answer && isQuizUIVisible() && cq.type !== 'sa' && cq.type !== 'sa-box' && cq.type !== 'ma') {
$('#instant_answer_msg').html(formatter(cq, 'answer'));
$('#instant_answer_wrapper').show();
}
}
if (!cq.hasOwnProperty('result')) {
if (cq.student_response && cq.student_response.length > 0) {
cq.result = 'incorrect';
cq.incorrect_count++;
} else {
cq.result = 'incorrect';
}
}
}
}

function response_disp(disp_flg) {

if (disp_flg) {
$('#instant_response_background').css('opacity', '1');
$('#instant_result_wrapper').css('opacity', '1');
$('#instant_answer_wrapper').css('opacity', '1');
$('#instant_feedback_wrapper').css('opacity', '1');
$('#instant_response_disp').hide();
$('#instant_response_disp_none').show();
$('#instant_response_container').css('overflow-y', 'auto');
$('#answer_mark').show();
} else {
$('#instant_response_background').css('opacity', '0.01');
$('#instant_result_wrapper').css('opacity', '0.01');
$('#instant_answer_wrapper').css('opacity', '0.01');
$('#instant_feedback_wrapper').css('opacity', '0.01');
$('#instant_response_disp').show();
$('#instant_response_disp_none').hide();
$('#instant_response_container').css('overflow-y', 'visible');
$('#answer_mark').hide();
}
}

function check_choiced_next_quiz() {

if (has_next_quiz()) {

check_answer(true, true, false);

if (!cq.hasOwnProperty('student_response')) {
return;
}
if (
!cq.student_response ||
!cq.student_response.length ||
(cq.type === 'wordbank' &&
$.inArray('未選択', cq.student_response) !== -1)
) {
return;
}

previousPosition = position;
position++;
display_quiz();
}
}

function mark_quiz() {

var is_all_question_answered, i, q;
if (!_cfg.settings.show_instant_result) {
if (
!_cfg.settings.movable &&
position + 1 === _cfg.settings.question_count
) {

check_answer(true, true, false);

if (!cq.hasOwnProperty('student_response')) {
return;
}
if (
!cq.student_response ||
!cq.student_response.length ||
(cq.type === 'wordbank' &&
$.inArray('未選択', cq.student_response) !== -1)
) {
return;
}
} else {

check_answer(false, true, false);
}
is_all_question_answered = true;
for (i = 0; i < _cfg.settings.question_count; i++) {
q = _cfg.questions[i];
if (!q.hasOwnProperty('student_response')) {
is_all_question_answered = false;
} else if (
!q.student_response ||
!q.student_response.length ||
(q.type === 'wordbank' &&
$.inArray('未選択', q.student_response) !== -1)
) {
is_all_question_answered = false;
}
}
if (!is_all_question_answered) {
if (!confirm(_cfg.settings.messages.confirm_midstream_mark)) {
return;
}
} else if (_cfg.settings.movable) {
if (!confirm(_cfg.settings.messages.confirm_mark)) {
return;
}
}
show_result();
}
}


function show_list() {

pushed_state = state;
store_answer(false);
cstate('list');
$('#result_table tbody').empty();
make_result_table('#result_table1');
show('#page_list');
helpToolTipHide();
if (isIOS() || isIPadOS() || isAndroid()) {
return;
}
$('#page_list div.scrollbartable').remove();
applyMathJax();


addMediaEvent(true);
}

function get_hide_list_n(i) {

return function () {
hide_list(i);
};
}

/**
* 設問毎の正誤一覧表示画面を作成
* @param {string} selector
* @return void
*/
function make_result_table(selector) {

$('.result_detail').remove();

let result_detail_record;
for (let i = 0; i < _cfg.settings.question_count; i++) {

if (selector === '#result_table1') {
result_detail_record = result_detail_template1.clone();
} else {
result_detail_record = result_detail_template2.clone();
}

const currentQuestion = JSON.parse(JSON.stringify(_cfg.questions[i]));

const qOrig = _cfg.questions[i];
$('.list_to_quiz', result_detail_record).click(get_hide_list_n(i));
$('.no', result_detail_record).html(i + 1);

const hasStudentResponse = qOrig.hasOwnProperty('student_response') ||
currentQuestion.student_response !== '' ||
currentQuestion.student_response !== false;
if (!hasStudentResponse) {
currentQuestion.student_response = '';
}

const hasResult = qOrig.hasOwnProperty('result') ||
currentQuestion.result !== '' ||
(selector === '#result_table1' && _cfg.settings.show_instant_result);
if (!hasResult) {
currentQuestion.result = '';
}

const scoreWeight = _cfg.settings.score_weighting
? currentQuestion.weight
: 100 / _cfg.settings.question_count;
if (qOrig.result == 'neutral') {
qOrig.scoreStr = '採点待';
} else if (qOrig.hasOwnProperty('result')) {
if (qOrig.type == 'textarea-report') {
qOrig.scoreStr = currentQuestion.scoreStr = '?/' + floor2ndDecimal(scoreWeight);
} else {
qOrig.scoreStr = currentQuestion.scoreStr =
floor2ndDecimal(fraction.toDouble(fraction.mul([1, scoreWeight], currentQuestion.correctness))) + '/' + floor2ndDecimal(scoreWeight);
}
} else {
qOrig.scoreStr = currentQuestion.scoreStr = '?/' + floor2ndDecimal(scoreWeight);
}
qOrig.backToQuestion = currentQuestion.backToQuestion =
'<input type=button value=表示 class="btn btn-primary btn-sm" onclick=backToQuestion(' +
i +
') style="">';

for (let key in currentQuestion) {
if (qOrig.hasOwnProperty(key)) {
$('.' + key, result_detail_record).html(wrap_div(formatter(currentQuestion, key)));
}
}
delete currentQuestion.scoreStr;
delete currentQuestion.backToQuestion;
if (fraction.toDouble(currentQuestion.correctness) > 0 && fraction.toDouble(currentQuestion.correctness) < 1) {
$('.result', result_detail_record).html(
_cfg.settings.messages['sankaku']
);
} else {
$('.result', result_detail_record).html(_cfg.settings.messages[currentQuestion.result]);
}

$(selector + ' tbody').append(result_detail_record);
}

if (!_cfg.settings.show_instant_result) {
$('.scoreStr').remove();
}
applyMathJax();
}

function formatter(q, elem) {

var dispAnswerArray, i, answers, j, k, ansArray;
if (elem == 'student_response') {
if (q[elem] == '分からない') {
return '分からない';
}
}
if (q.type === 'true-false') {
if (q[elem] === undefined) {
return '-';
}
if (q[elem][0] === 'true' || q[elem] === 'true') {
return '○';
}
if (q[elem][0] === 'false' || q[elem] === 'false') {
return '×';
}
return convert_image_tags(String(q[elem]));
}
if (q.type === 'fill-in-multi') {
if (elem == 'answer') {
dispAnswerArray = [];
k = 0;
for (i = 0; i < q[elem].length; i++) {
answers = q[elem][i].split('::');
if (!q.resultArray || q.resultArray[i] == false) {
for (j = 0; j < answers.length; j++) {
if (j === 0) {
dispAnswerArray[k] = htmlencode(answers[j]);
} else {
dispAnswerArray[k] = htmlencode(dispAnswerArray[k]) + '(' + htmlencode(answers[j]) + ')';
}
}
if (q.label && q.label[i]) {
dispAnswerArray[k] = htmlencode(q.label[i]) + '.' + dispAnswerArray[k];
}
k++;
}
}
return convert_image_tags(dispAnswerArray.join(', '));
}
}
if (typeof q[elem] === 'object') {
if (q.type === 'fill-in-plus' && elem === 'answer') {
answers = q[elem];
dispAnswerArray = new Array(answers.length);
for (i = 0; i < answers.length; i++) {
ansArray = answers[i].split(',');
for (j = 0; j < ansArray.length; j++) {
if (j === 0) {
dispAnswerArray[i] = htmlencode(ansArray[j]);
} else {
dispAnswerArray[i] = dispAnswerArray[i] + '(' + htmlencode(ansArray[j]) + ')';
}
}
}
return convert_image_tags(dispAnswerArray.join(', '));
}
if (q[elem].hasOwnProperty('length')) {
if (cq.type === 'ma') {
return convert_image_tags(q[elem].join(' ,<br>'));
} else {

elemArray = q[elem].concat();

if (elem === 'student_response' && (q.type === 'fill-in-multi' || q.type === 'pulldown')) {
for (i = 0; i < elemArray.length; i++) {
elemArray[i] = htmlencode(elemArray[i]);
}
}

if (elem === 'answer' && (q.type === 'fill-in' || q.type === 'pulldown')) {
for (i = 0; i < elemArray.length; i++) {
elemArray[i] = htmlencode(elemArray[i]);
}
}
return convert_image_tags(elemArray.join(', '));
}
}
} else {
if (q[elem] === undefined) {
return '-';
}
if (elem == 'student_response') {
if (q.type == 'button') {
return convert_image_tags(String(q[elem])).replace(/\n/g, '<br>');
} else {
return convert_image_tags(htmlencode(String(q[elem]))).replace(
/\n/g,
'<br>'
);
}
} else {
return String(q[elem]);
}
}
}

function hide_list(num) {


check_answer(false, true, false);

if (num !== undefined) {
position = num;
}
cstate(pushed_state);
if (state === 'quiz' || state === 'feedback') {
display_quiz();
show('#page_quiz');


if (pagination) {
pagination.updatePagination();
}
} else if (state === 'result') {
show('#page_result');
}

$('#back_to_question').tooltip('hide');
}


function show_result() {
if (pagination) {
pagination.allQuestionToggleAnswerState();
}

var diff;
var score;
var result;
if (localStorage) localStorage.removeItem("2cc349fb69929838af8c918603ea37900be522cc_recovery_data");
finished = true;
$('.timer').countdown('destroy');
$('.timer').remove();
$('.timer_wrapper').remove();
if (state === 'result') {
return;
}
if (state === 'quiz_review') {
cstate('result');
show('#page_result');
$('#choices').empty();
$('#question').empty();

addMediaEvent(true);
return;
}
cstate('result');
check_all_answers();
$('#choices').empty();
$('#question').empty();
check_all_answers();
try {
save_suspend_data();
} catch (e) {
console.log('IE and Edge do not support localStorage with local file.');
}
score = get_score();
if (count_neutral_answers()) {
$('.score').html('採点待');
} else {
if (_cfg.settings.score_weighting) {
$('.score').html(floor2ndDecimal(get_normal_score()) + '点');
} else {
$('.score').html(
floor2ndDecimal(get_normal_score()) +
'点' + '(' +
count_correct_answers() +
' ' + '/' + ' ' +
_cfg.settings.question_count +
')'
);
}
}

result = get_result();
$('td.result').html(_cfg.settings.messages[result]);
if (_cfg.settings.finish_at_result_page) {
finalize_scorm();
}
if (_cfg.settings.mode == 'normal') {
$('.passing_score').html(_cfg.settings.passing_score + '点');
$('#summary_table_normal').show();
$('#summary_table_master').hide();
} else {
$('.passing_score').html(_cfg.settings.passing_score + '%');
$('#summary_table_normal').hide();
$('#summary_table_master').show();
$('.progressBody').html(origProgress + '%→' + score + '%');
}
make_result_table('#result_table2');
if (_cfg.settings.hide_result_summary) {
$('#summary_table_normal').hide();
$('#summary_table_master').hide();
}
if (_cfg.settings.hide_result_detail) {
$('#result_table2').hide();
}
if (result == 'passed') {
if (
_cfg.settings.messages.passed_title ||
_cfg.settings.messages.passed_body
) {
$('#message_passed_head').show();
$('#messages_passed_title').html(_cfg.settings.messages.passed_title);
$('#messages_passed_body').html(_cfg.settings.messages.passed_body);
} else {
$('#messages_passed_head').hide();
}
if (_cfg.settings.certificate) {
$('#goto_certificate_button').show();
$('#restart_button').hide();
} else {
$('#goto_certificate_button').hide();
}
} else {
if (
_cfg.settings.messages.failed_title ||
_cfg.settings.messages.failed_body
) {
$('#message_passed_head').show();
$('#messages_passed_title').html(_cfg.settings.messages.failed_title);
$('#messages_passed_body').html(_cfg.settings.messages.failed_body);
} else {
$('#message_passed_head').hide();
}
$('#goto_certificate_button').hide();
}
show('#page_result');


addMediaEvent(true);
}

function count_correct_answers() {

var count = 0,
i;
for (i = 0; i < _cfg.settings.question_count; i++) {
if (_cfg.questions[i].result === 'correct') {
count++;
}
}
return count;
}

function count_incorrect_answers() {

var count = 0,
i;
for (i = 0; i < _cfg.settings.question_count; i++) {
if (_cfg.questions[i].result === 'incorrect') {
count++;
}
}
return count;
}

function count_neutral_answers() {

var count = 0,
i;
for (i = 0; i < _cfg.settings.question_count; i++) {
if (_cfg.questions[i].result === 'neutral') {
count++;
}
}
return count;
}

function get_normal_score() {

if (_cfg.settings.score_weighting === true) {
return get_weighted_score();
} else {
return get_unweighted_score();
}
}

function get_weighted_score() {

var score = [1, 0],
i;
for (i = 0; i < _cfg.settings.question_count; i++) {
if (_cfg.questions[i].correctness === undefined) {
return undefined;
}
score = fraction.add(score, fraction.mul([1, _cfg.questions[i].weight], _cfg.questions[i].correctness))
}
return fraction.toDouble(score);
}

function get_unweighted_score() {

var score = [1, 0],
i;
for (i = 0; i < _cfg.settings.question_count; i++) {
if (_cfg.questions[i].correctness === undefined) {
return undefined;
}
score = fraction.add(score, _cfg.questions[i].correctness);
}
return fraction.toDouble(fraction.div(fraction.mul([1, 100], score), [1, _cfg.settings.question_count]))
}

function get_score() {

try {
if (_cfg.settings.mode == 'normal') {
return get_normal_score();
} else if (_cfg.settings.mode == 'master') {
var i,
suspend_data = API.GetValue('cmi.suspend_data'),
suspend_data_body,
correct_count = 0,
question_count = 0,
suspend_data_array = JSON.parse(suspend_data);
suspend_data_body = suspend_data_array['counts'];
for (i = 0; i < suspend_data_body.length; i += 4) {
correct_count += parseInt(suspend_data_body.substring(i, i + 2), 10);
question_count += _cfg.settings.master_count;
}
return Math.round((correct_count / question_count) * 100);
}
alert('invalid mode:' + _cfg.settings.mode);
} catch (e) {
console.log('get score failed');
return 0;
}
}

function get_scaled_score() {

return get_score() / 100;
}

function get_result() {

if (_cfg.settings.mode == 'master') {
return get_score() >= _cfg.settings.passing_score ? 'passed' : 'incomplete';
} else {
if (get_score() === undefined) {
return 'completed'; //レポート問題が含まれている場合はcompletedとし、learningBOXで採点を行う
} else {
return get_score() >= _cfg.settings.passing_score ? 'passed' : 'failed';
}
}
}

function restart() {

location.href = location.href;
}


var API, startTime;
function DummyAPI() {

var seed = '2cc349fb69929838af8c918603ea37900be522cc';
this.dummy = true;
this.Initialize = function () {
console_log('Initialize');
};
this.Terminate = function () {
console_log('Terminate');
};
this.Commit = function () {
console_log('Commit');
};
this.SetValue = function (key, value) {
console_log('SetValue(' + key + ', ' + value + ')');
if (key === 'cmi.suspend_data') {
try {
lbLocalStorage.setItem(key + seed, value);
} catch (e) {
console.log("DummyAPI: setValue('cmi.suspend_data') failed");
}
}
};
this.GetValue = function (key) {
console_log('GetValue(' + key + ')');
if (key === 'cmi.suspend_data') {
return lbLocalStorage.getItem(key + seed);
}
};
}

function WrapperAPI_12to2004(api12) {

this.Initialize = function (str) {
return api12.LMSInitialize(str);
};
this.Terminate = function (str) {
return api12.LMSFinish(str);
};
this.Commit = function (str) {
return api12.LMSCommit(str);
};
this.SetValue = function (key, value) {
return api12.LMSSetValue(key, value);
};
this.GetValue = function (key) {
return api12.LMSGetValue(key);
};
this.GetLastError = function () {
return api12.LMSGetLastError('');
};
}

function init_scorm() {

var win1, win2;
try {
win1 = window;
try {
while (win1.API == null && win1.parent != null && win1.parent != win1) {
win1 = win1.parent;
}
} catch (e) {
console.log('e12');
}
win2 = window;
try {
while (
win2.API_1484_11 == null &&
win2.parent != null &&
win2.parent != win2
) {
win2 = win2.parent;
}
} catch (e) {
console.log('e2004');
}
if (
(_cfg.settings.scorm === 'auto' || _cfg.settings.scorm === '1.2') &&
win1.API !== undefined
) {
API = new WrapperAPI_12to2004(win1.API);
_cfg.settings.scorm = '1.2';
console_log('SCORM 1.2 API found');
} else if (
(_cfg.settings.scorm === 'auto' || _cfg.settings.scorm === '2004') &&
win2.API_1484_11 !== undefined
) {
API = win2.API_1484_11;
_cfg.settings.scorm = '2004';
console_log('SCORM 2004 API found');
} else {
throw 'No API Found';
}
} catch (e) {

API = new DummyAPI();
_cfg.settings.scorm = 'dummy';
console_log('SCORM API not found. DummyAPI loaded.');
}
API.Initialize('');
API.SetValue('cmi.core.session_time', formatTimeIntervalForSCORM12(0));
if (_cfg.settings.scorm === '1.2') {
setValue('cmi.core.lesson_status', 'browsed');
commit();
}
if (_cfg.settings.scorm === '2004') {
setValue('cmi.completion_status', 'incomplete');
commit();
}

$(window).on('unload', function () {
if (localStorage) {
localStorage.removeItem("2cc349fb69929838af8c918603ea37900be522cc_recovery_data");
}
});

const sendResult = function () {
if (state == 'quiz' || state == 'list') {

let isSuspend = true;

if (_cfg.settings.suspendable) {

if (1 <= _cfg.settings.suspendable_count && _cfg.settings.suspendable_count <= 99) {
isSuspend = currentSuspendCount <= _cfg.settings.suspendable_count;
}
}

if (_cfg.settings.suspendable && isSuspend) {

check_answer(false, true, false);
cstate('suspended');
} else {

cstate('unload_check_answer');
check_answer(true, true, false)
cstate('unload');
check_all_answers();
}
save_suspend_data();
finalize_scorm();
}
}


if (isIOS() || isIPadOS() || isAndroid()) {
$(window).on('pagehide', function () {
sendResult();
});
} else {
$(window).on('beforeunload', function () {
sendResult();
});
}

try {
load_suspend_data();
} catch (e) {
console_log(e);
console_log('Failed to load suspend data');
}
}

function sendCommonInteractions(q, i) {

setValue('cmi.interactions.' + i + '.id', q.id);
if (q.type === 'sa' || q.type === 'sa-box' || q.type === 'ma' || q.type === 'button') {
setValue('cmi.interactions.' + i + '.type', 'choice');
} else if (q.type === 'true-false') {
setValue('cmi.interactions.' + i + '.type', 'true-false');
} else if (q.type === 'fill-in') {
setValue('cmi.interactions.' + i + '.type', 'fill-in');
} else if (q.type === 'textarea') {
setValue('cmi.interactions.' + i + '.type', 'textarea');
} else if (q.type === 'textarea-enquete') {
setValue('cmi.interactions.' + i + '.type', 'textarea-enquete');
} else if (q.type === 'textarea-report') {
setValue('cmi.interactions.' + i + '.type', 'textarea-report');
} else if (q.type === 'fill-in-plus') {
setValue('cmi.interactions.' + i + '.type', 'fill-in');
} else if (q.type === 'fill-in-multi') {
setValue('cmi.interactions.' + i + '.type', 'fill-in');
} else if (q.type === 'sort') {
setValue('cmi.interactions.' + i + '.type', 'sequencing');
} else if (q.type === 'match') {
setValue('cmi.interactions.' + i + '.type', 'matching');
} else if (q.type === 'wordbank') {
setValue('cmi.interactions.' + i + '.type', 'matching');
} else if (q.type === 'pulldown') {
setValue('cmi.interactions.' + i + '.type', 'pulldown');
}


let interactionsChildren = getValue('cmi.interactions._children');

if (_cfg.settings.score_weighting) {
setValue('cmi.interactions.' + i + '.weighting', q.weight);

if (interactionsChildren && interactionsChildren.indexOf('isWeightingEmpty') != -1) {
setValue('cmi.interactions.' + i + '.isWeightingEmpty', q.weight == 0 ? 'true' : 'false');
}
} else {
setValue('cmi.interactions.' + i + '.weighting', '1');

if (interactionsChildren && interactionsChildren.indexOf('isWeightingEmpty') != -1) {
setValue('cmi.interactions.' + i + '.isWeightingEmpty', 'true');
}
}
if (_cfg.settings.scorm === '1.2') {
if (q.hasOwnProperty('latency')) {
setValue(
'cmi.interactions.' + i + '.latency',
formatTimeIntervalForSCORM12(q.latency * 100)
);
} else {
setValue(
'cmi.interactions.' + i + '.latency',
formatTimeIntervalForSCORM12(0)
);
}
} else {
if (q.hasOwnProperty('latency')) {
setValue(
'cmi.interactions.' + i + '.latency',
formatTimeIntervalForSCORM2004(q.latency * 100)
);
} else {
setValue(
'cmi.interactions.' + i + '.latency',
formatTimeIntervalForSCORM2004(0)
);
}
}
setValue('cmi.interactions.' + i + '.correct_responses.0.pattern', q.answer);
}

function finalize_scorm() {

var q,
i = 0,
hasReport = false;
if (API === null) {
return;
}
for (i = 0; i < _cfg.settings.question_count; i++) {
if (_cfg.questions[i].type === 'textarea-report') {
hasReport = true;
}
}
if (_cfg.settings.scorm === '1.2') {
for (i = 0; i < _cfg.settings.question_count; i++) {
q = _cfg.questions[i];
sendCommonInteractions(q, i);
for (var j = 0; j < tempQuesTag.length; j++) {
if (tempQuesTag[j] === undefined) {
tempQuesTag[j] = [];
}
if (tempSecTag[j] === undefined) {
tempSecTag[j] = [];
}
if (j == q.iid) {
var tempNum = 0;
for (var k = 0; k < cq.section_tag.length; k++) {
if (tempSecTag[j][k]) {
setValue(
'cmi.interactions.' + i + '.objectives.' + k + '.id',
's:' + tempSecTag[j][k]
);
}
tempNum++;
}
for (var l = tempNum; l < tempQuesTag[j].length + tempNum; l++) {
setValue(
'cmi.interactions.' + i + '.objectives.' + l + '.id',
'q:' + tempQuesTag[j][l - tempNum]
);
}
}
}
setValue(
'cmi.interactions.' + i + '.student_response',
q.student_response
);
if (!q.hasOwnProperty('time')) {
q.time = getCurrentTimeForSCORM12();
}
setValue('cmi.interactions.' + i + '.time', q.time);
if (
fraction.toDouble(q.correctness) == 0 ||
fraction.toDouble(q.correctness) == 1 ||
q.correctness === undefined
) {
setValue('cmi.interactions.' + i + '.result', scorm12[q.result ? q.result : q.tempResult]);
} else {
setValue(
'cmi.interactions.' + i + '.result',
floor2ndDecimal(fraction.toDouble(q.correctness) * 100)
);
}
}
if (hasReport) {
setValue('cmi.comments', JSON.stringify({ mode: 'report' }));
} else {
setValue('cmi.comments', JSON.stringify({ mode: _cfg.settings.mode }));
}
if (get_score() !== undefined) {
if (state == 'suspended') {
setValue('cmi.core.score.raw', 0);
} else {
setValue('cmi.core.score.raw', Math.floor(get_score()));
}
}
setValue('cmi.core.score.min', '0');
setValue('cmi.core.score.max', '100');
if (state == 'intro' || state == 'loading') {
setValue('cmi.core.lesson_status', 'browsed');
} else if (state == 'suspended') {
setValue('cmi.core.lesson_status', 'incomplete');
} else {
setValue('cmi.core.lesson_status', get_result());
}
setValue(
'cmi.core.session_time',
formatTimeIntervalForSCORM12(new Date().getTime() - startTime)
);
} else {
for (i = 0; i < _cfg.settings.question_count; i++) {
q = _cfg.questions[i];
sendCommonInteractions(q, i);
setValue(
'cmi.interactions.' + i + '.learner_response',
q.student_response
);
if (!q.hasOwnProperty('time')) {
q.time = getCurrentTimeForSCORM2004();
}
setValue('cmi.interactions.' + i + '.timestamp', q.time);
if (
fraction.toDouble(q.correctness) == 0 ||
fraction.toDouble(q.correctness) == 1 ||
q.correctness === undefined
) {
setValue('cmi.interactions.' + i + '.result', scorm2004[q.result ? q.result : q.tempResult]);
} else {
setValue(
'cmi.interactions.' + i + '.result',
floor2ndDecimal(fraction.toDouble(q.correctness) * 100)
);
}
}
if (hasReport) {
setValue('cmi.comments', JSON.stringify({ mode: 'report' }));
} else {
setValue('cmi.comments', JSON.stringify({ mode: _cfg.settings.mode }));
}
setValue('cmi.score.scaled', get_scaled_score().toFixed(3));

if (state == 'intro' || state == 'loading') {
setValue('cmi.success_status', 'unknown');
setValue('cmi.completion_status', 'not attempted');
} else if (state == 'suspended') {
setValue('cmi.success_status', 'unknown');
setValue('cmi.completion_status', 'incomplete');
} else {
setValue('cmi.success_status', get_result());
setValue('cmi.completion_status', 'completed');
}
setValue(
'cmi.session_time',
formatTimeIntervalForSCORM2004(new Date().getTime() - startTime)
);
}
API.Terminate('');
API = null;
}


function floor2ndDecimal(val) {
return Math.floor(val * 10) / 10;
}


function round2ndDecimal(val) {
return Math.round(val * 10) / 10;
}

function formatTimeIntervalForSCORM12(diff) {

var h, m, s;
s = (diff - (diff % 1000)) / 1000;
m = (s - (s % 60)) / 60;
h = (m - (m % 60)) / 60;
s = s - m * 60;
m = m - h * 60;
if (h < 10) {
h = '0' + h;
}
if (m < 10) {
m = '0' + m;
}
if (s < 10) {
s = '0' + s;
}
return h + ':' + m + ':' + s;
}

function formatTimeIntervalForSCORM2004(diff) {

return formatTimeIntervalForSCORM12(diff);
}

function setValue(key, value) {

if (typeof value === 'object') {
API.SetValue(key, value.join(', '));
} else if (value === undefined) {
API.SetValue(key, '');
} else {
API.SetValue(key, String(value));
}
}

function getValue(key) {

return API.GetValue(key);
}

function commit() {

if (API !== null) {
API.Commit('');
}
}

function getCurrentTimeForSCORM12() {

var ctime = new Date(),
h = ctime.getHours(),
m = ctime.getMinutes(),
s = ctime.getSeconds();
if (h < 10) {
h = '0' + h;
}
if (m < 10) {
m = '0' + m;
}
if (s < 10) {
s = '0' + s;
}
return h + ':' + m + ':' + s;
}

function getCurrentTimeForSCORM2004() {

return getCurrentTimeForSCORM12();
}


window.document.onkeydown = function (e) {

e = e || window.event;
var code = e.keyCode || e.which;

const enterKey = 13;
if (code === enterKey) {
if (state === 'quiz') {
if (
cq.type == 'textarea' ||
cq.type == 'textarea-enquete' ||
cq.type == 'textarea-report'
) {

} else {
if (_cfg.settings.show_instant_result) {
if ($(':focus').attr('id') !== 'check_answer_button') {
if (!cq.hasOwnProperty('result')) {
check_answer(true, true, true);
}

if (
$(':focus').attr('id') !== 'check_answer_next_button' &&
$(':focus').attr('id') !== 'show_result'
) {
return false;
}
}
} else if (!_cfg.settings.movable) {
if (
$(':focus').attr('id') !== 'not_disp_answer_next_button' &&
$(':focus').attr('id') !== 'not_disp_answer_mark_button'
) {
check_choiced_next_quiz();
}
} else if (_cfg.settings.movable) {
display_next_quiz();
}
}
} else if (state === 'intro') {

if (document.activeElement.localName !== 'button') {
start_quiz();
}
}
} else if (code >= 49 && code <= 57) {
numkey(code - 48);
} else if (code >= 97 && code <= 105) {
numkey(code - 96);
} else if (_cfg.settings.movable) {
if (
state === 'quiz' &&
((cq.type !== 'fill-in' &&
cq.type !== 'fill-in-plus' &&
cq.type !== 'fill-in-multi' &&
cq.type !== 'textarea' &&
cq.type !== 'textarea-enquete' &&
cq.type !== 'textarea-report') ||
e.shiftKey ||
(cq.hasOwnProperty('result') && cq.result !== ''))
) {

const isExamVertical = _cfg.settings.layout === 'exam-vertical';
if (code === 37) {
const move = isExamVertical ? display_next_quiz : display_prev_quiz;
move();
} else if (code === 39) {
const move = isExamVertical ? display_prev_quiz : display_next_quiz;
move();
}
}
}
};

function numkey(num) {

if (state === 'quiz' && !cq.hasOwnProperty('result')) {
if (
num <= $('.choice input').length + $('.choice button').length ||
(cq.type === 'true-false' && num <= 2)
) {
if (cq.type === 'sa' || cq.type === 'sa-box') {
$('.choice input')[num - 1].checked = 'checked';
} else if (cq.type === 'ma') {
$('.choice input')[num - 1].checked = !$('.choice input')[num - 1]
.checked;
} else if (cq.type === 'button') {
button_click(cq.choice[num - 1]);
} else if (cq.type === 'true-false') {
button_click(num === 1 ? 'true' : 'false');
}
}
}
}


var merge = function (p, q) {

var o = q,
z;
for (z in p) {
if (p.hasOwnProperty(z)) {
if (typeof p[z] === 'object' && typeof o[z] === 'object') {
o[z] = merge(p[z], o[z]);
} else {
o[z] = p[z];
}
}
}
return o;
},
clone = function (obj) {

var F = function () { };
F.prototype = obj;
return new F();
},
htmlencode = function (s) {

return s
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
},
jsencode = function (s) {

return s.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
},
unescapeHtml = function (target) {
if (typeof target !== 'string') return target;

const patterns = {
'&lt;': '<',
'&gt;': '>',
'&amp;': '&',
'&quot;': '"',
'&#x27;': '\'',
'&#x60;': '`'
};

return target.replace(/&(lt|gt|amp|quot|#x27|#x60);/g, function (match) {
return patterns[match];
});
},
qalert = function (msg) {

if (state === 'quiz') {
alert(msg);
}
},
console_log = function (msg) {

if (typeof console != 'undefined') {
console.log(msg);
}
},
wrap_div = function (str) {

return '<div class="break-word">' + str + '</div>';
},
cstate = function (new_state) {

state = new_state;
},
show = function (sel) {

$('.page').hide();
$(sel).fadeIn(0);
};

Array.prototype.shuffle = function () {

var i = this.length,
j,
t;
while (i) {
j = Math.floor(Math.random() * i);
t = this[--i];
this[i] = this[j];
this[j] = t;
}
return this;
};

function _getFlashObject() {

return document.getElementById('myFlash');
}

function play($file) {

try {
_getFlashObject().SetVariable('method:setUrl', $file);
_getFlashObject().SetVariable('method:play', '');
} catch (e) {
console_log('error: loading flash');
}
}

function pause() {

_getFlashObject().SetVariable('method:pause', '');
}

function stop() {

_getFlashObject().SetVariable('method:stop', '');
}

function setDivHeight() {

var max_height = 0,
max_outerHeight,
connection_height;
if (cq.type === 'sort') {
$('.drag-choice').each(function () {
if (max_height < $(this).height()) {
max_height = $(this).height();
}
});
$('.drag-choice').each(function () {
$(this).css('min-height', max_height);
$(this).css('max-width', $(this).width());
});
}
}

function setDragDropEvent() {

var dragObject, changeLi, former_list;
if (cq.type !== 'wordbank') {
dragObject = $('.drag-choice');
} else {
dragObject = $('.drag-choice-wordbank');
}
setClickEvent(dragObject,cq.type);
dragObject.each(function () {
$(this).draggable({
revert: true,
revertDuration: 0,
start: function () {
$(this).css('visibility', 'hidden');
},
stop: function () {
$(this).css('visibility', 'visible');
},
drag: function (event, ui) {
if (isIOS()) {
if (top.pageYOffset - ui.position.top < 50) {
if (top.pageYOffset > ui.position.top - 10) {
top.scrollTo(0, ui.position.top - 10);
}
}
if (ui.position.top - top.pageYOffset > top.innerHeight - 200) {
top.scrollTo(0, ui.position.top - top.innerHeight + 200);
}
}
},
appendTo: 'body',
helper: 'clone'

});
$(this).hover(
function () {
$(this).addClass('list-hover');
dragObject.not(this).removeClass('list-hover');
},
function () {
if (!$(this).hasClass('ui-draggable-dragging')) {
$(this).removeClass('list-hover');
}
}
);
});
if (cq.type === 'wordbank') {
$('.drop-choice-wordbank').each(function () {
$(this).droppable({
hoverClass: 'drop-hover',
drop: function (event, ui) {
if ($(this).children().length === 1) {
if (ui.draggable.parents('.drop-choice-wordbank').length === 1) {
ui.draggable
.prevAll('.wordbank-key')
.css('display', 'inline-block');
ui.draggable.appendTo(this);
$(this)
.find('.wordbank-key')
.css('display', 'none');
} else {
ui.draggable
.parent('#choices .drop-choice-list')
.css('display', 'none');
ui.draggable.appendTo(this);
$(this)
.find('.wordbank-key')
.css('display', 'none');
}
} else {
if (ui.draggable.parents('.drop-choice-wordbank').length === 1) {
ui.draggable.after($(this).find('.drag-choice-wordbank'));
ui.draggable.appendTo(this);
} else {
changeLi = $(this).find('.drag-choice-wordbank');
$('#choices .drop-choice-list')
.eq(changeLi.find('.drop-index').text())
.css('display', 'inline-block');
$('#choices .drop-choice-list')
.eq(changeLi.find('.drop-index').text())
.append(changeLi);
ui.draggable
.parent('#choices .drop-choice-list')
.css('display', 'none');
ui.draggable.appendTo(this);
}
}
ui.draggable.css('left', '');
ui.draggable.css('top', '');
play_dragged_sound();

setInitializeClick();
}
});
});
$('#choices').droppable({
drop: function (event, ui) {
ui.draggable.prevAll('.wordbank-key').css('display', 'inline-block');
$('#choices .drop-choice-list')
.eq(ui.draggable.find('.drop-index').text())
.css('display', 'inline-block');
$('#choices .drop-choice-list')
.eq(ui.draggable.find('.drop-index').text())
.append(ui.draggable);
ui.draggable.css('left', '');
ui.draggable.css('top', '');
play_dragged_sound();

setInitializeClick();
}
});
} else {
$('.drop-choice').each(function () {
$(this).droppable({
hoverClass: 'drop-hover',
drop: function (event, ui) {
$(this)
.find('li')
.removeClass('list-hover');
former_list = $(this).find('li');
ui.draggable.after($(this).find('li'));
$(this).append(ui.draggable);
ui.draggable.css('left', '');
ui.draggable.css('top', '');
change_sort_flg = true;
changelist_animation(ui.draggable, former_list);
play_dragged_sound();

setInitializeClick();
}
});
});
}
}

function setDragDropList() {

var template, displist, choice_value, choice_html, i;
if (cq.type === 'sort') {
template = sort_template;
} else if (cq.type === 'match') {
template = match_template;
}
if (cq.student_response && cq.student_response.length > 0) {
change_sort_flg = true;
displist = cq.student_response;
} else {
change_sort_flg = false;
displist = cq.choice;
}
for (i = 0; i < displist.length; i++) {
choice_value = convert_image_tags(displist[i]);
choice_html = template;
if (cq.type === 'match') {
choice_html = choice_html.replace(/\[\[choice\]\]/g, choice_value);
choice_html = choice_html.replace(
/\[\[match_key\]\]/g,
convert_image_tags(cq.match_key[i])
);
choice_html = choice_html.replace(/\[\[choice_id\]\]/g, 'choice_' + i);
} else {
choice_html = choice_html.replace(/\[\[choice\]\]/g, choice_value);
}
choice_html = choice_html.replace(
/\[\[choice_key\]\]/g,
htmlencode(displist[i])
);
choice_html = '<div class="choice">' + choice_html + '</div>';
$('#choices').append(choice_html);
}
}

function setDivWidth() {

var max_width = 0;
$('.drag-choice-wordbank').each(function () {
if (
max_width < $(this).width() &&
$(this).children('.disp_correct').length === 0
) {
max_width = $(this).width();
}
});
if (max_width < 50) {
max_width = 50;
}
$('.drag-choice-wordbank').each(function () {
$(this).css('min-width', max_width);
});
}

function isQuizUIVisible() {
return state == 'quiz' || state == 'quiz_review';
}

function disableDragDrop(dragobj, dropobj) {

dragobj.each(function () {
$(this).draggable('disable');
$(this)
.unbind('mouseenter')
.unbind('mouseleave');

$(this).css('pointer-events','none');
});
dropobj.each(function () {
$(this).droppable('disable');

$(this).css('pointer-events','none');
});
}

function is_shuffle(a1, a2) {

var i;
for (i = 1; i < a1.length; i++) {
if (a1[0] !== a1[i]) {
break;
}
if (i === a1.length - 1) {
return true;
}
}
for (i = 0; i < a1.length; i++) {
if (a1[i] !== a2[i]) {
break;
}
if (i === a1.length - 1) {
return false;
}
}
return true;
}

function is_shuffled_match(a1, a2, match_key) {
var aa1 = [],
aa2 = [],
i;
for (i = 0; i < a1.length; i++) {
aa1.push(
match_key[
a1.findIndex(function (j) {
return j == a1[i];
})
]
);
aa2.push(
match_key[
a1.findIndex(function (j) {
return j == a2[i];
})
]
);
}
return is_shuffle(aa1, aa2);
}

function changelist_animation(list1, list2) {

list1.css('left', '20px');
list2.css('left', '20px');
list1.animate(
{
left: '0px'
},
100
);
list2.animate(
{
left: '0px'
},
100
);
setTimeout(function () {
list1.css('background-color', 'white');
}, 100);
setTimeout(function () {
list1.css('background-color', '');
}, 300);
setTimeout(function () {
list2.css('background-color', 'white');
}, 100);
setTimeout(function () {
list2.css('background-color', '');
}, 300);
}

function gotoCertificate() {
window.open(
'https://quizgenerator.net/certificate/?type=' + _cfg.settings.certificate
);
}

function suspend() {
if (window.confirm('本当に中断しますか')) {

pauseAllMedias(null, null);
check_answer(false, true, false);
cstate('suspended');
show('#page_suspended');
save_suspend_data();
finalize_scorm();
helpToolTipHide();
}
}


setInterval(function () {
if (typeof cq == 'undefined') {
return;
}
if (typeof cq.result == 'undefined') {
if (cq.hasOwnProperty('latency')) {
cq.latency++;
} else {
cq.latency = 1;
}
}
}, 100);

var initPhotoSwipeFromDOM = function (gallerySelector) {
var parseThumbnailElements = function (el) {
var thumbElements = el.childNodes,
numNodes = thumbElements.length,
items = [],
figureEl,
linkEl,
size,
item;
for (var i = 0; i < numNodes; i++) {
figureEl = thumbElements[i];
if (figureEl.nodeType !== 1) {
continue;
}
linkEl = figureEl.children[0];
sizeStr = imgSize[linkEl.getAttribute('href')];
size = sizeStr.split('x');
item = {
src: linkEl.getAttribute('href'),
w: parseInt(size[0], 10),
h: parseInt(size[1], 10)
};
if (figureEl.children.length > 1) {
item.title = figureEl.children[1].innerHTML;
}
if (linkEl.children.length > 0) {
item.msrc = linkEl.children[0].getAttribute('src');
}
item.el = figureEl;
items.push(item);
}
return items;
};
var closest = function closest(el, fn) {
return el && (fn(el) ? el : closest(el.parentNode, fn));
};
var onThumbnailsClick = function (e) {
e = e || window.event;
e.preventDefault ? e.preventDefault() : (e.returnValue = false);
var eTarget = e.target || e.srcElement;
var clickedListItem = closest(eTarget, function (el) {
return el.tagName && el.tagName.toUpperCase() === 'FIGURE';
});
if (!clickedListItem) {
return;
}
var clickedGallery = clickedListItem.parentNode,
childNodes = clickedListItem.parentNode.childNodes,
numChildNodes = childNodes.length,
nodeIndex = 0,
index;
for (var i = 0; i < numChildNodes; i++) {
if (childNodes[i].nodeType !== 1) {
continue;
}
if (childNodes[i] === clickedListItem) {
index = nodeIndex;
break;
}
nodeIndex++;
}
if (index >= 0) {
openPhotoSwipe(index, clickedGallery);
}
e.stopPropagation();
return false;
};

var photoswipeParseHash = function () {
var hash = window.location.hash.substring(1),
params = {};
if (hash.length < 5) {
return params;
}
var vars = hash.split('&');
for (var i = 0; i < vars.length; i++) {
if (!vars[i]) {
continue;
}
var pair = vars[i].split('=');
if (pair.length < 2) {
continue;
}
params[pair[0]] = pair[1];
}
if (params.gid) {
params.gid = parseInt(params.gid, 10);
}
if (!params.hasOwnProperty('pid')) {
return params;
}
params.pid = parseInt(params.pid, 10);
return params;
};
var openPhotoSwipe = function (index, galleryElement, disableAnimation) {
var pswpElement = document.querySelectorAll('.pswp')[0],
gallery,
options,
items;
items = parseThumbnailElements(galleryElement);
options = {
index: index,
galleryUID: galleryElement.getAttribute('data-pswp-uid'),
getThumbBoundsFn: function (index) {
var thumbnail = items[index].el.getElementsByTagName('img')[0], // find thumbnail
pageYScroll =
window.pageYOffset || document.documentElement.scrollTop,
rect = thumbnail.getBoundingClientRect();
return { x: rect.left, y: rect.top + pageYScroll, w: rect.width };
}
};
if (disableAnimation) {
options.showAnimationDuration = 0;
}
gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options);
gallery.init();
};
var galleryElements = document.querySelectorAll(gallerySelector);

for (var i = 0, l = galleryElements.length; i < l; i++) {
galleryElements[i].setAttribute('data-pswp-uid', i + 1);
galleryElements[i].onclick = onThumbnailsClick;
}
var hashData = photoswipeParseHash();
if (hashData.pid > 0 && hashData.gid > 0) {
openPhotoSwipe(hashData.pid - 1, galleryElements[hashData.gid - 1], true);
}
};
var photo;
setTimeout(function () {
photo = initPhotoSwipeFromDOM('.my-gallery');
}, 500);

function backToQuestion(_position) {
cstate('quiz_review');
show('#page_quiz');
position = _position;
display_quiz();
$('.list').remove();
helpToolTipRemove();
}

function drawGraph() {
var data = [0, 0, 0, 0, 0];
var i;
for (i = 0; i < _cfg.questions.length; i++) {
if (_cfg.questions[i].correct_count >= _cfg.settings.master_count) {
data[0]++;
} else if (_cfg.questions[i].unknown_flag) {
data[2]++;
} else if (_cfg.questions[i].correct_count > 0) {
data[1]++;
} else if (_cfg.questions[i].incorrect_count > 0) {
data[3]++;
} else {
data[4]++;
}
}

if (data[0] + data[1] + data[2] + data[3] == 0) {
$('#start_quiz_button_weak')
.prop('disabled', true)
.css('pointer-events', 'none');
$('#start_quiz_button_weak')
.parent('div')
.css('cursor', 'not-allowed');
} else {
$('#start_quiz_button_weak')
.prop('disabled', false)
.css('pointer-events', 'auto');
$('#start_quiz_button_weak')
.parent('div')
.css('cursor', 'pointer');
$('#start_quiz_button_weak')
.parent('div')
.tooltip('disable');
}

var ctxD = document.getElementById('doughnutChart').getContext('2d');
var myLineChart = new Chart(ctxD, {
type: 'doughnut',
data: {
labels: [
'全問正解',
'学習中',
'分からない',
'間違い',
'未解答'
],
datasets: [
{
data: data,
backgroundColor: [
'#00C851',
'#4285F4',
'#FF8800',
'#F7464A',
'#949FB1'
],
hoverBackgroundColor: [
'#00e25b',
'#5a95f5',
'#FFC870',
'#FF5A5E',
'#A8B3C5'
]
}
]
},
options: {
responsive: true,
legend: {
display: false
}
}
});
}

if (!Array.prototype.findIndex) {
Array.prototype.findIndex = function (predicate) {
if (this === null) {
throw new TypeError(
'Array.prototype.findIndex called on null or undefined'
);
}
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
var list = Object(this);
var length = list.length >>> 0;
var thisArg = arguments[1];
var value;

for (var i = 0; i < length; i++) {
value = list[i];
if (predicate.call(thisArg, value, i, list)) {
return i;
}
}
return -1;
};
}


getSectionQuizMaxArray = function (save_questionData) {
let sectionArray = [];
let currentSection = 0;
let count = 0;

for (i = 0; i < save_questionData.length; i++) {
count++;

if (i + 1 == save_questionData.length) {
sectionArray.push(count);
break;
}

if (currentSection != save_questionData[i + 1].section) {
sectionArray.push(count);

currentSection = save_questionData[i + 1].section;
count = 0;
}
}

return sectionArray;
};

/**
* 分数計算ライブラリ
* @author yoichiro
*/
var fraction = {}
fraction.gcd = function (x, y) {
x = Math.abs(x);
y = Math.abs(y);
while (y) {
var t = y;
y = x % y;
x = t;
}
return x;
}

fraction.reduce = function (num) {
var gcdNum = fraction.gcd(num[0], num[1]);
return [num[0] / gcdNum, num[1] / gcdNum];
}

fraction.mul = function (num1, num2) {
return fraction.reduce([num1[0] * num2[0], num1[1] * num2[1]]);
}

fraction.div = function (num1, num2) {
return fraction.reduce([num1[0] * num2[1], num1[1] * num2[0]]);
}

fraction.add = function (num1, num2) {
return fraction.reduce([num1[0] * num2[0], num1[0] * num2[1] + num2[0] * num1[1]]);
}

fraction.tofrac = function (n) {
return [1, n];
}

fraction.toDouble = function (num) {
if (num) {
return num[1] / num[0];
} else {
return 0;
}
}


var LZString = function () { function o(o, r) { if (!t[o]) { t[o] = {}; for (var n = 0; n < o.length; n++)t[o][o.charAt(n)] = n } return t[o][r] } var r = String.fromCharCode, n = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", e = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$", t = {}, i = { compressToBase64: function (o) { if (null == o) return ""; var r = i._compress(o, 6, function (o) { return n.charAt(o) }); switch (r.length % 4) { default: case 0: return r; case 1: return r + "==="; case 2: return r + "=="; case 3: return r + "=" } }, decompressFromBase64: function (r) { return null == r ? "" : "" == r ? null : i._decompress(r.length, 32, function (e) { return o(n, r.charAt(e)) }) }, compressToUTF16: function (o) { return null == o ? "" : i._compress(o, 15, function (o) { return r(o + 32) }) + " " }, decompressFromUTF16: function (o) { return null == o ? "" : "" == o ? null : i._decompress(o.length, 16384, function (r) { return o.charCodeAt(r) - 32 }) }, compressToUint8Array: function (o) { for (var r = i.compress(o), n = new Uint8Array(2 * r.length), e = 0, t = r.length; t > e; e++) { var s = r.charCodeAt(e); n[2 * e] = s >>> 8, n[2 * e + 1] = s % 256 } return n }, decompressFromUint8Array: function (o) { if (null === o || void 0 === o) return i.decompress(o); for (var n = new Array(o.length / 2), e = 0, t = n.length; t > e; e++)n[e] = 256 * o[2 * e] + o[2 * e + 1]; var s = []; return n.forEach(function (o) { s.push(r(o)) }), i.decompress(s.join("")) }, compressToEncodedURIComponent: function (o) { return null == o ? "" : i._compress(o, 6, function (o) { return e.charAt(o) }) }, decompressFromEncodedURIComponent: function (r) { return null == r ? "" : "" == r ? null : (r = r.replace(/ /g, "+"), i._decompress(r.length, 32, function (n) { return o(e, r.charAt(n)) })) }, compress: function (o) { return i._compress(o, 16, function (o) { return r(o) }) }, _compress: function (o, r, n) { if (null == o) return ""; var e, t, i, s = {}, p = {}, u = "", c = "", a = "", l = 2, f = 3, h = 2, d = [], m = 0, v = 0; for (i = 0; i < o.length; i += 1)if (u = o.charAt(i), Object.prototype.hasOwnProperty.call(s, u) || (s[u] = f++, p[u] = !0), c = a + u, Object.prototype.hasOwnProperty.call(s, c)) a = c; else { if (Object.prototype.hasOwnProperty.call(p, a)) { if (a.charCodeAt(0) < 256) { for (e = 0; h > e; e++)m <<= 1, v == r - 1 ? (v = 0, d.push(n(m)), m = 0) : v++; for (t = a.charCodeAt(0), e = 0; 8 > e; e++)m = m << 1 | 1 & t, v == r - 1 ? (v = 0, d.push(n(m)), m = 0) : v++, t >>= 1 } else { for (t = 1, e = 0; h > e; e++)m = m << 1 | t, v == r - 1 ? (v = 0, d.push(n(m)), m = 0) : v++, t = 0; for (t = a.charCodeAt(0), e = 0; 16 > e; e++)m = m << 1 | 1 & t, v == r - 1 ? (v = 0, d.push(n(m)), m = 0) : v++, t >>= 1 } l--, 0 == l && (l = Math.pow(2, h), h++), delete p[a] } else for (t = s[a], e = 0; h > e; e++)m = m << 1 | 1 & t, v == r - 1 ? (v = 0, d.push(n(m)), m = 0) : v++, t >>= 1; l--, 0 == l && (l = Math.pow(2, h), h++), s[c] = f++, a = String(u) } if ("" !== a) { if (Object.prototype.hasOwnProperty.call(p, a)) { if (a.charCodeAt(0) < 256) { for (e = 0; h > e; e++)m <<= 1, v == r - 1 ? (v = 0, d.push(n(m)), m = 0) : v++; for (t = a.charCodeAt(0), e = 0; 8 > e; e++)m = m << 1 | 1 & t, v == r - 1 ? (v = 0, d.push(n(m)), m = 0) : v++, t >>= 1 } else { for (t = 1, e = 0; h > e; e++)m = m << 1 | t, v == r - 1 ? (v = 0, d.push(n(m)), m = 0) : v++, t = 0; for (t = a.charCodeAt(0), e = 0; 16 > e; e++)m = m << 1 | 1 & t, v == r - 1 ? (v = 0, d.push(n(m)), m = 0) : v++, t >>= 1 } l--, 0 == l && (l = Math.pow(2, h), h++), delete p[a] } else for (t = s[a], e = 0; h > e; e++)m = m << 1 | 1 & t, v == r - 1 ? (v = 0, d.push(n(m)), m = 0) : v++, t >>= 1; l--, 0 == l && (l = Math.pow(2, h), h++) } for (t = 2, e = 0; h > e; e++)m = m << 1 | 1 & t, v == r - 1 ? (v = 0, d.push(n(m)), m = 0) : v++, t >>= 1; for (; ;) { if (m <<= 1, v == r - 1) { d.push(n(m)); break } v++ } return d.join("") }, decompress: function (o) { return null == o ? "" : "" == o ? null : i._decompress(o.length, 32768, function (r) { return o.charCodeAt(r) }) }, _decompress: function (o, n, e) { var t, i, s, p, u, c, a, l, f = [], h = 4, d = 4, m = 3, v = "", w = [], A = { val: e(0), position: n, index: 1 }; for (i = 0; 3 > i; i += 1)f[i] = i; for (p = 0, c = Math.pow(2, 2), a = 1; a != c;)u = A.val & A.position, A.position >>= 1, 0 == A.position && (A.position = n, A.val = e(A.index++)), p |= (u > 0 ? 1 : 0) * a, a <<= 1; switch (t = p) { case 0: for (p = 0, c = Math.pow(2, 8), a = 1; a != c;)u = A.val & A.position, A.position >>= 1, 0 == A.position && (A.position = n, A.val = e(A.index++)), p |= (u > 0 ? 1 : 0) * a, a <<= 1; l = r(p); break; case 1: for (p = 0, c = Math.pow(2, 16), a = 1; a != c;)u = A.val & A.position, A.position >>= 1, 0 == A.position && (A.position = n, A.val = e(A.index++)), p |= (u > 0 ? 1 : 0) * a, a <<= 1; l = r(p); break; case 2: return "" }for (f[3] = l, s = l, w.push(l); ;) { if (A.index > o) return ""; for (p = 0, c = Math.pow(2, m), a = 1; a != c;)u = A.val & A.position, A.position >>= 1, 0 == A.position && (A.position = n, A.val = e(A.index++)), p |= (u > 0 ? 1 : 0) * a, a <<= 1; switch (l = p) { case 0: for (p = 0, c = Math.pow(2, 8), a = 1; a != c;)u = A.val & A.position, A.position >>= 1, 0 == A.position && (A.position = n, A.val = e(A.index++)), p |= (u > 0 ? 1 : 0) * a, a <<= 1; f[d++] = r(p), l = d - 1, h--; break; case 1: for (p = 0, c = Math.pow(2, 16), a = 1; a != c;)u = A.val & A.position, A.position >>= 1, 0 == A.position && (A.position = n, A.val = e(A.index++)), p |= (u > 0 ? 1 : 0) * a, a <<= 1; f[d++] = r(p), l = d - 1, h--; break; case 2: return w.join("") }if (0 == h && (h = Math.pow(2, m), m++), f[l]) v = f[l]; else { if (l !== d) return null; v = s + s.charAt(0) } w.push(v), f[d++] = s + v.charAt(0), h--, s = v, 0 == h && (h = Math.pow(2, m), m++) } } }; return i }(); "function" == typeof define && define.amd ? define(function () { return LZString }) : "undefined" != typeof module && null != module && (module.exports = LZString);

if (localStorage) {
var lbLocalStorage = {};
lbLocalStorage.getItem = function (key) {
var value = localStorage.getItem(key);
if (value && value.substring(0, 2) == "LB") {
return LZString.decompress(value.substring(2));
} else {
return value;
}
}
lbLocalStorage.setItem = function (key, value) {
var compressedValue = LZString.compress(value);
return localStorage.setItem(key, 'LB' + compressedValue);
}
}


const helpElementsId = '#suspend_button, #hide_list_button, #display_next_quiz, #display_prev_quiz, #not_disp_answer_mark_button, #suspend_button_wrapper';
const helpElementsArray = ['#suspend_button', '#hide_list_button', '#display_next_quiz', '#display_prev_quiz', '#not_disp_answer_mark_button', '#suspend_button_wrapper'];

function isTouchDevice() {
const hasTouchEvent = window.ontouchstart === null ? true : false
return hasTouchEvent;
}


function notTouchDeviceHoverAction() {
$(helpElementsId).hover(
function () {
if ($(this).css('display') !== 'none') {
$(this).next('.tooltip-common').css('display', 'block');
}
},
function () {
$(this).next('.tooltip-common').css('display', 'none');
}
);
$('#pagination').hover(
function () {
$('#question_count_wrapper').next('.tooltip-common').css('display', 'block');
},
function () {
$('#question_count_wrapper').next('.tooltip-common').css('display', 'none');
}
);
$('#timer_wrap_quiz').hover(
function () {
$('#timer_wrap_quiz .tooltip-common').css('display', 'block');
},
function () {
$('#timer_wrap_quiz .tooltip-common').css('display', 'none');
}
);
}


$(function () {
if (!isTouchDevice()) {
notTouchDeviceHoverAction();
}
});


function helpToolTipShow() {
$('.tooltip-wrapper .tooltip-common').addClass('tooltip-visible');
helpElementsArray.forEach(function (helpId) {
if ($(helpId).css('display') == 'none') {
$(helpId + '+ .tooltip-common').removeClass('tooltip-visible');
}
})

$('#help_button_show').tooltip('hide');
$('#help_button_show').hide();
$('#help_button_hide').show();
};


function helpToolTipHide() {
$('.tooltip-wrapper .tooltip-common').removeClass('tooltip-visible');
$('#help_button_show').show();
$('#help_button_hide').hide();
};


function helpToolTipRemove() {
$('#timer_wrap_quiz .tooltip-common').remove();

$('.col.order-md-1.flex-end').remove();
}

/**
* 択一問題で選択したラジオボタンを未選択に戻す
* @author a.yokoyama
*/
const removeChecked = function () {
const $this = $(this);
const thisValue = $this.val();

if (thisValue === window.checkedValue) {
$this.prop('checked', false);
const unique = new Date().getTime().toString(16) + Math.floor(1000 * Math.random()).toString(16);
window.checkedValue = unique;
return;
}
window.checkedValue = thisValue;
}

/**
* 複数選択問題で解答を正答数以上に選択できないようにする
* @author a.yokoyama
*/
const checkSelectionLimit = function () {
const limit = window.cq.answer.length;
const selectedNumber = $('.choice_checkbox:checked').length;

if (selectedNumber > limit) {
alert('解答をこれ以上選択できません');
$(this).prop('checked', false);
}
}


/**
* クリックで選択解答できるようにする（穴埋め、並び替え、組み合わせ）
* @author s.toyoshima
*/
let choiceSel = -1;
let beforeAnswerSel = -1;
let beforePosition = false;
let answerSel = false;
let dropSel = false;
let dropArea = false;
function setClickEvent(dragObject,type) {
if (beforeAnswerSel > -1){

beforeAnswerSel = -1;
}
if (type == 'wordbank') {
dragObject.each(function (index) {
$(this).attr('choice-num',index);
$(this).on('click', function(){
choiceSel = $(this).attr('choice-num');
if (beforeAnswerSel == choiceSel) {

$(this).fadeTo(100, 1, function(){
beforeAnswerSel = -1;
});
} else if (beforeAnswerSel == -1) {

if (dropSel && choiceSel){

if ($(this).parent().is($('.drop-choice-wordbank'))){
$(this).parent()
.find('.wordbank-key')
.css('display', 'inline-block');
} else {
$("#choices > .drop-choice-list:eq(" + choiceSel + ")").css('display','none');
}
$(beforePosition).css('display', 'none');
$(this).appendTo($(beforePosition).parent());
setInitializeClick()
return false;
} else {

$(this).fadeTo(100, 0.5, function(){
beforeAnswerSel = choiceSel;

beforePosition = $(this).parent();
});
}
} else if (beforeAnswerSel > -1){
dropArea = $('.drop-choice-wordbank').find(".drag-choice-wordbank[choice-num= " + beforeAnswerSel + "]");
if (dropArea.length > 0){

if ($(this).parent().is($('.drop-choice-wordbank'))){

$(dropArea).appendTo($(this).parent());
} else {

$(dropArea).appendTo($("#choices > .drop-choice-list:eq(" + beforeAnswerSel + ")"));
$("#choices > .drop-choice-list:eq(" + choiceSel + ")").css('display','none');
$("#choices > .drop-choice-list:eq(" + beforeAnswerSel + ")").css('display','inline-block');
}
$(beforePosition.context).css('opacity',1);

$(this).appendTo($(beforePosition));
setInitializeClick();
return false;
} else {

if ($(this).parent().is($('.drop-choice-list'))){

$(".drag-choice-wordbank[choice-num= " + beforeAnswerSel + "]").fadeTo(100, 1, function(){
$(".drag-choice-wordbank[choice-num= " + choiceSel + "]").fadeTo(100, 0.5, function(){
beforeAnswerSel = choiceSel;
});
});
}
}
}
});
});
$('.drop-choice-wordbank').each(function (index) {
$(this).attr('answer-num',index);
$(this).on('click', function(){
answerSel = $(this).children('.drag-choice-wordbank').attr('choice-num');
if (beforeAnswerSel > -1 && beforeAnswerSel !== answerSel){

if ($(this).children('.drag-choice-wordbank').length > 0){


$("#choices > .drop-choice-list:eq(" + answerSel + ")").css('display','inline-block');
$($('#choices').find(".drag-choice-wordbank[choice-num= " + answerSel + "]")[0]).css('opacity',1.0);
$(".drag-choice-wordbank[choice-num= " + answerSel + "]").appendTo($("#choices > .drop-choice-list:eq(" + answerSel + ")"));
} else {

$(".drag-choice-wordbank[choice-num= " + beforeAnswerSel + "]").parent()
.find('.wordbank-key')
.css('display', 'inline-block');
}

$(".drag-choice-wordbank[choice-num= " + beforeAnswerSel + "]").css('opacity', 1.0);
$(".drag-choice-wordbank[choice-num= " + beforeAnswerSel + "]").appendTo($(this));
$("#choices > .drop-choice-list:eq(" + beforeAnswerSel + ")").css('display','none');
$(this)
.find('.wordbank-key')
.css('display', 'none');
setInitializeClick();
return false;
} else {
if (answerSel === undefined){

if (dropSel){
$('.wordbank-key').css('border', '2px solid #ccc');
dropSel = false;
} else {
dropSel = $(this).attr('answer-num');
beforePosition = $(this).children();

$('.wordbank-key').css('border', '2px solid #ccc');
$(this).children().css('border','2px solid red')
}
}
}
})
});
} else {
dragObject.each(function (index) {
$(this).attr('choice-num',index);
$(this).on('click', function(){
choiceSel = $(this).attr('choice-num');
if (beforeAnswerSel == choiceSel) {

$(this).fadeTo(100, 1, function(){
beforeAnswerSel = -1;
});
} else if (beforeAnswerSel == -1) {

$(this).fadeTo(100, 0.5, function(){
beforeAnswerSel = choiceSel;
beforePosition = $(this).parent();
});
} else if (beforeAnswerSel > -1){

if (beforeAnswerSel != choiceSel){
$(".drag-choice[choice-num= " + beforeAnswerSel + "]").appendTo($(this).parent());
$(".drag-choice[choice-num= " + choiceSel + "]").appendTo(beforePosition);
$(".drag-choice[choice-num= " + beforeAnswerSel + "]").css('opacity',1);
beforeAnswerSel = -1;
}
}
})
})
}
}

/**
* クリック解答選択を初期化する
* @author s.toyoshima
*/
function setInitializeClick(){
beforeAnswerSel = -1;
choiceSel = -1;
dropSel = false;
dropArea = false;
answerSel = false;
beforePosition = false;
$('.drag-choice-wordbank').css('opacity',1.0);
$('.drag-choice').css('opacity',1.0);
$('.wordbank-key').css('border', '2px solid #ccc');
}
