var helpIsHidden = false;

var currentVideo = null;
var seekStart = 0;

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

/* 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;

var maxAnchorTime = 0;

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 > 512)
		level = 512;

	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);
	
	$('#currentPositionLabel').html(timeAtPosition(0));

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

	video_zoom_busy = false;
}

var newActiveMarker_Res = null;

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

	if (!flashConnectorAvailable)
	{
		newActiveMarker_Res = newActiveMarker;

		setTimeout('scrollToTime(' + parseInt(seconds) + ', ' + (flashUpdate ? 'true' : 'false') + ', newActiveMarker_Res);', 100);

		return;
	}

	var pixels = secondsToPixels(seconds-videoStart);

	repositionActiveUnsetMarker();

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

	//if (!playerModeCorrect)
	//if (!isDragging)

	var getMarkerAtPos = true;

	if (playerModeCorrect && isDragging)
	{
		getMarkerAtPos = false;
	}

	if (flashUpdate && playerModeCorrect)
	{
		getMarkerAtPos = false;
	}

	if (getMarkerAtPos)
	{
		if (!newActiveMarker)
		{
			newActiveMarker = getMarkerAtSeconds(seconds);
		}

		if (!newActiveMarker && activeMarker && activeMarker.isNewAnchor)
		{
			// we're keeping the current (new) marker
		}
		else
		{		
			if (newActiveMarker && !newActiveMarker.isMarked)
			{
				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);

						$('#video_download_link').attr('href', videoInfo.URL).fadeIn();

						var flashConnector = isInternetExplorer ? document.all.videoplayer : document.videoplayer;
						flashConnector.movieLoad(videoInfo.URL, seekStart);
						flashConnector.movieShowPlayButton();
					}
					catch(e)
					{
						alert('cannot call movieLoad: ' + e);
					}
				}
			}
		);
	}
}

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

function marker_correct(dontShowAlert)
{
	if (!activeMarker)
	{
		return;
	}

	playerModeCorrect = true;

	if (!dontShowAlert)
	{
		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.');
	}

	activeMarker.element.show();

	$('#altermarker_save').removeClass('newanchor');

	if (activeMarker.isNewAnchor)
	{
		$('#altermarker_save').addClass('newanchor');
	}

	$('#altermarker_incorrect_loading').hide();
	$('#altermarker_incorrect_loading').css('opacity', 0.5);
	$('#altermarker_incorrect').css('opacity', activeMarker.isMarked ? 1 : 0.25).show();

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

function marker_correct_cancel()
{
	if (activeMarker && activeMarker.isNewAnchor)
	{
		activeMarker.element.hide();
	}

	playerModeCorrect = false;

	$('#altermarker_info').hide();
	$('#altermarker_correct').show();
	$('#altermarker_incorrect').hide();
	$('#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);

		var okay = activeMarker.isNewAnchor;

		if (!okay)
		{
			okay = confirm('Weet je zeker dat je het ankerpunt wilt verplaatsen naar ' + time);
		}

		if (okay)
		{
			if (activeMarker && activeMarker.isNewAnchor)
			{
				activeMarker.element.hide();
			}

			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_info').hide();
					$('#altermarker_correct').show();
					$('#altermarker_save').hide();
					$('#altermarker_cancel').hide();
					*/

					if (result == 'false')
					{
						if (message)
						{
							alert(message);
						}
					}
					else
					{
						activeMarker.isNewAnchor = false;
						activeMarker.time = time;
						activeMarker.element.removeClass('notset');
						activeMarker.element.removeClass('invalid');
						activeMarker.element.css('opacity', 1);
						activeMarker.element.show();

						if (activeMarker.isMarked)
						{
							activeMarker.element.addClass('invalid');
						}

						$('#timeline div.marker[ID=' + activeMarker.ID + ']').each(
							function()
							{
								$(this).removeClass('notset');
								$(this).attr('time', time);
							}
						);

						parseMarkers(true);

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

function setActiveMarker_Navigate(direction)
{
	if (!activeMarker)
	{
		return false;
	}

	var markerNumber = 1;
	var cnt = 0;

	$(markerList).each(
		function (i)
		{
			if (markerList[i].ID == activeMarker.ID)
			{
				markerNumber = cnt;
			}

			cnt++;
		}
	);

	markerNumber += direction;

	if (markerNumber < 0)
	{
		markerNumber = 0;
	}
	else if (markerNumber >= markerList.length)
	{
		markerNumber = markerList.length-1;
	}

	setActiveMarker(markerList[markerNumber]);
}

function repositionActiveUnsetMarker()
{
	if (!activeMarker)
	{
		return;
	}

	if (activeMarker.isNewAnchor)
	{
		var seconds = video_lastStamp;
		var pixels = secondsToPixels(seconds-videoStart);

		var markerElementWidth = parseInt( activeMarker.element.css('width') );

		activeMarker.element.css('left', pixels - (markerElementWidth/2));
	}
}

var shareURLBase = null;

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

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

		if (activeMarker.isNewAnchor)
		{
			activeMarker.element.hide();
		}

		activeMarker = null;
	}

	var markerNumber = 1;
	var cnt = 0;

	$(markerList).each(
		function (i)
		{
			cnt++;

			if (markerList[i] == marker)
			{
				markerNumber = cnt;
			}
		}
	);
	
	marker.element.removeClass('invalid');

	if (marker.isMarked)
	{
		marker.element.addClass('invalid');
	}

	/*
	$('#altermarker_info_count').html(markerNumber + ' / ' + markerList.length);
	*/
	
	$('#altermarker_info_count').html(marker.ID);

	$('#altermarker_incorrect').css('opacity', marker.isMarked ? 0.75 : 0.25);

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

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

		$('#altermarker_info_politician').html(marker.politician);
	}

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

	if (!playerModeCorrect)
	{
		$('#altermarker_correct').hide();
		$('#altermarker_save').hide();
		$('#altermarker_cancel').hide();
	}

	if (marker)
	{
		if (shareURLBase)
		{
			var url, newURL = shareURLBase + marker.ID + '%2F';

			url = $('#sharelink_email').attr('href').replace(/body=(.+?)$/, 'body=' + newURL);
			$('#sharelink_email').attr('href', url);

			url = $('#sharelink_digg').attr('href').replace(/url=(.+?)&title/, 'url=' + newURL + '&title');
			$('#sharelink_digg').attr('href', url);

			url = $('#sharelink_delicious').attr('href').replace(/url=(.+?)&title/, 'url=' + newURL + '&title');
			$('#sharelink_delicious').attr('href', url);

			url = $('#sharelink_facebook').attr('href').replace(/u=(.+?)&t/, 'u=' + newURL + '&t');
			$('#sharelink_facebook').attr('href', url);

			url = $('#sharelink_myspace').attr('href').replace(/u=(.+?)&t/, 'u=' + newURL + '&t');
			$('#sharelink_myspace').attr('href', url);
		}

		if (marker.isNewAnchor)
		{
			$('#altermarker_correct').addClass('newanchor');
			$('#altermarker_correct').html('Plaats ankerpunt!');
		}
		else
		{
			$('#altermarker_correct').removeClass('newanchor');
			$('#altermarker_correct').html('Corrigeer ankerpunt!');
		}

		if (playerModeCorrect)
		{
			marker.element.show();
		}

		/*
		var markerParent = marker.parent();
		marker.remove();
		markerParent.addChild(marker);
		*/

		if (!playerModeCorrect)
		{
			$('#altermarker_correct').show();
		}

		marker.element.addClass('active');

		activeMarker = marker;

		repositionActiveUnsetMarker();

		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)
					{
						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 seconds = Math.round(secondsI);

	//var lastMarker = null;
	foundMarker = null;

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

			if (this.time > 0 && seconds >= this.time)
			{
				foundMarker = this;
			}
		}
	);

	return foundMarker;
}

