/**
	CALLED BY SERIA FLASH AND SILVERLIGHT PLAYERS
*/
var debugState = "";
var realState = "";
var startedPlaying = false;

var playerIsReady = false;

function stateChange(state) {
	if (state == "playing" || state == "buffering") {
		setTimeout("startedPlaying = true", 1000);
	}
	realState = state;
	debugState += state + "\n";
	main.debug('stateChange(' + state + ')');
	if (state == 'loading' || state == 'seeking' || state == 'buffering' || state == 'opening' || state == 'rewinding') {
		main.player.onStateChanged('waiting');
	} else if (state == 'stopped' || state == 'disconnected') {
		main.player.onStateChanged('stopped');
	} else if (state == 'paused') {
		main.player.onStateChanged('paused');
	} else if (state == 'playing') {
		main.player.onStateChanged('playing');
	} else {
		alert('state: ' + state);
	}
}
/**	CALLED BY SERIA FLASH AND SILVERLIGHT PLAYERS */
function videoCompleted()
{
	main.debug('videoCompleted()');

	main.player.onStateChanged('ended');
	if(main.onVideoCompleted)
		main.onVideoCompleted();
}


function _w(word) {
	var hash = createHash(word);
	if (main.language[hash])
		return main.language[hash][main.currentLanguage];
	else return "";
}

function createHash(word) {
	var length = word.length;
	var zigma = 0;
	for (var i = 0; i < length; i++) {
		zigma += word.charCodeAt(i) + (i * word.charCodeAt(i));
	}
	return 'h' + zigma;
}

var www = "";
var qqq = "";
function OnDSPlayStateChangeEvt(state)
{
www += state + " -- " + main.player.status() + " -- " + playerIsReady + "\n";
	if (state == 10) setTimeout("playerIsReady = true", 100);
        var unified_states = {
                0: "stopped",
                1: "stopped",
                2: "paused",
                3: "playing",
                4: "waiting", 	// "scanforward",
                5: "waiting", 	// "scanreverse",
                6: "waiting", 	// "buffering",
                7: "waiting",
                8: "ended", 	// "ended",
                9: "waiting", 	// "preparing",
                10: "stopped", 	// "ready",
                11: "waiting" 	// "reconnecting"
        }

	if (state == 10) return;
	realState = state;

	main.debug('OnDSPlayStateChangeEvt(' + state + ') = ' + unified_states[state]);

	if(main.player.onStateChanged)
		main.player.onStateChanged(unified_states[state]);

	if(state == 8) // video stopped playing
	{
		if(main.onVideoCompleted)
			main.onVideoCompleted();
	}

}

// TODO: change name to this function. Something like redrawElementsThatOftenNeedToBeUpdated
function redrawSeeker() {
	if (main.article.media_state == 'live') {
		$('#seeker').css('display', 'none');
	}

	if(!main.player)
		return false; // nothing to do

	var currentTime = main.getRealVideoPosition();
	var skip = main.article.skip_time;
	if(!skip) skip = 0;
	if(currentTime < skip)
	{
		main.seekRealVideoPosition(currentTime = skip);
	}
	var isSeeking = false;

	if (main.getState() == 'playing') {
		for(var i = 0; i < main.article.totalPauses; i++)
		{
			if(currentTime >= main.article.pauses[i].startTime && currentTime < main.article.pauses[i].endTime)
			{
				main.seekRealVideoPosition(main.article.pauses[i].endTime);
				currentTime = main.article.pauses[i].endTime;
				i = main.article.totalPauses;
				isSeeking = true;
			}
		}

		if (!isSeeking) {
			var vLength = main.getVideoLength();
			if (vLength > 0) {
				var percent = (main.getVideoPosition()) / vLength;
				var position = ($('#seekerContainer').width() - 9) * percent;
				$('#seeker').css('left', position + 'px');
				if(!$("#seeker").is(":visible")) $('#seeker').show();
			} else {
				if($("#seeker").is(":visible")) $('#seeker').hide();
			}
		} else {
			if(!$("#seeker").is(":visible")) $('#seeker').show();
		}
	}
	else
	{
		if(main.getState() != 'waiting' && main.getState() != 'paused' && $("#seeker").is(":visible"))
			$('#seeker').hide();
	}


}

