
/****************************************************************************

  This file is part of the EnemyTerritory.tv Content Management System

	EnemyTerritory.tv CMS by Steve "GreasedScotsman" Huff, 
	Copyright 2009 Steve Huff
	
	It is distributed under the terms of the 
	GNU General Public License

	This code is adapted from andersen's "Annotation Display" example:
	
	http://home5.inet.tele.dk/nyboe/flash/mediaplayer/

	and modified to take in parameters that append info to the 
	"file" value.  This "file" value uses JavaScript's 
	encodeURIComponent() to call a PHP page that dynamically 
	builds an XPSF text/xml playlist based on the parameters passed 
	to createPlayer().
 
	See "data/playlist_MySQL.php" for more info on how the
	XPSF text/xml playlist is generated.
		
***************************************************************************/

	var container_id  = 'placeholder';
	var player_id     = 'player';
	var player        =  null;
	var currentItem   =     0;
	var currentState  =  null;  //IDLE, BUFFERING, PLAYING, PAUSED, COMPLETED
	var width         =   730;
	var playlistWidth =   200;
	var height        =   548 - 45; // since media player is sized by div, have to account for margin val of -45
	var playlistHeight =  0;

	var featuredWidth =   930;
	var featuredHeight =  600 - 45 - 52;

	var repeatState   =  true;
	//var repeatState   = false;
	var index = null; // MUST be global to be used in the setTimeout() method.
	var skin = 'mplayer/skins/qltv.swf'
	
/*
	// this is handled in body tag of medialive.php
	if(window.addEventListener) {
		window.addEventListener('load', createPlayer, false);
	}
	else if(document.addEventListener) {
		document.addEventListener('load', createPlayer, false);
	}
	else if(window.attachEvent) {
		window.attachEvent('onload', createPlayer);
	}
*/

function loadNplay(idx) {

	player.sendEvent('ITEM', idx);
        player.sendEvent('PLAY', 'true');
};

function loadNstop(idx) {

	index = idx;
	setTimeout("player.sendEvent('ITEM', index)", 100);
	setTimeout("player.sendEvent('STOP')", 200);
};

function createPlayer(vodFilter, vodType, vodVal, vodSort) {

	if (vodType == "media") {
		var fileString = "/data/medialist_MySQL.php?vf="+vodFilter+"&t="+vodType+"&v="+vodVal+"&s="+vodSort;
	}
	else {
		var fileString = "/data/playlist_MySQL.php?vf="+vodFilter+"&t="+vodType+"&v="+vodVal+"&s="+vodSort;
	}

	// vodVal is matchID
	//var captString = "/data/captions_MySQL.php?c="+vodVal;

	if (vodType == "featured") {
		var so = new SWFObject('/mplayer/mediaplayer.swf', player_id, featuredWidth, featuredHeight, '9', '#CCCCCC');
	}
	else {
		var so = new SWFObject('/mplayer/mediaplayer.swf', player_id, '100%', height + playlistHeight, '9', '#CCCCCC'); //width + playlistWidth, height + playlistHeight, '9', '#CCCCCC');
	}

	so.addParam('allowscriptaccess',     'always');
	so.addParam('allowfullscreen',       'true');
	so.addParam('wmode',		     'opaque');

	if (vodType == "featured") {
		so.addVariable('width',       featuredWidth);
		so.addVariable('height',      featuredHeight);
		so.addVariable('playlist',    'none');
		so.addVariable('plugins',     'quickkeys-1,viral-1,googlytics-1');
//		so.addVariable('plugins',     'accessibility-1');
//		so.addVariable('captions',     encodeURIComponent(captString));
	}
	else if (vodType == "featurednohighs") {
		so.addVariable('width',       featuredWidth);
		so.addVariable('height',      featuredHeight);
		so.addVariable('playlist',    'none');
		so.addVariable('plugins',     'quickkeys-1,viral-1,googlytics-1');
	}
	else {
		//so.addVariable('width',       width + playlistWidth);
		//so.addVariable('height',      height +playlistHeight);
	        so.addVariable("displayheight",		"9999");
		so.addVariable('playlistsize', playlistWidth);
		so.addVariable('playlist',     'right');
		so.addVariable('plugins', 	     'quickkeys-1,googlytics-1');
	}

	if (vodType == "media") {
		so.addVariable('plugins',     'quickkeys-1,viral-1,googlytics-1');
	}

	so.addVariable('controlbar',         'over'); // bottom
	so.addVariable('repeat',             'true');
	so.addVariable('streamer','lighttpd');
	so.addVariable('frontcolor',	     '#343434'); // #999999
	so.addVariable('backcolor',	     '#B4B4B4'); // #444444
	so.addVariable('lightcolor',	     '#9A0000'); //#CCCCCC
	so.addVariable('skin',                skin);
	so.addVariable('file',                encodeURIComponent(fileString));
	//so.addVariable("overstretch",		"fit");
	so.addVariable("stretching",		"uniform");
	so.addVariable("id",		player_id);

    
	so.write(container_id);
};

