/* 
 *      Functions for quiz creation and maintenance
 *
 */

/* global quizConfig, courseStatus */

var currentQuiz;
var currentQuizMode;
var ID;
var currentQuizNextDelay = true;
var currentQuizTryAgain = false;

//Check if quiz common variables exist
function quizMakeVariables() {
    if ( currentQuizTryAgain === false ) {
        currentQuizMode = 0;
    }
    
    if ( courseStatus.quiz_bank === undefined ) {
	courseStatus.quiz_bank = new Array;
    }
    if ( courseStatus.quiz_questions === undefined ) {
	courseStatus.quiz_questions = new Array;
    }
    if ( courseStatus.quiz_answers === undefined ) {
	courseStatus.quiz_answers = new Array;
    }
    if ( courseStatus.quiz_attempts === undefined ) {
	courseStatus.quiz_attempts = new Array;
    }
    if ( courseStatus.quiz_best_grade === undefined ) {
	courseStatus.quiz_best_grade = new Array;
    }
    if ( courseStatus.quiz_last_grade === undefined ) {
	courseStatus.quiz_last_grade = new Array;
    }
    if ( courseStatus.quiz_finished === undefined ) {
	courseStatus.quiz_finished = new Array;
    }
}

//Create quiz question bank
function quizBankCreate( ID ) {
    if ( ID === undefined ) {
	ID = currentQuiz;
    }
    
    zork( 'Creating quiz bank...');
    if ( courseStatus.quiz_bank[ID] === undefined ) {
    	courseStatus.quiz_bank[ID] = new Array;
	zork( 'It didn\'t exist...');
    } else {
	courseStatus.quiz_bank.length = [];
	courseStatus.quiz_bank[ID] = new Array;
	zork( 'It did exist and now I\'m resetting it...');
    }

    
    if ( courseStatus.quiz_questions[ID] === undefined ) {	
	courseStatus.quiz_questions[ID] = new Array;
    } else {
	courseStatus.quiz_questions[ID].length = [0];
	courseStatus.quiz_questions[ID] = new Array;
    }
    
    var pools = quizConfig[ ID ].quiz_banks.length;
    
    //For each question bank pool
    zork( 'Creating question bank from ' + pools + ' question pools...');
    for ( i = 0; i < pools; i++ ) {
	zork('Loop ' + i + '!' );
	var size = quizConfig[ ID ].bank_questions[i];
	
	var poolSize = 0;
	
	for ( s = 0; s < 1000; s++ ) {
	    if ( quizQuestions[ quizConfig[ ID ].quiz_banks[i] ][s] !== undefined ) {
		poolSize += 1;
	    } else {
		break;
	    }
	}
	
	zork( 'We are going to take ' + size + ' questions from pool ' + i + ',a pool of ' + poolSize + ' questions...');

	var questions = new Array;
	
	var answers = new Array;
	
	for ( q = 0; q < poolSize ; q++ ){
	    questions.push( q );
	    answers.push( 0 );
	}
	if ( quizConfig[ ID ].shuffle === true ) {
	    questions = shuffle(questions);
	    zork( 'Shuffled questions to ' + questions + '!');
	} else if ( quizConfig[ ID ].shuffle === 'pool' ) {
            
            
        }
	zork( 'We have these ' + questions + ' questions and these  ' + answers + ' answers...');
	questions = questions.slice(0, size);
	answers = answers.slice(0, size);
	
	zork( 'We truncated the questions to ' + questions + '  and the answers to ' + answers + '...');
	
	//For each questions in poll
	for ( f = 0; f < size ; f++ ) {				
	    var poll = quizConfig[ID].quiz_banks[i];
 
	    //Set poll
	    courseStatus.quiz_bank[ID].push( poll );
	    courseStatus.quiz_questions[ID].push( questions.pop() );
	    zork( 'i = ' + i + ' and f = ' + f );
	    if ( quizQuestions[ courseStatus.quiz_bank[ID][f] ][ courseStatus.quiz_questions[ID][f] ].type === 'single' ) {
		//courseStatus.quiz_answers[ID].push( -1 );
		courseStatus.quiz_answers[ID].push( 'x' );
		zork('Single choice!');
	    } else if ( quizQuestions[ courseStatus.quiz_bank[ID][f] ][ courseStatus.quiz_questions[ID][f] ].type === 'multiple' ) { 
		courseStatus.quiz_answers[ID].push( 'x' );
		zork('Multiple choice!');
	    }
	}
	
	zork('Quiz banks for quiz ' + ID + ': ' + courseStatus.quiz_bank[ ID ] );
	zork('Quiz questions for quiz ' + ID + ': ' + courseStatus.quiz_questions[ ID ] );
	
    }
}

//Config all quiz variables
function quizCreate( ID ) {
    if ( ID === undefined ) {
	ID = currentQuiz;
    }
    
    quizMakeVariables();

    if ( courseStatus.quiz_attempts[ ID ] === undefined ) {

	courseStatus.quiz_attempts[ ID ] = quizConfig[ ID ].attempts;
	
	//Quiz mode, 0 = normal, 1 = retry, 2 = review
        if ( currentQuizTryAgain === false ) {
            currentQuizMode = 0;
        }

	courseStatus.quiz_best_grade[ ID ] = 0;

	courseStatus.quiz_last_grade[ ID ] = 0;
	
	courseStatus.quiz_finished[ ID ] = 0;
    
    }
    
    if ( quizConfig[ ID ].shuffle === true || quizConfig[ ID ].shuffle === 'pool' ) {
	courseStatus.quiz_answers[ ID ] = new Array;
	quizBankCreate( ID );
    }
}

