var VideoPlayer = new Class({
	options: {
		width: 275,
		height: 226,
		autostart: false,
		playerTarget: 'player',
		playerSWF: 'flvplayer.swf',
		playlist: ''
	},
	initialize: function(options){
		this.setOptions(options);		
		$$('a').forEach(function(elem) {
			if (elem.rel == 'video') {
				elem.href = '#';
				if (elem.getAttribute('flv')) {
					elem.addEvent('click', this.play_flv.bind(this, elem.getAttribute('flv')));
				} else if (elem.getAttribute('playlist_item')) {
					elem.addEvent('click', this.goto_item.bind(this, elem.getAttribute('playlist_item')));
				}				
			}
		}, this);
	},	
	play_flv: function(url_flv) {
		var file = this.options.playlist;
		if (url_flv)
			file = url_flv;		
		
		var so = new SWFObject(this.options.playerSWF, "mpl", this.options.width, this.options.height, '7');
		so.addParam('allowfullscreen', 'true');
		so.addParam('allowscriptaccess', 'true');
		so.addVariable('file', file);
		so.addVariable('height', this.options.height);
		so.addVariable('width', this.options.width);
		so.addVariable('autostart', this.options.autostart);
		so.addVariable('repeat', 'list');
		so.addVariable('shuffle', 'false');
		so.addVariable("enablejs","true");
		so.addVariable("javascriptid","mpl");
		so.write(this.options.playerTarget);
	},
	goto_item: function(item) {
		sendEvent("playitem", item);
	}
});
VideoPlayer.implement(new Options, new Events);


// some variables to save
var currentPosition;
var currentVolume;
var currentItem;

// these functions are caught by the JavascriptView object of the player.
function sendEvent(typ,prm) { thisMovie("mpl").sendEvent(typ,prm); };
function getUpdate(typ,pr1,pr2,pid) {
	if(typ == "time") { currentPosition = pr1; }
	else if(typ == "volume") { currentVolume = pr1; }
	else if(typ == "item") { currentItem = pr1; setTimeout("getItemData(currentItem)",100); }
	var id = document.getElementById(typ);
	id.innerHTML = typ+ ": "+Math.round(pr1);
	pr2 == undefined ? null: id.innerHTML += ", "+Math.round(pr2);
	if(pid != "null") {
		document.getElementById("pid").innerHTML = "(received from the player with id <i>"+pid+"</i>)";
	}
};

// These functions are caught by the feeder object of the player.
function loadFile(obj) { thisMovie("mpl").loadFile(obj); };
function addItem(obj,idx) { thisMovie("mpl").addItem(obj,idx); }
function removeItem(idx) { thisMovie("mpl").removeItem(idx); }
function getItemData(idx) {
	var obj = thisMovie("mpl").itemData(idx);
	var nodes = "";
	for(var i in obj) { 
		nodes += "<li>"+i+": "+obj[i]+"</li>"; 
	}
	document.getElementById("data").innerHTML = nodes;
};

// This is a javascript handler for the player and is always needed.
function thisMovie(movieName) {
    if(navigator.appName.indexOf("Microsoft") != -1) {
		return window[movieName];
	} else {
		return document[movieName];
	}
};