/*
Copyright � Interactive Services 2013 - 2015 All Rights Reserved.  
No part of this code may be used, with or without modification, without prior consent from Interactive Services. 
Version 2.1, 01 March 2015
*/

$.fn.hasScrollBar = function() {
    return this.get(0) ? this.get(0).scrollHeight > this.innerHeight() : false;
}

function initPage() {

	$(".audioBtn").removeClass("finished");

	closeOpenComponent();

	//check if page links need to be changed for mobile
	if($("#wrapper").attr("mobilelinks") == "true") {
		if(isMobile() == true) {
			$("a").text('Link');
		}
	}

	//disable the menu button if the profiler has not been completed
	if(lmsVariables.profilerCompleted == "true") {
		var menuButton = $(".menuBtn > .menu");
		menuButton.removeClass("disable_cb");
	}

	$(".centreContentContainer").scrollTop(0);
	setTimeout(resizeWindowCheck, 100); //Needs a timeout because FF was lagging
	
	//Check if we are on a phone sized device
	onPhoneCourse = ($('.phonePanel').css("display").toLowerCase()=="table") ? true : false
	close_feedback_overlay(true);	

	if(scrollLock) {
		document.ontouchmove = function(event){
    		event.preventDefault();
		}
	}
	//clearVideos();
	
	if ($("#vimeoplayer").length) {
		var iframe = $('#vimeoplayer')[0];
		var player = $f(iframe);

    player.addEvent('ready', function() {
    	if($('.audioBtn').hasClass('paused')){
				player.api('setVolume', 0); 
			}else{
				player.api('setVolume', 1);
			}
    	player.addEvent('finish', onVideoFinish);
		});
	}

	if(courseAudio && audioAsked==1){
		setupPageAudio();
	}

	// if the branch screen, mark a variable to check if audio has already played, if so audio won't be played a second time
	if($("#wrapper").hasClass("branchCheck")) {
		if(lmsVariables.introAudioPlay == "false") {
			lmsVariables.introAudioPlay = "true";
		}
	}

	$("#displayError").addClass("invisible"); //Make sure any error messages are closed when you move to a new screen

  question_type = null;
	var progressNum = ($("#wrapper").hasClass("controlnav") || currentPage.type=="question" || currentPage.progess == 0 || currentPage.progress==undefined) ? 1 : 2
	
	// check on screen mk02_01_18.html if it's the last screen then go back to the branch page
	if(currentPage.src == "mk02_01_18.html" && currentPage.nextCheck == "true" && (lmsVariables.userProfile == "4" || lmsVariables.userProfile == "5" || lmsVariables.userProfile == "6" || lmsVariables.userProfile == "7" || lmsVariables.userProfile == "9")) {
		currentPage.next = "mk02_00_03.html";
	} else if(currentPage.src == "mk02_02_22.html" && currentPage.nextCheck == "true" && (lmsVariables.userProfile == "1")) {
		currentPage.next = "mk02_03_01.html";
	}
	
	if($(".accordian_slide").length){
		setUpAccordian();
	}
	if($(".spots").length) {
		hotspotPopRes();
	}
	if ($(".res").length) {
		hsQRes();
	}
	if ($(".image_reveal").length) {
		imgReveal();
	}
	
	if($(".gsAnimation").length){
		$(".gsAnimation").each(function(index) {
			run_gs_animation($(this));
		});
	}

	if($("#wrapper").data('screen_type')!= undefined && $("#wrapper").data('screen_type')== "slideshow"){
		setUpSlideShow()
	}else if($("#wrapper").data('screen_type')!= undefined && $("#wrapper").data('screen_type')== "content_navigator"){
		setUpContentNav()
	}else if($("#wrapper").data('screen_type')!= undefined && $("#wrapper").data('screen_type')== "multi_question"){
		setUpMultiQuestion()
	}else if($("#wrapper").data('screen_type')!= undefined && $("#wrapper").data('screen_type')== "scenario"){
		setUpScenario()
	}else if($("#wrapper").data('screen_type')!= undefined && $("#wrapper").data('screen_type')== "timeline"){
		setUpTimeline()
	}else if($("#wrapper").data('screen_type')!= undefined && $("#wrapper").data('screen_type')== "branch"){
  checkBranchScreen();
	}

	$("#transcriptHolder").scrollTop(0);
	if($("#transcript_text").length > 0){	
		$("#transcriptHolder").scrollTop(0).empty().html($("#transcript_text").html());
	}else{
		$("#transcriptHolder").scrollTop(0).empty().html(txt_label_noTranscript);
	}
	
	if($("#wrapper").attr("bgimage") != undefined){
		$("#centreContent").css("background-image", "url("+$("#wrapper").attr("bgimage")+")")
	}else{
		$("#centreContent").css("background-image", "none")
	}
	
	$("#centreContent").removeClass("bottom_left").removeClass("bottom_right").removeClass("top_left").removeClass("top_right").removeClass("timelineBG");
	if($("#wrapper").attr("bgalign") != undefined && $("#wrapper").attr("bgalign") == "bottom_right"){
		$("#centreContent").addClass("bottom_right")
	}else if($("#wrapper").attr("bgalign") != undefined && $("#wrapper").attr("bgalign") == "bottom_left"){
		$("#centreContent").addClass("bottom_left")
	}else if($("#wrapper").attr("bgalign") != undefined && $("#wrapper").attr("bgalign") == "top_left"){
		$("#centreContent").addClass("top_left")
	}else if($("#wrapper").attr("bgalign") != undefined && $("#wrapper").attr("bgalign") == "top_right"){
		$("#centreContent").addClass("top_right")
	}else if($("#wrapper").attr("bgalign") != undefined && $("#wrapper").attr("bgalign") == "timelineBG"){
		$("#centreContent").addClass("timelineBG")
	}else{
		$("#centreContent").addClass("bottom_left")
	}
	
	if($("#wrapper").attr("bgcolor") != undefined){
		$("#centreContent").css("background-color", $("#wrapper").attr("bgcolor"))
	}else{
		$("#centreContent").css("background-color", default_cc_color)
	}

	if($("#wrapper").attr("bgsize") != undefined){
		$("#centreContent").css("background-size", $("#wrapper").attr("bgsize"))
	}else{
		$("#centreContent").css("background-size", "initial");
	}

	if($("#wrapper").attr("examStart") != undefined && $("#wrapper").attr("examStart") =="on"){
		resetQuiz();
	}
	
	if($("#wrapper").attr("examFinish") != undefined && $("#wrapper").attr("examFinish") =="on"){
		getQuizFeedback();
	}
	
	if($("#wrapper").data("scenariofinish") != undefined && $("#wrapper").data("scenariofinish")=="on"){
		getScenarioFeedback();
	}
	
	updateCurrentPageProgress(progressNum);

	if(isortObj.showIsort)loadexistingEdits();
	updateGUI();
	setupCommonButtons();
	
	if ($('#questionPanel').length){
		setupQuestionParameters();
		islDebug("q_randomisation: "+q_randomisation, "red")
		if(q_randomisation.toLowerCase() == "on"){
			randomise_Options();
		}
	}
	
	$("#qSubmit").bind(tEvent,function(event) {
		if($(this).hasClass("disabled")) return;
		if($("#qSubmit").attr("btn_func") == undefined){
			$("#qSubmit").attr("btn_func", "submit");
		}
		btnAction($("#qSubmit").attr("btn_func"));
		event.stopPropagation();
		event.preventDefault();
	})
		
	if ($('#questionPanel').length){ 
		setupQuestionControls();
	}
	
	$("#wrapper span.glossary_link").bind(tEvent,function(e) {
		openGlossaryLink($(this).attr("glossary_target"))
		e.stopPropagation();
		e.preventDefault();
	});
	//+++++++++++++++++++++++++++ JE 13/August/2013 +++++++++++++++++++++++++++++++
	// Move on without pressing the next button. Click the screen to move on.
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	if($("#wrapper").attr("clickScreenToMove") !=undefined && $("#wrapper").attr("clickScreenToMove")=="on" && currentPage.next != "null"){
		$("#wrapper").bind("click",function() {
			goNext();
		})
	}else if($("#wrapper").attr("clickScreenToMove") !=undefined && $("#wrapper").attr("clickScreenToMove")!="on" && $("#wrapper").attr("clickScreenToMove")!="off"){
		$("#wrapper").bind("click",function() {
			var page = findPageBySrc(course, $("#wrapper").attr("clickScreenToMove"));
			loadPage(page);
		})
	}
	
	$("#mediaLock").addClass("invisible");

	if($("#wrapper").attr("targetvideo")!=undefined && $("#wrapper").attr("targetvideo").toLowerCase()!= "vimeo" && audioAsked==1) {
		playVideo($("#wrapper").attr("targetvideo"), $("#vid1"));
		//$(".audioBtn").addClass("disabled");
	}else if($("#wrapper").attr("targetvideo")!=undefined && audioAsked!=1){
		$("#mediaLock").removeClass("invisible");
		 $('video').css("position","absolute")
		 $('video').css("top","-1500px")
	}

	//no multimedia video
	if($('.low_band_v')[0]) {
		noMultimediaMovie();
	}
	//rotating background
	if ($("#wrapper").hasClass("rotateBG") && detectIE() == false){
		$(viewport).show();
		rotationEl();
	}else{
		$(viewport).hide();
	}
}

