var  __LESSON_STATUS = 'cmi.core.lesson_status';
var __USER_ID = 'cmi.core.student_id';
var __SESSION_TIME = 'cmi.core.session_time';

/* not implemented:
cmi.core.total_time
cmi.core.lesson_location
cmi.core.lesson_mode
cmi.core.credit
cmi.core.entry
*/

/*
cmi.launch_data
cmi.suspend_data
cmi.comments
cmi.student_data
cmi.student_preference
cmi.objectives
cmi.interactions
*/


var __API = null;
var __startDate;
var __lastresult;

/*------------------------------------------------------------*/
function __LMSInit(){
	if (__API == null){__API = __LMSgetAPI();}
	__startDate = new Date().getTime();
	__lastresult = __API.LMSInitialize("");

   	if (__LMSGetValue(__LESSON_STATUS) == "not attempted") {
		__LMSSetValue(__LESSON_STATUS, "incomplete" );
		__lastresult = __LMSCommit();
   	}

}
/*------------------------------------------------------------*/
function __LMSUnInit(){
	var currentDate = new Date().getTime();
    var elapsedSeconds = ( (currentDate - startDate) / 1000 );
    var formattedTime = convertTotalSeconds( elapsedSeconds ); //from SCOFunctions.js

	__LMSSetValue(__SESSION_TIME, formattedTime);
	__LMSCommit();
	__lastresult = __API.LMSFinish();
}

/*------------------------------------------------------------*/
function __LMSGetValue(value){
	//alert('SCORM: get ' + value + ':  '  + __API.LMSGetValue(value));
	return __API.LMSGetValue(value);
	//return null;
}
/*------------------------------------------------------------*/
function __LMSSetValue(key, value){
	//alert('SCORM: set ' + key + ':  '  + value);
	__lastresult = __API.LMSSetValue(key, value);
	//return null;
}
/*------------------------------------------------------------*/
function __LMSCommit(){
	__lastresult = __API.LMSCommit('');
}


/*------------------------------------------------------------------------
	helper
*/
function __LMSgetAPI(){
   var _API = __findAPI(window);
   /*
   if ((_API == null) && (window.opener != null) && (typeof(window.opener) != "undefined")){
     	_API = __findAPI(window.opener);
   }*/
   //break any framesets there might be
   if ((_API == null) && (window.top.opener != null) && (typeof(window.top.opener) != "undefined")){
     	_API = __findAPI(window.top.opener);
   }

   if (_API == null){
      alert("dx: Unable to find an API adapter");
   }
   return _API
}

/*------------------------------------------------------------------------*/
function __findAPI(win){
   var findAPITries = 0;
   while ((win.API == null) && (win.parent != null) && (win.parent != win)) {
      findAPITries++;
      if (findAPITries > 12){ return null;}      // Note: 12 is an arbitrary number, but should be more than sufficient
      win = win.parent;
   }
   return win.API;
}




