Szerkesztő:Palotasb/common.js
A VIK Wikiből
Megjegyzés: közzététel után frissítened kell a böngésződ gyorsítótárát, hogy lásd a változásokat.
- Firefox / Safari: tartsd lenyomva a Shift gombot és kattints a Frissítés gombra a címsorban, vagy használd a Ctrl–F5 vagy Ctrl–R (Macen ⌘–R) billentyűkombinációt
- Google Chrome: használd a Ctrl–Shift–R (Macen ⌘–Shift–R) billentyűkombinációt
- Internet Explorer / Edge: tartsd nyomva a Ctrl-t, és kattints a Frissítés gombra, vagy nyomj Ctrl–F5-öt
- Opera: Nyomj Ctrl–F5-öt
/* Quiz.js for vikwikiQuiz project
Copyright (C) 2013 Palotás Boldizsár
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
(MIT License)
*/
(function (mw, $) {
var questions = [],
shownQuestionIds = [],
uiContentElement,
uiControlElements = {},
config = new ConfObject(true, true),
stats = new StatObject(),
defaultScoringMethod = +1,
currentCodeID = "2013.02.06 v1";
if (init())
return true;
else
return false;
function init() {
if (!shouldLoadQuiz()) {
return false;
}
getDefaultScoringMethod();
parseQuestionsInDocument();
parseAnswerGroupsInQuestions();
uiCreateQuizInterface();
uiPopulateQuizInterace();
uiReset();
return true;
}
function getDefaultScoringMethod() {
var defScorMethText = $('#vw-quiz-defaultscoringmethod').text();
if ($.trim(defScorMethText) === "-")
defaultScoringMethod = -1;
if ($.trim(defScorMethText) === "+")
defaultScoringMethod = +1;
}
function shouldLoadQuiz() {
if ($('#vw-quiz-canvas').length !== 1)
return false;
if (wgAction !== 'view' && wgAction !== 'submit')
return false;
if ($.cookie('vw-config-loadcodeid') && $.cookie('vw-config-loadcodeid') != currentCodeID)
return false;
return true;
}
function uiUpdateStats() {
uiControlElements.uiStatAverageText.text(
stats.totalAnswers != 0 ? Math.round(stats.getRunningAverage() * 100).toString() + '%' : '' );
uiControlElements.uiStatAllQuestionsText.text( stats.totalAnswers.toString() );
uiControlElements.uiStatGoodAnswersText.text( (Math.round(stats.totalPercentage * 100) / 100).toString() );
}
function parseQuestionsInDocument() {
var CQ_UNINITIATED = -1;
var CQ_EXIT = -2;
var uiContentElements = $('#mw-content-text > *');
var questionId = CQ_UNINITIATED;
for (var i = 0; i != uiContentElements.length && questionId != CQ_EXIT; i++) {
if (uiContentElements[i].nodeName === 'H2') {
// H2 -> start of quizquestions
questionId++ ;
questions.push(new QuestionObject(questionId));
questions[questionId].uiElements.push( $(uiContentElements[i]).detach()[0] );
} else if (uiContentElements[i].nodeName === 'HR') {
questionId = CQ_EXIT;
} else if (questionId > CQ_UNINITIATED) {
questions[questionId].uiElements.push( $(uiContentElements[i]).detach()[0] );
}
}
}
function parseAnswerGroupsInQuestions() {
for (var i = 0; i != questions.length; i++) {
questions[i].parseAnswerGroups(defaultScoringMethod, checkAnswer);
}
}
function uiCreateQuizInterface() {
uiContentElement = $('#vw-quiz-content');
$('#toc').remove();
var uiInfoboxElement = $('#vw-quiz-infobox');
uiInfoboxElement.css( {
position: 'fixed',
right: $('#content').css('padding-right')
} );
$('#vw-quiz-infobox .infobox').css('max-width', '100%');
$('#mw-content-text').css('margin-right', uiInfoboxElement.width().toString() + 'px');
$('#mw-content-text').css('min-height', uiInfoboxElement.height().toString() + 'px');
var setInfoboxPosition = function() {
var relTop = $('#vw-quiz-content').offset().top - $(window).scrollTop();
$('#vw-quiz-infobox .infobox').offset({
top: (relTop < 10 ? 10 + $(window).scrollTop() : $('#vw-quiz-content').offset().top)
});
};
$(window).scroll(setInfoboxPosition);
setInfoboxPosition();
}
function uiPopulateQuizInterace() {
var uiStatAverageText = $('#vw-quiz-stat-average');
var uiStatAllQuestionsText = $('#vw-quiz-stat-allquestions');
var uiStatGoodAnswersText = $('#vw-quiz-stat-goodanswers');
var resetButton = $('<input type="button" />').val('Újrakezdés');
resetButton.appendTo( $('#vw-quiz-stat-reset').text('') );
resetButton.click(uiReset);
var checkAllButton = $('<input type="button" />').val('Minden válasz ellenőrzése');
checkAllButton.appendTo( $('#vw-quiz-check-all').text('') );
checkAllButton.click(uiCheckAll);
var showAllCheckbox = $('<input type="checkbox" />').prop(
'checked', config.showAll
).prop(
'id', 'vw-quiz-show-all-checkbox'
);
showAllCheckbox.appendTo( $('#vw-quiz-conf-showall').text('') );
var randomCheckbox = $('<input type="checkbox" />').prop(
'checked', config.randomOrder
).prop(
'id', 'vw-quiz-random-checkbox'
);
randomCheckbox.appendTo( $('#vw-quiz-conf-ordering').text('') );
uiControlElements = {
uiStatAverageText: uiStatAverageText,
uiStatAllQuestionsText: uiStatAllQuestionsText,
uiStatGoodAnswersText: uiStatGoodAnswersText,
resetButton: resetButton,
checkAllButton: checkAllButton,
randomCheckbox: randomCheckbox,
showAllCheckbox: showAllCheckbox
};
}
function randomizeDisplayOrder() {
var ArrayShuffle = function(a) {
var d,
c,
b = a.length;
while (b) {
c = Math.floor(Math.random() * b);
d = a[--b];
a[b] = a[c];
a[c] = d;
}
return a;
};
shownQuestionIds = ArrayShuffle(shownQuestionIds);
}
function uiCheckAll() {
if (config.showAll) {
$(':button.vw-quiz-check-btn').click();
} else {
uiControlElements.showAllCheckbox.prop('checked', true);
uiReset();
}
}
function configSet() {
config.setRandomOrder(uiControlElements.randomCheckbox.prop('checked'));
config.setShowAll(uiControlElements.showAllCheckbox.prop('checked'))
}
function uiReset() {
configSet();
reset();
uiShowQuestions();
uiUpdateStats();
}
function reset() {
shownQuestionIds = [];
for (var i = 0; i != questions.length; i++) {
questions[i].submitted = false;
shownQuestionIds.push(i);
}
if (config.randomOrder) {
randomizeDisplayOrder();
}
if (!config.showAll) {
uiControlElements.checkAllButton.val('Minden kérdés mutatása');
} else {
uiControlElements.checkAllButton.val('Minden válasz ellenőrzése');
}
stats.reset();
}
function uiShowQuestions() {
uiContentElement.children().detach();
for (var i = 0; i != shownQuestionIds.length; i++) {
questions[ shownQuestionIds[i] ].uiResetAnswers();
questions[ shownQuestionIds[i] ].uiParentElement.appendTo(uiContentElement);
if (!config.showAll && i != 0) {
questions[ shownQuestionIds[i] ].uiParentElement.css('display', 'none');
} else {
// config.showAll || i == 0
questions[ shownQuestionIds[i] ].uiParentElement.css('display', 'block');
}
}
}
function checkAnswer(question) {
if (question.submitted) {
return false;
}
question.submitted = true;
var result = question.checkAnswer();
stats.totalAnswers += result.totalAnswers;
stats.totalPercentage += result.totalPercentage;
uiUpdateStats();
if (!config.showAll) {
uiHidePreviousQuestion(question);
uiShowNextQuestion(question);
}
}
function uiHidePreviousQuestion(question) {
var prevQuestion = getPreviousQuestion(question);
if (prevQuestion == null)
return false;
if (prevQuestion.uiParentElement.css('display') == 'none')
return true;
prevQuestion.uiParentElement.slideUp();
return true;
}
function uiShowNextQuestion(question) {
var nextQuestion = getNextQuestion(question);
if (nextQuestion == null) {
var uiEndOfQuizMessage = $('<p></p>').text('A kvíz véget ért.');
uiEndOfQuizMessage.css({
'padding': '1em',
'border': '1px solid #aaa',
'margin': '1em 0',
'text-align': 'center',
'font-size': '1.1em',
'display': 'none'
});
uiContentElement.append(uiEndOfQuizMessage);
uiEndOfQuizMessage.slideDown();
return false;
}
if (nextQuestion.uiParentElement.css('display') == 'block')
return true;
nextQuestion.uiParentElement.slideDown();
return true;
}
function getPreviousQuestion(question) {
for (var i = 0; i != shownQuestionIds.length; i++) {
if (question.id == shownQuestionIds[i] && i > 0) {
return questions[ shownQuestionIds[i - 1] ];
}
}
return null;
}
function getNextQuestion(question) {
for (var i = 0; i != shownQuestionIds.length; i++) {
if (question.id == shownQuestionIds[i] && i < shownQuestionIds.length - 1) {
return questions[ shownQuestionIds[i + 1] ];
}
}
return null;
}
/* ------------------------------------------------------- */
function QuestionObject(id) {
this.id = id;
this.uiElements = [];
this.uiParentElement = null;
this.answers = [];
this.submitted = false;
this.parseAnswerGroups = function(defaultScoringMethod, answerCheckingFunction) {
for (var j = 1; j < this.uiElements.length; j++) {
var currentElement = this.uiElements[j];
var previousElement = this.uiElements[j - 1];
if (currentElement.nodeName === "OL"
&& $('.vw-quiz-meta', previousElement).length !== 0
) {
this.answers.push(new AnswerGroupObject(
$('.vw-quiz-type', previousElement).text(),
$('.vw-quiz-answer', previousElement).text(),
$('.vw-quiz-scoringmethod', previousElement).text(),
$(currentElement).children().length,
currentElement,
this.id,
this.answers.length,
defaultScoringMethod
));
$(previousElement).css('display', 'none');
}
}
this.uiAddAnswerButton(answerCheckingFunction);
this.uiAddParentElement();
};
this.uiAddParentElement = function() {
this.uiParentElement = $('<div></div>').addClass('vw-quiz-container').append(this.uiElements);
this.uiParentElement.css({
'padding': '.3em 1em 1em 1em',
'border': '1px solid #aaa',
'margin': '1em 0'
});
};
this.uiAddAnswerButton = function(answerCheckingFunction) {
var button = $('<input type="button" />').val('Ellenőrzés').addClass("vw-quiz-check-btn");
button.css({
'display': 'block',
'margin-top': '1em',
'font-size': '1.1em'
});
var self = this;
button.click(function(eventObject) {
answerCheckingFunction(self);
});
this.uiElements.push(button[0]);
};
this.uiResetAnswers = function () {
var answerElements = $('.vw-quiz-question > li', this.uiParentElement);
answerElements.css({
'margin': '.1em',
'cursor': 'pointer',
'background-color': 'transparent',
'opacity': '1',
'border': '1px solid transparent'
});
$(':radio, :checkbox', this.uiParentElement).prop('checked', false);
$(':button, :checkbox, :radio', this.uiParentElement).css('cursor', 'pointer').prop('disabled', false);
};
this.checkAnswer = function() {
var result = {
totalAnswers: 0,
totalPercentage: 0
};
for (var i = 0; i != this.answers.length; i++) {
$('input', this.uiParentElement).prop('disabled', true);
$('input, .vw-quiz-question > li', this.uiParentElement).css('cursor', 'default')
var points = 0;
var ans = this.answers[i];
if (ans.type === 1) {
result.totalAnswers++;
$('li:not(:nth-of-type(' + (ans.answer + 1).toString() + '))', ans.uiElement).not("li li").css({
'opacity': '0.5'
});
var userSelectedAnswer = $(':radio:checked', ans.uiElement).data('answer-id');
if (!isNaN(userSelectedAnswer) && userSelectedAnswer !== ans.answer) {
// Hibás választ adott
result.totalPercentage += (ans.scoringMethod === -1 ? -1 : 0);
// Helyes választ sárgával jelöljük
$('li:nth-of-type(' + (ans.answer + 1).toString() + ')', ans.uiElement).not("li li").css({
'background-color': '#fff8d0',
'border-color': '#aa2'
});
// Megjelölt választ pirossal jelöljük
$('li:nth-of-type(' + (userSelectedAnswer + 1).toString() + ')', ans.uiElement).not("li li").css({
'background-color': '#ffe0e0',
'border-color': '#a00'
});
} else if (!isNaN(userSelectedAnswer)) {
// Jót jelölt, zölddel jelöljük
result.totalPercentage += 1;
$('li:nth-of-type(' + (userSelectedAnswer + 1).toString() + ')', ans.uiElement).not("li li").css({
'background-color': '#d8f8d0',
'border-color': '#0a0',
'opacity': '1'
});
} else {
// Nem jelölt semmit
// Helyes választ sárgával jelöljük
$('li:nth-of-type(' + (ans.answer + 1).toString() + ')', ans.uiElement).not("li li").css({
'background-color': '#fff8d0',
'border-color': '#aa2'
});
}
} else if (ans.type === 2) {
result.totalAnswers++;
var uiAnswerElements = $('li', ans.uiElement).not('li li');
var partialPoints = 0;
for (var j = 0; j != uiAnswerElements.length; j++) {
var currentAnswerElement = $(uiAnswerElements[j]);
var checkbox = $(':checkbox', currentAnswerElement);
if (ans.answer.indexOf(j) !== -1) {
// Be kéne legyen jelölve
if (checkbox.prop('checked')) {
// Be is van
currentAnswerElement.css({
'border-color': '#0a0',
'background-color': '#d8f8d0'
});
partialPoints++;
} else {
// Nincs
currentAnswerElement.css({
'border-color': '#aa2',
'background-color': '#fff8d0'
});
if (ans.scoringMethod === -1)
partialPoints--;
}
} else {
// Nem kéne bejelölve legyen
if (checkbox.prop('checked')) {
// De mégis be van
currentAnswerElement.css({
'border-color': '#a00',
'background-color': '#ffe0e0',
'opacity': '0.5'
});
if (ans.scoringMethod === -1)
partialPoints--;
} else {
// És nincs is
currentAnswerElement.css({
'opacity': '0.5'
});
partialPoints++;
}
}
}
result.totalPercentage += (partialPoints / ans.numberOfOptions);
}
}
return result;
}
}
/* ------------------------------------------------------- */
function AnswerGroupObject(typeText, correctAnswerText, scoringMethodText, numberOfOptions, uiElement, questionId, answerId, defaultScoringMethod) {
this.type = 1; // A default az egyválaszos (radio)
if ($.trim(typeText) === "egy")
this.type = 1;
if ($.trim(typeText) === "több")
this.type = 2;
this.answer = null;
this.scoringMethod = defaultScoringMethod;
if ($.trim(scoringMethodText) === "-")
this.scoringMethod = -1;
if ($.trim(scoringMethodText) === "+")
this.scoringMethod = +1;
this.numberOfOptions = numberOfOptions;
this.uiElement = $(uiElement);
this.questionId = questionId;
this.answerId = answerId;
init.call(this);
addAnswerControls.call(this);
function init() {
if (this.type === 1) {
this.answer = parseInt(correctAnswerText) - 1;
} else if (this.type === 2) {
this.answer = [];
var answer_list = correctAnswerText.split(",");
for (var ans_i = 0; ans_i != answer_list.length; ans_i++) {
this.answer.push(parseInt(answer_list[ans_i]) - 1);
}
}
this.uiElement.css({
'border': '1px solid #aaa',
'list-style-type': 'none',
'list-style-image': 'none',
'padding': '.25em',
'margin': '.5em 0 0 0'
});
}
function addAnswerControls() {
this.uiElement.addClass('vw-quiz-question');
var answerOptionElements = $('li', this.uiElement).not('li li');
if (this.type === 1) {
for (var i = 0; i != answerOptionElements.length; i++) {
var idString = 'vw-qa-' + this.questionId.toString() + '-' + this.answerId.toString();
var uiRadiobutton = $('<input type="radio" />')
.prop('id', idString + '-' + i.toString())
.prop('name', idString)
.data('answer-id', i);
$(answerOptionElements[i]).prepend(uiRadiobutton).click(uiRadiobutton, function(eventObject) {
if (eventObject.target.nodeName == "INPUT") {
return true;
}
eventObject.data.click();
});
}
} else if (this.type === 2) {
for (var i = 0; i !== answerOptionElements.length; i++) {
var idString = 'vw-qa-' + this.questionId.toString() + '-' + this.answerId.toString() + '-' + i.toString();
var uiCheckbox = $('<input type="checkbox" />')
.prop('id', idString)
.prop('name', idString)
.data('answer-id', i);
$(answerOptionElements[i]).prepend(uiCheckbox).click(uiCheckbox, function(eventObject) {
if (eventObject.target.nodeName == "INPUT") {
return true;
}
eventObject.data.click();
});
}
}
}
}
/* ------------------------------------------------------- */
function StatObject() {
this.totalAnswers = 0;
this.totalPercentage = 0;
this.getRunningAverage = function() { return this.totalPercentage / this.totalAnswers; };
this.reset = function() { this.totalAnswers = 0; this.totalPercentage = 0; };
}
/* ------------------------------------------------------- */
function ConfObject(showAllDefault, randomOrderDefault) {
this.showAll = showAllDefault;
if ($.cookie('vw-config-showall') == 'showall') {
this.showAll = true;
}
if ($.cookie('vw-config-showall') == 'showone') {
this.showAll = false;
}
this.randomOrder = randomOrderDefault;
if ($.cookie('vw-config-ordering') == 'random') {
this.randomOrder = true;
}
if ($.cookie('vw-config-ordering') == 'inorder') {
this.randomOrder = false;
}
this.setRandomOrder = function(value) {
this.randomOrder = value;
$.cookie('vw-config-ordering', value ? 'random' : 'inorder');
};
this.setShowAll = function(value) {
this.showAll = value;
$.cookie('vw-config-showall', value ? 'showall' : 'showone');
};
}
})( mediaWiki, jQuery );
/*
-----------------------------------------------
--------------- END OF Quiz.js ----------------
-----------------------------------------------
*/