/*
	topic_pre_test.js
	
	This file contains functionality for the section/topic
	test-out/pre-test

*/

/* Apply click events for test-out intro and results buttons */
$( document ).ready(function() {	

	$(".intro_btn").click(function(e){
		
		
		var btnNum = Number($(this).attr("id").split("_")[3]);
		var secNum = Number($(this).attr("id").split("_")[2]);
		
		document.currentSection = secNum;
		
		
		var currentTopic = Number($("#sec_"+secNum).index(".breaker")); // Zero index
		
		var tempTestAttemptArr = document.topicTestAttempted.split('');
		tempTestAttemptArr[currentTopic] = 1;
		document.topicTestAttempted = tempTestAttemptArr.join('');
		recordPercentComplete(1, document.subsectionCount, false);	
		
		
		if(btnNum == 1){
			document.skipTopicTest = false;
			document.takeTopicPreTest = true;
		}else{
			document.skipTopicTest = true;
			document.takeTopicPreTest = false;
			markTopicQsViewed()
		}
		
		document.topic_test_score = 0;
		
		document.currentPreQues = 0;
		document.lastPreQues = false;
		
		document.audioComplete = true;
		document.intComplete = true;
		
		topic_pre_ques_dat['test_dat'][0].user_score = '0';
		
		isPageComplete(document.currentSection);
		//document.getElementById("sec_"+ document.nextSection).focus();
		
		$(".topicPre_"+secNum).css("display","none");
		
		//$(".topicPre_"+secNum).css("visibility","hidden");
		
		$("body, html").animate({
			scrollTop: $('#sec_'+ document.nextSection).position().top -70
			},750, function(){

			if(btnNum == 1){
				$('#sec_'+ document.nextSection + " .topicTestLabel").focus();
			}else{
				$('#sec_'+ document.nextSection + " .topicTitle .content_text").focus();
			}

		});

	});
	
	
	
	$('.intro_btn').keypress(function (e) {
        if (e.keyCode == 13 || e.keyCode == 32) {
            $(this).trigger('click');
        }
    });
	
	
	
	$(".topic_res_btn").click(function(e){
		
		
		var btnNum = Number($(this).attr("id").split("_")[4]);
		var secNum = Number($(this).attr("id").split("_")[3]);
		
		var currentSection = secNum;
		var nextSec = Number(currentSection + 1)
		
		//var currentTopic = Number($("#sec_"+secNum).index(".breaker")) + 1; // Zero index
	
		if(btnNum == 1){
			
			unlockTestTopic(document.currentTopic);
			
			$("#home_nav").trigger('click');
			
			
		}else if(btnNum == 2){
			
			document.audioComplete = true;
			document.intComplete = true;
			
			isPageComplete(currentSection);
			unlockTestTopic(document.currentTopic);
			
			$("body, html").animate({
				scrollTop: $('#sec_'+ nextSec).position().top - 70
			},750);
			
		}else if(btnNum == 3){
			
			document.audioComplete = true;
			document.intComplete = true;
			
			isPageComplete(currentSection);
			
			//
			
			$("body, html").animate({
				scrollTop: $('#sec_'+ nextSec).position().top - 70
			},750, function(){
				//markTopicQsViewed()
			});
		}

	});
	
	$('.topic_res_btn').keypress(function (e) {
        if (e.keyCode == 13 || e.keyCode == 32) {
            $(this).trigger('click');
        }
    });
	
});


/* 
	calcTopicTest
	Function to calculate if user has passed section test-out/pre-test
	
*/

