
var currentVideo = null;
var seekStart = 0;

var isDragging = false;
var startX = 0;
var startMouseX = 0;
var sliderWidth = 72;
var sliderWidth2 = sliderWidth/2;

/* FLASH CONNECTOR */

var isInternetExplorer = navigator.appName.indexOf("Microsoft") != -1;

var flashConnectorAvailable = false;

var flashConnector_info_party = -1;
var flashConnector_info_politician = -1;

var videoIsPlaying = false;
var gotFirstOffset = false;

function movieOnStateChange(object, state, offsetSeconds)
{
	if (state == "FLASH_INITIALISED")
	{
		flashConnectorAvailable = true;
	}
	else if (state == "CONNECTING")
	{
		videoIsPlaying = false;
		gotFirstOffset = false;
	}
	else if (state == "BUFFERING")
	{
	}
	else if (state == "BUFFER_FULL")
	{
		try
		{
			gotFirstOffset = false;

			if (videoIsPlaying)
			{
				var flashConnector = isInternetExplorer ? document.all.videoplayer : document.videoplayer;
				flashConnector.movieStart();
			}
		}
		catch(e)
		{
			alert('cannot call movieStart: ' + e);
		}
	}
	else if (state == "PLAYING")
	{
		videoIsPlaying = true;
	}
	else if (state == "PAUSED")
	{
		videoIsPlaying = false;
	}
	else if (state == "TIMEOFFSET")
	{
		videoIsPlaying = true;

		// offsetSeconds can be smaller (when loading keyframes for example)
		if (offsetSeconds > 0 && gotFirstOffset)
		{
			/*
			$('#debug_1').html(
				offsetSeconds+' seekStart = '+
				(offsetSeconds-seekStart)
				+'\n'+$('#debug_1').html()
			);
			*/

			if (offsetSeconds-seekStart >= currentVideo.duration)
			{
				scrollToTime(currentVideo.startTime + currentVideo.duration, false);
			}
			else
				scrollToTime((offsetSeconds-seekStart) + currentVideo.startTime, true);
	
			if (!isDragging)
				$('#currentPositionLabel').html(timeAtPosition(0));
		}

		gotFirstOffset = true;
	}
	else
		alert(state);

	if (videoIsPlaying)
		flashConnector_sendInfo();
}

function flashConnector_sendInfo()
{
	if (flashConnector_info_politician != -1 || flashConnector_info_party != -1)
	{
		try
		{
			var flashConnector = isInternetExplorer ? document.all.videoplayer : document.videoplayer;
			flashConnector.movieSetInfo(flashConnector_info_party, flashConnector_info_politician);
		}
		catch(e)
		{
			alert('cannot call movieSetInfo: ' + e);
		}	

		flashConnector_info_party = -1;
		flashConnector_info_politician = -1;
	}
}



/* JS ONLY */

var video_zoom_scale = 1;

function secondsToPixels(seconds)
{
	return Math.floor(seconds)/video_zoom_scale;
}

function pixelsToSeconds(pixels)
{
	return video_zoom_scale*pixels;
}

var video_lastStamp = null;
var video_zoom_busy = false;

function video_zoom(s)
{
	if (video_zoom_busy)
		return;

	video_zoom_busy = true;
	
	var oldSeconds = pixelsToSeconds(-scrollPosition) + pixelsToSeconds(256) + videoStart;

	var level = video_zoom_scale;

	if (s > 0)
	{
		level /= 2;
	}
	else
	{
		level *= 2;
	}

	if (level < 0.125)
		level = 0.125;
	else if (level > 64)
		level = 64;

	video_zoom_scale = level;

	parseVideos();
	parseMarkers(true);

	scrollLastTick = -1;
	scrollPosition = secondsToPixels(videoStart-(video_lastStamp == null ? videoStart : video_lastStamp))+256;
	scrollInterval(true);

	scrollToTime(video_lastStamp == null ? videoStart : video_lastStamp, true);

	$('#video_zoom_in').show();
	$('#video_zoom_out').show();

	video_zoom_busy = false;
}

