var _Debug = false;
var _NoError = 0;
var _GeneralException = 101;
var _ServerBusy = 102;
var _InvalidArgumentError = 201;
var _ElementCannotHaveChildren = 202;
var _ElementIsNotAnArray = 203;
var _NotInitialized = 301;
var _NotImplementedError = 401;
var _InvalidSetValue = 402;
var _ElementIsReadOnly = 403;
var _ElementIsWriteOnly = 404;
var _IncorrectDataType = 405;
var apiHandle = null;
var API = null;
var findAPITries = 0;

var cookieUse = false;
var cookiePrompt = true;
var cookieTimeout = 60;

var FlatLearningUnit = true;

//Jenison Vars
var aiccon=0;AiccUrl='';AiccSid='';errorResp=0;conLF='%0D%0A';corelessonvar='';
var API = null;
var viewedar='';


function doLMSInitialize(){
parseURL();		// ParseUrl to look for AICC_URL and AICC_SID if found set aiccon=1
if(aiccon==1){
	// If Aicc Found
	CoreVars = new createCoreVars();		// Initialize Required Core Vars
	queryMSXML();				// Get Param
	var StartDate = new Date();		// Initialize timer
	StartTime = StartDate.getTime();	//
	readAICCVars();				// Use retrieved CoreVars to set course location etc
	}else {
    API = FindAPI(this.parent);
  }
  if (API != null) {
    var result = API.LMSInitialize("");
    var StartDate = new Date();
    StartTime = StartDate.getTime();
    ScormAPIGetData();
  }
}

function parseURL(){				//Extract AICC vars from URL
  URL_DATA = new Object(); 
  query = '' + this.parent.parent.location; 
  if (query.indexOf('?')==-1) { 
	return false;
  }else{
	  query = query.substring((query.indexOf('?')) + 1);
	  keypairs = new Object(); 
	  numKP = 1; 
	  while (query.indexOf('&') > -1) { 
	    keypairs[numKP] = query.substring(0,query.indexOf('&')); 
            query = query.substring((query.indexOf('&')) + 1); 
	    numKP++; 
	  } 
	  keypairs[numKP] = query; 
	    for (i in keypairs) { 
	            keyName = keypairs[i].substring(0,keypairs[i].indexOf('=')).toLowerCase(); 
	            keyValue = keypairs[i].substring((keypairs[i].indexOf('=')) + 1); 
	            while (keyValue.indexOf('+') > -1) { 
	                  keyValue = keyValue.substring(0,keyValue.indexOf('+')) + ' ' + keyValue.substring(keyValue.indexOf('+') + 1); 
	            }
	        keyValue = unescape(keyValue);
	        URL_DATA[keyName] = keyValue; 
	      }
		if(URL_DATA['aicc_url']){AiccUrl=URL_DATA['aicc_url'];aiccon=1;}
		if(URL_DATA['aicc_sid']){AiccSid=URL_DATA['aicc_sid'];}
   return true;
   }
}

function createCoreVars(){			//Initialize CoreVars Object
  this.StudentID="";this.StudentName="";this.Credit="";this.LessonLocation="";this.LessonStatus="";this.Score="";this.Time="";
  return this
}

function parseResponse(respStr){		//Break Response from GetParam into name, value array
var bufstr = '';
  RESPONSE_DATA = new Object(); 
  query = '' + respStr; 
  if (query.length < 1) { return false; }
  keypairs = new Object(); 
  numKP = 1; 
  var splitarray = '';
  splitarray = escape(query).split(conLF);
  for (i in splitarray){
  		if(unescape(splitarray[i]).indexOf('=') > -1){
		keypairs[numKP]=unescape(splitarray[i]);
		numKP++;}
  }
    for (i in keypairs) { 
            keyName = keypairs[i].substring(0,keypairs[i].indexOf('=')); 
            keyValue = keypairs[i].substring((keypairs[i].indexOf('=')) + 1); 
            while (keyValue.indexOf('+') > -1) { 
                  keyValue = keyValue.substring(0,keyValue.indexOf('+')) + ' ' + keyValue.substring(keyValue.indexOf('+') + 1); 
            }
        keyName = trim(keyName);
		keyName = keyName.toUpperCase();
        RESPONSE_DATA[keyName] = trim(keyValue); 
      }
return RESPONSE_DATA;
}

