/**
 * @author sjorek
 */
function onYouTubePlayerChange(state){
	alert('YT CHANGE: ' + state);
}
function onYouTubePlayerError(code){
	alert('YT ERROR: ' + code);
}
var onYouTubePlayerEvents = {};
var onYouTubePlayerReady = function(playerId){
	if (playerId) {
		jQuery(document).trigger('ready.youtube',[playerId]);
	} else {
		alert('TEST2 ' + playerId);
	}
};

(function($){

	application.factory.Youtube = function(appId,appOpts){

		var app = function(id,opts){
			this.id=application.control(id,this);
			if (typeof(opts)=='object') {
				this.options = $.extend(1,this.options,opts);
			}
			if (this.options.attributes==null) {
				this.options.attributes={};
			}
			if (!this.options.id) {
				this.options.id=id+'_media';
			}
			if (!this.options.attributes.id) {
				this.options.attributes.id=this.options.id+'_flash';
			}
			this.options.url= this.options.url.replace(/###player###/, (this.options.chromeless?('apiplayer?v='+this.options.key):('v/'+this.options.key+'?'))).replace(/###id###/,this.options.id);
			var obj = this;
			$(document).bind('ready.youtube',function(e,playerId){obj.onYoutubeReady(e,playerId);});
			application.debug('Youtube Init: '+this.options.url);

			var flashFn = function(){};
			if (typeof($.flash)=='object' && typeof($.flash.create)=='function') {
				var youtubePlayerFlashMarkup = $.flash.create({
					id              : obj.options.attributes.id,
//					name            : obj.options.attributes.id,
					swf             : obj.options.url,
					width           : obj.options.width,
					height          : obj.options.height,
					hasVersion      : obj.options.flash,
					expressInstall  : obj.options.xi,
					flashvars       : obj.options.flashvars,
					params          : obj.options.parameters,
					attrs           : obj.options.attributes
				});
				var flashFn = function(){
					$('#' + obj.options.id).replaceWith(youtubePlayerFlashMarkup);
				};
			} else if(typeof(swfobject)=='object' && typeof(swfobject.embedSWF)=='function'){
				var flashFn = function(){
					swfobject.embedSWF(
						obj.options.url,
						obj.options.id,
						obj.options.width,
						obj.options.height,
						obj.options.flash,
						obj.options.xi,
						obj.options.flashvars,
						obj.options.parameters,
						obj.options.attributes
					);
				};
			} else {
				application.debug('failed to find a swfobject');
			}
			$(document).ready(flashFn);
		};
		app.prototype.callback=[];
		app.prototype.id=null;
		app.prototype.player=null;
		app.prototype.options={
			url:'http://www.youtube.com/###player###rel=0&amp;enablejsapi=1&amp;playerapiid=###id###_player&amp;autoplay=0&amp;loop=0&amp;egm=0&amp;border=0&amp;color1=73bd1e&amp;color2=73bd1e&amp;showsearch=0&amp;showinfo=0&amp;hd=0&amp;hl=de&amp;fs=1',
			key:'',
			id:'',
			width:'288',
			height:'231',
			flash:'10',
			xi:'/fileadmin/gpd/basics/javascript/swfobject.2.2/expressInstall.swf',
			flashvars:null,
			parameters:{
				allowFullScreen:'true',
				allowScriptAccess:'always',
				wmode:'transparent'
			},
			attributes:null,
			chromeless:false
		};
		app.prototype.stop=function(){
			application.debug('Youtube Stop attempt recognized: '+this.id);
			if (this.player!=null && typeof(this.player.pauseVideo)=='function'){
				application.debug('Youtube Stop: '+this.id);
				this.player.pauseVideo();
			}
		};
		app.prototype.busy=function(){
			if (this.player!=null && typeof(this.player.getPlayerState)=='function'){
				var state = this.player.getPlayerState();
				// unstarted (-1), ended (0), playing (1), paused (2), buffering (3), video cued (5)
				application.debug('Youtube Busy: ' + this.id + ' = ' + state,{
					'unstarted':-1,
					'ended':0,
					'playing':1,
					'paused':2,
					'buffering':3,
					'video cued':5
				});
				if (state==1 || state==3) {
					return true;
				}
			}
			return false;
		};
		app.prototype.onYoutubeReady=function(e,playerId){
			var player = document.getElementById(this.options.attributes.id);
			if (player && playerId) {
				var playerIE = playerId?document.getElementById(playerId):playerId;
				application.debug('youtube callback attempt by playerId[' + playerId + '] vs. attrId[' + this.options.attributes.id + '] => ' + escape((playerIE?playerIE:player).parentNode.innerHTML),{
					'event': e,
					'options': this.options,
					'player': player,
					'playerIE': playerIE
				});
				this.player = player;
				var obj = this;
				var ctrlId = String(this.id).replace(/_[^_]+_[^_]+$/,'');
				var ctrl = application.control(ctrlId);
				if (ctrl && typeof(ctrl.media) == 'function') {
					ctrl.media(this.id, this);
					application.debug('Youtube Ready and registered at Controller: '+playerId+' => '+this.id+' => '+this.options.id+' => '+this.options.attributes.id+' => '+ctrlId);
				} else {
					application.debug('Youtube Ready Standalone: '+playerId+' => '+this.id+' => '+this.options.id+' => '+this.options.attributes.id+' => '+ctrlId);
				}
				onYouTubePlayerEvents[playerId] = {
					change:function(state){
						obj.onYoutubeChange(state);
					},
					error:function(code){
						obj.onYoutubeError(code);
					}
				}
//				alert('EVENT TYPE addEventListener[' + typeof(player.addEventListener) + '] vs. attachEvent[' + typeof(player.attachEvent) + ']');
//				if (typeof(player.addEventListener)=='function') {
//					player.addEventListener("onStateChange", "onYouTubePlayerChange");
//					player.addEventListener("onError", "onYouTubePlayerError");
//				} else {
//					player.attachEvent("onStateChange", onYouTubePlayerChange);
//					player.attachEvent("onError", onYouTubePlayerError);
//				}
				player.addEventListener("onStateChange", 'onYouTubePlayerEvents["'+playerId+'"]["change"]');
				player.addEventListener("onError", 'onYouTubePlayerEvents["'+playerId+'"]["error"]');
				if (this.options.chromeless) {
					$(player).parent().click(function(e){if(player.getPlayerState()===2){player.playVideo();}else if(player.getPlayerState()===1){player.pauseVideo();}});
					$(document).bind('change.youtube',function(e,state){if(state===0){player.cueVideoById(obj.options.key,.001);}});
					player.cueVideoById(obj.options.key);
				}
			}
		};

		app.prototype.onYoutubeChange=function(state){
			application.debug('Youtube Change: '+this.id);
			$(document).trigger('change.youtube',[state]);
		};

		app.prototype.onYoutubeError=function(code){
			application.debug('Youtube Error: '+this.id);
			$(document).trigger('error.youtube',[code]);
		};

		return new app(appId,appOpts);
	};

})(jQuery);