function scrollToTime(seconds, flashUpdate)
{
	video_lastStamp = seconds;

	if (!flashConnectorAvailable)
	{
		setTimeout('scrollToTime(' + parseInt(seconds) + ', ' + (flashUpdate ? 'true' : 'false') + ');', 100);

		return;
	}

	var pixels = secondsToPixels(seconds-videoStart);

	if (!isDragging)
		$('#currentPosition').css('left', Math.round(pixels-sliderWidth2) + 'px');

	if (!playerModeCorrect)
	{
		var newActiveMarker = getMarkerAtSeconds(seconds);
		setActiveMarker(newActiveMarker);
	}

	scrollTo(pixels);

	if (!flashUpdate)
	{
		jQuery.each(
			videoList,
			function ()
			{
				var videoInfo = this;

				if (seconds >= videoInfo.startTime && seconds < videoInfo.startTime + videoInfo.duration)
				{
					try
					{
						currentVideo = videoInfo;

						seekStart = Math.floor(seconds-currentVideo.startTime);

						var flashConnector = isInternetExplorer ? document.all.videoplayer : document.videoplayer;
						//flashConnector.movieLoad("http://www.openkamer.tv/video/20/10:15:00/", seekStart);
						//flashConnector.movieLoad("/video/" + videoInfo.ID + "/" + secondsToTimestring(videoInfo.startTime) + "/", seekStart);
						flashConnector.movieLoad(videoInfo.URL, seekStart);
					}
					catch(e)
					{
						alert('cannot call movieLoad: ' + e);
					}
				}
			}
		);
	}
}

var activeMarker = null;
var infoTiming = new Array();
var playerModeCorrect = false;

function marker_correct()
{
	playerModeCorrect = true;

	alert('Let op: je kunt nu het ankerpunt verplaatsen.\n\nGa opzoek naar het juiste moment in de video.\n\nDruk op opslaan om de wijziging definitief te maken of annuleren om de wijziging ongedaan te maken.');

	$('#altermarker_correct').hide();
	$('#altermarker_save').show();
	$('#altermarker_cancel').show();
}

function marker_correct_cancel()
{
	playerModeCorrect = false;

	$('#altermarker_correct').show();
	$('#altermarker_save').hide();
	$('#altermarker_cancel').hide();
}

function marker_correct_save()
{
	if (activeMarker && activeMarker.ID)
	{
		try
		{
			var flashConnector = isInternetExplorer ? document.all.videoplayer : document.videoplayer;

			if (videoIsPlaying && flashConnector)
			{
				flashConnector.moviePause();
			}
		}
		catch(e)
		{
			alert('cannot call moviePause: ' + e);
		}

		var time = timeAtPosition(0);

		if (confirm('Weet je zeker dat je het ankerpunt wilt verplaatsen naar ' + time))
		{
			jQuery.get(
				'/api/anchor/' + activeMarker.ID + '/correct/' + time,
				null,
				function(response)
				{
					var xml = $(response);
					var result = xml.find('result').text();
					var newTime = xml.find('newTime').text();
					var message = xml.find('message').text();

					playerModeCorrect = false;

					$('#altermarker_correct').show();
					$('#altermarker_save').hide();
					$('#altermarker_cancel').hide();

					if (result == 'false')
					{
						if (message)
							alert(message);
					}
					else
					{
						$('#timeline div.marker[ID=' + activeMarker.ID + ']').each(
							function()
							{
								$(this).attr('time', time);
							}
						);

						parseMarkers();

						scrollToTime(timeStringToSeconds(newTime), true);
					}
				}
			);
		}
	}
}

