
// NOTE:  Certain values are hardcoded in the script below.
//   Silverlight does not provide the Network property, with a number of the more
//   detailed transfer rate, buffering, and other status bits we've handled before:
//   http://msdn.microsoft.com/en-us/library/system.windows.controls.mediaelement_members(VS.95).aspx

var DEBUG = false;
var hasValidDuration = false;
var chkLive = '<<@VODONLY@>>';
var isLive = false;
if (chkLive == 'hidden' || getvar('mediaUrl') != ''){
	isLive = true;
}
var pid = getvar('i');
var uid = getvar('u');
var trackingUrl = decodeURIComponent(getvar('trackingUrl'));
var trackingID = getvar('trackingID');
var eventID = getvar('eventID');
var webDirectoryID = getvar('webDirectoryID');
var streamPointID = -1;
var postCount = 0;
var lowBandwidth = 0;
var highBandwidth = 0;
var averageBandwidth = 0;
var lowFrameRate = 0;
var highFrameRate = 0;
var averageFrameRate = 0;
var redirFrmLoc = 'index.htm';
var cookieUpdRate = '<<@CLIENTSIDE_REFRESH@>>';
if(getvar('trackingInterval') != '')
{
	cookieUpdRate = getvar('trackingInterval');
}
var dataUpdRate = '<<@SERVERSIDE_REFRESH@>>';
var statsFULL = 1;
var clipFinished = false;
var mediaLength = 0;
var openerReloaded = false;
var playing = true;
var makeFinalPost = true;
var playerType = 1; //1 = ms, 2 = real
var clipStartTime = '';
var clipEndTime = '';
var viewingEndTime = '';
var viewingStartTime = '';
var videoStartTime = '';
var clipDuration = '';
var mediaUrl = decodeURIComponent(getvar('mediaUrl'));
cookieUpdRate = Math.floor(cookieUpdRate * 1000);
dataUpdRate = Math.floor(dataUpdRate * 1000);

window.onunload = function()
{
	try
	{
		window.top.opener.location.reload(1);
	}
	catch (e)
	{
	}
}

function RedirectMediaPlayerURL()
{
    if(mediaUrl != '')
    {
        if(!MediaPlayer)
        {
            var reset
            
            reset = window.setTimeout('RedirectMediaPlayerURL()', 50);
        }
        else
        {
            MediaPlayer.source = mediaUrl;
        }
    }
}

function playStateChange(NewState)
{
	try{
		playerType = 1;
		if (playing && NewState != 'Playing'){  makeFinalPost = true;  }
		playing = (NewState == 'Playing');
		switch(NewState){
			case 'Paused':
				if(Math.abs(MediaPlayer.Position.Seconds - MediaPlayer.NaturalDuration.Seconds) < 0.01){
					// end of presentation reached
					onMediaEnded(MediaPlayer, null);
					return;
				}
				break;
			case 'Complete':
				Stopbutton_MouseLeftButtonUp(MediaPlayer);
				clipFinished = true;
				break;
		}
	}
	catch (e){ }
}

function getcookie(cookiename) {
	var cookiestring=""+document.cookie;
	var index1=cookiestring.indexOf(cookiename);
	if (index1==-1 || cookiename=="") return "";
	var index2=cookiestring.indexOf(';',index1);
	if (index2==-1) index2=cookiestring.length;
	return unescape(cookiestring.substring(index1+cookiename.length+1,index2));
}

function conv_jsTime2Sql(time_ms){
	tempJs = parseInt(time_ms); 
	t = new Date(tempJs);
	tDay = t.getDay(); // actual day
	tMonth = new String(t.getMonth() + 1); // js 0-11 for months
	tDate = new String(t.getDate());
	tYear = new String(t.getFullYear());
	tHours = new String(t.getHours());
	tMinutes = new String(t.getMinutes());
	tSeconds = new String(t.getSeconds());
	if (tMinutes < 10) tMinutes = new String('0' + tMinutes);
	if (tSeconds < 10) tSeconds = new String('0' + tSeconds);
	tMTemp = tMonth + '/' + tDate + '/' + tYear + ' ' + tHours + ':' + tMinutes + ':' + tSeconds;
	var sqlTime = new String(tMTemp);
	return(sqlTime);
}

