var CurrentTime = 0;
var g_Browser = navigator.appName;
var oMP;
var g_exiting = 0;
var g_loadok = 0;
var UrlArray;
var UrlIdArray;
var UrlArrayIndex = 0;
var g_bFileProtocol = (window.location.protocol.toLowerCase() == "file:");
var g_mailFrm;
var g_firstTime = true;
var g_scormInitialized = false;
var g_scormVersion = "";
var g_playok = 0;
var WebUpdate_loadedOK = false;

var g_MPTimesDelta = -1; // the difference between stream time, and scriptCommand time, in live

var m_WatchID = null;

function GetAbsJavaLoc()
{
	var jarLoc = "";
	if (window.ViewerCodeDebug == "0" && !g_bFileProtocol)
	{
		jarLoc = location.protocol + "//" + location.hostname + "/" + window.ViewerCodeDir + "/" + window.BuildNumber +"/";
	}
	return jarLoc;
}

function GetRelJavaLoc()
{
	var jarLoc = "";
	if (window.ViewerCodeDebug == "0" && !g_bFileProtocol)
	{
		var slashIdx = location.pathname.indexOf('/');
		var countSlashes = 0;
		while (slashIdx != -1)
		{
			countSlashes++;
			if (countSlashes > 1)
				jarLoc += "../"
			slashIdx = location.pathname.indexOf('/',slashIdx+1);
		}
		jarLoc += window.ViewerCodeDir + "/" + window.BuildNumber +"/"
	}
	return jarLoc;
}

function GetWatchID()
{
	if (m_WatchID == null)
		m_WatchID = Number(new Date());
		
	return m_WatchID;
}
function AddSearchString(sFile,sLocationSearch)
{
	if (g_bFileProtocol)
		return sFile;
	if (typeof(sLocationSearch) != "undefined" && sLocationSearch.length>1) //verify location.search contains more than "?"
		return sFile+sLocationSearch+"&Watchid="+GetWatchID();
	return sFile+"?Watchid="+GetWatchID();
}

function closeWin()
{
	window.top.close();
}

function setLoadedOK()
{
	WebUpdate_loadedOK=true;
}

function getLoadedOK()
{
	return WebUpdate_loadedOK;
}

function setTitle()
{
	s = "";
	if (window.__Title__.length > 0)
	{
		s = '<title>'+window.__Title__;
		if (window.__Instructor__.length > 0)
		
			s+=' - '+window.__Instructor__;
		s+='</title>';
		document.write(s);
	}

}


function IsPlayerEmbedded()
{
	return (navigator.platform.substr(0, 3).toLowerCase() == "win");
}

function getSearchAsArray()
{
	var results = new Array();
	var input = location.search.substring(1);
	if (input) 
	{
		var srchArray = input.split("&");
		var tempArray = new Array();
		for (i = 0; i < srchArray.length; i++) 
		{
			tempArray = srchArray[i].split("=");
			results[tempArray[0]] = unescape(tempArray[1]);
		}
	}
	return results;
}

function TegRemoveIlegal(strOrig)
{
	var i,strNoIlegal="";
	var strLegal=":0123456789";
	for(i=0; i<strOrig.length; i++) 
	{
		if (strLegal.indexOf(strOrig.substr(i,1))>=0) 
			strNoIlegal += strOrig.substr(i,1);
	}
	return strNoIlegal;
}


function GetTegTime(strTime)
{
	var  nSeconds=0;
	var timeArray;
	if( ( typeof(strTime)!="string" ) || (strTime.length==0) )
	{
		return -1;
	} 
	else 
	{
		strTime = TegRemoveIlegal(strTime);
		timeArray = strTime.split(":");
		if (timeArray.length<=3) 
		{
			var i, factor;
			for (i=(timeArray.length-1),factor=1; !(i<0); i--,factor*=60) 
			{
				if ( isFinite(timeArray[i]) ) 
					nSeconds += factor * timeArray[i];
				else 
					return -1;
			}
		}
	}

	return nSeconds;
}