function getMarkerByID(ID)
{
	var foundMarker = null;

	jQuery.each(
		markerList,
		function (i, marker)
		{
			if (this.ID == ID)
			{
				foundMarker = this;
			}
		}
	);

	return foundMarker;
}

var getMarkerByElement_result = null;

function getMarkerByElement(element)
{
	getMarkerByElement_result = null;

	jQuery.each(
		markerList,
		function (i, marker)
		{
			if (this.element.attr('id') == element.attr('id'))
			{
				getMarkerByElement_result = this;
			}
		}
	);

	return getMarkerByElement_result;
}

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/10;

		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 >= 24)
		hours -= 24;

	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)
{
	timeString = new String(timeString);
	var hours = timeString.substr(0, 2);
	var minutes = timeString.substr(3, 2);
	var seconds = timeString.substr(6, 2);

	hours = parseFloat(hours);
	minutes = parseFloat(minutes);
	seconds = parseFloat(seconds);

	hours *= 60*60;
	minutes *= 60;

	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;
	var newActiveMarker = null;
	var newAnchors = 0;
	var lastAnchorTime = 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()
						{
							var time = $(this).attr('time');

							if (!time)
							{
								time = 0;
							}

							$(this).mouseout();

							scrollToTime(timeStringToSeconds(time), false, getMarkerByElement($(this)));
						}
					);
			}

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

			if (!time)
			{
				time = 0;
			}

			if (time > maxAnchorTime)
			{
				maxAnchorTime = time;
			}

			var markerInfo = new Object();
			markerInfo.ID = marker.attr('ID');
			markerInfo.isMarked = marker.attr('isMarked') == 1 ? true : false;
			markerInfo.politician = marker.attr('politician');
			markerInfo.time = time;
			markerInfo.element = marker;
			markerInfo.isNewAnchor = false;

			if (!markerInfo.time)
			{
				markerInfo.isNewAnchor = true;
			}

			if (markerInfo.isMarked)
			{
				markerInfo.element.addClass('invalid');
			}

			if (markerInfo.isNewAnchor || markerInfo.element.hasClass('notset'))
			{
				markerInfo.element.addClass('notset');
				markerInfo.element.hide();
				/*
				if (!newAnchors && lastAnchorTime > 0)
				{
					markerInfo.element.addClass('notset');
					markerInfo.element.hide();
					//markerInfo.time = lastAnchorTime + 20;
					//markerInfo.element.attr('time', secondsToTimestring(markerInfo.time));
				}
				else
				{
					//markerInfo.element.hide();
				}*/

				newAnchors++;
			}
			else
			{
				newAnchors = 0;
				lastAnchorTime = time;
			}

			markerList.push(markerInfo);

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

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

				if (markerInfo.isNewAnchor)
				{
					if (maxAnchorTime)
					{
						playTime = maxAnchorTime + autoIncrementTimeForNewAnchors;
					}

					newActiveMarker = markerInfo;
				}
			}
		}
	);

	if (playTime && !dontScrollToTime)
	{
		scrollToTime(playTime, false, newActiveMarker);
	}

	if (newActiveMarker && !dontScrollToTime)
		setActiveMarker(newActiveMarker);

	if (newActiveMarker && newActiveMarker.element.attr('autoplay') && newActiveMarker.isNewAnchor)
	{
		marker_correct(true);
	}
}

