
var gAPI = null; // Stand-in for the API object, if found.

// capture time when course was launched to be able to track session_time
var startDateTimeMilliSecs = (new Date()).getTime();


////////////////////////////////////////////////////////////////////////////////////////////////////
// INIT
// These functions are used to lookup the SCORM API during initialization
////////////////////////////////////////////////////////////////////////////////////////////////////

function _ScanForAPI(win) // Revised to handle x-scripting errors
{
	// This function is called by GetAPI
	var nFindAPITries = 500; // paranoid to prevent runaway
	var objAPI = null;
	var bOK = true;
	var wndParent = null;
	while ((!objAPI)&&(bOK)&&(nFindAPITries>0))
	{
		nFindAPITries--;
		try { objAPI = win.API; } catch (e) { bOK = false; }
		if ((!objAPI)&&(bOK))
		{
			try { wndParent = win.parent; } catch (e) { bOK = false; }
			if ((!bOK)||(!wndParent)||(wndParent==win))
			{
				break;
			}
			win = wndParent;
		}
	}
	return objAPI;
}

function GetAPI(win) // Revised to handle x-scripting errors
{
	// Sets gAPI to be a reference to the API object provided by the RTE,
	// or leave it as null if no API object could be found.
	// Parameter win is the SCO's window
	var wndParent = null;
	var wndOpener = null;
	try { wndParent = win.parent; } catch(e) { }
	try { wndOpener = win.opener; } catch(e) { }
	if ((wndParent != null) && (wndParent != win))
	{
		gAPI = _ScanForAPI(wndParent);
	}
	if ((gAPI == null) && (wndOpener != null))
	{
		gAPI = _ScanForAPI(wndOpener);
	}
}

function findScormAPI() {
	if ( gAPI != null ) {
		return gAPI;
	} else {
		GetAPI(window);
		return gAPI;
	}
}

// Calcuates the amount of time spent in the course, and returns a string in the proper format
function getFormattedSessionTime()
{
	var n = Math.round(((new Date()).getTime() - startDateTimeMilliSecs)/10);

	// Format is [HH]HH:MM:SS[.SS]
	var bTruncated = false;
	with (Math)
	{
		var nH = floor(n / 360000);
		var nCs = n - nH * 360000;
		var nM = floor(nCs / 6000);
		nCs = nCs - nM * 6000;
		var nS = floor(nCs / 100);
		nCs = nCs - nS * 100;
	}
	if (nH > 9999)
	{
		nH = 9999;
		bTruncated = true;
	}
	var str = "0000" + nH + ":";
	str = str.substr(str.length-5,5);
	if (nM < 10) str += "0";
		str += nM + ":";
	if (nS < 10) str += "0";
		str += nS;
	if (nCs > 0)
	{
		str += ".";
		if (nCs < 10) str += "0";
		str += nCs;
	}
	return str;
}



