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

var course = new Object();
var pagecount = 0;
var pageNumber = 0;
var totalPages = 0;
var islSettings = new Object();
var islCompletion = new Object();
var islTrack = new Object();
courseTrackingStringsArray = new Array();
courseTrackingProgressArray = new Array();
var pageNames = new Array();

var currentPage = "";
//var jLessonLocation="t_branch.html";
//var jProgress = "2@2@2@2@2@2@2@2@2@2@2@2@2@2@2@2@2@2@2@2@2@2@2@2@2@2@2@2***_cm_155555,_cm_00,_cm_01,_cm_02,_cm_03,_cm_04,_cm_05,_cm_06,_cm_07,_cm_08,_cm_09,_cm_10,_cm_11,_cm_12,_cm_13,_cm_14,_cm_15,_cm_16,_cm_17,_cm_18,_cm_19,_cm_20,_cm_21,_cm_22,_cm_23,_cm_24,_cm_25,_cm_26*****test1**test2";
var jLessonLocation="";
var jProgress = "";
var jScore = "";
var jName = "";
var jStatus = "";
var jCredit= "";
var jEntry = "";

var islSuspendData ="";
var islBookmarkTracker = "";
debugModeEnabled = '';

var onPhoneCourse = null;

//++++++++++++++++++++++++++ setupCourse +++++++++++++++++++++++++++++++++++++++++
// Take the JSON object and parse it into a recognised course structure that
// we can work with.
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function setupCourse(){

	document.title = course.title = structure.title;
	course.id = structure.id;
	
	//LOAD THE INTERFACE
	$('head').append('<script type="text/javascript" src="tools/'+course_interface+'/interface.js"></script>');
	$('<link>')
  .appendTo('head')
  .attr({type : 'text/css', rel : 'stylesheet'})
  .attr('href', 'tools/'+course_interface+'/interface.css'); //Implemented this way because IE8 is a lovely browser!
  
  
  //Load an IE8 specific interface and stylesheet
  if(isIE8){
		$('<link>')
	  .appendTo('head')
	  .attr({type : 'text/css', rel : 'stylesheet'})
	  .attr('href', 'tools/'+course_interface+'/interface_ie8.css');
		var targetLoad = "tools/"+course_interface+"/interface_ie8.html";
  }else{
  	var targetLoad = "tools/"+course_interface+"/interface.html";
  }

	$("#interfaceHolder").load(targetLoad, function(){
		init_interface_buttons();
		soundManager.setup({
		    url: 'scripts/swf/',
		    debugMode: false,
		   	onready: function() {
			    checkInView();
					if (structure.groupnode != undefined && structure.groupnode.length > 0){
						for (var i=0; i < structure.groupnode.length; i++){
							parseGroupNode(structure.groupnode[i], course, 0);
						}
					}else if(structure.groupnode != undefined){
						parseGroupNode(structure.groupnode, course, 0);
					}
					buildExamNodes();
					initMenu();
				
					islDebug("Course delivery: "+delivery, "green")
					islDebug("isortObj.showIsort: "+isortObj.showIsort, "green")
					
					//Turn on|off isort - isort needs to be loaded before the course starts.
					if(isortObj.showIsort == true){
						$("#isort").load("tools/isort.html", function(){
							window.initIsort();
							startCourseTracking();
						});
					}else{
						$("#isort").remove();
						startCourseTracking();
					}
				}
		});
	});
	// Add a dummy text to the index - we can test this to see if the course is
	// being displayed on a phone.
	$('body').append('<div class="phonePanel"></div>');
}

//++++++++++++++++++++++ INIT SCORM ++++++++++++++++++++++++++++++++++++++++++++
// Initalise a connection with the scorm LMS and load the appropiate page
// from the bookmark.
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function startCourseTracking(){
	if(delivery.toLowerCase() == "aicc"){
		init_aicc();
	}else if(delivery.toLowerCase() == "scorm"){
		loadLms();
	}else if(delivery.toLowerCase() == "iln"){
		init_iln()
	}else{
		startCourse();
	}
}

