/* 	VIDEO ANALYTICS
	v 0.3
	Last updated Oct 28, 2008
	dbax
*/

// SETUP VIDEO ANALYTICS
var va_log_granularity = 2;

var va_player;
var va_current_item;
var va_current_item_url;
var va_current_time;
var va_logged_this_item = 0;
var va_last_status;

var va_debug = false;

var va_log_server = "http://stats.biola.webfactional.com/log";

var va_user_session = va_generate_session();

var va_tracking_rebuffering = false;
var va_tracking_rebuffering_time;

var va_bitrate_start_time = 0;
var va_bitrate_start_bytes;

var va_state_time;
var va_state_haspaused;



function playerReady(obj) {

	printTrace("PLAYER READY (id:"+obj['id']+",version:"+obj['version']+",client:"+obj['client']+')');
	
	// Find player
	va_player = gid(obj.id);
	
	// Setup listeners
	va_player.addModelListener('TIME','va_time_listener');
	va_player.addViewListener('SEEK','va_seek_listener');
	va_player.addControllerListener("ITEM","va_item_listener");
	va_player.addControllerListener("RESIZE","va_fullscreen_listener");
	va_player.addModelListener('META','va_rebuffer_listener');
	va_player.addModelListener('LOADED','va_bitrate_listener');
	va_player.addModelListener('STATE','va_state_listener');
	
	printTrace("all done");
	
	if (video_autoplay_temp) {
		//alert("autoplay");
		//va_player.sendEvent('PLAY');
	}
	
};

function va_generate_session() {
	var random_session = "";
	
	now = new Date();
	now_string = now.getFullYear() + ((now.getMonth() < 9) ? "0" : "") + (now.getMonth()+1) + ((now.getDate() < 10) ? "0" : "") + now.getDate();
	random_session += now_string;
	
	var random_set = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
	var random_length = 12;
	for (var i=0; i < random_length; i++) {
		random_value = Math.floor(Math.random() * random_set.length);
		random_session += random_set.substring(random_value, random_value+1);
	}
	
	return random_session;
}


/* === LISTENERS === */
function va_item_listener(o) {
	va_current_item = va_player.getPlaylist()[o.index].description;
	va_current_item_url = va_player.getPlaylist()[o.index].file;
	va_logged_this_item = 0;
	va_bitrate_start_time = 0;
	va_state_time = 0;
	va_state_haspaused = false;
}

function va_rebuffer_listener(o) {
	if ((o.info == "NetStream.Buffer.Empty") && (va_last_status == "TIME")) {
		va_tracking_rebuffering = true;
		
		now_date = new Date();
		va_tracking_rebuffering_time = now_date.getTime();
		
		logTrace("BUFFER EMPTY!");
	}
	
	if ((o.info == "NetStream.Buffer.Full") && (va_tracking_rebuffering == true)) {
		now_date = new Date();
		now_time = now_date.getTime();
		
		length_of_rebuffer = (now_time - va_tracking_rebuffering_time);
		
		// Throw out invalid rebuffers thrown by scrubbing
		if (length_of_rebuffer > 10) {
			va_log_qos('BUFF', (length_of_rebuffer/1000));
			logTrace("Spent " + (length_of_rebuffer/1000) + " seconds rebuffering at " + va_current_time);
		}		
		
		va_tracking_rebuffering = false;
		va_tracking_rebuffering_time = 0;		
		
	}
}

function va_state_listener(o) {
	if ((o.newstate == "PLAYING") && (va_state_time == 0)) {
		now_date = new Date();
		va_state_time = now_date.getTime();
		logTrace("STARTED COUNTDOWN:" + va_state_time);
	}
	if (o.newstate == "PAUSED") {
		va_state_haspaused = true;
		logTrace("PAUSED");
	}
	if ((o.newstate == "COMPLETED") && (va_state_haspaused == false)) {
		now_date = new Date();
		finished = now_date.getTime();
		length_to_play = (finished - va_state_time);
		
		va_log_qos('COMP', (length_to_play/1000));
		logTrace("TIME TO PLAY:" + (length_to_play/1000));
	}
}


function va_bitrate_listener(o) {
	now_date = new Date();
	
	if (va_bitrate_start_time == 0) {
		// First call for this item, set things up
		va_bitrate_start_time = now_date.getTime();
		va_bitrate_start_bytes = o.loaded;
	} else if (o.total == o.loaded) {
		// Done loading, crunch our numbers
		kbps = (((o.total * 8) / 1024) / ((now_date.getTime() - va_bitrate_start_time) / 1000));
		va_log_qos('INIT', parseInt(kbps));
		logTrace("LOADED AT " + parseInt(kbps) + "kbps");
	}
	
	
}