$(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;
	}
);

function glowUnsetAnchors()
{
	if (activeMarker)
	{
				var marker = activeMarker;

				if (marker.isNewAnchor && marker.element && marker.element.css('visibility') != 'none')
				{
					var o = marker.element.css('opacity');

					if (o == 1)
					{
						o = 0.5;
					}
					else
					{
						o = 1;
					}

					marker.element.css('opacity', o);
				}
	}

		/*
	if (markerList)
	{
		$(markerList).each(
			function(i)
			{
				var marker = markerList[i];	

				if (marker.isNewAnchor && marker.element && marker.element.css('visibility') != 'none')
				{
					var o = marker.element.css('opacity');

					if (o == 1)
					{
						o = 0.5;
					}
					else
					{
						o = 1;
					}

					marker.element.css('opacity', o);
				}
			}
		);
	}
		*/

	setTimeout('glowUnsetAnchors();', 333);
}

$(document).ready(
	function()
	{
			glowUnsetAnchors();

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

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

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

					isDragging = true;

					return false;
				}
			);

			$('img.player_help').click(
				function ()
				{
					$(this).fadeOut();
				}
			);

			$('#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);
				}
			);

			var table = $('<table width="100%" height="100%"><tr valign="middle" align="center"><td><table width="700" height="628" cellpadding="0" cellspacing="0" background="/images/discussion_frame.png"><tr><td align="left" valign="top"><div class="discussion_content"><div id="discussion_header">Discussie: dsgdsgdsg dsgsdg</div><div id="discussion_text">Tekster de tekst</div><div class="discussion_footer"><div id="discussion_comment_label">Jouw opmerking</div><textarea id="discussion_input"></textarea><div id="discussion_comment" title="Plaats je opmerking...">Plaats commentaar</div></div><div id="discussion_close">[x]</div></div></td></tr></table></td></tr></table>');
			
			$(table).appendTo($('#discussion'));

			$('#altermarker_discussion').click(
				function ()
				{
					discussion_open($('#current_debate').attr('debateID'));
				}
			);

			$('#altermarker_debatedetails a').click(
				function ()
				{
					window.open($(this).attr('href'));

					return false;
				}
			);

			$('#discussion_close').click(
				function ()
				{
					discussion_close();
				}
			);

			$('#discussion_comment').click(
				function ()
				{
					discussion_send_comment();
				}
			);

			$('#altermarker_nav_prev').click(
				function ()
				{
					setActiveMarker_Navigate(-1);
				}
			);

			$('#altermarker_nav_next').click(
				function ()
				{
					setActiveMarker_Navigate(+1);
				}
			);

			$('#altermarker_incorrect').mouseover(
				function ()
				{
					$(this).css('opacity', 1);
				}
			);

			$('#altermarker_incorrect').mousedown(
				function ()
				{
					$(this).hide();
					$('#altermarker_incorrect_loading').show();
					$(this).css('opacity', 0.5);

					jQuery.get(
						'/api/anchor/' + activeMarker.ID + '/marktoggle/',
						null,
						function(response)
						{
							var xml = $(response);
							var result = xml.find('result').text();
							var ID = xml.find('ID').text();
							var isMarked = xml.find('isMarked').text() == '1';
							var message = xml.find('message').text();

							if (result)
							{
								var marker = getMarkerByID(ID);
								marker.isMarked = isMarked;

								marker.element.removeClass('invalid');
								
								if (marker.isMarked)
								{
									marker.element.addClass('invalid');
								}

								if (marker == activeMarker)
								{
									$('#altermarker_incorrect').css('opacity', marker.isMarked ? 0.75 : 0.25);
								}
							}
							else
							{
								alert(message);
							}

							$('#altermarker_incorrect').show();
							$('#altermarker_incorrect_loading').hide();
						}
					);

				}
			);

			$('#altermarker_incorrect').mouseup(
				function ()
				{
					$(this).css('opacity', 1);
				}
			);

			$('#altermarker_incorrect').mouseout(
				function ()
				{
					$(this).css('opacity', activeMarker.isMarked ? 0.75 : 0.25);
				}
			);

			$('#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;
					
						if (Math.abs(newX) >= 1 && !helpIsHidden)
						{
							helpIsHidden = true;
							$('img.player_help').fadeOut();
						}

						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;
					}
				}
			);
	}
);