//++++++++++++++++++++++++++ startCourse +++++++++++++++++++++++++++++++++++++++++
// Start the course by loading in the appropiate page.
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function startCourse(){
	generateProgressFromData();
	$('#loadingAnimation').css("display","none");
	
	if($('.phonePanel')!=undefined){
		onPhoneCourse = ($('.phonePanel').css("display")=="table") ? true : false
	}
	
	if(enableDebug == true) {
		$("#debugger").load("tools/debugger.html", function(){
			debugCourseContent();
			$("#debugWindow").removeClass('invisible');
			$(".clientdebugger").remove();
			$(".debug_currentPage span.drag_area_element").html('IS Debug Tool - ' + currentPage.src);
			$(".debug_pageName").html(currentPage.src)
			minmax();
			closeBtn();
			dragItems();
		});
	}else {
		$("#debugger").load("tools/debugger.html", function(){
			$("#debuggerContent").remove();
			$("#min_max").hide();
			$(".debug_currentPage span.drag_area_element").html('IS Debug Tool - Client Debugger');
		});
	}
	stealthDebugger();
	stealthDebuggerTouch();
	
	
	//Turn on|off the multimedia prompt
	if(courseAudio == true){
		if(is_touch_device()) {
			$("#audioOverlay").removeClass("invisible");
			$("#audioPopupOverlay").show();
			TweenMax.from($("#audioOverlay"), 0.5, {opacity:0, top:"-50px", ease:Bounce.easeOut, delay:0.5});
			
		} else {
			$("#audioOverlay").remove();
			$("#audioPopupOverlay").remove();
			initAudio(true);
			loadfirstPage();
		}
	}else{
		$("#audioOverlay").remove();
		$("#audioPopupOverlay").remove();
		loadfirstPage();
	}
}

function loadfirstPage(){
	
	//if(enableDebug == true) jLessonLocation="t_standard_tt.html";
	
	//If we are using a Profile then rearrange the course with the profile.
	if(islProfile.useProfile && lmsVariables.userProfile!=""){
		islDebug(lmsVariables.userProfile,"#ff00ff");
		rebuildCourseUsingProfile(lmsVariables.userProfile)
	}
	
	if(islBookmark.toLowerCase()=="prompt" && jLessonLocation.indexOf(".htm") != -1 ){
		$("#bookmark_prompt").removeClass("invisible")
		addBlackOut("all");
		if(!onPhoneCourse){
			TweenMax.to($("#bookmark_prompt"), 0.5, {top:"30%", startAt:{top:"-10%"}, ease:Bounce.easeOut});
		}else{
			TweenMax.to($("#bookmark_prompt"), 0.5, {top:"0%", startAt:{top:"-10%"}, ease:Bounce.easeOut});
		}
	}else if(islBookmark.toLowerCase()=="on" && jLessonLocation.indexOf(".htm") != -1 ){
		$("#bookmark_prompt").remove();
		var pageToLoad = findPageBySrc(course, jLessonLocation);
		loadPage(pageToLoad);
	}else{
		$("#bookmark_prompt").remove();
		var pageToLoad = getFirstPageOfGroup(course);
		loadPage(pageToLoad);
	}
}

//++++++++++++++++++++++++++ unloadPage +++++++++++++++++++++++++++++++++++++++++++++
// Call the appropiate function to unload the page where the course is disconnected
// properly from the LMS and the connection shut down.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function unloadPage(){
	if(delivery.toLowerCase() == "scorm"){
		scorm_unloadPage();
	}else if(delivery.toLowerCase() == "iln"){
		iln_unloadPage()
	}else if(delivery.toLowerCase() == "aicc"){
		exitAU();
	}
}