//Build the quiz
function quizBuildHtml( ID ) {
    if ( ID === undefined ) {
	ID = currentQuiz;
    }
    $('.slide-current').empty();
    
    currentQuiz = ID;
    
    zork('Building Quiz ' + ID + '!');
    
    reshuffleQuizMBCP();
    
    quizCreate( ID );
    
    var size = 0;

    var pools = quizConfig[ ID ].quiz_banks.length;
    
    //Count number of questions
    for ( i = 0; i < pools; i++ ) { 
	size += quizConfig[ ID ].bank_questions[i];
    }
    
    zork('This quiz has ' + size + ' questions!');
    
    //Create start screen
    $('#slide-'+ courseStatus.position).append(	
				'<div id="layer-0" class="layer layer-first layer-quiz quiz-start">' +
                                    '<div id="message-start-terminated" class="quiz-message-start" tabindex="0">' +
                                        quizConfig[ ID ].message_start_terminated +
				    '</div>' +
                                    
				    '<div id="message-start-first" class="quiz-message-start" tabindex="0">' +
					quizConfig[ ID ].message_start_first +
				    '</div>' +

				    '<div id="message-start-pass" class="quiz-message-start" tabindex="0">' +
					quizConfig[ ID ].message_start_pass +
				    '</div>' +

				    '<div id="message-start-fail" class="quiz-message-start" tabindex="0">' +
					quizConfig[ ID ].message_start_fail +
				    '</div>' +

				    '<div id="message-start-pass-no-attempts" class="quiz-message-start" tabindex="0">' +
					quizConfig[ ID ].message_start_pass_no_attempts +
				    '</div>' +

				    '<div id="message-start-fail-no-attempts" class="quiz-message-start" tabindex="0">' +
					quizConfig[ ID ].message_start_fail_no_attempts +
				    '</div>' +
				    
				    '<div id="message-start-generic" class="quiz-message-start" tabindex="0">' +
					quizConfig[ ID ].message_start_generic +
				    '</div>' +
				    
				    '<p id="quiz-start-grade">' +
					quizConfig[ ID ].label_grade +
					'<span class="quiz-grade"></span>%'+
				    '</p>' +
				    
				    '<p id="quiz-start-best-grade">' +
					quizConfig[ ID ].label_best_grade +
					'<span class="quiz-best-grade"></span>%'+
				    '</p>' +
				    
				    '<p id="quiz-start-attempts">' +
					quizConfig[ ID ].label_attempts +
					'<span class="quiz-attempts"></span>'+
				    '</p>' +
                                    
                                    
                                    '<a href="#" id="quiz-start" class=" quiz-button button-click" onclick="quizControlsStart( ' + ID + ' ); return false;">' +
                                        quizConfig[ ID ].button_start +
                                    '</a>' +
				'</div>'
				);
    //Create each question
    for ( q = 0; q < size; q++ ) { 
	var n = q + 1;
	
	var content = '';
	
	content +=  '<h2 id="question-' + n + '" class="quiz-question-text" tabindex="' + n + '">' +	//Add question
			quizQuestions[courseStatus.quiz_bank[ ID ][q]][courseStatus.quiz_questions[ ID ][q]].question +
		    '</h2>';
	
	if ( quizQuestions[courseStatus.quiz_bank[ ID ][q]][courseStatus.quiz_questions[ ID ][q]].instruction !== false ) {
	    content +=  '<p id="instruction-' + n + '" class="quiz-question-instruction" tabindex="0">' +	//Add instruction
			quizQuestions[courseStatus.quiz_bank[ ID ][q]][courseStatus.quiz_questions[ ID ][q]].instruction +
		    '</p>';
	}
	    
	//Add answers
	content += '<div class="quiz-answer-area">';
	var answers = quizQuestions[courseStatus.quiz_bank[ ID ][q]][courseStatus.quiz_questions[ ID ][q]].answers.length;
	
	for ( a = 0; a < answers; a++ ) {
	    var aAnswer = a + 1;
            var aOrder = '';
            if ( quizConfig[ ID ].shuffle_answers === true ) {
                aOrder = 'order-' + randomNumber(20);
            }
            
	    content +=	'<a href="#" id="quiz-answer-' + n + '-' + aAnswer + '" class="quiz-answer quiz-answer-' + n + ' button-click ' + aOrder + '" onclick="quizAnswer( ' + ID + ', ' + q + ', ' + aAnswer + '); return false;">' +
			    quizQuestions[courseStatus.quiz_bank[ ID ][q]][courseStatus.quiz_questions[ ID ][q]].answers[a] +
			'</a>';
	}
	content += '</div>';
	
	if ( quizConfig[ ID ].help === true ) {
	    content +=	'<div id="help-' + q + '" class="quiz-help">' +
			    'Dica: '+
			    quizQuestions[courseStatus.quiz_bank[ ID ][q]][courseStatus.quiz_questions[ ID ][q]].help +
			'</div>';
	} else if ( quizConfig[ ID ].help === 'review' ) {
	    content +=	'<div id="help-' + q + '" class="quiz-help-review">' +
			    
			    quizQuestions[courseStatus.quiz_bank[ ID ][q]][courseStatus.quiz_questions[ ID ][q]].help +
			'</div>';
	}
	
	$('#slide-'+ courseStatus.position).append( 
	    '<div id="layer-' + n + '" class="layer layer-quiz quiz-question quiz-question-' + ID + '-' + q + '" ' +
		'data-quiz-id="' +  ID  + '" ' +
		'data-quiz-bank="' + courseStatus.quiz_bank[ ID ][q] + '" ' +
		'data-quiz-questions="' + courseStatus.quiz_questions[ ID ][q] + '"' +
		' style="display: none;"><div class="quiz-question-area">' +

	    content +
//BLAH
            
            
	    '</div>' +
                    
            '<a href="#" id="" class="quiz-feedback-button quiz-button button-click" onclick="quizControlsFeedback( ' + ID + ' ); return false;" style="display: none;">' +
		quizConfig[ ID ].button_feedback +
	    '</a>' +
            
            '<div id="" class="quiz-feedback-window quiz-feedback">' +
                '<p id="" class="quiz-feedback-message" tabindex="0" ></p>'+
                '<a href="#" id="" class="quiz-feedback-next quiz-button button-click" onclick="quizControlsFeedbackContinue( ' + ID + ' ); return false;" >' +
                    quizConfig[ ID ].button_feedback_continue +
                '</a>' +
            '</div>' +
            
            '<a href="#" id="" class="quiz-next quiz-button button-click" onclick="quizControlsNext( ' + ID + ' ); return false;" style="display: none;">' +
                quizConfig[ ID ].button_next +
            '</a>' +

            '<a href="#" id="" class="quiz-submit quiz-button button-click" onclick="quizControlsSubmit( ' + ID + ' ); return false;" style="display: none;">' +
                quizConfig[ ID ].button_submit +
            '</a>' +
            
            '</div>'
	);
	
    }
    
    var lastSlide = size + 1;
    
    //Create end screen
    $('#slide-'+ courseStatus.position).append(	
	'<div id="layer-' + lastSlide + '" class="layer layer-last layer-quiz quiz-end"' +
	    'data-quiz-questions="' + courseStatus.quiz_questions[ ID ][q] + '" ' +
	    'style="display: none;">'+
	    
	    '<div id="message-end-pass-generic" class="quiz-message-end" style="display: none" tabindex="0">' +
		quizConfig[ ID ].message_end_pass_generic +
	    '</div>' +
	    
	    '<div id="message-end-fail-generic" class="quiz-message-end" style="display: none" tabindex="0">' +
		quizConfig[ ID ].message_end_fail_generic +
	    '</div>' +
	    
	    '<div id="message-end-pass" class="quiz-message-end" style="display: none" tabindex="0">' +
		quizConfig[ ID ].message_end_pass +
	    '</div>' +

	    '<div id="message-end-fail" class="quiz-message-end" style="display: none" tabindex="0">' +
		quizConfig[ ID ].message_end_fail +
	    '</div>' +

	    '<div id="message-end-pass-no-attempts" class="quiz-message-end" style="display: none" tabindex="0">' +
		quizConfig[ ID ].message_end_pass_no_attempts +
	    '</div>' +

	    '<div id="message-end-fail-no-attempts" class="quiz-message-end" style="display: none" tabindex="0">' +
		quizConfig[ ID ].message_end_fail_no_attempts +
	    '</div>' +

	    '<div id="message-end-best" class="quiz-message-end" style="display: none" tabindex="0">' +
		quizConfig[ ID ].message_end_best +
	    '</div>' +

	    '<div id="message-end-best-no-attempts" class="quiz-message-end" style="display: none" tabindex="0">' +
		quizConfig[ ID ].message_end_best_no_attempts +
	    '</div>' +

            '<div id="message-end-terminated" class="quiz-message-end" style="display: none" tabindex="0">' +
		quizConfig[ ID ].message_end_terminated +
	    '</div>' +

	    '<div id="quiz-end-grade">' +
		quizConfig[ ID ].label_grade +
		'<span class="quiz-grade"></span>%'+
	    '</div>' +

	    '<div id="quiz-end-best-grade">' +
		quizConfig[ ID ].label_best_grade +
		'<span class="quiz-best-grade"></span>%'+
	    '</div>' +

	    '<div id="quiz-end-attempts">' +
		quizConfig[ ID ].label_attempts +
		'<span class="quiz-attempts"></span>'+
	    '</div>' +
	'</div>'
	);
    
    //Create controls
//    if ( quizConfig[ ID ].feedback === true ) {
//	$('#slide-'+ courseStatus.position).append(	
//	    //blah2
//	);
//    }
    $('#slide-'+ courseStatus.position).append(	

	'<a href="#" id="quiz-try-again" class="quiz-button button-click" onclick="quizControlsTryAgain( ' + ID + ' ); return false;" style="display: none;">' +
	    quizConfig[ ID ].button_try_again +
	'</a>'
    );
    
    if ( quizConfig[ ID ].review ) {
	$('#slide-'+ courseStatus.position).append(
	    '<a href="#" id="quiz-review" class=" quiz-button button-click" onclick="quizControlsReview( ' + ID + ' ); return false;" style="display: none;">' +
		quizConfig[ ID ].button_review +
	    '</a>'
	);
    }
    
    if ( quizConfig[ ID ].submit_conditions === 'user' || quizConfig[ ID ].submit_conditions === 'best' ) {
	$('#slide-'+ courseStatus.position).append(
	    '<a href="#" id="quiz-finish" class=" quiz-button button-click" onclick="quizControlsFinish( ' + ID + ' ); return false;" style="display: none;">' +
		quizConfig[ ID ].button_finish +
	    '</a>'
	);
    }
    //Adding feedback screen
//    if ( quizConfig[ ID ].feedback === true ) {
//	var feedback =	'<div id="" class="quiz-feedback-window  quiz-feedback">' +
//			'<p id="" class="quiz-feedback-message"></p>'+
//			'<a href="#" id="" class="quiz-feedback-next quiz-button button-click" onclick="quizControlsFeedbackContinue( ' + ID + ' ); return false;" >' +
//			    quizConfig[ ID ].button_feedback_continue +
//			'</a>' +
//			'</div>';
//	$('#slide-'+ courseStatus.position).append(
//	    feedback
//	);
//    }
    //Create list
    if ( quizConfig[ ID ].list && quizConfig[ ID ].advance !== 'auto' ) {
	var list = '';
	
	list += '<div id="quiz-list" class="quiz-list quiz-list-size-'+size+'" style="display: none">';
	//Add answer numbers
	for ( l = 0; l < size; l++ ) { 
	    var n = l + 1;

	    list += '<a href="#" id="quiz-list-' + n + '" class="quiz-list-item button-click button-locked" onclick="quizControlsListGoTo( ' + ID + ', ' + n + ', this ) "><span class="hidden-text">Ir para pergunta número </span>' + n + '</a>';
	}
	list += '</div>';
	$('#slide-'+ courseStatus.position).append(
		list
	);

    }
    
    
    
    zork( 'Current quiz mode ' + currentQuizMode +'!');
    if ( currentQuizMode === 0 ) {    
	layer( 'first' );
    } else {
	layer( 1 );
    }
    quizUpdateAnswers( ID );
    quizUpdateStartScreen( ID );
    quizUpdateEndScreen( ID );
    quizUpdateScreenInfo( ID );
    quizUpdateQuiz( ID );

}

