/* SCORM 1.2 LMS functions */

var findAPITries = 0;

/*
	Function: actionsFindAPI
	Arguments: the current window
	Description: check to see if win contains the SCORM 1.2 API adaptor
	Returns: null if SCORM 1.2 API could not be located
			 a handle to SCORM 1.2 API adapter is returned if the API was located
*/
function actionsFindAPI(win)
{
   /* Check to see if the window (win) contains the SCORM 1.2 API
      if the window (win) does not contain the API and
     the window (win) has a parent window and the parent window  
     is not the same as the window (win)
   */ 
   while ( (win.API == null) && 
           (win.parent != null) && 
           (win.parent != win) )
   {
      /* increment the number of findAPITries */
      findAPITries++;

      /* note: 7 is an arbitrary number, but would be more than sufficient */
      if (findAPITries > lms_num_tries)
      {
         return null;
      }

      /* set the variable that represents the window being 
         being searched to be the parent of the current window
         then search for the API again
	  */	 
      win = win.parent;
   }
   return win.API;
}

/*
	Function: actionsGetAPI
	Arguments: none
	Description: locate the SCORM 1.2 API adaptor
	Returns: null if SCORM 1.2 API could not be located
			 a handle to API adapter is returned if the API was located
*/
function actionsGetAPI()
{
  
    
    var theAPI = actionsFindAPI(window);

    if ((theAPI == null) && (parent != null) && (typeof(parent) != "undefined")){
        theAPI = actionsFindAPI(parent);
    }
    if ((theAPI == null) && (parent.parent != null) && (typeof(parent.parent) != "undefined")){
        theAPI = actionsFindAPI(parent.parent);
    }
    if ((theAPI == null) && (parent.parent.parent != null) && (typeof(parent.parent.parent) != "undefined")){
        theAPI = actionsFindAPI(parent.parent.parent);
    }
    if ((theAPI == null) && (parent.parent.parent.parent != null) && (typeof(parent.parent.parent.parent) != "undefined")){
        theAPI = actionsFindAPI(parent.parent.parent.parent);
    }
    if ((theAPI == null) && (window.opener != null) && (typeof(window.opener) != "undefined")){
        theAPI = actionsFindAPI(window.opener);
    }
    if ((theAPI == null) && (parent.window != null) && (parent.window.opener != null) && (typeof(parent.window.opener) != "undefined")){
        theAPI = actionsFindAPI(parent.window.opener);
    }
    if ((theAPI == null) && (top.opener != null) && (top.opener.top != null) && (top.opener.top.opener != null) && (typeof(top.opener.top.opener) != "undefined")){   
        theAPI = actionsFindAPI(top.opener.top.opener);
    }

    return theAPI

}

/*
	Function: actionsLMSInitialize
	Arguments: none		
	Description: initializes the LMS API
	Returns: boolean for success of initialization
*/
function actionsLMSInitialize()
{
	/* if LMS API adaptor exists */
	/* 20221130 Update to language selection and bookmark functionality replaced LMSAPI with parent.document.scormAPI as API is now at sco.html */
	if(parent.document.scormAPI != null){
		/* attempt to initialize API */
		var result = parent.document.scormAPI.LMSInitialize("");
		/* report on the error if API not initialized */
		if(result == "false") {
			actionsLMSError("LMSInitialize","");
		}
	}
	return result;
}

/*
	Function: actionsLMSFinish
	Arguments: none		
	Description: executes final LMS calls on exit of the course
	Returns: nothing
*/
function actionsLMSFinish()
{
	/* check that the code has not already executed */
	if(!document.courseFinished)
	{
		/* if LMS API adaptor exists */
		/* 20221130 Update to language selection and bookmark functionality replaced LMSAPI with parent.document.scormAPI as API is now at sco.html */
		if(parent.document.scormAPI != null){
			/* attempt to finish up with the LMS */
			var less_status = actionsLMSGetValue('cmi.core.lesson_status');			
			/* check status completion flag variable */
			if((less_status == lms_pass_status1) || (less_status == lms_pass_status2)){			
				/* do nothing */
			}else{					
				 actionsLMSSetValue('cmi.core.lesson_status',lms_fail_status);
			}			
			/* set tracking data on closing course */
			recordPercentComplete(document.currentSection, document.subsectionCount, false);
			/* set the session time */
			courseWriteTimer(false);
			actionsLMSSetValue('cmi.core.exit','suspend');
			/* commit date to the LMS */
			actionsLMSCommit();			
			parent.document.scormAPI.LMSFinish('');
			document.courseFinished = true;
		}
	}
}