//++++++++++++++++++++++++++ parseGroupNode ++++++++++++++++++++++++++++++++++++++
// Function to parse through the groupnodes and store them in the course object.
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function parseGroupNode(obj, parentNode, depth){
		if (parentNode.subNodes == undefined){
			parentNode.subNodes = new Array()
		}
		
		var groupObject = new Object();
		groupObject.parent = parentNode; // set the parent object group for this page
		groupObject.progress = 0; // initialise the progress for this object (0-100)
		groupObject.depth = depth;
		
		for (var attribute in obj) {
	    groupObject[attribute] = obj[attribute];
		}
		
		groupObject.type = (groupObject.type!= undefined) ? groupObject.type :"normal"
		
		
		if (obj.page != undefined && obj.page.length > 0){
			for (var i=0; i < obj.page.length; i++){
				if (groupObject.pageNodes == undefined) groupObject.pageNodes = new Array();
				var page = new Object();
				page.parent = groupObject; // set the parent object group for this page
				page.progress = 0; // initialise the progress for this page object (0-100)
			
				
				for (var attribute in obj.page[i]) {
					if(attribute=="back" || attribute=="next"){
			    	page["orig_"+attribute] = obj.page[i][attribute];
				  }else{
			    	page[attribute] = obj.page[i][attribute];
				  }
				}
				
				pageNames.push(page.src);
				groupObject.pageNodes.push(page);
				page.number = pagecount;
				pagecount++;
				page.index = groupObject.pageNodes.length;	
			}	
		}else if(obj.page != undefined){
				if (groupObject.pageNodes == undefined) groupObject.pageNodes = new Array();
				var page = new Object();
				page.parent = groupObject; // set the parent object group for this page
				page.progress = 0; // initialise the progress for this page object (0-100)
			
				for (var attribute in obj.page) {
					if(attribute=="back" || attribute=="next"){
						islDebug("FOUND: "+attribute +" WITH A VALUE OF "+obj.page[attribute]+" IN "+obj.page.src)
						page["orig_"+attribute] = obj.page[attribute];
				  }else{
			    	page[attribute] = obj.page[attribute];
				  }
				}
				
				groupObject.pageNodes.push(page);
				page.number = pagecount;
				pagecount++;
				page.index = groupObject.pageNodes.length;		
		}
		
		if (obj.groupnode != undefined && obj.groupnode.length > 0){
			for (var i=0; i < obj.groupnode.length; i++){
				parseGroupNode(obj.groupnode[i], groupObject, depth+1);
			}
		}else if(obj.groupnode != undefined){
			parseGroupNode(obj.groupnode, groupObject, depth+1);
		}

		parentNode.subNodes.push(groupObject);
		groupObject.index = parentNode.subNodes.length;
		
}
//++++++++++++++++++++++++++++ JE 28/May/2009 ++++++++++++++++++++++++++++++++++++
// This function is to update the page counts after the profiler has removed nodes,
// it updates the total page counts and fixes the numbering in all the pages.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function buildPageCount(obj){
	if (obj.pageNodes != undefined && obj.pageNodes.length > 0){
		for (var i=0; i < obj.pageNodes.length; i++){
			if (obj.type.indexOf("exam") == -1) {
				obj.pageNodes[i].number = pageNumber;
				pageNumber++;
			}
			assignNextBack(obj.pageNodes[i])
		}	
	} 
	if (obj.subNodes != undefined && obj.subNodes.length > 0){
		for (var k=0; k < obj.subNodes.length; k++){
			 buildPageCount(obj.subNodes[k]); 
		}
	} 
}

function assignNextBack(curPage){
	//Determine the back state for this page
	//islDebug(curPage.src +" "+curPage.number +" "+curPage.index+" :: "+curPage.orig_back,"#ff00ff")
	if(curPage.number==0 ||curPage.type=="exam_results" ){
		curPage.back = (curPage.orig_back==undefined) ? "null" : curPage.orig_back;
	}else if((curPage.number!=0)&&(curPage.index != 1)&&(curPage.index <= curPage.parent.pageNodes.length)){
		curPage.back =  (curPage.orig_back==undefined)? "prevScreen" : curPage.orig_back; 
	}else if(curPage.index == 1){
		curPage.back =  (curPage.orig_back==undefined) ? findBack(curPage)  : curPage.orig_back;  
	}
	
	//Determine the next state for this page
	if((curPage.index != curPage.parent.pageNodes.length)&&(curPage.index < curPage.parent.pageNodes.length)){
		curPage.next =  (curPage.orig_next==undefined) ? "nextScreen" : curPage.orig_next; 
	}else if(curPage.index == curPage.parent.pageNodes.length){
		curPage.next = (curPage.orig_next==undefined)? findNext(curPage) : curPage.orig_next;  
	}
	islDebug(curPage.src +" "+curPage.back +" "+curPage.next,"#ff00ff")
}

function findBack(obj){
	if(obj.parent !=undefined && obj.parent.index != 1){
		return "prevNode"
	}else if(obj.parent.parent !=undefined && obj.parent.parent.index != 1){
		return "prevParentNode"
	}else if(obj.parent.parent.parent !=undefined && obj.parent.parent.parent.index != 1){
		return "prevrootNode"
	}else{
		return "null";
	}
}