//Quiz controls buttons

function quizControlsStart( ID ){
    if ( currentQuizNextDelay === true ) {
	currentQuizNextDelay = false;
        quizUpdateList( ID );
	quizUpdateQuiz( ID );
        quizUpdateAnswers( ID );
        up();
    }
    if ( totalQuestions[ID] !== undefined ) {
       var target = document.getElementById('instruction-' + totalQuestions[ID] );
       var targetString = target.innerHTML;
       var targetResult = targetString.replace(quizConfig[ID].button_next, quizConfig[ID].button_submit);
       target.innerHTML = targetResult;
    }
    var str = "Visit Microsoft!";
    var res = str.replace("Microsoft", "W3Schools");
    setTimeout( function() {
	currentQuizNextDelay = true;
    }, 1000);
}
function quizControlsNext( ID ){
    if ( currentQuizNextDelay === true ) {
	currentQuizNextDelay = false;
        
	quizUpdateList( ID );
	up();
        if ( layerBeforeLast() ) {
            $( '#quiz-list' ).fadeOut(500);
        };
        quizUpdateList( ID );
        quizUpdateQuiz( ID );
        quizUpdateAnswers( ID );
        $('#next-button-blink').hide();
        $('#submit-button-blink').hide();
        $('.quiz-feedback-window').fadeOut();
    }
    setTimeout( function() {
	currentQuizNextDelay = true;
    }, 1000);
}
function quizControlsFeedback( ID ) {
    var question = layerCurrent() - 1;
    quizFeedbackAnswer( ID, question );
}
function quizControlsFeedbackContinue( ID ) {
    $( '.quiz-feedback-window' ).fadeOut(500);
    $( '.quiz-feedback-next' ).fadeOut(500); //Blah DuLt CiberSegurança Animate
    if ( layerInTheMiddle() && layerBeforeLast() === false ) {
	$( '.quiz-next' ).fadeIn(500);
    } else if ( layerInTheMiddle() && layerBeforeLast() ) {
	$( '.quiz-submit' ).fadeIn(500); 
    }
}
function quizControlsSubmit( ID ){
    if ( currentQuizNextDelay === true ) {
	currentQuizNextDelay = false;
        $( '#quiz-list' ).fadeOut(500);
        quizUpdateList( ID );
        quizGrade( ID );
        quizUpdateQuiz( ID );
        layer( 'last' );
        currentQuizMode = 0;
        $('#next-button-blink').hide();
        $('#submit-button-blink').hide();
        $('.quiz-feedback-window').fadeOut();
        setTimeout( function() {
            quizUpdateEndScreen( ID );
        }, 500);
    }
    
    setTimeout( function() {
	currentQuizNextDelay = true;
    }, 1000);
}
function quizControlsTryAgain( ID ){
    quizTryAgain( ID );
}
function quizControlsReview( ID ){
    quizReview( ID );
}
function quizControlsFinish( ID ){
    quizFinish( ID );
}
function quizControlsListGoTo( ID, number, caller ) {
    if( !$( caller ).hasClass('button-locked') ){
        
	layer( number );
	quizUpdateList( ID );
	quizUpdateQuiz( ID );
        quizUpdateAnswers( ID );
        $('#next-button-blink').hide();
        $('#submit-button-blink').hide();
        $('.quiz-feedback-window').fadeOut();
    }
}