function redrawArticle()
{
	main.debug("redrawArticle()");
	if(!main.player)
		return;

	if (document.getElementById('main').className != main.displayState) {
		document.getElementById('main').className = main.displayState;
       	        $(".foilssmall #live,.nofoils #live").css({top:60,left:10})
                $(".foilslarge #live").css({top:61,left:615})
	}

	if(main.popupMessage) {
		if(!$("#popup_message").is(":visible")) {
			$("#popup_message").html("<div style='padding: 10px;' id='popup_message_container'>" + main.popupMessage + "</div>");
			$("#popup_message").fadeIn(1000);
		}
	}
	else
	{
		if($("#popup_message").is(":visible")) {
			$("#popup_message").fadeOut(1000, function() {
	        	        $(".foilssmall #live,.nofoils #live").css({top:60,left:10})
		                $(".foilslarge #live").css({top:61,left:615})
			});
		}
	}

	if (main.getState() == "waiting") {
		if(!$("#player_message").is(":visible")) {
			$("#player_message").html("Buffering");
			$("#player_message").fadeIn(1000);
		}
	} else if ($("#player_message").is(":visible")) {
			$("#player_message").fadeOut(1000);
	}

	if(main.showTimer)
	{
		var e = document.getElementById('admininfo');
		if(!e)
		{
			e = $("<div style='border:1px solid black; background-color: white;position:absolute;top:0px;left:0px;right:0px;' id='admininfo'></div>");
			$(document.body).append(e);
		}
		else e = $(e);
		e.html("Second: " + main.getRealVideoPosition());
	}

        switch(main.article.media_state)
        {
                case "live" :
			main.debug("redrawArticle(): live: " + main.article.transmission_state, "mainArticleTransmissionState", main.article.transmission_state);
			var stateChanged = main.tmp_media_state != main.article.transmission_state;
			main.tmp_media_state = main.article.transmission_state;

			switch(main.article.transmission_state)
			{
				case "before" :
					// This should realy never happen...
					setTimeout("top.location.href = SERIA_VARS.HTTP_ROOT + '/no_cast.php?id=' + main.article.id", Math.ceil(Math.random()*15000));
					break;
				case "after" : // offline mode
					setTimeout("top.location.href = SERIA_VARS.HTTP_ROOT + '/no_cast.php?id=' + main.article.id", Math.ceil(Math.random()*15000));
					break;
				case "during" :
					if(stateChanged)
					{
						main.debug('state changed to "during"');
						main.player.playVideo();
					}
					main.liveMessage = false;
					if(typeof(main.article.foils)=='undefined')
					{
			                        var smallURL = SERIA_VARS.HTTP_ROOT + "/error_images/no-powerpoint-found.png";
		        	                var largeURL = SERIA_VARS.HTTP_ROOT + "/error_images/no-powerpoint-found.png";
					}
					else
					{
			                        var smallURL = main.article.foils[main.article.presentation_current_slide_index].small;
			                        var largeURL = main.article.foils[main.article.presentation_current_slide_index].large;
					}
					break;
			}
                        break;
                case "file" :
                	if (typeof(main.article.foil_timing[0]) != 'undefined') {

				var currentTime = main.getRealVideoPosition() - main.article.skip_time;
				var currentFoil = main.article.foil_timing[0].slide;
				if (main.article.foil_timing &&  main.article.foil_timing[0]) {
					var currentFoil = main.article.foil_timing[0].slide;
					for(var i in main.article.foil_timing)
					{
						if(currentTime > main.article.foil_timing[i].time)
							currentFoil = main.article.foil_timing[i].slide;
					}
	
					if (!main.article.foils[currentFoil]) currentFoil = main.article.foil_timing[0].slide;

					var smallURL = main.article.foils[currentFoil].small;
					var largeURL = main.article.foils[currentFoil].large;
				}
	
			}

			// 0 - 6

			var newTime = "";
			if (main.getState() == 'playing') {
				newTime = (main.displayState == "foilslarge" ? convertSecondsToHumanReadable(main.getVideoPosition()) : convertSecondsToHumanReadable(main.getVideoPosition()) + " / " + convertSecondsToHumanReadable(main.getVideoLength()));
			} else if (main.getState() == 'ended') {
				newTime = (main.displayState == "foilslarge" ? "00:00" : "00:00 / " + convertSecondsToHumanReadable(main.getVideoLength()));
			}
			if ($("#right").text() != newTime) $("#right").text(newTime);

                        break;
        }

	if(main.liveMessage)
	{
		$("#live").css({top:-2000,left:-2000})
		$("#live_message").fadeIn(1000);

		var bgImage = "";
		if(main.article.media_type=="audio" && main.article.speaker_image)
		{
			switch(main.displayState)
			{
				case "foilslarge" :
					bgImage = "<img src='" + main.article.speaker_image.small + "' style='position: absolute; width: 311px; height: 176px;'>";
					break;
				case "foilssmall" :
				case "nofoils" :
					bgImage = "<img src='" + main.article.speaker_image.small + "' style='position: absolute; width: 584px; height: 328px;'>";
					break;

			}
		}
		var newMessage = bgImage + "<table style='width:" + (main.displayState == "foilslarge" ? "311" : "584") + "px; position: absolute; height: " + (main.displayState == "foilslarge" ? "176" : "328") + "px;'><tr><td style='text-align:center;font-weight:bold;'><span id='info'>" + main.liveMessage + "</span></td></tr></table>";
		if ($("#live_message").html() != newMessage) $("#live_message").html(newMessage);
	}
	else if(main.article.media_type=="audio")
	{
		$("#live").css({top:-2000,left:-2000});

		var bgImage = "";
		if(main.article.media_type=="audio" && main.article.speaker_image)
		{
			switch(main.displayState)
			{
				case "foilslarge" :
					bgImage = "<img src='" + main.article.speaker_image.small + "' style='width: 311px; height: 176px;'>";
					break;
				case "foilssmall" :
				case "nofoils" :
					bgImage = "<img src='" + main.article.speaker_image.large + "' style='width: 584px; height: 328px;'>";
					break;
			}
		}

		if ($("#live_message").html() != bgImage) $("#live_message").html(bgImage);
	}
	else
	{
		if($("#live_message").is(":visible")) {
			$("#live_message").fadeOut(1000, function() {
		       	        $(".foilssmall #live,.nofoils #live").css({top:60,left:10})
		                $(".foilslarge #live").css({top:61,left:615})
			});
		}
	}

	var imageChanged = main.tmp_old_largeURL != largeURL;
	main.tmp_old_largeURL = largeURL;

        switch(main.displayState)
	{
		case "foilslarge" : 

			if(imageChanged)
			{
				$("#foils img:first").show().each(function(){
					if(!$(this).attr("src"))
					{
						$(this).attr("src", largeURL).css({position:"absolute",top:"0px",left:"0px"});
					}
					else
					{

						var i = $(document.createElement("IMG"));
						i.attr("src", largeURL);
						i.css({position:"absolute",top:"0px",left:"0px"});
						$(i).insertBefore($(this));
						$(this).fadeOut(1000, function(){$(this).remove();});

					}
				});
			}


			if (embed) {
				$("#windowsMediaPlayer").css({width: main.playerWidth + "px",height: main.playerHeight + "px"});
			} else {
				$("#windowsMediaPlayer").css({width: "311px",height: "175px"});
			}
			break;
		case "foilssmall" : 
			if(imageChanged)
			{
				$("#foils img").each(function(){
					if(!$(this).attr("src"))
					{
						//Changed to prevent images from getting lower quality if foils are in the upper right
						//$(this).attr("src", smallURL).css({position:"absolute",top:"0px",left:"0px"});
						$(this).attr("src", largeURL).css({position:"absolute",top:"0px",left:"0px"});
					}
					else
					{
						var i = $(document.createElement("IMG"));
						i.attr("src", largeURL);
						// Changed here too.
						//i.attr("src", smallURL);
						i.css({position:"absolute",top:"0px",left:"0px"});
						$(i).insertBefore($(this));
						$(this).fadeOut(1000, function(){$(this).remove();});
					}
				}); 
			}

			$("#windowsMediaPlayer").css({width: "584px",height: "330px"});
			break;
		case "nofoils" : 
			$("#windowsMediaPlayer").css({width: "584px",height: "330px"});
			break;
	}

}