function SetSearchStringVars()
{
	var searchArray=getSearchAsArray();

	window.TegPos = searchArray["pos"];	
	if( (typeof(window.TegPos) != "undefined") && (!isNaN(window.TegPos)) )
		window.TegPos = parseInt(window.TegPos);
	else
		window.TegPos = (-1);

	var tmpTegStart=Math.max(GetTegTime(searchArray["start"]), 0);
	var tmpTegSessionStart = 0;
	if( (window.TegSessionStart) && ( typeof(window.TegSessionStart)=="string" ) )
		tmpTegSessionStart = GetTegTime(window.TegSessionStart);
	window.TegStart = Math.max(tmpTegStart,tmpTegSessionStart);

	var tmpTegStop=GetTegTime(searchArray["stop"]);
	var tmpTegSessionStop = (-1);
	if( (window.TegSessionStop) && ( typeof(window.TegSessionStop)=="string" ) )
		tmpTegSessionStop = GetTegTime(window.TegSessionStop);
	if( (tmpTegStop >= 0) && (tmpTegSessionStop >= 0) )
		window.TegStop = Math.min(tmpTegStop,tmpTegSessionStop);
	else
		window.TegStop = Math.max(tmpTegStop,tmpTegSessionStop);
	if (window.TegStop >= 0 && (window.TegStop < window.TegStart) )
		window.TegStop = window.TegStart;


	if (typeof (searchArray["media"] ) != "undefined")
		window.media = searchArray["media"];
		
	window.trackid = searchArray["trackid"];
	window.aicc_sid = searchArray["aicc_sid"];
	window.aicc_url = searchArray["aicc_url"];
	
	window.m_WatchID = searchArray["Watchid"];
	window.Host = searchArray["Host"];
	window.HostVer = searchArray["build"];
	
	if (typeof (searchArray["username"] ) != "undefined")
		window.username = searchArray["username"];
	else
		window.username = "";

	if (typeof (searchArray["CourseGUID"] ) != "undefined")
		window.CourseGUID = searchArray["CourseGUID"];
	else
		window.CourseGUID = "";

	if (typeof (searchArray["SpecialAudioOnly"] ) != "undefined")
		window.SpecialAudioOnly = searchArray["SpecialAudioOnly"];

	if (typeof (searchArray["DisablePreload"] ) != "undefined")
		window.DisablePreload = searchArray["DisablePreload"];

		
}


function OpenPlayerStream(streamName)
{
	MP_FileName(streamName);
	g_loadok = 1;
	return 1;
}

function TSelectionEnd()
{
	return MP_SelectionEnd();
}

function TSetTime(t)
{
	if (MP_CanSeek() )
	{
		CurrentTime = t;
		tt = t+"/1000.0";
		tt = eval(tt);
		MP_SetCurrentPos(tt);
	}
}

function TGetTime()
{
	nRet = 0;
	if (g_MPTimesDelta >= 0)
		nRet = (MP_CurrentPos()*1000 + g_MPTimesDelta) ;
	else
		nRet = CurrentTime;
		
	return Math.floor(nRet); //bug in Sun VM plugin: overflow (?) when fraction too long -> will return -1
		
}

function TpGetPosition()
{
	g_exiting = 0;
	TGetPosition();
}



function TGetVideoCodec() //!!##only relevant to MP6.4 (7 comes with all needed codecs), need to add a QT dummy codec name/id
{
	rv = -1;
	if (window.__AsxFileType__ == 2)
		rv = 0;
	else  if (window.TVideoCodec.toLowerCase() == "vdo")
		rv = 1;
	else if (window.TVideoCodec.toLowerCase() == "mp43")
		rv = 2;
	return rv;
}

function InitializePage ()
{
	UrlArray = new Array();
	UrlIdArray = new Array();
	
	oMP = document.NSPlay;
	
	if ( (playback != "TRUE") && (NetShowLiveExpediteTime>5000) && (Collaboration != "1"))
	{
		MP_ContextMenu(false);
		MP_Mute(true);
	}
}


function TOpenURL(path,id,pause,isEditor,isSC)
{
	if (isEditor)
	{
		window.UrlArray[id] = window.open(path);
		if(pause)
			window.UrlIdArray[window.UrlIdArray.length] = id;
	}
	else
	{
		if(!window.UrlArray[id] || window.UrlArray[id].closed)
		{
			window.UrlArray[id] = window.open("about:blank");
			window.UrlArray[id].document.write("<!-- saved from url=(0016)http://tegrity/. --><FRAMESET COLS='*'><FRAME SRC='"+path+"'></FRAMESET>");
			
			if(pause)
				window.UrlIdArray[window.UrlIdArray.length] = id;
		}
	}
}