function quizUpdateList( ID ) {
    var n = layerCurrent() + 1;
    
    $( '#quiz-list-' + layerCurrent() ).removeClass( 'button-locked' );  
    $( '#quiz-list-' + n ).removeClass( 'button-locked' );   
}

// Choose an answer
function quizAnswer( ID, question, answer ) {
    var bankID = courseStatus.quiz_bank[ID][ question ];
    var questionID = courseStatus.quiz_questions[ID][ question ];
    
    if ( quizQuestions[ bankID ][ questionID ].type === 'single' ) {
	//zork('Single choice question!');
    } else if ( quizQuestions[ bankID ][ questionID ].type === 'multiple' ) {
	//zork('Multiple choice question!');
	var answered = '' + courseStatus.quiz_answers[ ID ][ question ];
	var answerString = '' + answer;
	
	if ( answered.length <= 0 || answered === 'x' ) {
	    zork('There wasn\'t an answer before!');
	    answered = '' + answer;
	} else {
	    zork('There was an answer before! It was ' + answered + '!');
	    if ( answered.includes( answerString ) ) {
		zork('You had already choosen ' + answerString + '!');
		answered = answered.replace( answerString, '');
	    } else {
		zork('Adding ' + answerString + ' to ' + answered + '!');
		answered += answerString;
	    }
	    
	    
	    if ( answered <= 0 ) {
		answered = 'x';
	    }
	    
	    answer = answered;
	}
    }
    courseStatus.quiz_answers[ ID ][ question ] = answer;
    zork( 'Answered ' + answer + ' to question ' + question + ' in quiz ' + ID + '.');
    quizUpdateAnswers( ID );
    $('#next-button-blink').show();
    $('#submit-button-blink').show();
}

// Update Answers
function quizUpdateAnswers( ID ) {
    if ( ID === undefined ) {
	ID = currentQuiz;
    }
    
    zork( 'Updating answers!');
    var answers = courseStatus.quiz_answers[ ID ].length;
    $( '.quiz-answer' ).removeClass( 'selected' );
    
    for( i = 0; i < answers; i++) {
	var bankID = courseStatus.quiz_bank[ID][ i ];
	var questionID = courseStatus.quiz_questions[ID][ i ];
	var n = i + 1;

	if ( quizQuestions[ bankID ][ questionID ].type === 'single' ) {
	    //zork('Single choice question!');
	    var answer = courseStatus.quiz_answers[ ID ][i];
	    $( '#quiz-answer-' + n + '-' + answer ).addClass( 'selected ');
	    zork( 'Selecting answer ' + answer + ' for question ' + i +'!');
	} else if ( quizQuestions[ bankID ][ questionID ].type === 'multiple' ) {
	    //zork('Multiple choice question!');
	    var options = '' + courseStatus.quiz_answers[ ID ][i];
	    var numberOfOptions = options.length;
	    for ( f = 0; f < numberOfOptions; f++ ) {
		var answer = options[f];
		$( '#quiz-answer-' + n + '-' + answer ).addClass( 'selected ');
		zork( 'Selecting answer ' + answer + ' for question ' + i +'!');
	    }
	}
	
    }
    setTimeout( function() {
	if ( quizConfig[ ID ].advance === 'answer' ) {
	    if ( layerInTheMiddle() && layerBeforeLast() === false && layerFirst() === false ) {
		if ( currentQuizMode === 0 ) {
		    if ( quizConfig[ ID ].feedback === true ) {//This is what's bugging at the start
			$( '.quiz-feedback-button' ).fadeIn(500);
		    } else {
			$( '.quiz-next' ).fadeIn(500);
		    }
		} else {
		    $( '.quiz-next' ).fadeIn(500);
		}
	    } else if ( layerInTheMiddle() && layerBeforeLast() ) {
		if ( currentQuizMode === 0 ) {
		    if ( quizConfig[ ID ].feedback === true ) {
			$( '.quiz-feedback-button' ).fadeIn(500);
		    } else {
			$( '.quiz-submit' ).fadeIn(500);
		    }
		} else {
		    $( '.quiz-next' ).fadeIn(500);
		}
	    }
	} else if ( quizConfig[ ID ].advance === 'auto' ) {
	    if ( layerInTheMiddle() && layerBeforeLast() === false ) {
		quizControlsNext( ID );
	    } else if ( layerBeforeLast() ) {
		quizControlsSubmit( ID ); 
	    }
	} else if ( quizConfig[ ID ].advance === 'always' ) {
            if ( layerInTheMiddle() && layerBeforeLast() === false ) {
		$( '.quiz-next' ).fadeIn(500);
	    } else if ( layerBeforeLast() ) {
                if ( currentQuizMode === 0 ) {
                    $( '.quiz-submit' ).fadeIn(500);
                } else {
                    $( '.quiz-next' ).fadeIn(500);
                }
	    }
        }
    }, 500);
}