function convertSecondsToHumanReadable(secs) {
	var hours = Math.floor(secs / 3600);
	secs -= hours * 3600;
	var minutes = Math.floor(secs / 60);
	secs -= minutes * 60;
	secs = Math.floor(secs);
	if (minutes < 10) minutes = "0" + minutes;
	if (secs < 10) secs = "0" + secs;
	return (hours > 0 ? hours + ":" : "") + minutes + ":" + secs;
}

function initArticle()
{
	$("#main").css({display: "block"});
	main.debug("initArticle()");
	// insert video player
	switch (main.article.media_type) {
		case "chat" :
			main.debug("initArticle(): chat");
			$("#live").html('<iframe src="'+SERIA_VARS.HTTP_ROOT+'/embed/chat.php?id='+main.article.id+'" scrolling="no" style="width: 584px; height: 360px; border: none; padding: 0px;"></iframe>');
			break;
		default:
			main.debug("initArticle(): default: " + main.article.media_type);

			if (embed == "media") {
				main.playerWidth = $("#live").parent().width();
				main.playerHeight = Math.floor(main.playerWidth / 1.7777777);
				$("#live_controls").css("top", main.playerHeight);
				$("#live_controls").css("width", main.playerWidth);
				$("#live_controls #controls").css("width", main.playerWidth);
				$("#live_controls #middle,#live_controls #player_message").css({width: (main.playerWidth - 97) + "px"});
	
			} else {
				if (main.displayState == "foilslarge") {
					main.playerWidth = 311;
					main.playerHeight = 175;
				} else {
					main.playerWidth = 584;
					main.playerHeight = 330;
				}
			}

			switch(main.article.media_player)
			{
				case "windows_media_player" : 
					if($.browser.msie)
					{
						$("#live").html('<OBJECT id="windowsMediaPlayer" classid="clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6" width="' + main.playerWidth + '" height="' + main.playerHeight + '" style="position:absolute; left:0;top:0;" stype="application/x-oleobject"><PARAM NAME="SendPlayStateChangeEvents" VALUE="True"><PARAM NAME="StretchToFit" VALUE="True"><PARAM NAME="AutoStart" VALUE="False"><PARAM name="uiMode" value="none"><PARAM name="PlayCount" value="1"></OBJECT>');
					}
					else
					{

						$("#live").html('<OBJECT id="windowsMediaPlayer" width="' + main.playerWidth + '" height="' + main.playerHeight + '" style="position:absolute; left:0;top:0;" type="application/x-ms-wmp"><PARAM NAME="SendPlayStateChangeEvents" VALUE="True"><PARAM NAME="AutoSize" VALUE="False"><PARAM NAME="StretchToFit" VALUE="True"><PARAM NAME="AutoStart" VALUE="False"><PARAM name="uiMode" value="none"><PARAM name="PlayCount" value="1"></OBJECT>');
					}
					// It has to be delayed to get it to work with firefox
					setTimeout(initWindowsMediaPlayer, 200);
					break;
				case "silverlight" :
					initSilverlightPlayer();
					break;
				case "flash" :
					$("#live").html("<div id='flashhere'>Requires Flash</div>");
					var flashvars = {};
					var params = {"allowFullScreen": "true", "allowscriptaccess": "always", "swmode" : "opaque"};
					var attributes = {"id" : "flashPlayer", "style" : ""};
					try {
						if(top.location.href.indexOf("new_player=1") != -1) {
							swfobject.embedSWF(SERIA_VARS.HTTP_ROOT + "/embed/player/cikplayer_new.swf?412", "flashhere",  main.playerWidth,  main.playerHeight, "9.0.115", SERIA_VARS.HTTP_ROOT + "/embed/swfobject/expressInstall.swf", flashvars, params, attributes);
						} else if(top.location.href.indexOf("new_version=1") != -1) {
							swfobject.embedSWF(SERIA_VARS.HTTP_ROOT + "/embed/player/player_ny.swf", "flashhere",  main.playerWidth,  main.playerHeight, "9.0.115", SERIA_VARS.HTTP_ROOT + "/embed/swfobject/expressInstall.swf", flashvars, params, attributes);					
						}
						else {
							swfobject.embedSWF(SERIA_VARS.HTTP_ROOT + "/embed/player/player.swf", "flashhere",  main.playerWidth,  main.playerHeight, "9.0.115", SERIA_VARS.HTTP_ROOT + "/embed/swfobject/expressInstall.swf", flashvars, params, attributes);
						}
					}
					catch (e) {
							swfobject.embedSWF(SERIA_VARS.HTTP_ROOT + "/embed/player/player.swf", "flashhere",  main.playerWidth,  main.playerHeight, "9.0.115", SERIA_VARS.HTTP_ROOT + "/embed/swfobject/expressInstall.swf", flashvars, params, attributes);
					}
					initFlashPlayer();
					break;
			}
			break;
	}


}