function TShowDocument(path) //replaces the not-working showDocument in mac
{
	var newWin = window.open("about:blank");
	newWin.document.write("<!-- saved from url=(0016)http://tegrity/. --><FRAMESET COLS='*'><FRAME SRC='"+path+"'></FRAMESET>");
}

//this function should not be entered in editor mode, due to an IE bug that fails when trying
//to get the property window.closed on the last browser window that was closed
function urlMonitor()
{
	var flag = 0;
	for(var i=0;i<window.UrlIdArray.length;i++)
	{
		if((!window.UrlArray[window.UrlIdArray[i]]) || (window.UrlArray[window.UrlIdArray[i]].closed))
		{
			window.UrlArray[window.UrlIdArray[i]] = null;
			for(var j=i+1;j<window.UrlIdArray.length;j++)
				window.UrlIdArray[j-1] = window.UrlIdArray[j];
			window.UrlIdArray.length = (window.UrlIdArray.length > 0)? window.UrlIdArray.length -1:0;
			if (window.UrlIdArray.length == 0)
				flag = 1;
		}
	}
	return flag;
}

function closeMonitoredUrls()
{
	for(var i=UrlIdArray.length-1;i>=0;i--)
	{
		if((UrlArray[UrlIdArray[i]]) && (typeof(UrlArray[UrlIdArray[i]])!="undefined")  && (!UrlArray[UrlIdArray[i]].closed))
		{
			UrlArray[UrlIdArray[i]].close();
		}
	}

}

function time_string(time_in_millisec)
{
	ticks = parseInt(time_in_millisec /1000);
	seconds = ticks % 60;
	if (String(seconds).length == 1)
		seconds = "0" + seconds;
	time_str = ":"+ seconds;
	if (ticks >= 60)
	{
		ticks = parseInt(ticks /60);
		minutes = ticks % 60;
		if (String(minutes).length == 1)
			minutes = "0" + minutes;
		time_str = minutes + time_str;
		if (ticks >= 60 )
			time_str = parseInt(ticks /60) + ":" + time_str;
	}
	else
		time_str = "00" + time_str;
	return (time_str);
}

function send_mail(dest)
{
	ClickPos = TGetTime()
	str = dest;
	str += "?subject="+__Title__;
	str += "&body=At time: " + time_string(ClickPos);
	str += "%0c%0a";
	str += "Class URL: ";
	_url = escape(location.toString());
	if (_url.lastIndexOf(".htm") == _url.length-4)
	{
		idx = _url.lastIndexOf("/");
		if (idx>0)
		{
			_url = _url.substring(0,idx+1) +"default.htm";
		}
	}
	if (location.protocol.indexOf("file")<0)
	{
		_url = _url+"?pos="+Math.floor(ClickPos);
	}
	str += "<" + _url + ">";
	if (g_Browser == "Netscape")
	{
		window.location = str;
	}
	else
	{
		if(g_firstTime)
		{
			s='<DIV id="mailFrm_div" STYLE="position: absolute; left: 0px; top: 0px">';
			s+='<IFRAME ID="mailFrm" FRAMEBORDER=0 WIDTH=0 HEIGHT=0></IFRAME>';
			s+='</DIV>';
			document.body.insertAdjacentHTML( "beforeEnd", s);
			g_firstTime = false;
		}
		s='<HTML><BODY><SCRIPT>location="'+str+'";</SCRIPT></BODY></HTML>';
		g_mailFrm = eval("mailFrm");
		g_mailFrm.document.write(s);
	}
}

function TCloseURL(id)
{
	if(window.UrlArray[id])
	{
		window.UrlArray[id].close();
		window.UrlArray[id] = null;
	}
}