function writeCookie_CurPos(f) {
	if (playing || makeFinalPost)
	{
		makeFinalPost = false;
		var oldClipEndTime = clipEndTime;
		if (mediaLength == 0) 
		{
//			if(ie)
				mediaLength = MediaPlayer.NaturalDuration.Seconds;
//			else
//				mediaLength = '5591';
		}
		var initClipPos = 0;
		clipStartTime = initClipPos;
		var getWindowsPos = 0;
		getWindowsPos = Math.floor(MediaPlayer.Position.Seconds);
		if (clipFinished)
		{
			getWindowsPos = Math.floor(mediaLength)
			if (!openerReloaded)
			{
				try
				{
					window.top.opener.location.reload(1);
				}
				catch (e)
				{
				}
				openerReloaded = true;
			}
		}
		clipEndTime = getWindowsPos;
		var cookieDate = new Date();
		var cookieDate_ms = cookieDate.getTime();
		viewingEndTime = cookieDate_ms;
		var viewerProg = clipEndTime;
		var viewerTime = viewingEndTime;
		var startTime = viewingStartTime;
		viewerT = conv_jsTime2Sql(viewerTime);
		startT = conv_jsTime2Sql(startTime);
		postCount++;

		// var currentBandwidth = MediaPlayer.Network.bandWidth;
		// unrecognized property in Silverlight; substitute hard-coded val
		var currentBandwidth = 100;

		if ((currentBandwidth < lowBandwidth || lowBandwidth == 0) && currentBandwidth != 0)
		{
			lowBandwidth = currentBandwidth;
		}
		if (currentBandwidth > highBandwidth)
		{
			highBandwidth = currentBandwidth;
		}
		if (currentBandwidth > 0)
		{
			averageBandwidth = ((averageBandwidth * (postCount - 1)) + currentBandwidth) / postCount;
		}
		
		var currentFrameRate = 0;
		var winVistaCheck = navigator.userAgent.indexOf("NT 6.")
		if (winVistaCheck == -1)
		{
			// var currentFrameRate = MediaPlayer.Network.frameRate;
			var currentFrameRate = 24;  // (config'd in f.htm on object creation)
			
			if ((currentFrameRate < lowFrameRate || lowFrameRate == 0) && currentFrameRate != 0)
			{
				lowFrameRate = currentFrameRate;
			}
			if (currentFrameRate > highFrameRate)
			{
				highFrameRate = currentFrameRate;
			}
			if (currentFrameRate > 0)
			{
				averageFrameRate = ((averageFrameRate * (postCount - 1)) + currentFrameRate) / postCount;
			}
		}
		
		var framesSkippedCheck = 0;
		if (winVistaCheck == -1)
		{
			// framesSkippedCheck = MediaPlayer.network.framesSkipped;
			framesSkippedCheck = 0;
		}
		
		if (trackingUrl != '')
		{
			// var bitrate = MediaPlayer.Network.bitRate;
			var bitrate = 100;
			
			var redirectUrl = trackingUrl +
				'?trackingID=' + encodeURIComponent(trackingID) +
				'&presentationID=' + encodeURIComponent(pid) + 
				'&eventID=' + encodeURIComponent(eventID) + 
				'&viewerID=' + encodeURIComponent(uid) +
				'&viewingStartTime=' + encodeURIComponent(viewingStartTime) +
				'&viewingEndTime=' + encodeURIComponent(viewingEndTime) +
				'&clipStartTime=' + encodeURIComponent(clipStartTime) + 
				'&clipEndTime=' + encodeURIComponent(clipEndTime) +
				'&lastDateTracked=' + encodeURIComponent(new Date()) +
				'&isFinished=' + encodeURIComponent(clipFinished) +
				'&clipDuration=' + encodeURIComponent(mediaLength) +
				'&isLive=' + encodeURIComponent(isLive) +
				'&baseURL=' + encodeURIComponent('http://accordent.powerstream.net/008/00131/LF/Library_Futures_120109/') +
				'&lowBandwidth=' + encodeURIComponent(lowBandwidth) +
				'&highBandwidth=' + encodeURIComponent(highBandwidth) +
				'&averageBandwidth=' + encodeURIComponent(averageBandwidth) +
				'&bitrate=' + encodeURIComponent(bitrate) +
				'&bufferingCount=' + encodeURIComponent(replaceZeroWithEmptyString(Math.floor(100*MediaPlayer.BufferingProgress))) +
				'&bufferingTime=' + encodeURIComponent(replaceZeroWithEmptyString(MediaPlayer.BufferingTime.Seconds)) +
				'&lowFrameRate=' + encodeURIComponent(lowFrameRate) +
				'&highFrameRate=' + encodeURIComponent(highFrameRate) +
				'&averageFrameRate=' + encodeURIComponent(averageFrameRate) +
				'&framesSkipped=' + encodeURIComponent(replaceZeroWithEmptyString(framesSkippedCheck)) +
				'&lostPackets=' + encodeURIComponent(replaceZeroWithEmptyString(0)) +
				'&receivedPackets=' + encodeURIComponent(replaceZeroWithEmptyString(Math.floor(100*MediaPlayer.DownloadProgress))) +
				'&recoveredPackets=' + encodeURIComponent(replaceZeroWithEmptyString(0)) +
				'&playerType=' + encodeURIComponent(playerType) +
				'&versionInfo=' + encodeURIComponent('Silverlight') +
				'&postCount=' + postCount +
				'&webDirectoryID=' + webDirectoryID +
				'&streamPointID=' + streamPointID;
			if(DEBUG){ 
				alert('Tracking points to:\n  '+redirectUrl); 
			}
			document.getElementById('trackingImage').src = redirectUrl;
		}
	}
}

