var baseurl = "http://" + location.hostname + "/";

function warn(what) {
	if (console && console.log) console.log(what);
}

function YmoLoadStory( story_id, pars ) {
	var s = document.createElement("script");
	s.setAttribute("type", "text/javascript");
	s.setAttribute("src", baseurl + 'js/sprintf.js');
	document.getElementsByTagName("HEAD")[0].appendChild(s);
	var s = document.createElement("script");
	s.setAttribute("type", "text/javascript");
	s.setAttribute("src", baseurl + 'js/core.js');
	document.getElementsByTagName("HEAD")[0].appendChild(s);
	var s = document.createElement("script");
	s.setAttribute("type", "text/javascript");
	s.setAttribute("src", baseurl + 'js/swfobject.js');
	document.getElementsByTagName("HEAD")[0].appendChild(s);
	var s = document.createElement("script");
	s.setAttribute("type", "text/javascript");
	s.setAttribute("src", baseurl + 'studio/load_story?as_js=1&story=' + story_id);
	document.getElementsByTagName("HEAD")[0].appendChild(s);

	var settings = {
		height : 660,
		width: 370,
		sidebar : true
	};
	if (pars) {
		for (var i in pars) {
			settings[i] = pars[i];
		}
	}

	waitStoryData(settings);
}

function waitStoryData(settings) {
	if (!window.YmoStory || !window.http_request) {
		setTimeout(function() {
			waitStoryData(settings);
		}, 100);
		return;
	}
	for (var i in settings) {
		YmoStory[i] = settings[i];
	}
	new YmoPlayer(YmoStory);
}

YmoPlayer = function(pars) {
	if (pars.load_story) {
		http_request("/studio/load_story", 'GET', {
			story: pars.load_story,
			mix: pars.load_mix || 0
		}, function(res) {
			if (res.status != 'OK') {
				dialogue("Something went wrong", "This story could not be loaded");
				return;
			}
			warn("LOADED RES");
			for (var i in pars) {
				if (i == 'load_story') continue;
				if (!res[i]) res[i] = pars[i];
			}
			return window.player = new YmoPlayer(res);
		});
		return;
	}

	this.objects_loaded = {};
	this.is_director = 0;
	if (pars['is_director']) {
		this.is_director = 1;
	}

	this.sidebar = true;
	if (pars['sidebar'] != null) {
		this.sidebar = pars.sidebar;
	}
	this.playlist = false;
	if (pars['playlist']) {
		this.playlist = true;
	}

	if (pars['elemname']) this.elemname = pars['elemname'];

	this.width = pars.width || 660;
	this.height = pars.height || 370;

	if (pars.story_id) this.story_id = pars.story_id;
	if (pars.info) this.info = pars.info;
	this.sources = pars.sources || [];
	this.loop = pars.loop || 0;
	this.total_duration = pars.duration || 0;
	if (!this.total_duration) {
		for (var i=0, ic=this.sources.length; i<ic; i++) {
			if (this.sources[i].duration) {
				this.total_duration += Number(this.sources[i].duration);
			} else {
				this.total_duration += 2;
			}
		}
	}
	this.use_flash = (video_mp4())?0:1;
	this.container = pars.container;
	this.playedtime = 0;
	this.load_fullscreen = pars.fullscreen || 0;
	this.autoplay = 1;
	if (pars['autoplay'] != null) this.autoplay = pars.autoplay;
	this.progressbar = pars.progressbar || Elem('progressholder') || null;
	this.playbtn = pars.playbtn || Elem('playpause') || null;
	if (pars.transition == 'crossfade') pars.transition = 'fade';
	this.transition = pars.transition || null;
	this.bgsound = pars.bgsound;
	this.idx = 0;
	this.elem = null;
	window.player = this;

	if (!Elem('video')) {
		this.createPlayer();
	}

	var _this = this;
	this.load_players(function() {
		_this.preload();
		if (pars.fullscreen)
			_this.fullscreen();
		if (pars.autoplay) {
			_this.loadVideo(0, 'play');
		} else {
			_this.loadVideo(0);
		}
	});
};

function fade(id, oldid, value) {
	if (!Elem(oldid)) {
		Elem(id).opacity = 1;
		return;
	}
	value = value + 0.10;
	Elem(id).zIndex = 5;
	Elem(oldid).zIndex = 6;
	Elem(oldid).style.opacity = 1 - value;
	Elem(id).style.opacity = 1;
	if (value > 1) {
		Elem(oldid).parentNode.removeChild( Elem(oldid) );
	} else {
		setTimeout("fade('" + id + "', '" + oldid + "', " + value + ")", 20);
	}
}

function video_mp4() {
	//return 0; // Makes Safari etc. use Flash player
	var can_video = !!document.createElement('video').canPlayType;
	if (!can_video) return null;
	if (navigator.userAgent.indexOf("Mac OS") > 0 && navigator.userAgent.indexOf("Chrome") > 0)
		return null; // bug with playback in Chrome on Mac
	var v = document.createElement('video');
	return v.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"');
}