function trim(str){
var i=0,p = str.length-1;
	while(str.charAt(i)==' ') i++;
	while(str.charAt(p)==' ') p--;
if(i>p) return '';
return str.substring(i,p+1);
}

function BreakResponse(respStr){ //Calls parseresponse to seperate data retrieved from LMS getparam then reads vars into CoreVars object
	var RESPONSES = parseResponse(respStr);
	//Set Core Vars
	if(RESPONSES['STUDENT_ID']){
	CoreVars.StudentID = RESPONSES['STUDENT_ID'];}
	if(RESPONSES['STUDENT_NAME']){
	CoreVars.StudentName = RESPONSES['STUDENT_NAME'];}
	if(RESPONSES['LESSON_LOCATION']){
	CoreVars.LessonLocation = RESPONSES['LESSON_LOCATION'];}
	if(RESPONSES['CREDIT']){	
	CoreVars.Credit = RESPONSES['CREDIT'];}
	if(RESPONSES['LESSON_STATUS']){
	CoreVars.LessonStatus = RESPONSES['LESSON_STATUS'];}
	if(RESPONSES['SCORE']){	
	CoreVars.Score = RESPONSES['SCORE'];}
	if(RESPONSES['TIME']){	
	CoreVars.Time = RESPONSES['TIME'];}
	if(RESPONSES['CORELESSONVAR']){
	corelessonvar = RESPONSES['CORELESSONVAR'];}
}

function readAICCVars(){ // Action retrieved Corevars

//Used to Action Core Vars
}

function queryMSXML(){	// GetParam
  communicateMSXML('Command=GetParam&Version=3&Session_ID='+escape(AiccSid)+'&AICC_Data=');
}

function communicateMSXML(withString){ // This is the business object microsoft.xmlhttp used to do post to LMS AICC adapter
  var msXMLHTTP = new ActiveXObject("microsoft.xmlhttp");
  msXMLHTTP.open("POST", AiccUrl, false);
  msXMLHTTP.setRequestHeader("Server-protocol", "HTTP/1.0");
  msXMLHTTP.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  msXMLHTTP.send(withString);
  BreakResponse(msXMLHTTP.responseText);
}

function setParam(){ // Create Return string and send to communicateMSXML for return to LMS adapter
var putData='';
var vLF='\r\n';
putData +="[Core]"+vLF+"Lesson_Location="+CoreVars.LessonLocation+vLF;
putData +="Lesson_Status="+CoreVars.LessonStatus+vLF+"Time="+GetTimeOnPage()+vLF;
putData +="Score='0,0,0'"+vLF+"[Core_Lesson]"+vLF+corelessonvar;
communicateMSXML('Command=PutParam&Version=3&Session_ID='+escape(AiccSid)+'&AICC_Data='+escape(putData));
}

function ExitAu(){ // Write progress into Corevars object and execute the setParam then send ExitAU
  writeAICCVars();
  setParam();
  communicateMSXML('Command=ExitAU&Version=3&Session_ID='+escape(AiccSid));
}

function GetTimeOnPage() 
// Calculate time spent on page
{
  var EndDate = new Date();
  var EndTime = EndDate.getTime();
  var NewTime = EndTime-StartTime;
  var timediff = new Date();
  timediff.setTime(NewTime);
  dd = timediff;
  dd = Math.floor(timediff/1000);   var sst = dd % 60;  if (sst < 10) sst = '0' + sst;
  dd = Math.floor(dd/60);           var mmt = dd % 60;  if (mmt < 10) mmt = '0' + mmt;
  dd = Math.floor(dd/60);           var hht = dd % 24;  if (hht < 10) hht = '0' + hht;
  return hht + ':' + mmt + ':'+sst;
}

