// printCookie();

function needsMSJava()
{
	if (getCompositeCookie("Community", "JV") == 1)
		return true;
	else	
		return false;
}

function openMyProgress()
{
	var studId = getCompositeCookie("Student", "StudentID");
	if (isNumber(studId)) {
		var URL = Root + "Runtime/MyProgress/MyProgress.asp?Type=Unit";
		window.open(URL, "MyProgress", "width=700,height=460,left=" + (screen.width-700)/2 + ",top=" + (screen.Height-460)/2 + ",scrollbars=no,resizable=no");
	}
	else
		alert(getTranslate("cxt000000PTUnpredictedProgramUse"));
}

function openMyRecordings(fromTMS, reqSended)
{
	var studId = getCompositeCookie("Student", "StudentID");
	if (isNumber(studId)) {
		var URL, hasRecs;
		hasRecs = getCompositeCookie("Student", "HasRecs"); 
		if (hasRecs == null) {
			if (typeof reqSended == "undefined") {
				URL = Root + "Runtime/MyRecordings/hasRecordings.asp?ts=" + new Date().getTime();
				loadData(URL, processHasRecsResponse);
			}
			setTimeout("openMyRecordings(" + fromTMS + ", 1)", 100);
			return;
		}
		if (hasRecs == 0) {
			alert(getTranslate("cxt0000AMNoRecordSaved"))
			return;
		}
		var x = (screen.width - 520) / 2;
		var y = (screen.height - 590 - 50) / 2;
		URL = Root + "Runtime/MyRecordings/MyRecordings.asp?fromTMS=" + fromTMS;
		var win = window.open(URL,'MyRecs','width=520,height=590,left='+x+',top='+y+',resizable=no,scrollbars=no')
		win.focus();
	}
	else
		alert(getTranslate("cxt000000PTUnpredictedProgramUse"));
}

function processHasRecsResponse(req)
{
	var resText = req.responseText;
	resText = resText.substr(resText.indexOf("[data]") + 6);
	setCompositeCookie("Student", "HasRecs", resText);
}
	
function keydownHandler(e)
{
	if (!e) e = window.event;
	if ((e.keyCode == 78 || e.keyCode == 84) && e.ctrlKey)
		e.returnValue = false;
}

function isNumber(str) 
{     
	if (str == "" || /\D/.test(str))
		return false;
	else
		return true;
}   

function showCTResults(studentId, courseId, testId)
{
	var URL = Root + "Runtime/viewCTResults.asp?StudentId=" + studentId + "&CourseId=" + courseId + "&TestId=" + testId;
	var win = window.open(URL, "CTR", "width=630,height=600,left=150,top=50,resizable=no,scrollbars=yes")
	win.focus();
}

function showCompTests(unitId, compId)
{
	var URL = Root + "Runtime/viewTestResults.asp?studentId=" + studentId + "&unitId=" + unitId + "&compId=" + compId;
	var win = window.open(URL, 'ViewTests', 'width=630,height=600,left=150,top=50,resizable=no,scrollbars=yes')
	win.focus();
}

function errorRestoreUS()
{
	alert(getTranslate("cxt00TrPmNtNoAT"));
}

function showRPDemo()
{
	var x = (screen.width - 755) / 2;
	var y = (screen.height - 545 - 50) / 2;
	var URL = Root + "Runtime/RPDemo.asp";
	window.open(URL,'RPDemo','width=755,height=545,left='+x+',top='+y+',resizable=no,scrollbars=no')
}

function setLangTools()
{
	var height;
	if (bWinXP)
		height = 320;
	else	
		height = 300;
	
	var URL = Root + "Runtime/Window.asp?Mode=Alert&Width=370&Height=210&Title=cxt00DiRdTtLanguageToolsSettings&Feature=cxt00DiRdStSettings&Source=" + Root + "Runtime/langToolsSettings.asp";
	var features = "dialogWidth: 400px; dialogHeight: " + height + "px; scroll: no; status: no; edge: Sunken; help: no;";
	var ret = window.showModalDialog(URL, self, features);
}

function attachEvent()
{
	var interval = 1000;
	
	if (document && document.attachEvent) {
		document.attachEvent("oncontextmenu", handleRightClick);
		document.attachEvent("onkeydown", keydownHandler);
	}	
	else
		timerId = setTimeout("attachEvent()", interval);
}

function handleRightClick(e, word)  
{
	if (showRCD == "1") {
		var text = "";
		if (typeof word != "undefined")
			text = word;
		else {
			if (!e) e = window.event;
			var rng, x = e.x, y = e.y, src = e.srcElement;
			if (src != null && src.isTextEdit) {
				if (src.tagName == "INPUT") {
					if (src.type == "submit" || src.type == "button" || src.type == "reset") {
						text = src.value.trim();
						var length = text.split(" ").length;
						if (length > 1)
							text = getCurrentWord(src, x, y);
					}	
					else if (src.type == "text")
						text = getCurrentWord(src, x, y);
				}
				else if (src.tagName == "BUTTON") {
					text = src.value.trim();
					var length = text.split(" ").length;
					if (length > 1)
						text = getCurrentWord(src, x, y);
				}
				else if (src.tagName == "TEXTAREA") {
					rng = src.createTextRange();
					rng.moveToPoint(x, y);
					rng.expand("word");
					rng.select();
					text = rng.text.trim();
				}
			}
			else if (src != null && src.tagName == "SELECT") {
				text = src.options[src.selectedIndex].text.trim();
				var length = text.split(" ").length;
				if (length > 1) {
					var rect = src.getClientRects()[0];
					text = text.split(" ")[0].trim();
				} 
			}
			else if (src != null && src.tagName == "IMG") {
				return;				
			}
			else {
				try {
					rng = document.body.createTextRange();
					rng.moveToPoint(x, y);
					rng.expand("word");
					rng.select();
					text = rng.text.trim();
				}
				catch (ex) {} 		
			}
		}
		text = remSpecialChar(text);
		if (text != "" && isEnglish(text))
			openDictionary(text)
	}	
	if (e) e.returnValue = false;
}

function getCurrentWord(src, x, y)
{
	var text = "";
	var rng = src.createTextRange();
	var length = rng.text.split(" ").length;
	rng.moveEnd("word", 1 - length);
	for (var i = 0; i < length; i++) {
		var oRect = rng.getBoundingClientRect();
		if (x >= oRect.left && x <= oRect.right) {
			rng.select();
			text = rng.text.trim();
			break;
		}
		else {
			rng.move("word");
			rng.expand("word");
		}
	}
	return text;
}

