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

//+++++++++++++++++++++++ Variables +++++++++++++++++++
//LMS TRACKING VARIABLES
var suspend_data = "";
var lesson_loc = "";
var courseScore = 0;
var courseStatus = "";
var student_name = "John Doe";

var startDate;
var exitPageStatus = false;
var boolCourseCompleted = false;
var ilnConnection = false; // boolean, indicate if we've established connection with the iln system

var startDate;
var exitPageStatus = false;
var lesson_score = "";
var student_name = "";
var currentStatus = "";
var currentScore = 0;
var boolCourseCompleted = false;
var lesson_status = "";

errorArray = new Array();
logArray = new Array();
var setupBtns = false
var errLogNum = 1;
var logWin = null;

//++++++++++++++++++++++++++++++++++++++++++++++++++++

//++++++++++++++++++++ loadPage() +++++++++++++++++++
// Initialise the scorm connection.
//+++++++++++++++++++++++++++++++++++++++++++++++++++
function loadLms(){
	result = doLMSInitialize();	
	if (result == "true"){
		var entryStatus = doLMSGetValue( "cmi.core.entry" );
		lesson_status = doLMSGetValue("cmi.core.lesson_status");
	   	if ( entryStatus == "ab-initio" || lesson_status.toLowerCase().charAt(0) == "n" ){
	   		// first time into the course, the student is now attempting the lesson
		  	var tempData = doLMSSetValue( "cmi.core.lesson_status", "incomplete" );
		  	jLessonLocation = "first_time";
	   	} else {
	   		// they've already started. get values in the lesson_location and suspend_data
	   		jProgress = doLMSGetValue( "cmi.suspend_data" );
	   		
	   		if(jProgress.length>0){
	   			clipArray = jProgress.split(",");
	   		}
	   		
	   		jLessonLocation = doLMSGetValue( "cmi.core.lesson_location");	
	   		lesson_score = doLMSGetValue("cmi.core.score.raw");
	   		if (lesson_status == "completed" || lesson_status == "passed"){
	   			boolCourseCompleted = true;
	   			caseStatus = "completed";
	   		}
	   	}
	}
	var howScoWasNavigatedTo = null;
  exitPageStatus = false;
  startTimer();
  startCourse();
}


//++++++++++++++++++++ unloadPage() ++++++++++++++++++++++++++++++++++++
// Called from the content.htm page when it is closed. Shuts down the
// LMS connection properly.
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function scorm_unloadPage(){
	if (exitPageStatus == false){
		exitPageStatus = true;
		doQuit();
	} 
}
//++++++++++++++++++++ doQuit() ++++++++++++++++++++++++++++++++++++
// Function that correctly shuts down the LMS connection.
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function doQuit(){
	if(delivery.toLowerCase() == "scorm"){
		var strSuspend = (boolCourseCompleted) ? "" : "suspend";
		doLMSSetValue("cmi.core.exit", strSuspend );
		computeTime();
		doLMSFinish();
	}
}

//++++++++++++++++++++ scorm_updateTracking() +++++++++++++++++++++++++++++++++
// This is the function that updates all the different LMS values. The values 
// are passed from the flash framework and updated on the LMS here.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function scorm_updateTracking(strData, strBkmark, strCompStatus, strScore){
	
	if (strData != undefined && strData.length > 0) doLMSSetValue("cmi.suspend_data" , strData);
	if (strBkmark != undefined && strBkmark.length > 0) doLMSSetValue("cmi.core.lesson_location", strBkmark);
	if (strCompStatus != undefined && strCompStatus.length > 0){
		setStatus(strCompStatus);	
	 	if (strCompStatus=="completed") boolCourseCompleted = true;
	}

	if(typeof(strScore)== "number"){
		doLMSSetValue("cmi.core.score.raw", strScore);	
	}
	doLMSCommit();
}

//++++++++++++++++++++ scorm_interactionsData() +++++++++++++++++++++++++++++++
// This function is used to track the users responses to quiz questions.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function scorm_interactionsData(intNo, intID, intTimeSt, intType, intCorrResp, intLearnResp, intResult, intLatency) {
	intCorrResp = intCorrResp.toString();
	var interaction = 'cmi.interactions.' + intNo;
	if(intID) doLMSSetValue(interaction + '.id', intID);
	if(intTimeSt) doLMSSetValue(interaction + '.time', intTimeSt);
	if(intType) doLMSSetValue(interaction + '.type', intType);
	if(intCorrResp) doLMSSetValue(interaction + '.correct_responses.0.pattern', intCorrResp);
	if(intLearnResp) doLMSSetValue(interaction + '.student_response', intLearnResp);
	if(intResult) doLMSSetValue(interaction + '.result', intResult);
	if(intLatency) doLMSSetValue(interaction + '.latency', intLatency);	
	doLMSCommit();


}

