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
* @returns {H5P.QuestionSet} Instance
*/
H5P.QuestionSet = function (options, contentId) {
if (!(this instanceof H5P.QuestionSet)) {
return new H5P.QuestionSet(options, contentId);
}
H5P.EventDispatcher.call(this);
var $ = H5P.jQuery;
var self = this;
this.contentId = contentId;
var texttemplate =
'<% if (introPage.showIntroPage) { %>' +
'
' +
' <% if (introPage.title) { %>' +
'
<%= introPage.title %>
' +
' <% } %>' +
' <% if (introPage.introduction) { %>' +
'
<%= introPage.introduction %>
' +
' <% } %>' +
'
' +
'
' +
'<% } %>' +
'' +
'
<%= message %>
' +
'
' +
' <% if (comment) { %>' +
' ' +
' <% } %>' +
' <% if (resulttext) { %>' +
'
<%= resulttext %>
' +
' <% } %>' +
'
' +
' ' +
' ' +
' ' +
'
' +
'
';
var defaults = {
randomOrder: false,
initialQuestion: 0,
progressType: 'dots',
passPercentage: 50,
questions: [],
introPage: {
showIntroPage: false,
title: '',
introduction: '',
startButtonText: 'Start'
},
texts: {
prevButton: 'Previous question',
nextButton: 'Next question',
finishButton: 'Finish',
textualProgress: 'Question: @current of @total questions',
jumpToQuestion: 'Jump to question %d',
questionLabel: 'Question'
},
endGame: {
showResultPage: true,
noResultMessage: 'Finished',
message: 'Your result:',
successGreeting: 'Congratulations!',
successComment: 'You have enough correct answers to pass the test.',
failGreeting: 'Sorry!',
failComment: "You don't have enough correct answers to pass this test.",
scoreString: 'You got @score of @total points',
finishButtonText: 'Finish',
solutionButtonText: 'Show solution',
retryButtonText: 'Retry',
showAnimations: false,
skipButtonText: 'Skip video'
}
};
var template = new EJS({text: texttemplate});
var endTemplate = new EJS({text: resulttemplate});
var params = $.extend(true, {}, defaults, options);
var currentQuestion = 0;
var questionInstances = [];
var $myDom;
var scoreBar;
var up;
renderSolutions = false;
var $template = $(template.render(params));
// Set overrides for questions
var override;
if (params.override.showSolutionButton || params.override.retryButton) {
override = {};
if (params.override.showSolutionButton) {
// Force "Show solution" button to be on or off for all interactions
override.enableSolutionsButton =
(params.override.showSolutionButton === 'on' ? true : false);
}
if (params.override.retryButton) {
// Force "Retry" button to be on or off for all interactions
override.enableRetry =
(params.override.retryButton === 'on' ? true : false);
}
}
// Instantiate question instances
for (var i = 0; i < params.questions.length; i++) {
var question = params.questions[i];
if (override) {
// Extend subcontent with the overrided settings.
$.extend(question.params.behaviour, override);
}
question.params = question.params || {};
question.params.overrideSettings = question.params.overrideSettings || {};
question.params.overrideSettings.$confirmationDialogParent = $template.last();
question.params.overrideSettings.instance = this;
var questionInstance = H5P.newRunnable(question, contentId, undefined, undefined, {parent: self});
questionInstance.on('resize', function () {
up = true;
self.trigger('resize');
});
questionInstances.push(questionInstance);
}
// Resize all interactions on resize
self.on('resize', function () {
if (up) {
// Prevent resizing the question again.
up = false;
return;
}
for (var i = 0; i < questionInstances.length; i++) {
questionInstances[i].trigger('resize');
}
});
// Update button state.
var _updateButtons = function () {
var answered = true;
for (var i = questionInstances.length - 1; i >= 0; i--) {
answered = answered && (questionInstances[i]).getAnswerGiven();
}
if (currentQuestion === (params.questions.length - 1) && answered &&
questionInstances[currentQuestion]) {
questionInstances[currentQuestion].showButton('finish');
}
};
var _stopQuestion = function (questionNumber) {
if (questionInstances[questionNumber]) {
pauseMedia(questionInstances[questionNumber]);
}
};
var _showQuestion = function (questionNumber) {
// Sanitize input.
if (questionNumber < 0) {
questionNumber = 0;
}
if (questionNumber >= params.questions.length) {
questionNumber = params.questions.length - 1;
}
currentQuestion = 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 (params.progressType === 'textual') {
$('.progress-text', $myDom).text(params.texts.textualProgress.replace("@current", questionNumber+1).replace("@total", params.questions.length));
}
else {
// Set currentNess
$('.progress-dot.current', $myDom).removeClass('current');
$('.progress-dot:eq(' + questionNumber +')', $myDom).addClass('current');
}
// Remember where we are
_updateButtons();
self.trigger('resize');
return currentQuestion;
};
/**
* Show solutions for subcontent, and hide subcontent buttons.
* Used for contracts with integrated content.
* @public
*/
var showSolutions = function () {
for (var i = 0; i < questionInstances.length; i++) {
try {
questionInstances[i].showSolutions();
}
catch(error) {
H5P.error("subcontent does not contain a valid showSolutions function");
H5P.error(error);
}
}
};
/**
* Resets the task and every subcontent task.
* Used for contracts with integrated content.
* @public
*/
var resetTask = function () {
for (var i = 0; i < questionInstances.length; i++) {
try {
questionInstances[i].resetTask();
}
catch(error) {
H5P.error("subcontent does not contain a valid resetTask function");
H5P.error(error);
}
}
// Hide finish button
questionInstances[questionInstances.length - 1].hideButton('finish');
// Mark all tasks as unanswered:
$('.progress-dot').removeClass('answered').addClass('unanswered');
//Force the last page to be reRendered
rendered = false;
};
var rendered = false;
this.reRender = function () {
rendered = false;
};
var moveQuestion = function (direction) {
_stopQuestion(currentQuestion);
if (currentQuestion + direction >= questionInstances.length) {
_displayEndGame();
}
else {
_showQuestion(currentQuestion + direction);
}
};
var _displayEndGame = function () {
if (rendered) {
$myDom.children().hide().filter('.questionset-results').show();
self.trigger('resize');
return;
}
//Remove old score screen.
$myDom.children().hide().filter('.questionset-results').remove();
rendered = true;
// Get total score.
var finals = self.getScore();
var totals = self.totalScore();
var scoreString = params.endGame.scoreString.replace("@score", finals).replace("@total", totals);
var success = ((100 * finals / totals) >= params.passPercentage);
var eventData = {
score: scoreString,
passed: success
};
/**
* Makes our buttons behave like other buttons.
*
* @private
* @param {string} classSelector
* @param {function} handler
*/
var hookUpButton = function (classSelector, handler) {
$(classSelector, $myDom).click(handler).keypress(function (e) {
if (e.which === 32) {
handler();
e.preventDefault();
}
});
};
var displayResults = function () {
self.triggerXAPICompleted(self.getScore(), self.totalScore(), success);
var eparams = {
message: params.endGame.showResultPage ? params.endGame.message : params.endGame.noResultMessage,
comment: params.endGame.showResultPage ? (success ? params.endGame.successGreeting : params.endGame.failGreeting) : undefined,
resulttext: params.endGame.showResultPage ? (success ? params.endGame.successComment : params.endGame.failComment) : undefined,
finishButtonText: params.endGame.finishButtonText,
solutionButtonText: params.endGame.solutionButtonText,
retryButtonText: params.endGame.retryButtonText
};
// Show result page.
$myDom.children().hide();
$myDom.append(endTemplate.render(eparams));
if (params.endGame.showResultPage) {
// Add event handlers to summary buttons
hookUpButton('.qs-finishbutton', function () {
self.trigger('h5pQuestionSetFinished', eventData);
});
hookUpButton('.qs-solutionbutton', function () {
showSolutions();
$myDom.children().hide().filter('.questionset').show();
_showQuestion(params.initialQuestion);
});
hookUpButton('.qs-retrybutton', function () {
resetTask();
$myDom.children().hide();
var $intro = $('.intro-page', $myDom);
if ($intro.length) {
// Show intro
$('.intro-page', $myDom).show();
}
else {
// Show first question
$('.questionset', $myDom).show();
_showQuestion(params.initialQuestion);
}
});
if (scoreBar === undefined) {
scoreBar = H5P.JoubelUI.createScoreBar(totals);
}
scoreBar.appendTo($('.feedback-scorebar', $myDom));
scoreBar.setScore(finals);
$('.feedback-text', $myDom).html(scoreString);
}
else {
// Remove buttons and feedback section
$('.qs-finishbutton, .qs-solutionbutton, .qs-retrybutton, .feedback-section', $myDom).remove();
}
self.trigger('resize');
};
if (params.endGame.showAnimations) {
var videoData = success ? params.endGame.successVideo : params.endGame.failVideo;
if (videoData) {
$myDom.children().hide();
var $videoContainer = $('