/* 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()	
		}
		positionIndex()
		setUpMenu()
		pagesFromBookmark()
		removeMenuTabIndex(); // remove menu tab functionality
		setNavTab(); // set Nav tab functionality
		$(newScreen).focus();

		/* 2021 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
		
		/* only enable scrolling if an error popup is not showing */	
		if (!document.errorMessagePresent)
		{
			$('html, body').css('overflow','visible');
		}
		/* menu visited state functionality 2018 */
		markTopicsVisited();	
		
		//20210318 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_loader').hide()
			},1000)
		}else{
			$(".topic_index").addClass('displayBlock')
		}
		$(".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');
				}*/
			}	
		}		
	}

	function positionIndex(){
		$('.topic_nav_bar').css({'display':'none' });
		if(isWeb && !isMacChrome){
			$('.topic_index').addClass('loading index_book');
			$(".topic_index").css({"position":"fixed","top":"0px"})
		}else{
			$('.topic_index').removeClass('displayBlock')
			$('.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()
		displayBadges()
		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); /* 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);
					$('.bar_robot').css('top',0+'px');
					$(".bar_bot").removeClass('displayNone').addClass('displayBlock');
					$(".bar_robot").removeClass('displayNone').addClass('displayBlock');
				}
			}else{
				$(window).scrollTop($(document.lesson_location).offset().top);
				$('.bar_robot').css('top',0+'px');
			}	
		}
	}
		
	function setUpMenu(){
		var display_topic = false
		
		var suspend = actionsLMSGetSuspendData();
		suspend = suspend.split('_Data:')[1];
		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)
				{
					if(document.hasSplashVideo){
						$('.topic_select .overlay').eq(i+2).css('display', 'none');
						/* menu visited state functionality 2018 */
						$('.select_bottom:eq('+(i+2)+') img').hover(function () {
							$(this).attr('src' ,'images/custom_int/topic_launch_rollover.png')
						});
						$('.select_bottom:eq('+(i+2)+') img').attr('title', localiseString('topic_start'));
						$('.select_bottom:eq('+(i+2)+') img').attr('alt', localiseString('topic_start'));
					}else if(document.hasBranches){
						$('.topic_select .overlay').eq(i+2).css('display', 'none');						
						/* menu visited state functionality 2018 */
						$('.select_bottom:eq('+(i+2)+') img').hover(function () {
							$(this).attr('src' ,'images/custom_int/topic_launch_rollover.png')
						});
						$('.select_bottom:eq('+(i+2)+') img').attr('title', localiseString('topic_start'));
						$('.select_bottom:eq('+(i+2)+') img').attr('alt', localiseString('topic_start'));
					}else{
						$('.topic_select .overlay').eq(i+1).css('display', 'none');
						/* menu visited state functionality 2018 */
						$('.select_bottom:eq('+(i+1)+') img').hover(function () {
							$(this).attr('src' ,'images/custom_int/topic_launch_rollover.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 .content_text_2').html('<p class="">' + attestation_dat['attestation'][0].attested_msg + '</p>');
		}
		else
		{
			$('.attestation .content_text .content_text_2').html('<p class="">' + attestation_dat['attestation'][0].pre_attesting_msg + '</p>');
		}
		$('.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";
					}
					/* trickle button functionality 2020 */
					/* go to the test topic intro when pre-test is selected */
					document.lesson_location = '#'+$('.testStartSec').attr('id');
					/* 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() {
			/* 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);
			}				
			if(!isWeb){
				deviceAudio();
			}
			/*$('.topic_index').css({ 'bottom': '0', 'opacity': '1', 'display':'block' });*/			
			var suspend = actionsLMSGetSuspendData();			
			suspend = suspend.split('_Data:')[1];
			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)
					{
						if(document.hasSplashVideo){
							$('.topic_select .overlay').eq(i+2).css('display', 'none');
							/* menu visited state functionality 2018 */
							$('.select_bottom:eq('+(i+2)+') img').hover(function () {
								$(this).attr('src' ,'images/custom_int/topic_launch_rollover.png')
							});
							$('.select_bottom:eq('+(i+2)+') img').attr('title', localiseString('topic_start'));
							$('.select_bottom:eq('+(i+2)+') img').attr('alt', localiseString('topic_start'));
						}else if(document.hasBranches){
							$('.topic_select .overlay').eq(i+2).css('display', 'none');							
							/* menu visited state functionality 2018 */
							$('.select_bottom:eq('+(i+2)+') img').hover(function () {
								$(this).attr('src' ,'images/custom_int/topic_launch_rollover.png')
							});							
							$('.select_bottom:eq('+(i+2)+') img').attr('title', localiseString('topic_start'));
							$('.select_bottom:eq('+(i+2)+') img').attr('alt', localiseString('topic_start'));
						}else{
							$('.topic_select .overlay').eq(i+1).css('display', 'none');
							/* menu visited state functionality 2018 */
							$('.select_bottom:eq('+(i+1)+') img').hover(function () {
								$(this).attr('src' ,'images/custom_int/topic_launch_rollover.png')
							});
							$('.select_bottom:eq('+(i+1)+') img').attr('title', localiseString('topic_start'));
							$('.select_bottom: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()
			displayBadges();
			lockNav()
			hideLoader(); 
			
			// 20200701 splash video functionality. Content screen has been viewed so do show splash video on menu
			if(document.hasSplashVideo){
				$(".splash_video_holder").css("display","none");
				$(".menu_content").css("display","block");
			}
			
			if(document.hasBranches){
				$(".branch_screen").css("display","none");
				$(".menu_content").css("display","block");
			}
			
			topic_height() /* fix for iPad menu position issue */
			$(".sec_rest_wrapper").css('display', 'none');
			/* menu visited state functionality 2018 */
			markTopicsVisited();			
		});		
		$(".bookmark_nav_resume").bind("click", function() {			
			/* 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)
				{
					$('.testStart .content_text').html(test_intro_dat['pre_test'][0].generic_msg);
					$('.bar_robot .home').css('visibility','hidden');
					$('.bar_robot .page').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);
				}
			}
			if(!isWeb){
					deviceAudio();
				}
			
			// 20200701 splash video functionality. Content screen has been viewed so do show splash video on menu
			if(document.hasSplashVideo){
				$(".splash_video_holder").css("display","none");
				$(".menu_content").css("display","block");
			}
			
			if(document.hasBranches){
				$(".branch_screen").css("display","none");
				$(".menu_content").css("display","block");
			}
			
			$('.topic_index').css('display', 'none'); 
				gotoBookmark();
			
			 
			getSliderHeight(); // slider height fix
		});
		
		
		$('.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);
		//}
	}	
})