﻿/*
jqIzeYoutubePlayer - (c) 2010 Emil Müller
http://ize.webhop.net/home/jquery-plugins/jqizeyoutubeplayer
Released under the GPL License
http://www.gnu.org/licenses/gpl-3.0.txt
	
requires:
- jQuery 1.4.x
- SWFObject 2
*/

function onYouTubePlayerReady(playerId) {    
    var ytplayer = document.getElementById(playerId);
    var mainid = $(ytplayer).attr("mainid");
    var youtubeplayer = $("#" + mainid).data("ytplayer");
    youtubeplayer.setPlayer(ytplayer);    
    ytplayer.addEventListener("onStateChange", 'function (e) { onytplayerStateChange("' + playerId + '", e); }');
    youtubeplayer.doPlayerReadyEx();
}

function onytplayerStateChange(playerId, newState) {
    var ytplayer = document.getElementById(playerId);
    var mainid = $(ytplayer).attr("mainid");
    var youtubeplayer = $("#" + mainid).data("ytplayer");
    youtubeplayer.handleStateChange(newState);
}

(function ($) {
    $.fn.IzeYoutubePlayer = function (settings) {        
        var ytplayer;
        var videoInfo;
        var isReady = false;
        var playerloaded = false;

        var config = {
            width: 640,
            height: 360,
            highdef: 1, // 1 for high-def, 0 for default,
            quality: 'hd720', //small, medium, large, hd720, default
            onPlayerReady: function() {},
            onUnstarted: function() {},
            onEnded: function() {},
            onPlaying: function() {},
            onPaused: function() {},
            onBuffering: function() {},
            onVideoCued: function() {},
            onVideoInfo: function() {}
        };

        if (settings) $.extend(config, settings);

        init = function (el) {
            setupMainContainer(el);
            loadPlayer(el);


        }

        setupMainContainer = function(el)
        {
            $(el).css({width: config.width, height: config.height, position: 'relative'});
        }

        loadPlayer = function (el) {
            var playerPlaceholder = $("<div />").attr("id", "playerplaceholder");
            $(el).prepend(playerPlaceholder);

            var uniquePlayerId = "youtubeplayer" + (new Date()).getTime();

            var flashvars = {
                rel: 0,
                color1: '0x2b405b',
                color2: '0x000000',
                border: 0,
                fs: 1,
                iv_load_policy: 3,
                showinfo: 0,
                showsearch: 0,
                hd: config.highdef,
                playerapiid: uniquePlayerId
            };
            var params = {
                width: '100%',
                height: '100%',
                allowfullscreen: "true",
                allowscriptaccess: "always",
                wmode: 'opaque',
                bgcolor: '#000000'
            };
            var attributes = {
                id: uniquePlayerId,
                name: uniquePlayerId,
                style: 'position: relative;', /* use absolute positioning so html overlays are faster */
                mainid: $(el).attr("id")
            };

            swfobject.embedSWF("http://www.youtube.com/apiplayer?version=3&enablejsapi=1", "playerplaceholder", '100%', '100%', "9.0.0", "expressInstall.swf", flashvars, params, attributes);         
        }

        getVideoInfo = function(el, VideoId)
        {           
            $.getJSON('http://gdata.youtube.com/feeds/api/videos/' + VideoId + '?alt=json-in-script&v=2&callback=?', function(data) {
                videoInfo = data.entry;
                doVideoInfo(el, videoInfo);                
            });
        }

        doVideoInfo = function(el, videoInfo)
        {
            if ($.isFunction(config.onVideoInfo)) config.onVideoInfo.call(this, videoInfo);
        }

        this.setPlayer = function(player) {                    
            ytplayer = player;
        }

        this.getPlayer = function() {
            return ytplayer;
        }

        this.playUrl = function(url) {
            ytplayer.loadVideoByUrl(url, 0);
        }

        this.playVideo = function(id) {
            getVideoInfo($(this),id);
            ytplayer.loadVideoById(id, 0, config.quality);
        }

        this.play = function() {
            ytplayer.playVideo();
        }

        this.pause = function() {
            ytplayer.pauseVideo();
        }

        this.stop = function() {
            ytplayer.stopVideo();
        }

        this.seekTo = function(seconds, allowSeekAhead) {
            ytplayer.seekTo(seconds, allowSeekAhead);
        }

        this.mute = function() {
            ytplayer.mute();
        }

        this.unMute = function() {
            ytplayer.unMute();
        }

        this.isMuted = function() {
            return ytplayer.isMuted();
        }

        this.setVolume = function(level) {
            ytplayer.setVolume(level);
        }

        this.getVolume = function() {
            return ytplayer.getVolume();
        }

        this.getVideoBytesLoaded = function() {
            return ytplayer.getVideoBytesLoaded();
        }

        this.getVideoBytesTotal = function() {
            return ytplayer.getVideoBytesTotal();
        }

        this.getVideoStartBytes = function() {
            return ytplayer.getVideoStartBytes();
        }

        this.getPlayerState = function() {
            return ytplayer.getPlayerState();
        }

        this.getCurrentTime = function() {
            return ytplayer.getCurrentTime();
        }

        this.getPlaybackQuality = function() {
            return ytplayer.getPlaybackQuality();
        }

        this.setPlaybackQuality = function(quality) {
            ytplayer.setPlaybackQuality(quality);
        }

        this.getAvailableQualityLevels = function() {
            return ytplayer.getAvailableQualityLevels();
        }

        this.getDuration = function() {
            return ytplayer.getDuration();
        }

        this.getVideoUrl = function() {
            return ytplayer.getVideoUrl();
        }

        this.getVideoEmbedCode = function() {
            return ytplayer.getVideoEmbedCode();
        }

        this.getIsReady = function() {
            return isReady;
        }

        this.handleStateChange = function(newState) {
                //unstarted (-1), ended (0), playing (1), paused (2), buffering (3), video cued (5)
                switch (newState) {
                    case -1:
                        doUnstarted($(this));
                        break;
                    case 0:
                        doEnded($(this));
                        break;
                    case 1:
                        doPlaying($(this));
                        break;
                    case 2:
                        doPaused($(this));
                        break;
                    case 3:
                        doBuffering($(this));
                        break;
                    case 5:
                        doVideoCued($(this));
                        break;
                }
        }

        doPlayerReady = function(el) { 
            isReady = true;
            //set player to absolute positioning
            //$(ytplayer).css( { position: 'absolute', width: $(el).width() + 'px', height: $(el).height() + 'px'});
            if ($.isFunction(config.onPlayerReady)) config.onPlayerReady.call(this); 
        }
        //expose this event, so it can be called externally
        this.doPlayerReadyEx = function () { doPlayerReady($(this)); }

        doUnstarted = function(el) { if ($.isFunction(config.onUnstarted)) config.onUnstarted.call(this); }

        doEnded = function(el) { if ($.isFunction(config.onEnded)) config.onEnded.call(this); }

        doPlaying = function(el) { if ($.isFunction(config.onPlaying)) config.onPlaying.call(this); }

        doPaused = function(el) { if ($.isFunction(config.onPaused)) config.onPaused.call(this); }

        doBuffering = function(el) { if ($.isFunction(config.onBuffering)) config.onBuffering.call(this); }

        doVideoCued = function(el) { if ($.isFunction(config.onVideoCued)) config.onVideoCued.call(this); }

        this.each(function () {
            //setup element            
            init(this);
        });

        //put instance of this object in data
        $(this).data("ytplayer", this);
        return this;

    };

})(jQuery);
