/*
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
*/


function loadPage(pageObj) {
	closeOpenComponent();
	if($('.vimeoVideo').length > 0) {
		$('.vimeoVideo').attr('src','');
	}
	moreIndicatorViewed = false
	$('#loadingAnimation').css("display","none");
	//preloaderAnim.stop()
	closeVideo();

	currentPage=pageObj;
	$(".debug_currentPage span.drag_area_element").html('IS Debug Tool - ' + currentPage.src);
	$(".debug_pageName").html(currentPage.src)
	islDebug("Loading page: "+currentPage.src, "#FF9900");

	if((currentPage.parent.type == "pre_exam" || currentPage.parent.type == "post_exam")&&((currentPage.type=="question")||(currentPage.type=="exam_results"))){
		islBookmarkTracker = currentPage.parent.pageNodes[0].src;
	}else{
		islBookmarkTracker = currentPage.src;
	}
	islDebug("SET islBookmarkTracker TO: "+islBookmarkTracker)

	var pathToLoad="course/"+currentPage.src;

	$("#contentPage").delay(100).empty().load(pathToLoad,function (responseText, textStatus, XMLHttpRequest) {
	    if (textStatus == "success") {
	    	initPage();
	    	if (browser_notification == true) {
					browserNotSupported();
				}
	    }
  });
}


//++++++++++++++++++++++++++++ updateGUI() ++++++++++++++++++++++++++++++++++++++
// Function to control the next|back button and make them enabled as required.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function updateGUI(){
	islDebug("[[updateGUI()]]","#ff00ff");

	//UPDATE THE TEXT
 	$("#title").html(course.title);
 	$("#subtitle").html(course.subtitle);
 	$("#subheading").html(currentPage.parent.subtitle);
	$("#page_numbers").html("<span>" + txt_label_page + "</span>" + currentPage.parent.index + txt_label_of + course.subNodes.length);
	$(".phonecrumb").html(currentPage.parent.index + "/" + course.subNodes.length);


	//CONTROL THE BACK BUTTON
	if(currentPage.back == "null"){
		disableInterfaceBtn($(".backBtn"))
	}else if(currentPage.parent.type =="linear_scenario" && currentPage.type!="intro"){
		disableInterfaceBtn($(".backBtn"))
	}else if(currentPage.parent.type.indexOf("exam") != -1 && currentPage.type=="question"){
		disableInterfaceBtn($(".backBtn"))
	}else{
		enableInterfaceBtn($(".backBtn"))
	}

	//CONTROL THE NEXT BUTTON
	//If the page has restricted navigation
	if(currentPage.parent.type =="linear_scenario" && currentPage.type!="summary"){
		disableInterfaceBtn($(".nextBtn"))
	}else if(($("#wrapper").hasClass("controlnav") || currentPage.type=="question") && currentPage.progress!=2){
		disableInterfaceBtn($(".nextBtn"))
	}else if(($("#wrapper").hasClass("controlnav") || currentPage.type=="question") && currentPage.progress==2 && currentPage.tempNext != undefined){
		enableInterfaceBtn($(".nextBtn"))
	}else if(currentPage.next == "null"){
		disableInterfaceBtn($(".nextBtn"))
	}else if(currentPage.parent.type.indexOf("exam") != -1 && currentPage.type=="question" && currentPage.progress!=2){
		disableInterfaceBtn($(".nextBtn"))
	}else{
		enableInterfaceBtn($(".nextBtn"))
	}

	//RESET THE AUDIO BTN
	$(".audioBtn").removeClass("disabled");

	//LINEAR SCENARIO PROGRESS
	if(currentPage.parent.type =="linear_scenario" && currentPage.type=="question"){
		addLSindicator()
	}

}

// find the first page in a given object
function getFirstPageOfGroup(grpObj){
	islDebug("getFirstPageOfGroup("+grpObj.id+")")
	var page = "";
	if (grpObj.pageNodes != undefined && grpObj.pageNodes.length > 0){
		 page = grpObj.pageNodes[0];
	}else if (grpObj.subNodes != undefined && grpObj.subNodes.length > 0){
		for (var k=0; k< grpObj.subNodes.length; k++){
			page = getFirstPageOfGroup( grpObj.subNodes[k] );
			if (page != undefined && page.src != undefined) {
				break;
			}
		}
	}else{
		page = null;
	}
	pageCounter = 1;
	return page;
}