function initFlashPlayer()
{
	main.debug('initFlashPlayer()');
	var player = main.findSWF("flashPlayer");
	if(player && player.videoLoad)
	{

//		if (player.state != 'loaded') {
//			setTimeout(initFlashPlayer, 50);
//			return;
//		}

		//TODO: Flash må bruke new Object og så må alle kommandoer implementeres
		main.player = player;

		main.player.state = 'stopped';
		
		main.player.onStateChanged = function(state) {
			main.player.state = state;
			main._onStateChanged(state);
		}

		main.player.getPlayerState = function() {
			return main.player.state;
		}

		main.player.isMuted = function() {
			return (player.getVolume() == 0);
		};

		main.player.mute = function() {
			player.setVolume(0);
		};

		main.player.unMute = function() {
			player.setVolume(1);
		}

		main.player.loadVideo = function(url) {
			player.videoLoad(url, main.article.media_state=='live');
		}

		main.player.playVideo = player.videoPlay;
		main.player.pauseVideo = player.videoPause;
//TODO:alert('check this videoStop stuff');
		main.player.stopVideo = player.videoStop;
		main.player.seek = function(seconds) {
			player.seekSeconds(seconds);
		}

		if ($.browser.safari) {
			setTimeout(main.onPlayerReady, 2000);
		} else {
			main.onPlayerReady();
		}
		if (main.article.media_state == "live") setInterval(checkConnection, 400);
	}
	else
		setTimeout(initFlashPlayer, 50);
}