function getDownloadingMessage(x,y) //!!##need some adptations to sun VM signing/jar-caching mechanisms
{
	if (typeof(y) == "undefined")
		y = 0;
	var h = typeof(window.NotesMode) == "undefined" ? 300 : 240;
	var msg='';
	msg += '<DIV ID="loading" STYLE="position:absolute; left:' + (x) + 'px; top:'+(y)+'px">';
	msg += '<TABLE BORDER=0 WIDTH="100%" HEIGHT="100%">';
	msg += '<TR HEIGHT='+h+'><TD ALIGN="center"><img src="download.gif"></TD></TR>';
	
	if (g_Browser != "Netscape")
	{
		if (navigator.userAgent.indexOf("Windows NT 5.1")>-1)
		{
			msg += '<TR HEIGHT=20 ALIGN="center"><TD>';
			msg += '<FONT FACE="Arial" SIZE="2" COLOR="White">';
			msg += "If you don't have the Microsoft Java virtual machine and can't download<BR>";
			msg += 'it from Microsoft, please <A href="http://www.tegrity.com/MSJavaVM.htm">click here</A>';
			msg += '</FONT>';
			msg += '</TD></TR>';

		}
	
		if (!g_bFileProtocol)
		{
			msg += '<TR HEIGHT=200><TD ALIGN="center" VALIGN="bottom">';
			msg += '<FONT FACE="Arial" SIZE="2" COLOR="White">';							
			msg += 'If a Security Warning message appears Tegrity recommends<BR>';
			msg += 'to click on &#39;Yes&#39; when prompted. This will minimize the loading<BR>';
			msg += 'time the next time you view a WebLearner session.';
			msg += '</FONT>';
			msg += '</TD></TR>';
		}
	}

	msg += '</TABLE>';
	msg += '</DIV>';
	return msg;
}

function getMaxVideoWidth()
{
	Stream2 = window.__AsxFileType__ & 2;
	Stream3 = window.__AsxFileType__ & 4;
	nMax = 0;
	if ( Stream2 == 2 && window.VideoWidth.length)
		nMax = Number(window.VideoWidth);
	if ( Stream3 == 4 && window.Video2Width.length && window.Video2Width > nMax)
		nMax = Number(window.Video2Width);
	return nMax;
}

function setSizes()
{
	var appVer = navigator.appVersion;
	var msie = appVer.indexOf ( "MSIE " )
	var safariidx = appVer.indexOf("Safari");
	var bMac = (navigator.platform.substring(0,3).toLowerCase() == "mac");
	var bNS = (navigator.appName=="Netscape") && safariidx < 0;
	var bFirefox = navigator.userAgent.toLowerCase().indexOf("firefox")>=0;
	
	SRW = 0; 	
	aM = 3;//margin between instructor video and slide
	aW = 640; //slide/SR area width
	aH = 552; //slide height +controlPanel
	if (window.playback != "TRUE" && window.Collaboration == "1")//live
	{
		aW = 800; //appShare width
		SRW = 800;
		mpW = 160; //instructor video width
		aH = 671; //appShare width +control panel
	}
	else if (window.NotesMode == 1)
	{
		mpW = 320;
	}	
	else if (screen.availWidth>800)
	{
		mpW = getMaxVideoWidth() ;
		mpW = mpW > 0 ? mpW : 160;
		SRW = 640; 
	}
	else
	{
		if (!bMac) 
			aW = 635;
		mpW = 160;
		aM = 0;
		SRW = 640; 
	}
	mpH = (mpW*3)/4;
	rM = 3;//right margin
	bM = 3;//bottom margin
	bW = 6;//horizontal borders
	bH = 4+29; //vertical borders and Title
	
	wW = aW+mpW+aM+rM+(bNS&&!bMac ? bW : 0);
	wH = aH+bM+(bNS&&!bMac&&!bFirefox? bH : 0);
	if ((screen.availWidth <= 800) && bMac)
		wW = 800;
	
	if (!bMac && msie>0)
	{
		WinWidth = window.document.body.clientWidth;
		WinHeight = window.document.body.clientHeight;
	}
	else
	{
		WinWidth = wW;
		WinHeight = wH;
	}
	
	if (window.NotesMode == 1)
		SRW = WinWidth; 
		
	SRH = (SRW*3)/4;
}

