/* 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 {
			/* test-downs and section assessments 2025 */
			if (!$('#sec_'+ n).hasClass('sectionAssessQues') && !$('#sec_'+ n).hasClass('testDownQues')) {
				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 ++;
			}
		}

	/* test-downs and section assessments 2025 */
	} else if ((currClassName.indexOf('testDownIntro') != -1) || (currClassName.indexOf('testDownQues') != -1) || (currClassName.indexOf('sectionAssessIntro') != -1) || (currClassName.indexOf('sectionAssessQues') != -1)) {
		// do nothing
	}
	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 */
							/* client testing requirements 2024: */
							/* must answer all questions in course-level (no topics associated) pre-test */
							/* client testing requirements 2024: */
							/* if enough questions are answered incorrectly that the learner can no longer pass the pre-test then show the pre-test results */
							/* client testing requirements 2024 v2.3: */
							/* if the learner answers enough questions incorrectly that they can no longer pass the test-out, they must be informed that they have failed the test-out and be given the option to finish the test-out or proceed to the content */
							if (document.pretestAnsIncorrect)
							{
								var totalQCorrOrNotAns = document.assessTotalQues - document.pretestAnsIncorrectTotal;
								var totalQNeededToPass = Math.round(document.assessTotalQues * (document.preTestPassmark / 100));
								if (totalQCorrOrNotAns < totalQNeededToPass) {
									if (i == document.testResultsSubsection) {
										document.pretestAlreadyFailed = true;
										$('#sec_'+ document.testResultsSubsection).css('display', 'block');
										/* show resources and switch language when fail pre-test 100824 */
										/* v6 template: client learning design specs 2025 v5.4: navigation tips button and popup */
										if (document.showResourcesButton) {
											if (document.hideResourcesButtonDisclaimer) {
												if (document.trackingArr[1] == 1) {
													$('.bar_robot .page').css('visibility','visible');
													$('.bar_robot .page').css('display','block');
												}
											}
											else {
												$('.bar_robot .page').css('visibility','visible');
												$('.bar_robot .page').css('display','block');
											}
										}
										if(document.isMultiSco){
											$('.bar_robot .switchLang').css('visibility','visible');
											$('.bar_robot .switchLang').css('display','block');
										}
										/* v6 template: client learning design specs 2025 v5.4: navigation tips button and popup */
										$('.bar_robot .nav_tips').css('visibility','visible');
										$('.bar_robot .nav_tips').css('display','block');
										document.pretestAnsIncorrect = false;
									}
									else if (document.pretestAlreadyFailed) {
										$('#sec_'+ i).css('display', 'block');
										document.pretestAnsIncorrect = false;
									}
									else {
										document.pretestContinueQues = i;
										/* client learning design specs 2025 v4.3 */
										$('#sec_' + document.testResultsSubsection + ' .assessTitle').html('');
										$('#sec_' + document.testResultsSubsection + ' .assessTitle').attr('data-tab', $('#sec_' + document.testResultsSubsection + ' .assessTitle').attr('tabindex'));
										$('#sec_' + document.testResultsSubsection + ' .assessTitle').attr('tabindex', -1);
										$('#sec_' + document.testResultsSubsection + ' .result_left .content_text').html('<p class="lgTitleSubText">' + test_results_dat['pre_test'][0].fail_msg_4 + '</p>');
										$('#sec_' + document.testResultsSubsection).css('display', 'block');
										/* client learning assessment specs 2025 v2.8 */
										/*$('#continue_pretest_btn_div_' + document.testResultsSubsection).show();*/
										/* client learning design specs 2025 v5.2 */
										/* v6 template: client learning design specs 2025 v5.4: change Review Content to Continue when answer too many test-out questions incorrectly */
										/*$(".home_assess_btn").html(localiseString('continue_button'));*/
										document.pretestAnsIncorrect = false;
									}
								}
								else {
									if (i == document.testResultsSubsection) {
										document.pretestAlreadyFailed = true;
										/* show resources and switch language when fail pre-test 100824 */
										/* v6 template: client learning design specs 2025 v5.4: navigation tips button and popup */
										if (document.showResourcesButton) {
											if (document.hideResourcesButtonDisclaimer) {
												if (document.trackingArr[1] == 1) {
													$('.bar_robot .page').css('visibility','visible');
													$('.bar_robot .page').css('display','block');
												}
											}
											else {
												$('.bar_robot .page').css('visibility','visible');
												$('.bar_robot .page').css('display','block');
											}
										}
										if(document.isMultiSco){
											$('.bar_robot .switchLang').css('visibility','visible');
											$('.bar_robot .switchLang').css('display','block');
										}
										/* v6 template: client learning design specs 2025 v5.4: navigation tips button and popup */
										$('.bar_robot .nav_tips').css('visibility','visible');
										$('.bar_robot .nav_tips').css('display','block');
									}
									$('#sec_'+ i).css('display', 'block');
									document.pretestAnsIncorrect = false;
								}
							}
							else {
								if (i == document.testResultsSubsection) {
									document.pretestAlreadyFailed = true;
									/* show resources and switch language when fail pre-test 100824 */
									/* v6 template: client learning design specs 2025 v5.4: navigation tips button and popup */
									if (document.showResourcesButton) {
										if (document.hideResourcesButtonDisclaimer) {
											if (document.trackingArr[1] == 1) {
												$('.bar_robot .page').css('visibility','visible');
												$('.bar_robot .page').css('display','block');
											}
										}
										else {
											$('.bar_robot .page').css('visibility','visible');
											$('.bar_robot .page').css('display','block');
										}
									}
									if(document.isMultiSco){
										$('.bar_robot .switchLang').css('visibility','visible');
										$('.bar_robot .switchLang').css('display','block');
									}
									/* v6 template: client learning design specs 2025 v5.4: navigation tips button and popup */
									$('.bar_robot .nav_tips').css('visibility','visible');
									$('.bar_robot .nav_tips').css('display','block');
								}
								$('#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);
			}
		}
	}

	/* 20240319 pre-test that appears after first topic */
	/* 20230427 hide nav when pre-test has been taken */
	if ((document.pretestPresent == 1) && (document.pretestAttempted == 1) && (document.topicsPretestedOut.indexOf("0") != -1) && (document.topicsPretestedOut.indexOf("1") != -1)){
		/* client testing requirements 2024: */
		/* 80% pass for course-level (no topics associated) pre-test */
		if (document.takingPretest) {
			$('#right_nav').hide();
			$('#left_nav').hide();
			$('#home_nav').addClass("pretest");
		}
		/* client testing requirements 2024: */
		/* 80% pass for course-level (no topics associated) pre-test */
		/* $('.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)
	{		
		/* client learning design specs 2025 v4.3 */		
		if ($('.noTestTrainCompSec').length != 0)
		{
			$('.noTestTrainCompSec h2').html(test_intro_dat['post_test'][0].test_complete_title);
			$('.noTestTrainCompSec .content_text').html(test_intro_dat['post_test'][0].no_test_complete_msg);
			/* v6 template: client learning design specs 2025 v5.4: do not show Review Content button and show burger Menu button on test-out and final assessment passed results */
			/*$(".home_assess_btn").html(localiseString('home_assess_button'));
			$('#home_assess_btn_div_' + document.subsectionCount).show();*/
		}	
			
		if ($('#sec_'+ document.testResultsSubsection).css('display') != 'block')
		{
			$('.testStartSec h2').html(test_intro_dat['post_test'][0].title);
			$('.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();
			/* client learning design specs 2025 v4.3 */
			/* client learning design specs 2025 v5.2 */
			$(".home_assess_btn").html(localiseString('home_assess_button'));			
			/* client change edit to hide Review Content button on return after passing 05062025 */
			$('#home_assess_btn_div_' + document.testIntroSubsection).hide();
		}
	}
	
	/* completed test message and test lock-out 2023 */
	if (document.currentSection == document.testResultsSubsection)
	{
		if (!document.takingPretest)
		{
			document.pretestThisSession = false;
		}
	}
}