function quizFeedbackAnswer( ID, question ) {
    var bank = courseStatus.quiz_bank[ ID ][question];
    var bankQuestion = courseStatus.quiz_questions[ ID ][question];
    var questionNumber = question + 1;
    var key = quizQuestions[bank][bankQuestion].key;
    var correct = false;
    
    zork('Showing feedback for question ' + questionNumber + ' (bank: ' + ID + ', question ' + question + ')!');
    
//    $( '.quiz-next' ).fadeOut(500);
    $( '.quiz-feedback-button' ).fadeOut(500);
    
    zork('Removing click from question ' + questionNumber + ' answers!');
    $( '.quiz-answer-' + questionNumber ).prop( 'onclick', null  );
    $( '.quiz-answer-' + questionNumber ).removeClass( 'button-click' );
    
    zork('Coloring question ' + questionNumber + ' answers!');
    $( '.quiz-answer-' + questionNumber ).addClass( 'wrong' );
    
    if ( quizQuestions[bank][bankQuestion].type === 'single' ) {
	$( '#quiz-answer-' + questionNumber + '-' + key ).addClass( 'correct' );
	$( '#quiz-answer-' + questionNumber + '-' + key ).removeClass( 'wrong' );

	if ( $( '#quiz-answer-' + questionNumber + '-' + key + '.correct' ).hasClass( 'selected' ) ) {
	    zork( 'Question ' + questionNumber + ' (single) is CORRECT!' );
	    $( '#quiz-list-' + questionNumber ).addClass( 'correct' );
	    correct = true;
	    
	} else {
	    zork( 'Question ' + questionNumber + ' (single) is WRONG!' );
	    $( '#quiz-list-' + questionNumber ).addClass( 'wrong' );
	}

    } else if ( quizQuestions[bank][bankQuestion].type === 'multiple' ) {
	var keySize = key.length;
	var ruined = 0;

	for ( f = 0; f < keySize; f++ ) {
	    var answerKey = key[f];
	    $( '#quiz-answer-' + questionNumber + '-' + answerKey ).addClass( 'correct' );
	    $( '#quiz-answer-' + questionNumber + '-' + answerKey ).removeClass( 'wrong' );
	    if( !$( '#quiz-answer-' + questionNumber + '-' + answerKey ).hasClass('selected') ) {
		ruined += 1;
	    }
	}
	
	if ( $('.quiz-answer-' + questionNumber + '.wrong').hasClass('selected') ||
		ruined > 0 ) {
	    zork( 'Question ' + questionNumber + ' (multiple) is WRONG!' );
	    $( '#quiz-list-' + questionNumber ).addClass( 'wrong' );
	} else {
	    zork( 'Question ' + questionNumber + ' (multiple) is CORRECT!' );
	    $( '#quiz-list-' + questionNumber ).addClass( 'correct' );	
	    correct = true;
	}

    }
    $( '.quiz-feedback-window' ).removeClass( 'quiz-feedback-window-wrong' );
    $( '.quiz-feedback-window' ).removeClass( 'quiz-feedback-window-right' );
    var feedbackData = '';
    if ( correct === true ) {
	if ( quizQuestions[bank][question].feedback_right === false ) {
	    feedbackData = quizConfig[ ID ].message_feedback_standard_right;
	} else {
	    feedbackData = quizQuestions[bank][bankQuestion].feedback_right;
	}
	
	$( '.quiz-feedback-window' ).addClass( 'quiz-feedback-window-right' );
    } else {
	if ( quizQuestions[bank][question].feedback_wrong === false ) {
	    feedbackData = quizConfig[ ID ].message_feedback_standard_wrong;
	} else {
	    feedbackData = quizQuestions[bank][bankQuestion].feedback_wrong;
	}
	$( '.quiz-feedback-window' ).addClass( 'quiz-feedback-window-wrong' );
    }
    
    $( '.quiz-feedback-message' ).html( feedbackData );
	
    $( '.quiz-feedback-window' ).fadeIn(500);
    $( '.quiz-feedback-next' ).hide();

    if ( layerInTheMiddle() && layerBeforeLast() === false ) {
	$( '.quiz-next' ).fadeIn(500);
    } else if ( layerInTheMiddle() && layerBeforeLast() ) {
	$( '.quiz-submit' ).fadeIn(500); 
    }
}