function addCalculatedParams()
{
	window.g_aPrms["mpH"] = mpH ;
	window.g_aPrms["mpY"] = mpY ;
	window.g_aPrms["mpW"] = mpW ;
	window.g_aPrms["aM"] = aM ;
	window.g_aPrms["WinWidth"] = WinWidth ;
	window.g_aPrms["SRW"] = SRW ;
	window.g_aPrms["SRH"] = SRH ;
}

function getScreenWidth()
{
	return window.screen.availWidth; //##need to fix this, may not be the whole width
}
function getShowCC(){ return window.UseClosedCaptions;}

function ScormSetInitialized(bSet)
{
	g_scormInitialized = bSet
}

function ScormGetInitialized()
{
	return g_scormInitialized;
}

//scorm 1.2 implementation

function getScormAPI12()
{
	var theAPI = findScormAPI12(this.top);
	if (theAPI == null)
		if (typeof(this.opener) != "undefined")
			if (this.opener != null)
			{
				if (!this.opener.closed && typeof(this.opener.top) != "undefined")
				{
					theAPI = findScormAPI12(this.opener.top);
					if (theAPI == null)
						if (typeof(this.opener.opener) != "undefined" )
						{
							if (this.opener.opener != null)
							{
								if (!this.opener.opener.closed && typeof(this.opener.opener.top) != "undefined" )
									theAPI = findScormAPI12(this.opener.opener.top);
							}
						}
				}
	        }	
	return theAPI;
}

function findScormAPI12(win) 
{
	if (win.API != null)
		return win.API;
	if (win.length > 0)  // does the window have frames?
	{
		for (var i=0;i<win.length;i++)
		{
			var theAPI = findScormAPI12(win.frames[i]);
			if (theAPI != null)
	            return theAPI;
		}
	}
	return null;
}
function ScormInitialize12()
{
	if (g_scormInitialized==false)
	{
		api = getScormAPI12();
		if (api)
			api.LMSInitialize("");
		else
			return false;
	}
	return true;
}

function ScormGetLastError12()
{
	api = getScormAPI12();
	if (api)
		return api.LMSGetLastError(""); //retval==0 if no error
	return 0;
}
function ScormGetErrorString12(errCode)
{
	api = getScormAPI12();
	if (api)
		return api.LMSGetErrorString(errCode);
	return "";
}
function ScormGetValue12(paramName)
{
	api = getScormAPI12();
	if (api)
	{
		api.LMSGetValue(paramName);
		return true;
	}
	return false;
}
function ScormSetValue12(paramName,paramValue)
{
	api = getScormAPI12();
	if (api)
	{
		api.LMSSetValue(paramName,paramValue);
		return true;
	}
	return false;
}
function ScormCommit12()
{
	api = getScormAPI12();
	if (api)
	{
		api.LMSCommit("");
		return true;
	}
	return false;
}
function ScormFinish12()
{
	if (ScormGetInitialized()==true)
	{
		api = getScormAPI12();
		if (api)
		{
			api.LMSFinish("");
			return true;
		}
		else
		{
			ScormSetInitialized( false );
			return false;
		}
	}
	return true;
}  


 
 //scorm 1.3 implementation
 
 function getScormAPI13()
 {
 	var theAPI = findScormAPI13(this.top);
 	if (theAPI == null)
 		if (typeof(this.opener) != "undefined")
 			if (this.opener != null)
 			{
 				if (!this.opener.closed && typeof(this.opener.top) != "undefined")
 				{
 					theAPI = findScormAPI13(this.opener.top);
 					if (theAPI == null)
 						if (typeof(this.opener.opener) != "undefined" )
 						{
 							if (this.opener.opener != null)
 							{
 								if (!this.opener.opener.closed && typeof(this.opener.opener.top) != "undefined" )
 									theAPI = findScormAPI13(this.opener.opener.top);
 							}
 						}
 				}
 	        }	
 	return theAPI;
 }
 
 function findScormAPI13(win) 
 {
 	if (win.API_1484_11 != null)
 		return win.API_1484_11;
 	if (win.length > 0)  // does the window have frames?
 	{
 		for (var i=0;i<win.length;i++)
 		{
 			var theAPI = findScormAPI13(win.frames[i]);
 			if (theAPI != null)
 	            return theAPI;
 		}
 	}
 	return null;
 }
 function ScormInitialize13()
 {
 	if (g_scormInitialized==false)
 	{
 		api = getScormAPI13();
 		if (api)
 			api.Initialize("");
 		else
 			return false;
 	}
 	return true;
 }
 
 function ScormGetLastError13()
 {
 	api = getScormAPI13();
 	if (api)
 		return api.GetLastError(""); //retval==0 if no error
 	return 0;
 }
 function ScormGetErrorString13(errCode)
 {
 	api = getScormAPI13();
 	if (api)
 		return api.GetErrorString(Number(errCode));
 	return "";
 }
 function ScormGetValue13(paramName)
 {
 	api = getScormAPI13();
 	if (api)
 		return api.GetValue(paramName);
 	return false;
 }
 function ScormSetValue13(paramName,paramValue)
 {
 	api = getScormAPI13();
 	if (api)
 	{
 		return api.SetValue(paramName,paramValue);
 	}
 	return false;
 }
 function ScormCommit13()
 {
 	api = getScormAPI13();
 	if (api)
 		return api.Commit("");
 	return false;
 }
 function ScormFinish13()
 {
 	if (ScormGetInitialized()==true)
 	{
 		api = getScormAPI13();
 		if (api)
 		{
 			api.Terminate("");
 			return true;
 		}
 		else
 		{
 			ScormSetInitialized( false );
 			return false;
 		}
 	}
 	return true;
 }  