/*
	Function: actionsLMSCommit
	Arguments: none
	Description: commits the current value to the LMS
	Returns: nothing
*/
function actionsLMSCommit()
{
	/* if LMS API adaptor exists */
	/* 20221130 Update to language selection and bookmark functionality replaced LMSAPI with parent.document.scormAPI as API is now at sco.html */
	if(parent.document.scormAPI != null){
		/* commit the currently stored values to the LMS */
		parent.document.scormAPI.LMSCommit('');
		/* if there is an error with the LMS communication report on it */
		actionsLMSError("LMSCommit","");		
	}
}

/*
	Function: actionsLMSSetValue
	Arguments: 
		arg: database field e.g. cmi.core.session_time
		val: value for the database field
	Description: sets the database field value in the LMS and commits it to the LMS			 
	Returns: nothing
*/
function actionsLMSSetValue(arg,val)
{
	/* if LMS API adaptor exists */
	/* 20221130 Update to language selection and bookmark functionality replaced LMSAPI with parent.document.scormAPI as API is now at sco.html */
	if(parent.document.scormAPI != null){	
		parent.document.scormAPI.LMSSetValue(arg,val);
		/* if there is an error with the LMS communication report on it */
		actionsLMSError("LMSSetValue",arg);		
	}
	/* ensure value is updated in LMS on tablet or phone but not in the Saba LMS app */
	if(!isWeb){
		if(androidApp == false && iOSApp == false){
			actionsLMSCommit();
		}
	}
}

/*
	Function: actionsLMSGetValue
	Arguments: 
		arg: database field e.g. cmi.core.session_time
	Description: obtains the database field value from the LMS				 
	Returns: value of the database field
*/
function actionsLMSGetValue(arg)
{
	var result = "";
	/* if LMS API adaptor exists */
	
	/* 20221130 Update to language selection and bookmark functionality replaced LMSAPI with parent.document.scormAPI as API is now at sco.html */
	if(parent.document.scormAPI != null){
		result = parent.document.scormAPI.LMSGetValue(arg);	
		//console.log("arg = " + arg + "    result = " + result)
		/* if there is an error with the LMS communication report on it */
		actionsLMSError("LMSGetValue",arg);
	}
	return result;
}

/*
	Function: actionsLMSError
	Arguments: 
		errLMS: code to indicate the type of LMS call that was attempted
		errArg: database field e.g. cmi.core.session_time or a code for a database field
	Description: obtains the error code from LMSGetLastError() and uses this to obtain 
				 further details to display in an error pop up if error occurred
	Returns: none
*/
function actionsLMSError(errLMS,errArg)
{
	var result = 0;	
	/*if (errArg != "") 
	{ 
		if (errLMS != "") {	errLMS = errLMS + ": "; }
		errArg = errArg + " "; 
	}*/
	/* if LMS API adaptor exists */
	/* 20221130 Update to language selection and bookmark functionality replaced LMSAPI with parent.document.scormAPI as API is now at sco.html */	
	if(parent.document.scormAPI != null){
		result = parent.document.scormAPI.LMSGetLastError();
		if (result != 0) {
			/* 20240130 accessibility 2024 */
			/*var errorString = "<p>" + errLMS + errArg + "</p><p>" + result + " - " + parent.document.scormAPI.LMSGetErrorString(result) + "</p>";
			var errorString2 = parent.document.scormAPI.LMSGetDiagnostic(result);*/
			//showErrorMessage("Error", errorString, errorString2, "");
			var errorString = lms_error_dat["lms_error_1"][0].text2;
			showErrorMessage("Error", "", "", errorString);
		}
	}
	/* if LMS API adaptor does not exist */
	else {	
		/*var errorString = lms_error_dat["lms_error_1"][0].text1;
		var errorString2 = lms_error_dat["lms_error_1"][0].text2;*/
		//showErrorMessage("Error", errorString, errorString2, "");
		var errorString = lms_error_dat["lms_error_1"][0].text2;
		//showErrorMessage("Error", "", "", errorString);
	}
}

/*
	Function: actionsLMSSetScore
	Arguments: integer for score
	Description: calls function to set the score in the LMS
	Returns: none
*/
function actionsLMSSetScore(n)
{
    if(document.setScoreToLMS){
	   actionsLMSSetValue('cmi.core.score.raw',n);
    }
}

/*
	Function: actionsLMSGetScore
	Arguments: none
	Description: calls function to get the score from the LMS
	Returns: integer for score
*/
function actionsLMSGetScore()
{
	return actionsLMSGetValue('cmi.core.score.raw');
}