//++++++++++++++++++++ scorm_objectivesData() +++++++++++++++++++++++++++++++++
// This function is used to track the users responses to quiz questions.
// EXAMPLE:
//
// if(delivery == "scorm"){
//		var objectiveIndex = getObjectiveNum();
//		scorm_objectivesData(objectiveIndex, "johntest1", 99, 0, 100, "passed");
//	}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function scorm_objectivesData(objIndex, objId, objRaw, objMin, objMax, objStatus){
	var objRef = "cmi.objectives." + objIndex;
	doLMSSetValue(objRef + ".id", objId);
	doLMSSetValue(objRef + ".score.raw", objRaw);
	doLMSSetValue(objRef + ".score.min", objMin);
	doLMSSetValue(objRef + ".score.max", objMax);
	doLMSSetValue(objRef + ".status", objStatus);
	doLMSCommit();
}

//+++++++++++++++++++++++++ getObjectiveNum() +++++++++++++++++++++++++++++++++
// Get the index of the next available objective.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function getObjectiveNum(){
	if(delivery.toLowerCase() != "scorm"){
		return -1;
	}else{
		var returnNum = doLMSGetValue("cmi.objectives._count");
		var returnVal = (returnNum == "") ? -1 : parseInt(returnNum)
		return returnVal;
	}
}



//++++++++++++++++++++ setStatus() ++++++++++++++++++++++++++++++++++++++++++++
// This function sets the status of the sco
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function setStatus(sSCOCompleted){
	
	var mode = doLMSGetValue( "cmi.core.lesson_mode" );
	var currentStatus = doLMSGetValue("cmi.core.lesson_status");
	
	if(currentStatus == "passed" || currentStatus == "failed"  || currentStatus == "completed"){
			//return false because if this is a question (passed or failed)
			return false	
	}
	if ( mode != "review"  &&  mode != "browse" ){
		//the status is already set from "not attempted" to "incomplete" when the user first attempts a sco
		if(sSCOCompleted == "completed"){
			doLMSSetValue( "cmi.core.lesson_status", "completed" );
			doLMSCommit();
		}
	}
}

//++++++++++++++++++++ startTimer() +++++++++++++++++++++++++++
// Capture the time that the user started the course.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function startTimer()
{
   	startDate = new Date().getTime();
}


//++++++++++++++++++++ computeTime() +++++++++++++++++++++++++++
// Calculate how much time the user has spent in the course.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function computeTime(){
	if ( startDate != 0 ){
		var currentDate = new Date().getTime();
		var elapsedSeconds = ( (currentDate - startDate) / 1000 );
		var formattedTime = convertTotalSeconds( elapsedSeconds );
	} else {
		formattedTime = "00:00:00.0";
	}
	doLMSSetValue( "cmi.core.session_time", formattedTime );
}

//++++++++++++++++++++ computeTime() ++++++++++++++++++++++++++++++++++++++
// This function will convert seconds into hours, minutes, and seconds in
// CMITimespan type format - HHHH:MM:SS.SS (Hours has a max of 4 digits &
// Min of 2 digits
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function convertTotalSeconds(ts){
	var sec = (ts % 60);
	
	ts -= sec;
	var tmp = (ts % 3600);  //# of seconds in the total # of minutes
	ts -= tmp;              //# of seconds in the total # of hours
	
	// convert seconds to conform to CMITimespan type (e.g. SS.00)
	sec = Math.round(sec*100)/100;
	
	var strSec = new String(sec);
	var strWholeSec = strSec;
	var strFractionSec = "";
	
	if (strSec.indexOf(".") != -1)
	{
	strWholeSec =  strSec.substring(0, strSec.indexOf("."));
	strFractionSec = strSec.substring(strSec.indexOf(".")+1, strSec.length);
	}
	
	if (strWholeSec.length < 2)
	{
	strWholeSec = "0" + strWholeSec;
	}
	strSec = strWholeSec;
	
	if (strFractionSec.length)
	{
	strSec = strSec+ "." + strFractionSec;
	}
	
	
	if ((ts % 3600) != 0 )
	var hour = 0;
	else var hour = (ts / 3600);
	if ( (tmp % 60) != 0 )
	var min = 0;
	else var min = (tmp / 60);
	
	if ((new String(hour)).length < 2)
	hour = "0"+hour;
	if ((new String(min)).length < 2)
	min = "0"+min;
	
	var rtnVal = hour+":"+min+":"+strSec;
	
	return rtnVal;
}


//+++++++++++++++++++++++++++++++++ generateTimeStamp  ++++++++++++++++++++++++++++++++++++++++++++++++++
// Generate a time stamp for the SCORM errors so we know when the error was triggered.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
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
}