//general scorm interface
 
 function getScormAPI()
 {
 	oAPI = null;
 	if (g_scormVersion == "" || g_scormVersion  == "1.3")
 	{
 		oAPI = getScormAPI13();
 		if (oAPI != null)
 			g_scormVersion  = "1.3";
 	}
 	if (oAPI == null && (g_scormVersion == "" || g_scormVersion == "1.2"))
 	{
 	
	 	oAPI = getScormAPI12();
	 	if (oAPI != null)
 			g_scormVersion  = "1.2";
 	}
 	return oAPI;
 }
 
 function ScormInitialize()
 {
 	sv = GetScormVersion();
 	if (sv == 1.2 )
 		return ScormInitialize12();
 	if (sv == 1.3) 
 		return ScormInitialize13();
 	return false;
 }
 
 function ScormGetLastError()
 {
 	sv = GetScormVersion();
 	if (sv == 1.2 )
 		return ScormGetLastError12();
 	if (sv == 1.3) 
 		return ScormGetLastError13();
 	return -1;
 }
 
 function ScormGetErrorString(errCode)
 {
 	sv = GetScormVersion();
 	if (sv == 1.2 )
 		return ScormGetErrorString12(errCode);
 	if (sv == 1.3) 
 		return ScormGetErrorString13(errCode);
 	return "Cannot find SCORM API.";
 }
 
 function ScormGetValue(paramName)
 { 
  	sv = GetScormVersion();
 	if (sv == 1.2 )
 		return ScormGetValue12(paramName);
 	if (sv == 1.3) 
 		return ScormGetValue13(paramName);
 	return false;
 }
 function ScormSetValue(paramName,paramValue)
 {
 	sv = GetScormVersion();
 	if (sv == 1.2 )
 		return ScormSetValue12(paramName,paramValue);
 	if (sv == 1.3) 
 		return ScormSetValue13(paramName,paramValue);
 	return false;
 }
 function ScormCommit()
 {
 	sv = GetScormVersion();
 	if (sv == 1.2 )
 		return ScormCommit12();
 	if (sv == 1.3) 
 		return ScormCommit13();
 	return false;
 }
 function ScormFinish()
 {
 	sv = GetScormVersion();
 	if (sv == 1.2 )
 		return ScormFinish12();
 	if (sv == 1.3) 
 		return ScormFinish13();
 	return false;
 }
 
 function GetScormVersion()
 {
 	if (g_scormVersion == "")
 		getScormAPI() ;//initializes g_scormVersion
 	n = Number(g_scormVersion);
 	if (n <= 1.2) return 1.2;
 	if (n > 1.2) return 1.3;
 	return 0;
 }
 
 function GetScormVersionStr()
 {
  	if (g_scormVersion == "")
 		getScormAPI() ;//initializes g_scormVersion
 	return g_scormVersion;
 }