YmoPlayer.prototype = {	
	faketimer : 0,
	faketime : 0,
	faketimer_timeout : null,
	is_muted : false,
	is_paused : false,
	ctx_pause : false, /* Paused by contextual menus etc. -- blocks user interaction such as space to resume */
	is_loading : false,
	is_fullscreen : false,
	ymoplayer : null,
	objects_loaded : {},
	use_flash : (video_mp4())?0:1,
	is_firefox : (navigator.userAgent.indexOf("Firefox") > 0)?1:0,
	player : "html4",
	waitaudio : 0,
	cache : [],
	flash_player : "ymogen",
	volume : 100,
	elemname : 'player',
	info : [],
	active : {
		'comments' : 1
	},

	createPlayer : function() {
		if (!Elem(this.elemname)) {	
			document.getElementsByTagName("BODY")[0].appendChild( newElem('div', { 'id' : this.elemname }) );
		}
		Elem(this.elemname).appendChild(
			newElem('div', { 'id' : 'overlayholder' },
				newElem('div', { 'id' : 'overlay' },
					newElem('div', { 'style' : { 'position' : 'absolute' } },
						newElem('div', { 'id' : 'ymoplay' } )
					),
					newElem('div', { 'id' : 'video', 'class' : 'player viderror' }, 'player not supported'),
					newElem('div', { 'id' : 'socialbar' }
					),
						newElem('div', { 'id' : 'loader' }),
					newElem('div', { 'id' : 'controlbar' },
						newElem('div', { 'style' : { 'id' : 'cblb', 'paddingRight' : '5px', 'width' : '55px' }, 'class' : 'buttholder' },
									newElem('button', { 'id' : 'playpause' }, ' ')
						),
						newElem('div', { 'id' : 'progressholder' },
							//newElem('div', { 'id' : 'progresstimer' }, 'LOADING'),
							newElem('div', { 'id' : 'progress' })
						),
						newElem('div', { 'id' : 'progresstimer' }, 'LOADING'),
						newElem('div', { 'width' : '100', 'class' : 'buttholder', 'style' : { 'paddingLeft' : '5px', 'textAlign' : 'right' }, 'id' : 'rtButtHolder' },
							newElem('button', { 'id' : 'fsbutt' }, ' '),
							' ',
							newElem('button', { 'id' : 'mute' }, ' ')
						)
						/* ,
						newElem('table', { 'width' : '100%' },
							newElem('tr', {}, 
								newElem('td', { 'style' : { 'paddingRight' : '5px' }, 'width' : '55', 'class' : 'buttholder' },
									newElem('button', { 'id' : 'playpause' }, 'Pause')
								),
								newElem('td', { 'width' : '*', 'id' : 'progressholder' },
									newElem('div', { 'id' : 'progresstimer' }, 'LOADING'),
									newElem('div', { 'id' : 'progress' })
								),
								newElem('td', { 'width' : '140', 'class' : 'buttholder', 'style' : { 'paddingLeft' : '5px', 'textAlign' : 'right' }, 'id' : 'rtButtHolder' },
									newElem('button', { 'id' : 'fsbutt' }, 'FullScreen'),
									' ',
									newElem('button', { 'id' : 'mute' }, 'Mute')
								)
							)
						)
						*/
					)
				)
			)
		);

		Elem('progresstimer').ondragstart =
		Elem('progresstimer').onselectstart = function () { return false; }; // IE

		if (this.sidebar) {
			Elem('socialbar').appendChild(
				newElem('button', { 'id' : 'add_comment' }, ' ')
			);
			Elem('socialbar').appendChild(
				newElem('button', { 'id' : 'add_plan' }, ' ')
			);
		}
		Elem('socialbar').appendChild(
			newElem('button', { 'id' : 'add_face' }, ' ')
		);
		Elem('socialbar').appendChild(
			newElem('button', { 'id' : 'add_tweet' }, ' ')
		);
		Elem('socialbar').appendChild(
			newElem('button', { 'id' : 'copy_url' }, ' ')
		);
		Elem('socialbar').appendChild(
			newElem('button', { 'id' : 'embed_html' }, ' ')
		);
		

		/* Adjust width of progressbar */
		var tw = Elem('progressholder').clientWidth || Elem('video').clientWidth - 240;
		//Elem('progressholder').style.width = tw + 'px';
		//Elem('progresstimer').style.width = tw + 'px';

		Elem('rtButtHolder').appendChild(
			newElem('div', { 'id' : 'volumecontrol' },
				newElem('div', { 'id' : 'volumepad' },
					newElem('div', { 'id' : 'volumevalue' })
				)
			)
		);

		Elem('overlay').style.width = this.width + 'px';
		Elem('overlay').style.height = this.height + 'px';

		var _this = this;
		Elem('volumepad').onclick = function(e) {
			if (!e) e = window.event;
			var xy = elem_xy(Elem('volumepad'));
			var vol  = (70 - (e.clientY - xy.y - 5)) / 70 * 100;
			_this.set_volume( vol );
		}

		this.show_volume = 0;
			Elem('mute').onmouseover = function(e) {
				_this.show_volume++;
				_this.show_hide_volume();
			}
			Elem('mute').onmouseout = function(e) {
				_this.show_volume--;
				_this.show_hide_volume();
			}
			Elem('volumecontrol').onmouseover = function(e) {
				_this.show_volume++;
				_this.show_hide_volume();
			}
			Elem('volumecontrol').onmouseout = function(e) {
				_this.show_volume--;
				_this.show_hide_volume();
			}
		/* BUTTONS */
		var _this = this;
		Elem('fsbutt').onclick = function(e) {
			if (_this.is_fullscreen) {
				_this.normalscreen();
			} else {	
				_this.fullscreen();
			}
		}
		Elem('mute').onclick = function(e) { 
			if (_this.muted()) {
				_this.unmute(); 
			} else {
				_this.mute(); 
			}
		}

		/* Copy URL */
		var diatext = [ 'Please press Ctrl+C to copy the URL to your clipboard.', br(), 'Then paste it wherever you want to share it' ];
		if (navigator.userAgent.indexOf("Mac") > 0) {
			diatext = [ 'Please press Command+C to copy the URL to your clipboard.', br(), 'Then paste it wherever you want to share it' ];
		}
		Elem('copy_url').onclick = function() {
			dialogue("Copy URL", [
				newElem('div', { 'style' : 'font-size: 12pt' }, diatext),
				br(),
				newElem('input', { 'type' : 'text', 'value' : window.location.href, 'id' : 'copyurl_text', 'readonly' : 'readonly' })
			], {
				'OK' : closeDialogue
			}, {
				onload : function() {
					Elem('copyurl_text').onclick = Elem('copyurl_text').select;
					Elem('copyurl_text').onmousemove = Elem('copyurl_text').select;
					Elem('copyurl_text').onfocus = Elem('copyurl_text').select;
					Elem('copyurl_text').focus();
				}
			});
		};
		/* Embed HTML */
		var diatext2 = [ 'Please press Ctrl+C to copy the HTML to your clipboard.', br(), 'Then paste it wherever you want to insert it.' ];
		if (navigator.userAgent.indexOf("Mac") > 0) {
			diatext2 = [ 'Please press Command+C to copy the HTML to your clipboard.', br(), 'Then paste it wherever you want to insert it.' ];
		}
		Elem('embed_html').onclick = function() {
			var embeddable = '<iframe src="' + baseurl + 'studio/playwin/' + _this.story_id + '" width="660" height="370" scrolling="no" frameborder="0"></iframe>';
			dialogue("Copy HTML to embed", [
				newElem('div', { 'style' : 'font-size: 12pt' }, diatext2 ),
				br(),
				newElem('input', { 'type' : 'text', 'value' : embeddable, 'id' : 'copyurl_text', 'readonly' : 'readonly' })
			], {
				'OK' : closeDialogue
			}, {
				onload : function() {
					Elem('copyurl_text').onclick = Elem('copyurl_text').select;
					Elem('copyurl_text').onmousemove = Elem('copyurl_text').select;
					Elem('copyurl_text').onfocus = Elem('copyurl_text').select;
					Elem('copyurl_text').focus();
				}
			});
		};
		/* Twitter */
		Elem('add_tweet').onclick = function(e) {
			var is_pause = _this.is_paused;
			_this.pause();
			new Twitter({
				label : "Tweet this story",
				content : "Have a look at this story on Create.tv " + baseurl + "s/" + _this.story_id + ' #createtv',
				onclose : function() {
					if (!is_pause) _this.play();
				}
			});
		};
		Elem('add_face').onclick = function(e) {
			window.open("http://www.facebook.com/sharer.php?u=" + baseurl + "s/" + _this.story_id , "fbshare", "width=652,height=372,resizable=no,scrollbars=no,toolbar=no,location=no,directories=no,status=no,menubar=no,copyhistory=no");
		};

		this.playbtn = Elem('playpause');
		this.progressbar = Elem('progressholder');
		this.setupPlayBtn();
		this.setupCommentBtn();
		this.setupPlanBtn();
		this.setupProgressbar();
		//this.setupSidebar();
		this.setupSidebar();
		this.setupPlaylist();
	},
	setupPlaylist : function() {

		if (!this.playlist) return;

		Elem(this.elemname).appendChild(
			newElem('div', { 'id' : 'playlistcontainer' },
				newElem('h2', {}, 'Current playlist'),
				newElem('table', { 'border' : '1', 'style': { 'borderCollapse' : 'collapse' }, 'id' : 'playlist' },
					newElem('tr', {}, 
						newElem('th', {}, '#'),
						newElem('th', {}, 'URL'),
						newElem('th', {}, 'Start'),
						newElem('th', {}, 'Offset'),
						newElem('th', {}, 'Duration')
					)
				)
			)
		);
		var start = 0;
		for (var i=0, ic=this.sources.length; i<ic; i++) {
			Elem('playlist').appendChild( newElem('tr', { 'id' : 'checkrow' + i }, 
				newElem('td', {}, String(i)),
				newElem('td', {}, this.sources[i].url),
				newElem('td', { 'align' : 'right' }, String(start)),
				newElem('td', { 'align' : 'right' }, String(this.sources[i].starttime)),
				newElem('td', { 'align' : 'right' }, this.sources[i].duration || 3)
			));
			start += Number(this.sources[i].duration);
		}
	},
	setupPlanBtn : function() {
		var _this = this;
		if (!Elem('add_plan')) return;
		Elem('add_plan').onclick = function(e) {
			if (Elem('commaddform')) return;
			_this.pause();
			_this.ctx_pause = true;
			var now = sprintf("%02d:%02d", _this.currtime / 60, _this.currtime % 60);
			if (_this.currtime >= 3600) {
				now = sprintf("%d:%02d:%02d", _this.currtime / 3600, (_this.currtime % 3600) / 60, _this.currtime % 60);
			}
			dialogue("Add plan entry at " + now, [
				newElem('textarea', { 'id' : 'comaddtext' }),
			], {
				'Submit' : function(e) {
					var time = _this.currtime;

					http_request("/studio/insert_plan", "POST", {
						story: _this.story_id,
						content: Elem('comaddtext').value,
						pos: time
					}, function(res) {
						warn("RESCALL");
						if (res.status == 'OK') {
							_this.info = res.info;
							closeDialogue();
							dialogue("Plan data submitted", "Plan data submitted", null, { 'onclose' : function(e) {
								Elem('socialbar').style.display = null;
								Elem('controlbar').style.display = null;
								_this.ctx_pause = false;
								_this.play();
							}});
							_this.sideContent();
						} else if (res.status == 'FORBIDDEN') {
							dialogue("Permission denied", "Sorry, you are not allowed to add plan entries to this story", null, { onclose : function(e) {
								Elem('socialbar').style.display = null;
								Elem('controlbar').style.display = null;
								_this.ctx_pause = false;
								_this.play();
							}});
						} else {
							dialogue("Server error", "Something went wrong. Try reloading and trying again", null, { onclose : function(e) {
								Elem('socialbar').style.display = null;
								Elem('controlbar').style.display = null;
								_this.ctx_pause = false;
								_this.play();
							}});
						}
					});
				},
				'Cancel' : closeDialogue
			}, {
				'onclose' : function(e) {
					Elem('socialbar').style.display = null;
					Elem('controlbar').style.display = null;
					_this.ctx_pause = false;
					_this.play();
				},
				'align' : 'center',
				'parent' : Elem('overlay')
			});
			Elem('socialbar').style.display = 'none';
			Elem('controlbar').style.display = 'none';
			Elem('comaddtext').focus();
		}
	},
	setupCommentBtn : function() {
		var _this = this;
		if (!Elem('add_comment')) return;
		Elem('add_comment').onclick = function(e) {
			if (Elem('commaddform')) return;
			_this.pause();
			_this.ctx_pause = true;
			dialogue("Add comment", [
				newElem('textarea', { 'id' : 'comaddtext' }),
			], {
				'Submit' : function(e) {
					http_request('/studio/add_comment/' + _this.story_id, 'GET', {
						offset : _this.currtime,
						comment : Elem('comaddtext').value
					}, function(res) {
						if (res.info) {
							_this.info = res.info
							_this.sideContent();
						}
					});
					closeDialogue();
				},
				'Cancel' : closeDialogue
			}, {
				'onclose' : function(e) {
					Elem('socialbar').style.display = null;
					Elem('controlbar').style.display = null;
					_this.ctx_pause = false;
					_this.play();
				},
				'align' : 'center',
				'parent' : Elem('overlay')
			});
			Elem('socialbar').style.display = 'none';
			Elem('controlbar').style.display = 'none';
			Elem('comaddtext').focus();
		}
	},
	setupSidebar : function() {
		/* Sidebar */
		if (!this.sidebar) {
			Elem(this.elemname).appendChild(
				newElem('div', { 'style' : { 'height' : this.height + 'px' } })
			);
			return;
		}
		Elem(this.elemname).appendChild(
			newElem('div', { 'class' : 'sidebar' },
				newElem('div', { 'class' : 'sidebarCont', 'id' : 'sidebarCont' },
						newElem('div', { 'id' : 'sidebarHeading' },
							newElem('b', {}, 'Sidebar')
						),
						newElem('div', { 'id' : 'sidebarControls' },
							newElem('button', { 'id' : 't_comments' }, ' '),
							newElem('button', { 'id' : 't_notes' }, ' '),
							newElem('button', { 'id' : 't_plan' }, ' ')
						),
						newElem('div', { 'id' : 'sidebarContent' },
							'More details here'
						)
				)
			)
		);
		for (var i=0, ic=Elem('sidebarControls').childNodes.length; i<ic; i++) {	
			var elem = Elem('sidebarControls').childNodes[i];
			if (elem.tagName != 'BUTTON') continue;

			if (this.active[ elem.id.substring(2) ]) {
				elem.setAttribute("class", "active");
				elem.className = "active";
			}
			
			var _this = this;
			elem.onclick = function(e) {
				if (!e) e = window.event;
				var elem = e.srcElement || e.currentTarget;
				if (elem.className == 'active') {
					elem.setAttribute("class", "");
					elem.className = "";
					_this.active[ elem.id.substring(2) ] = 0;
					_this.sideContent();
				} else {
					elem.setAttribute("class", "active");
					elem.className = "active";
					_this.active[ elem.id.substring(2) ] = 1;
					_this.sideContent();
				}
			}
		}
		this.sideContent();
	},
	sideContent : function() {
		var c = Elem('sidebarContent');
		if (!c) return;
		emptyElem(c);
		c = c.appendChild(newElem('div', { 'id' : 'sidebarBoxes' }));

		var scene = null;
		for (var i=0, ic=this.info.length; i<ic; i++) {
			// If not currently on (filters)
			if (!this.active[this.info[i].type]) continue;
			// Do not show empty entries
			if (!this.info[i].shortcontent) continue;
			if (this.info[i].shortcontent.length < 2) continue;
			// Do not show if not director and plan entry without time sync.
			if (this.info[i].type == 'plan' && !this.info[i].time && !this.is_director) continue;
			if (this.info[i].type == 'comments' && !this.info[i].time) continue;

			c.appendChild(
				newElem('div', { 'class' : 'infobox info' + this.info[i].type, 'id' : 'info' + i },
					newElem('div', { 'class' : 'authinfo' },
						newElem('span', { 'class' : 'infoboxwhen' }),
						newElem('span', { 'id' : 'ab_info' + i })
					),
					newElem('div', { 'id' : 'comment' + i, 'class' : 'commenttext' })
				)
			);
			var when = Elem('info' + i).childNodes[0].childNodes[0];
			if (this.info[i].type == 'plan') {
				if (!this.is_director) {
					Elem('ab_info' + i).appendChild(newElem('b', {}, 'Plan'));
					when.appendChild( newText(this.prettyTime( this.info[i].time )));
				} else { 
					Elem('ab_info' + i).appendChild(newElem('b', {}, 'Plan @ ' + this.prettyTime( this.info[i].time )));
					when.appendChild(newElem('button', { 'id' : 'pin' + i}, 'Set to now') );
					var _this = this;
					var _i = i;
					Elem('pin' + i).onclick = function(e) {
						if (!e) e = window.event;
						var elem = e.srcElement || e.currentTarget;
						var me = _this.info[elem.id.substring(3)];
						var ctime = _this.currtime;
						http_request("/studio/update_msec", 'GET', {
							topic: me.topic,
							name: me.name,
							row: me.row,
							msec: ctime * 1000
						}, function(res) {
							if (res.status == 'OK') {
								/* Update */
								var id = elem.id.substring(3);
								Elem('info' + id).style.opacity = 1;
								_this.info[id].time = ctime;
								_this.sideContent();
							} else {
								dialogue("Server error", "Something went wrong. Try reloading and trying again");
							}
						});
					};
				}
				if (!scene || scene != this.info[i].scene.id) {
					scene = this.info[i].scene.id;
					Elem('info' + i).insertBefore(
						newElem('h2', {}, this.info[i].scene.title),
						Elem('info' + i).childNodes[0]
					);
				}
				Elem('info' + i).style.display = 'block';
			} else if (this.info[i].type == 'notes') {
				emptyElem(when);
				when.appendChild(newElem('b', {}, 'NOTE'));
				Elem('info' + i).style.display = 'block';
			} else {
				if (this.info[i].time < this.currtime) 
					Elem('info' + i).style.display = 'block';

				//when.appendChild( newText( this.prettyTime( this.info[i].time, this.total_duration ) ) );
				var ws = newElem('span', { 'class' : 'seek' + this.info[i].time }, this.prettyTime( this.info[i].time, this.total_duration ) ) 
				when.appendChild( ws );
				var _time = this.info[i].time;
				var _this = this;
				ws.style.color = '#333399';
				ws.onclick = function(e) {
					if (!e) e = window.event;
					var elem = e.srcElement || e.currentTarget;
					var tm = elem.className.substring(4);
					_this.seek( tm );
				}
					
				Elem('ab_info' + i).appendChild(
					newElem('a', { 'href' : '/profile/' + this.info[i].username },
						newElem('img', { 'src' : this.info[i].image, 'width' : 16, 'height' : 16, border: 0 }),
						' ',
						this.info[i].username
					)
				);
			}
			var con = this.info[i].shortcontent;
			if (this.info[i].title) {
				Elem('ab_info' + i).appendChild(
					newElem('b', {}, this.info[i].title)
				);
			}
			if (this.info[i].time <= this.currtime) {
				Elem('info' + i).style.opacity = 1;
			}
			if (this.info[i].more) {
				con = con + " <a href='#' id='commlink" + i + "'>More</a>";
				Elem('comment' + i).innerHTML = con;
				var fullcon = this.info[i].content;
				var idx = i;
				Elem('commlink' + i).onclick = function(e) {
					Elem('comment' + idx).innerHTML = fullcon;
				};
			} else {
				Elem('comment' + i).innerHTML = con;
			}
			if (this.info[i].urls && this.info[i].urls.length) {
				Elem('info' + i).appendChild(
					newElem('ul', { 'class' : 'infourls', 'id' : 'infourls' + i },
						newElem('li', {}, newElem('b', {}, 'Links:') )
					)
				);
				for (var j=0, jc=this.info[i].urls.length; j<jc; j++) {
					var url = this.info[i].urls[j];
					Elem('infourls' + i).appendChild(
						newElem('li', {}, 
							newElem('a', { 'href' : url, 'target' : '_blank' }, url)
						)
					);
				}
			}
		}
	},
	set_volume : function(vol) {
		vol = Math.floor(vol);
		this.volume = vol;
		this.show_hide_volume();
		if (this.is_muted) this.unmute();
		if (2) {
			if (window.soundManager) {
				soundManager.setVolume('video', vol);
				soundManager.setVolume('bgsound', vol);
				soundManager.defaultOptions.volume = vol;
			}
		}
		if (this.ymoplayer) {
			this.ymoplayer.setVolume(vol);
		}
		if (this.player == 'html5') 
			this.elem.volume = vol/100;
	},
	show_hide_volume : function() {
		if (this.show_volume) {
			//Elem('mute').style.background = 'red';
			Elem('volumevalue').style.height = this.volume/100 * 70 + 'px';
			Elem('volumecontrol').style.display = 'block';
		} else {
			//Elem('mute').style.background = 'yellow';
			Elem('volumecontrol').style.display = 'none';
		}
	},

	load_ymoplayer : function() {
		if (!Elem('ymoplay')) {
			document.getElementsByTagName("BODY")[0].appendChild(
				newElem('div', { 'id' : 'ymoplay' })
			);
		}
		var _this = this;
		setTimeout(function() {
			warn("FS = " + _this.load_fullscreen);
			if (_this.load_fullscreen && 0 ) {
				swfobject.embedSWF(baseurl + "flash/vid.swf", 'ymoplay', document.documentElement.clientWidth, document.documentElement.clientHeight, "9.0.124", false, {}, { 'wmode' : 'opaque' } );
			} else {
				swfobject.embedSWF(baseurl + "flash/vid.swf", 'ymoplay', _this.width, _this.height, "9.0.124", false, {}, { 'wmode' : 'opaque' } );
			}
		}, 100);
		this.wait_ymoplayer();
	},
	wait_ymoplayer : function() {
		var _this = this;
		if (Elem('ymoplay').load) {
			this.objects_loaded['ymoplayer'] = 1;
			this.ymoplayer = Elem('ymoplay');
		} else {
			setTimeout(function() {
				_this.wait_ymoplayer();
			}, 200);
		}
	},

	load_sm2 : function() {
		require(baseurl + "js/soundmanager2.js");
		this.wait_sm2();
	},

	wait_sm2 : function() {
		var _this = this;
		if (!window.SoundManager) {
			setTimeout(function() {
				_this.wait_sm2();
			}, 200);
			return;
		}
		if (!window.soundManager) {
			window.soundManager = new SoundManager();
			soundManager.beginDelayedInit();
			setTimeout(function() {
				_this.wait_sm2();
			}, 200);
			return;
		}
		if (!soundManager._didInit) {
			setTimeout(function() {
				_this.wait_sm2();
			}, 200);
			return;
		}
		if (!soundManager.o) {
			setTimeout(function() {
				_this.wait_sm2();
			}, 200);
			return;
		}
		if (!soundManager.o._createSound) {
			setTimeout(function() {
				_this.wait_sm2();
			}, 200);
			return;
		}
		soundManager.url = '/flash/';
		soundManager.flashVersion = 9;
		soundManager.useMovieStar = true;
		soundManager.allowFullScreen = true;
		soundManager.debugMode = false;

		_this.objects_loaded['sm2'] = 1;
	},

	load_players : function(fn) {
		if (this.use_flash) {
			this.load_ymoplayer();
			this.wait_sm2();
			this.wait_objects(['ymoplayer', 'sm2'], fn);
			return;
		}
		fn();
	},

	wait_objects : function(keys, fn) {
		var ok = 1;
		for (var i=0, ic=keys.length; i<ic; i++) {
			if (!this.objects_loaded[keys[i]]) {
				//warn("Waiting for " + keys[i]);
				ok = 0;
			}
		}
		if (!ok) {
			var _this = this;
			setTimeout(function() {
				_this.wait_objects(keys, fn);
			}, 200);
			return;
		}
		fn();
	},

	preload : function() {
		com.updatefrequence = 0;
		window.in_preload = 1;
		var start = 0;
		if (this.idx) start = this.idx + 1;
		var end = this.sources.length;
		if (end > start + 5) end = start + 5; 
		for (var i=start; i<end; i++) {
			var source = this.sources[i];
			//warn("Preloading " + source.url);
			var pic1;
			if (source.type == 'image' || source.type == 'audio' || !this.use_flash) {
				pic1 = new Image(100,25); 
				if (source.type == 'audio') {
					this.waitaudio = 1;
					var _this = this;
					pic1.onload = function() {
						_this.waitaudio = 0;
					};
				}
				pic1.src = this.sources[i].url; 
				this.cache.push(pic1);
			} else {
				this.ymoplayer.preload({ 
					src: source.url,
					width: this.sources[i].width || Elem('overlay').clientWidth,
					height: this.sources[i].height || Elem('overlay').clientHeight
				});
			}
		}
		//warn("PreloadEND");
		//if (this.ymoplayer) warn(this.ymoplayer.load);
		window.in_preload = 0;
	},

	loadVideo : function(offset, command) {
		com.updatefrequence = 0;
		var _this = this;
		if (window.in_preload) {
			setTimeout(function() { _this.loadVideo(offset, command) }, 100);
			return;
		}
		this.faketimer = 0;
		this.is_loading = true;
		if (this.ymoplayer) {
			this.ymoplayer.style.top = _this.width + 'px';
			this.ymoplayer.marginTop = '-2000px';
		}
		if (this.playlist) {
			if (this.oldidx != null) {
				if (Elem('checkrow' + this.oldidx)) {
					Elem('checkrow' + this.oldidx).style.background = 'white';
					Elem('checkrow' + this.oldidx).style.color = 'black';
				}
			}
			if (Elem('checkrow' + this.idx)) {
				Elem('checkrow' + this.idx).style.background = 'black';
				Elem('checkrow' + this.idx).style.color = 'white';
				this.oldidx = this.idx;
			}
		}
		if (this.idx >= this.sources.length) {
			return null;
		}
		if (this.snd) {
			this.snd.destruct();
			this.snd = null;
			if (2) soundManager.oMC.style.width = '1px';
		}
		var s = this.sources[ this.idx ];
		if (!s.starttime) s.starttime = 0;
		if (!s.duration) s.duration = 3;
		if (!s.type) s.type = 'video';
		var vid = null;
		if (s.type == 'video') {
			if (this.use_flash) {
				vid = newElem('div', { 'id' : 'video', 'class' : 'player' });
				this.player = 'ymoplayer';
			} else {
				vid = newElem('video', { 'id' : 'video', 'autobuffer' : 'autobuffer', 'preload' : 'auto', 'height' : this.height, 'width' : this.width, 'class' : 'player', 'style' : { 'float' : 'left', 'display' : 'block' } },
					newElem('source', { 'src' : s.url })
				);
				this.player = 'html5';
			}
		} else if (s.type == 'image') {
			var width = this.width;
			var height = this.height;
			vid = newElem('img', { 'id' : 'video', 'height' : height, 'width' : width, 'class' : 'player', 'style' : { 'float' : 'left', 'display' : 'block' }, 'src' : s.url });
			this.player = 'html4';
		} else if (s.type == 'audio') {
			if (this.use_flash) {
				vid = newElem('div', { 'id' : 'video', 'class' : 'viderror player' },
					newElem('div', {}, "Sound playing")
				);
				this.player = 'html4';
				var sndpars = {
					id : 'video',
					url : s.url,
					autoplay : true,
					position: s.starttime * 1000,
					autoPlay : true,
					volume : 100
				};
				if (this.is_muted) sndpars.volume = 0;
					if (2) {
						var snd = soundManager.createSound(sndpars);
						this.snd = snd; 
					}
			} else {
				vid = newElem('audio', { 'id' : 'video', 'height' : this.height, 'preload' : 'auto', 'width' : this.width, 'class' : 'player', 'style' : { 'float' : 'left', 'display' : 'block' }, 'src' : s.url },
					newElem('source', { 'src' : s.url })
				);
				this.player = 'html5';
			}
		} else {
			vid = newElem('div', { 'id' : 'video', 'class' : 'viderror player' },
				newElem('div', {}, "Media type not recognized")
			);
			this.player = 'html4';
		}
		var v = Elem('video');
		v.parentNode.insertBefore(vid, v);

		var trans = s.transition || this.transition || 'none';
		//trans = '';
		if (trans == 'fade' && !offset) {
			if (Elem('oldvideo')) {
				Elem('oldvideo').parentNode.removeChild( Elem('oldvideo') );
			}
			v.setAttribute("id", 'oldvideo');
			fade('video','oldvideo', 0);
		} else {
			v.parentNode.removeChild(v);
		}
		if (this.player == 'ymoplayer') {
			var offset = s.starttime + ( offset || 0);

			this.ymoplayer.style.top = '10px';
			this.ymoplayer.marginTop = '0px';
			this.ymoplayer.style.width = Elem('overlay').clientWidth + 'px';
			this.ymoplayer.style.height = Elem('overlay').clientHeight + 'px';
			this.ymoplayer.load({
				idx : this.idx,
				url : s.url,
				duration : s.duration,
				starttime : offset || 0,
				width: s.width || Elem('overlay').clientWidth,
				height: s.height || Elem('overlay').clientHeight,
				label : "Video"
			});
			if (this.is_muted) this.ymoplayer.mute();
		}
		this.elem = vid;
		this.playoffset = offset || 0;
		this.starttime = s.starttime || 0;
		this.duration = s.duration || 3;
		this.faketime = 0;
		if (this.player == 'html5') {
			//warn("SDASDSA");
			this.setupListeners();
		}

		this.is_loading = false;

		if (this.progressbar)
			this.setupProgressbar();
		if (this.playbtn) 
			this.setupPlayBtn();

		if (command == 'play') { // && this.player != 'ymoplayer') {
			this.play();
		}
		this.preload();
	},
	setupPlayBtn : function() {
		var _this = this;
		this.playbtn.onclick = function(e) { 
			if (_this.is_paused) {
				_this.play(); 
				//Elem('playpause').style.border = '1px solid black';
				//Elem('playpause').style.background = 'black';
				Elem('playpause').style.backgroundImage = 'url(/images/pause.png)';
			} else {
				_this.pause(); 
				//Elem('playpause').style.border = '1px solid black';
				//Elem('playpause').style.background = 'gray';
				//Elem('playpause').style.color = 'white';
				Elem('playpause').style.backgroundImage = 'url(/images/player_play.png)';
			}
		};
	},
	setupProgressbar : function() {
		var _this = this;
		this.progressbar.onclick = function(e) {
			var xy = elem_xy(_this.progressbar);
			if (!e.x) e.x = e.clientX;
			var pos = _this.total_duration * (e.x - xy.x) / Elem('progressholder').clientWidth;

			if (_this.is_paused) {
				_this.seek(pos);
			} else {
				_this.seek(pos,'play');
			}
		};
	},
	seek : function(pos, action) {
		//warn("SEEK TO " + pos);
		if (Elem('oldvideo')) Elem('oldvideo').style.display = 'none';
		var idx = 0;
		var offset = 0;
		var done = 0;
		var is_paused = this.is_paused;
		this.pause();
		for (var i=0, ic=this.sources.length; i<ic; i++) {
			var s = this.sources[i];
			s.duration = Number(s.duration) || 3;
			//warn("POS " + pos + " DONE " + done + " DUR " + s.duration);
			if (pos > done + s.duration) {
				done += s.duration;
				continue;
			}
			idx = i;
			offset = pos - done;
			break;
		}
		//warn("index " + idx + " at offset " + offset);
		//warn(pos);
		if (this.faketimer_timeout) clearTimeout(this.faketimer_timeout);
		this.idx = idx;
		this.playedtime = done;
		this.updateProgress(idx, this.playoffset);
		this.faketimer = 0;

		/* BG sound */
		if (this.use_flash) {
			/* sm2 */
		} else if (Elem('bgsound')) {
			Elem('bgsound').currentTime = 0;
		}

		this.currtime = pos;
		this.sideContent();

		if (action && action == 'play') {
			this.loadVideo(offset, 'play');
		} else {
			this.loadVideo(offset);
		}
	},
	faketimerupdate : function(idx, msecs) {
		if (this.faketimer_timeout) clearTimeout(this.faketimer_timeout);
		if (!this.faketimer) return;
		if (this.idx != idx) return;
		if (this.is_paused) return;
		if (!msecs) msecs  = 0;
		this.faketime = this.faketime + msecs;
		//warn("FAKE");
		this.updateProgress(idx,  this.playoffset + this.faketime/1000 );
		var _this = this;
		var _idx = idx;
		//warn("Call func " + idx + " and 100");
		this.faketimer_timeout = setTimeout(function(idx) {
			//warn("IDX = " + _this.idx);
			//warn("Setting up FTU for " + _this.idx + " and 100");
			_this.faketimerupdate(_this.idx, 100);
		}, 100);
	},
	prettyTime : function(secs, total) {
		if (!total || total < secs) total = secs;
		if (total > 3600) {
			return sprintf("%d:%02d:%02d", secs/3600, (secs % 3600)/60, secs % 60);
		} else {
			return sprintf("%2d:%02d", secs/60, secs % 60);
		}
	},
	updateTimer : function(played,total) {
		if (total > 3600) {
			Elem('progresstimer').innerHTML = sprintf("%d:%02d:%02d / %d:%02d:%02d", 
				played / 3600,
				(played % 3600) / 60,
				played % 60, 
				total / 3600,
				(total % 3600) / 60,
				total % 60
			);
		} else if (total > 60) {
			Elem('progresstimer').innerHTML = sprintf("%2d:%02d / %2d:%02d", 
				played / 60,
				played % 60, 
				total / 60,
				total % 60
			);
		} else {
			Elem('progresstimer').innerHTML = sprintf("%.2f / %.2f", played, total);
		}
	},
	updateProgress : function( idx, time ) {
		if (time) {
		  if (this.lasttime && this.lasttime == time) return;
		  //warn("THis.lasttime " + this.lasttime + " cs " + time);
		  this.lasttime = time;
		}
		if (!Elem('progressholder')) {
			this.mute();
			this.pause();
			return;
		}
		var tw = Elem('progressholder').clientWidth || Elem('video').clientWidth - 240;
		if (!time) time = 0;
		//warn("Played " + this.playedtime + " - this.starttime " + this.starttime + " time : " + time + " dur : " + this.total_duration);
		var w = Math.floor(tw * ( this.playedtime + time - (this.starttime || 0) ) / this.total_duration);
		if (w > tw) w = tw;
		Elem('progress').style.width = w + 'px';
		//Elem('progressholder').style.width = tw + 'px';
		//Elem('progresstimer').style.width = tw + 'px';

		this.updateTimer(this.playedtime + time - this.starttime, this.total_duration);

		this.currtime = this.playedtime + time - this.starttime;
		for (var i=0, ic=this.info.length; i<ic; i++) {
			if (this.info[i].time <= this.currtime) {
				if (!Elem('info' + i)) continue;
				Elem('info' + i).style.opacity = 1;
				if (Elem('info' + i).style.display != 'block') {
					Elem('info' + i).style.display = 'block';
					/* Move this outside this IF to auto-scroll */
					var xy = local_elem_xy(Elem('info' + i));
					xy.y = xy.y - Elem('sidebarContent').clientHeight + Elem('info' + i).clientHeight;
					Elem('sidebarContent').scrollTop = xy.y;
				}
			}
		}
		if (time - this.starttime >= this.duration) {
			if (0 && this.idx < this.sources.length - 1) {
			  this.seek(this.playedtime + time - (this.starttime || 0) + 0.1, 'play');
			  return;
			}
			//warn("IDX " + this.idx + " VS " + idx);
			//warn("Reached the end as " + time + " - " + this.starttime + " >= " + this.duration);
			if (this.player == 'html5') this.elem.pause();
			if (this.ymoplayer) this.ymoplayer.pause();
			this.next();
		}
	},
	setupListeners : function() {
		var _this = this;
		this.elem.addEventListener("loadeddata", function() {
			if (_this.is_muted) _this.elem.muted = true;
			/*warn('-----s');
			warn(_this.starttime);
			warn(_this.playoffset);
			warn(_this.elem);
			warn( _this.starttime + (_this.playoffset || 0));*/
			_this.elem.currentTime = _this.starttime + (_this.playoffset || 0);
		}, true);
		var _idx = this.idx;
		this.elem.addEventListener('ended', function(e) {
			if (_idx == _this.idx) /* If we don't do this, in some rare cases it'll jump twice */
			  _this.next();
		}, true);
		this.elem.addEventListener("timeupdate", function(e) {
			if (!e) e = window.event;
			var elem = e.srcElement || e.currentTarget;
			//warn(elem);
			//_this.faketimer = 0;
			//warn(_this.faketimer);
			//warn("TIMER");
			_this.updateProgress( _idx, _this.elem.currentTime );
		}, true);
	},
	next : function() {
		this.faketimer = 0;
		this.playedtime += Number(this.sources[this.idx].duration);
		this.idx++;
		if (this.sources.length <= this.idx) {
			this.idx = 0;
			this.playedtime = 0;
			this.loadVideo();
			this.pause();
			Elem('progress').style.width = '0px';
			this.updateTimer(0, this.total_duration);
			return;
		}
		this.loadVideo(0, 'play');
	},
	load_bgsound : function() {
		if (this.waitaudio) return;
		if (this.bgsound) {
			if (this.use_flash) {
				this.bgsnd = soundManager.createSound({
					id : 'bgsound',
					url : this.bgsound.url,
					autoplay : true,
					position: (this.currtime || 0) * 1000,
					autoPlay : true,
					volume : 100
				});
			} else {
				if (!Elem('bgsound')) {
					//warn("AUDIO ****");
					var bg = newElem('audio', { 'id' : 'bgsound', 'preload' : 'auto', 'src' : this.bgsound.url },
						newElem('source', { 'src' : this.bgsound.url })
					);
					var _this = this;
					bg.onload = function() {
						if (!e) e = window.event;
						var elem = e.srcElement || e.currentTarget;
						_this.waitaudio = 0;
						elem.currentTime = _this.currtime || 0;
						elem.play();
					};
					bg.src = this.bgsound.url;
					Elem('player').appendChild( bg );
					//warn('rs ' + bg.readyState);
					if (bg.readyState < 4) {
						this.waitaudio = 1;
					} else {
						elem.play();
					}
					//warn("SEEK " + this.currtime);
				} else {
					/* Uncomment next line to synchronise background audio
					 * Note that this may lead to a more uneven playback of the
					 * audio if time is spent loading videos etc. */

					//Elem('bgsound').currentTime = this.currtime || 0;

					/* Instead, make sure it's set to the beginning for the first
					 * asset (otherwise just continues if you play again) */

					if (this.idx == 0 && (!this.currtime || this.currtime == 0)) Elem('bgsound').currentTime = 0;
					Elem('bgsound').play();
				}
			}
		}
	},
	play : function(ff) {
		com.updatefrequence = 0;
		/* Wait till buffered and ready to play */
		this.load_bgsound();
		//warn("WaitAudio " + this.waitaudio);

		/* HTML 5 */
		if (this.waitaudio && Elem('bgsound') && Elem('bgsound').readyState && Elem('bgsound').readyState == 4) {
			this.waitaudio = 0;
		}
		/* FLASH */
		if (this.use_flash && this.bgsound && this.bgsound.url && this.bgsnd) {
			if (this.bgsnd.loaded) {
				this.waitaudio = 0;
			} else {
				this.waitaudio = 1;
			}
		}

		if (this.ymoplayer && (!this.ymoplayer.isReady || !this.ymoplayer.isReady()) || this.waitaudio) {
			Elem('loader').style.display = 'block';
			var _this = this;
			setTimeout(function() { _this.play('1'); }, 100);
			return;
		}
		if (Elem('bgsound')) Elem('bgsound').play();
		//if (this.ymoplayer) warn("ISREADY => " + this.ymoplayer.isReady());
		Elem('loader').style.display = 'none';
		if (this.is_loading) {
			var _this = this;
			setTimeout(function() { _this.play(); }, 100);
			return;
		}

		this.is_paused = false;
		//warn(this.player);
		if (this.player == 'html5') {
			this.elem.play();
		} else if (this.player == 'ymoplayer') {
			/* Originally called play; IE doesn't support that so doplay it is */
			this.ymoplayer.doplay();
		} else {
			this.faketimer = 1;
			//warn("FAKETIMER");
			this.faketimerupdate(this.idx);
		}
		if (this.playbtn) {
			Elem('playpause').style.backgroundImage = 'url(/images/pause.png)';
		}
	},
	pause : function() {
		if (this.faketimer_timeout) clearTimeout(this.faketimer_timeout);
		if (this.bgsnd) {
			this.bgsnd.destruct();
			this.bgsnd = null;
		}
		if (Elem('bgsound')) {
			//warn('pause');
			Elem('bgsound').pause();
		}
		if (this.player == 'html5') {
			this.elem.pause();
		} else if (this.player == 'ymoplayer') {
			this.ymoplayer.pause();
		}
		this.is_paused = true;
		/*if (this.playbtn) {
			emptyElem(this.playbtn);
			this.playbtn.appendChild(newText('Play'));
		}*/
		if (this.playbtn) {
			Elem('playpause').style.backgroundImage = 'url(/images/player_play.png)';
		}
	},
	paused : function() {
		return this.elem.paused;
	},
	mute : function() {
		if (this.player == 'html5') {
			this.elem.muted = true;
		}
		if (this.snd) this.snd.mute();
		if (this.bgsnd) this.bgsnd.mute();
		if (this.ymoplayer) this.ymoplayer.mute();
		//Elem('mute').style.border = '1px solid black';
		//Elem('mute').style.background = 'gray';
		//Elem('mute').style.color = 'white';
		if (Elem('mute')) Elem('mute').style.opacity = '0.5';
		this.is_muted = true;
	},
	unmute : function() {
		if (this.player == 'html5') {
			this.elem.muted = false;
		}
		if (this.snd) this.snd.unmute();
		if (this.bgsnd) this.bgsnd.unmute();
		if (this.ymoplayer) this.ymoplayer.unmute();
		//Elem('mute').style.border = '1px solid black';
		//Elem('mute').style.background = 'black';
		Elem('mute').style.opacity = '1';
		this.is_muted = false;
	},
	muted : function() {
		if (this.player == 'html5') {
			return this.elem.muted;
		}
		return this.is_muted;
	},
	fullscreen : function() {
		// -- STOPS playback in Firefox(!)
		// Elem('overlayholder').style.position = 'fixed';
		var xy = elem_xy(Elem('overlayholder'));
		var w = document.documentElement.clientWidth;
		var h = document.documentElement.clientHeight;

		//if (this.is_firefox) {
		if (navigator.userAgent.indexOf("Firefox") > 0) {
			/* Flash stops working in FF if we do overflow hidden or fixed positioning */
			h = h - 20;
		} else {
			document.getElementsByTagName("BODY")[0].style.overflow = 'hidden';
		}
		Elem('overlayholder').style.left = -xy.x + 'px';
		Elem('overlayholder').style.right = '0px';
		Elem('overlayholder').style.bottom = '0px';
		Elem('overlayholder').style.top = -xy.y + 'px';

	/* Break out of confines */
		this.parelem = Elem('overlayholder').parentNode;
		var ovh = Elem('overlayholder');
		if (0) {
			this.parelem.removeChild( ovh );
			document.getElementsByTagName("BODY")[0].appendChild( ovh);
		} else {
			var parElem = this.parelem;
			parElem.style.marginTop = '-10px';
			parElem.style.marginLeft = '-20px';

			if (Elem('innerbasewin')) {
				this.oldx = Elem('innerbasewin').clientWidth;
				this.oldy = Elem('winCont').clientHeight;

				Elem('winCont').style.top = '0px';
				Elem('winCont').style.left = '0px';
				Elem('winCont').style.right = '0px';
				Elem('winCont').style.bottom = '0px';
				Elem('winCont').style.height = '100%';

				Elem('innerbasewin').style.width = '100%';
				Elem('innerbasewin').style.height = '100%';
				Elem('innerbwin').style.display = 'none';

				Elem('baseWindow').style.top = '0px';
				Elem('baseWindow').style.bottom = '0px';
			} else {
				var xy = elem_xy(parElem);
				parElem.style.marginTop = '-' + (xy.y + 10) + 'px';
				parElem.style.marginLeft = '-' + (xy.x + 20) + 'px';
				window.scroll(0,0);
			}
			if (Elem('dock')) Elem('dock').style.display = 'none';
			if (Elem('redock')) Elem('redock').style.display = 'none';
			var sb = getElementsByClass('sidebar')[0]
			if (sb && sb.length) sb[0].style.display = 'none';
		}
		ovh.style.zIndex = 999999999;
		//ovh.style.position = 'absolute';
		ovh.style.left = '0px';
		ovh.style.top = '0px';
	/* -- END */

		if (w/this.width < h/this.height) {
			Elem('overlay').style.width = w + 'px';
			Elem('overlay').style.height = (w/this.width) * this.height + 'px';
			Elem('overlay').style.top = (h - (w/this.width * this.height))/2 + 'px';
		} else {
			Elem('overlay').style.height = h + 'px';
			Elem('overlay').style.width = (h/this.height) * this.width + 'px';
			Elem('overlay').style.left = (w - (h/this.height * this.width))/2 + 'px';
		}

		Elem('overlayholder').style.width = w + 'px';
		Elem('overlayholder').style.height = h + 'px';
		//Elem('fsbutt').style.border = '1px solid black';
		//Elem('fsbutt').style.background = 'gray';
		//Elem('fsbutt').style.color = 'white';
		Elem('fsbutt').style.backgroundImage = 'url(/images/smallscreen.png)';
		Elem('overlay').style.border = 'none';

		var maxx = Elem('overlay').clientWidth;
		if (maxx > w) maxx = w;
		var maxy = Elem('overlay').clientHeight;
		if (maxy > h) maxy = h;

		if (this.ymoplayer) {
			this.ymoplayer.style.width = maxx + 'px';
			this.ymoplayer.style.height = maxy + 'px';
		}
		if (Elem('video')) {
			Elem('video').style.width = maxx + 'px';
			Elem('video').style.height = maxy + 'px';
		}
		/* Hide presence when in fullscreen (overlaps) */
		if (Elem('presence')) Elem('presence').style.display = 'none';

		this.is_fullscreen = true;
	},
	normalscreen : function() {
		if (this.load_fullscreen) {
			window.close();
		}
		var ovh = Elem('overlayholder');
		if (0) { 
			ovh.parentNode.removeChild( ovh );
			this.parelem.insertBefore( ovh, this.parelem.childNodes[0] );
		} else { 
			var parElem = this.parelem;
			parElem.style.marginTop = '0px';
			parElem.style.marginLeft = '0px';
			if (Elem('innerbasewin')) {
				Elem('innerbasewin').style.width = this.oldx + 'px';
				Elem('innerbasewin').style.height = '400px';
				Elem('innerbwin').style.display = 'block';
				Elem('baseWindow').style.bottom = '140px';
			} else {
				var xy = elem_xy(parElem);
				parElem.style.marginTop = '0px';
				parElem.style.marginLeft = '0px';
				window.scroll(0,0);
			}

			if (Elem('redock')) Elem('redock').style.display = 'block';
			if (Elem('dock')) Elem('dock').style.display = 'block';
			var arr = getElementsByClass('sidebar');
			if (arr && arr.length) arr[0].style.display = 'block';
		}
		ovh.style.position = 'relative';
		ovh.style.left = '0px';
		ovh.style.top = '0px';
	/* -- END */
		//Elem('overlayholder').style.position = 'relative';
		Elem('overlayholder').style.left = '0px';
		Elem('overlayholder').style.right = '0px';
		Elem('overlayholder').style.float = 'left';
		Elem('overlayholder').style.bottom = '0px';
		Elem('overlayholder').style.top = '0px';
		Elem('overlayholder').style.width = this.width + 'px';
		Elem('overlayholder').style.height = 'auto';
		Elem('overlay').style.top = '0px';
		Elem('overlay').style.left = '0px';
		Elem('overlay').style.width = this.width + 'px';
		Elem('overlay').style.height = this.height + 'px';
		Elem('overlay').style.border = '2px solid black';
		Elem('overlay').style.borderLeft = '8px solid black';
		Elem('overlay').style.borderRight = '0px solid black';
		//Elem('fsbutt').style.border = '1px solid black';
		//Elem('fsbutt').style.background = 'black';
		Elem('fsbutt').style.backgroundImage = 'url(/images/fullscreen.png)';
		if (this.ymoplayer) {
			this.ymoplayer.style.width = Elem('overlay').clientWidth + 'px';
			this.ymoplayer.style.height = Elem('overlay').clientHeight + 'px';
		}
		if (Elem('video')) {
			Elem('video').style.width = Elem('overlay').clientWidth + 'px';
			Elem('video').style.height = Elem('overlay').clientHeight + 'px';
		}

		/* Hide presence when in fullscreen (overlaps) */
		if (Elem('presence')) Elem('presence').style.display = 'block';

		this.is_fullscreen = false;
			winAdjustHeight();
	}
};