function findNext(obj){
	if((obj.parent != undefined && obj.parent.parent!=undefined) && (obj.parent.index != obj.parent.parent.subNodes.length)){
		return "nextNode"
	}else if((obj.parent.parent != undefined && obj.parent.parent.parent!=undefined) && (obj.parent.parent.index != obj.parent.parent.parent.subNodes.length)){
		return "nextParentNode"
	}else if((obj.parent.parent.parent != undefined && obj.parent.parent.parent.parent!=undefined) && (obj.parent.parent.parent.index != obj.parent.parent.parent.parent.subNodes.length)){
		return "nextrootNode"
	}else{
		return "null"
	}	
}



//++++++++++++++++++++++++++ parseSettings +++++++++++++++++++++++++++++++++++++++
// Function to parse through the settings.xml file and spit them out into a format
// that can be read by jQuery and used to build the course. The elements are
// stored in various objects that reflect the flash framework.
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function parseSettings(obj){
	obj.children("settings").each(function(j){
		var attrs = $(this)[0].attributes;
		for(var i=0;i<attrs.length;i++) {
			//islDebug(attrs[i].nodeName + " (1)=> " + attrs[i].nodeValue);
			islSettings[attrs[i].nodeName] = attrs[i].nodeValue
		}
	});	
	
	obj.children("settings").children("extra_setting").each(function(j){
		var attrs = $(this)[0].attributes;
		for(var i=0;i<attrs.length;i++) {
			//islDebug(attrs[i].nodeName + " (2)=> " + attrs[i].nodeValue);
			islSettings[attrs[i].nodeName] = attrs[i].nodeValue
		}
	});	
	
	obj.children("settings").children("completion").each(function(j){
		var attrs = $(this)[0].attributes;
		for(var i=0;i<attrs.length;i++) {
			//islDebug(attrs[i].nodeName + " (3)=> " + attrs[i].nodeValue);
			islCompletion[attrs[i].nodeName] = attrs[i].nodeValue
		}
	});	
	
	obj.children("settings").children("tracking").each(function(j){
		var attrs = $(this)[0].attributes;
		for(var i=0;i<attrs.length;i++) {
			//islDebug(attrs[i].nodeName + " (4)=> " + attrs[i].nodeValue);
			islTrack[attrs[i].nodeName] = attrs[i].nodeValue
		}
	});	
}


function findExamNode(obj, exam_type){
	if (obj.subNodes != undefined && obj.subNodes.length > 0){
		for (var k=0; k < obj.subNodes.length; k++){
			if(obj.subNodes[k].type.toLowerCase() == exam_type.toLowerCase()){
				var newNode = createExamNode(obj, obj.subNodes[k])
				obj.subNodes[k] = newNode
				obj.subNodes[k].index = (k+1);
				return obj.subNodes[k];
			}
		}
	} 
}


function buildExamNodes(){
	var postExamNode = findExamNode(course, "post_exam");
	var preExamNode = findExamNode(course, "pre_exam");
	if(preExamNode != undefined) {selectQuizQuestions(preExamNode)}
	if(postExamNode != undefined) {selectQuizQuestions(postExamNode)}
	buildPageCount(course)
}

	
	
