/*

unbad object library Copyright © 2006-2010 - Sean Claflin

unbad object library is licensed under the MIT License
http://www.opensource.org/licenses/mit-license.php

*/

(ub.youtube = {
	init: function() {
		//attach to the onYouTubePlayerReady callback, try to be nice
		//and not override any existing code
		var old = window.onYouTubePlayerReady;
		window.onYouTubePlayerReady = function(playerID) {
			ub.youtube._youTubePlayerReady(playerID);
			if(old) old();
		};
		ub.e.attach(ub, 'unload', function(e) {
			this.destruct();
		}, false, this);
	},
	destruct: function() {
		//clear out our fx stack in reverse order
		ub.a.each(this.stack, function(player) {
			player.destruct();
		}, this, true);
		ub.a.clear(this.stack);
	},
	stack: [],
	_youTubePlayerReady: function(playerID) {
		var player = this.findPlayer(playerID);
		if(player) player._onready();
	},
	_youTubeStateChange: function(playerID) {
		var player = this.findPlayer(playerID);
		if(player) {
			var state = player.swf.getPlayerState();
			player.onstatechange(new ub.e.event('statechange'), state);
		}
	},
	findPlayer: function(playerID) {
		for(var i=0,player=null;player=this.stack[i];i++) {
			if(player.options.playerAPIID == playerID) {
				return player;
			}
		}
		return false;
	},
	player: function() {
		var playerNormal = 'http://www.youtube.com/v/';
		var playerChromeless = 'http://www.youtube.com/apiplayer?';
		var player = function(videoId, options) {
			ub.a.append(ub.youtube.stack, this);
			//http://code.google.com/apis/youtube/player_parameters.html
			this.options = ub.u.extend({
				'relatedVideos': 1,//rel
				'autoPlay': 0,//autoplay
				'loop': 0,//loop
				'enableJavaScriptAPI': 1,//enablejsapi
				'playerAPIID': ub.u.randStr(),//playerapiid
				'disableKeyboard': 0,//disablekb
				'enhancedGenieMenu': 0,//egm
				'border': 0,//border
				'color1': '0xffffff',//color1
				'color2': '0xffffff',//color2
				'startTime': 0,//start
				'fullScreenButton': 0,//fs
				'highDefinition': 0,//hd
				'showSearch': 0,//showsearch
				'showInfo': 1,//showinfo
				'width': 320,
				'height': 240,
				'chromeless': false
			}, options);
			//create the events array
			this.events = [];
			//player states
			this.states = {
				'unstarted': -1,
				'ended': 0,
				'playing': 1,
				'paused': 2,
				'buffering': 3,
				'cued': 5
			};
			//player qualites
			this.qualities = {
				'small': 'small',
				'medium': 'medium',
				'large': 'large',
				'720p': 'hd720',
				'default': 'default'
			};
			//stub out the swf property
			this.swf = null;
			//store the videoId
			this.videoId = videoId;
			//build the container
			this.container = document.createElement('div');
			//DOM methods weren't working on IE, had to use innerHTML
			//to get working crosss-browser. :(
			this.container.innerHTML = '\
				<object id="'+ this.options.playerAPIID +'" type="application/x-shockwave-flash" data="'+ this.buildDataString(videoId) +'" style="width: '+ this.options.width +'px; height: '+ this.options.height +'px;">\
					<param name="movie" value="'+ this.buildDataString(videoId) +'">\
					<param name="allowScriptAccess" value="always">\
					<param name="wmode" value="transparent">\
				</object>\
			';
		};
		player.prototype.destruct = function() {
			ub.a.remove(ub.youtube.stack, this);
			ub.a.each(this.events, function(event) {
				event.detach();
			}, this);
			ub.a.clear(this.events);
			this.container = null;
			this.swf = null;
			this.destruct = function() {};
		};
		player.prototype.buildDataString = function(videoId) {
			var str = ((this.options.chromeless) ? playerChromeless : playerNormal) + videoId;
			str += '&rel='+ this.options.relatedVideos;
			str += '&autoplay='+ this.options.autoPlay;
			str += '&loop='+ this.options.loop;
			str += '&enablejsapi='+ this.options.enableJavaScriptAPI;
			str += '&playerapiid='+ this.options.playerAPIID;
			str += '&disablekb='+ this.options.disableKeyboard;
			str += '&egm='+ this.options.enhancedGenieMenu;
			str += '&border='+ this.options.border;
			str += '&color1='+ this.options.color1;
			str += '&color2='+ this.options.color2;
			str += '&start='+ this.options.startTime;
			str += '&fs='+ this.options.fullScreenButton;
			str += '&hd='+ this.options.highDefinition;
			str += '&showsearch='+ this.options.showSearch;
			str += '&showinfo='+ this.options.showInfo;
			return str;
		};
		player.prototype.cueVideoById = function(videoId, startSeconds, suggestedQuality) {
			if(!this.swf) return;
			this.swf.cueVideoById(
				videoId, 
				parseInt(startSeconds || 0), 
				(this.qualities[suggestedQuality]) ? this.qualities[suggestedQuality] : this.qualities['default']
			);
		};
		player.prototype.loadVideoById = function(videoId, startSeconds, suggestedQuality) {
			if(!this.swf) return;
			this.swf.loadVideoById(
				videoId, 
				parseInt(startSeconds || 0), 
				(this.qualities[suggestedQuality]) ? this.qualities[suggestedQuality] : this.qualities['default']
			);
		};
		player.prototype.cueVideoByUrl = function(url, startSeconds) {
			if(!this.swf) return;
			this.swf.cueVideoByUrl(url, parseInt(startSeconds || 0));
		};
		player.prototype.loadVideoByUrl = function(url, startSeconds) {
			if(!this.swf) return;
			this.swf.loadVideoByUrl(url, parseInt(startSeconds || 0));
		};
		player.prototype.playVideo = function() {
			if(!this.swf) return;
			this.swf.playVideo();
		};
		player.prototype.pauseVideo = function() {
			if(!this.swf) return;
			this.swf.pauseVideo();
		};
		player.prototype.stopVideo = function() {
			if(!this.swf) return;
			this.swf.stopVideo();
		};
		player.prototype.seekTo = function(seconds, allowSeekAhead) {
			if(!this.swf) return;
			this.swf.seekTo(parseInt(seconds || 0), (allowSeekAhead === false) ? false : true);
		};
		player.prototype.mute = function() {
			if(!this.swf) return;
			this.swf.mute();
		};
		player.prototype.unMute = function() {
			if(!this.swf) return;
			this.swf.unMute();
		};
		player.prototype.isMuted = function() {
			if(!this.swf) return;
			return this.swf.isMuted();
		};
		player.prototype.setVolume = function(volume) {
			if(!this.swf) return;
			volume = parseInt(volume || 0);
			this.swf.setVolume(volume);
		};
		player.prototype.getVolume = function() {
			if(!this.swf) return;
			return this.swf.getVolume();
		};
		player.prototype.setSize = function(width, height) {
			if(!this.swf) return;
			this.swf.setSize(parseInt(width || 0), parseInt(height || 0));
		};
		player.prototype.getVideoBytesLoaded = function() {
			if(!this.swf) return;
			return this.swf.getVideoBytesLoaded();
		};
		player.prototype.getVideoBytesTotal = function() {
			if(!this.swf) return;
			return this.swf.getVideoBytesTotal();
		};
		player.prototype.getVideoStartBytes = function() {
			if(!this.swf) return;
			return this.swf.getVideoStartBytes();
		};
		player.prototype.getPlayerState = function() {
			if(!this.swf) return;
			return this.swf.getPlayerState();
		};
		player.prototype.getCurrentTime = function() {
			if(!this.swf) return;
			return this.swf.getCurrentTime();
		};
		player.prototype.getPlaybackQuality = function() {
			if(!this.swf) return;
			return this.swf.getPlaybackQuality();
		};
		player.prototype.setPlaybackQuality = function(suggestedQuality) {
			if(!this.swf) return;
			return this.swf.setPlaybackQuality((this.qualities[suggestedQuality]) ? this.qualities[suggestedQuality] : this.qualities['default']);
		};
		player.prototype.getAvailableQualityLevels = function() {
			if(!this.swf) return;
			return this.swf.getAvailableQualityLevels();
		};
		player.prototype.getDuration = function() {
			if(!this.swf) return;
			return this.swf.getDuration();
		};
		player.prototype.getVideoUrl = function() {
			if(!this.swf) return;
			return this.swf.getVideoUrl();
		};
		player.prototype.getVideoEmbedCode = function() {
			if(!this.swf) return;
			return this.swf.getVideoEmbedCode();
		};
		player.prototype._onready = function() {
			//w00t, player is ready, assign the object node
			this.swf = ub.$(this.options.playerAPIID);
			//the addEventListener is a youtube player defined function
			//and only accepts strings as function references no
			//lambda functions allowed here. :(
			this.swf.addEventListener('onStateChange', 'ub.youtube._youTubeStateChange("'+ this.options.playerAPIID +'")');
			this.onready(new ub.e.event('ready'));
		};
		player.prototype.onready = function(e) {};
		player.prototype.onstatechange = function(e, state) {};
		return player;
	}()
}).init();

