/**
	CALLED BY SERIA FLASH AND SILVERLIGHT PLAYERS
*/
function stateChange(state) {
	main.debug('stateChange(' + state + ')');
//	$('#states').append(state + '<br>');
	if (state == 'loading' || state == 'seeking' || state == 'buffering' || state == 'opening') {
		main.onStateChanged('loading');
	} else if (state == 'stopped') {
		main.onStateChanged('stopped');
	} else if (state == 'paused') {
		main.onStateChanged('paused');
	} else if (state == 'playing') {
		main.onStateChanged('playing');
	} else if (state == 'disconnected') {
		main.onStateChanged('disconnected');
	} else if (state == 'rewinding') {
		main.onStateChanged('rewinding');
	} else {
		alert('state: ' + state);
	}
}
/**	CALLED BY SERIA FLASH AND SILVERLIGHT PLAYERS */
function videoCompleted()
{
	main.debug('videoCompleted()');
	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;
}

/** CALLED BY WINDOWS MEDIA PLAYER IN FIREFOX */
function OnDSPlayStateChangeEvt(state)
{
        var unified_states = {
                0: "undefined",
                1: "stop",
                2: "pause",
                3: "playing",
                4: "playing", 	// "scanforward",
                5: "playing", 	// "scanreverse",
                6: "playing", 	// "buffering",
                7: "wait",
                8: "stop", 	// "ended",
                9: "playing", 	// "preparing",
                10: "stop", 	// "ready",
                11: "wait" 	// "reconnecting"
        }
	main.player.state = unified_states[state];
	main.debug('OnDSPlayStateChangeEvt(' + state + ') = ' + unified_states[state]);


	if(main.onStateChanged)
		main.onStateChanged(unified_states[state]);
	//TODO: call main.onStateChanged when player is buffering, loading or seeking

	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.player.state == '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');
				$('#seeker').show();
			} else {
				$('#seeker').hide();
			}
		} else {
			$('#seeker').show();
		}
	}
	else
	{
		if(main.player.state != 'paused')
			$('#seeker').hide();
	}


}

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


	document.getElementById('main').className = main.state;

	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
	{
		$("#popup_message").fadeOut(1000, function() {
        	        $(".foilssmall #live,.nofoils #live").css({top:60,left:10})
	                $(".foilslarge #live").css({top:61,left:615})
		});
	}


	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 (main && main.player && main.player.state && main.player.state == 'playing') {
				$("#right").html(convertSecondsToHumanReadable(main.getVideoPosition()) + " / " + convertSecondsToHumanReadable(main.getVideoLength()));
			}

                	if (typeof(main.article.foil_timing[0]) == 'undefined')
                		break;
//OER
			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;
				}

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

//			if (main && main.player && main.player.state && main.player.state == 'playing') {
//				$("#right").html(convertSecondsToHumanReadable(main.getVideoPosition()) + " / " + convertSecondsToHumanReadable(main.getVideoLength()));
//			}

                        break;
        }