/*
	Function: actionsLMSSetSuspendData
	Arguments: string for suspend data
	Description: calls function to set the suspend data in the LMS
	Returns: none
*/
function actionsLMSSetSuspendData(n) 
{
	actionsLMSSetValue('cmi.suspend_data', n);
}

/*
	Function: actionsLMSGetSuspendData
	Arguments: none
	Description: calls function to get the suspend data from the LMS
	Returns: string for suspend data
*/
function actionsLMSGetSuspendData() 
{
	return actionsLMSGetValue('cmi.suspend_data');
}

/*
	Function: actionsLMSSetLessonLocation
	Arguments: string for lesson location
	Description: calls function to set the lesson location in the LMS
	Returns: none
*/
function actionsLMSSetLessonLocation() 
{
	actionsLMSSetValue('cmi.core.lesson_location', int_tracking.int_lesson_location);	
}

/*
	Function: actionsLMSGetLessonLocation
	Arguments: none
	Description: calls function to get the lesson location from the LMS
	Returns: string for lesson location
*/
function actionsLMSGetLessonLocation() 
{
	return actionsLMSGetValue('cmi.core.lesson_location');	
}

/*
	Function: actionsLMSSetLessonStatus
	Arguments: 
		m: string for lesson status to set
		n: boolean to indicate if lesson status should be set in the LMS
	Description: calls function to set the lesson status in a local variable
				 and/or in the LMS
	Returns: none
*/
function actionsLMSSetLessonStatus(m,n)
{
	/* if the lesson status is incomplete then set it in the LMS */
	if (m == "incomplete")
	{
		actionsLMSSetValue('cmi.core.lesson_status',lms_fail_status);
		int_tracking.int_lesson_status = lms_fail_status;
	}
	/* if the lesson status is completed then set it in the LMS only if indicated by n */
	else if (m == "completed")
	{
		if (n == true)
		{
			actionsLMSSetValue('cmi.core.lesson_status',lms_pass_status1);
			int_tracking.int_lesson_status = lms_pass_status1;
		}
		else
		{
			int_tracking.int_lesson_status = lms_pass_status1;
		}	
	}
}

/*
	Function: actionsLMSGetLessonStatus
	Arguments: none
	Description: calls function to get the lesson status from the LMS
	Returns: string for lesson status
*/
function actionsLMSGetLessonStatus()
{
	return actionsLMSGetValue('cmi.core.lesson_status');
}

/*
	Function: actionsLMSSetSessionTime
	Arguments: CMITimeSpan string
	Description: calls function to set the session time in the LMS
	Returns: none
*/
function actionsLMSSetSessionTime(n) 
{
	actionsLMSSetValue('cmi.core.session_time',n);
}

/*
	Function: actionsLMSGetStudentId
	Arguments: none
	Description: calls function to get the student id from the LMS
	Returns: a string of the student id
*/
function actionsLMSGetStudentId() 
{
	return actionsLMSGetValue('cmi.core.student_id');
}

/*
	Function: actionsLMSGetStudentName
	Arguments: none
	Description: calls function to get the student name from the LMS
	Returns: a string of the student name
*/
function actionsLMSGetStudentName() 
{
	return actionsLMSGetValue('cmi.core.student_name');
}



function recordInteractions(intID, userResponse, result, corrResponse, description, intType, intWeighting, intTimeStamp, strLOID){
	
	var intInteractionIndex;
	
	var intResult = "";
	
	

	
	if(result){
		intResult = "correct"
	}else{
		intResult = "wrong"
	}
	
	intInteractionIndex = actionsLMSGetValue("cmi.interactions._count");
	
	
	actionsLMSSetValue("cmi.interactions." + intInteractionIndex + ".id", intID);
	actionsLMSSetValue("cmi.interactions." + intInteractionIndex + ".type", intType);
	actionsLMSSetValue("cmi.interactions." + intInteractionIndex + ".student_response", userResponse);
	actionsLMSSetValue("cmi.interactions." + intInteractionIndex + ".result", intResult);
	actionsLMSSetValue("cmi.interactions." + intInteractionIndex + ".correct_responses.0.pattern", corrResponse);
	//actionsLMSSetValue("cmi.interactions." + intInteractionIndex + ".description", description);
	actionsLMSSetValue("cmi.interactions." + intInteractionIndex + ".weighting", intWeighting); 
	actionsLMSSetValue("cmi.interactions." + intInteractionIndex + ".time", intTimeStamp);
	actionsLMSSetValue("cmi.interactions." + intInteractionIndex + ".objectives.0.id", strLOID)
	
}
