/* functions to facilitate lock down on objects */

var debugLocking = false;

if(commitTimer){	
	setInterval(function () { if(typeof actionsLMSCommit !="undefined" ){actionsLMSCommit()}}, 600000);
}

function adjustScreenNavButtons(){
	if(typeof(LMSAPI)!="undefined"){
		if(useAICCRules!=true && commitTimer!=true){
			actionsLMSCommit();
		}
		checkCourseCompletion();	
	}
}

//adjustScreenNavButtons()

/* 
	isPageComplete
	Function to check if the page/section is complete
	Has the audio and and interaction been completed
	Called when interactions/audio have completed
 */
var pageCompleted = null;

function isPageComplete(n){
	/* ensure the first test question shows when in the test topic and on the test intro page */
	//console.log('pageCompleted = ' + pageCompleted + '     n = ' + n);
	if((pageCompleted != n) || ((pageCompleted == n) && (n == document.testIntroSubsection) && ($("#sec_" + document.testIntroSubsection).css("display") == "block"))){
		//console.log(document.audioComplete + '    ' + document.intComplete + '      n = ' + n);
		if(document.audioComplete && document.intComplete){
			
			//2019/06/04 Next arrow on unlocked screens		
			if(!$('#sec_'+ (n)).next().hasClass('breaker') || $('#sec_'+ (n)).hasClass('testResults') ){
				
				if(document.trackingArr[n-1] == 0){
					
					if(!$('#sec_'+ (n)).hasClass('preTopicTest') && !$('#sec_'+ (n)).hasClass('preTopicRes') ){

						if(document.intArr[n-1] == 1){
							$('#sec_' + n + ' .complete_arrow').css('display', 'block');
							$('#sec_' + n + ' .complete_arrow').addClass('unlocked');
						}
					}
				}else if($('#sec_'+ (n)).hasClass('preTopicQues')){
					$('#sec_' + n + ' .complete_arrow').css('display', 'block');
					$('#sec_' + n + ' .complete_arrow').addClass('unlocked');
				}
				//2019/06/18 remove down arrow from screen before coming next on desktop
				if($('#sec_'+ (n)).next().hasClass('cNext')){
					if(!isiPad && !isiPhone && !isAndroidTablet && !isAndroidPhone){
						//$('#sec_' + n + ' .complete_arrow').css('display', 'none');
					}
				}
				//2019/06/18 remove down arrow from screen before coming next on desktop
				
			}
			//2019/06/04 reset variables
			document.audioComplete = false;
			document.intComplete = false;
			
			markSectionComplete(n);
			pageCompleted = n;
		}
	}else{
		
		document.audioComplete = false; 
		document.intComplete = false;
		
		if($('#sec_'+ (n)).hasClass('one_page_topic')){
			markSectionComplete(n);
		}
	}	
}

function downButton(){
	for(var i=1; i<$('.section').length; i++){
		if(document.lockedArr[i] === 1 && document.trackingArr[i] != 1 && !$('.section').eq(i).next().hasClass('breaker')){
			
			//$('.complete_arrow').eq(i-1).css('display', 'block');
			
			//2019/06/18 remove down arrow from screen before coming next on desktop
			if($('.section').eq(i).next().hasClass('cNext')){
				if(!isiPad && !isiPhone && !isAndroidTablet && !isAndroidPhone){
					$('.complete_arrow').eq(i-1).css('display', 'none');
					$('.complete_arrow').eq(i-1).removeClass('unlocked');
				}
			}
			//2019/06/18 remove down arrow from screen before coming next on desktop
		}
		
		//2019/06/04 Next arrow on unlocked screens
		if(document.intArr[i] === 0){
			if(!$('.section').eq(i).next().hasClass('breaker')){
				
				//$('.complete_arrow').eq(i).css('display', 'block');
				//$('.complete_arrow').eq(i).addClass('unlocked');
			}
			
			//2019/06/18 remove down arrow from screen before coming next on desktop	
			if($('.section').eq(i).next().hasClass('cNext')){
				if(!isiPad && !isiPhone && !isAndroidTablet && !isAndroidPhone){
					//$('.complete_arrow').eq(i-1).css('display', 'none');
				}
			}
			//2019/06/18 remove down arrow from screen before coming next on desktop
		}
		//2019/06/04
	}
}