function setActiveMarker(marker)
{
	if (activeMarker == marker)
		return;

	if (activeMarker)
	{
		activeMarker.element.removeClass('active');

		activeMarker = null;
	}

	$('#recent_options li.anchors ul li.active').removeClass('active');

	if (marker && marker.ID)
		$('#recent_options li.anchors ul li[anchorID=' + marker.ID + ']').addClass('active');

	$('#anchor_info').html('');

	$('#altermarker_correct').hide();
	$('#altermarker_save').hide();
	$('#altermarker_cancel').hide();

	if (marker)
	{
		$('#altermarker_correct').show();

		marker.element.addClass('active');

		activeMarker = marker;

		var queryString = new String(document.location);
		queryString = queryString.substring(queryString.indexOf('?'), queryString.length);

		jQuery.get(
			'/api/anchor/' + activeMarker.ID + '/' + queryString,
			null,
			function(response)
			{
				var xml = $(response);
				var anchor = xml.find('anchor');

				$('#anchor_info').html(anchor.find('text').text());

				var flashConnector = isInternetExplorer ? document.all.videoplayer : document.videoplayer;
				var party = anchor.find('party').text();
				var politician = anchor.find('politician').text();

				try
				{
					if (party || politician)
					{
						// hier
						var date = new Date();
						var tick = Math.round(date.getTime()/1000);
						var diff = -1;
						var showInfo = true;

						jQuery.each(
							infoTiming,
							function (i)
							{
								if (this.politician == politician)
								{
									diff = tick-this.tick;
									
									if (diff >= 60)
									{
										this.tick = tick;
									}
									else
									{
										showInfo = false;
									}
								}
							}
						);

						if (diff == -1)
						{
							var o = new Object();
							o.politician = politician;
							o.tick = tick;
							infoTiming.push(o);
						}

						if (showInfo)
						{
							flashConnector_info_party = party;
							flashConnector_info_politician = politician;
						}
					}
					else
					{
						// Remove the overlay
						flashConnector_info_party = '';
						flashConnector_info_politician = '';
					}
				}
				catch(e)
				{
					alert('cannot call movieSetInfo: ' + e);
				}
			},
			'xml'
		);
	}
}

var foundMarker = null;

function getMarkerAtSeconds(secondsI)
{
	var seconds = Math.round(secondsI+0.5);

	var lastMarker = null;
	foundMarker = null;

	jQuery.each(
		markerList,
		function (i, marker)
		{
			if (foundMarker == null && this.time >= seconds)
			{
				foundMarker = lastMarker;
			}
			else
				lastMarker = this;
		}
	);

	return foundMarker;
}

function scrollTo(position)
{
	var w = 512;
	var w2 = w/2;

	var offset = w2 - position;

	scrollTargetPosition = offset;

	if (scrollIntervalID == null)
	{
		scrollLastTick = -1;
		scrollIntervalID = setInterval('scrollInterval()', 1000/30);
	}

}

var scrollTargetPosition = 0;
var scrollPosition = 0;
var scrollDate = new Date();
var scrollLastTick = -1;//scrollDate.getTime();
var scrollIntervalID = null;

function scrollInterval(forceUpdate)
{
	var scrollDate = new Date();
	var scrollTick = scrollDate.getTime();

	if (scrollLastTick == -1)
		scrollLastTick = scrollTick;

	if (!isDragging && (forceUpdate || scrollTargetPosition != scrollPosition))
	{
		var timeDiff = 1000 / parseFloat(scrollTick - scrollLastTick);

		var diff = scrollTargetPosition-scrollPosition;
		diff /= timeDiff/5;

		scrollPosition += diff;

		$('#timeline').css('left', Math.round(scrollPosition) + 'px');

		if (Math.round(scrollTargetPosition) == Math.round(scrollPosition))
		{
			scrollPosition = scrollTargetPosition;

			clearInterval(scrollIntervalID);

			scrollIntervalID = null;
		}
		
		$('#currentPositionLabel').html(timeAtPosition(0));
	}

	scrollLastTick = scrollTick;
}

function timeAtPosition(timeOffset)
{
	var seconds = pixelsToSeconds(timeOffset-scrollTargetPosition+256);
	seconds = Math.round(seconds);
	seconds += videoStart;

	return secondsToTimestring(seconds);
}

function secondsToTimestring(seconds)
{
	if (seconds < 0)
		seconds = 0;

	var hours = Math.floor(seconds / (60*60));
	seconds -= hours*60*60;
	var minutes = Math.floor(seconds / 60);
	seconds -= minutes*60;

	if (hours < 10)
		hours = '0'+hours;

	if (minutes < 10)
		minutes = '0'+minutes;

	if (seconds < 10)
		seconds = '0'+seconds;

	return hours + ':' + minutes + ':' + seconds;
}