// This is only for flash
var connectionCounter = 0;
function checkConnection() {
	if (realState == "stopped" && startedPlaying) document.location.href = document.location.href;

	if (isNaN(main.player.getCurrentTime() && startedPlaying)) {
		connectionCounter++;
		if (connectionCounter == 2) {
 			document.location.href = document.location.href;
		}
	} else {
		connectionCounter = 0;
	}
}

function initWindowsMediaPlayer()
{
	main.debug('initWindowsMediaPlayer()');
	var player = document.getElementById('windowsMediaPlayer');
	main.update();
	if(player && player.controls)
	{
		main.player = new Object();
		main.player.state = 'stopped';

		main.player.status = function() {
			return player.status;
		}


		main.player.onStateChanged = function(state) {
			main.player.state = state;
			main._onStateChanged(state);
		}

		main.player.getPlayerState = function() {
			return main.player.state;
		}

		main.player.isMuted = function() {
			return player.settings.mute;
		};

		main.player.mute = function() {
			player.settings.mute = true;
		};

		main.player.unMute = function() {
			player.settings.mute = false;
		}

		main.player.loadVideo = function(url) { 

			main.debug('loadVideo: '+ url+' playstate:' + main.player.playState());

			playerIsReady = false;
			player.URL = url;
//			setTimeout(function(){main.debug('loadVideo delayed setting URL'); player.URL = url;}, 500);
		};

		main.player.playState = function() {
			return player.playState;
		}

		main.player.pauseVideo = function() {
			main.debug('pauseVideo');
			if(player.controls.isAvailable('Pause'))
			{
				player.controls.pause();
			}
		}
		main.player.stopVideo = function() {
			main.debug('stopVideo');
			if(player && player.controls && player.controls.isAvailable('Stop'))
			{
				player.controls.stop();
			}
			else
			{
				main.debug('Stop not available');
			}
		}

		main.player.playVideo = function() { 
			
			main.debug('playVideo()');

			if (playerIsReady) {
				player.controls.play();
			} else {
				setTimeout(main.player.playVideo, 100);
			}

		}
		main.player.seek = function(seconds) {
			main.debug('main.player.seek(' + seconds + ')');
			player.controls.currentPosition = seconds;
		}

		main.player.getVideoLength = function() { 
			if (player.currentMedia) {
				return player.currentMedia.duration; 
			} else {
				return 0;
			}
		}

		main.player.getCurrentTime = function() { 
			return player.controls.currentPosition; 
		}

		if(player.attachEvent)
		{
			player.attachEvent("playStateChange", OnDSPlayStateChangeEvt);
		} else if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
//			player.addEventListener("playStateChange", OnDSPlayStateChangeEvt, false);
//			setTimeout(checkStateChange, 100);
		}

		main.onPlayerReady();
	}
	else {
		setTimeout(initWindowsMediaPlayer, 50);
	}
}