//++++++++++++++++++++++++++++ createExamNode++++++++++++++++++++++++++++++++++++++
// Set up the exam object so that it can be used to create the quiz.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function createExamNode(parentObject, obj){
		newExamNode = new Object();
		var eNode = obj;
		newExamNode.pageNodes = new Array(); //array I will store new question order in
		newExamNode.storedQuestions = new Array(); //array I will store new question order in
		newExamNode.type = eNode.type;
		newExamNode.id = eNode.id;
		newExamNode.profile = eNode.profile;
		newExamNode.groupnodes_visible = eNode.groupnodes_visible;
		newExamNode.title = eNode.title;
		newExamNode.depth = eNode.depth;
		newExamNode.progress = eNode.progress;
		newExamNode.allQuestions = eNode.allQuestions;
		newExamNode.parent = parentObject;
		newExamNode.order = eNode.order 
		newExamNode.key = eNode.key
		newExamNode.examscore = -1;
		newExamNode.onsubmit_next = (eNode.onsubmit_next != undefined) ? eNode.onsubmit_next.toLowerCase() : "off";
		
		
		for (var k=0; k < eNode.subNodes[0].pageNodes.length; k++) {
			newExamNode.storedQuestions.push(eNode.subNodes[0].pageNodes[k]);	
		}
		
		for(var i=0; i<eNode.pageNodes.length; i++){
			if(eNode.pageNodes[i].type.toLowerCase() == "exam_intro"){
				newExamNode.pageNodes.push(eNode.pageNodes[i]);
			}else if(eNode.pageNodes[i].type.toLowerCase() == "exam_results"){
				newExamNode.pageNodes.push(eNode.pageNodes[i]);
			}
		}
		
		// assigning indexes to the new array
		for (var m=0; m < newExamNode.pageNodes.length; m++) {
			newExamNode.pageNodes[m].index = (m+1);
			newExamNode.pageNodes[m].parent = newExamNode;
		}
		
		//++++++++++++++++++++++++++++++++ JE 15/12/08 +++++++++++++++++++++++++++++++++++++++++
		// This loop is used to find out how many extra pages there are at the start and end of 
		// the exam node. These valuse are used by the interface in the progress indicator.
		//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
		var num_intro_pages = 0;
		var num_result_pages = 0;
		
		for(var j=0; j<newExamNode.pageNodes.length; j++){
			if(newExamNode.pageNodes[j].type =="exam_intro")num_intro_pages++
			if(newExamNode.pageNodes[j].type =="exam_results")num_result_pages++
		}
		
		newExamNode.num_intro_pages = num_intro_pages;
		newExamNode.num_result_pages = num_result_pages;
		//newExamNode.index = parentObject.subNodes.length;
		
		var total_extra_pages = num_intro_pages +num_result_pages+newExamNode.storedQuestions.length
		
		//islDebug(num_intro_pages)
		return newExamNode
}


function selectQuizQuestions(obj){
	//Temporarily remove the exam_results pages from the end of the object.
	var temp_result_array = new Array();
	
	for(var i=1; i<=obj.num_result_pages; i++){
		temp_result_array.push(obj.pageNodes.pop())
	}
	temp_result_array.reverse();
	
	
	//Remove any previously added questions.
	var numPages = obj.pageNodes.length-obj.num_intro_pages;
	for(var i=0; i<numPages; i++){
		obj.pageNodes.pop();
	}
		
	if(obj.allQuestions == "off"){
		//+++++++++++++++++++++++ JE 19/May/2009 ++++++++++++++++++++++++
		// Store the selected questions in a temp array - we can then completely randomise them 
		// before adding them to the structure of the course.
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
		var temp_questions_array = new Array();
		
		//Randomise the question Pool.
		
		for (var m=0; m < obj.storedQuestions.length; m++) {
			if(obj.storedQuestions[m].orginal_index == undefined){
				obj.storedQuestions[m].orginal_index = parseInt(obj.storedQuestions[m].index);
			}else{
				obj.storedQuestions[m].index = obj.storedQuestions[m].orginal_index
			}
		}
		
		for (j=0; j < obj.storedQuestions.length; j++) {
			obj.storedQuestions.sort(randomOrder);
		}
		
		//Key for sorting of the questions pool
		var arr_key = new Array(); 
		arr_key = obj.key.split("|");
		
		//Filling the array on KEY basis
		for(k=0;k<arr_key.length;k++){
			var counter =0;
			for(n=0;n<obj.storedQuestions.length;n++){
				if(parseInt(obj.storedQuestions[n].category)==(k+1)&&counter<parseInt(arr_key[k])){
					temp_questions_array.push(obj.storedQuestions[n]);
					counter++;
				}
			}
		}
		
		//If its not sequential order so we must randomize the array again
		if(obj.order == "random_unsequential"){
			for (j=0; j < temp_questions_array.length; j++) {
				temp_questions_array.sort(randomOrder);
			}
		}
		
		//islDebug("temp_questions_array:"+temp_questions_array.length)
		
		//We have finished randomising the questions - now add them to the structure of the course.
		for (j=0; j < temp_questions_array.length; j++) {
			obj.pageNodes.push(temp_questions_array[j])
		}
		
		
	}else{
		for(var i=0; i<obj.storedQuestions.length; i++){
			obj.pageNodes.push(obj.storedQuestions[i]);	
		}
		
	}
	
	//Add the exam_results pages back to the end of the object
	for(var i=0; i<temp_result_array.length; i++){
		obj.pageNodes.push(temp_result_array[i]);	
	}
	
	//Index the newly formed exam node correctly.
	for (var m=0; m < obj.pageNodes.length; m++) {
		islDebug(m+" "+obj.pageNodes[m].src, "#00ff99")
		obj.pageNodes[m].index = (m+1);
		obj.pageNodes[m].parent = obj;
	}
}