function quizUpdateQuiz( ID ) {
    if ( ID === undefined ) {
	ID = currentQuiz;
    }
    
    zork('Hiding EVERYTHING!');
    $( '#quiz-start' ).fadeOut(500);
    $( '#quiz-try-again' ).fadeOut(500);
    $( '#quiz-review' ).fadeOut(500);
    $( '#quiz-finish' ).fadeOut(500);
    $( '.quiz-next' ).fadeOut(500);
    $( '#quiz-feedback' ).fadeOut(500);
    $( '.quiz-submit' ).fadeOut(500);
    
    var grade = quizGradeToSubmit( ID );
    
    setTimeout( function() {
	if ( layerFirst() ) {
	    if ( courseStatus.quiz_attempts[ ID ] > 0 && currentQuizMode === 0 || courseStatus.quiz_attempts[ ID ] === -1 && currentQuizMode === 0 ) {
//		$( '#quiz-start' ).fadeIn(500);
                if ( courseStatus.quiz_finished[ ID ] === 1 ) {
                    if ( quizConfig[ ID ].submit_try_again_allow === true ) {
                        $( '#quiz-start' ).fadeIn(500);
                    }
                } else {
                    $( '#quiz-start' ).fadeIn(500);
                }
	    }
	    if ( quizConfig[ ID ].submit_conditions === 'user' && grade >= quizConfig[ ID ].minimum_grade && currentQuizMode === 0 && courseStatus.quiz_finished[ ID ] === 0 || 
                quizConfig[ ID ].submit_conditions === 'best' && grade >= quizConfig[ ID ].minimum_grade && currentQuizMode === 0 && courseStatus.quiz_finished[ ID ] === 0) {
		$( '#quiz-finish' ).fadeIn(500);
	    }
	} else if ( layerLast() ) {
	    if ( quizConfig[ ID ].submit_conditions === 'user' && grade >= quizConfig[ ID ].minimum_grade && courseStatus.quiz_finished[ ID ] === 0 ||
                    quizConfig[ ID ].submit_conditions === 'best' && grade >= quizConfig[ ID ].minimum_grade && grade < 100 && courseStatus.quiz_finished[ ID ] === 0  ) {
		$( '#quiz-finish' ).fadeIn(500);
            } else if ( quizConfig[ ID ].submit_conditions === 'best' && grade === 100 && courseStatus.quiz_finished[ ID ] === 0  ) {
		courseStatus.quiz_attempts[ ID ] = 0;
                quizFinish( ID );
	    } else if ( quizConfig[ ID ].submit_conditions === 'attempts' && courseStatus.quiz_attempts[ ID ] === 0 && courseStatus.quiz_finished[ ID ] === 0 ) {
		quizFinish( ID );
	    } else if ( quizConfig[ ID ].submit_conditions === 'pass' && grade >= quizConfig[ ID ].minimum_grade && courseStatus.quiz_finished[ ID ] === 0 ) {
		quizFinish( ID );
	    }
	       
	    if ( courseStatus.quiz_attempts[ ID ] > 0 || courseStatus.quiz_attempts[ ID ] === -1) {
                if ( courseStatus.quiz_finished[ ID ] === 1 ) {
                    if ( quizConfig[ ID ].submit_try_again_allow === true ) {
                        $( '#quiz-try-again' ).fadeIn(500);
                    }
                } else {
                    $( '#quiz-try-again' ).fadeIn(500);
                }
	    }
	    if ( quizConfig[ ID ].review === true ) {
		$( '#quiz-review' ).fadeIn(500);
	    } else if ( quizConfig[ ID ].review === 'pass' && grade >= quizConfig[ ID ].minimum_grade ) {
		$( '#quiz-review' ).fadeIn(500);
	    }
	} else if ( layerBeforeLast() ) {
	    //$( '.quiz-submit' ).fadeIn(500);
	    if ( currentQuizMode === 0 ) {
		if ( quizConfig[ ID ].feedback === true ) {
		    $( '#quiz-feedback' ).fadeIn(500);
		} else {
		    //$( '.quiz-submit' ).fadeIn(500);
		}
	    } else {
		//$( '.quiz-next' ).fadeIn(500);
	    }
	}
	var q = layerCurrent() - 1;
	if ( layerInTheMiddle() && layerBeforeLast() === false && quizConfig[ ID ].advance === 'always' || 
		layerInTheMiddle() && layerBeforeLast() === false && courseStatus.quiz_answers[ ID ][q] > -1) {
	    if ( currentQuizMode === 0 ) {
		if ( quizConfig[ ID ].feedback === true ) {
		    $( '#quiz-feedback' ).fadeIn(500);
		} /*else {
		    $( '.quiz-submit' ).fadeIn(500);
		}*/
	    } else {
		$( '.quiz-next' ).fadeIn(500);
	    }
	}
	if ( layerInTheMiddle() ) {
	    $( '#quiz-list' ).fadeIn(500);
	    var a = layerCurrent();
	    $( '.quiz-list-item' ).removeClass( 'active' );
	    $( '#quiz-list-' + a ).addClass( 'active' );
	} else {
            
            $( '#quiz-list' ).fadeOut(500);
        }
	
	quizCorrectAnswer( ID );
	$( '.llwindow-quiz' ).show();
	$( '#llwindow-data-quiz-name' ).text( quizConfig[ID].name );
	$( '#llwindow-data-quiz' ).text( ID );
	$( '#llwindow-data-last' ).text( courseStatus.quiz_last_grade[ID] );
	$( '#llwindow-data-best' ).text( courseStatus.quiz_best_grade[ID] );
	$( '#llwindow-data-attempts' ).text( courseStatus.quiz_attempts[ID] );
    },
    1000);
    

}

function quizCorrectAnswer( ID ) {
    if ( ID === undefined ) {
	ID = currentQuiz;
    }
    
    if ( layerInTheMiddle() ) {
	var questionNumber = layerCurrent() - 1;
	var bank = courseStatus.quiz_bank[ ID ][ questionNumber ];
	var question = courseStatus.quiz_questions[ ID ][ questionNumber ];
	var key = quizQuestions[bank][question].key;
	
	zork( 'PSST! The correct answer to question ' + questionNumber + ' is ' + key +'!');
	
	$( '#llwindow-data-bank' ).text( bank );
	$( '#llwindow-data-question' ).text( question );
	$( '#llwindow-data-answer' ).text( key );

    }
}

function quizUpdateEndScreen( ID ) {
    if ( ID === undefined ) {
	ID = currentQuiz;
    }
    
    var grade;
    
    grade = quizGradeToSubmit( ID );
    
    var attempts = courseStatus.quiz_attempts[ ID ];
    var pass = quizConfig[ ID ].minimum_grade;
    $('.quiz-message-end').hide();
//    $( '#message-end-best' ).hide();
//    $( '#message-end-best-no-attempts' ).hide();
//    $( '#message-end-pass' ).hide();
//    $( '#message-end-pass-no-attempts' ).hide();
//    $( '#message-end-fail' ).hide();
//    $( '#message-end-fail-no-attempts' ).hide();
//    $( '#message-end-pass-generic' ).hide();
//    $( '#message-end-fail-generic' ).hide();
    
    if ( layerLast() ) {
        $('#quiz-start-grade').fadeIn();
        $('#quiz-start-best-grade').fadeIn();
        $('#quiz-start-attempts').fadeIn();
        if ( courseStatus.quiz_finished[ID] !== 1 ) {
            if ( grade === 100 ) {
                if ( attempts > 0 || quizConfig[ ID ].attempts === -1 ) {
                    $( '#message-end-best' ).fadeIn();
                } else if ( attempts === 0 && quizConfig[ ID ].attempts !== -1 ) {
                    $( '#message-end-best-no-attempts' ).fadeIn();
                }
                $( '#message-end-pass-generic' ).fadeIn();
                $('#try-again-button-lines').remove();
                $('#try-again-button-button').attr('src','images/avaliacao/btn_repetir-av-gray.png');
                $('#quiz-try-again').prop("onclick", null).off("click");
                $('#quiz-try-again').removeClass("button-click");
                $('#quiz-try-again').css( 'cursor', 'default');
            } else if ( grade < 100 && grade >= pass  ) {
                if ( attempts > 0 || attempts === -1 ) {
                    $( '#message-end-pass' ).fadeIn();
                } else if ( attempts === 0 ) {
                    $( '#message-end-pass-no-attempts' ).fadeIn();
                }
                $( '#message-end-pass-generic' ).fadeIn();
            } else if ( grade < pass  ) {
                if ( attempts > 0 || attempts === -1 ) {
                    $( '#message-end-fail' ).fadeIn();
                    $( '#message-end-fail-generic' ).fadeIn();

                } else if ( attempts === 0 ) {
                    $( '#message-end-fail-no-attempts' ).fadeIn();
                    $( '#message-end-fail-generic' ).fadeIn();
                    $( '#quiz-review' ).remove();
                }
            }
	} else {
            $('.quiz-message-end').hide();
            $( '#message-end-terminated' ).show();   
        }
    }
    
    quizUpdateScreenInfo( ID );
}

