/**
 * YouTube.js
 * 
 * @version 1.0
 * @author Maurice Snip <mauricesnip at hotmail dot com>
 * @uses swfobject.js <http://code.google.com/p/swfobject/>
 */
function YouTubePlayer(el,options){this.API_PLAYER_URL='http://www.youtube.com/apiplayer?enablejsapi=1&version=3&playerapiid=';this.VIDEO_ID_REGEX=/[^=]*.(.{11}).*/;this.el=$(el);this.options=options;this.player=null;this.playerId='';this.playerCanvas=null;this.playerObject=null;this.playing=false;this.interval=null;this.ready=false;this.init();}YouTubePlayer.prototype={init:function(){if(this.el.length&&!/ipod|iphone|ipad/i.test(navigator.userAgent)){var self=this;this.options=$.extend({template:'<div class="player"><div class="player-canvas"><div class="player-video"></div></div><div class="player-controls"><div class="player-play"></div><div class="player-stop"></div><div class="player-mute"></div><div class="player-full-screen"></div><div class="player-progress"><div class="player-buffered"></div><div class="player-elapsed"></div><div class="player-handle"></div></div></div></div>',autoPlay:false,startMuted:false,autoSize:true,aspectRatio:16/9,width:480,height:270,hideLink:true,hideControls:false,playerParams:{allowScriptAccess:'always',bgcolor:'#000000',wmode:'transparent'},onReady:function(){},onStateChange:function(){},onEnd:function(){},onPlay:function(){},onPause:function(){},onBuffering:function(){},onCue:function(){},onMute:function(){},onUnMute:function(){},onFullScreen:function(){},onFramed:function(){},onError:function(){},onInvalidParameterError:function(){},onNotFoundError:function(){},onNoEmbedError:function(){}},this.options||{});self.createPlayer();}},createPlayer:function(){this.playerId='player'+Math.floor(Math.random()*1000);this.player=$(this.options.template);this.playerCanvas=this.player.find('.player-canvas');this.player.find('.player-video').attr('id',this.playerId);this.player.insertAfter(this.el);if(this.options.hideLink===true){this.el.hide();}if(this.options.autoSize===true){this.playerCanvas.height(this.calculateAspectRatioHeight());}else{this.playerCanvas.height(this.options.height);}this.bindPlayerEventHandlers();swfobject.embedSWF(this.API_PLAYER_URL+this.playerId,this.playerId,'100%','100%','8',null,null,this.options.playerParams,{id:this.playerId});},bindPlayerEventHandlers:function(){var self=this;function onYouTubePlayerReadyHandler(playerId){if(playerId===self.playerId){self.playerObject=document.getElementById(playerId);self.playerObject.addEventListener('onStateChange',playerId+'onStateChange');self.playerObject.addEventListener('onError',playerId+'onError');window[playerId+'onStateChange'](200);}}function onStateChangeHandler(state){self.fireCustomEvent('onStateChange',state);switch(state){case 0:self.handlePlayerEnd();break;case 1:self.handlePlayerPlay();break;case 2:self.handlePlayerPause();break;case 3:self.handlePlayerBuffering();break;case 5:self.handlePlayerCue();break;case 50:self.handlePlayerMute();break;case 51:self.handlePlayerUnMute();break;case 52:self.handlePlayerFullScreen();break;case 53:self.handlePlayerFramed();break;case 200:self.handlePlayerReady(self.playerId);break;}}function onErrorHandler(error){self.fireCustomEvent('onError',error);switch(error){case 2:self.handleInvalidParameter();break;case 100:self.handleNotFound();break;case 101:case 150:self.handleNoEmbed();break;}}if(typeof window.onYouTubePlayerReady==='function'){var oldOnYouTubePlayerReady=window.onYouTubePlayerReady;window.onYouTubePlayerReady=function(playerId){oldOnYouTubePlayerReady(playerId);onYouTubePlayerReadyHandler(playerId);};}else{window.onYouTubePlayerReady=onYouTubePlayerReadyHandler;}window[this.playerId+'onStateChange']=onStateChangeHandler;window[this.playerId+'onError']=onErrorHandler;},bindEventHandlers:function(){var self=this;$('.player-controls',this.player).click(function(e){var target=e.target;switch($(target).attr('class')){case'player-play':self.getPlayerState()===1?self.pauseVideo():self.playVideo();break;case'player-stop':if(self.getPlayerState()===1){self.stopVideo();}break;case'player-mute':self.isMuted()?self.unMute():self.mute();break;case'player-full-screen':self.isFullScreen()?self.framed():self.fullScreen();break;case'player-progress':case'player-buffered':case'player-elapsed':self.seekToPercentage(((e.layerX||e.offsetX)*100)/self.player.find('.player-progress').width());break;}});$(document).keyup(function(e){if(e.keyCode===27&&self.isFullScreen()){self.framed();}});},getPlayer:function(){return this.player;},getPlayerObject:function(){return this.playerObject;},setPlayerObject:function(playerObject){this.playerObject=playerObject;},fireCustomEvent:function(event){if(this.options.hasOwnProperty(event)){var args=[this.player,this.playerObject].concat(Array.prototype.slice.call(arguments,1));this.options[event].apply(this,args);}},seekToPercentage:function(percentage){if(this.playing){this.seekTo((this.getDuration()*percentage)/100,false);}},calculateAspectRatioHeight:function(){return Math.round(this.playerCanvas.width()/this.options.aspectRatio);},fullScreen:function(){window[this.playerId+'onStateChange'](52);this.playerCanvas.width('100%').height('100%');},framed:function(){window[this.playerId+'onStateChange'](53);this.playerCanvas.removeAttr('style').height(this.calculateAspectRatioHeight());},isFullScreen:function(){return this.player.hasClass('full-screen');},updateProgress:function(){this.player.find('.player-buffered').css('width',(this.getVideoBytesLoaded()*100)/this.getVideoBytesTotal()+'%');this.player.find('.player-elapsed').css('width',(this.getCurrentTime()*100)/this.getDuration()+'%');},setProgressInterval:function(){if(!this.playing){var self=this;this.interval=setInterval(function(){self.updateProgress();},100);}},clearProgressInterval:function(){if(this.playing){clearInterval(this.interval);this.interval=null;}},handlePlayerReady:function(playerId){if(!this.ready){this.fireCustomEvent('onReady');this.bindEventHandlers();this.ready=true;}var videoId=this.el.attr('href').replace(this.VIDEO_ID_REGEX,'$1');if(this.options.autoPlay){this.loadVideoById(videoId);}else{this.cueVideoById(videoId);}if(this.options.startMuted){this.mute();}},handlePlayerEnd:function(){this.fireCustomEvent('onEnd');this.player.removeClass('playing');this.clearProgressInterval();this.playing=false;},handlePlayerPlay:function(){this.fireCustomEvent('onPlay');this.player.addClass('playing');this.setProgressInterval();this.playing=true;},handlePlayerPause:function(){this.fireCustomEvent('onPause');this.player.removeClass('playing');this.clearProgressInterval();this.playing=false;},handlePlayerBuffering:function(){this.fireCustomEvent('onBuffering');},handlePlayerCue:function(){this.fireCustomEvent('onCue');},handlePlayerMute:function(){this.fireCustomEvent('onMute');this.player.addClass('muted');},handlePlayerUnMute:function(){this.fireCustomEvent('onUnMute');this.player.removeClass('muted');},handlePlayerFullScreen:function(){this.fireCustomEvent('onFullScreen');this.player.addClass('full-screen');},handlePlayerFramed:function(){this.fireCustomEvent('onFramed');this.player.removeClass('full-screen');},handleInvalidParameter:function(){this.fireCustomEvent('onInvalidParameterError');},handleNotFound:function(){this.fireCustomEvent('onNotFoundError');},handleNoEmbed:function(){this.fireCustomEvent('onNoEmbedError');},cueVideoById:function(videoId,startSeconds,suggestedQuality){this.playerObject.cueVideoById(videoId,startSeconds,suggestedQuality);},loadVideoById:function(videoId,startSeconds,suggestedQuality){this.playerObject.loadVideoById(videoId,startSeconds,suggestedQuality);},cueVideoByUrl:function(mediaContentUrl,startSeconds){this.playerObject.cueVideoByUrl(mediaContentUrl,startSeconds);},loadVideoByUrl:function(mediaContentUrl,startSeconds){this.playerObject.loadVideoByUrl(mediaContentUrl,startSeconds);},playVideo:function(){this.playerObject.playVideo();},pauseVideo:function(){this.playerObject.pauseVideo();},stopVideo:function(){this.playerObject.stopVideo();},seekTo:function(seconds,allowSeekAhead){this.playerObject.seekTo(seconds,allowSeekAhead);},mute:function(){this.playerObject.mute();window[this.playerId+'onStateChange'](50);},unMute:function(){this.playerObject.unMute();window[this.playerId+'onStateChange'](51);},isMuted:function(){return this.playerObject.isMuted();},getVolume:function(){return this.playerObject.getVolume();},setVolume:function(volume){this.playerObject.setVolume(volume);},setSize:function(width,height){this.playerObject.setSize(width,height);},getVideoBytesLoaded:function(){return this.playerObject.getVideoBytesLoaded();},getVideoBytesTotal:function(){return this.playerObject.getVideoBytesTotal();},getVideoStartBytes:function(){return this.playerObject.getVideoStartBytes();},getPlayerState:function(){return this.playerObject.getPlayerState();},getCurrentTime:function(){return this.playerObject.getCurrentTime();},getPlaybackQuality:function(){return this.playerObject.getPlaybackQuality();},setPlaybackQuality:function(suggestedQuality){this.playerObject.setPlaybackQuality(suggestedQuality);},getAvailableQualityLevels:function(){return this.playerObject.getAvailableQualityLevels();},getDuration:function(){return this.playerObject.getDuration();},getVideoUrl:function(){return this.playerObject.getVideoUrl();},getVideoEmbedCode:function(){return this.playerObject.getVideoEmbedCode();}};