function timeStringToSeconds(timeString)
{
	var hours = parseInt(timeString.substr(0, 2))*60*60;
	var minutes = parseInt(timeString.substr(3, 2))*60;
	var seconds = parseInt(timeString.substr(6, 2));

	return seconds + minutes + hours;
}

var videoList = null;
var videoStart = -1;
var videoEnd = -1;
var markerList = null;

function parseVideos()
{
	videoList = new Array();
	videoStart = -1;
	videoEnd = -1;

	$('#timeline div.block').each(
		function ()
		{
			var video = $(this);
			var startTime = timeStringToSeconds(video.attr('time'));
			var duration = timeStringToSeconds(video.attr('duration'));

			var videoInfo = new Object();
			videoInfo.ID = video.attr('videoID');
			videoInfo.URL = video.attr('videoURL');
			videoInfo.startTime = startTime;
			videoInfo.duration = duration;
			videoInfo.endTime = startTime+duration;

			videoList.push(videoInfo);

			if (startTime < videoStart || videoStart == -1)
				videoStart = startTime;

			if (videoInfo.endTime > videoEnd)
				videoEnd = videoInfo.endTime;

			video.css('width', secondsToPixels(videoInfo.duration));
		}
	);

	if (videoStart >= 0)
	{
		$('#currentPosition').show();
	}

	updateTimeIndication();
}

function updateTimeIndication()
{
	$('#timeindication').empty();

	var timeFrame = videoEnd-videoStart;
	var viewWidth = 512;
	var minItemsPerView = 3;
	var minSpacing = Math.floor(viewWidth/minItemsPerView);

	var scale = video_zoom_scale;

	var currentSpacing = pixelsToSeconds(scale);

	var i = 0;

	while(i++ <= 150 && currentSpacing < pixelsToSeconds(minSpacing))
	{
		scale += pixelsToSeconds(scale);

		currentSpacing = pixelsToSeconds(scale);
	}

	if (currentSpacing > 60)
	{
		currentSpacing /= 60;
		currentSpacing = Math.floor(currentSpacing)*60;
	}
	else if (currentSpacing > 30)
	{
		currentSpacing /= 30;
		currentSpacing = Math.floor(currentSpacing)*30;
	}
	else if (currentSpacing > 15)
	{
		currentSpacing /= 15;
		currentSpacing = Math.floor(currentSpacing)*15;
	}
	else
	{
		currentSpacing = Math.floor(currentSpacing);
	}

	if (secondsToPixels(currentSpacing) >= 150)
		currentSpacing = pixelsToSeconds(150);

	var count = Math.ceil(timeFrame/currentSpacing);
	var time = videoStart;

	if (count < 3)
		count = 3;

	for(var i=0; i<count; i++)
	{
		var div = $(document.createElement('div'));
		div.html(secondsToTimestring(time));
		div.css('left', secondsToPixels(time-videoStart));
		div.appendTo('#timeindication');

		div.mousedown(
			function()
			{
				return false;
			}
		);

		time += currentSpacing;
	}
}

function marker_showInfo(anchorElement, mouseX, markerY, time)
{
	var popupID = 'anchor_popup_' + anchorElement.attr('ID');
	var popup = document.getElementById(popupID);
	
	if (!popup)
	{
		popup = $(document.createElement('div'));
		
		var html = '';

		if (anchorElement.attr('politician'))
		{
			html += '<div class="politician">';
			html += anchorElement.attr('politician');

			if (anchorElement.attr('party'))
				html += '<div class="party">(' + anchorElement.attr('party') + ')</div>';
			
			html += '</div>';
		}

		if (anchorElement.attr('tags'))
			html += '<p class="tags">' + anchorElement.attr('tags') + '</p>';

		$(document.createElement('div'))
			.addClass('anchor_popup_header')
			.appendTo(popup);

		$(document.createElement('div'))
			.addClass('anchor_popup_content')
			.html(html)
			.appendTo(popup);

		$(document.createElement('div'))
			.addClass('anchor_popup_footer')
			.appendTo(popup);

		popup.attr('id', popupID);
		popup.appendTo(document.body);
		popup.addClass('anchor_popup');
	}
	else
		popup = $(popup);

	popup.show();
	popup.css('left', mouseX - (308/2));
	popup.css('top', markerY);
	
	anchorElement.mouseout(
		function ()
		{
			var popupID = 'anchor_popup_' + $(this).attr('ID');
			var popup = $('#'+popupID);
			popup.hide();
		}
	);
}

