// Copyright 2002 Macromedia, Inc. All rights reserved.

var MM_SID="", MM_TURL="", MM_CMIDOC="", aicd = "aicc_data", co = "[core]", ls="Lesson_Status", cmnd="command", cmdArray;
var IE3 = ((navigator.appName.indexOf("Microsoft") != -1) && (parseFloat(navigator.appVersion) < 3));
if (window.cmdQueue == null)
  window.cmdQueue = new CmdQueue()

function CmdQueue() {
  this.cmd = new Array();
  this.cmdData = new Array();
  this.sIDs = new Array();
  this.qLen = 0;  
  this.latency = (navigator.appName.indexOf('Microsoft') != -1)?1250:1000;
  this.addCmd = cmdQAddCmd;
  this.delCmd = cmdQDelCmd;  
}

var xmlhttp= null;
var returnedData  = null;

function SendCommandsToServer(url, send)
{
	try 
	{
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} 
	catch (e) 
	{
		try 
		{
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} 
		catch (ee) 
		{
			xmlhttp = ( !window.XMLHttpRequest ) ? ( new ActiveXObject( "Microsoft.XMLHTTP" ) ) : ( new XMLHttpRequest() );
		}
	}		
	xmlhttp.onreadystatechange = readyChange;
	xmlhttp.open( "POST", url , false);
	xmlhttp.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' );
	xmlhttp.send(send);
};

function readyChange()
{
	if( xmlhttp.readyState==4 )
	{
	// if "OK"
	  if (xmlhttp.status==200)
		{
			returnedData = xmlhttp.responseText;
			if(returnedData != null)
			{
				document.command.elements[aicd].value = returnedData;
			}
			
			//alert("returnedData:" + returnedData);
			window.status = "returnedData:" + returnedData;
			
			// GET LESSON LOCATION FROM RETURNED DATA			
			lesson_location = CMIAICCGetValue(returnedData,"core", "lesson_location");
			
			//alert("2lesson_location1:" + lesson_location);
			window.status = "lesson_location0:" + lesson_location;
					
			if(lesson_location != null && lesson_location != "undefined" && lesson_location != "")
			{
				CMIitem  = 1;
				//alert("2lesson_location2:" + lesson_location);
				window.status = "lesson_location:" + lesson_location;
					
				// SET SHELL TO GO TO THE AICC_LOCATION, ELSE START FROM START.
				shellObj.SetVariable("_global.aicc", "1");
				shellObj.SetVariable("_global.aicc_enabled", true);
				shellObj.SetVariable("_global.aicc_sid", MM_SID);
				shellObj.SetVariable("_global.aicc_location", lesson_location);
				shellObj.SetVariable("_global.currentPage", lesson_location);
				
				shellObj.SetVariable("aicc", "1");
				shellObj.SetVariable("aicc_enabled", true);
				shellObj.SetVariable("aicc_sid", MM_SID);
				shellObj.SetVariable("aicc_location", lesson_location);
				shellObj.SetVariable("currentPage", lesson_location);
				shellObj.SetVariable("navigation.screenIndex", lesson_location);
				
				shellObj.SetVariable("_global.aicc_bookmark", "bookmark");
				shellObj.SetVariable("aicc_bookmark", "bookmark");
				
				
				
				//var lcId = new Date().getTime();
				//var flashProxy = new FlashProxy(lcId, "scripts/JavaScriptFlashGateway.swf");
				//flashProxy.call("aiccGotoBookmark", "");
				
			}
			
		}
	  }
}

function cmdQAddCmd(command, sid, cmddata) {
  this.cmd[this.qLen] = command;
  this.sIDs[this.qLen] = sid;
  this.cmdData[this.qLen] = cmddata;
  this.qLen++;
  if (this.qLen == 1) { 
    if (!IE3 && (window.CmdSubmit == null))
      window.CmdSubmit = CmdSubmit; 
    setTimeout("CmdSubmit()", this.latency); 
  }
}

function cmdQDelCmd() {
  var i, len;
  if (this.qLen == 0) return;
  else if (this.qLen == 1)
    this.cmd.length = this.sIDs.length = this.cmdData.length = 0;
  else {
    for (i=1, len=this.qLen; i<len; i++) {
      this.cmd[i-1] = this.cmd[i];
      this.sIDs[i-1] = this.sIDs[i];
      this.cmdData[i-1] = this.cmdData[i];
    }
    this.cmd.length = this.sIDs.length = this.cmdData.length = this.qLen - 1;
  }
  this.qLen--;
}

