//Error handler
function silentHandler()  {return true}
window.onerror=silentHandler


/*
	Class Servder View	ECS_ViewType value	Code to Execute
	Authoring			0					Nothing
	Preview				1					Nothing
	Assigned			2					get & set for Points and State
	Grading				3					get for State
	Graded				4					get for State
	Print				5					Nothing

*/

//Declare Global variables
	var starInteractionObj = new Object();
	var adlAPI = new Object();
	var lmsInitialized = false;
	var viewType = -1;
	var maxPoints = 20;
	var interactionScore = 0;
	var sco_min = -1;
	var sco_max = -1;
	var sco_score = -1;
	var kor_field_array = new Array("Q1_1","Q2_1","Q3_1","Q4_1"); //This is the list of fields that theKOR data will stripe Accross
	
	//var scormDebug = false;  //set to true if goal is to debug SCORM inside Class Server
	

// Hook for Internet Explorer.

if (navigator.appName && navigator.appName.indexOf("Microsoft") != -1 && navigator.userAgent.indexOf("Windows") != -1 && navigator.userAgent.indexOf("Windows 3.1") == -1)
{
	document.write('<script language=\"VBScript\"\>\n');
	document.write('On Error Resume Next\n');
	document.write('Sub starInteraction_FSCommand(ByVal command, ByVal args)\n');
	document.write('	Call starInteraction_DoFSCommand(command, args)\n');
	document.write('End Sub\n');
	document.write('</script\>\n');
}
var isInternetExplorer = navigator.appName.indexOf("Microsoft") != -1;
var isWindows = navigator.userAgent.indexOf("Windows") != -1 ;

/*
Method:       	isMCS
Return Type:	Boolean
				true - Microsoft Class Server Environment
				false - Some other environment

Purpose:  This is the test to see if the environment is Microsoft Class Server.

*/
function isMCS()
{
//*********************************override detection of Microsoft Class Server  -- return false so that SCORM functionality kicks in
	return false;
	if (viewType == -1)
	{
		//return false;
		return true;
    }
	else{
		return true;
    }
}
/*
-------------------------------------------------------------------------------------------------
Method:       	getAPI
Return Type:	None

Purpose:  Looks for the SCORM API object in the parent window

*/
function getAPI()
{
	win = window;
  	str = "";
    while ((win.API_1484_11 == null) && (win.parent != null) && (win.parent != win))
    {
	   	win = win.parent;
    }
    return win.API_1484_11;
}




/*
-------------------------------------------------------------------------------------------------
Method:       	checkSCORMExists
Return Type:	True or False

Purpose:  	lmsInitialized is a global var that gets set to True if
		SCORM API successfully initialized

*/
function checkSCORMExists()
{
	//window.alert("Check if scorm exists.  Result = " + lmsInitialized);
	return lmsInitialized;
}

/*
Method:       	load
Return Type:	None

Purpose:  	Upon HTML load, calls getAPI method; if SCORM is already initialized,
		calls Terminate, and re-initializes

*/
function load()
{

	//window.alert("Loading");
	

	starInteractionObj = isInternetExplorer ? document.all.starInteraction : document.starInteraction;
	var isWindows = navigator.userAgent.indexOf("Windows") != -1 ;

	if(isWindows)
	{
		//alert('isWindows: ' + isWindows);
		starInteractionObj.SetVariable("htmlPage", "true");
	}

	var obj = document;
	
	if(typeof ECS_ViewType == 'undefined')
	{	
		viewType = -1;
	} else {
		viewType = ECS_ViewType;
	}

    // make sure the browser supports minimum functionality
	if  ((!document.getElementById) && (!document.all))
    {
     	//alert("This browser does not meet minimal requirements");
        return;
    }
    adlAPI = getAPI();

	if (adlAPI == null)
    {
       	//window.alert("Unable to load SCORM adaptor");
        return;
    }
	else {
		//window.alert("Initializing SCORM....");
       	lmsInitialized = adlAPI.Initialize("");

        if (!lmsInitialized)
		{
        	adlAPI.Terminate("");
            lmsInitialized = adlAPI.Initialize("");
            //window.alert("adlAPI terminated. Failure to find Scorm");

		}
        	//window.alert("Found SCORM adaptor. Great!");
	}

	
}

// Handle all the FSCommand messages in a Flash movie.
function starInteraction_DoFSCommand(command, args)
{
	starInteractionObj = isInternetExplorer ? document.all.starInteraction : document.starInteraction;

	if (command == "fsPing")
	{
		// This responds to the initial request from the flash object to verify
        // that fscommand() works.  If it does, this line will execute and the
        // value 'true' will be set to the flash _root.fsworks variable, if fscommand
        // doesn't work, this line will not be called, and the _root.fsworks variable
        // will remain set to 'false' and future calls will be made through getURL().

		starInteractionObj.SetVariable("fsworks", "true");
   }

	if (command == "exec")
	{

		// take the message and process it through externalCommand() as we
        // would if the command arrived from flash using the getURL() function.

        //window.alert("page.doFScommand reached with " + args);
		externalCommand( args );
     }
}