function quizUpdateStartScreen( ID ) {
    if ( ID === undefined ) {
	ID = currentQuiz;
    }
    
    var grade = quizGradeToSubmit( ID );
    
    var attempts = courseStatus.quiz_attempts[ ID ];
    var pass = quizConfig[ ID ].minimum_grade;
    
    zork('Updating start screen...');
    $('.quiz-message-start').hide();
//    $( '#message-start-terminated' ).hide();
//    $( '#message-start-first' ).hide();
//    $( '#message-start-pass' ).hide();
//    $( '#message-start-pass-no-attempts' ).hide();
//    $( '#message-start-fail' ).hide();
//    $( '#message-start-fail-no-attempts' ).hide();
    
    if ( attempts === quizConfig[ ID ].attempts && courseStatus.quiz_finished[ ID ] !== 1 ){
	$( '#message-start-first' ).show();
        $('#quiz-start-grade').hide();
        $('#quiz-start-best-grade').hide();
        $('#quiz-start-attempts').hide();

	zork('FIRST!');
    } else { 
//        $('#quiz-start-grade').show();
//        $('#quiz-start-best-grade').show();
//        $('#quiz-start-attempts').show();
        $('#quiz-start-grade').hide();
        $('#quiz-start-best-grade').hide();
        $('#quiz-start-attempts').hide();
        if ( courseStatus.quiz_finished[ ID ] === 1 ) {
            $( '#message-start-terminated' ).show();
        } else {
            if ( grade <= 100 && grade >= pass ) {
                if ( attempts > 0 || attempts === -1 ) {
                    $( '#message-start-pass' ).show();
                    zork('Passed with attempts left...');
                } else if ( attempts === 0 ) {
                    $( '#message-start-pass-no-attempts' ).show();
                    zork('Passed with no attempts left...');
                }
            } else if ( grade < pass  ) {
                if ( attempts > 0 || attempts === -1 ) {
                    $( '#message-start-fail' ).show();
                    zork('Failed with attempts left...');
                } else if ( attempts === 0 ) {
                    $( '#message-start-fail-no-attempts' ).show();
                    zork('Failed with no attempts left...');
                }
            }
        }
    }
    
    quizUpdateScreenInfo( ID );
}

function quizUpdateScreenInfo( ID ) {
    if ( ID === undefined ) {
	ID = currentQuiz;
    }
    
    var best = courseStatus.quiz_best_grade[ ID ];
    var grade = courseStatus.quiz_last_grade[ ID ];
    var attempts = courseStatus.quiz_attempts[ ID ];
    var pass = quizConfig[ ID ].minimum_grade;
    var submit = /*grade =*/ quizGradeToSubmit( ID );
    
    $( '.quiz-best-grade' ).html( best );
    $( '.quiz-grade' ).html( grade );
    //ALTA PEDREIRADA DULT
    var answers = grade * 4 / 100;
    $( '.quiz-questions-answered-right' ).html( answers );
    $( '.quiz-attempts' ).html( attempts );
    $( '.quiz-pass' ).html( pass ); 
    $( '.quiz-final-grade' ).html( submit ); 
}

function quizClearAnswers( ID ) {
    if ( ID === undefined ) {
	ID = currentQuiz;
    }
    
    var answers = courseStatus.quiz_answers[ ID ].length;
    
    for ( i = 0; i < answers; i++ ) {
	courseStatus.quiz_answers[ ID ][ i ] = -1;
    }
    
    quizUpdateAnswers( ID );
}

function quizTryAgain( ID ) {
    if ( ID === undefined ) {
	ID = currentQuiz;
    }
    currentQuizTryAgain = true;
    
    currentQuizMode = 1;
    quizBuildHtml( ID );
    
    currentQuizMode = 0;
//    quizControlsStart( ID );
}

function quizReview( ID, target ) {
    if ( target === undefined ) target = 'all';
    
    if ( ID === undefined ) {
	ID = currentQuiz;
    }
    
    currentQuizMode = 1;
    
    zork( 'Updating answers for review!');
    var answers = courseStatus.quiz_answers[ ID ].length;
    
    $( '.quiz-answer' ).removeClass( 'button-click' );
    $( '.quiz-answer' ).prop( 'onclick', null  );
    $( '.quiz-answer' ).addClass( 'wrong' );
    $( '.quiz-list-item' ).addClass( 'wrong' );
    
    if ( quizConfig[ ID ].help = 'review' ) {
	$( '.quiz-help-review' ).addClass( 'quiz-help' );
	$( '.quiz-help' ).removeClass( 'quiz-help-review' );
    }
    
    for( i = 0; i < answers; i++) { //Check each answer
	var n = i + 1;
	var bank = courseStatus.quiz_bank[ ID ][i];
	var question = courseStatus.quiz_questions[ ID ][i];
	var key = quizQuestions[bank][question].key;
	
	zork( 'Checking answer ' + n + '!' );
	if ( quizQuestions[bank][question].type === 'single' ) {
	    $( '#quiz-answer-' + n + '-' + key ).addClass( 'correct' );
	    $( '#quiz-answer-' + n + '-' + key ).removeClass( 'wrong' );
	    
	    if ( $( '#quiz-answer-' + n + '-' + key + '.correct' ).hasClass( 'selected' ) ) {
		zork( 'Question ' + n + ' (single) is CORRECT!' );
		$( '#quiz-list-' + n ).addClass( 'correct' );
		$( '#quiz-list-' + n ).removeClass( 'wrong' );
	    } else {
		zork( 'Question ' + n + ' (single) is WRONG!' );
	    }
	    
	} else if ( quizQuestions[bank][question].type === 'multiple' ) {
	    var keySize = key.length;
	    var ruined = 0;
	    
	    for ( f = 0; f < keySize; f++ ) {
		var answerKey = key[f];
		$( '#quiz-answer-' + n + '-' + answerKey ).addClass( 'correct' );
		$( '#quiz-answer-' + n + '-' + answerKey ).removeClass( 'wrong' );
		if( !$( '#quiz-answer-' + n + '-' + answerKey ).hasClass('selected') ) {
		    ruined += 1;
		}
	    }
	    if ( quizConfig[ ID ].multiple_choice_grade === 'some' ) {
		
	    } else if ( quizConfig[ ID ].multiple_choice_grade === 'all' ) {
		
		if ( $('.quiz-answer-' + n + '.wrong').hasClass('selected') ||
			ruined > 0 ) {
		    zork( 'Question ' + n + ' (multiple) is WRONG!' );
		} else {
		    zork( 'Question ' + n + ' (multiple) is CORRECT!' );
		    $( '#quiz-list-' + n ).addClass( 'correct' );
		    $( '#quiz-list-' + n ).removeClass( 'wrong' );
		}
	    }

	}

    }
    $('.quiz-question-instruction').hide();
    layer( 1 );
    quizUpdateQuiz( ID );
}