function CmdSubmit() {
InternetExplorer = navigator.appName.indexOf("Microsoft") != -1;
shellObj = InternetExplorer ? shell : document.shell;

    document.command.elements[cmnd].value = cmdQueue.cmd[0];
    document.command.elements["session_id"].value = cmdQueue.sIDs[0];
	
	// FIX to MACROMEDIA GETPARAM - USE XMLHTTP TO GRAB VALUES AND SET TO CURRENT AICC_SID
	if( document.command.elements[cmnd].value == "getparam")
	{
	// BLANK ANY AICC_DATA VALUE
		document.command.elements[aicd].value = "";
		
		// CALL XMLHTTP IF GETPARAM
		//alert("MM_TURL:" + MM_TURL);
		var arrUrl = MM_TURL.split("/");
		arrUrl[0] = "";
		arrUrl[1] = "";
		arrUrl[2] = "";
		var strUrl = "";
		for(h=3;h<arrUrl.length;h++){
			strUrl = strUrl + "/" + arrUrl[h];
		}
		//alert("strUrl:" + strUrl);		
		SendCommandsToServer(strUrl,"command=getparam&session_id=" + MM_SID + "&aicc_data=");
		
		// IF WE HAVE DATA THEN SET TO AICC_DATA	

	}else{
		document.command.elements[aicd].value = cmdQueue.cmdData[0];
		document.command.submit();
	}

    cmdQueue.delCmd();
    if (cmdQueue.qLen >= 1) {
      if (!IE3) window.CmdSubmit = CmdSubmit;
      setTimeout("CmdSubmit()", cmdQueue.latency);
    }
}

function MM_SGet() {document.command.elements["command"].value = "getparam";}
function MM_SPut() {document.command.elements["command"].value = "putparam";}
function MM_SPInt() {document.command.elements["command"].value = "putinteractions";}

function MM_SVal(idx, val0, sub) {
  document.command.elements[idx].value=val0;
  if (sub) MM_Sub();
}
function MM_ApndVal(val0) {document.command.elements[aicd].value += '\r\n'+val0;}

function MM_Sub() {
  if (MM_SID.length > 0) {
    var frm = document.command;
	//alert("htl:" + document.innerHTML);
	
    cmdQueue.addCmd(frm.elements[cmnd].value,MM_SID,frm.elements[aicd].value);
  }
}

function MM_CMISetParms(url) {
  var prms="", tmpp;  
  pos=url.indexOf("#")
  if (pos==-1) pos=url.indexOf("?")
  if (pos>-1) prms=url.substring(pos+1,url.length)
  tmpp=prms.toUpperCase()
  if (tmpp.indexOf("AICC-SID")>-1) {
    alert("Lesson Server version incompatible.  Your administrator must upgrade to the latest version.");
    return false;
  }
  if ((pos=tmpp.indexOf("AICC_SID="))>-1) {
    MM_SID=prms.substring(pos+8,prms.length)
    if (MM_SID.indexOf("&")>0)
      MM_SID=unescape(MM_SID.substring(1,MM_SID.indexOf("&")))
  }
  if ((pos=tmpp.indexOf("AICC_URL"))>-1) {
    MM_TURL=prms.substring(pos+9,prms.length)
    if (MM_TURL.indexOf("&")>0)
      MM_TURL=MM_TURL.substring(1,MM_TURL.indexOf("&"))
    MM_TURL=unescape(MM_TURL)
  }
  return (MM_TURL=="" || MM_SID=="")?false:true;  
}

function findcmidocument(win) { 
  if (MM_CMISetParms(win.document.location+"") == false) {
    if (win == window.top) return null
    return findcmidocument(win.parent)
  } else {
    MM_CMIDOC = win.document;
    return win.document;
  }
} 

function cmiinit(win) {
  frm=findcmiframe(null);
  if (frm!=null)
   frm.installcmi(win);
  findcmidocument(win);
  window.CMITURL = MM_TURL;
  return CMIIsPresent();
}

function CMIInitialize() {
  if ((MM_CMIDOC!=null) && (MM_CMIDOC.length!=0)){  
    MM_SVal("session_id",MM_SID);
	MM_SVal("command","getparam",1);
    retVal = true;
  } else retVal = false;
  return retVal;
}

function CMIIsPresent() {
  return MM_SID.length != 0;
}
var nLocation	= "";
function CMIAICCGetValue(str, section, getvar)
{
	if(str.length >0)
	{
		//alert("data1:" + str);
		arrstr = str.split("[");
		if(arrstr.length > 0)
		{
			for(i=0;i<arrstr.length;i++)
			{
				//alert("data2:" + arrstr[i]);
				arritem = arrstr[i].split("]");
				//alert("arritem[0]:" + arritem[0]);
				if(arritem[0] == section)
				{
					//alert("inner" + arritem[1]);
					arrinner = arritem[1].split("\r\n");
					//alert("inner" + arrinner.toString());
					if(arrinner.length > 0)
					{
						
						for(h=0;h<arrinner.length;h++)
						{
							arrg = arrinner[h].split("=");
							//alert("arrg" + arrg.toString());
							if(arrg[0] == getvar)
							{
							//alert("nLocation:" + nLocation);
								nLocation = arrg[1];
								return arrg[1];
							}
						}
					}
				}
			}
		}
	}
	return "";
}