function calcTopicTest(topicNum, totalNumQs){
	
	var totalQues = totalNumQs;
	
	var corrNumArr = topic_pre_ques_dat['test_dat'][0].num_corr_ques.split(',');
	
	var tempTPretestOutArr = document.topicsPretestedOut.split('');
	
	var userScore = 0;
	var passMark = corrNumArr[topicNum-1]
	
	if(document.topicPrePassMark == null){
		
		userScore = document.topic_test_score;
		passMark
	}else{
	
		userScore = Math.round((document.topic_test_score / totalQues)*100);	
		passMark = document.topicPrePassMark
	}
	
	//console.log("userScore = " + userScore)
	
	if(userScore >= passMark){
		
		var menuArr = document.sectionCompleted.split('');
	
	
		for(var i = 0; i != menuArr.length; i++){

			if(menuArr[i] == 0){
				menuArr[i] = 2;
				break;
			}
		}
		
		document.sectionCompleted = menuArr.join('')
		
		
		$("#topic_" + topicNum +"_passed_text").show();
		$("#topic_" + topicNum +"_passed_img").show();
		
		tempTPretestOutArr[topicNum-1] = 1;
		
		unlockTestTopic(topicNum);
		
	}else{
		$("#topic_" + topicNum +"_failed_text").show();
		$("#topic_" + topicNum +"_failed_img").show();
		tempTPretestOutArr[topicNum-1] = 2;
	}
	
	document.topicsPretestedOut = tempTPretestOutArr.join('');
	
	recordPercentComplete(1, document.subsectionCount, false);	
}

/*

	unlockTestTopic called when passing the scetion test-out/pre-test
	It calculates which pages should be marked as viewed and unlocked 
	based on the topics contained in this section

*/

function unlockTestTopic(topicNum){
	var startQuesArr = topic_pre_ques_dat['test_dat'][0].pre_start_sec_num.split(',');
	var startID = $(".breaker").eq(topicNum-1).attr("id");
	var endID = $(".preTopicTest").eq(topicNum-1).attr("id"); // = $(".breaker").eq(topicNum).attr("id")
			
	for(var i = (topicNum); i != startQuesArr.length; i++){
		
		if(Number(startQuesArr[i]) != 0){
			
			var tempNum = Number(startQuesArr[i]) - 1;
			endID = "sec_"+tempNum;
			break
		}else{
			if(i == startQuesArr.length-1){
				if(document.summarySection == null){
					var tempEnd = (Number(document.subsectionCount) + 1);
					endID = "sec_" + tempEnd;
				}else{
					endID = "sec_" + document.summarySection;
				}
			}
			
		}
	}
	
	var startNum = Number(startID.split("_")[1]);
	var endNum = Number(endID.split("_")[1]);
	
	//console.log("startNum =  " + startNum + "    endNum = " +endNum)
	
	for(var i = startNum; i!= endNum; i++){
		
		document.trackingArr[i-1] = 1;
	}
	recordPercentComplete(1, document.subsectionCount, false);	
	
	markTopicQsViewed();
}

/*

	markTopicQsViewed
	Function will mark all questions in a section/topic as viewed so they can
	be removed when returning to a topic after taking/skipping the test-out.pre-test
	
*/

function markTopicQsViewed(){
	
	var topicArr = document.topicTestAttempted.split("");
	var startQuesArr = topic_pre_ques_dat['test_dat'][0].pre_start_sec_num.split(',');
	var endQuesArr = topic_pre_ques_dat['test_dat'][0].pre_end_sec_num.split(',');
	
	
	for(var i = 0; i!= document.topicsCount; i++){
		
		var start = 0;
		var end = 0;
		if(Number(topicArr[i]) == 1){
				
			start = Number(startQuesArr[i]);
			end = Number(endQuesArr[i])+1;
			$(".topicPre_"+(start-1)).css("display","none")
			for(var j = start; j <= end; j++){
				$("#sec_" + j).attr("data-hide", true)
			}
			document.getElementById("sec_" + (end+1)).offsetHeight;
		}
	}
	
}


/*

	clearTopicQs
	Function to remove the content of section/topic test-out questions
	so they aren't visible when returning to the section

*/

function clearTopicQs(){
	
	var currentsection = $('.section');
	
	for(var i = 2; i<= currentsection.length; i++){
		if($("#sec_"+i).attr("data-hide")){
			
			
			//$("#sec_" + i).html("<div class='container'></div>")
			//$("#sec_" + i).css("margin-bottom","0px");
			
			if($("#sec_" + i).hasClass("preTopicRes")){
				//$("#sec_" + i).css("margin-bottom","15px");
			}
			
		}
	}
}


/*

	seenTopicTest
	Function to mark page complete when returning to start of topic and calculate current topic
	to update accent colors
	
*/