var curState = '';
function checkStateChange() {
	if (main.player.playState() != curState) {
		curState = main.player.playState();
		OnDSPlayStateChangeEvt(curState);
	}
	setTimeout(checkStateChange, 50);
}

function initSilverlightPlayer()
{
	main.debug('initSilverlightPlayer()');
	var player = document.getElementById('silverlightPlayer');

        if (player) {
                // Internet Explorer throws an exception if Silverlight is not initialized
                try {
                        if (!player.content.js) 
				setTimeout(initSilverlightPlayer, 50);
			else
			{
				main.player = player.content.js;
				main.player.loadVideo = player.videoLoad;
				main.player.playVideo = player.videoPlay;
				main.player.pauseVideo = player.videoPause;
//TODO:alert('check this videoStop stuff');
				main.player.stopVideo = player.videoStop;
				main.player.seek = function(seconds) {
					if(player.getCurrentState()=="closed") {
						setTimeout(function(){main.player.seek(seconds)},100);
					} else {
						main.player.seekSeconds(seconds);
					}
				}
				main.onPlayerReady();
			}

                } catch (e) {
			main.debug("initSilverlightPlayer error: " + e);
			setTimeout(initSilverlightPlayer, 50);
                }
        }
	else
	{
		setTimeout(initSilverlightPlayer, 100);
	}
}