// search for a page object using its src attribute as a unique identifier
function findPageBySrc(obj, src){
	if (obj.pageNodes != undefined && obj.pageNodes.length > 0){
		for (var i=0; i < obj.pageNodes.length; i++){
			if (obj.pageNodes[i].src == src){
				return obj.pageNodes[i];
			}
		}
	}
	if (obj.subNodes != undefined && obj.subNodes.length > 0){
		for (var k=0; k < obj.subNodes.length; k++){
			 var pg = findPageBySrc( obj.subNodes[k] , src );
			 if (pg != null && typeof(pg) == "object") return pg;
		}
	}
	return null;
}

//++++++++++++++++++++++++++++ findObjectById ++++++++++++++++++++++++++++++++++++++
// A recursive function to search a given object for a particualr object id.
// @param obj:Object the groupnode object from which to start the search,
// @param id:String the id of the groupnode we're looking for
// @returns the groupNode Object if found, otherwise null
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function findObjectById(obj, id){
	if (obj.id != undefined && id == obj.id){
		return obj;
	}
	if (obj.subNodes != undefined && obj.subNodes.length > 0){
		for (var k=0; k < obj.subNodes.length; k++){
			 var pg = findObjectById(obj.subNodes[k] , id);
			 if (pg != null && typeof(pg) == "object") return pg;
		}
	}
	return null;
}

//++++++++++++++++++++++++++++ goReplay +++++++++++++++++++++++++++++++++++++++++++
// This function is called when the next navigation button is pressed or swiped,
// the destination is governed by the 'next' attribute on each page object. This
// can be manually set or determined automatically.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function goReplay(){
	islDebug("[[goReplay]]")
	loadPage(currentPage);
};


//++++++++++++++++++++++++++++ goNext +++++++++++++++++++++++++++++++++++++++++++++
// This function is called when the next navigation button is pressed or swiped,
// the destination is governed by the 'next' attribute on each page object. This
// can be manually set or determined automatically.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function goNext(completionValue){

	if(completionValue == 2) {
		updateCurrentPageProgress(2);
		updateGUI();
	}

	islDebug("currentPage.next: "+currentPage.next, "#FFCC00");
	switch( currentPage.next.toLowerCase() ){
		case "nextscreen":
			loadPage(currentPage.parent.pageNodes[currentPage.index ]);
			break;
		case "nextnode":
			var nn = findNextNode(currentPage.parent);
			loadPage(getFirstPageOfGroup(nn));
			break;
		case "nextparentnode":
			var npn = findNextNode(currentPage.parent.parent);
			loadPage( getFirstPageOfGroup(npn));
			break;
		case "nextrootnode":
			var nrn = findNextNode( currentPage.parent.parent.parent);
			loadPage( getFirstPageOfGroup(nrn));
			break;
		case "rootscreen":
			loadPage(course.pageNodes[0]);
			break;
		case "last":
			showWarning(txt_label_endOfCourse,"message")
			break;
		case "null":
			$("#lock").fadeIn('slow').delay(1000).fadeOut('slow');
			break;
		default:
			if(currentPage.next.toLowerCase()!="null"){
				loadPage(findPageBySrc(course, currentPage.next.toLowerCase()));
			}
			break;
	}
};

/*
	function called when the back navigation button is pressed
	the destination is governed by the 'back' attribute on each page object in the course menu
*/
function goBack(){
	if (currentPage.back != undefined && currentPage.back.length > 0){
		switch( currentPage.back.toLowerCase() ){
			case "prevscreen":
				loadPage( currentPage.parent.pageNodes[currentPage.index - 2] );
				break;
			case "prevnode":
				loadPage( getLastPageOfGroup(currentPage.parent.parent.subNodes[currentPage.parent.index-2]) );
				break;
			case "prevparentnode":
				loadPage( getLastPageOfGroup(currentPage.parent.parent.parent.subNodes[currentPage.parent.parent.index-2]) );
				break;
			case "prevrootnode":
				loadPage( getLastPageOfGroup(currentPage.parent.parent.parent.parent.subNodes[currentPage.parent.parent.parent.index-2]) );
				break;
			case "rootscreen":
				loadPage(course.pageNodes[0] );
				break;
			case "originalpage":
				//loadPage( PreviousPage );
				break;
			case "null":
				$("#lock").fadeIn('slow').delay(1000).fadeOut('slow');
				break;
			case "lessonsplash":
				loadPage( currentPage.parent.parent.pageNodes[0] )
				break;
			default:
				if(currentPage.back.toLowerCase()!="null"){
					loadPage(findPageBySrc(course ,  currentPage.back.toLowerCase()));
				}
				break;
		}
	} else {
		//islDebug("No back attribute defined for current page. Going back to page index - 1");
		loadPage( currentPage.parent.pageNodes[currentPage.index - 2] );
	}
};