function writeCookie_Close() {
	var initClipPos = 0;
	clipStartTime = initClipPos;
	var getWindowsPos = MediaPlayer.Position;
	getWindowsPos = Math.floor(getWindowsPos);
	clipEndTime = getWindowsPos;
	var cookieDate = new Date();
	var cookieDate_ms = cookieDate.getTime();
	viewingEndTime = cookieDate_ms;
	var viewerProg = clipEndTime;
	var viewerTime = viewingEndTime;
	var startTime = viewingStartTime;
	viewerT = conv_jsTime2Sql(viewerTime);
	startT = conv_jsTime2Sql(startTime);
	closeButtonHit();
}

function closeButtonHit() {
	
}

function load_window(){
	
}

function exit_window(){
	window.setTimeout("window.top.close()",1000);
	writeCookie_Close();
}

function init_Load(){
	tempInit = new Date();
	initTimeStamp = tempInit.getTime();
	viewingStartTime = initTimeStamp;
	chkFrames();
}

function actualTimeViewed() {
	initTm = viewingStartTime;
	curTm = viewingEndTime;
	timeVw = Math.ceil( (curTm - initTm)/1000 );
	return(timeVw);
}

function clearIntval() {
	clock_timer = window.clearInterval(clock_timer);
}

function chkFrames(){
	if (document.getElementById('trackingImage')) {	   
	    RedirectMediaPlayerURL();
		clock_timer = window.setInterval("writeCookie_CurPos()",cookieUpdRate);
		currentPID = window.setInterval("getContentID()", cookieUpdRate);
	} else {
		alert('Unable to reference media management server.');
		window.location = redirFrmLoc;
	}
}

