/* If there's no clip reference in the url we'll start off on the first clip */
var myclip = 0;

/* In order to wait 'till the player's fully initialized we'll be listening for a callback,
but we only want to respond on the first such call - best have a state tracking variable */
var flowplayerLoaded = 0;
/* here's the callback */
function onStartBuffering(cliploaded) {
	if (flowplayerLoaded == 0 && myclip != 0) {
		play(null, myclip);
	}
	else if (flowplayerLoaded == 0) {
		showInfo(0);
	}
	flowplayerLoaded++;
}

/* Surely there's a more compact way to extract a request variable from the url? And one which would work with an http post as well?? */
function getActiveClipOnLoad() {
	var qs = {};
	var clipindex;
	var query = window.location.search.substring(1);
	var pairs = query.split('&');
	for (var i=0;i<pairs.length;i++) {
		var kv = pairs[i].split('=');
		qs[kv[0]] = kv[1]
	}
	clipindex = qs['myclip'];
	if (clipindex) { myclip = clipindex }
	else { myclip = 0 };
}

function multiplexInit() {
	/* Initialization for Multiplex Page*/
	
	/* Discover if we've been asked to start with a particular clip */
	getActiveClipOnLoad();
	/* Build the main clip carousel */
	$('.cliptrigger').show();
   	jQuery('#maincarousel').jcarousel({animation:'slow', wrap:'both', start:myclip});
	
	/* Build the carousels of info for each clip */
	$('.clipinfo').show();
	jQuery('.infocarousel').jcarousel({visible:1, scroll:1, wrap:null});
	/* Hide all the info carousel containers*/
	jQuery('.clipinfo').hide();

	/* Bind the play functions to each cliptrigger in the main carousel */
	jQuery('.cliptrigger').each(function(i) {
		var ident;
		/* grab the end if the element id - it'll be the clip reference */
		ident = $(this).attr("id").substring(7);
		$(this).bind(
			"click", function() {play(this, ident); return false;}	
		);
		
	});

	var fo = new SWFObject("FlowPlayer.swf", "fp", "320", "240", "9", "#ffffff", true);
	fo.addParam("AllowScriptAccess", "always");
	fo.addParam("allowFullScreen", "true");
	fo.addVariable("config", "{configFileName: 'js/playerConfig.js'}");
	fo.write("screen");

}


function play(item, clipIndex) {
		/* The playlist index point for the thumbnail will be the clipIndex x 2 */
		var playlistIndex;
		playlistIndex = clipIndex * 2
		var player = document.getElementById('fp');
		try {   
			player.ToClip(playlistIndex);	
		}
		catch (e) {
			/* The player's not present or not fully ready yet */
			setTimeout('play(null, myclip)', 1800);
			
		}
		/* Update other display components */
		showInfo(clipIndex);
}

function showInfo(clipIndex) {

	jQuery('.clipinfo:visible').hide();
	jQuery('.focussed').removeClass('focussed');
	jQuery('#info' + clipIndex).show();
	jQuery('#trigger' + clipIndex).addClass('focussed');

}