/*
-------------------------------------------------------------------------------------------------
Method:       	externalCommand(cmd)
Return Type:	None

Purpose:  	Called from the Flash object directly through getURL or called through the FSCommand
		The cmd comes in two parts:
		"command data"
		If the characters before the first space are the command and the remaining characters comprise the data.

*/
function externalCommand( arg )
{

	//alert("externalCommand called with the following argument:  " + arg);
	var spaceIndex = arg.indexOf(' ');

	var cmd = arg.substring(0,spaceIndex);
	var cmdOption = cmd.substring(0,6);
	cmd = cmd.substring(7, cmd.length);
	var data = arg.substring(spaceIndex, arg.length);

	if(cmdOption == 'setCMI')
	{
		
		setCMI(cmd,data);
	}
	if(cmdOption == 'getCMI')
	{
		if(isWindows)	//Only Windows can you use SetVariable
		{
			var rc = getCMI(cmd);

			switch(cmd)
			{
				case 'cmi.suspend_data':
					starInteractionObj.SetVariable("state", rc);

					break;
				
			}
		}
	}	
	//return 1
}

/*
-------------------------------------------------------------------------------------------------
Method:       	setCMI
Return Type:	True or False

Purpose:  	Used with adlAPI.LMSSetValue(cmiElement,cmiData) to communicate
			various cmi options to the server via the adlAPI adapter

*/
function setCMI(cmiElement,cmiData)
{
	//alert('setCMI: ' + cmiElement + ', ' + cmiData + "      isMCS(): " + isMCS() );
	if(isMCS())
	{
		//alert('Class Server Exists - setCMI: ' + cmiElement + ": " + cmiData);
		switch(cmiElement)
		{
			case 'cmi.suspend_data':
				if(viewType == 2)
				{
					saveMCSState(cmiData);
				}
				break;	
			case 'cmi.suspend_kor':
				if(viewType == 2)
				{
					//alert('saveMCSKOR: ' + cmiData)
					saveMCSKOR(cmiData);
				}
				break;	

			case 'cmi.core.score.max':
				//interactionScore = cmiData;
				sco_max = cmiData;
				setPointsIfValid();
				break;	
			case 'cmi.core.score.min':
				sco_min = cmiData;
				setPointsIfValid();
				break;	
			case 'cmi.core.score.raw':
				if(viewType == 2)	//Student Assigned
				{
					sco_score = cmiData;
					setPointsIfValid();
				//	var actualScore = (maxPoints/interactionScore) * cmiData;
					//alert('actualScore: ' + actualScore);
				//	defaultStatus = 'cmiData: ' + cmiData + '  actualScore: ' + actualScore + '  maxPoints: ' + maxPoints + '  interactionScore : ' + interactionScore;
				//	setPoints(actualScore);
				}
				break;	
		}				
	} else {
		if (lmsInitialized)
		{
			//remove core. from data elememts
			
			if(cmiElement == 'cmi.core.score.max'){
				
				cmiElement = 'cmi.score.max';
			}
			
			if(cmiElement == 'cmi.core.score.min'){
				
				cmiElement = 'cmi.score.min';
			}
			
			if(cmiElement == 'cmi.core.score.raw'){
				
				cmiElement = 'cmi.score.raw';
			}


			//window.alert("About to call adlAPI.setValue with the following arguments: " + cmiElement + " " + cmiData);
			
			
			var returnVal = adlAPI.SetValue(cmiElement,cmiData);
			var returnVal = adlAPI.Commit('');
			//window.alert("Error Status of SetValue:  " + adlAPI.GetErrorString(adlAPI.GetLastError()));
		}
	}
}
function setPointsIfValid()
{
	//This exists so that no matter what order the calls come in, they will record properly.
	//It seems that different browsers process the js command in different orders even when called in the
	//same order every time. Arghh!
	if(sco_score > -1 && sco_min > -1 && sco_max > -1)
	{
		var actualScore = (maxPoints/sco_max) * sco_score;
		//defaultStatus = 'sco_score: ' + sco_score + '  sco_min: ' + sco_min + '  maxPoints: ' + maxPoints + '  sco_max : ' + sco_max;
		setPoints(actualScore);
	
	}
	


}
function getCMI(cmiElement)
{
	
	if(isMCS())
	{
		//In class server
		switch(cmiElement)
	    {
			case 'cmi.suspend_data':
			if(viewType == 2 || viewType == 3 || viewType == 4) //Student Assigned, Teacher Grading
			{
				var gs = getMCSState();
				//alert('gs: ' + gs);
				return gs;
			} else {
				return "Check Local";
			}
			break;						        
		}	
	} else {
		if (lmsInitialized)
			return adlAPI.GetValue(cmiElement);
		}		
}