function quizFinish( ID ) {
    var grade = quizGradeToSubmit( ID );
    quizSubmit( ID );
    if ( courseStatus.quiz_attempts[ ID ] > 0 ) {
	courseStatus.quiz_attempts[ ID ] = 0;
    }
    courseStatus.quiz_finished[ ID ] = 1;
    if ( courseStatus.quiz_attempts[ ID ] === 0 && quizConfig[ ID ].unlock === 'attempts' ) {
	slideComplete();
    }
    if ( quizConfig[ ID ].unlock === 'pass' && grade >= quizConfig[ ID ].minimum_grade ) {
	slideComplete();
    }  
    
    quizUpdateQuiz( ID );
    quizUpdateEndScreen( ID );
}


// Get quiz grade in %
function quizGradeToSubmit( ID ) {
    if ( ID === undefined ) {
	ID = currentQuiz;
    }
    
    var grade;
    if ( quizConfig[ ID ].best_grade === true ) {
	grade = courseStatus.quiz_best_grade[ ID ];
    } else {
	grade = courseStatus.quiz_last_grade[ ID ];
    }
    return grade;
}

function quizGrade( ID ) {
    if ( ID === undefined ) {
	ID = currentQuiz;
    }
        
    zork( 'Calculating grade for quiz ' + ID +'...');
    
    var totalQuestions = courseStatus.quiz_answers[ ID ].length;
    
    var correctAnswers = 0;
    
    for ( i = 0; i < totalQuestions; i++ ) {
	var bank = courseStatus.quiz_bank[ ID ][ i ];
	var question = courseStatus.quiz_questions[ ID ][ i ];
	var answer = courseStatus.quiz_answers[ ID ][ i ];
	var key = quizQuestions[bank][question].key;
	var type = quizQuestions[bank][question].type;
	
	zork( 'Checking if question ' + question + ' key (' + key + ') and it\'s answer (' + answer + ') are equal...');
	
	if ( type === 'single' ) {
	    zork('Single choice question!');
	    if ( key === answer ) {
		correctAnswers += 1;
		zork('They are! And this answer is worth 1!');
	    } else {
		zork('They aren\'t...');
	    }
	} else if ( type === 'multiple' ) {
	    zork('Multiple choice question!');
	    var answerSize = answer.length;
	    var keySize = key.length;
	    var valuePerItem = 100 / keySize;
	    var answerValue = 0;
	    var ruined = 0;
	    
	    for ( f = 0; f < answerSize; f++ ) {
		if ( answerSize <= keySize ) {
		    zork( 'Checking ' + answer + ' includes ' + key[f] + '...' );
		    if ( answer.includes( key[f] ) ) {
			answerValue += valuePerItem;
			zork('It does!');
		    } else {
			ruined += 1;
			zork('It doesn\'t!');
		    }
		} else {
		    ruined = answerSize - keySize;
		    zork('Too many locks for so little keys...');
		}
	    }
	    zork('You choose ' + ruined + ' unecessary questions...');
	    
	    if ( answerValue >= 100 - quizConfig[ ID ].multiple_choice_forgiveness &&
		 answerValue <= 100 + quizConfig[ ID ].multiple_choice_forgiveness ){
		answerValue = 100;
	    }
	    
	    if ( quizConfig[ ID ].multiple_choice_grade === 'some' ) {
		/*answerValue = ( Math.round( answerValue / 10 ) ) / 10;
		correctAnswers += answerValue;
		zork('This answer is worth ' + answerValue + '!');*/
	    } else if ( quizConfig[ ID ].multiple_choice_grade === 'all' ) {
		if ( ruined > 0) {
		    answerValue = 0;
		    zork('You chose WRONG! And for that you must die!!!');
		}
		if ( answerValue === 100 ) {
		    correctAnswers += 1;
		    zork('They are equal! And this answer is worth 1!');
		} else {
		    zork('They aren\'t equal...');
		}
	    }
	}	
	
    }
    zork( 'You answered correctly to ' + correctAnswers + ' questions in a total of ' + totalQuestions + '.');
    
    var grade = correctAnswers * 100 / totalQuestions;
    
    var decimals = quizConfig[ ID ].grade_round_decimal;
    
    if ( decimals > 0 ) {
        decimals = Math.pow(10, decimals);
    } else {
        decimals = 1;
    }
    
    if ( quizConfig[ ID ].grade_round === true ) {
        grade = Math.round( grade * decimals) / decimals;
    } else if ( quizConfig[ ID ].grade_round === 'down' ) {
        grade = Math.floor( grade * decimals) / decimals;
    } else if ( quizConfig[ ID ].grade_round === 'up' ) {
        grade = Math.ceil( grade * decimals) / decimals;
    }
    
    courseStatus.quiz_last_grade[ ID ] = grade;
    
    if ( grade > courseStatus.quiz_best_grade[ ID ] ) {
	courseStatus.quiz_best_grade[ ID ] = grade;
    }
    
    zork( 'Your grade for quiz ' + ID + ' is... ' + grade + '%!');
    
    if ( courseStatus.quiz_attempts[ ID ] > 0 && currentQuizMode === 0 ) {
	courseStatus.quiz_attempts[ ID ] = courseStatus.quiz_attempts[ ID ] - 1;
	zork( 'You still have ' + courseStatus.quiz_attempts + ' attempts!');
    } else if ( courseStatus.quiz_attempts[ ID ] === -1 ) {
	zork( 'You have unlimited attempts. That is almost like cheating...');
    } else {
	zork( 'You don\'t have any more attempts...');
    }
    $( '#llwindow-data-attempts' ).text( courseStatus.quiz_attempts[ID] );
    
    quizUpdateQuiz( ID );
    courseSave();
}

function quizResetQuiz( ID ) {
    if ( ID === undefined ) {
	ID = currentQuiz;
    }
    courseStatus.quiz_last_grade[ID] = 0;
    courseStatus.quiz_best_grade[ID] = 0;
    courseStatus.quiz_finished[ID] = 0;
    courseStatus.quiz_attempts[ID] = quizConfig[ID].attempts;
}

function quizSubmit( ID ) {
    if ( quizConfig[ ID ].submit_conditions !== false ) {
	courseStatus.grade = quizGradeToSubmit( ID );
	courseStatus.completed = 1;
	courseGrade();
    }
}
