﻿/*
	jqChromelessYoutube - (c) 2010 Emil Müller
	http://ize.webhop.net/home/jquery-plugins/jqchromelessyoutube
	Released under the GPL License
	http://www.gnu.org/licenses/gpl-3.0.txt
	
	requires:
	- jQuery 1.4.x
	- SWFObject 2
*/

        var ytplayer;
        function onYouTubePlayerReady(playerId) {			
    	  ytplayer = document.getElementById(playerId);
    	  ytplayer.addEventListener("onStateChange", "onytplayerStateChange");    	
    	  $(ytplayer).parent().parent().parent().data("playercomponent").load();
	    }

	    function onytplayerStateChange(newState) {
	        //unstarted (-1), ended (0), playing (1), paused (2), buffering (3), video cued (5)
	        switch (newState) {
	            case 0:
	                //play next video in playlist, instance of plugin is in data
	                $(ytplayer).parent().parent().parent().data("playercomponent").next();
	                break;

	        }
	    }
	    
(function($) {

    $.fn.ChromelessYoutube = function(settings) {
        var clipindex = -1;
        var titleTimeout;
        
        var config = {
            width: 640,
            height: 360,
            playlistWidth: 260,
            playlistID: '021B87CCA16D5E96',
            highdef: 1, // 1 for high-def, 0 for default
            showPlaylist: true,
            showTitle: true,
            showControls: true,
            maxResults: 50
        };

        if (settings) $.extend(config, settings);        

        init = function(el) {
            //setup element
            setupMainContainer(el);
            setupComponentContainer(el);
            setupTitleContainer(el);
            setupPlayerContainer(el);
            setupPlaylistContainer(el);
            setupControllerContainer(el);

            //setup chromeless youtube player on element with playlist
            loadPlayer(el);

            setupEvents(el);                   
        }

        setupMainContainer = function(el) {
            $(el).css({ 'width': config.width + 'px', 'height': config.height + 'px', 'overflow': 'hidden' });
        }

        setupComponentContainer = function(el) {
            var componentContainer = $("<div />").attr("id", "componentContainer");
            componentContainer.css({ 'width': (config.width + config.playlistWidth) + 'px', 'height': config.height + 'px', 'position': 'relative' });
            $(el).append(componentContainer);
        }

        setupTitleContainer = function(el) {
            var titleContainer = $("<div />").attr("id", "titleContainer").attr("hidden", "true");
            titleContainer.css({ 'width': config.width + 'px', 'height': '20px', 'position': 'absolute', 'left': '0px', 'top': '-20px'});
            
            titleContainer.append( $("<div />").attr("id", "label" ) );
            $("#componentContainer", $(el)).append(titleContainer);
        }

        setupPlayerContainer = function(el) {
            var playerContainer = $("<div />").attr("id", "playerContainer");
            playerContainer.css({ 'width': config.width + 'px', 'height': config.height + 'px', 'float': 'left' });
            $("#componentContainer", $(el)).append(playerContainer);
        }

        setupPlaylistContainer = function(el) {
            var playlistContainer = $("<div />").attr("id", "playlistContainer").attr("hidden", "true");
            playlistContainer.css({
                'width': config.playlistWidth + 'px',
                'height': (config.height - 40) + 'px',
                'float': 'left',
                'overflow-y': 'auto',                
                'position': 'relative',
                'margin': '20px 0px 20px 0px'
            });
            $("#componentContainer", $(el)).append(playlistContainer);
        }

        setupControllerContainer = function(el) {
            var controllerContainer = $("<div />").attr("id", "controllerContainer").attr("hidden", "true");
            controllerContainer.css({ 'width': config.width + 'px', 'height': '20px', 'position': 'relative', 'left': '0px', 'top': '0px', 'clear':'left'});

            var list = $("<ul />");            
            list.append( $('<li><a href="#">previous</a></li>').click( function() { playPreviousVideo( el ); return false; } ) );            
            list.append( $('<li><a href="#">next</a></li>').click( function() { playNextVideo( el ); return false; } ) );
            list.append( $('<li><a href="#">pause</a></li>').click( function() { pauseVideo( el ); return false; } ) );
            list.append( $('<li><a href="#">play</a></li>').click( function() { playVideo( el ); return false; } ) );
            list.append( $('<li><a href="#">mute</a></li>').click( function() { muteVideo( el ); return false; } ) );
            list.append( $('<li><a href="#">umute</a></li>').click( function() { unmuteVideo( el ); return false; } ) );
            controllerContainer.append(list);
            
            $("#componentContainer", $(el)).append(controllerContainer);
        }

        loadPlayer = function(el) {
            var playerPlaceholder = $("<div />").attr("id", "playerplaceholder");
            $("#playerContainer", $(el)).append(playerPlaceholder);

            var uniquePlayerId = "youtubeplayer" + $(el).attr("id");

            var flashvars = {
                rel: 0,
                color1: '0x2b405b',
                color2: '0x000000',
                border: 0,
                fs: 1,
                iv_load_policy: 3,
                showinfo: 0,
                showsearch: 0,
                hd: config.highdef,
                enablejsapi: 1,
                playerapiid: uniquePlayerId
            };
            var params = {
                width: config.width,
                height: config.height,
                allowfullscreen: "true",
                allowscriptaccess: "always",
                wmode: 'opaque'
            };
            var attributes = {
                id: uniquePlayerId,
                name: uniquePlayerId
            };

            swfobject.embedSWF("http://www.youtube.com/apiplayer", "playerplaceholder", config.width, config.height, "9.0.0", "expressInstall.swf", flashvars, params, attributes);                                           
        }

        showPlaylist = function(el) {
            if (!config.showPlaylist) return false;
            $("#playlistContainer", $(el)).animate({ 'left': '-260px' });
            $("#playlistContainer", $(el)).attr("hidden", "false");
        }

        hidePlaylist = function(el) {
            $("#playlistContainer", $(el)).animate({ 'left': '0px' });
            $("#playlistContainer", $(el)).attr("hidden", "true");
        }

        togglePlaylist = function(el) {
            if ($("#playlistContainer", $(el)).attr("hidden") == "true") {
                showPlaylist(el);
            } else {
                hidePlaylist(el);
            }
        }

        showTitleContainer = function(el) {   
            if (!config.showTitle) return false;         
            if ($("#titleContainer", $(el)).attr("hidden")=="false") return false;            
            $("#titleContainer", $(el)).animate({ 'top': '0px' });
            $("#titleContainer", $(el)).attr("hidden", "false");
            return true;
        }

        hideTitleContainer = function(el) {
            if ($("#titleContainer", $(el)).attr("hidden")=="true") return;
            $("#titleContainer", $(el)).animate({ 'top': '-20px' });
            $("#titleContainer", $(el)).attr("hidden", "true");
        }

        showControllerContainer = function(el) {
            if (!config.showControls) return false;
            $("#controllerContainer", $(el)).animate({ 'top':  '-20px' });
            $("#controllerContainer", $(el)).attr("hidden", "false");
        }

        hideControllerContainer = function(el) {
            $("#controllerContainer", $(el)).animate({ 'top':  '0px' });
            $("#controllerContainer", $(el)).attr("hidden", "true");
        }
        setupEvents = function(el) {
            $(el).mouseenter(function() { clearTimeout(titleTimeout); showPlaylist(el); showTitleContainer(el); showControllerContainer(el); });
            $(el).mouseleave(function() { hidePlaylist(el); hideTitleContainer(el); hideControllerContainer(el); });
        }

        loadPlaylist = function(el) {
            //load youtube playlist in json format
            //eg. http://gdata.youtube.com/feeds/api/playlists/021B87CCA16D5E96?v=2&max-results=50&alt=json
            $.getJSON('http://gdata.youtube.com/feeds/api/playlists/' + config.playlistID + '?v=2&max-results=' + config.maxResults + '&alt=json-in-script&callback=?', function(data) {
                //populate playlist
                var playlist = $("<ul />").attr("id", "playlist");

                //remove unsupported clips from list
                for (var i = data.feed.entry.length - 1; i >= 0; i--) {
                    if (data.feed.entry[i].media$group.media$content === undefined || data.feed.entry[i].media$group.media$content[0].type != 'application/x-shockwave-flash') {
                    	data.feed.entry.splice(i, 1);
                    }
                }
                
                for (var i = 0; i < data.feed.entry.length - 1; i++) {
                    var entry = $("<li />");
                    
                    
                    entry.attr("url", data.feed.entry[i].media$group.media$content[0].url);
                    var link = $('<a href="#" />').attr("index", i).text(data.feed.entry[i].title.$t).click( function() { playClip( el, $(this).attr("index") ); return false; } );
                    entry.append(link);
                    playlist.append(entry);
                }

                $("#playlistContainer", $(el)).append(playlist);
                
                playNextVideo(el);
            });

        }
        
        playClip = function(el, index)
        {
	        clipindex = index;

	        var item = $("#playlist", $(el)).find("li:eq(" + index + ")");
	        var url = item.attr("url"); 
	        var title = item.text() + " (" + (index + 1) + " of " + $("#playlist", $(el)).find("li").length + ")";
        	
	        ytplayer.loadVideoByUrl(url,0);
        	
	        //set caption
	        $("#titleContainer #label", $(el)).text( title );
	        //showcaption for a moment	        
	        if (showTitleContainer(el))
	            titleTimeout = setTimeout( function() { hideTitleContainer(el); }, 7000);
        	
	        //clear active class on all items
	        $("#playlist", $(el)).find("li").removeClass("active");
	        //set active class
	        item.addClass("active");

	        //scroll item into view
	        var targetOffset = $("#playlistContainer", $(el)).offset().top - item.offset().top + ((config.height / 2 ) - 20);
	        $("#playlistContainer", $(el)).animate({scrollTop: '-=' + targetOffset + 'px'});
        }  

        playNextVideo = function(el) {     
        	
	        clipindex++;
	        if (clipindex >= $("#playlist", $(el)).find("li").length)
		        clipindex = 0;

	        playClip(el, clipindex);

        }

        playPreviousVideo = function(el) {	        
        	
	        clipindex--;
	        if (clipindex < 0)
		        clipindex = $("#playlist", $(el)).find("li").length - 1;

	        playClip(el,clipindex);

        }
        
        pauseVideo = function(el) {
            ytplayer.pauseVideo();
        }
        
        playVideo = function(el) {
            ytplayer.playVideo();
        }
        
        muteVideo = function(el) {
            ytplayer.mute();
        }
        
        unmuteVideo = function(el) {
            ytplayer.unMute();
        }
        
        this.next = function() {
            playNextVideo($(this));
        }
        
        this.previous = function() {
            playPreviousVideo($(this));
        }
        
        this.play = function() {
            playVideo($(this));
        }
        
        this.pause = function() {
            pauseVideo($(this));
        }
        
        this.mute = function() {
            muteVideo($(this));
        }
        
        this.unmute = function() {
            unmuteVideo($(this));
        }
        
        this.load = function() {
            loadPlaylist($(this));
        }

        this.each(function() {
            //setup element            
            init(this);
        });

        //put instance of this object in data
        $(this).data("playercomponent", this);        
        return this;

    };

})(jQuery);

        