/* 
	markSectionComplete	
	Function to mark page as complete in the LMS
	And display the next section	
	Called from isPageComplete
*/
function markSectionComplete(n){
	console.log('markSectionComplete ' + n);
	if ((document.currentSection < document.testIntroSubsection) || (document.currentSection >= document.testResultsSubsection))
	{
		/* test out: if there is a pre-test in the course */
		if (document.pretestPresent == 1)
		{
			/* test out: if the pre-test is not being currently taken and it is not the post-test results then mark this page as complete */
			if (!document.takingPretest) {
				document.trackingArr[n - 1] = 1; /* to keep each section unlocked once completed */
			}
		}
		else {
			document.trackingArr[n - 1] = 1; /* to keep each section unlocked once completed */
		}	
		if(!isWeb){
			/* mobile devices so commit tracking data */
			recordPercentComplete(n, document.subsectionCount, false);
			courseWriteTimer(true);			
			/* applied to fix issue with progress not updating in LMS */
			/*if(error_tracking){
				actionsLMSCommit();
			}*/			
		}else{
			trackSectionComplete(n);
		}
	}
	document.audioComplete = false;
	document.intComplete = false;
	var currClassName = $('#sec_'+ n).attr("class");
	//console.log("currClassName = " + currClassName);
	if (currClassName.indexOf('testStart') != -1) {	
		/* test intro */
		var color1 = "bgColor1";
		var color2 = "bgColor2"
		if($('.testStart .background_stretch .background_stretch_bg').hasClass('bgColor1')){
			color1 = "bgColor1";
			color2 = "bgColor2"
		}else{
			color1 = "bgColor2";
			color2 = "bgColor1"
		}

		for (var i = 0; i < document.assessRandomQuesArr.length; i++) 
		{
			var secNum = document.assessRandomQuesArr[i];
			$("#testQues" + (i + 1)).replaceWith($("#sec_" + secNum));
			//$("#sec_" + secNum + " .background_stretch .background_stretch_bg").removeClass("bgColor1");
			//$("#sec_" + secNum + " .background_stretch .background_stretch_bg").removeClass("bgColor2");
			if ((i + 1)%2 == 0)
			{
				//$("#sec_" + secNum + " .background_stretch .background_stretch_bg").addClass(color1);
			}
			else
			{
				//$("#sec_" + secNum + " .background_stretch .background_stretch_bg").addClass(color2);
			}			
			$("#sec_" + secNum + " .testQuesLabel").html(localiseString('test_question') + " " + (i + 1) + " " + localiseString('test_of') + " " + document.assessTotalQues);
		}
		setTabIndex(); /* 20180501 Accessibility Reapply tab index when assessment is randomised */
		for (var k = (document.testIntroSubsection + 1); k < document.testResultsSubsection; k++)		
		{		
			if (!document.assessAttempted)
			{
				$("#sec_"+k).css("display","none");
			}	
		}
		var nextSection = document.assessRandomQuesArr[0];
		/* randomise assessment question options */
		if(document.assessOptRandomize){			
			$(".testQues:eq(0) .grid .container .optionHolder").not('.optionsNoRand').shuffleOptions('.qOption');
			
			setTabIndex(); // 20221710 Updated tab order when options are randomised
		}
		$('.testQues:eq(0)').show()
	}
	else if (currClassName.indexOf('testQues') != -1) {
		/* test question */
		/* ensure current test question number is not lost in fast scrolling */		
		var tempCurrQues = $("#sec_" + n + " .testQuesLabel").html().split(" ")[1];
		if (document.currentAssessQues != tempCurrQues) {
			document.currentAssessQues = tempCurrQues;
		}
		var nextSection = document.assessRandomQuesArr[document.currentAssessQues];
		
	} else if(currClassName.indexOf('preTopicTest') != -1){ // Is this the start of a topic test-out
		
		if($("#sec_"+n).hasClass("breaker")){
			document.currentTopic = Number($("#sec_"+n).index(".breaker"))+1;
		}
		// if user decides to take the topic test-out, show the first question from the bank
		if(document.takeTopicPreTest){
			for(var i = 0; i != document.preQuesArr[document.currentTopic-1].length; i++){

				var secNum = document.preQuesArr[document.currentTopic-1][i];
				$("#test"+document.currentTopic+"Ques" + (i + 1)).replaceWith($("#sec_" + secNum));
				
				$("#sec_" + secNum + " .topicTestLabel").html(localiseString('test_question') + " " + (i + 1) + " " + localiseString('test_of') + " " + Number(document.preSelectQuesArr[document.currentTopic-1]));
			}
			
			document.currentPreQues = 1;
			
			var nextSection = document.preQuesArr[document.currentTopic-1][0];
			
		}else{ // if user skips test-out show first page of section/topic content
			var tempArr = document.preQuesArr[document.currentTopic-1].sort(function(a, b){return a-b});
			var nextSection = Number(tempArr[tempArr.length-1])+2;
		}
		//console.log("nextSection = " + nextSection)
		// topic pre test intro
	}else if(currClassName.indexOf('preTopicQues') != -1){ // Is this a topic test-out question
		
		// topic pre test question
		
		var totalTopicQs = Number(document.preSelectQuesArr[document.currentTopic-1]);
		
		if(document.currentPreQues == totalTopicQs){ // last question so show results page
			var tempArr = document.preQuesArr[document.currentTopic-1].sort(function(a, b){return a-b});
			var nextSection = Number(tempArr[tempArr.length-1])+1;
			document.lastPreQues = true;
			calcTopicTest(document.currentTopic,totalTopicQs); // calculate test-out result
		}else{
			
			if(document.autoFailTopicTest){ // if autoFailTopicTest and user answers incorrectly go straight to results page
				if(document.answeredCorrect){
					var nextSection = document.preQuesArr[document.currentTopic-1][document.currentPreQues];
					document.currentPreQues ++;
			   }else{
				   	var tempArr = document.preQuesArr[document.currentTopic-1].sort(function(a, b){return a-b});
					var nextSection = Number(tempArr[tempArr.length-1])+1;
					document.lastPreQues = true;
					calcTopicTest(document.currentTopic,totalTopicQs);
			   }
				
			}else{
				// show next question
				var nextSection = document.preQuesArr[document.currentTopic-1][document.currentPreQues];
				document.currentPreQues ++;
			}
		}
		
		
	}
	else {		
		if (((Number(n) + 1) != document.testIntroSubsection) || $('#sec_'+ document.assessRandomQuesArr[0]).css('display')==='none')
		{
			var nextSection = Number(n) + 1;		
		}		
	}
	// section topic test-out
	if(document.skipTopicTest){
		var prevSection = $('#sec_'+ n);
	}
	else{
		if(document.lastPreQues){// section topic test-out
			var prevSection = $('#sec_'+ n);
		}else{
			var prevSection = $('#sec_'+ nextSection).prev('.section');
		}
	}
	//
	if ((document.testIntroSubsection != null) & (nextSection == document.subsectionCount))
	{
		prevSection = $('#sec_'+ document.assessRandomQuesArr[document.assessRandomQuesArr.length - 2]);
	}
	
	//document.nextSection = nextSection;
	
	//console.log("prevSection = " + $(prevSection).attr("id"));
	
	if(prevSection.css('display')==='block'){
		/* updated unlock code to handle when screen is fullscreen and therefore scroll not working */
		var className = $('#sec_'+ nextSection).attr("class");
		//console.log("className = " + className)
		if(className != undefined){
			if(className.indexOf('breaker') == -1){
				
				for(var i=nextSection; i<= document.lockedArr.length; i++){
					if(!$('#sec_'+ (i)).hasClass('breaker') || $('#sec_'+ (i)).hasClass('testResults') ){
						if(!$('#sec_'+ i).is('.testQues:eq(0)') || !$('#sec_'+ i).is('.preTopicQues:eq(0)')){
							/* pre-test no topics associated with questions support kgs 03/18/22 */
							/* if a question is answered incorrectly then show the pre-test results */
							if (document.pretestAnsIncorrect)
							{
								$('#sec_'+ document.testResultsSubsection).css('display', 'block')
								document.pretestAnsIncorrect = false;
							}	
							else
							{
								$('#sec_'+ i).css('display', 'block')
							}	
						}
					}
					if(document.lockedArr[i-1] == 0 && !$('#sec_'+ (i)).hasClass('breaker')){
						$('#sec_'+ (i)).css('display','block');
					}else{
						break;
					}
				}
					//console.log("nextSection = " + nextSection)
				$('#sec_'+ nextSection +' .grid .h2_inner').css({ 
					opacity:1
				});			
				var nextElem = ('#sec_'+ nextSection +' .grid .h2_inner').split(".h2_inner");
				nextElem = nextElem[0] + ".grid_inner";
				$(nextElem).css({ 
					opacity:1
				});
				$('#sec_'+ nextSection +' .grid .h2_inner').next().css({ 
					opacity:1
				});
				checkBoxInView(nextSection)
			  //20190917 desktop portrait fix
				
				
					var cNext = $('#sec_'+ nextSection).hasClass("cNext");
					if(cNext){
						//console.log("nextSection = " + nextSection)
						if(nextSection != document.subsectionCount){
							$('.topic_nav_bar').css('display','block');
							$('#right_nav').removeClass('locked');
						}
					}
				
					if(document.hasBranches){
						if($('#sec_'+ n).hasClass("endBranch")){
							doBranchCompletion();
						}
					}
				
				}else{
					//console.log("nextSection = " + nextSection)
					if(nextSection != document.subsectionCount){ // 20200708 fix for 1 page topics
						$('.topic_nav_bar').css('display','block');
						if(document.lockedArr[n-1]){
							$('#right_nav').removeClass('locked');
						}
					}
					
					if(document.hasBranches){
						if($('#sec_'+ n).hasClass("endBranch")){
							doBranchCompletion();
						}
					}
				}
		}else{
			
		}
		
		/* Updated unlock code to handle when screen is fullscreen and therefore scroll not working */	
		//console.log("nextSection = " + nextSection)
		document.nextSection = nextSection;
	}else{
		//console.log("hello")
		//console.log("nextSection = " + nextSection)
		setTimeout(function(){
			//$('#sec_'+ nextSection).css('display', 'block')
		},1500);
	}
	if(document.lockedArr[(n-1)] === 1 && !$('#sec_'+ Number(n)).next('.section').hasClass('breaker')){
	var prevSec = '#'+($('#sec_'+ Number(n)).prev('.section').attr('id'))
	//$(prevSec+' .complete_arrow').fadeOut();
	$('#sec_'+ Number(n)+' .complete_arrow').addClass('unlocked');
	}
	if($('#sec_'+n).next('.section').hasClass('breaker')){
		//$('#sec_'+ (Number(n)-1)+' .complete_arrow').fadeOut(); /* fadeout down arrow on at end of topic */
	}
	document.topic_complete.push(1)
	progress(n)
	unlockTopic(n);	
	if(isAndroidTablet || isAndroidPhone || isMacChrome){
			$('html,body').scrollTop(windowTop -1)
	}
	
	getSliderHeight() // slider height fix
	rePosHotSpots();
	
	if(document.hasBranches){
		if($('#sec_'+ n).hasClass("endBranch")){
			doBranchCompletion();
		}
	}
    
    //20190205 Added to reset the course tracking when user fails assessment 3 times, forcing user back through the course
	/* ensure to not reset the course after exiting the pre-test 060622 */
    if((document.currentSection == document.testResultsSubsection) && (document.assessAttempts == document.maxAssessAttempts) && (document.assessAttempts != 0)){
		
		var lesson_status = actionsLMSGetLessonStatus();
					
		if(lesson_status != "completed" && lesson_status != "passed"){
			//alert("HI!");
			resetCourse();
		}
    }
	
	//20221017 Fix for JAWs to move to next question in assessment
	if (currClassName.indexOf('testQues') != -1) {
		
		// 20221128 fix for different option feedback with assessment review 
		if (currClassName.indexOf('diff_feedback') == -1){
			/* 20221020 ensure assessment question immediate feedback is focused on for screen reader */
			if(!document.showAssessFeedback && !document.showImmediateAssessFeedback){
				setTimeout(function(){
				$("#sec_" + (document.nextSection) + " .question_leadin").focus();

				},10);
			}
		}
	}

	/* 20230427 hide nav when pre-test has been taken */
	if ((document.pretestPresent == 1) && (document.pretestAttempted == 1) && (document.topicsPretestedOut.indexOf("1") != -1)){
		$('#right_nav').hide();
		$('#left_nav').hide();
		$('#home_nav').addClass("pretest");
		$('.nav_instruction .instruction').html(test_intro_dat['pre_test_nav'][0].home_only);	
	}

	/* completed test message and test lock-out 2023 */
	var lesson_status = actionsLMSGetLessonStatus();
	var passScoreObtained = false;
	if (document.pretestThisSession)
	{
		if (document.assessPercentageScore == document.preTestPassmark)
		{
			passScoreObtained = true;
		}
	}
	else
	{
		if (document.assessPercentageScore >= document.assessPassmark)
		{
			passScoreObtained = true;
		}
	}
	if (((lesson_status==lms_pass_status1) || (lesson_status==lms_pass_status2) || passScoreObtained) && document.showAssessCompleteMsg)
	{
		if ($('#sec_'+ document.testResultsSubsection).css('display') != 'block')
		{
			$('.testStart h2').html(test_intro_dat['post_test'][0].test_complete_title);
			$('.testStart .content_text').html(test_intro_dat['post_test'][0].test_complete_msg);
			$('.testQues:eq(0)').hide();
		}
	}
	
	/* completed test message and test lock-out 2023 */
	if (document.currentSection == document.testResultsSubsection)
	{
		if (!document.takingPretest)
		{
			document.pretestThisSession = false;
		}
	}
}