var H5P = H5P || {};
/**
* Will render a Question with multiple choices for answers.
*
* Events provided:
* - h5pQuestionSetFinished: Triggered when a question is finished. (User presses Finish-button)
*
* @param {Array} options
* @param {int} contentId
* @param {Object} contentData
* @returns {H5P.QuestionSet} Instance
*/
H5P.QuestionSet = (function($, EventDispatcher) {
var QuestionSet = function (options, contentId, contentData) {
var self = this;
EventDispatcher.call(this);
self.contentId = contentId;
self.isEndgameRendered = false;
self.contentData = contentData || {};
// set default params
var params = $.extend(true, {}, getDefaults(), options);
// add the params to the this scope
$.extend(true, this, params);
// Bring question set up to date when resuming
if (self.contentData.previousState) {
if (self.contentData.previousState.progress) {
currentQuestionIndex = self.contentData.previousState.progress;
}
questionOrder = self.contentData.previousState.order;
}
this.instances = this.init(params, contentId, self.contentData);
};
QuestionSet.prototype = Object.create(EventDispatcher.prototype);
QuestionSet.prototype.constructor = QuestionSet;
var texttemplate =
'<% if (introPage.showIntroPage) { %>' +
'
' +
' <% if (introPage.title) { %>' +
'
<%= introPage.title %>
' +
' <% } %>' +
' <% if (introPage.introduction) { %>' +
'
<%= introPage.introduction %>
' +
' <% } %>' +
'
' +
'
' +
'<% } %>' +
'' +
'
<%= message %>
' +
'
' +
' <% if (comment) { %>' +
' ' +
' <% } %>' +
' <% if (resulttext) { %>' +
'
<%= resulttext %>
' +
' <% } %>' +
'
' +
' ' +
' ' +
' ' +
'
' +
'
';
var template = new EJS({text: texttemplate});
var endTemplate = new EJS({text: resulttemplate});
// TODO Move to QuestionSet
var currentQuestionIndex = 0;
var questionInstances = [];
var questionOrder; //Stores order of questions to allow resuming of question set
var $myDom;
var scoreBar;
var up;
var renderSolutions = false;
var showingSolutions = false;
var $template;
var cloneQuestionAndIndex = function (question, index) {
var result = H5P.cloneObject(question, true);
result.initialIndex = index;
return result;
};
var limitArrayToPoolSize = function (array, poolSize) {
return array.slice(0, poolSize);
};
var initQuestions = function (questions, poolSize) {
var result = questions.map(cloneQuestionAndIndex);
result = H5P.shuffleArray(questions);
result = limitArrayToPoolSize(result, poolSize);
return result;
};
var useQuestionPool = function (questions, poolSize) {
return poolSize && poolSize < questions.length || poolSize > 0;
};
var createQuestionContainerDom = function (params, questions) {
var clonedParams = H5P.cloneObject(params, true);
clonedParams.questions = questions;
return $(template.render(clonedParams));
};
var overrideBehaviourAndSettings = function (question, override, $template, instance) {
if (override.showSolutionButton) {
question.params.behaviour.enableSolutionsButton = (override.showSolutionButton === 'on');
}
if (override.retryButton) {
question.params.behaviour.enableRetry = (override.retryButton === 'on');
}
question.params.overrideSettings = question.params.overrideSettings || {};
question.params.overrideSettings.$confirmationDialogParent = $template.last();
question.params.overrideSettings.instance = instance;
return question;
};
var getAnswersPreviousState = function (contentData, questionIndex) {
if (contentData.previousState && contentData.previousState.answers) {
return contentData.previousState.answers[questionIndex];
}
};
var createQuestionInstance = function (questionSet, question, questionIndex, contentId, contentData) {
var previousState = getAnswersPreviousState(contentData, questionIndex);
var instance = H5P.newRunnable(question, contentId, undefined, undefined, {
previousState: previousState,
parent: questionSet
});
instance.on('resize', function () {
up = true;
questionSet.trigger('resize');
});
return instance;
};
QuestionSet.prototype.init = function (params, contentId, contentData) {
var self = this;
var questions = params.questions;
if (contentData.previousState && contentData.previousState.questions) {
questions = contentData.previousState.questions;
}
else if (useQuestionPool(questions, params.poolSize)) {
questions = initQuestions(questions, params.poolSize);
}
else if (params.randomQuestions) {
questions = H5P.shuffleArray(questions);
}
// Create the html template for the question container
$template = createQuestionContainerDom(params, questions);
questionInstances = questions.map(function (question, index) {
question = overrideBehaviourAndSettings(question, params.override, $template, self);
return createQuestionInstance(self, question, index, contentId, contentData);
});
// Resize all interactions on resize
this.on('resize', onResize);
return questionInstances;
};
var onResize = function () {
if (up) {
// Prevent resizing the question again.
up = false;
}
else {
questionInstances.forEach(function (instance) {
instance.trigger('resize');
});
}
};
var _stopQuestion = function (questionNumber) {
if (questionInstances[questionNumber]) {
pauseMedia(questionInstances[questionNumber]);
}
};
QuestionSet.prototype._showQuestion = function (questionNumber, preventAnnouncement) {
var self = this;
// Sanitize input.
if (questionNumber < 0) {
questionNumber = 0;
}
if (questionNumber >= self.questions.length) {
questionNumber = self.questions.length - 1;
}
currentQuestionIndex = questionNumber;
// Hide all questions
$('.question-container', $myDom).hide().eq(questionNumber).show();
if (questionInstances[questionNumber]) {
// Trigger resize on question in case the size of the QS has changed.
var instance = questionInstances[questionNumber];
instance.setActivityStarted();
if (instance.$ !== undefined) {
instance.trigger('resize');
}
}
// Update progress indicator
// Test if current has been answered.
if (self.progressType === 'textual') {
$('.progress-text', $myDom).text(self.texts.textualProgress.replace("@current", questionNumber + 1).replace("@total", self.questions.length));
}
else {
// Set currentNess
var previousQuestion = $('.progress-dot.current', $myDom).parent().index();
if (previousQuestion >= 0) {
self.toggleCurrentDot(previousQuestion, false);
self.toggleAnsweredDot(previousQuestion, questionInstances[previousQuestion].getAnswerGiven());
}
self.toggleCurrentDot(questionNumber, true);
}
if (!preventAnnouncement) {
// Announce question number of total, must use timeout because of buttons logic
setTimeout(function () {
var humanizedProgress = self.texts.readSpeakerProgress
.replace('@current', (currentQuestionIndex + 1).toString())
.replace('@total', questionInstances.length.toString());
$('.qs-progress-announcer', $myDom)
.html(humanizedProgress)
.show().focus();
if (instance && instance.readFeedback) {
instance.readFeedback();
}
}, 0);
}
// Remember where we are
self._updateButtons();
self.trigger('resize');
return currentQuestionIndex;
};
/**
* Show solutions for subcontent, and hide subcontent buttons.
* Used for contracts with integrated content.
* @public
*/
var showSolutions = function () {
showingSolutions = true;
for (var i = 0; i < questionInstances.length; i++) {
// Enable back and forth navigation in solution mode
toggleDotsNavigation(true);
if (i < questionInstances.length - 1) {
questionInstances[i].showButton('next');
}
if (i > 0) {
questionInstances[i].showButton('prev');
}
try {
// Do not read answers
questionInstances[i].toggleReadSpeaker(true);
questionInstances[i].showSolutions();
questionInstances[i].toggleReadSpeaker(false);
}
catch (error) {
H5P.error("subcontent does not contain a valid showSolutions function");
H5P.error(error);
}
}
};
/**
* Toggles whether dots are enabled for navigation
*/
var toggleDotsNavigation = function (enable) {
$('.progress-dot', $myDom).each(function () {
$(this).toggleClass('disabled', !enable);
$(this).attr('aria-disabled', enable ? 'false' : 'true');
// Remove tabindex
if (!enable) {
$(this).attr('tabindex', '-1');
}
});
};
/**
* Resets the task and every subcontent task.
* Used for contracts with integrated content.
* @public
*/
QuestionSet.prototype.resetTask = function () {
var self = this;
showingSolutions = false;
questionInstances.forEach(function(instance, index){
if(typeof instance.resetTask === 'function'){
instance.resetTask();
} else {
H5P.error("subcontent does not contain a valid resetTask function");
}
// Hide back and forth navigation in normal mode
if (self.disableBackwardsNavigation) {
toggleDotsNavigation(false);
var isAnsweredFirstQuestion = (index === 0 && instance.getAnswerGiven());
instance[isAnsweredFirstQuestion ? 'showButton': 'hideButton']('next');
instance.hideButton('prev');
}
});
// Hide finish button
var lastQuestionInstance = questionInstances[questionInstances.length - 1];
lastQuestionInstance.hideButton('finish');
// Mark all tasks as unanswered:
$('.progress-dot').each(function (idx) {
self.toggleAnsweredDot(idx, false);
});
//Force the last page to be reRendered
self.rendered = false;
// if using pool
if(self.poolSize > 0){
var questions = H5P.shuffleArray(self.questions);
questionInstances = questions.map(function (question, index) {
question = overrideBehaviourAndSettings(question, self.override, $template, self);
return createQuestionInstance(self, question, index, self.contentId, self.contentData);
});
questionInstances = limitArrayToPoolSize(questionInstances, self.poolSize);
}
if (self.randomQuestions || self.poolSize > 0) {
self.renderRandomizedQuestions();
}
};
/**
* Randomizes question instances
*/
QuestionSet.prototype.renderRandomizedQuestions = function () {
var self = this;
self.removeQuestionsFromDom();
questionInstances = H5P.shuffleArray(questionInstances);
questionInstances.forEach(function(question, i){
var $questionContainer = $('.question-container:eq(' + i + ')', $myDom);
// Make sure styles are not being added twice
$questionContainer.attr('class', 'question-container');
question.attach($questionContainer, $myDom);
// toggle buttons
self._updateButtons(question, i);
});
};
QuestionSet.prototype.removeQuestionsFromDom = function () {
$('.question-container', $myDom).each(function () {
$(this).children().detach();
});
};
// Update button state.
QuestionSet.prototype._updateButtons = function () {
var self = this;
var currentQuestion = questionInstances[currentQuestionIndex];
var isLast = currentQuestionIndex === (questionInstances.length - 1);
};
QuestionSet.prototype.isAllAnswered = function(){
return questionInstances.every(function(question){
return question.getAnswerGiven();
});
};
QuestionSet.prototype._updateButtons = function (questionInstance, index) {
questionInstance = questionInstance || questionInstances[currentQuestionIndex];
index = index || currentQuestionIndex;
var self = this;
var isFirst = self.isFirst(index);
var isLast = self.isLast(index);
//Show buttons if necessary
questionInstance[isLast && self.isAllAnswered() ? 'showButton' : 'hideButton']('finish');
// Verify that current question is answered when backward nav is disabled
if (self.disableBackwardsNavigation) {
var showNextButton = questionInstance.getAnswerGiven() && !isLast;
questionInstance[showNextButton ? 'showButton' : 'hideButton']('next');
} else {
questionInstance[!isLast ? 'showButton' : 'hideButton']('next');
}
if (isFirst || self.disableBackwardsNavigation) {
questionInstance.hideButton('prev');
}
else {
questionInstance.showButton('prev');
}
};
QuestionSet.prototype.moveQuestion = function (direction) {
var self = this;
if (self.disableBackwardsNavigation && !questionInstances[currentQuestionIndex].getAnswerGiven()) {
questionInstances[currentQuestionIndex].hideButton('next');
questionInstances[currentQuestionIndex].hideButton('finish');
return;
}
_stopQuestion(currentQuestionIndex);
if (currentQuestionIndex + direction >= questionInstances.length) {
self._displayEndGame();
}
else {
// Allow movement if backward navigation enabled or answer given
self._showQuestion(currentQuestionIndex + direction);
}
};
/**
* Toggle answered state of dot at given index
* @param {number} dotIndex Index of dot
* @param {boolean} isAnswered True if is answered, False if not answered
*/
QuestionSet.prototype.toggleAnsweredDot = function (dotIndex, isAnswered) {
var $el = $('.progress-dot:eq(' + dotIndex + ')', $myDom);
// Skip current button
if ($el.hasClass('current')) {
return;
}
// Ensure boolean
isAnswered = !!isAnswered;
var label = this.texts.jumpToQuestion
.replace('%d', (dotIndex + 1).toString())
.replace('%total', $('.progress-dot', $myDom).length) +
', ' +
(isAnswered ? this.texts.answeredText : this.texts.unansweredText);
$el.toggleClass('unanswered', !isAnswered)
.toggleClass('answered', isAnswered)
.attr('aria-label', label);
};
/**
* Toggle current state of dot at given index
* @param dotIndex
* @param isCurrent
*/
QuestionSet.prototype.toggleCurrentDot = function (dotIndex, isCurrent) {
var self = this;
var $el = $('.progress-dot:eq(' + dotIndex + ')', $myDom);
var texts = self.texts;
var label = texts.jumpToQuestion
.replace('%d', (dotIndex + 1).toString())
.replace('%total', $('.progress-dot', $myDom).length);
if (!isCurrent) {
var isAnswered = $el.hasClass('answered');
label += ', ' + (isAnswered ? texts.answeredText : texts.unansweredText);
}
else {
label += ', ' + texts.currentQuestionText;
}
var disabledTabindex = self.disableBackwardsNavigation && !showingSolutions;
$el.toggleClass('current', isCurrent)
.attr('aria-label', label)
.attr('tabindex', isCurrent && !disabledTabindex ? 0 : -1);
};
QuestionSet.prototype._displayEndGame = function () {
var self = this;
$('.progress-dot.current', $myDom).removeClass('current');
if (self.isEndgameRendered) {
$myDom.children().hide().filter('.questionset-results').show();
self.trigger('resize');
return;
}
//Remove old score screen.
$myDom.children().hide().filter('.questionset-results').remove();
self.isEndgameRendered = true;
// Get total score.
var finals = self.getScore();
var totals = self.getMaxScore();
var scoreString = self.endGame.scoreString.replace("@score", finals).replace("@total", totals);
var success = ((100 * finals / totals) >= self.passPercentage);
var eventData = {
score: scoreString,
passed: success
};
if (self.endGame.showAnimations) {
var videoData = success ? self.endGame.successVideo : self.endGame.failVideo;
if (videoData) {
$myDom.children().hide();
var $videoContainer = $('