var discussion_debateID = null;
var discussion_sending_comment = false;

function discussion_open(debateID)
{
	discussion_debateID = debateID;

	var debateTitle = $('#debate_title').html();
	debateTitle = debateTitle.replace(/Video:/, 'Discussie:');
	$('#discussion_header').html(debateTitle);
	$('#discussion_text').html("<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><center><img src='/images/anchor_edit_invalid_loading.gif' /></center>");
	$('#disabler').css('opacity', 0).show().fadeTo(500, 0.75,
		function()
		{
			$('#discussion').show();
			$('#discussion_text').load(
				"/discussie/" + discussion_debateID + "/",
				null,
				function()
				{
					$("#discussion_text").attr({ scrollTop: $("#discussion_text").attr("scrollHeight") });
				}
			);
		}
	);
}

function discussion_send_comment()
{
	if (discussion_sending_comment)
	{
		return;
	}
	
	$('#discussion_input').attr('disabled', true);
	$('#discussion_input').addClass('disabled');

	discussion_sending_comment = true;

	jQuery.post(
		'/discussie/' + discussion_debateID + '/comment/',
		{ comment: $('#discussion_input').val() },
		function(response)
		{
			var xml = $(response);
			var result = xml.find('result').text();
			var message = xml.find('message').text();

			discussion_sending_comment = false;

			$('#discussion_input').attr('disabled', '');
			$('#discussion_input').removeClass('disabled');
			
			if (result)
			{
				$('#discussion_input').val('');
				$('#discussion_text').load("/discussie/" + discussion_debateID + "/");
			}
			else
			{
				alert(message);
			}
		}
	);
}

function discussion_close()
{
	$('#discussion').hide();	
	$('#disabler').fadeTo(500, 0, function() { $('#disabler').hide(); } );
}