// End of jenison code ******************************************************


function doLMSFinish() //called when the application is exited
{
	if(aiccon==1){
		ExitAu();
	}else if  (API != null) {
        var now = new Date();
        ExitSCO();
    }
}

function doLMSGetValue(name) //gets the value held in a cookie
{
	if(name=='cmi.suspend_data'){
		value=corelessonvar;
	}
	return String(value); //return the value returned from the lmsgetvalue function
}

function writeAICCVars(){  // Set Corevars to reflect progress in course
     CoreVars.LessonLocation = 0;
	 CoreVars.Score=0;
}

function doLMSSetValue(name, value) //Sets tha value of a given cookie to a given value
{
	if(name=='cmi.suspend_data'){
		corelessonvar='corelessonvar='+value;
	}else if(name=='cmi.core.lesson_status'){
		CoreVars.LessonStatus=value;
	}
	return; //return nothing
}



// next code added by matc, 7/11/5, emailed by andrewd
var szone = 0;
var start=new Date();
var theSeverTime;
var server = new Date();

function clockClass()
{
	this.iterate = function()
	{
		var digital = new Date(theSeverTime);
		var ofst    = digital.getTimezoneOffset()/60;
		var hours   = digital.getHours() + parseInt(ofst) + parseInt(szone);
		var minutes = digital.getMinutes();
		var seconds = digital.getSeconds();
		var amOrPm  = "AM";
		if (hours <= 9) hours = "0" + hours;
		if (minutes <= 9) minutes = "0" + minutes;
		if (seconds <= 9) seconds = "0" + seconds;
		top.dispTime = hours + ":" + minutes + ":" + seconds;
	}
}
clockClass.prototype = new Object();

function serverdate()
{
	var dateNow = new Date();
	var difference = dateNow.getTime() - start.getTime();
	theSeverTime = difference;
	setTimeout("serverdate()",500);
}

function timeInit()
{
	if (!document.getElementById) return;
	serverdate();
	clockObj = new clockClass("Loadon", 0);
	clockObj.iterate();
	setInterval("clockObj.iterate()", 500);
}

timeInit();

var MY_COOKIES = { //cookies object

	getCookie:		function(name, d) { //get cookies function
				  if (!d) var d = null; //create var d if it did not exist before
				  var arg = name + "=";
				  var alen = arg.length;
				  var clen = document.cookie.length;
				  var i = 0;
				  while (i < clen) {
				    var j = i + alen;
				    if (document.cookie.substring(i, j) == arg) {
				      var endstr = document.cookie.indexOf (";", j);
				      if (endstr == -1) endstr = document.cookie.length;
				      return unescape(document.cookie.substring(j, endstr));
 				    }
				    i = document.cookie.indexOf(" ", i) + 1;
				    if (i == 0) break;
				  }
				  return d;
				},

	setCookie:		function(name, value, expires) {	//set cookies function
				  if (expires) { //if a value is set for expires then set expires to be a number of hours
				    var exp = new Date();
				    exp.setTime(exp.getTime() + (expires*60*60*1000));
				    expires = exp;
				  }
				  document.cookie = name + "=" + escape(value) + ((expires == null) ? "" : ("; expires=" + expires.toGMTString()));
				  //set up the cookie with a name, a value and an expiry date/time
				  if (_Debug){ //if debug mode then show an alert
				    alert( "cookie string == " + document.cookie );
				  }
				},

	deleteCookie:		function(name) { //function deleteCookie. Sets the expiry time of the cookie to be one that has already past
				  var exp = new Date();
				  exp.setTime (exp.getTime() - 1000);
				  var cval = this.getCookie (name);
				  document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
				},

	debug:			function(){ //debug function
					alert( "COOKE DEBUG:\n\n" + document.cookie ); //shows an alert
				},

	deleteAllCookies:	function() {	//function to delete all of the cookies. Gets the name of each of the cookies from the cookie string and then calls the deletecookie function.
					var start_pointer = 0; //
					var end_pointer = -1;
					var cookie_names = new Array();
					for(var n = 0; n < document.cookie.length; n++){
					    if (document.cookie.substr(n,1) == ";"){
					    	n++;
					    	start_pointer = n;
					    }
					    if( (start_pointer != -1) && (document.cookie.substr(n,1) == "=") ){
					    	end_pointer = n;
	 				    }
	 				    if( (start_pointer != -1) && (end_pointer != -1) ){
	 				    	cookie_names[cookie_names.length] = document.cookie.substring(start_pointer,end_pointer);
	 				    	start_pointer = -1;
	 				    	end_pointer = -1;
	 				    }
					}
					for(var n = 0; n < cookie_names.length; n++){
						this.deleteCookie(cookie_names[n]);
					}
				},

	find:			function(id, frame, d) { //finds something on the page
				  var img = null;
				  if (!d) {
				    if (frame && top[frame]) d = top[frame].document;
				    else d = document;
				    if (!d) return null;
				  }
				  if (d.layers) {
				    img = d.layers[id];
				    if(!img) img = d.links[id];
				    if(!img) img = d.images[id];
				  }
				  else if (d.getElementById) img = d.getElementById(id);
				  for (var i=0; !img && d.layers && i<d.layers.length; i++){
				    img = this.find(id, null, d.layers[i].document);
				  }
				  return img;
				}

}