function CMIAddInteraction(date, time, intid, objid, intrtype, correct, student, result, weight, latency) {
  MM_SVal("command","putinteractions")
  MM_SVal(aicd,'"date", "time", "interaction_id", "objective_id", "type_interaction", "correct_response", "student_response", "result", "weighting", "latency"\r\n' +
    '"' + date + '", ' +
    '"' + time + '", ' +
    '"' + intid + '", ' +
    '"' + objid + '", ' +
    '"' + intrtype + '", ' +
    '"' + correct + '", ' +
    '"' + student + '", ' +
    '"' + result + '", ' +
    '"' + weight + '", ' +
    '"' + latency+ '"',1);
}

function CMISetCompleted() { CMISetStatus("C"); }

var gStatus	= "i";
var gScore	= "";
var gLocation = nLocation;
var gTime = "0:00:00";
var gTimeSet = false;
var gD		= new Date();
var gStartSeconds	= Math.round(gD.getTime() / 1000);
function getCore()
	{
	var	core	= "[core]\r\n";
	core	+= "lesson_status=" + gStatus + "\r\n";
	core	+= "score=" + gScore + "\r\n";
	core	+= "lesson_location=" + gLocation + "\r\n";
	if (gTimeSet == false)
		{
		d	= new Date();
		formatTime( Math.round(d.getTime() / 1000) - gStartSeconds );
		gStartSeconds	= Math.round(d.getTime() / 1000);
		}
	core	+= "time=" + gTime + "\r\n";
	return core;
	}


function CMISetData(data) {
  MM_SPut()
  MM_SVal(aicd,getCore() + "[Core_Lesson]\r\n"+data,1)
}

function CMISetFailed() { CMISetStatus("F"); }

function CMISetLocation(loc) {
  MM_SPut();
  gLocation	= loc;
  MM_SVal(aicd,getCore(),1)
}

function CMISetObj(index, id, score, status, started, completed, passed, failed) {
  MM_SPut()
  MM_SVal(aicd,getCore() + "[Objectives_Status]\r\nJ_ID."+index+"="+id)
  // if objective info isn't there already need to write a not-started flag
  if (status=="")
    MM_ApndVal("J_STATUS."+index+"="+started?'I':completed?'C':passed?'P':'F');
  else 
    MM_ApndVal("J_STATUS."+index+"="+status); 
  MM_ApndVal("J_SCORE."+index+"="+score);
  MM_Sub();
}

function CMISetPassed() { CMISetStatus("P"); }

function CMISetScore(score) { 
  MM_SPut()
  gScore	= score;
  MM_SVal(aicd,getCore(),1)
}

function CMISetStarted() { CMISetStatus("I"); }

function CMISetStatus(stat) {
  MM_SPut();
  gStatus	= stat;
  MM_SVal(aicd,getCore(),1)
}

function formatTime(t)
	{
	var x=3600;
	var y=60;
	var h=Math.round(t/x - t%x/x)+'';
	var m=Math.round((t-h*x)/y-(t-h*x)%y/y)+'';
	var s=Math.round(t-h*x-m*y)+'';
	if (h.toString().length == 1) h='0'+h;
	if (m.toString().length == 1) m='0'+m;
	if (s.toString().length == 1) s='0'+s;
	gTime	= h+":"+m+":"+s;
	}

function CMISetTime(t) {
	formatTime(t);
  MM_SPut()
  MM_SVal(aicd,getCore(),1)
  gTimeSet	= true;
}

function CMISetTimedOut() {
  MM_SPut()
  gStatus	= "incomplete,time-out";
  MM_SVal(aicd,getCore(),1)
}

function installcmi(win) {
  if ((win.CMIInitialize == null) && !IE3) {
    win.CMIInitialize = CMIInitialize;
    win.CMIIsPresent = CMIIsPresent;
    win.CMIAddInteraction =CMIAddInteraction
    win.CMISetCompleted =CMISetCompleted
    win.CMISetData =CMISetData
    win.CMISetFailed =CMISetFailed
    win.CMISetLocation =CMISetLocation
    win.CMISetObj =CMISetObj
    win.CMISetPassed =CMISetPassed
    win.CMISetScore =CMISetScore
    win.CMISetStarted =CMISetStarted
    win.CMISetStatus =CMISetStatus
    win.CMISetTime =CMISetTime
    win.CMISetTimedOut =CMISetTimedOut
    win.CMITURL = MM_TURL
  }
}