function seenTopicTest(){
	
	var secNum = 0;
	secNum = Number(document.lesson_location.split("_")[1]);
	if($(document.lesson_location).hasClass("preTopicTest")){
				
		document.audioComplete = true;
		document.intComplete = true;

		isPageComplete(secNum);
	}
	
	
	var topicNum
	
	for(var i = secNum; i>=0; i--){
		
		if($("#sec_"+i).hasClass("breaker")){
			
			topicNum = Number($("#sec_"+i).index(".breaker")) + 1;
			break
		}
	}
	
	document.currentTopic = topicNum;
	
	updateAccentColors()

}

/*

	prepareInteractions
	Function to prepare and collate all data from the test-out question
	and send to LMS if document.sendInteractions = true;

*/
function prepareInteractions(secNum, userAnsArray, result, confidence){
	
	var isTopicTest = $("#sec_"+secNum).hasClass("preTopicQues");
	
	var isAssessTest = $("#sec_"+secNum).hasClass("testQues");
	
	var isInline;
	
	if(!isTopicTest && !isAssessTest){
		isInline = true;
	}
	
	//console.log("isTopicTest = " + isTopicTest);
	
	if(document.sendInteractions){
		
		var userAnsArr = [];
		userAnsArr = userAnsArray;
		var questionNum;
		var questionType;
		
		if(isTopicTest){
			questionNum = topic_pre_ques_dat["sec_" + secNum][0].question;
			questionType = topic_pre_ques_dat["sec_" + secNum][0].type;
		}
		
		if(isAssessTest){
			questionNum = post_test_ques_dat["sec_" + secNum][0].question;
			questionType = post_test_ques_dat["sec_" + secNum][0].type;
		}
		
		if(isInline){
			questionNum = inline_ques_dat["sec_" + secNum][0].question;
			questionType = inline_ques_dat["sec_" + secNum][0].type;
		}

		if(questionType == "mcsa" || questionType == "mcma"){
			questionType = "choice";
		}

		var questionID = "T_" + document.currentTopic + "_Q_" + questionNum;
		var optionsArr = [];
		var questStem = ""
		var correctAnsArray = [];
		
		if(isTopicTest){
			correctAnsArray = jQuery.makeArray(topic_pre_ques_dat["sec_" + secNum][0].ans.split(","));
		}
		
		if(isAssessTest){
			correctAnsArray = jQuery.makeArray(post_test_ques_dat["sec_" + secNum][0].ans.split(","));
		}
		
		if(isInline){
			correctAnsArray = jQuery.makeArray(inline_ques_dat["sec_" + secNum][0].ans.split(","));
		}

		optionsArr = document.optionsArr;
		questStem = document.questStem;

		var correctResponse = "";
		var userResponse = "";

		var courseTitle = document.courseTitle.replace(/ /g, '_');
		
		var intWeighting = confidence;//1;
		
		
		for(var i = 0; i != correctAnsArray.length; i++){

			if(Number(correctAnsArray[i]) == 1){
				if(lms_type == "scorm_2004"){
					correctResponse = optionsArr[i].replace(/ /g, '_');
				}else if (lms_type == "scorm_1_2"){
					correctResponse = Number(i) + 1;
				}
			}

			if(Number(userAnsArr[i]) == 1){
				if(lms_type == "scorm_2004"){
					userResponse = optionsArr[i].replace(/ /g, '_');
				}else if (lms_type == "scorm_1_2"){
					userResponse = Number(i) + 1;
				}
				
			}
		}

		
		var dateobj = new Date(); 
		var dateStr = dateobj.toISOString();
		
		var intTimeStamp = "";
		var tempDatStr1 = dateStr.split(":")[0];
		var tempDatStr2 = dateStr.split(":")[1];
		var tempDatStr3 = dateStr.split(":")[2];
		
		if(lms_type == "scorm_2004"){
			intTimeStamp = tempDatStr1 + ":" + tempDatStr2 + ":" + tempDatStr3.split(".")[0];
			
		}else if(lms_type == "scorm_1_2"){
			intTimeStamp = tempDatStr1.split("T")[1] + ":" + tempDatStr2 + ":" + tempDatStr3.split(".")[0];
		}
		
		//console.log(questionID + " " + userResponse + " " + result + " " + correctResponse + " " + questStem + " " + questionType + " " + intWeighting + " " + intTimeStamp + " " +  courseTitle);
					
		recordInteractions(questionID, userResponse, result, correctResponse, questStem, questionType, intWeighting, intTimeStamp, courseTitle);
		
	}
}