//STARTRACKER -- CS SLUG HANDLER

function saveMCSState(state)
{
	document.frmPage.Q8_1.value = state;
}
function saveMCSKOR(state)
{
	document.frmPage.Q1_1.value = "<KOR>" + state + "</KOR>";	
	stripeKOR(state);
}

function stripeKOR(data_str)
{
	stipeDataToFields(data_str,kor_field_array);
}
function getStripedKOR()
{
	var data_str = getStipedDataFromFields(kor_field_array);
	return data_str;
}
function stipeDataToFields(data_str,field_array)
{
	var loopCount = field_array.length;							//How many fields or pieces are there going to be?
	var charLength = Math.floor(data_str.length/loopCount) + 1;		//Figure out how big each chunk should be
	for(var i = 0; i < loopCount; i ++)
	{
		var p = data_str.substring(i * charLength,i*charLength + charLength);
		document.frmPage[field_array[i]].value = "<KOR" + i + ">" + p + "</KOR" + i + ">";	
	}
}
function getStipedDataFromFields(field_array)
{
	var viewType = "";
	var result = "";
	var p1 = "";
	var p2 = "";
	var p3 = "";

	if(typeof ECS_ViewType == 'undefined')
	{	
		viewType = -1;
	} else {
		viewType = ECS_ViewType;
	}
	
	var p = "";
	var loopCount = field_array.length;

	for(var i = 0; i < loopCount; i ++)
	{
		var startDelim ="&lt;KOR" + i + "&gt;";
		var endDelim ="&lt;/KOR" + i + "&gt;";
		
		if(viewType == 2 || viewType == 4) //Student View - HTML & Form Fields Present
		{
			if(typeof document.body.innerHTML != 'undefined')
			{
				source_str = document.body.innerHTML;
			}
		}
				
		if(viewType == 3 ) //Teacher Grading View - HTML & Form Fields Present
		{
			var source_str = cs_aTextInits[i];	
		}
		//alert(i + ") source_str: " + source_str);
		var rc_str = convertData(getData(source_str,startDelim,endDelim));
		//alert("rc_str: " + rc_str);
		result = result + rc_str;
	}
	//alert("rc_str: " + rc_str);

	

	//result = rc_str;

	return result;
}

function convertData(myString)
{
	//alert("myString: " + myString);
	//myString = new String("Go &#39;to&#39; &lt;DevGuru&gt; today!")
	var results = new String("");

	rExp = /&lt;/gi;
	//rExp = "&lt;";
	newString = new String ("<");
	results = myString.replace(rExp, newString);

	rExp = /&gt;/gi;
	//rExp = "&gt;";
	newString = new String (">");
	results = results.replace(rExp, newString);

	rExp = /&#39;/gi;
	//rExp = "&#39;";
	newString = new String ("'");
	results = results.replace(rExp, newString);


//alert("results: " + results);
	return results;

}

//================================================================================================
function getMCSState()
{
	
	var result = "Check Local";
	var source_str = "";

	if(viewType == 2) //Student View - HTML Form Fields Present
	{
		if (typeof document.frmPage.Q8_1 != 'undefined')
		{
			source_str = document.frmPage.Q8_1.value;
			return source_str; //We are done. It is in the correct format
		}
	}
	if(viewType == 3 ) //Teacher Grading View - HTML but Form Fields Not Present
	{
		if (typeof document.frmPage.Q8_1 != 'undefined')
		{
			source_str =document.frmPage.Q8_1.DocumentHTML;
			//source_str = cs_aTextInits[0];

		}
		
	}
	if(viewType == 4 ) //Student Graded View - HTML but Form Fields Not Present
	{
		if(typeof document.body.innerHTML != 'undefined')
		{			
			source_str = document.body.innerHTML;
		}		
	}

	var startDelim ="&lt;state&gt;";
	var endDelim ="&lt;/state&gt;";
	var rc_str = getData(source_str,startDelim,endDelim);

	//Try this. It uses Regular Expressions
	result = convertData(rc_str);

	return rc_str;
}
//================================================================================================
function getMCSKOR()
{
	var result = getStripedKOR();
	return result;
}
function getPrintIcon()
{
	var result = "<BR><a href=\"javascript:printpage();\"><IMG SRC=\"system/printer.gif\" WIDTH=\"23\" HEIGHT=\"24\" BORDER=\"0\" ALT=\"Print This Page\"></a>";
	return result;
}
function setPoints(pointValue)
{
	var pointValue = Math.floor(pointValue);
	
	//tens
	var numberOfTens = Math.floor(pointValue / 10);
	if(numberOfTens == 2)
	{
		numberOfTens = 1;
	};
   	var remainder = pointValue - (numberOfTens * 10);
	
  //fives
  	var numberOfFives = Math.floor(remainder / 5);
	if(numberOfFives == 2)
	{
		numberOfFives = 1;
	};
   	remainder = remainder -  numberOfFives * 5;
	var numberOfOnes = remainder;
  //ones

  	if(pointsExist())
		{
		alert("You have either already completed or submitted this assignment.");
		return;
	}

	var tensRadioGrp = document.frmPage.Q5;
	var fivesRadioGrp = document.frmPage.Q6;
	var onesRadioGrp = document.frmPage.Q7;
	eval(tensRadioGrp[numberOfTens * 1].checked= true); //Varients cause problems in Mac environments
	eval(fivesRadioGrp[numberOfFives * 1].checked= true);
	eval(onesRadioGrp[numberOfOnes * 1].checked= true);
} //end function