function playerReady(obj) {

	player  = document.getElementsByName(obj['id'])[0];
	var aCL = player.addControllerListener('ITEM', 'itemMonitor');
	var aML = player.addModelListener('STATE', 'stateMonitor');

	// sometimes if the player takes a while to load, getting the annotation info will
	// fail because the player isn't quite "ready" yet.
	// this code will try to get the description info from the playlist but if the player
	// isn't ready and an Error event is thrown, it will try again later.
	// this problem is only on the player's initial load. Other playlist items
	// will always work fine.
	
	//loadNstop(0);
	
	try {
		setTimeout("gid('annotation').innerHTML = player.getPlaylist()[0]['description']", 1000);
	} catch (err) {
		setTimeout("gid('annotation').innerHTML = player.getPlaylist()[0]['description']", 10000);
	}

	setTimeout("gid('annotation').innerHTML = player.getPlaylist()[0]['description']", 1000);
	
	if(obj['id'] == 'player') {

		// comment to not auto-play on page load...
//		setTimeout("player.sendEvent('PLAY', 'true')", 100);

		// Load the match details into the annotation div 
		setTimeout("gid('annotation').innerHTML = player.getPlaylist()[0]['description']", 1000);

		// sometimes IE sucks... okay, IE always sucks... but in this case, we need to test
		// to see if we can execute the tipsX3 object... if not, wait longer and try again
/*		try {
			setTimeout("var theTips = new TipsX3 ($$('.tipper'), {showDelay: 0});", 1000);
		} catch (err) {
			setTimeout("var theTips = new TipsX3 ($$('.tipper'), {showDelay: 0});", 5000);
		}
*/
	}
};

function itemMonitor(obj) {

	currentItem = obj['index'];
};

function stateMonitor(obj) {

	var urlvars = getVars();
	var vodType = urlvars['t'];
	//alert('vodtype is: '+vodType);

	currentState = obj['newstate'];

	//IDLE, BUFFERING, PLAYING, PAUSED, COMPLETED
	if(currentState == 'IDLE' || currentState == 'COMPLETED' || currentState == 'PAUSED') {
		gid('annotation').innerHTML = player.getPlaylist()[currentItem]['description'];

		if (vodType == "featured" || vodType == "featurednohighs") {
			// do nothing
		}
		else {
			gid('placeholder').style.width = "930px";
		}
	}
        else if(currentState == 'PLAYING') {
		gid('annotation').innerHTML = player.getPlaylist()[currentItem]['description'];

		if (vodType == "featured" || vodType == "featurednohighs") {
			// do nothing
		}
		else {
			gid('placeholder').style.width = "1130px";
		}
	}
	else if((currentState == 'COMPLETED') && (repeatState == true)) {
		player.sendEvent('PREV');
	}

	/*
	var property = '';
	for(var j in obj) {
		property += j + ': ' + obj[j] + ' ';
	}

	gid('property').innerHTML = property;
	*/
};

function addPlaylist(newItem) {

	newItem.duration = '';
	newItem.type     = 'sound';
	var oldList = player.getPlaylist();
	var newList = oldList.concat(newItem);
	player.sendEvent("LOAD", newList);

/*
	for(var j in newList) {
		var nodes = '<br />';
		for(var k in newList[j]) {
			nodes += '<li>' + k + ': ' + newList[j][k] + '</li>';
		}
		gid('dump' + j).innerHTML = nodes;
	}
*/
};

function gid(name) {
	return document.getElementById(name);
};

/**
 * Provides GET vars in an easily accessible format
 * by Matt Hackett [scriptnode.com]
 * @return {Object} The GET vars in key/value pairs
**/
function getVars() {

	var
		obj = {},
		op = location.href.split('?');

	if (op && op[1]) {

		var pos = op[1].search('#');

		if (pos != -1) {
			op[1] = op[1].substr(0, pos);
		}

		var
			op = op[1].split('&'),
			parsed;

		for (var i = 0; i < op.length; i++) {
			parsed = op[i].split('=');
			obj[parsed[0]] = parsed[1] || true;
		}

	}

	return obj;

};

/*
function createPlayer(vodType, vodVal, vodSort) {
	
	var fileString = "/data/playlist_MySQLnew.php?t="+vodType+"&v="+vodVal+"&s="+vodSort;
	
	// DEBUG
	document.getElementById("debug").innerHTML = fileString;
	
	var s = new SWFObject("/mplayernew/mediaplayer.swf","thePlayerId","930","500","9"); 
	s.addParam("allowfullscreen","true");
	s.addParam("allowscriptaccess","always");
	s.addParam("wmode","opaque");
	s.addParam("flashvars","file="+encodeURIComponent(fileString)
		+"&skin=/mplayernew/nacht_skin.swf"
		+"&playlist=right"
		+"&playlistsize=200"
		+"&frontcolor=0xffffff"
		+"&lightcolor=0xffffff"
		+"&backcolor=0x333333"
		+"&controlbar=over"
		+"&stretching=uniform");
//		+"&plugins=drelated-1"
//		+"&drelated.dxmlpath=relatedclips.xml"
//    		+"&drelated.dposition=bottom"
//    		+"&drelated.dskin=skins/grayskin.swf"
//    		+"&drelated.dtarget=_self");
	s.addVariable("type", "video");
	//s.addVariable("skin", "/mplayernew/overlay.swf");

	// OLD METHOD, kept here for default value reference
	//s.addParam('flashvars','height=450&width=900&file=/data/media.xml&backcolor=0x333333&frontcolor=0xffffff&lightcolor=0xffffff&displayheight=430&displaywidth=640&searchbar=false&repeat=false&showdownload=true');

	
	//s.addVariable("width","930");
	//s.addVariable("height","500");
	s.addVariable("backcolor","0x333333");
	s.addVariable("frontcolor","0xffffff");
	s.addVariable("lightcolor","0xffffff");
	//s.addVariable("displayheight","480");
	//s.addVariable("displaywidth","680");
	//s.addVariable("searchbar","false");
	//s.addVariable("repeat","false");
	//s.addVariable("showdownload","true");
	s.addVariable("controlbar","over");
	//s.addVariable("autostart","false");
	//s.addVariable("shuffle","false");
	s.addVariable("stretching","fill");


	s.addVariable("enablejs","true");
	s.addVariable("javascriptid","thePlayerId"); 

	s.write("placeholder");
}
*/
// EOF