function va_time_listener(o) {
	// Track only once per second, at most
	if (Math.floor(o.position) != va_current_time) {
		va_current_time = Math.floor(o.position);
		// Track only as specified in logger settings, with a hack so "0" time is bumped up, to avoid another hit on rewind
		if (va_current_time%va_log_granularity == 0) {
			// Flag initial plays to send extra data to server
			if ((va_current_time == 0)) {
				if (va_logged_this_item == 0) {
					va_last_status = "TIME";
					va_log("TIME", va_current_time);
					va_log_first(o);
				}
			} else {
				// Log the time
				va_last_status = "TIME";
				va_log("TIME", va_current_time);
			}
		}
	}
}

function va_seek_listener(o) {
	va_state_haspaused = true;
	logTrace("PAUSED");
	
	if (va_current_time > o.position) {
		va_last_status = "REW";
		va_log("REW", va_current_time);
	} else if (va_current_time < o.position) {
		va_last_status = "FFWD";
		va_log("FFWD", va_current_time);
	}
}

function va_fullscreen_listener(o) {
	if(o.fullscreen) {
		va_last_status = "FULL";
		va_log("FULL", va_current_time);
	}
}

function va_log_first(o) {
	now_date = new Date();
	now_time = now_date.getTime();
	
	var ls = "/s/?";
	ls += "session=" + va_user_session;
	ls += "&item=" + va_current_item;
	ls += "&client=" + o['client'];
	ls += "&player=" + o['version'];
	ls += "&purl=" + escape(location.href);
	ls += "&ptitle=" + document.title;
	ls += "&vurl=" + escape(va_current_item_url);
	ls += "&rdm=" + now_time;
	
	report = new Image(); 
	report.src = va_log_server + ls;
	
	va_logged_this_item = 1;

	logTrace(ls);
	
	// Google Analytics hack for now
	if (pageTracker) {
		var google_url = va_current_item_url;
		google_url = google_url.replace("http://biolaedu.web.aplus.net/", "");
		google_url = google_url.replace("http://video1.biola.edu.simplecdn.net/", "video/");
		google_url = google_url.replace("http://www.biola.edu/media/video/cdn/", "video/");
		google_source = "/start_stream/" + google_url;
		pageTracker._trackPageview(google_source);
	}
}

function va_log(state, position) {
	now_date = new Date();
	now_time = now_date.getTime();
	
	var ls = "/d/?";
	ls += "session=" + va_user_session;
	ls += "&item=" + va_current_item;
	ls += "&state=" + state;
	ls += "&pos=" + position;
	ls += "&detail=" + va_log_granularity;
	ls += "&rdm=" + now_time;
	
	report = new Image(); 
	report.src = va_log_server + ls;
	
	logTrace(ls);
}

function va_log_qos(state, num) {
	now_date = new Date();
	now_time = now_date.getTime();
	
	var ls = "/q/?";
	ls += "session=" + va_user_session;
	ls += "&item=" + va_current_item;
	ls += "&state=" + state;
	if (va_current_time	>= 0) {
		ls += "&pos=" + va_current_time;
	} else {
		ls += "&pos=0";
	}
	if (state == 'INIT') {
		ls += "&kbps=" + num;
		ls += "&time=0";
	} else if (state == 'BUFF') {
		ls += "&time=" + num;
		ls += "&kbps=0";
	} else if (state == 'COMP') {
		ls += "&time=" + num;
		ls += "&kbps=0";
	}
	ls += "&vurl=" + escape(va_current_item_url);
	ls += "&rdm=" + now_time;

	report = new Image(); 
	report.src = va_log_server + ls;

	logTrace(ls);
}



// GENERAL FUNCTIONS
function gid(name) {
	return document.getElementById(name);
}

function thisMovie(movieName) {
	return document.getElementById(movieName);
	/*
	if(navigator.appName.indexOf("Microsoft") != -1) {
		return window[movieName];
	} else {
		return document[movieName];
	}
	*/
};


// DEBUGGING FUNCTIONS FOR NOW
function printTrace(str) {
	if (va_debug == true) {
		var itm = gid('tracecode');
		var txt = itm.innerHTML + str + '\n';
		itm.innerHTML = txt;
		itm.scrollTop = itm.scrollHeight;
	}

};

function logTrace(str) {
	if (va_debug == true) {
		var itm = gid('tracecode');
		var txt = itm.innerHTML + "LOG..." + str + '\n';
		itm.innerHTML = txt;
		itm.scrollTop = itm.scrollHeight;
	}

};