function getContentID()
{
    var vid = MediaPlayer;
    // var pl = vid.currentPlaylist;
    var pl = new Array();
    var plItem;
    var entryIndex;
    var attrName;
    var attrVal;
        
    if(streamPointID < 0)
    {
        if(vid.CurrentState == 'Playing')
        {
            for (var i=0; i < pl.count; i++)
            {            
                if (vid.currentmedia.isIdentical(pl.item(i)))
                {
                    entryIndex = i;
                }
            }
//          plItem = pl.item(entryIndex);            
//          streamPointID = plItem.getItemInfo('ID');
            streamPointID = 0;
        }
    }   
}

function ck_Duration() {
	var ckDuration = 0;
    var state;
	var vid = MediaPlayer;
	state = vid.CurrentState;
	if (state == 'Playing') ckDuration = 1;
	return(ckDuration);
}

function getDuration() {
	var currentDuration;
//	if(ie)
//	{
		var state;
		var vid = MediaPlayer;
		state = vid.CurrentState;
		if (state == 'Playing') currentDuration = vid.NaturalDuration;
//	}
//	else
//	{
//		currentDuration = '5591';
//	}
	return(currentDuration);
}

function getError() {
//	var curError;
//	var vid = MediaPlayer;
//	curError = vid.error.errorCount;
//	return(curError);
	return 0;
}

function updateChp(){
	if (window.top.chapters && window.top.chapters.sync){
		var curTime = MediaPlayer.Position;
		window.top.chapters.genSync(curTime);
	}
}

var init = 0;

function errorFxn(errCnt){
	window.clearInterval(idTmr);
}


var displayDuration = '';

function getDurationCk() {
	if(!MediaPlayer) 
	{
		window.clearInterval(idTmr);
        self.setTimeout('getDurationCheck()', 1000);
        return false;
		// self.document.cookie = 'pres_error=1';
	} 
	else{  // silverlight player exists
		alert
		var chkError = getError();
		if (chkError == 0)
		{
			var durationChk = 0; 
			durationChk = ck_Duration();
			if (durationChk > 0) 
			{
				window.clearInterval(idTmr);
				setDurationCookie();
				hasValidDuration = true;
				displayDuration = durationChk;
			}

		} 
		else 
		{
			errorFxn(chkError);
		}
	}
//	else
//	{
//		if (videoStartTime == '')
//		{
//			videoStartTime = (new Date()).getTime();
//		}
//		window.clearInterval(idTmr);
//		setDurationCookie();
//		hasValidDuration = true;
//		displayDuration = '5591';
//	}

	if(hasValidDuration)
	{
		if(pid != '' && uid != '')
		{
			var myurl;
			if (clipEndTime == '')
			{
				myurl = 'clear.asp?pid=' + pid + '&uid=' + uid + '&trackingUrl=' + trackingUrl;
			}
			else
			{
				myurl = 'track.asp?pid=' + pid + '&uid=' + uid + '&trackingUrl=' + trackingUrl;
			}
		}
	}
}
	
function getMediaDurationScan(){
	init_Load();
	if(isLive)
	{
		clipDuration = 999999999;
	} 
	else 
	{
		idTmr = window.setInterval('getDurationCk()',50);
	}
}

function setDurationCookie(){
	window.clearInterval(idTmr);
	var localClipDuration = getDuration();
	var localClipDuration = Math.floor(localClipDuration);
	clipDuration = localClipDuration;
	return(localClipDuration);
}

var nowTime = new Date();
nowTime = new String(nowTime.getTime());

function getvar(el, case_sensitive) { //el=str, case_sensitive=bool
	var rs="";
	if(!case_sensitive) rs="i";
	var urls = new String(window.location);
	var re = new RegExp( "\\?[\\w\\W]*"+ el +"=([^\\&\\?#]*)", rs );
	var arr = re.exec(urls);
	if(arr && arr.length>1) return arr[1];
	else return '';
}

clipDuration = 0;

function replaceZeroWithEmptyString(intValue)
{
	if (intValue == 0)
	{
		return "";
	}
	else
	{
		return intValue;
	}
}