function remSpecialChar(string)
{
	var ret = string.replace(/\u00A0/g, "");
	ret = ret.replace(/[\s!@#%'",:<>\.\-\+\*\&\?/\(\)]/g, "");
	return ret;
}
	
function isEnglish(word)
{	
	var len = word.length;
	for (var i = 0; i < len; i++) {
		var code = word.charCodeAt(i);
		if (code >= 128)
			return false;
	}
	return true;
}
	
function openDictionary(word)
{
	var wd_Language, URL, myWin

	if (word != "")
	{
		wd_Language = 1;
		if	(myWin != null)
			URL = Root + "Runtime/Dictionary/WDFrames.asp?wd_Word=" + word + "&wd_Language=" + wd_Language + "&wd_History=1";
		else
			URL = Root + "Runtime/Dictionary/WDFrames.asp?wd_Word=" + word + "&wd_Language=" + wd_Language + "&wd_History=0";
			
		var dicWin = window.open(URL, "Dictionary", "width=242,height=312,left=200,top=200");
		dicWin.focus();
		return false;
	}
}

function showCourseTest() 
{
	if (typeof win == "undefined")
	{
		var lang = getCompositeCookie("Community", "PLTLanguage");
		var URL = Root + "Runtime/CourseTest/CTIntro.asp?language=" + lang;
		win = window.open(URL, "CourseTest", "resizable=no,status=no,scrollbars=yes,toolbar=no,fullscreen=yes")
		var el = document.getElementById("CTBtn");
		el.detachEvent("onclick", showCourseTest);
		el.style.display = "none";
		clearTimeout(timerId);
		setCompositeCookie("Student", "CT", "-1");
	}
}

function CTTimer(minutes, diff)
{
	var interval, htm, msg;
	var TF = getCompositeCookie("Student", "TF");
	var TT = getCompositeCookie("Student", "TT");
	if (TF == 1) {
		var el = document.getElementById("CTBtn");
		if (minutes > 0) {
			el.attachEvent("onclick", showCourseTest);
			el.style.cursor =	"pointer";
			document.getElementById("CTText").style.color = "red";
		}
		else {
			el.detachEvent("onclick", showCourseTest);
			el.style.display = "none";
			clearTimeout(timerId);
			setCompositeCookie("Student", "CT", "-1");
			return;
		}
	}
	else if (minutes == 0) {
		TF = 1;
		setCompositeCookie("Student", "TF", TF);
		var TFL = getCompositeCookie("Student", "TFL");
		minutes = TFL;
		setCompositeCookie("CT", "ST", TFL);
		var el = document.getElementById("CTBtn");
		el.attachEvent("onclick", showCourseTest);
		el.style.cursor =	"pointer";
		document.getElementById("CTText").style.color = "red";
	}
	setCompositeCookie("CT", "LT", new Date().getTime());
	if (minutes > 1440) {
	  if (typeof diff == "undefined" || diff == 0) {
			interval = 86400000;
			setCompositeCookie("CT", "TD", "0");
			getCTTime();
		}
		else {	
			var TD = parseInt(getCompositeCookie("CT", "TD")) + diff;
			interval = 86400000 - TD;
			setCompositeCookie("CT", "TD", TD);
		}
		var testDate = getCompositeCookie("Student", "CTDate");
		
		if (TF == 0)
			msg = getTranslate("cxtHoEt00NtTestWillTakePlaceOn") + "<br>" + testDate + ".";
		else	
			msg = getTranslate("cxtHoEtBtFinalTeDate").replace("<date>", testDate);
		
		if (TT == "3") 
			msg = msg.replace("<test>", "Final Course Test");
		else if (TT == "2") 
			msg = msg.replace("<test>", "Mid-Term Course Test");
		
		htm = "<center>" + msg + "</center>";
		setCompositeCookie("CT", "ST", minutes);
		minutes -= 1440;
	}
	else {
		var testTime;
	  if (typeof diff == "undefined" || diff == 0) {
			interval = 60000;
			setCompositeCookie("CT", "TD", "0");
		}
		else {	
			var TD = parseInt(getCompositeCookie("CT", "TD")) + diff;
			interval = 60000 - TD;
			setCompositeCookie("CT", "TD", TD);
		}
		var hours = parseInt(minutes / 60);
		var mins = minutes - (hours * 60);
		if (mins >= 10)
			testTime = hours + " : " + mins;
		else
			testTime = hours + " : 0" + mins;

		if (TF == 0)
			msg = getTranslate("cxtHoEt00NtFinalTestStartsIn").replace("<hour>", hours);
		else
			msg = getTranslate("cxtHoEtBtFinalTeInTime").replace("<hour>", hours);
		
		if (TT == "3") 
			msg = msg.replace("<test>", "Final Course Test");
		else if (TT == "2") 
			msg = msg.replace("<test>", "Mid-Term Course Test");

		msg = msg.replace("<min>", mins);
		htm = "<center>" + msg + "</center>";
		setCompositeCookie("CT", "ST", minutes);
		if (minutes > 0)
			minutes -= 1;
	}	
	document.getElementById("CTText").innerHTML = htm;
	document.getElementById("CTBtn").style.display = "block";
		
	timerId = setTimeout("CTTimer(" + minutes + ")", interval);
}

function getCTTime() 
{
	var url = Root + "Runtime/CourseTest/getCourseTestTime.asp?SID=" + new Date().getTime();
	loadData(url, processCTTResponse);
}
	
function processCTTResponse(req)
{
	var resText = req.responseText;
	resText = resText.substr(resText.indexOf("[data]") + 6);
	if (resText == "done") {
		ST = getCompositeCookie("Student", "CT");
		if (ST != -1) {
			var oldTime = parseInt(getCompositeCookie("CT", "LT"));
			var curTime = new Date().getTime();
			diff = curTime - oldTime;
			CTTimer(ST, diff);
		}
		else {
			var el = document.getElementById("CTBtn");
			el.style.display = "none";
			clearTimeout(timerId);
		}
	}	
}
	
String.prototype.trim = function () {
    return this.replace(/^\s+|\s+$/, "");
}; 

function tracer()
{
	var agent = newXMLHttpRequest();
	var URL = Root + "Runtime/Trace.asp?id=" + studentId + "&URL=" + escape(document.URL) + "&ref=" + escape(document.referrer);
	var marks = getCompositeCookie("Component", "markArr");
	if (marks != null && marks != "")
		URL += "&marks=" + marks; 
	agent.open("GET", URL, true);
  agent.send();
}

function getWMPVer()
{
	var ver = 6.4, WMPVer;

	WMPVer = getCompositeCookie("Media", "MPV");
	if (WMPVer != null)
	{
		WMPVer = parseFloat(WMPVer);
		if (!isNaN(WMPVer))
			ver = WMPVer;
	}
	else
	{
		try {
			var objMP7 = new ActiveXObject("WMPlayer.OCX");
			WMPVer = objMP7.versionInfo;
			WMPVer = parseFloat(WMPVer);
			if (!isNaN(WMPVer))
				ver = WMPVer;
			objMP7 = null;
		}
		catch(e) {}
	}
  return ver;
}

function buildMediaPlayer(id, width, height, autoStart, showStatusBar)
{
	var GUID6 = "22d6f312-b0f6-11d0-94ab-0080c74c7e95";
	var GUID7 = "6BF52A52-394A-11D3-B153-00C04F79FAA6";
	var style = "block";

	if (width == 0 && height == 0)
		style = "none";

	if (getWMPVer() >= 7.0)
	{
		w('<OBJECT id="'+id+'" codeBase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701" classid="CLSID:'+GUID7+'" width="'+width+'" height="'+height+'" type="application/x-oleobject">')
			w('<PARAM NAME="AutoStart" VALUE="' + autoStart + '">')
			w('<PARAM NAME="uiMode" VALUE="none">')
			w('<PARAM NAME="enableContextMenu" VALUE="false">')
		w('</OBJECT>')
	}
	else	
	{
		w('<div style="display:'+style+'"><OBJECT id="'+id+'" codeBase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701" classid="CLSID:'+GUID6+'" width="'+width+'" height="'+height+'" type="application/x-oleobject">')
			w('<PARAM NAME="AutoStart" VALUE="' + autoStart + '">')
			w('<PARAM NAME="AutoRewind" VALUE="0">')
 			w('<PARAM NAME="DisplaySize" VALUE="4">')  
			w('<PARAM NAME="ShowTracker" VALUE="0">')
			w('<PARAM NAME="ShowControls" VALUE="0">')
			w('<PARAM NAME="ShowStatusBar" VALUE="' + showStatusBar + '">') 
			w('<PARAM NAME="ClickToPlay" VALUE="0">') 
			w('<PARAM NAME="EnableContextMenu" VALUE="0">') 
		w('</OBJECT></div>')
	}
}

function newXMLHttpRequest() 
{
  var xmlReq = false;

  if (window.XMLHttpRequest) {
    xmlReq = new XMLHttpRequest();
  } 
  else if (window.ActiveXObject) {
    try {
      xmlReq = new ActiveXObject("MSXML2.XMLHTTP.3.0");
    } 
    catch (e) {
      try {
        xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
      } 
      catch (e1) {
        alert("Unable to create an XMLHttpRequest with ActiveX");
      }
    }
  }
  return xmlReq;
}

function getReadyStateHandler(req, responseHandler, sequence) 
{
  return function () 
				{
					if (req.readyState == 4) {
					  if (req.status == 200) {
					    responseHandler(req, sequence);
					  } 
					  else {
							alert("There was a problem retrieving the data:\n" + req.statusText);
					  }
					}
				}
}

function loadData(url, processResponse, sequence, isAsync)
{
  var req = newXMLHttpRequest();

  req.onreadystatechange = getReadyStateHandler(req, processResponse, sequence);
	var async = true;
	if (typeof isAsync != "undefined" && isAsync == false)
		async = isAsync;
	req.open("GET", url, async);
  req.send();
}

function includeCommonVars()
{
	var href = window.location.href;
	var Root = href.substring(0, href.toLowerCase().indexOf("runtime"));
	document.write('<script language="JavaScript" src="' + Root + 'Runtime/CommonVars.js"></script>')
}

function printCookie()
{
  var d = document;
  var str = "";
	str += "defaultCharset = " + d.defaultCharset + "\n"
	str += "charset = " + d.charset + "\n"
	str += "================================\n"
  var aCookie = d.cookie.split("; ");
  var length = aCookie.length;
  var size = d.cookie.length;
	str += "Number of cookies = " + length + "\n";
	str += "Size of cookies = " + size + " bytes\n";
	str += "******************************\n";
  for (var i = 0; i < length; i++)
		str += (i + 1) + ". " + unescape(aCookie[i]) + "\n";
  alert(str);
}

function detect()
{
	var ua = window.navigator.userAgent;
	if (ua.indexOf("Windows") != -1) {
		bWinXP = (ua.indexOf("Windows NT 5.1") != -1);
		if (bWinXP)
			bWinXPSP2 = (ua.indexOf("SV1") != -1);
		bWinVS = (ua.indexOf("Windows NT 6.0") != -1);
		bWin7 = (ua.indexOf("Windows NT 6.1") != -1);
    if (!bWinXP && !bWinVS && !bWin7)
			alert("Unsupported version of the Operating System");

	  var bMSIE = (ua.indexOf("MSIE") != -1);
		if (bMSIE) {
			bControl = true
			var bMSIE6 = (ua.indexOf("MSIE 6.0") != -1);
			var bMSIE7 = (ua.indexOf("MSIE 7.0") != -1);
			var bMSIE8 = (ua.indexOf("MSIE 8.0") != -1);
			if (!bMSIE6 && !bMSIE7 && !bMSIE8)
				alert(getTranslate("cxt2410000PmNtUnsupportedIE"))
		}
		else
			alert(getTranslate("cxt2410000PmNtOnlyMicrosoftIE"))
	}
	else
		alert("Unsupported Operating System");
}

function f1w(strV) {
	document.write(strV);
}

function getCss()
{
	var a = arguments;
	for (i = 0; i < a.length; i++) { 
		if (a[i].toLowerCase().indexOf("print") > -1)
			var smedia = 'MEDIA="print"'
		else
			var smedia=""   
		document.write('<link rel="stylesheet" href=' + resPath + a[i] + '.css type="text/css" ' + smedia + '>')
	}

	var lang, support;
	var w = f1w;	
	if (GetCookie("Student") != null && getCompositeCookie("Student", "SID") != "-1") {
		support = getCompositeCookie("Student", "LangSupLevel");
		lang = language;
	}
	else {
		support = getCompositeCookie("Community", "InstLangSupLevel");
		lang = instLang;
	}
	
	if ((lang == "heb" || lang == "ara") && support == 3) {
		w("<style>")
		w("#navTable{direction:rtl;}")
		w("table.homeBarButtonT{direction:ltr;}")
		w("body.hebBody{direction:rtl;text-align:right}")
		w("table.homeBarButtonTH{direction:ltr;}")	
		w("table.homeBarButtonI{direction:ltr;}")
		w("table.homeBarButtonIH{direction:ltr;}")
		w("#tbl_DHPMainArea{direction:rtl;}")
		w("#downloads{direction:rtl;text-align:right}")
		w(".downloadsTitles{direction:ltr;text-align:right;}")
		w(".downloadBtn{text-align:center}")
		w("#txteduobj{text-align:right;padding-right:12}")
		w("#homeWelcomeMessage{direction:rtl;text-align:right;padding-right:8;padding-bottom:20;padding-top:10;font-weight:bold}")
		w("#myPageWelcomeMessage{direction:rtl;text-align:right;padding-right:45;padding-left:40;}")
		w("#InstructionsCellH{direction:rtl;text-align:right;}")
		w(".midScreenTexts{text-align:right;direction:rtl;}")
		w(".homeBarButtonT,.homeBarButtonTH,.homeBarButtonI,.homeBarButtonILast,.homeBarButtonIH,.HomeBarsCources,.MfButton,.homeBarButtonILastH{direction:rtl;}")	
		w(".PopupTitle{direction:rtl;}")
		w(".dirRTL{direction:rtl}")
		w(".dirLTR{direction:ltr}")
		w(".hebDir{direction:rtl;text-align:right;}")
		w(".TestFB{direction:rtl;}")
		w(".hebBtn{direction:rtl;text-align:left;}")
		w(".forumList{direction:ltr;}")
		w(".magazineGlossLinks{direction:rtl;padding-right:5;}")
		w("</style>")
	}
	w('<style>')
	w('.BgChange {background-image: url("' + Root + 'Runtime/Context/NewLF/Common/side_bg.gif")}')
	w('.navbarbg {background-image: url("' + Root + 'Runtime/Context/NewLF/Common/HeaderNav_bg_off.gif")}')
	w('.navbarbgSelected {background-image: url("' + Root + 'Runtime/Context/NewLF/Common/HeaderNav_bg_on.gif")}')
	w('.upper0footer0bg {background-image: url("' + Root + 'Runtime/Context/NewLF/Common/footer_bg.gif")}')
	w('.toolsDark {background-image: url("' + Root + 'Runtime/Context/NewLF/Common/side_bg.gif")}')
	w('.selectedNav {background-image: url("' + Root + 'Runtime/Context/NewLF/Common/selectedTile.gif")}')
	w('.unselectedNav {background-image: url("' + Root + 'Runtime/Context/NewLF/Common/unselectedTile.gif")}')
	w('.loginDiv {background-image: url("' + Root + 'Runtime/Context/NewLF/Common/loginPic.gif")}')
	w('.btnTableTitle {background-image: url("' + Root + 'Runtime/Context/NewLF/Home/headerBg.gif")}')
	w('</style>')
}

function MM_swapImgRestore()
{ //v3.0
  var i,x,a=document.MM_sr;
  for (i = 0; a && i < a.length && (x = a[i]) && x.oSrc; i++)
		x.src = x.oSrc;
}

function MM_preloadImages()
{ //v3.0
	var d = document;
	if (d.images)
	{
		if (!d.MM_p)
			d.MM_p = new Array();
			
	  var i, j = d.MM_p.length, a = MM_preloadImages.arguments;
	  for (i = 0; i < a.length; i++)
			if (a[i].indexOf("#") != 0)
			{
				d.MM_p[j] = new Image;
				d.MM_p[j++].src = a[i];
			}
	}
}

function MM_findObj(n, d)
{ //v4.0
	var p, i, x;
	if (!d)
		d = document;
	if ((p = n.indexOf("?")) > 0 && parent.frames.length)
	{
		d = parent.frames[n.substring(p + 1)].document;
		n = n.substring(0,p);
	}
  if (!(x = d[n]) && d.all)
		x = d.all[n];
	for (i = 0; !x && i < d.forms.length; i++)
		x = d.forms[i][n];
  for (i = 0; !x && d.layers && i < d.layers.length; i++)
		x = MM_findObj(n, d.layers[i].document);
  if (!x && document.getElementById)
		x = document.getElementById(n);
	return x;
}

function MM_swapImage()
{ //v3.0
	var i, j = 0, x , a = MM_swapImage.arguments;
	document.MM_sr = new Array;
	for (i = 0; i < a.length - 2; i += 3)
		if ((x = MM_findObj(a[i])) != null)
		{
			document.MM_sr[j++] = x;
			if (!x.oSrc)
				x.oSrc = x.src;
			x.src = a[i + 2];
		}
}

function catchExitItem()
{
	if (saved) return;

	if (obj.SubComponent == "Test") {
		if (appletMode == "Test") {
			if (event.clientX > document.body.clientWidth || event.clientY < 0) {   
				event.returnValue = getTranslate('cxtCoTmNtHaventSubmitted');
			}
		}
	}
	else {
		if (!FromTMS) {
			stopTime = new Date()
			diff = Math.floor((stopTime - startTime) / 1000);
			var mark = getMark(appName);             
			saveMark(obj.Id, mark, diff, 1);
			if (skill == "Speaking") {
				switch(obj.SubComponent) {
					case "Practice":
						if (mark > 0)
							updateProgress(1);
						break;    
					default:
						updateProgress(1);
						break;    
				}
			}
			else if (mark > 0) {
				switch(obj.SubComponent) {
					case "Practice":
						updatePracticeProgress();
						break;    
					default:
						updateProgress(1);
						break;    
				}
			}
			saved = true;
		}			
	}
}

function exitItem()
{
	if (obj.SubComponent == "Test")
	{
		var stage = getCompositeCookie("Test", "Stage");
		if (stage == "Intro")
		{
			if (event.clientX > document.body.clientWidth || event.clientY < 0) {
				eraseTestCookie();
				saved = true;
			}
		}
		else if (stage == "Test") {
			saved = true;
		}
	}

	if (saved) return;

	if (appletMode == "Test" || appletMode == "TestCheck" || appletMode == "seeUserAnswer")
	{ 
		eraseTestCookie();
	}
}

function SavePage(url, appletName, itemId, appletMode)
{
	var mark;
	var locUrl = url;
	saved = true;
  
  url = url.replace("?", "*") 
  do
  {
		url = url.replace("&", "^")
  }
  while (url.indexOf("&") > -1)
	if (url != "#")
	{
		if (obj.SubComponent == "Test" && getCompositeCookie("Test", "Stage") == "Intro")
		{
			setCompositeCookie("Unit", "ItemType", getCompositeCookie("Component", "ItemType"));
			if (locUrl.indexOf("LogOut") == -1)
				eraseTestCookie();
			document.location = locUrl;
		}
		else if (appletMode == "Test")
		{
			if (skill == "Listening" || skill == "Grammar")
				var janre = "&janre=" + obj.Subject;
			else
				var janre = "";
			var source = escape('MsgPage.asp?saveState=no' + janre + '&url=' + url + '&FromTMS=' + FromTMS);
			var URL = Root + 'Runtime/Window.asp?Mode=Alert&Width=300&Height=220&Title=cxtCo00TtTest&Feature=cxtCo00TtTest&Source=' + source;
			var features = "dialogWidth: 320px; dialogHeight: 310px; scroll: no; status: no; edge: Sunken; help: no;";
			var ret = window.showModalDialog(URL, self, features);
			if (ret == "Ok") {
				eraseTestCookie();
				document.location = locUrl;
			}	
			else	
				saved = false;
		}
		else if (appletMode == "TestCheck" || appletMode == "seeUserAnswer")
		{ 
			if (!FromTMS)
			{
				startTime = getCompositeCookie("Test", "StartTime");  
				if (startTime != null && startTime != "0")
				{
					stopTime = Math.floor(new Date().getTime() / 1000);
					diff = stopTime - parseInt(startTime);
					var compId = getCompositeCookie("Component", "Id");
					saveTestTime(compId, diff)
					setCompositeCookie("Test", "StartTime", 0);
				}
			}
			setCompositeCookie("Unit", "ItemType", getCompositeCookie("Component", "ItemType"));
			if (locUrl.indexOf("LogOut") == -1)
				eraseTestCookie();
			document.location = locUrl;
		}
		else
		{
			if (!FromTMS)
			{
				stopTime = new Date()
				diff = Math.floor((stopTime - startTime) / 1000);
				mark = getMark(appletName);             
				saveMark(obj.Id, mark, diff, 1);
				if (skill == "Speaking")
				{
					switch(obj.SubComponent)
					{
						case "Practice":
							if (mark > 0)
								updateProgress(1);
							break;    
						default:
							updateProgress(1);
							break;    
					}
				}
				else if (mark > 0) {
					switch(obj.SubComponent)
					{
						case "Practice":
							updatePracticeProgress();
							break;    
						default:
							updateProgress(1);
							break;    
					}
				}
			}			
			setCompositeCookie("Unit", "ItemType", getCompositeCookie("Component", "ItemType"));
			document.location = locUrl
		}
	}
}

function eraseTestCookie()
{
	setCompositeCookie("Test", "Stage", "Intro");
	setCompositeCookie("Test", "testMode", "");
	setCompositeCookie("Test", "SetId", "");
	setCompositeCookie("Test", "Marks", "");
	setCompositeCookie("Test", "FinalMark", 0);
	setCompositeCookie("Test", "testsVisited", "");
	setCompositeCookie("Test", "StartTime", 0);
}

function updatePracticeProgress()
{
	var VI = getCompositeCookie("Unit", "VisitedItems");
	var total = obj.TotalSequence;
	var items =	obj.SequenceArr;
	var sum = 0, ratio = 0, ind;
	for (var i = 0; i < total; i++)
	{
		ind = -1;
		if (VI != null)
			ind = VI.indexOf(items[i])
		if (ind != -1)
			sum += 1;
	}
	ratio = sum / total; 
	if (ratio >= 0.2 && ratio < 0.8)
		updateProgress(2);
	else if (ratio >= 0.8)	
		updateProgress(1);
}

function saveCCData(url, itemId)
{
	var locUrl = url;
  
  url = url.replace("?", "*") 
  do {
		url = url.replace("&", "^")
  }
  while (url.indexOf("&") > -1)
	if (url != "#")
	{
		if (!FromTMS)
		{
			stopTime = new Date()
			stopTime = Math.floor(stopTime.getTime() / 1000);
			diff = stopTime - startTime;
			if (arguments.length == 1)
				var lastItemId = getCompositeCookie("Component", "ItemId");
			else	
				var lastItemId = itemId;
			setCompositeCookie("Component", "lastItemId", lastItemId);
			saveMark(lastItemId, 1, diff, 2);
			updateProgress(1);
		}			
		document.location = locUrl;
	}
}

function updateProgress(progress)
{
	var compId = getCompositeCookie("Component", "Id");
	var subCompId = getCompositeCookie("Component", "SCId");
	var oldProgress = getCompositeCookie("Unit", "Progress");
	if (oldProgress != null)
	{
		var ind = oldProgress.indexOf(compId + ":") + compId.length + 1;
		var compType = oldProgress.substring(ind, ind + 1);
		ind = ind + 2;
		if (compType == "1")
		{
			var ind1 = oldProgress.indexOf("|", ind);
			if (ind1 != -1)
				var subComps = oldProgress.substring(ind, ind1);
			else	
				var subComps = oldProgress.substr(ind);
			ind1 = subComps.indexOf(subCompId + ".") + subCompId.length + 1;
			ind += ind1;
		}	
		var newProgress = oldProgress.substring(0, ind) + progress + oldProgress.substring(ind + 1, oldProgress.length);
		setCompositeCookie("Unit", "Progress", newProgress)
	}
}

function saveMark(id, mark, time, compType)
{
	if (!isNumber(id) || !isNumber(mark) || !isNumber(time) || !isNumber(compType))
		return;

	var tmpArr, tmpArr1, tmpArr2, tmpArr3, newMarks, newTime, newMark;
	
  var oldMarks = getCompositeCookie("Component", "markArr");
  if (oldMarks != null && oldMarks != "")
  {
		if (oldMarks.indexOf(id + ":") > -1)
    {
			tmpArr = oldMarks.split(id + ":");
			tmpArr1 = tmpArr[1].split(",");   
			tmpArr2 = tmpArr1[0].split("|");
			if (parseInt(tmpArr2[1]) >= mark)
				newMark = tmpArr2[1];
			else	
				newMark = mark;
			newTime = time + parseInt(tmpArr2[2]);   
			tmpArr3 = oldMarks.split(id + ":" + tmpArr1[0]);
			newMarks = tmpArr3[0] + id + ":" + tmpArr2[0] + "|" + newMark + "|" + newTime + tmpArr3[1];
    }
    else 
			newMarks = oldMarks + "," + id + ":" + compType + "|" + mark + "|" + time;
  }   
  else
		newMarks = id + ":" + compType + "|" + mark + "|" + time;

	setCompositeCookie("Component", "markArr", newMarks);
	
	if (mark > 0 && compType == 1)
		setPracticeVisited(id);
}

function saveTestTime(id, time)
{
	if (!isNumber(id) || !isNumber(time))
		return;

	var tmpArr, tmpArr1, tmpArr2, newTimes;
  var oldTimes = getCompositeCookie("Test", "Times")
  if (oldTimes != null && oldTimes != "")
  {
		if (oldTimes.indexOf(id + ":") > -1)
    {
			tmpArr = oldTimes.split(id + ":")
			tmpArr1 = tmpArr[1].split(",")   
			newTime = time + parseInt(tmpArr1[0])   
			tmpArr2 = oldTimes.split(id + ":" + tmpArr1[0])
			newTimes = tmpArr2[0] + id + ":" + newTime + tmpArr2[1]   
    }
    else 
			newTimes = oldTimes + "," + id + ":" + time    
  }   
  else
		newTimes = id + ":" + time  

	setCompositeCookie("Test", "Times", newTimes)
}

function setPracticeVisited(id)
{
	var visStr = getCompositeCookie("Unit", "VisitedItems")
  if (visStr != null)
  {      
		if (visStr.indexOf(id) == -1)
		{
			visStr += (visStr != "") ? "," + id : id; 
			setCompositeCookie("Unit", "VisitedItems", visStr)
		}
	}		
  else
		setCompositeCookie("Unit", "VisitedItems", id)
}

function getPracticeVisited(id)
{
	var visStr = getCompositeCookie("Unit", "VisitedItems")
  if (visStr != null)      
		if (visStr.indexOf(id + "") > -1)
			return true;
    else
			return false;
  else
		return false;       
}

function updateTestsVisited(num)
{
	var newStr;
  var testsVisitedStr = getCompositeCookie("Test", "testsVisited")
  if (testsVisitedStr != null)    
  {  
		if (testsVisitedStr.indexOf("[" + num + "]") == -1)
    { 
      newStr = testsVisitedStr + "[" + num + "]"
      setCompositeCookie("Test", "testsVisited", newStr)    
    }
  }
  else        
  {
		newStr = "[" + num + "]"
    setCompositeCookie("Test", "testsVisited", newStr)    
  }  
}

function getTestVisited(num)
{
  var testsVisitedStr = getCompositeCookie("Test", "testsVisited")
  if (testsVisitedStr != null)      
    if (testsVisitedStr.indexOf("[" + num + "]") > -1)
      return true;
    else
      return false;
  else
      return false;       
}

function OpenMsgWindow(url, appletName)
{
	var ret = "";
  if (!compleatTest) {
		var janre = "";
		if (skill == "Listening" || skill == "Grammar")
			janre += obj.Subject

		var source = escape('MsgPage.asp?janre=' + janre + '&FromTMS=' + FromTMS);
		var URL = Root + 'Runtime/Window.asp?Mode=Alert&Width=300&Height=220&Title=cxtCo00TtTest&Feature=cxtCo00TtTest&Source=' + source;
		var features = "dialogWidth: 320px; dialogHeight: 310px; scroll: no; status: no; edge: Sunken; help: no;";
		var ret = window.showModalDialog(URL, self, features);
	}
	if (compleatTest || ret == "Ok") {
		var d = document;
		var applet = d.applets[appletName];
		if (applet != null) {
			applet.saveUserState();
			var marks = applet.getTestMarks();
			var finalMark = applet.getFinalMark();
			setCompositeCookie("Test", "Marks", marks);
			setCompositeCookie("Test", "FinalMark", finalMark);
		}	
		updateTestTaken();
		saved = true;
		d.location = url;
	}	
}

function updateTestTaken()
{
	var compId = getCompositeCookie("Component", "Id");
	var subCompId = getCompositeCookie("Component", "SCId");
	var oldProgress = getCompositeCookie("Unit", "Progress");
	if (oldProgress != null)
	{
		var ind = oldProgress.indexOf(compId + ":") + compId.length + 1;
		var compType = oldProgress.substring(ind, ind + 1);
		ind = ind + 2;
		if (compType == "1")
		{
			var ind1 = oldProgress.indexOf("|", ind);
			if (ind1 != -1)
				var subComps = oldProgress.substring(ind, ind1);
			else	
				var subComps = oldProgress.substr(ind);
			ind1 = subComps.indexOf(subCompId + ".") + subCompId.length + 3;
			ind += ind1;
		}	
		var newProgress = oldProgress.substring(0, ind) + "1" + oldProgress.substring(ind + 1, oldProgress.length);
		setCompositeCookie("Unit", "Progress", newProgress)
	}
}

function getSubCompArr()
{
	var subComp = getCompositeCookie("Component", "Items")
	if (subComp != null && subComp != "")
	{
		var arr1 = subComp.split("%")
		for (var i = 0; i < arr1.length; i++)
		{
			var arr2 = arr1[i].split(",");
			subCompNameArr[i] = arr2[0];
			subCompIdArr[i] = parseInt(arr2[1]);
			itemIdArr[i] = parseInt(arr2[2]);
		}
  } 
}

function getSubComp(itemId, itemType, subCompId)
{
	var url = "Template.asp?unitData=" + getCompositeCookie("Unit", "UnitId") + "&FromTMS=" + FromTMS + "&SID=" + getCompositeCookie("Student", "SID"); 
	setCompositeCookie("Component", "ItemId", itemId);
	setCompositeCookie("Component", "ItemType", itemType);
	if (itemType == "Test")
		setCompositeCookie("Test", "Stage", "Intro");
	SavePage(url, appName, obj.Id, appletMode);
	setCompositeCookie("Component", "SCId", subCompId);
}

function getCustSubComp(itemId)
{
	var lastItemId = getCompositeCookie("Component", "ItemId");
	setCompositeCookie("Component", "ItemId", itemId);
	var url = "CustomTemplate.asp?unitData=" + getCompositeCookie("Unit", "UnitId") + "&FromTMS=" + FromTMS + "&SID=" + getCompositeCookie("Student", "SID")

	saveCCData(url, lastItemId);
}

function getQueryString(param)
{
	var sURL = document.URL.toString();
	if (sURL.indexOf(param + "=") != -1)
	{
		var aQuery = sURL.split("?");
	  aQuery = aQuery[1].split("&");
	  for (var i = 0; i < aQuery.length; i++)
	  {
	    var aCrumb = aQuery[i].split("=");
	    if (param == aCrumb[0]) 
	      return unescape(aCrumb[1]);
	  }
	}
	else
	  return null;
}

function restoreTestVars()
{
	setCompositeCookie("Component", "ItemId", obj.SequenceArr[obj.Sequence - 1]);
	setCompositeCookie("Component", "ItemType", "Test");
}

function getMediaPath()
{
	var ret = "", wave, folder;
	var path = document.location.href;
	var num = path.lastIndexOf("/");
	if (skill == "Listening" && obj.SubComponent == "Explore")
	{
		wave = obj.Code + ".wav";
		folder = obj.Code.substr(0, obj.Code.length - 1);
	}
	if (skill == "Grammar")
	{
		folder = obj.Code.substr(0, obj.Code.length - 1);
		wave = folder + "101.mp3";
	}
	else if (skill == "Speaking" && obj.SubComponent == "Practice")
		return ret;
	else if (obj.SubComponent == "Explore")
	{
		wave = obj.Code + "01.mp3";
	  folder = obj.Code.substr(0, obj.Code.length - 1);
	}
	else    
	{
		folder = obj.Code.substr(0, obj.Code.length - 4);
	  wave = folder + "e01.mp3";
	}   
	if (skill == "Listening" && TVMode == "Video")
	{
		if (getWMPVer() >= 7.0)
			wave = folder + "e.wmv";
		else
			wave = folder + "e.mpg";
	}
	return path.substr(0, num) + "/Media/" + skill + "/" + folder + "/" + wave;
}

function openText(val)
{  
  var applet = document.applets[appName];
	if (applet != null && applet.isActive())
	{
		switch(val)
		{
			case "seeText":
				applet.seeText();
		    break;
			case "seeExplanation":
				applet.seeExplanation();
		    break;
		}
	}        
}

function openMediaWindow(testSeq)
{
	var source;

	if (isCTR)
		source = escape("seeMedia.asp?unitData=" + getCompositeCookie("CTR", "UnitId") + "&CTR=1");
	else if (typeof testSeq == "undefined" || testSeq == "")
		source = escape("seeMedia.asp?unitData=" + getCompositeCookie("Unit", "UnitId"));
	else
		source = escape("seeMedia.asp?unitData=" + getCompositeCookie("CompTest", "UnitId") + "&testSeq=" + testSeq);

	switch (obj.Subject) {
		case "TV":
		case "Blank":
			window.open(Root + 'Runtime/Window.asp?Width=250&Height=250&Title=cxtCoTrTtWatchTV&Feature=cxtCoTrTtWatchTV&Source=' + source,'SeeMedia','width=240,height=305,left=200,top=200,resizable=no,scrollbars=no')
      break; 
		case "Radio":
			window.open(Root + 'Runtime/Window.asp?Width=250&Height=200&Title=cxtCoTrTtListenRadio&Feature=cxtCoTrTtListenRadio&Source=' + source,'SeeMedia','width=230,height=255,left=200,top=200,resizable=no,scrollbars=no')
      break;
		case "Voice Mail":
			window.open(Root + 'Runtime/Window.asp?Width=250&Height=200&Title=cxtCoTrTtListenVoiceMail&Feature=cxtCoTrTtListenVoiceMail&Source=' + source,'SeeMedia','width=230,height=255,left=200,top=200,resizable=no,scrollbars=no')
      break;
  }   
}

function changeTVMode(mode, state)
{
  var d = document;
	setCompositeCookie("Media", "TVMode", mode)		
	if (state == 0) { // EDO
		d.location = "Template.asp?unitData=" + getCompositeCookie("Unit", "UnitId") + "&FromTMS=" + FromTMS + "&SID=" + getCompositeCookie("Student", "SID")
	}
	else if (state == 1) { // PLT
		d.location.reload();
	}
}

function changeTVModeCB(objSelect, state)
{
	var curState = 0;
	if (arguments.length == 2) {
		if (state != "")
			curState = state;
	}
	var mode = objSelect[objSelect.selectedIndex].value;
	changeTVMode(mode, curState);
}

function GetCookie(sName)
{
  var aCookie = document.cookie.split("; ");
  for (var i = 0; i < aCookie.length; i++)
  {
    var aCrumb = aCookie[i].split("=");
    if ((sName == aCrumb[0]) && (aCrumb[1] != null)) 
    {
			var ret = unescape(aCrumb[1]);
      do {
        ret = ret.replace("+", " ");
      } while (ret.indexOf("+") > -1)
      return ret; 
    }
  }
  return null;
}	

function getCompositeCookie(sCName, sIName)
{
  var cookieStr = GetCookie(sCName);
	if (cookieStr != null)
  {
		var aCookie = cookieStr.split("^");
		for (var i = 0; i < aCookie.length; i++)
		{
			var aCrumb = aCookie[i].split("*");
			if ((sIName == aCrumb[0]) && (aCrumb[1] != null)) 
			{
				var ret = aCrumb[1];
				do {
					ret = ret.replace("+", " ");
        } while (ret.indexOf("+") > -1)
				return ret; 
      }
		}
		return null; 
  }
	else
		return null; 
}

function setCompositeCookie(sCName, sIName, sIVal)
{
	var newCookie;
	
  var oldCookie = GetCookie(sCName);
	if (oldCookie != null)
  {
		var SInd = 0, EInd = 0;
		EInd = oldCookie.indexOf("^" + sIName + "*");
		if (EInd != -1)
		{
			EInd += sIName.length + 2;
			newCookie = oldCookie.substring(SInd, EInd) + sIVal;
			SInd = EInd;
			EInd = oldCookie.indexOf("^", SInd);
			if (EInd != -1)
				newCookie += oldCookie.substring(EInd);
		}
		else
		{
			newCookie = oldCookie + "^" + sIName + "*" + sIVal;
		}
  }
  else
		newCookie = "^" + sIName + "*" + sIVal; 

	document.cookie = sCName + "=" + escape(newCookie) + "; path=/";
}

function DelCookie(sName)	//Deletes permanent cookie
{
  document.cookie = sName + "=" + "" + "; expires=Fri, 31 Dec 1989 23:59:59 GMT;";	
}

function OnDicClick(userLanguage)
{
	var wd_Word, wd_Language, URL, myWin

	wd_Word = document.DicForm.WDQString.value.trim();
	if (wd_Word != "")
	{
		wd_Word = escape(wd_Word);
		wd_Language = userLanguage;
		if	(myWin != null)
			URL = Root + "Runtime/Dictionary/WDFrames.asp?wd_Word=" + wd_Word + "&wd_Language=" + wd_Language + "&wd_History=1";
		else
			URL = Root + "Runtime/Dictionary/WDFrames.asp?wd_Word=" + wd_Word + "&wd_Language=" + wd_Language + "&wd_History=0";
			
		myWin = window.open(URL, "Dictionary", "width=250,height=312,left=200,top=200");
	}
}

function MM_openBrWindow(theURL, winName, features)
{ 
  window.open(theURL, winName, features);
}

function getHelp(sHelpName)
{
  var a = arguments;
	var sHelp = a.length > 0 ? a[0] : helpFile;
	if (sHelp != "")
	{
	  var URL = Root + "Runtime/Help.asp?name=" + sHelp
		var x = (800 - 550) / 2
		var y = (600 - 460) / 2
    window.open(URL, 'Help', 'width=550,height=455,left='+x+',top='+y+',resizable=no,scrollbars=no')
	}
}

function downloads()
{
	var URL = Root + "Runtime/Window.asp?Mode=download&Width=490&Height=420&Title=cxtCoOwStDownloads&Feature=cxtCoOwStDownloads&Source=" + Root + "Runtime/Detect.htm"
	var x = (800 - 550) / 2
	var y = (600 - 460) / 2
	window.open(URL, 'Detect', 'width=500,height=475,left='+x+',top='+y+',resizable=no,scrollbars=no')
}

function register()
{
	var URL = Root + "Runtime/Window.asp?Mode=Registration&Width=450&Height=425&Title=cxtCgOw00TtEDOnline&Feature=cxtCgOw00TtRegistration&Source=" + Root + "Runtime/Register.asp";
	window.open(URL, 'Registration', 'width=460,height=480,left=100,top=100,resizable=no,scrollbars=no')
}

function LogOut()
{
	var height;
	if (bWinXP)
		height = 210;
	else	
		height = 210;
	
	var URL = Root + "Runtime/Window.asp?Mode=Alert&Width=280&Height=100&Title=cxt00NbBtLogOut&Feature=cxt00NbBtLogOut&Source=" + Root + "Runtime/LogOut.asp"
	var features = "dialogWidth: 300px; dialogHeight: " + height + "px; scroll: no; status: no; edge: Sunken; help: no;"
	var ret = window.showModalDialog(URL, "", features);
	if (ret == "Yes")
		endSession();
}

function endSession()
{
	setCompositeCookie("Student", "SID", -1);
	document.location = Root + "Runtime/Home/Home.asp"
}

function getSupport()
{
	var studId = getCompositeCookie("Student", "StudentID") ;
	if (isNumber(studId)) {
		var hasTeacher = getCompositeCookie("Student", "HasTeacher");
		if (hasTeacher != null && hasTeacher != 0)
			document.location = Root + "Runtime/Support/Inbox.asp";
		else {
			var URL = Root + "Runtime/Window.asp?Width=390&Height=185&Title=cxt00NbBtSupport&Feature=cxtTsMs00NtContactYourTeacher&Source=" + Root + "Runtime/Support/SendMail.asp"
			var x = (800 - 400) / 2
			var y = (600 - 240) / 2
			window.open(URL,'SendMail','width=400,height=240,left='+x+',top='+y+',resizable=no,scrollbars=no')
		}
	}
	else
		alert(getTranslate("cxt000000PTUnpredictedProgramUse"));
}

function openYouWho()
{
	var iStId = getCompositeCookie("Student", "StudentID") ;
	if("undefined" != typeof(iStId) && !isNaN(parseInt(iStId)))
		var wndYW = window.open(Root + "Runtime/FriendsOnline/YHPage.asp", "youwho", 'width=250,height=220,left=200,top=200');
	else{
		alert(getTranslate("cxt000000PTUnpredictedProgramUse"));
	}
}

function openGrammarBook(reqSended)
{
	var studId = getCompositeCookie("Student", "StudentID") ;
	if (isNumber(studId)) {
		var URL, gbVer;
		gbVer = getCompositeCookie("Student", "GBVer"); 
		if (gbVer == null) {
			if (typeof reqSended == "undefined") {
				URL = Root + "Runtime/GrammarBook/getGBVersion.asp?ts=" + new Date().getTime();
				loadData(URL, processGBVResponse);
			}
			setTimeout("openGrammarBook(1)", 100)
			return;
		}
		if (gbVer == 0) {
			setCompositeCookie("Student", "GB", 0);
			alert(getTranslate("cxt24100GbPmNtNotAuthorized"))
			return;
		} 	
		var x = (screen.width - 755) / 2;
		var y = (screen.height - 545 - 50) / 2;
		URL = Root + "Runtime/GrammarBook/GrammarBook.asp";
		window.open(URL,'GrammarBook','width=755,height=545,left='+x+',top='+y+',resizable=no,scrollbars=no')
	}
	else
		alert(getTranslate("cxt000000PTUnpredictedProgramUse"));
}

function processGBVResponse(req)
{
	var resText = req.responseText;
	resText = resText.substr(resText.indexOf("[data]") + 6);
	setCompositeCookie("Student", "GBVer", resText);
}
	
function openAppletDialog(message, title, buttons)
{
	var height;
	if (bWinXP)
		height = 230;
	else	
		height = 210;

	message = message.replace("?", "&#63;")
	var source = escape(Root + "Runtime/appletDialog.asp?message=" + message + "&buttons=" + buttons);
	var URL = Root + "Runtime/Window.asp?Mode=Alert&Width=270&Height=120&Title=" + title + "&Feature=" + title + "&Source=" + source;
	var features = "dialogWidth: 300px; dialogHeight: " + height + "px; scroll: no; status: no; edge: Sunken; help: no;"
	var ret = window.showModalDialog(URL, "", features);
	if (ret == "Yes")
		return true;
	else	
		return false;
}

function insertTemplateTxt(strTxt, arSeach, arRepl)
{
	if (strTxt && arSeach)
	{
		for(var i = 0; i < arSeach.length; i++)
		{
			if (strTxt.indexOf(arSeach[i]) != -1)
			{
				strTxt = strTxt.substring(0, strTxt.indexOf(arSeach[i])) + arRepl[i] + strTxt.substring(strTxt.indexOf(arSeach[i]) + arSeach[i].length);
			}
		}
	}
	return strTxt;
}

function FindIndex(select, text)
{
	var i;
	for (i = 0; i < select.length; i++)
	{
		if (select.options[i].text == text)
			break;
	}
	return i;
}

function buildPictureContainer(graphicMode, width, height, flashSrc, imgSrc, imgName, containerId)
{
	if (graphicMode == "flash")
	{
		w("<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0' width='" + width + "' height='" + height + "' id='" + containerId + "'>")
		w("<param name=movie value='" + Root + "Runtime/Flash/supercontainer.swf?" + flashSrc + "&height=" + height + "&width=" + width + "&path=" + resPath + "flashcss.txt'>")
		w("<param name=quality value=high>")
		w("<param name='SCALE' value='exactfit'>")
		w("<embed src='" + Root + "Runtime/Flash/supercontainer.swf?" + flashSrc + "&height=" + height + "&width=" + width + "&path=" + resPath + "flashcss.txt' quality='high' pluginspage='http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash' type='application/x-shockwave-flash' width='" + width + "' height='" + height + "' scale='exactfit'></embed>")
		w("</object>")
	}
	else if (width != "")
		w("<img width='" + width + "' height='" + height + "' src='" + imgSrc + "' border=0 name='" + imgName + "'>")
	else	
		w("<img src='" + imgSrc + "' border=0 name='" + imgName + "'>")
}

function RollOverObject(p1, p2, pic, p4, mode, numPic, containerId)
{
	if (mode == "flash")
	  rollover(numPic, containerId)
	else
	  MM_swapImage(p1, p2, pic, p4)
}

function RollOutObject(mode, numPic, containerId)
{
	if (mode == "flash")
	  rollout(numPic, containerId)
	else
	  MM_swapImgRestore()
}

function isObjValid(sName)
{
  var Obj = document.getElementById(sName);
  return ((Obj != null) && (Obj.object != null));
}

function rollover(pic, containerId)
{
	if (!isObjValid(containerId))
		return false;
	
	var cid = eval("window.document." + containerId);
	if (cid.PercentLoaded() == 100)
	{
		cid.SetVariable("_root.activepicture",pic);  
		cid.TCallLabel('/','rollover')
	}
}

function rollout(pic, containerId)
{
	if (!isObjValid(containerId))
		return false;
		
	var cid = eval("window.document." + containerId);
	if (cid.PercentLoaded() == 100)
	{
		cid.SetVariable("_root.activepicture",pic);  
		cid.TCallLabel('/','rollout')
	}
}

function getTextTR(code, link)
{
	var txt = getTranslate(code)
	txt = txt.replace("<link>", link)
	if (link != "")
		txt = txt.replace("</link>", "</a>")
	else	
		txt = txt.replace("</link>", "")
	return txt
}

function getSkillTranslate(skill)
{
	switch(skill)
	{
		case "Reading":
			return getTranslate("cxtCo00NtReading");
		case "Listening": 
			return getTranslate("cxtCo00NtListening");
		case "Speaking":
			return getTranslate("cxtCo00NtSpeaking");
		case "Grammar":
			return getTranslate("cxtCo00NtGrammar");
		case "Vocabulary":
			return getTranslate("cxt241000000NtVocabulary");
		case "Alphabet":
			return getTranslate("cxt24100Co00NtAlphabet");
		case "Writing":
			return getTranslate("cxt24100Co00NtWriting");
		default:
			return skill;
	}
}

function getEPTTranslate(val)
{
	switch(val)
	{
		case "Prepare":  
			return getTranslate("cxt24100Co00TtPrepare");
		case "Explore":
			return getTranslate("cxtCo00TtExplore");
		case "Practice":  
			return getTranslate("cxtCo00TtPractice");
		case "Practice 1":  
			return getTranslate("cxt24100Co00TtPractice1");
		case "Practice 2":  
			return getTranslate("cxt24100Co00TtPractice2");
		case "Test":
			return getTranslate("cxtCo00TtTest");
		case "Interact 1":
			return getTranslate("cxt24100Co00TtInteract1");
		case "Interact 2":
			return getTranslate("cxt24100Co00TtInteract2");
		default:
			return val;
	}
}

function getCharsetLC(langCode){
	var charset = "iso-8859-1";
	switch(langCode){
		case "ara":	charset = "windows-1256"
		break; 
		case "chi":	charset = "big5" 
		break; 
		case "chs":	charset = "gb2312" 
		break; 
		case "heb":	charset = "windows-1255" 
		break; 
		case "jpn":	charset = "Shift-JIS" 
		break; 
		case "kor":	charset = "ks_c_5601" 
		break; 
		case "lit":	charset = "windows-1257" 
		break; 
		case "pol","slv":charset = "windows-1250" 
		break; 
		case "rus":	charset = "windows-1251" 
		break; 
		case "tha":	charset = "windows-874" 
		break; 
		case "tur":	charset = "windows-1254" 
		break; 
		case "vie":	charset = "utf-8" 
		break; 
		case "gre":	charset = "windows-1253" 
		break; 
	}
	return charset;
}

function includeTranslationJS()
{
	var lang = getContextLanguage();
	var ch = getCharsetLC(lang) ;
	document.write('<script language="JavaScript" charset="' + ch + '" src="' + Root + 'Runtime/Localization/Context/' + lang + '.js"></script>');
}

function getContextLanguage()
{
	var lang, support;
		
	if (GetCookie("Student") != null && getCompositeCookie("Student", "SID") != "-1")
	{
		support = getCompositeCookie("Student", "LangSupLevel");
		if (support == 0 || support == 1)
			lang = "eng";
		else	
			lang = language;
	}
	else if (GetCookie("Community") != null)
	{
		support = getCompositeCookie("Community", "InstLangSupLevel");
		if (support == 0 || support == 1)
			lang = "eng";
		else	
			lang = instLang;
	}
	else	// PLT
		lang = "eng";
			
	return lang;
}

function getContentLanguage()
{
	var lang, support;
		
	if (GetCookie("Student") != null && getCompositeCookie("Student", "SID") != "-1")
	{
		support = getCompositeCookie("Student", "LangSupLevel");
		if (support == 0)
			lang = "eng";
		else	
			lang = getCompositeCookie("Student", "Language");
	}
	else
		lang = "eng";

	return lang;
}

function checkInstallation(feature)
{
	var isInstalled = getCompositeCookie("Media", feature)
	if (isInstalled == "1")
		return

	var x = (800 - 450) / 2
	var y = (600 - 255) / 2

	var source = escape(Root + "Runtime/InstallOne.asp?feature=" + feature);
	var URL = Root + "Runtime/Window.asp?Mode=download&Width=440&Height=200&Title=cxtCoOwStDownloads&Feature=cxtCoOwStDownloads&Source=" + source;

	window.open(URL,'InstallOne','width=450,height=255,left='+x+',top='+y+',resizable=no,scrollbars=no')
}
	
function IsSRInstalled()
{
  var SRPresent = getCompositeCookie("Media", "SR");
  if (SRPresent != 1)
  {
		try
    {
			var srObj = new ActiveXObject("MTWTools.SafeSRS");
      if ((srObj != null) && (srObj.isSRAvailable))
				SRPresent = 1;
      else
				SRPresent = 0;
      srObj = null;    
    }
    catch (Expt) { SRPresent = 0; }    
	      
    if (SRPresent == 1)
			setCompositeCookie("Media", "SR", 1);
  }
  return SRPresent;
}

function getPageOf(code, currentPage, totalPages)
{
	var txt = getTranslate(code)
	txt = txt.replace("<cur>", currentPage)
	txt = txt.replace("<total>", totalPages)
	return txt
}

function changeBtnStyle(btnName, NStyle, HStyle, enter)
{
	var btn = document.getElementById(btnName);
	if (enter == 1)
	{
		if (btn.className == NStyle)
			btn.className = HStyle
	}
	else
		btn.className = NStyle
}

function checkSoundCompression()
{
	var isInstalled = getCompositeCookie("Media", "SComp");
	if (isInstalled == 1)
		return;
	else
	{
		if (bWin95 || bWin98)
			alert(getTranslate("cxt0000PmNtSoundComponent9895"))
		else if (bWinNT || bWin2K || bWinXP)
			alert(getTranslate("cxt0000PmNtSoundComponent2000"))
	}	
}

function loginAlert()
{
	alert(getTranslate("cxtCoLgNtPleaseLogin"))
}

function putAlert(code)
{
	alert(getTranslate(code).replace(/<br>/gi,"\n"));
}
	
function openLoginWindow(feature, source)
{
	var Source = escape(Root + "Runtime/LogIn.asp?Feature=" + feature + "&Source=" + source);
	var URL = Root + "Runtime/Window.asp?Width=300&Height=250&Title=cxtHoMnBtLogin&Feature=cxtHoMnBtLogin&Source=" + Source;
	window.open(URL,'LogIn','width=310,height=305,left=200,top=200,resizable=no,scrollbars=no')
}

function getNextPractice(num)
{
	if (practiceLoaded)
	{
		practiceLoaded = false;
		if (num == 0 || num == obj.Sequence || num > obj.TotalSequence)
		  return;
		else
		{
			document.body.style.cursor = "wait";
			if (!FromTMS)
			{
				var mark = getMark(appName);             
				stopTime = new Date()
				diff = Math.floor((stopTime - startTime) / 1000);
				saveMark(obj.Id, mark, diff, 1);
				if (mark > 0)
					updatePracticeProgress();
				startTime = new Date()
			}
			setCompositeCookie("Component", "ItemId", obj.SequenceArr[num - 1]);
			obj = getItem(obj.SequenceArr[num - 1]);
			helpFile = getHelpFileName(InteractionArr[num - 1]);
			var applet = document.applets[appName];
			if (applet != null)
			{
				applet.getPractice(num - 1);
			}
			buildPager("Practice", "yes");
			//buildBackNextBtn("", "yes");
		}
  }
}

function restorePagerIndex(ind)
{
	obj = getItem(obj.SequenceArr[ind]);
	setCompositeCookie("Component", "ItemId", obj.SequenceArr[ind]);
	helpFile = getHelpFileName(InteractionArr[ind]);

	endLoading();
}

function endLoading()
{
	practiceLoaded = true;
	document.body.style.cursor = "default";
}

function getNextTest(num, mode)
{
	if (practiceLoaded)
	{
		practiceLoaded = false;

		if (num == 0 || num == obj.Sequence || num > obj.TotalSequence)
		  return;
		else
		{
			document.body.style.cursor = "wait";
			if (mode != testMode)
			{
				setCompositeCookie("Test", "testMode", mode)
			}    
			setCompositeCookie("Component", "ItemId", obj.SequenceArr[num - 1]);
			obj = getItem(obj.SequenceArr[num - 1]);
			obj.SequenceArr = testRandomSet;
			obj.Sequence = num;
			var url = "TestFeedback.asp?sequence=" + obj.Sequence + "&ItemId=" + obj.Id + "&TotalSequence=" + obj.TotalSequence + "&FromTMS=" + FromTMS
			document.getElementById("SubmitTest").innerHTML = '<a href="javascript:OpenMsgWindow(&quot;' + url + '&quot;, &quot;' + appName + '&quot;)" class="StartTestText">' + getTranslate("cxtCoTeBtSubmitTest") + ' &gt;&gt;</a>'
			helpFile = getHelpFileName(InteractionArr[num - 1]);
			buildPager(mode, "yes")
			var applet = document.applets[appName];
			if (applet != null)
			{
				applet.setItemVisited(visitedCurrentItem);
				applet.getPractice(num - 1);
			}
		}
	}
}

function getTestAnswer(num)
{
	setCompositeCookie("Component", "ItemId", testRandomSet[num - 1])
	setCompositeCookie("Test", "Sequence", num);
	document.location = "TestCheckAnswers.asp?Sequence=" + num + "&TotalSequence=" + obj.TotalSequence + "&ItemId=" + testRandomSet[num-1] + "&FromTMS=" + FromTMS
}

function getNextTestAnswer(num, mode)
{
	if (practiceLoaded)
	{
		practiceLoaded = false;

		if (num == 0 || num == obj.Sequence || num > obj.TotalSequence)
		  return;
		else
		{
			setCompositeCookie("Component", "ItemId", obj.SequenceArr[num - 1]);
			obj = getItem(obj.SequenceArr[num - 1]);
			obj.SequenceArr = testRandomSet;
			obj.Sequence = num;
			helpFile = getHelpFileName(InteractionArr[num - 1]);
			var applet = document.applets[appName];
			if (applet != null)
				applet.getPractice(num - 1);
			buildPager(mode, "yes");
			appletMode = "seeUserAnswer"
			currentMode = "seeUserAnswer";
			UpdateMenuView("Your", "Correct");      
			updateResultTable(num, obj.TotalSequence);
		}
	}
}
		
function updateResultTable(num, numPractices)
{
	var marks = getCompositeCookie("Test", "Marks");
	if (marks != null && marks != "")
	{
		var marksArr = marks.split("|");
		var styleButton = "TestQuestionButton";
		var testMark, pic, url, strHref, strHrefImg;
	
		for (var i = 1; i <= numPractices; i++)
		{
		  testMark = marksArr[i - 1];                 
			if (testMark == 0)
				pic = "Context/test/feadback/WrongAnswer3.gif";
			else if (testMark > 0 && testMark < 100)
				pic = "Context/test/feadback/halfAnswer3.gif";
			else
				pic = "Context/test/feadback/RightAnswer3.gif";

			url = "javaScript:getNextTestAnswer(" + i + ", &quot;TestCheck&quot;)"
			if (i == num)
			{
			 	strHref = "<span class='TestPageActive'>" + i + "</span>";
			 	strHrefImg = "<img src='" + pic + "' width='11' height='11'>";  		 		  
 			}		 	
 			else
 			{
			  strHref = "<a class='TestPage' href='" + url + "'>" + i + "</a>";
			  strHrefImg = "<a href='" + url + "'><img src='" + pic + "' width='11' height='11' border='0'></a>";
 			}
			document.getElementById("Ref" + i).innerHTML = strHref;
			document.getElementById("imgRef" + i).innerHTML = strHrefImg;
		}
	}
}

function getTestItem(num, mode)
{
	if (practiceLoaded)
	{
		practiceLoaded = false;

		if (num == 0 || num == obj.Sequence || num > obj.TotalSequence)
		  return;
		else
		{
			obj = getItem(obj.SequenceArr[num - 1]);
			obj.SequenceArr = testRandomSet;
			obj.Sequence = num;
			var applet = document.applets[appName];
			if (applet != null)
				applet.getPractice(num - 1);
			buildPager(mode, "yes");
			appletMode = "seeUserAnswer"
			currentMode = "seeUserAnswer";
			UpdateMenuView("Your", "Correct");      
			updateTestResultTable(num, obj.TotalSequence);
			if (isCTR) {
				top.FTDone = false;
				top.STDone = false;
				top.TTDone = false;
				top.setIFramesHeight(); 
			}
			else {
				top.FTDone = false;
				top.LTDone = false;
				top.setIFramesHeight(); 
				top.setIFramesHeight1(); 
			}
		}
	}
}
		
function updateTestResultTable(num, numPractices)
{
	var marks;
	if (isCTR)
		marks = testMarks;
	else
		marks = getCompositeCookie("CompTest", "Marks" + testSeq);
	if (marks != null && marks != "")
	{
		var marksArr = marks.split("|");
		var styleButton = "TestQuestionButton";
		var testMark, pic, url, strHref, strHrefImg;
	
		for (var i = 1; i <= numPractices; i++)
		{
		  testMark = marksArr[i - 1];                 
			if (testMark == 0)
				pic = "Context/test/feadback/WrongAnswer3.gif";
			else if (testMark > 0 && testMark < 100)
				pic = "Context/test/feadback/halfAnswer3.gif";
			else
				pic = "Context/test/feadback/RightAnswer3.gif";

			url = "javaScript:getTestItem(" + i + ", &quot;testResults&quot;)"
			if (i == num)
			{
			 	strHref = "<span class='TestPageActive'>" + i + "</span>";
			 	strHrefImg = "<img src='" + pic + "' width='11' height='11'>";  		 		  
 			}		 	
 			else
 			{
			  strHref = "<a class='TestPage' href='" + url + "'>" + i + "</a>";
			  strHrefImg = "<a href='" + url + "'><img src='" + pic + "' width='11' height='11' border='0'></a>";
 			}
			document.getElementById("Ref" + i).innerHTML = strHref;
			document.getElementById("imgRef" + i).innerHTML = strHrefImg;
		}
	}
}

function getMark(appletName)
{
	var mark = 0;
	if (appletName == "")
	{
		mark = 1;
		if (obj.SubComponent != "Test")
			setCompositeCookie("Component", "lastItemId", obj.Id);
	}
	else
	{
		var applet = document.applets[appletName];
		if (applet != null && applet.isActive())
		{
			mark = applet.calculateMark();
		  if (mark > 0 && obj.SubComponent != "Test")
		  {
				setCompositeCookie("Component", "lastItemId", obj.Id);
			}
		}
	}
	return mark;
}

function getAppletName()
{
	var helpCode = skill.substr(0,1) + obj.SubComponent.substr(0,1);
	switch(obj.SubComponent)
	{
		case "Explore":
			switch(skill)
			{ 
				case "Listening":
					strApplN = "ExploreLLM"
					helpFile = "ListeningExploreH"
					break;
				case "Reading":
				case "Writing":
					strApplN = "ExploreRLV"
					helpFile = "ReadingExploreH"
					break;
				case "Grammar":
					strApplN = "ExploreG"
					helpFile = "GrammarExploreH"
					break;
				case "Speaking":
					if (obj.Subject == "Video" || obj.Subject == "Blank") {
						strApplN = "ExploreLLM"
						helpFile = "ListeningExploreH"
					}	
					else {
						strApplN = "ExploreSLV"
						helpFile = "SpeakingExploreH"
					}	
					break;	        
			}
			break;    
		case "Practice 1":
		case "Practice 2":
			strApplN = "PracticeSpk";
			var lasrLetter = obj.Code.substr(obj.Code.length - 1, 1);
			if (lasrLetter.toLowerCase() == "m")
				helpFile = "SpeakingPractice2H";
			else
				helpFile = "SpeakingPractice1H";
			break;    
		case "Interact 1":
		case "Interact 2":
			strApplN = "PracticeVSO";
			var lasrLetter = obj.Code.substr(obj.Code.length - 1, 1);
			if (lasrLetter.toLowerCase() == "w")
				helpFile = "SpeakingPractice2H";
			else
				helpFile = "SpeakingPractice1H";
			break;    
		case "Practice":
		case "Test":
			appCode = "PracticeManager";
			appName = "PracticeManager";
			strApplN = "PracticeManager";
			if (obj.SubComponent == "Test" && testMode != "Test")
				helpFile = helpCode + "openH";
			else
				helpFile = getHelpFileName(obj.ItemType);
			break;    
	}
}

function getHelpFileName(Interaction)
{
	var hc = skill.substr(0,1) + obj.SubComponent.substr(0,1);
	var name;

	switch(Interaction)
	{
		case "Classification":
		  name = hc +  "ClassificationH"
		  break;    
		case "Fill in The Blanks Segment":
		  name = hc +  "FITBSegH"
		  break;  
		case "Fill In The Blanks Whole":
		  name = hc +  "FITBWholeH"  
		  break;  
		case "Sequence Image":
		  name = hc +  "sequencingIH"      
		  break;  
		case "Sequence Sentence":
		  name = hc +  "sequencingSH"	         
		  break;  
		case "Cloze":
		  name = hc +  "ClozeH"
		  break;  
		case "Cloze Whole":
		  name = hc +  "ClozeWholeH"
		  break;  
		case "Cloze Whole (bmp)":
		  name = hc +  "ClozeWholeH"
		  break;  
		case "Mark The True":
		  name = hc +  "MTTH"
		  break;  
		case "Matching":
		  name = hc +  "matchingH"
		  break;  
		case "Multiple Choice Question Segments":
		  name = hc +  "mcqsegH"
		  break;  
		case "Multiple Choice Question Whole":
		  name = hc +  "mcqwholeH"
		  break;      
		case "Cloze Segments":
		  name = hc +  "ClozeSegH"
		  break;  
		case "Open Ended Segments":
		  name = hc +  "OpenEndedH"
		  break;  
	}
	return name;
}

function buildPracticesPath()
{
	var name, found;
	var path = "";
	var length = InteractionArr.length;
	
	for (var i = 0; i < length; i++)
	{
		found = false;
		for (var j = 0; j < i; j++)
		{
			if (InteractionArr[i] == InteractionArr[j])
			{
				found = true;
				break;
			}
		}		
		if (found)
			continue;
			
		switch(InteractionArr[i])
		{
			case "Classification":
			  name = "PracticeClassification"     
			  break;    
			case "Fill in The Blanks Segment":
			  name = "PracticeFITBSegments"     
			  break;  
			case "Fill In The Blanks Whole":
			  name = "PracticeFITBWhole"   
			  break;  
			case "Sequence Image":
			  name = "PracticeSeqImages"     
			  break;  
			case "Sequence Sentence":
			  name = "PracticeSeqSentences"       
			  break;  
			case "Cloze Whole":
			  name = "PracticeClozeWhole"         
			  break;  
			case "Cloze Whole (bmp)":
			  name = "PracticeClozeWholeGrammar"         
			  break;  
			case "Mark The True":
			  name = "PracticeMarkTheTrue"      
			  break;  
			case "Matching":
			  name = "PracticeMatching"    
			  break;  
			case "Multiple Choice Question Segments":
			  name = "PracticeMCQSegments" 
			  break;  
			case "Multiple Choice Question Whole":
			  name = "PracticeMCQWhole"   
			  break;      
			case "Cloze Segments":
			  name = "PracticeClozeSegments"         
			  break;  
			case "Open Ended Segments":
			  name = "PracticeOESegments"         
			  break;  
			case "Match Text To Picture":
			  name = "PracticeTextToPicture"         
			  break;  
			case "Matching Game":
			  name = "PracticeMatchingGame" 
			  break;  
			case "Cloze":
			  name = "PracticeCloze"         
			  break;  
			case "Multiple Choice Question":
			  name = "PracticeMultipleChoiceQuestion" 
			  break;  
			case "Open Ended":
			  name = "PracticeOpenEnded"         
			  break;  
			case "Free Writing":
			  name = "PracticeFreeWriting"         
			  break;  
			case "Fill In The Blanks":
			  name = "PracticeFillInTheBlanks"   
			  break;  
		}
		path += "Programmers/" + name + "/" + name + ".jar,";
	}
	return path;
}

function buildExplApplet(id, width, height)
{
	w('<APPLET id="' + id + '" name="TextImg" code="edweb/tools/TextImg.class"') 
		w('width="'+width+'" height="'+height+'"')
		w('archive="Programmers/CommonClasses/BaseClasses.jar,Programmers/Tools/TextImg.jar,Programmers/CommonClasses/CommonClasses.jar" mayscript>')
	w('</APPLET>')
}

// Flash functions

function MediaPlayer_DoFSCommand(command, args)
{ 
	var applList = getTrackerObj().getVariable("ListenerObj");
	if (command == "eos")
	{ 
		var mp = document.applets[applList].getPlayerForName("MediaPlayer");
		if (mp != null)
			mp.EndOfStream(0);
	}
	else if (command == "play")
	{
		onBtnValueChanged(applList,"mtrc_play",true);
	}
	else if (command == "stop")
	{
		onBtnValueChanged(applList,"mtrc_play",false);
	}
	else if (command == "TrPos")
	{
		onTrackerValueChanged(applList,"TrackerLite",args,0);
	}
	else if (command == "TrPosDrag")
	{
		onTrackerValueChanged(applList,'TrackerLite',args-1,3);
	}
	else if (command == "btnState")
	{
		alert(args);
	}
}

function setFSelectedSE(from_tm,to_tm)
{
	if(psFSeg) {
		if(psFSeg == from_tm)
			from_tm = 0;
	}
	var MP = window.document.MediaPlayer;
	MP.changeModePart();
	MP.setFSelectedSE(from_tm,to_tm);
}

function playFlash()
{
	var MP = document.getElementById('MediaPlayer');
	MP.playFlash();
}

function stopFlash()
{
	var MP = document.getElementById('MediaPlayer');
	MP.pauseFlash();
}

function setPositionFL(from_tm)
{
//	window.document.MediaPlayer.SetVariable("_root.fromFrame",from_tm*12.026);  
//	window.document.MediaPlayer.TCallLabel('/','setTrPos');
}

function GetDurationFl()
{
	var MP = document.getElementById('MediaPlayer');
	var duration = MP.getDuration();
	return duration;
}

function GetPositionFl()
{
	var MP = document.getElementById('MediaPlayer');
	var position = MP.getPosition() ;
	return strApplN == "PracticeManager" ? position * 12.026 : position ;
}

function btnState()
{
	var MP = document.embeds['MediaPlayer'];
	var buttonState = MP.GetVariable("buttonState");
	return buttonState;
}

var objSegments;
var psFSeg;

function initFlash(strIni)
{
	if(typeof(strIni) == 'undefined')
		return;
		
	var iSPoint ;
	if(strIni && (iSPoint = strIni.toLowerCase().indexOf("segments=")) >-1){
		iSPoint = strIni.toLowerCase().indexOf(";",iSPoint) ;
		if(iSPoint > -1){
			var strFParam = strIni.substr(iSPoint + 1) ;
			var MP = document.embeds['MediaPlayer'];
			if(typeof(MP) == 'undefined')
				MP = document.getElementById('MediaPlayer');
			if(MP && MP.setKeyframes){
				MP.setKeyframes(strFParam,0);
			}
			else
				alert('Function "setKeyframes" not exists yield in the current flash object') ;
		}
	}

	var splitString = strIni.split(";");
	var SegArray = splitString[4].split("&");
	objSegments = new Array();
	for (var i = 0; i < SegArray.length ; i++){
		var currFrom = SegArray[i].split("=")[1];
		if( i == SegArray.length - 1)
			var currTo = currFrom * currFrom ;
		else
			var currTo = SegArray[i+1].split("=")[1];
		if(i == 0){psFSeg = currFrom /12.026 ;currFrom = 0 ;}
		objSegments[i]= new Array(currFrom/12.026,currTo/12.026);
	}
  return;
}

function setFile(fileName)
{
	var MP = document.embeds['MediaPlayer'];
	if(typeof(MP) == 'undefined')
		MP = document.getElementById('MediaPlayer');
	var strFN = (new String(fileName)).toString() ;
	var paths = strFN.split("/");
	var filetmp = paths[paths.length-1].split(".");
	var directory = paths[paths.length-2]; 
	MP.openFile(fileName);
}

function glSetAutoStart(bAutoStart)
{
	bglAutoStart = bAutoStart;
}

var objBtnState;

function onTrackerValueChanged(strAppId, strTrName, i_Value, i_type)
{
	if(objSegments){
		objBtnState = getBtnState('mtrs_play');
		var iV = parseInt(new Number(i_Value));
		var iT = parseInt(new Number(i_type));
		var dVal = iV ;
		var bFound = false ;
		if(objSegments){
			for(var i = 0 ; i < objSegments.length ; i ++){
				if(iV < objSegments[i][1] & iV > objSegments[i][0]){
					dVal = i ;
					bFound = true ;
					break ;
				}
			}
			if(bFound == false){
				if(iV < objSegments[0][0]){
					dVal = 0 ;
					bFound = true ;
				}
				else if(iV > objSegments[objSegments.length -1][1]){
					dVal = objSegments.length ;
					bFound = true ;
				}
			}
		}
		if(bFound == true && (i_type != false || objBtnState == 1 )){
			document.applets[strAppId].onTrackerValueChanged(dVal,iT);
		}
	}
	else
		document.applets[strAppId].onTrackerValueChanged(i_Value,i_type);
}

function endOfStream()
{
	var applList = strApplN
	var mp = document.applets[applList].getPlayerForName("MediaPlayer");
	if (mp != null)
		mp.EndOfStream(0);
	objBtnState = 0 ;
}

function btnStateChanged(state)
{
	var strAppId = strApplN
	var strBN = new String('mtrc_play') ;
	if(typeof(objBtnState) == 'indefined')objBtnState = new Object();
	objBtnState = state ;
	document.applets[strAppId].onBtnClick(strBN.toString(),state == 1 ? true : false);
}

function onTrackPlayed(strListenerName){
	var bSROpen = false ;
	try{
		if (srWin != null && !srWin.closed)
			bSROpen = true ;
	}catch(e){}
	if(bSROpen)
		endOfStream() ;
}

function cookieRepair(){
	var arrCookie = document.cookie.split(";") ;
	var bFirst = false ;
	var iRepair = 0 ;
	for (var i = arrCookie.length - 1; i>= 0 ; i--){
		if (arrCookie[i].split('=')[0].toLowerCase().indexOf("aspsessionid") > -1){
			if(bFirst == true){
				var dtCookie = new Date() ;
				dtCookie.setTime(dtCookie.getTime() - 1) ;
				DelCookie(arrCookie[i].split('=')[0]) ;
				iRepair ++ ;
			}
			bFirst = true ;
		}
	}
	var arrCCN = new Array('Student','Community','Course','Unit','Component','Test','CT','PLT','CTR','Media') ;
	for(var i = 0 ; i < arrCCN.length ; i ++){
		var strCTMPC = GetCookie(arrCCN[i]) ;
		if(strCTMPC != null && strCTMPC != ""){
			setCompositeCookie(arrCCN[i], "a", "a") ;
		}
	}
	return iRepair ;
}