//+++++++++++++++++++++++++++++++++ generateErrorAlert  ++++++++++++++++++++++++++++++++++++++++++++++++++
// Open the error message dialogue box and populate it with the error.  If an error occurs when the
// the course is closing down then open a new window and populate it with the error message.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function generateErrorAlert(code, errCode, errDesc){
	if(!setupBtns){
		assignErrorBtns()
		setupBtns = true;
	}
	
  var curTime = generateTimeStamp();
  var errorString = code+"<br/>"
	errorString += txt_label_errorTime+" "+curTime+"<br/>"
	errorString += txt_label_errorCode+" "+errCode+"<br/>"
	errorString += txt_label_errorDesc+" "+errDesc
  
  if(exitPageStatus){
  	var errorString ="<center><img src='framework_images/scorm_error.jpg'></center><br/><br/>" +errorString;
		var errorWindow = window.open(" ", "_blank", "toolbar=no, scrollbars=no, resizable=no, top=500, left=500, width=400, height=400");
		errorWindow.document.write(errorString);
		errorWindow.document.title=txt_label_errorLabel2;
	}else{
		errorArray.unshift(errorString)
		errLogNum = 1;
		$(".scormErrorCount").html(txt_label_errorLabel1+ " "+errLogNum+" "+ txt_label_of+" "+errorArray.length)
    $(".scormBody").html(errorArray[errLogNum-1])
    $("#scormError").removeClass("invisible")
    shakeTween($("#scormErrorPanel"), 6);
  }  
}

//+++++++++++++++++++++++++++++++++++ assignErrorBtns  ++++++++++++++++++++++++++++++++++++++++++++++++++
// Assign functionality to the next/back edit arrows on the scrom error popup panel
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function assignErrorBtns(){
	$('.scormBack').unbind("click");
	$('.scormNext').unbind("click");
	
	$('.scormBack').bind( "click", function(event) {
		errLogNum = (errLogNum == 1) ? 1 : errLogNum-1
		$(".scormErrorCount").html(txt_label_errorLabel1+ " "+errLogNum+" "+ txt_label_of+" "+errorArray.length)
		$(".scormBody").html(errorArray[errLogNum-1]);
	});
	$('.scormNext').bind( "click", function(event) {
		errLogNum = (errLogNum == errorArray.length) ? errorArray.length: errLogNum+1
		$(".scormErrorCount").html(txt_label_errorLabel1+ " "+errLogNum+" "+ txt_label_of+" "+errorArray.length)
		$(".scormBody").html(errorArray[errLogNum-1]);
	});
}

//++++++++++++++++++++++++++++++++++++++++ shakeTween  ++++++++++++++++++++++++++++++++++++++++++++++++++
// Shake the scrom error popup panel when it appears on screen. 
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function shakeTween(obj, repeatCount){
	var max = 30;
	var min = -30;
	TweenMax.to(obj,0.1,{repeat:repeatCount-1, x:Math.floor(Math.random() * (max - min + 1) + min), delay:.3});
	TweenMax.to(obj,0.1,{y:0, x:0, delay:(repeatCount+1) * .1});
}

//++++++++++++++++++++++++++++++++++++++++ scormLog  ++++++++++++++++++++++++++++++++++++++++++++++++++++
// Open the SCORM logging window so the user can see the communication between the course and the LMS.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function scormLog(){
	if(logWin ==null){
		var logParams = "toolbars=no,location=no,status=yes,resizable=yes,scrollbars=yes,maximize=yes";
		logParams += ",width=450,height=600";
		logParams += ",left=0,top=0";
		
		logWin = window.open("", "logWin" , logParams);
		logWin.document.write("<html><head><title>SCORM Communication Log</title><link type='text/css' rel='stylesheet' href='styles/tools.css'/></head><body onunload='window.opener.resetLog()'><h2>SCORM Communication Log</h2><div id='logcontent'></div></body></html>");
		logText();
	}
}

//++++++++++++++++++++++++++++++++++++++++ resetLog  ++++++++++++++++++++++++++++++++++++++++++++++++++++
// Called when the SCORM logging window is closed and everything needs to be reset so it can be reopened.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function resetLog(){
	logWin = null;
	for(var i=0; i<logArray.length; i++){
		logArray[i]["viewed"] = false;
	}
}

//++++++++++++++++++++++++++++++++++++++++ logText  ++++++++++++++++++++++++++++++++++++++++++++++++++++
// Store all the SCORM communication data in an array. If the SCORM logging window is open then add
// any new logs that have been recorded to the window.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function logText(logTxt, logType){
	if(logTxt!=undefined){
		logArray.push({txt:logTxt, type:logType, viewed:false})
	}
	
	if(logWin !=null){
		for(var i=0; i<logArray.length; i++){
			if(logArray[i]["viewed"] == false){
				logWin.document.getElementById("logcontent").innerHTML += "<span class='"+logArray[i]['type']+"'>"+logArray[i]['txt']+"</span><br/>";
				logArray[i]["viewed"] = true;
			}
		}
	}
}