var lmsResult = doLMSInitialize();
if ((lmsResult == "true") || (lmsResult == true)) { //works out if the lms is available or not
	LMSAvailable = true;
}else{
	LMSAvailable = false;
}

function doLMSCommit()
{
//no commit
}

//Jenison Scorm

function ExitSCO()
// Exit for Scorm
{
  a1 = (currslide==CSlides.length-1) ? "complete" : "incomplete";
  var result = API.LMSSetValue("cmi.core.lesson_location", currslide + '');
  result = API.LMSSetValue("cmi.core.session_time", GetTimeOnPage());
  result = API.LMSSetValue("cmi.core.lesson_status", a1);
  result = API.LMSSetValue("cmi.core.score.raw", currscore + '');
  result = API.LMSSetValue("cmi.core.score.min", "0");
  result = API.LMSSetValue("cmi.core.score.max", "100");
  result = API.LMSSetValue("cmi.suspend_data", '');
  result = API.LMSCommit("");
  result = API.LMSFinish("");
}

function ScormBreakResponse(respStr)
// Get additional response values (Scorm) - Most Scorm values are attained from API.
{
//  var RESPONSES = parseResponse(respStr);
  //Set Core Vars
//  if (RESPONSES['TQBREAKDOWN'])     aibreakdown = RESPONSES['TQBREAKDOWN'];
//  if (RESPONSES['TWEAKNESS'])       weakness = RESPONSES['TWEAKNESS'];
}

function ScormAPIGetData()
// Get data from LMS using Scorm API
{
  ScormBreakResponse(API.LMSGetValue("cmi.suspend_data"));
	if(API.LMSGetValue("cmi.core.lesson_location")!=''){
		currslide = parseInt(API.LMSGetValue("cmi.core.lesson_location"));
	}
  var getscore = parseInt(API.LMSGetValue("cmi.core.score.raw"));
  var getstatus = API.LMSGetValue("cmi.core.lesson_status");
  var passmark = API.LMSGetValue("cmi.student_data.mastery_score");
}

function FindAPIInWin(winto)
// Attempt to find the Scorm API in this window
{
  var API = winto.API;
  if (API == null) {
    if (winto.length > 0) {
      for (var i = 0; i < winto.length; i++) {
        API = FindAPIInWin(winto.frames[i]);
        if (API != null) break;
      }
    }
  }
  return API;
}

function FindAPI()
// Attempt to find the Scorm API
{
  var API;
  API = FindAPIInWin(this.top);
  if (API == null) {
    if (typeof(this.opener) != "undefined") {
      if (this.opener != null) {
        API = FindAPIInWin(this.opener);
      }
    }
  }
  return API;
}

