/* mini-framework for using chrome-less YouTube player from javascript

 Example usage
 -------------
 
 HTML CODE: 
 
 <head>
 	<script type="text/javascript" src = "swfobject.js"></script>
 </head>
 <body>
	<div id="player-container; display: none">
		<div id="player-div" style="display: none">&nbsp;</div>
	</div>
 </body>
 
 JAVASCRIPT CODE:
 
 	play(videoId, "player-container", "player-div", "425", "356");
	
 */

var ytPlayerWidth = null;
var ytPlayerHeight = null;
var ytContainerId = null;
var ytPlayerId = 'yt-player';

var ytPlayerCreated = false;
var ytPlayerReady = false;
var ytWantToPlay = null;

function play(videoId, container, div, w, h) {
	ytContainerId = container;
	if (!ytPlayerCreated) {
		ytWantToPlay = videoId;
		ytCreatePlayer(div, w, h);
	}
	else if (!ytPlayerReady) {
		ytWantToPlay = videoId;
	}
	else {
		ytLoadAndPlay(videoId);
	}
}

function ytLoadAndPlay(videoId) {
	var player = document.getElementById(ytPlayerId);
//	jQuery('#' + ytContainerId).show();
//	jQuery('#' + ytContainerId).css({width: ytPlayerWidth + 'px', height: ytPlayerHeight + 'px'});
	jQuery('#' + ytPlayerId).css({width: ytPlayerWidth + 'px', height: ytPlayerHeight + 'px'});
	player.loadVideoById(videoId, 0);
}

function ytCreatePlayer(div, w, h) {
	ytPlayerCreated = true;
	var params = { allowScriptAccess: "always"};
	var atts = { id: ytPlayerId };
//	var url1 = "http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid=player1&fs=1";
	var url1 = "http://www.youtube.com/v/fDwllBbqToc?enablejsapi=1&playerapiid=player1";
	swfobject.embedSWF(url1, div, '' + w, '' + h, "8", null, null, params, atts);
	ytPlayerWidth = w;
	ytPlayerHeight = h;
}


/* YouTube player event handlers */

function onPlayerError(errorCode) {
	//alert("An error occurred of type:" + errorCode);
}

function onYouTubePlayerReady(playerid) {
	ytPlayerReady = true;
	var player = document.getElementById(ytPlayerId);
	player.addEventListener("onStateChange", "onPlayerStateChange");
	if (ytWantToPlay) {
		ytLoadAndPlay(ytWantToPlay);
		ytWantToPlay = null;
	}
}

function onPlayerStateChange(newState) {
	//alert("Player's new state: " + newState);
	if (newState==0) {
		//alert('done playing');
		// hide or destroy the player
		jQuery('#' + ytPlayerId).css({width: 0, height: 0});
//		jQuery('#' + ytContainerId).css({width: 0, height: 0});
//		jQuery('#' + ytContainerId).hide();
	}
}