//++++++++++++++++++++++++++++ findNextNode +++++++++++++++++++++++++++++++++++++++++++++
// Find the next groupNode object relative to a given one
// @param node:Object, a groupnode object as created from the xml
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function findNextNode(node){
	if (node.parent == undefined){
		return node.subNodes[0];
	}

	if (node.index < node.parent.subNodes.length ){
		return node.parent.subNodes[node.index];
	} else {
		findNextNode( node.parent );
	}
}


//++++++++++++++++++++++++++++ getLastPageOfGroup +++++++++++++++++++++++++++++++++
// Recursive function to go through all the nodes and find the last page of
// the last node in the group.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function getLastPageOfGroup(node){
	if(node.pageNodes != undefined && node.pageNodes.length>0){
		return node.pageNodes[node.pageNodes.length-1];
	}else{
		return getLastPageOfGroup(node.subNodes[node.subNodes.length-1])
	}
}
//++++++++++++++++++++++++++++ showWarning ++++++++++++++++++++++++++++++++++++++++++++
// This function is used to display a warning|error message to the user|developer.
// Warning messages will only display if the debugger is turned on and error messages
// will always appear.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function showWarning(txt, type){
	console.log("warning????")
	if(type==undefined)type="warning";
	if(!enableDebug && type=="warning") return;
	txt = txt.replace('[%%date%%]',generateTimeStamp());
	$("#displayError").removeClass("invisible");
	$("#error_header").removeClass("error_header_red").removeClass("error_header_yellow").removeClass("error_header_green");
	if(type=="warning"){
		$("#error_header").addClass("error_header_yellow");
		$("#error_header").html(txt_label_warning);
	}else if(type=="error"){
		$("#error_header").addClass("error_header_red");
		$("#error_header").html(txt_label_error);
	}else if(type=="message"){
		$("#error_header").addClass("error_header_green");
		$("#error_header").html(txt_label_message);
	}
	$("#error_msg").html(txt);
}
//++++++++++++++++++++++++++++ generateTimeStamp ++++++++++++++++++++++++++++++++++++++
// This function is used to create an accurate timestamp for the showWarning function.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function generateTimeStamp(){
	m  =  new  Array("Jan","Feb","Mar","Apr","May","June","July","Aug","Sept","Oct","Nov","Dec");
	var currentTime = new Date()
	var month = currentTime.getMonth()
	var day = currentTime.getDate()
	if (day < 10){day = "0" + day}
	var year = currentTime.getFullYear()
	var hours = currentTime.getHours()
	var minutes = currentTime.getMinutes()
	if (minutes < 10){minutes = "0" + minutes}
	var timeStamp = day + "-" + m[month] + "-" + year+", "+hours + ":" + minutes;
	return timeStamp
}

//++++++++++++++++++++++++++++ generateSpriteSheet ++++++++++++++++++++++++++++++++++++
// This function is used to create and run a sprite animation
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 function generateSpriteSheet(spriteContainer, spriteSheetURL ,animationJSONURL, tlArguments){
	var tl = new TimelineMax(tlArguments);
	var spriteContainer = document.getElementById(spriteContainer);

	$.getJSON(animationJSONURL, function(data){
		spriteContainer.style.width = data.frames[0].sourceSize.w + "px";
		spriteContainer.style.height = data.frames[0].sourceSize.h + "px";
		spriteContainer.style.background = "url("+spriteSheetURL+")";

		$.each( data, function( key, val ){
		    for(var i = 0, k=0; i < val.length; i++, k+=0.05){
		    	tl.to(spriteContainer, 0.0,{css:{backgroundPosition:(val[i].frame.x*-1 + "px " + val[i].frame.y*-1 + "px")}}, k);
			}
	  	});
	});
	return tl;
};