document.onkeydown = function(e) {
	if (!e) e = window.event;
	var elem = e.srcElement || e.currentTarget;

	if (!window.player) return;

	if (player.ctx_pause) return;
	
	if (e.keyCode == 27 && player.is_fullscreen) { /* Escape = exit full screen */
		player.normalscreen();
	}
	if (e.keyCode == 13) { /* Return = back to beginning */
		if (player.is_paused) {
			player.seek(0);
		} else {
			player.seek(0, 'play');
		}
	}
	if (e.keyCode == 32) { /* Space = pause */
		if (player.is_paused) {
			player.play();
		} else {
			player.pause();
		}
	}
};


function flashwarn(what) {	
	warn(what);
}

function statehandler(what, url) {
	warn("Statehandler " + what);
	if (what == 'FLV_COMPLETE') {
		player.next();
	}
	if (what.indexOf("Error") > 0) {
		alert("ERROR: " + what + " on " + url);
	} 
	//warn("State (" + url + ") => " + what);
}

function ontimechange(idx, time) {
	if (time == 0) return;
	if (player.idx != idx) return;
	/* Some times starts marginally before start time, don't make playhead jump back */
	if (time < player.starttime) time = player.starttime;
	//warn("UPDPROG " + idx + " TIME " + time);
	player.updateProgress(idx, time);
}