// function will randomise items in an array when called as a sort function
function randomOrder(){
	return (Math.round(Math.random())-0.5);
}

function islDebug(txt, font_color){
	if( $("#tracers")[0]) {
		var existing_text = $("#tracers").html();
		existing_text = (existing_text.length > 10000) ? "" : existing_text
		if(font_color != undefined){var txt_string = "<span style='color:"+font_color+"'>"+txt+"</span><br/>"+existing_text}
		else{var txt_string = txt+"<br/>"+existing_text}
		$("#tracers").html(txt_string);
		
		if(enableDebug==false) {debugCourseContent();}
	}
}

function debugCourseContent() {
	var html = "<select id='debugger_select' ><option></option>";
	for(var i = 0; i < pageNames.length; i++)
	{
		html+="<option value='"+ pageNames[i] +"'>"+ pageNames[i] +"</option>";
	}
	$("#debug_selectPage").html(html + "</select>");
	$("select#debugger_select").on({
    	change: function() {
    		loadPage(findPageBySrc(course, $(this).val()));
    		$("select#debugger_select").val('');
	    }	  
	});	
}

// Close button for the debug and isort panels
function clearTracers(){
	$("#tracers").html("Cleared.......")
}

function closeBtn(){
	$('.closeBtn').unbind("click");
	$('.closeBtn').bind("click",function(event) {
		$(this).parent().parent().addClass("invisible");
  });
}
function minmax(){
	// MIN MAX BUTTON FUNCTIONALITY
	$('.min_maxBtn').unbind("click");
	$('.min_maxBtn').bind("click",function(event) {
		if($(this).attr("toggle")=="min"){
			$(this).attr("toggle","max")
			$(this).attr("src", "framework_images/maximise.jpg")
			$(".debug_currentPage span.drag_area_element").html(currentPage.src);
			$(this).parent().parent().children().each(function(index){
				if(index>1 && $(this).is(":visible")){
					$(this).css("display","none")
					$(this).attr("min", "true")
				}
			});
			$(this).parent().parent().css("height", "37px");
		}else if($(this).attr("toggle")=="max"){
			$(this).attr("toggle", "min")
			$(this).attr("src", "framework_images/minimise.jpg")
			$(".debug_currentPage span.drag_area_element").html('IS Debug Tool - ' + currentPage.src);
			$(this).parent().parent().children().each(function(index){
				if($(this).attr("min")=="true"){
					$(this).css("display","block")
					$(this).attr("min", "false")
				}
			});
			$(this).parent().parent().css("height", "auto");
		}
  });
}

function dragItems() {
	$("#debugWindow, #transcript_Panel, #isort, #resources_Panel, #glossary_Panel").draggable({ handle: "#dragarea" }, { cursor: "crosshair" }, {containment:"#content_body"});
}
/* STEALTH DEBUGGER */

