/* Logger for flowplayer events */

$f.addPlugin("logger", function(){

	// "this" is the Player object
	var self = this;
	self.onStart(function(clip)
	{
		var duration = clip.duration || 0;	// Get clip duration

		duration *= 1000; 					// Convert to ms
		var time = 0;
		var cuepoints = [];
		var logId = 0;

		// Synchronous request to get the logging id for this view 
		$.ajax({
		    type: 'GET',
		    url: '/video/logId/videoUrl/' + encodeURIComponent(encodeURIComponent(clip.completeUrl)),
		    dataType: 'json',
		    success: function(json)
		    {
				logId = json.id;
		    },
		    data: {},
		    async: false
		});
		
		// Only add cuepoints if the video doesn't have any already. This stops
		// another set of cuepoints being added when a video is played again. 
		if(clip.cuepoints.length == 0)
		{
			// Create array of cuepoint times
			while(time < (duration - 12000))
			{
				cuepoints.push(time);
				time += (30 * 1000);
			}
			
			// Add a curepoint 10s from the end of the clip as a "complete" marker 
			if(duration > 10000)
			{
				cuepoints.push(duration - 10000);
			}
	
			// Setup cuepoints. Perform AJAX on each cuepoint with the video id and current position
			clip.onCuepoint(cuepoints, 	function(clip, cuepoint)
			{
				var time = cuepoint/1000;		// Convert time to seconds
				$.get('/video/updateLog/id/' + logId + '/duration/' + time);
			});
		}
	});

	return this;

});