//++++++++++++++++++++++ scrollToFeedback ++++++++++++++++++++++++++++++++++++
// Function to scroll to the feedback section in a question.
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function scrollToFeedback(targetScroll){
	islDebug("[[scrollToFeedback("+targetScroll+")]]","#336767")
	switch(targetScroll.toLowerCase()){
		case "feedback":
				var targetArea=$("#onScreenFeedback");		
		break;
		case "question":
			var targetArea=$("#questionPanel");
		break;
		case "multiquestion":
			var targetArea=$("#qFeedback");
		break;
		default:
			var targetArea=targetScroll;
	}
	var inview = isScrolledIntoView(targetArea)
	if (!inview){
		targetArea=targetArea.offset().top;
		if(targetScroll.toLowerCase() == 'multiquestion')
			$("#wrapper").animate({scrollTop:targetArea});
		else
			$("html,body").animate({scrollTop:targetArea});
	}
}

//+++++++++++++++++++++ isScrolledIntoView() +++++++++++++++++++++++++++++++++++++++
// Check if an element is in view. If it is then return true otherwise retun false
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function isScrolledIntoView(elem){
	var docViewTop = $(window).scrollTop()+interfaceOffset;
	var docViewBottom = docViewTop + ($(window).height()-(interfaceOffset+interfaceBottomOffset));
	
	var elemTop = $(elem).offset().top;
	var elemBottom = elemTop + $(elem).height();
	
	return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

function feedbackButtonEffect(times, type) {
	clearTimeout(function () {
        feedbackButtonEffect(times,type);
    });
	if(!$("input.cs_feedback_btn").hasClass("effect")) {
		$("input.cs_feedback_btn").removeClass("flash_"+type);
	} else if (times > 0 || times < 0) {
        if ($("input.cs_feedback_btn").hasClass("flash_"+type)) $("input.cs_feedback_btn").removeClass("flash_"+type);
        else $("input.cs_feedback_btn").addClass("flash_"+type);

        setTimeout(function () {
            feedbackButtonEffect(times,type);
        },500);
        times -= .5;
    }
}



function flashBtn(obj){
	obj.fadeOut(550, function() {
		obj.fadeIn(550, function() {
			flashBtn(obj)
		});
  });
}

function detectIE() {
    var ua = window.navigator.userAgent;
    var msie = ua.indexOf('MSIE ');
    var trident = ua.indexOf('Trident/');

    if (msie > 0) {
        // IE 10 or older => return version number
        return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
    }

    if (trident > 0) {
        // IE 11 (or newer) => return version number
        var rv = ua.indexOf('rv:');
        return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
    }

    // other browser
    return false;
}

function onVideoFinish() {
	$('.nextBtn').removeClass('disabled');
	$( ".arrow_next_screen p" ).animate({bottom: 11}, 400);
	return true;
}

function noMultimediaMovie(){
	var timePlay = $("#timePlayBtn");
	var timePause = $("#timePauseBtn");

	if (typeof(movie) != "undefined") {
		movie.stop();
		movie.kill();	
		movie.clear();	
		$('.scene_1 *').stop();
		movie.time(0);	
		$('.scene_1 *').attr('style', '');
	}

	movie = new TimelineLite({onUpdate:updateSlider});
	
	if ($(".noMediaMovie").is("[autoplay]")) {
		movie.play();
		timePlay.hide();
		timePause.show();
	} else {
		movie.pause();
		timePlay.show();
		timePause.hide();
	}
	
	movie.to(".black_fadeout", 1, {autoAlpha:0});

	var noMediaMovie = $(".noMediaMovie").children();

	$('.nextBtn').addClass('disabled');

	for (var i = 0; i < noMediaMovie.length - 3; i++) {
		var movieAnim = $(noMediaMovie[i]).children();

		for (var z = 0; z < movieAnim.length; z++) {
			var sceneAnim = $(movieAnim[z]);
			var deepScene = $(movieAnim[z]).children();

			//image time
			if($(sceneAnim).data('vtime') !== undefined) {
				var time = sceneAnim.data('vtime');
				if ($(sceneAnim).hasClass("scenePng") && isIE8) {
					var time = 0;
				}
			}
			else {
				var time = 1;
			}

			if(sceneAnim.hasClass('zoomIn')){
				movie.to(sceneAnim, time, {autoAlpha:1}, 'zoomIn');
				movie.to(sceneAnim, time, {width: "180%",top:"-170", left: "-320"}, 'zoomIn');
			} else if(sceneAnim.hasClass('zoomOut')){
				movie.to(sceneAnim, time, {autoAlpha:1}, 'zoomOut');
				movie.from(sceneAnim, time, {width: "200%",top:"-600"}, 'zoomOut');
			}
			else if ($(sceneAnim).hasClass("scenePng") && isIE8) {
				movie.to(sceneAnim, time, {autoAlpha:1});
			} 
			
			
			for (var a = 0; a < deepScene.length; a++) {
				var deeperScene = $(deepScene[a]).children();
				movie.to($(deepScene[a]), time, {autoAlpha:1});
				movie.from($(deepScene[a]), time, {opacity:0, y:"-100px", ease:Bounce.easeOut});

				for (var b = 0; b < deeperScene.length; b++) {
					if ($(deeperScene[b]).hasClass("description_submenu")) {
						movie.from($(deeperScene[b]), time, {opacity:0, x:"500px", ease:Back.easeInOut});
					}
				}
			}

			if (sceneAnim.hasClass("lastScene")) {
				movie.to(sceneAnim, time, {autoAlpha:1, onComplete: function(){
					onVideoFinish();
					movie.progress(0).pause();
				}});
			}
		}
	}

	$("#timeProgressSlider").slider({
		range: false,
		min: 0,
		max: 1,
		step:.001,
		slide: function ( event, ui ) {
			movie.progress( ui.value ).play();
		}
	});	

	function updateSlider() {
		$("#timeProgressSlider").slider("value", movie.progress());
		if (movie.progress()){
			timePlay.hide();
			timePause.show();
		}
		else {
			timePlay.show();
			timePause.hide();
		}
	} 

	timePlay.on("click", function(){
		movie.play();
		$(this).addClass("play").fadeOut();
		timePause.fadeIn();
	});

	timePause.on("click", function(){
		movie.pause();
		$(this).fadeOut();
		timePlay.removeClass("play").fadeIn();
	});

	$(".noMediaMovie").hover(function(){
		$("#movieControls").fadeIn("slow");
	}, function(){
		$("#movieControls").fadeOut("slow");
	});
}

//CSS3 / JavaScript rotating/floating background elements
function rotationEl() {
	(function() {
			var lastTime = 0;
			var vendors = ['ms', 'moz', 'webkit', 'o'];
			for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
				window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
				window.cancelRequestAnimationFrame = window[vendors[x]+
				  'CancelRequestAnimationFrame'];
			}
			if (!window.requestAnimationFrame)
				window.requestAnimationFrame = function(callback, element) {
					var currTime = new Date().getTime();
					var timeToCall = Math.max(0, 16 - (currTime - lastTime));
					var id = window.setTimeout(function() { callback(currTime + timeToCall); }, 
					  timeToCall);
					lastTime = currTime + timeToCall;
					return id;
				};

			if (!window.cancelAnimationFrame)
				window.cancelAnimationFrame = function(id) {
					clearTimeout(id);
				};
		}())

		var layers = [],
			objects = [],
			
			rotateBG = document.getElementById( 'rotateBG' ),
			viewport = document.getElementById( 'viewport' ),
			
			d = 0,
			p = 400,
			rotateBGXAngle = 0,
			rotateBGYAngle = 0;
		
		viewport.style.webkitPerspective = p;
		viewport.style.MozPerspective = p;
		viewport.style.oPerspective = p;
		generate();
		
		function createCloud() {
		
			var div = document.createElement( 'div'  );
			div.className = 'rotateBase';
			var x = 256 - ( Math.random() * 512 );
			var y = 256 - ( Math.random() * 512 );
			var z = 256 - ( Math.random() * 512 );
			var t = 'translateX( ' + x + 'px ) translateY( ' + y + 'px ) translateZ( ' + z + 'px )';
			div.style.webkitTransform = t;
			div.style.MozTransform = t;
			div.style.oTransform = t;
			rotateBG.appendChild( div );
			
			for( var j = 0; j < 2; j++ ) {
				var cloud = document.createElement( 'div' );
				cloud.style.opacity = 0;
				cloud.style.opacity = .8;
				cloud.className = 'rotateLayer';
				
				var x = 256 - ( Math.random() * 512 );
				var y = 256 - ( Math.random() * 512 );
				var z = 256 - ( Math.random() * 512 );
				var a = Math.random() * 360;
				var s = .25 + Math.random();
				x *= .2; y *= .2;
				cloud.data = { 
					x: x,
					y: y,
					z: z,
					a: a,
					s: s,
					speed: .1 * Math.random()
				};
				var t = 'translateX( ' + x + 'px ) translateY( ' + y + 'px ) translateZ( ' + z + 'px ) rotateZ( ' + a + 'deg ) scale( ' + s + ' )';
				cloud.style.webkitTransform = t;
				cloud.style.MozTransform = t;
				cloud.style.oTransform = t;
			
				div.appendChild( cloud );
				layers.push( cloud );
			}
			
			return div;
		}
		

		window.ondevicemotion = function(e) {
			rotateBGXAngle = -( 0.5 - ( e.accelerationIncludingGravity.y / viewport.clientWidth ) );
			rotateBGYAngle = ( 0.5 - ( e.accelerationIncludingGravity.x / viewport.clientWidth ) );

			updateView();
		} 



		function generate() {
			objects = [];
			if ( rotateBG.hasChildNodes() ) {
				while ( rotateBG.childNodes.length >= 1 ) {
					rotateBG.removeChild( rotateBG.firstChild );       
				} 
			}
			for( var j = 0; j < 12; j++ ) {
				objects.push( createCloud() );
			}
		}
		
		function updateView() {
			var t = 'translateZ( ' + d + 'px ) rotateX( ' + rotateBGXAngle + 'deg) rotateY( ' + rotateBGYAngle + 'deg)';
			rotateBG.style.webkitTransform = t;
			rotateBG.style.MozTransform = t;
			rotateBG.style.oTransform = t;
		}
		
		
		function update (){
			
			for( var j = 0; j < layers.length; j++ ) {
				var layer = layers[ j ];
				layer.data.a += layer.data.speed;
				var t = 'translateX( ' + layer.data.x + 'px ) translateY( ' + layer.data.y + 'px ) translateZ( ' + layer.data.z + 'px ) rotateY( ' + ( - rotateBGYAngle ) + 'deg ) rotateX( ' + ( - rotateBGXAngle ) + 'deg ) rotateZ( ' + layer.data.a + 'deg ) scale( ' + layer.data.s + ')';
				layer.style.webkitTransform = t;
				layer.style.MozTransform = t;
				layer.style.oTransform = t;
			}
			
			requestAnimationFrame( update );
			
		}
		update();
}