function parseMarkers(dontScrollToTime)
{
	markerList = new Array();

	var playTime = null;

	$('#timeline div.marker').each(
		function ()
		{
			var marker = $(this);

			if (marker.attr('eventAdded') != 1)
			{
				marker.attr('eventAdded', 1);

				marker
					.mouseover(
						function(e)
						{
							marker_showInfo(
								$(this),
								$(this).offset().left+8,
								$(this).offset().top+20,
								timeStringToSeconds($(this).attr('time'))
							);
						}
					)
					.click(
						function()
						{
							$(this).mouseout();

							scrollToTime(timeStringToSeconds($(this).attr('time')));
						}
					);
			}

			var time = timeStringToSeconds(marker.attr('time'));

			var markerInfo = new Object();
			markerInfo.ID = marker.attr('ID');
			markerInfo.time = time;
			markerInfo.element = marker;

			markerList.push(markerInfo);

			marker.css('left', secondsToPixels(markerInfo.time-videoStart)-7);

			if (marker.attr('autoplay') == 'true')
				playTime = markerInfo.time;
		}
	);

	if (playTime && !dontScrollToTime)
		scrollToTime(playTime);
}

$(window).unload(
	function ()
	{
		try
		{
			var flashConnector = isInternetExplorer ? document.all.videoplayer : document.videoplayer;

			if (videoIsPlaying && flashConnector)
			{
				flashConnector.moviePause();
			}
		}
		catch(e)
		{
			alert('cannot call moviePause: ' + e);
		}
			
		if (scrollIntervalID)
			clearInterval(scrollIntervalID);

		scrollIntervalID = null;
	}
);

$(document).ready(
	function()
	{
			$('#currentPosition').mousedown(
				function(e)
				{
					if (isDragging)
						return;

					$('#currentPosition').addClass('selected');
					$('#currentPosition').blur();

					startX = $('#currentPosition').position().left;
					startMouseX = e.pageX;

					isDragging = true;

					return false;
				}
			);

			$('#video_zoom_in').click(
				function ()
				{
					$('#video_zoom_in').hide();
					$('#video_zoom_out').hide();
					video_zoom(1);
				}
			);

			$('#video_zoom_out').click(
				function ()
				{
					$('#video_zoom_in').hide();
					$('#video_zoom_out').hide();
					video_zoom(-1);
				}
			);

			$('#altermarker_correct').click(
				function ()
				{
					marker_correct();
				}
			);

			$('#altermarker_save').click(
				function ()
				{
					marker_correct_save();
				}
			);

			$('#altermarker_cancel').click(
				function ()
				{
					marker_correct_cancel();
				}
			);

			$('#currentPosition').css('left', (-sliderWidth2) + 'px');
			scrollTo(0);

			parseVideos();
			parseMarkers();

			$(document).mousemove(
				function(e)
				{
					if (isDragging)
					{
						var newX = e.pageX - startMouseX;
						newX = (startX + newX);

						var padding = 0;

						if (newX+scrollPosition < padding)
							newX = -scrollPosition + padding;
						else if (newX+scrollPosition > 512-sliderWidth-padding)
							newX = -scrollPosition + 512-sliderWidth-padding;

						if (newX < -sliderWidth2)
							newX = -sliderWidth2;

						$('#currentPosition').css('left', newX + 'px');
		
						$('#currentPositionLabel').html(
							timeAtPosition(
								newX+scrollPosition+sliderWidth2-(512/2)
							)
						);

						return false;
					}
				}
			);

			$(document).mouseup(
				function(e)
				{
					if (isDragging)
					{
						$('#currentPosition').removeClass('selected');

						var p = $('#currentPosition').position().left+sliderWidth2;

						if (p < 0)
							p = 0;

						scrollToTime( pixelsToSeconds(p)+videoStart );

						isDragging = false;

						return false;
					}
				}
			);
	}
);