function pointsExist()
{
	var tensRadioGrp = document.frmPage.Q5;
	if (typeof tensRadioGrp != 'undefined')
	{//1
		if(typeof tensRadioGrp[0] != 'undefined' && typeof tensRadioGrp[1] != 'undefined')
		{ //2
	       	if(tensRadioGrp[0].checked == true || tensRadioGrp[1].checked == true)
			{ //3
				return true;
			}
           	else {return false;} //3
		}
		else{ return false;} //2
	}
	else{return false;} //1
} //method

//-----------------------------------------------------------------------------
		// Retrieve an element if it exists in this view and can be found by this
		// browser (this function is friendly to both Netscape & IE)

function findElement(sElementID) //1
{
	if (document.getElementById)
    {
        	return document.getElementById(sElementID);
    }
	else if (document.all)
	{
		return document.all[sElementID];
	}
	// couldnt do either, return null
	return null;
}

function popup_window2(msg,the_width,the_height,buildHTML) 
{
	if(buildHTML)
	{
		//var URL = "javascript: document.write(&quot;<html><head></head><body>" + msg + "<body></html>&quot;);"
		var URL = "<html><head></head><body>" + msg + "<body></html>";
		var URL = "javascript: document.write(&quot;" + URL + "&quot;);"
	} else {
		var URL = msg;
	}
	window.open(URL,"","status=no,menubar=no,scrollbars=yes,resizable=no,width=" + the_width + ",height=" + the_height);
	return false;
}

function popup_window(the_page,the_width,the_height) {
  window.open(the_page,"","status=no,menubar=no,scrollbars=yes,resizable=no,width=" + the_width + ",height=" + the_height);
  return false;
}


function getData(sourceData,startDelim,endDelim)
{
	
	var msg = unescape(sourceData);
	if(typeof sourceData == 'undefined')
	{
		return "";
	}
	
	var pIndex1 = msg.indexOf(startDelim) + startDelim.length;
	var pIndex2 = msg.indexOf(endDelim) - pIndex1 + 1;
	var result = msg.substr(pIndex1,pIndex2-1);
	return result;
}
function replace(s, t, u) {
	i = s.indexOf(t);
	r = "";
	if (i == -1) return s;
	r += s.substring(0,i) + u;
	if ( i + t.length < s.length)
	r += replace(s.substring(i + t.length, s.length), t, u);
	return r;
}
function getReport()
{
	var html_str = getMCSKOR();
	return html_str;
}
function openReport()
{
	var html_str = getReportPageHTML();
	popup_window( html_str ,500,400);return false;
}
function getReportPageHTML()
{
	var rc = "";
	var hd = "&quot;<html>";
	rc = rc + "javascript:";

	var p1 = hd + "<head><title>Question Summary</title></head><body>"
	var dw = ""
	var stuff_str = getReport();
	stuff_str = replace(stuff_str,"system/","http://www.lodestarlearning.com/assets/");

	p1 = p1 + stuff_str
	p1 = p1 + "</body></html>&quot;";
	
	p1 = replace(p1,"'","&#39;");
	
	var loopCount = Math.floor(p1.length/100) +1;
	
	for(var i = 0; i < loopCount; i ++)
	{
		var p = p1.substring(i * 100,i*100 + 100);
		dw = dw + "document.write('" + p + "');";
	
	}
	
	rc = rc + dw;
	return rc;

}

var message = "Print this Page";

function printpage() {
	window.print();  
}



