/* functions to handle preliminary tasks such as loader, bookmark and setting up menu and screens */

$( document ).ready(function() {

	gotoBookmark = function(){
		/* topic bookmarking */
		positionIndex()
		if(document.lesson_location == false || document.lesson_location == 'false'){
			document.lesson_location = '#topic_intro+0';
		}
		if (document.lesson_location.toString().indexOf("#topic_intro") > -1){
			var topic_num = document.lesson_location.split('+')[1]
			var topic = document.lesson_location.split('+')[0]
			$('.breaker').eq(topic_num).css('display','block')
			currentSec = topic_num
		}
		if(document.lesson_location.toString().indexOf("#topic_intro") === -1 && document.lesson_location != '%23sec_1'){
			if(document.lesson_location.indexOf('%23') != -1){
				document.lesson_location = document.lesson_location.replace("%23", "#");
			}
			var newScreen = document.lesson_location;
			
			if((typeof(LMSAPI)=="undefined")){									
			}else{
				/* test out: if there is a pre-test in the course */
				if (document.pretestPresent == 1)
				{
					/* test out: store a bookmark if the pre-test has been attempted and it is not currently being taken */
					if ((document.pretestAttempted == 1) && (!document.takingPretest))
					{
						doBookMark(newScreen);
					}
				}	
				else {
					doBookMark(newScreen);
				}	
			}
			hideLoader()
			var screenNum = Number(document.lesson_location.split('_')[1]);
			if ($(document.lesson_location.toString()).hasClass("breaker")) {
				currentSec = $(document.lesson_location).index('.breaker')
			}else{
				var secParent = $(document.lesson_location.toString()).prevAll('.breaker').attr('id')
				currentSec = $('#'+secParent).index('.breaker')
				unlockTopic()
			}
			/* added fix to scroll to bookmark on devices */
		}else{
			hideLoader()	
		}
		$('.index_banner_holder').css('display','none');
		positionIndex()
		setUpMenu()
		pagesFromBookmark()
		removeMenuTabIndex(); // remove menu tab functionality
		setTabIndex(); // 20221018 QA fix for tabbing to buttons when resource/hotword popup visible
		setNavTab(); // set Nav tab functionality
		$(newScreen).focus();
		
		/* 20220630 Accessibility Update */
		// set focus to title or content, when returning from bookmark		
		$(newScreen).find('.page_start').focus();
		// set focus to title or content, when returning from bookmark
		
		/*
		// set focus to title or content, when returning from bookmark
		var focusBeenSet = false;
		$(newScreen).find('.h2_inner').each(function(index, element) { 
			$(this).focus();
			focusBeenSet = true;
		});
		if(!focusBeenSet){
			$(newScreen).find('.content_text').each(function(index, element) { 
				$(this).focus();
				focusBeenSet = true;
			});
		}
		// set focus to title or content, when returning from bookmark
		*/
		
		/* only enable scrolling if an error popup is not showing */	
		if (!document.errorMessagePresent)
		{
			$('html, body').css('overflow','visible');
		}	
		//20190917 desktop portrait fix
		portraitTestFix();
	}	
	var delay_loader = false
	hideLoader = function(){
		if(document.pretestPresent == 1 && delay_loader == true){
			$('#topic_loader').show()
			setTimeout(function(){
			//$(".topic_index").addClass('displayBlock')
			$('.topic_index').css('display', 'block'); 
			$('#topic_loader').hide()
			},1000)
		}else{
			if(document.showMenuOnLaunch){ // LJ 20190211 hae the homescreen/menu configurable
			     //$(".topic_index").addClass('displayBlock');
				 $('.topic_index').css('display', 'block'); 
            }else{
                index = false;
                topic_height();
                $('.topic_index').css('display', 'none'); 
                if(document.lesson_location == ""){
                    gotoTopic('topic_select');
                }
                //$(".sec_rest_wrapper").css({'margin-top':'-64px'}) // LJ Updated so content starts under banner LJ//
            }
		}
		$(".bar_robot").css('display', 'block')
		var loaderVisible = ($(".screen_loader").css("display") == "block");
		if(loaderVisible){
			/*if((typeof(LMSAPI)=="undefined")){									
			}else{
				if(typeof(LMSAPI)!="undefined"){
					if(document.audioLocked){
					}else{
					}
				}
			}*/
			/* show API not found error message if course launched from wbtframe.html or index_dynamic.html which uses en if no language is available to obtain */
			/* also ensures to not hide other error messages on launch of course */
			if (!document.errorMessagePresent) {
				boxClose();
			}
			if ((!document.errorMessagePresent) && (!document.errorNotifyPresent))
			{
				$('.screen_loader').css('display', 'none');
				topic_height()
				$('html, body').css('overflow','visible')
				if(!isWeb){
					setTimeout(function() {topic_height()}, 500)
				}else{
					setTimeout(function() {topic_height()}, 10)
				}
				getSliderHeight(); // slider height fix
				/* transitions: fade in topics one at a time */
				displayMenu();
				/* close button is always hidden */
				/*if(isWeb){
					$(".topic_index .bar_close").addClass('displayBlock');
					$(".bar_close").addClass('displayBlock');
				}*/
				rePosHotSpots();
				markTopicQsViewed();
				
				/* custom branching based on CITI070 */
				/*if(document.hasBranches){
					branchDone();
				}*/
			}	
		}	
		
		
	}

	function positionIndex(){
		$('.topic_nav_bar').css({'display':'none' });
		/*if(isWeb){
			$('.topic_index').addClass('loading index_book');
			//$(".topic_index").css({"position":"fixed","top":"-2000px"})
		}else{
			//$('.topic_index').removeClass('displayBlock')
			$('.topic_index').css('display', 'none'); 
			$('.topic_index').hide()
		}*/
		$('.topic_index').css('display', 'none'); 
			$('.topic_index').hide()
	}

	function pagesFromBookmark(){
		nav = true
		op=null
		videoorimage(nav, op)
		index = false
		relaunch=true;
		topicTitle()
		addSuspendData()
		var sec = $('.section').eq((document.trackingArr.indexOf("0")-1))
		topic_book = sec.prevAll('.breaker').index('.section');
		oraginiseLocking()
		if(document.pretestPresent == 1 && document.takingPretest == true && (isiPhone || isAndroidPhone)){
			$('#topic_loader').show()
			setTimeout(function(){
				unlockPages(relaunch, topic_book)
				$('#topic_loader').hide()
			},1000)
		}else{
			unlockPages(relaunch, topic_book)
		}
		scrollTolastViewed()
		progress()
		lockNav()
		downButton()
		resizeCheckBox()
	}
	
	function scrollTolastViewed(){
		/* added fix to scroll to bookmark on devices */
		if(isWeb){
			$(window).scrollTop($(document.lesson_location).offset().top)
		}else{
			if(isiPad || isiPhone){
				if(window.top !== window.self) {
					$(parent.parent.document).scrollTop($(document.lesson_location).offset().top - 70); /* updated for extra frameset */
					$('.bar_robot').css('top',($(parent.parent.document).scrollTop())-1+'px'); /* updated for extra frameset */
					$(".bar_bot").removeClass('displayNone').addClass('displayBlock');
					$(".bar_robot").removeClass('displayNone').addClass('displayBlock');
				}else{
					$(window).scrollTop($(document.lesson_location).offset().top - 70);
					$('.bar_robot').css('top',0+'px');
					$(".bar_bot").removeClass('displayNone').addClass('displayBlock');
					$(".bar_robot").removeClass('displayNone').addClass('displayBlock');
				}
				
				/* fix issue with logo appearing in worng place when when returing to bookmark LJ 03/23/22*/
				$(window).scrollTop($(document.lesson_location).offset().top - 70);
				$('.bar_robot').css('top',0+'px');
				
			}else{
				$(window).scrollTop($(document.lesson_location).offset().top - 70);
				$('.bar_robot').css('top',0+'px');
			}	
		}
        
         //$(".sec_rest_wrapper").css({'margin-top':'-64px'}) // LJ Updated so content starts under banner LJ//
		
		seenTopicTest();
	}
		
	function setUpMenu(){
        
		var display_topic = false
		
		var suspend = actionsLMSGetSuspendData();
		var menuArr = suspend.split('|')[3].split('%')[0]; // Updated menu funcitonality due menu being section based
		suspend = suspend.split('_Data:')[1];
        suspend = suspend.split('|')[0];/* 20190102 Updated to track post-test attempts */
		for(i=0; i<$('.breaker').length; i++){
			var check_topic = ($('div.breaker:eq('+i+')').nextUntil($('div.breaker').eq(i+1)).length+1);
			for(j=$('div.breaker:eq('+i+')').index('.section'); j<$('div.breaker:eq('+(i+1)+')').index('.section'); j++){
				if (lms_type == "none")
				{
					display_topic = true;
				}
				else
				{
					if(suspend[j] === '1'){
					display_topic = true
					}else{
						display_topic = false
					}
				}	
			}
			if(display_topic === true){
				/* test out: if there is no pre-test in the course */
				if (document.pretestPresent == 0)
				{                    
                    $('.burger_select .overlay').eq(i+1).css('display', 'none');
					$('.burger_select:eq('+(i+1)+') img').attr('src', 'images/custom_int/burger_unlocked.png');
					$('.burger_select:eq('+(i+1)+') img').attr('title', localiseString('topic_start'));
					$('.burger_select:eq('+(i+1)+') img').attr('alt', localiseString('topic_start'));
				}	
			}
		}
		
		// Updated menu funcitonality due menu being section based
		for(var i = 0; i != menuArr.length; i++){
		 
			if(menuArr[i] == 1){
				$('.topic_select .overlay').eq(i+1).css('display', 'none');
				$('.select_bottom:eq('+(i+1)+') img').attr('src', 'images/custom_int/topic_launch.png');
				$('.select_bottom:eq('+(i+1)+') img').attr('title', localiseString('topic_start'));
				$('.select_bottom:eq('+(i+1)+') img').attr('alt', localiseString('topic_start'));

			}
		}
		
		launchHover();
		/* close button is always hidden */
		/*if(!isWeb){
			$('.bar_close').css('display','none');
			$('.topic_index .bar_close, .bar_close').css('display','none');
		}else{
			$('.bar_close').css('display','block !important');
			$('.topic_index .bar_close').css('display','block');
		}*/
		
	}
		
	checkBookmarkNavReady = function(){
		var lesson_status = actionsLMSGetLessonStatus();
		if ((lesson_status==lms_pass_status1) || (lesson_status==lms_pass_status2))
		{
			$('.attestation_btn_div .retake_assess_btn').hide();
			$('.attestation .content_text').html('<p class="lgTitleSubText">' + attestation_dat['attestation'][0].attested_msg + '</p>');
			/* completed test message and test lock-out 2023 */
			if (document.showAssessCompleteMsg)
			{
				$('.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();
			}
			else
			{				
				//$('.testStartSec h1').html(test_intro_dat['post_test'][0].title);
				$('.testStart h2').html(test_intro_dat['post_test'][0].title);
				$('.testStart .content_text').html(test_intro_dat['post_test'][0].generic_msg);
			}
		}
		else
		{
			$('.attestation .content_text').html('<p class="lgTitleSubText">' + attestation_dat['attestation'][0].pre_attesting_msg + '</p>');
			/* completed test message and test lock-out 2023 */
			//$('.testStartSec h1').html(test_intro_dat['post_test'][0].title);
			$('.testStart h2').html(test_intro_dat['post_test'][0].title);
			$('.testStart .content_text').html(test_intro_dat['post_test'][0].generic_msg);
		}
		loaderPercent = loaderPercent + 5;
		writeLoaderInfo("%"+loaderPercent)
		if((typeof(LMSAPI)=="undefined")){
			document.lesson_location = "";
			document.lesson_location_retrieved = true;
		}
		if (document.lesson_location_retrieved==true){	
			loaderPercent = "100";
			writeLoaderInfo("%"+loaderPercent)
			clearInterval(bookmarkInterval);				
			/* test out: if there is a pre-test in the course */
			if (document.pretestPresent == 1)
			{
				/* test out: show the pre-test bookmark popup if pre-test has not yet been attempted */	
				if (document.pretestAttempted == 0) {
					document.trackingArr[0] = "1";
					for (var k = 1; k < document.subsectionCount; k++) {
						document.trackingArr[k] = "0";
					}	
					/* pre-test no topics associated with questions support kgs 03/18/22 */
					if (document.topicPreTest)
					{
						document.lesson_location = "#sec_" + (document.testIntroSubsection - 1);
					}
					else
					{
						document.lesson_location = "#sec_" + document.testIntroSubsection;
					}	
					/* test out: do not bookmark the pre-test upon leaving it */
					document.pretestDone = false;						
				}	
			}	
			if (document.lesson_location == ""){
				document.bookmarkNavDone = true;
				hideLoader();
			}else{
				document.bookmarkNavDone = true;
				boxPop(null,'bookmark');
			}
		}else{
			document.lesson_location = "";
			clearInterval(bookmarkInterval);
			hideLoader();
		}
		$(".bookmark_nav_start").bind("click", function() {
			/* custom branching based on CITI071: Module 6: common topic, a branching topic with branching screentype, two branches, no assessement 2023 */
			/* if a branch was previously selected in a session, enable the Home buttons on launch */
			if(document.hasBranches){
				if(document.userBranch != 0){
					$('.home').css("opacity","1")
					$('.home').css("pointer-events","auto")
					$('#home_nav').css("opacity","1");
					$('#home_nav').css("pointer-events","auto")
				}
			}
			/* test out: if there is a pre-test in the course */
			if (document.pretestPresent == 1)
			{
				/* test out: mark the pre-test as having been attempted if the pre-test is cancelled */
				if(document.pretestAttempted == 0 && (isiPhone || isAndroidPhone)){
					delay_loader = true
				}
				document.pretestAttempted = 1;
				recordPercentComplete(1, document.subsectionCount, false);
				
				/* 20230502 Fix to randomise assessment when deciding to skip pre-test*/
				document.randomizeAssessment();
			}				
			if(!isWeb){
				//deviceAudio();
			}
            
            var display_topic = true; // LJ 20190215
            
			/*$('.topic_index').css({ 'bottom': '0', 'opacity': '1', 'display':'block' });*/			
			var suspend = actionsLMSGetSuspendData();	
			var menuArr = suspend.split('|')[3].split('%')[0]; // Updated menu funcitonality due menu being section based
			suspend = suspend.split('_Data:')[1];
            suspend = suspend.split('|')[0];/* 20190102 Updated to track post-test attempts */
			for(i=0; i<$('.breaker').length; i++){
				var check_topic = ($('div.breaker:eq('+i+')').nextUntil($('div.breaker').eq(i+1)).length+1);
				for(j=$('div.breaker:eq('+i+')').index('.section'); j<$('div.breaker:eq('+(i+1)+')').index('.section'); j++){
					if (lms_type == "none")
					{
						display_topic = true;
					}
					else
					{
						if(suspend[j] === '1'){
							display_topic = true
						}else{
							display_topic = false
						}
					}	
				}
                
				if(display_topic === true){
					/* test out: if there is no pre-test in the course */
					if (document.pretestPresent == 0)
					{
                        
                        $('.burger_select .overlay').eq(i+1).css('display', 'none');
                        $('.burger_select:eq('+(i+1)+') img').attr('src', 'images/custom_int/burger_unlocked.png');
                        $('.burger_select:eq('+(i+1)+') img').attr('title', localiseString('topic_start'));
                        $('.burger_select:eq('+(i+1)+') img').attr('alt', localiseString('topic_start'));
					}	
				}
			}
			
			launchHover();
			if ($(document.lesson_location.toString()).hasClass("breaker")) {
				currentSec = $(document.lesson_location).index('.breaker')
			}else{
				/*currentSec = $('#'+secParent).index('.breaker')*/				
			}
			relaunch=true;			
			var sec = $('.section').eq((document.trackingArr.indexOf("0")-1))
			topic_book = sec.prevAll('.breaker').index('.section');
			//console.log(topic_book)
			index = true
			addSuspendData()
			oraginiseLocking()
			unlockPages(relaunch)			
			progress()
			lockNav()
			hideLoader(); 
			topic_height() /* fix for iPad menu position issue */
			
            if(document.showMenuOnLaunch){ // LJ 20190211 hae the homescreen/menu configurable
                 $(".sec_rest_wrapper").css('display', 'none');
			     
             }else{
                 //topic_height();
                 $('.topic_index').css('display', 'none'); 
				 //gotoBookmark();
                 index = false
                 currentSec = 0;
                 gotoTopic('topic_select');
			     getSliderHeight(); // slider height fix
				 rePosHotSpots();
             }
		});		
		$(".bookmark_nav_resume").bind("click", function() {
			/* custom branching based on CITI071: Module 6: common topic, a branching topic with branching screentype, two branches, no assessement 2023 */
			/* if a branch was previously selected in a session, enable the Home buttons on launch */
			if(document.hasBranches){
				if(document.userBranch != 0){
					$('.home').css("opacity","1")
					$('.home').css("pointer-events","auto")
					$('#home_nav').css("opacity","1");
					$('#home_nav').css("pointer-events","auto")
				}
			}
			/* test out: if there is a pre-test in the course */
			if (document.pretestPresent == 1)
			{
				/* test out: if the pre-test has not been attempted set initial variables for pre-test */
				if (document.pretestAttempted == 0)
				{
					$('.testStartSec h1').html(test_intro_dat['pre_test'][0].title);
					$('.testStart h2').html(test_intro_dat['pre_test'][0].subtitle);
					$('.testStart .content_text').html(test_intro_dat['pre_test'][0].generic_msg);
					$('.bar_robot .home').css('visibility','hidden');
					$('.bar_robot .page').css('visibility','hidden');
					/* pre-test no topics associated with questions support kgs 03/18/22 */
					$('.bar_robot .switchLang').css('visibility','hidden');
					$('.bar_robot .menu_title').css('margin-left','38px');
					/* test out: mark the pre-test as having been attempted and also that the pre-test is being currently taken */
					document.pretestAttempted = 1;
					document.takingPretest = true;
					recordPercentComplete(1, document.subsectionCount, false);
					
					setTimeout(preTestStart,250);
				}
			}
			if(!isWeb){
					//deviceAudio();
				}
			$('.topic_index').css('display', 'none'); 
				gotoBookmark();
			getSliderHeight(); // slider height fix
			rePosHotSpots();
			setTimeout(checkTopicTest,250);
			
			$(window).trigger('scroll');
			
		});
		
		
		$('.bookmark_nav_resume').keypress(function (e) {
			if (e.keyCode == 13 || e.keyCode == 32) {
				
				$(this).trigger('click');
			}		
		});	
		$('.bookmark_nav_start').keypress(function (e) {
			if (e.keyCode == 13 || e.keyCode == 32) {
				
				$(this).trigger('click');
			}		
		});
		
		
	}
		
	showBookmarkNav = function(){
		if(bookmarkInterval){
			clearInterval(bookmarkInterval)
			bookmarkInterval = false;
		}
		bookmarkInterval = setInterval(checkBookmarkNavReady,500);
	}	
		
	setSections = function (o){
		loaderPercent = loaderPercent + 5;
		writeLoaderInfo("%"+loaderPercent)	
		firstloaded = true;
		checkCourseCompletion()
		if (!document.bookmarkNavDone) {
			showBookmarkNav();
		}
	}

	resetBinds = function (o){
		loaderPercent = loaderPercent + 5;
		writeLoaderInfo("%"+loaderPercent)
		setSections(o);
	}

	newOrientation = function(){
		loaderPercent = loaderPercent + 5;
		writeLoaderInfo("%"+loaderPercent)
		resetBinds(orient);
	}
	
	initialOrientation = function (){
		loaderPercent = loaderPercent + 5;
		writeLoaderInfo("%"+loaderPercent)
		newOrientation();
	}

	setUpScreens = function (){
		loaderPercent = loaderPercent + 5;
		writeLoaderInfo("%"+loaderPercent)
		//if(isWeb || isiPad || isAndroidTablet){					
			setTimeout(initialOrientation,1000);
		//}
	}	
})