//alert(main.liveMessage);
	if(main.liveMessage)
	{
		$("#live").css({top:-2000,left:-2000})
		$("#live_message").fadeIn(1000);
		$("#live_message").html("<table style='width:100%;height:176px;'><tr><td style='text-align:center;font-weight:bold;'>" + main.liveMessage + "</td></tr></table>");

		if(main.article.media_type=="audio" && main.article.speaker_image)
		{
			switch(main.state)
			{
				case "foilslarge" :
					$("#live_message").css({backgroundImage:"url("+main.article.speaker_image.small+")",backgroundRepeat:"no-repeat",backgroundPosition:"top center"});
					break;
				case "foilssmall" :
				case "nofoils" :
					$("#live_message").css({backgroundImage:"url("+main.article.speaker_image.large+")",backgroundRepeat:"no-repeat",backgroundPosition:"top center"});
					break;
			}
		}
	}
	else if(main.article.media_type=="audio")
	{
		$("#live").css({top:-2000,left:-2000});
		$("#live_message").html("<div id='live_message_image'></div>");
		switch(main.state)
		{
			case "foilslarge" :
				$("#live_message").css({backgroundImage:"url("+main.article.speaker_image.small+")", backgroundRepeat:"no-repeat", backgroundPosition:"top center"});
				break;
			case "foilssmall" :
			case "nofoils" :
				$("#live_message").css({backgroundImage:"url("+main.article.speaker_image.large+")", backgroundRepeat:"no-repeat", backgroundPosition:"top center"});
				break;
		}
	}
	else
	{
		$("#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_state != main.state;
	main.tmp_old_largeURL = largeURL;
	main.tmp_old_state = main.state;
//if (imageChanged && main.article.id == "10843") alert(largeURL);
//imageChanged = true;

        switch(main.state)
	{
		case "foilslarge" : 
			$("#foils img:first").show().each(function(){
				if(imageChanged)
				{
					if(!$(this).attr("src"))
					{
						$(this).attr("src", largeURL).css({position:"absolute",top:"0px",left:"0px"});
					}
					else
					{
//if (imageChanged && main.article.id == "10843") alert(smallURL + " large");
						var i = $(document.createElement("IMG"));
						i.attr("src", largeURL);
						i.css({position:"absolute",top:"0px",left:"0px"});
						$(i).insertBefore($(this));
						$(this).remove();
//						$(this).fadeOut(1000, function(){$(this).remove();});
					}
				}
			}); 
			$("#windowsMediaPlayer").css({width:"311px",height:"175px"});
			break;
		case "foilssmall" : 
			$("#foils img").each(function(){
				if(imageChanged)
				{
					if(!$(this).attr("src"))
					{
						$(this).attr("src", smallURL).css({position:"absolute",top:"0px",left:"0px"});
					}
					else
					{
//if (imageChanged && main.article.id == "10843") alert(smallURL + " small");
						var i = $(document.createElement("IMG"));
						i.attr("src", smallURL);
						i.css({position:"absolute",top:"0px",left:"0px"});
						$(i).insertBefore($(this));
						$(this).remove();
//						$(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.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);
			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="584" height="330" style="position:absolute; left:0;top:0;" stype="application/x-oleobject"><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>');
					}
					else
					{
						$("#live").html('<OBJECT id="windowsMediaPlayer" width="584" height="330" 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>');
					}
					initWindowsMediaPlayer();
					break;
				case "silverlight" :
					initSilverlightPlayer();
					break;
				case "flash" :
					$("#live").html("<div id='flashhere'>Requires Flash</div>");
					var flashvars = {};
					var params = {"allowscriptaccess": "always", "swmode" : "opaque"};
					var attributes = {"id" : "flashPlayer", "style" : ""};
					swfobject.embedSWF(SERIA_VARS.HTTP_ROOT + "/embed/player/player.swf", "flashhere", "311", "175", "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)
	{
		//TODO: Flash må bruke new Object og så må alle kommandoer implementeres
		main.player = player;

		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);
		}
		try
		{
			main.player.getVideoLength = player.getVideoLength;
		} catch (e) {
			//FRODE: Feil her - må fikses
		}

		try {
			main.player.getCurrentTime = player.getCurrentTime;
		} catch (e) {
			//FRODE: Feil her - må fikses
		}
		main.onPlayerReady();
	}
	else
		setTimeout(initFlashPlayer, 50);
}
function initWindowsMediaPlayer()
{
	main.debug('initWindowsMediaPlayer()');
	var player = document.getElementById('windowsMediaPlayer');
	main.update();
	if(player && player.controls)
	{
		main.player = new Object();
		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());
			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();
			else
			{
				main.debug('Pause not available');
				throw 'Pause is not available for live streams';
			}
		}
		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(player.controls.isAvailable('play')) {
			if(player.playState == 9) // preparing new media item - try again
			{
				main.debug('playVideo(): Not ready: preparing new media item');
				setTimeout(main.player.playVideo, 200);
			}
			else if(player.controls.isAvailable('play')) 
			{
				player.controls.play();
			} else {
				main.debug('playVideo(): Not ready: play control unavailable');
				setTimeout(function(){main.player.playVideo();}, 200);
			}
		}
		main.player.seek = function(seconds) {
			main.debug('main.player.seek(' + seconds + ')');
			player.controls.currentPosition = seconds;
		}

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

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

		if(player.attachEvent)
		{
			player.attachEvent("playStateChange", OnDSPlayStateChangeEvt);
		} else if (player.addEventListener) {
//			player.addEventListener("playStateChange", OnDSPlayStateChangeEvt, false);
		}
		main.onPlayerReady();
	}
	else
		setTimeout(initWindowsMediaPlayer, 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);
	}
}

function getMS()
{
	var d = new Date();
	return d.getSeconds() + (d.getMilliseconds() / 1000);
}

var oldDelay = 5000;

function reloadArticle()
{
        var ms = getMS();

        var t = SERIA.Lib.SJSON('/cache/' + main.article.id + '.js?' + Math.random());

        if(typeof(t)!="undefined")
                main.article = t;

        if(main.article.refreshTime)
                setTimeout(reloadArticle, main.article.refreshTime);
        else
                setTimeout(reloadArticle, 14000);
}

document.playerInit = (function(){
	/**
		PREPARE
	*/
	main.state = main.article.presentation_file_id ? "foilslarge" : "nofoils";
	main.update = 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) {
			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.player.state == 'playing') {
			main.debug("main.getRealVideoPosition()");
			if(!main.player)
				return 0; //TODO: Cast exception when player is not ready?

			if (main.article.video_url) {
				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

//		main.player.state = 'ready';
		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);
		}

		main.update();

	}


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



	main.onStateChanged = function(state) {
		main.debug("main.onStateChanged("+state+")", "mainPlayerState", state);
		if((state=="disconnected") && (main.article.media_state=='live'))
		{
			main.liveMessage = "<div class='info'>You got disconnected.</div>";
			setTimeout(function(){location.href=location.href;}, 5000);
		}
		main.player.state = state;
		main.update();
	}

	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])
			throw "Unknown index";

//		stateChange('loading');
//		main.onStateChanged('busy');
		main.filePos = index;
		main.player.loadVideo(main.article.files[index].url, false);
	}
	main.setState = function(state)
	{
		main.debug("main.setState("+state+")");
		try
		{
			switch (state)
			{
				case "foilssmall" : 
					if(main.state != "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.state != "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.state != "nofoils")
						throw "Illegal state nf";
					break;
				default : 
					throw "Unknown state (must be nofoils, foilslarge, foilssmall)";
			}
			main.debug("main.setState("+state+") set.", "mainState", state);
			main.state = state;
			main.update();
		}
		catch (e)
		{
			alert(e);
		}
	}

	/**
		GET TO WORK
	*/
	initArticle();
	if(main.article.media_state == 'live')
	        setTimeout(reloadArticle, 0);

	/**
		POLL
	*/
//	setInterval(main.update, 500);
	setInterval(main.updateSeeker, 100);
});