document.playerInit = (function(){
	/**
		PREPARE
	*/$
	main.displayState = main.article.presentation_file_id ? "foilslarge" : "nofoils";

	main.state = 'stopped';

	main.update = function() {
		redrawArticle();
	}

	main.updateSeeker = function() {
		redrawSeeker();
	}
	
	main.toggleMute = function() {
		if (main.player.isMuted()) main.player.unMute();
		else main.player.mute();
	}

	main.debug = function(m, statusName, statusValue)
	{
		return false;
		if(statusName)
		{
			var dbg = $("#debugger #debugger_status").get(0);
			if(!dbg)
			{
				dbg = document.createElement("DIV");
				dbg.id = "debugger_status";
				$(dbg).css({border:"1px solid black",position:"fixed",bottom:"0px",height:"100px",width:"100%",backgroundColor:"white",left:"0px"});
				$("#debugger").append(dbg);
			}
			var box = $(dbg).find("." + statusName).get(0);
			if(!box)
			{
				box = document.createElement("DIV");
				box.className=statusName;
				$(dbg).append(box);
			}
			$(box).html(statusName + ": " + statusValue);
		}
		if(m===false) return;

		if(main.tmp_debug == m)
		{ // last message is identical
			main.tmp_debug_counter++;
			$("#debugger :first").html(m + " <span style='color:#777'>(" + main.tmp_debug_counter + " times)</span>");
			return;
		}
		main.tmp_debug_counter = 1;
		main.tmp_debug = m;
		$('#debugger').prepend("<div>" + m + "</div>");
	}
	main.findSWF = function(name) {
		main.debug("main.findSWF("+name+")");
		if($.browser.msie)
			return window[name];
		else
			return document[name];
	}

	// Returns the persieved length in seconds of this movie (when removing all pauses and initial skip time)
	main.getVideoLength = function() {
		var videoLength = 0;
		if ((main.article.video_url && main.article.media_state == "live") || main.article.video_rtmp_1) {
			videoLength = main.player.getVideoLength();
		} else {
			videoLength = main.article.totalLength;
		}

		var skip = main.article.skip_time;
		if(!skip) skip = 0;
		return videoLength - skip;
	}

	// Returns the persieved position in seconds of this movie (when removing all pauses and initial skip time)
	// ØYVIND: Jeg forandret denne til å trekke fra skip_time
	main.getVideoPosition = function() {
		main.debug("main.getVideoPosition()");
		var realPos = main.getRealVideoPosition();
		var skip = main.article.skip_time;
		if(!skip) skip = 0;
		var pos = realPos - skip;

		for (var i = 0; i < main.article.totalPauses; i++) {
			if (realPos >= (main.article.pauses[i].startTime + main.article.skip_time)) 
				pos -= (main.article.pauses[i].endTime - main.article.pauses[i].startTime);
		}
		return pos;
	}

	main.getRealVideoPosition = function() {
		if (main.getState() == 'playing') {
			main.debug("main.getRealVideoPosition()");
			if(!main.player)
				return 0; //TODO: Cast exception when player is not ready?

			if (main.article.video_rtmp_1 || (main.article.video_url && main.media_state == 'live')) {
				return parseFloat(main.player.getCurrentTime());
			} else {
				var currentTime = 0;
				for(var i = 0; i < main.filePos; i++)
					currentTime += parseFloat(main.article.files[i].duration);
				currentTime += parseFloat(main.player.getCurrentTime());
				return currentTime;
			}
		}
	}

	// Seeks to any offset inside the video - taking into account initial skip time and all pauses.
	// ØYVIND: Forandret denne til å hoppe over skip_time
	main.seekVideoPosition = function(seconds) {
		main.debug("main.seekRealVideoPosition("+seconds+")");
		var realSeconds = seconds;

		var skip = main.article.skip_time;
		if(!skip) skip = 0;
		realSeconds += skip;

		for (var i = 0; i < main.article.totalPauses; i++) {
			if (realSeconds >= main.article.pauses[i].startTime) realSeconds += (main.article.pauses[i].endTime - main.article.pauses[i].startTime);
		}
		main.seekRealVideoPosition(realSeconds);
	}

	main.seekRealVideoPosition = function(seconds) {
		main.debug("main.seekRealVideoPosition("+seconds+")");
		// sometimes it hangs while seeking - meaning it seeks and seeks to the same position:
		if(main.rememberLastSeek == seconds && main.rememberLastSeekTime == Math.floor(main.getRealVideoPosition()))
			return;
		main.rememberLastSeek = seconds;
		main.rememberLastSeekTime = Math.floor(main.getRealVideoPosition());

		if(!main.player) 
			throw "Video not playing";

		var pos = 0;
		var curFile = 0;
		var totTime = 0;
		for(var i=0; i < main.article.totalFiles; i++)
		{
			pos += parseFloat(main.article.files[i].duration);
			if(pos > seconds)
			{
				curFile = i;
				i = main.article.totalFiles;
			}
			else
			{
				totTime = parseFloat(main.article.files[i].duration) + totTime;
			}
		}

                // If seeking to another file, change file
                if((main.article.video_rtmp_1=="") && (main.filePos != curFile))
		{
                        main.loadFileByIndex(curFile);

                        if ((seconds - totTime) > 0) {
				main.player.seek(seconds - totTime);
                        }

			main.player.playVideo();
                } else {
                        main.player.seek(seconds - totTime);
                }

	}

	main.onPlayerReady = function() {
		main.debug("main.onPlayerReady()");
		// player is ready to rumble

		reloadArticle();

		if(main.article.media_state == "live")
		{
			main.player.loadVideo(main.article.video_url);
			if(main.article.transmission_state=="during")
				main.player.playVideo();

			setInterval(main.update, 100);
		}
		else if(main.article.media_state == "file")
		{
			if(main.article.video_rtmp_1=="") {
				main.loadFileByIndex(0);
			} else {
				main.player.loadVideo(main.article.video_rtmp_1);
			}

			if (!main.article.require_registering || hasRegistered) {
				main.player.playVideo();
			}
			setInterval(main.update, 100);
		}

		$(".shadow").createShadow();
		main.update();

		setInterval(main.updateSeeker, 100);

	}


	main.playPause = function() {
		if (main.getState() == 'playing') {
			try
			{
				main.player.pauseVideo();
			}
			catch (m)
			{
				main.player.stopVideo();
			}
		} else {
			main.player.playVideo();
		}
	}

	var streamHasStarted = false;
	var streamHasEnded = false;
	// This is a private function. Use the onStateChanged function
	main._onStateChanged = function(state) {
		if (state == 'playing') {
			// Has to do this. If not the player will be black in IE8 (Other IE browsers not tested)
			var wmp = document.getElementById("windowsMediaPlayer");
			if (wmp) {
				wmp.style.left = "1px";
				setTimeout('document.getElementById("windowsMediaPlayer").style.left = "0px";', 100);
			}

			streamHasStarted = true;
			streamHasEnded = false;
		}
		if (!streamHasStarted) state = 'waiting';
		if (streamHasEnded) state = 'ended';

		if (state == 'ended' && main.article.media_state=='file' && !streamHasEnded) {
			if(main.article.files[main.filePos+1]) {
				state = 'stopped';
			} else {
				streamHasEnded = true;
			}
		}

		if (state != main.state) {
			main.state = state;
			main.onStateChanged(state);
		}
	}
	main.onStateChanged = function(state) {
qqq += state + "\n";	
		main.update();
	}


	main.getState = function() {
//return "playing";
		return main.state;
	}

	main.onVideoCompleted = function() {
		main.debug("main.onVideoCompleted()");
		if(main.article.media_state=='file')
		{
			try
			{
				main.loadFileByIndex(main.filePos+1);
				main.player.playVideo();
			}
			catch (e)
			{
				main.loadFileByIndex(0);
			}
		}
	}
	main.loadFileByIndex = function(index) {
		main.debug("main.loadFileByIndex("+index+")");
		if(typeof(main.article.files)=="undefined" || !main.article.files[index]) {
//			alert("unknown index: " + index);
			throw "Unknown index";
		}

		main.filePos = index;
		main.player.loadVideo(main.article.files[index].url, false);
	}
	main.setDisplayState = function(state)
	{
		main.debug("main.setDisplayState("+state+")");
		try
		{
			switch (state)
			{
				case "foilssmall" : 
					if(main.displayState != "foilslarge")
						throw "Illegal state fl";
					if(main.article.media_player == "windows_media_player" && $.browser.mozilla)
						throw "Unable to resize Windows Media Player in Firefox";
					break;
				case "foilslarge" : 
					if(main.displayState != "foilssmall")
						throw "Illegal state fs";
					if(main.article.media_player == "windows_media_player" && $.browser.mozilla)
						throw "Unable to resize Windows Media Player in Firefox";
					break;
				case "nofoils":
					if(main.displayState != "nofoils")
						throw "Illegal state nf";
					break;
				default : 
					throw "Unknown state (must be nofoils, foilslarge, foilssmall)";
			}
			main.debug("main.setDisplayState("+state+") set.", "mainState", state);
			main.displayState = state;
			main.update();
			$(".shadow").createShadow();
		}
		catch (e)
		{
			alert(e);
		}
	}

	/**
		GET TO WORK
	*/
	// Has to be delayed to get windows media player to work with firefox


	
	setTimeout(initArticle,200);


	/**
		POLL
	*/
});