function generateCode(enteredCode){var Debuglevel='qed99';var courseCode=enteredCode.toLowerCase().split('');var expectedString=Debuglevel;var decryptKey=new Array("h1w","g6g","m7","n8","o9t","pk","f2","i3d","ct","d5l","q1","r2","s3","u4","v5","je","bx","w8","x9u","y0","z1","e2","t3","k9","l5","a6");var normalKey=new Array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z");for(var i=0;i<courseCode.length;i++){for(var j=0;j<normalKey.length;j++){if(courseCode[i]==normalKey[j]){expectedString+=decryptKey[j]}}}return expectedString}

function stealthDebugger() {
	var map = {34: false, 68: false};
	$(document).keydown(function(e) {
	    if (e.keyCode in map) {
	        map[e.keyCode] = true;
	        if (map[34] && map[68]) {
	        	if ($('.min_maxBtn').attr("toggle")=="min") {
	        		DebugShowHide();
	        		$(".clientdebugger").show();
	        		minmax();
	        	}
	        	else if ($(".min_maxBtn").attr("toggle")=="max") {
	        		$("#debuggerContent").css("display","none")
	        		DebugShowHide();
	        		minmax();
	        	}	
	        }
	    }
	}).keyup(function(e) {
	    if (e.keyCode in map) {
	        map[e.keyCode] = false;
	    }
	});
}

function DebugShowHide(displayNow, once) {
	minmax();
	closeBtn();
	dragItems()

	$('.course_code').html(course.id);
	var courseHash = generateCode(course.id);

    if (!$('#debugWindow').is(':visible')) {   	
    	if ($("#debugWindow").hasClass("invisible")) {
    		$("#debugWindow").removeClass("invisible");
    		$('#debugWindow').show();
    	}
		if(debugModeEnabled == true || displayNow == true) {
			ShowDebugger();
			return true;
		} 
		else {
			$( "#submitDCode" ).click(function() {
				if ($("#debug_code").val() == courseHash)  { 
			  		debugModeEnabled = 1;
			  		DebugShowHide(true, 'yes'); 
			  		
			  		$("#debugger").load("tools/debugger.html", function(){
			  			$(".clientdebugger").remove();
			  			ShowDebugger();
			  			debugCourseContent();
			  			$(".debug_currentPage span.drag_area_element").html('IS Debug Tool - ' + currentPage.src)
			  			minmax();
						closeBtn();
						dragItems();
			  		});
			  	} 
			  	else {
			  		$('.code_status').hide().html('Incorrect Code').fadeIn('slow');
			  	}
				return true;
			});
		}
		ShowDebugger();
		return true;
	} else {
		$('#debugWindow').hide();
		return false;
	}
}

function ShowDebugger() {
		$(".clientdebugger").hide();
		$("#debugWindow").removeClass('invisible');
		$("#debugWindow").show();		
		$("#debugWindow table").show(); 
		$("#debugWindow").addClass("a"); 
		return true;
}

function stealthDebuggerTouch() {
	$(".logo").swipe( {
        //Generic swipe handler for all directions
        swipe:function(event, direction, distance, duration, fingerCount) {
          DebugShowHide();
          minmax();
          $(".clientdebugger").show();
        },
        //Default is 75px, set to 0 for demo so any distance triggers swipe
         threshold:700
      });
	return true;
}

// Avoid `console` errors in browsers that lack a console.
(function() {
    var method;
    var noop = function () {};
    var methods = [
        'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
        'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
        'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
        'timeStamp', 'trace', 'warn'
    ];
    var length = methods.length;
    var console = (window.console = window.console || {});

    while (length--) {
        method = methods[length];

        // Only stub undefined methods.
        if (!console[method]) {
            console[method] = noop;
        }
    }
}());

// ++++++++++++++++++++++++++++++++++++ AICC FUNCTIONALITY +++++++++++++++++++++++++++++++++++++++++++++++++++++++
function init_aicc(){
	$.aicc({
      action:'get',
      response:function(r){
      	jEntry = r['lesson_status'];
      	jLessonLocation = r['lesson_location'];
      	jProgress = r['islsuspenddata'];
      	jScore = r['score'];
      	jName = r['student_name'];
        jStatus = r['lesson_status'];
        jCredit = r['credit'];
        start_aicc_course();
      }
  });
}

function start_aicc_course(){
	startTimer();
	if(jEntry.charAt(0).toLowerCase()=="n"){
  	$.aicc({
        action:'set',
        score:jScore,
        time:'00:00:00',
        credit:jCredit,
        location:jLessonLocation,
        status:'incomplete',
        suspend_data:jProgress,
        response:function(r){
  				startCourse();
        }
    });
  }else{
  	startCourse();
  }
}

function exitAU(){
	$.aicc({
      action:'exit',
      response:function(r){}
  });
}

function getAICCTime(){
	if(startDate != 0){
		var currentDate = new Date().getTime();
		var elapsedSeconds = ( (currentDate - startDate) / 1000 );
		var formattedTime = convertTotalSeconds( elapsedSeconds );
	} else {
		formattedTime = "00:00:00";
	}
	return formattedTime
}




