/// <reference path="jquery-1.4.1.min-vsdoc.js" />

/*
jqYoutubePlaylist - (c) 2010 - Emil Müller
renders a youtube playlist
Released under the GPL License
http://www.gnu.org/licenses/gpl-3.0.txt
	
requires:
- jQuery 1.4.x
- SWFObject 2
*/
var ytplayer = null;

function onYouTubePlayerReady(playerId) {

    ytplayer = document.getElementById(playerId);
    ytplayer.addEventListener("onStateChange", "onytplayerStateChange");

    ytplayer.loadVideoByUrl($("#" + playerId).attr("url"), 0);
}

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("playlistcomponent").showP();
            break;

    }
}

jQuery.jQueryRandom = 0;
jQuery.extend(jQuery.expr[":"],
{
    random: function(a, i, m, r) {
        if (i == 0) {
            jQuery.jQueryRandom = Math.floor(Math.random() * r.length);
        };
        return i == jQuery.jQueryRandom;
    }
});
(function($) {

    $.fn.YoutubePlaylist = function(settings, onCompleteFunc) {

        var config = { PlaylistID: 'B6BE2043B97A995E',
            clearFloating: true,
            playOnMouseOver: true,
            pageSize: 4,
            width: 715,
            height: 500
        };
        var playlist = null;
        var currentPage = 1;
        var pageCount = 0;
        var clipIndex = -1;
        var ti = -1;

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

        init = function(el) {
            //hide the contents
            $(el).hide();
            $(el).css({ width: config.width + 'px', height: config.height + 'px' });

            setupPlaylistContainer(el);
            setupPlayerContainer(el);

            //hide playercontainer
            $("#playercontainer").hide();

            //determine pagesize
            var x = Math.floor($(el).width() / 140);
            var y = Math.floor(($(el).height() - 35) / 140);
            config.pageSize = x * y;

            //get the playlist
            getPlaylist(el);
        }

        setupPlaylistContainer = function(el) {
            var playlistContainer = $("<div/>").attr("id", "playlistcontainer");
            playlistContainer.css({ width: config.width + 'px', height: config.height + 'px',clear:'both' });
            $(el).append(playlistContainer);
        }

        setupPlayerContainer = function(el) {
            var playerContainer = $("<div/>").attr("id", "playercontainer");
            playerContainer.css({ width: config.width + 'px', height: config.height + 'px', 'overflow': 'hidden', 'position': 'relative' });
            $(el).append(playerContainer);

            //setup titlecontainer
            var titleContainer = $("#titlecontainer");


            //setup playerplaceholder
            playerContainer.append(getPlayerPlaceHolder(el));
            

            //setup controllercontainer
            var controllerContainer = $("#controllerContainer");
            $('#youtubePlaylist').prepend(controllerContainer);
			$('#youtubePlaylist').prepend(titleContainer);
            controllerContainer.click(function() { showPlaylist($(el)); });

            //bind mouseenter, mouseleave events for controlling player
            playerContainer.mouseenter(function() {
                //show title and controller
                
                $("#controllercontainer", playerContainer).animate({ 'top': (config.height - 20) + 'px' });
            });
            playerContainer.mouseleave(function() {
                //show title and controller
               
                $("#controllercontainer", playerContainer).animate({ 'top': config.height + 'px' });
            });
        }

        getPlayerPlaceHolder = function(el) {
            return $("<div />").attr("id", "playerplaceholder")
                                                .css({
                                                    'position': 'relative',
                                                    'width': config.width + 'px',
                                                    'height': config.height + 'px'
                                                }).data("component", el);
        }

        getPlaylist = function(el) {
            var url = "http://gdata.youtube.com/feeds/api/playlists/" + config.PlaylistID + "?v=2&alt=json-in-script&max-results=50&callback=?"
            $.getJSON(url, function(data) {
                playlist = data;

                renderPlaylist(el, currentPage);
                $(el).show();

                if (typeof onCompleteFunc == 'function') {
                    onCompleteFunc.call(this, $(el));
                }
            });
        }

        renderPlaylist = function(el, pageIndex) {
            //remove unsupported clips from list
            for (var i = playlist.feed.entry.length - 1; i >= 0; i--) {
                if (playlist.feed.entry[i].media$group.media$content === undefined || playlist.feed.entry[i].media$group.media$content[0].type != 'application/x-shockwave-flash') {
                    playlist.feed.entry.splice(i, 1);
                }
            }

            var startIndex = (pageIndex * config.pageSize) - config.pageSize;
            var endIndex = (pageIndex * config.pageSize);
            if (endIndex > playlist.feed.entry.length) endIndex = playlist.feed.entry.length;
            pageCount = Math.ceil(playlist.feed.entry.length / config.pageSize);

            for (var i = startIndex; i < endIndex; i++) {
                var url = playlist.feed.entry[i].media$group.media$content[0].url;

                url = playlist.feed.entry[i].media$group.media$content[0].url;

                var item = $("<div>").addClass("item")
                                     .attr("url", url)
                                     .attr("title", playlist.feed.entry[i].title.$t)
                                     .attr("index", i)
                                     .attr("thumbIndex", "1")
                                     .attr("maximized", "false");

                var thumbnail = $("<div/>").addClass("thumbnail").attr("id", "thumbnail" + i);
                var duration = $("<div/>").addClass("duration").attr("id", "duration" + i).text(playlist.feed.entry[i].media$group.yt$duration.seconds);
                var caption = $("<div/>").addClass("caption");

                item.append(thumbnail);
                thumbnail.append(duration);
                item.append(caption);


                thumbnail.css("background-image", "url('" + playlist.feed.entry[i].media$group.media$thumbnail[1].url + "')");
                caption.text(playlist.feed.entry[i].title.$t);

                //load player ?
                if (config.playOnMouseOver) {
                    item.mouseenter(function() {
                        //loadPlayer($(".thumbnail", $(this)), $(this).attr("url"));
                    	var item = $(this);
                    	ti = setTimeout(function() { thumbnailSwitch(el, item) }, 200);
                    });

                    item.mouseleave(function() {
                        //minimizePlayer($(this));
                        //unloadPlayer($(".thumbnail", $(this)));
                    	clearTimeout(ti);
                    });
                    item.click(function() {
                        //toggleMaximize($(this));
                        hidePlaylist($(el), $(this));
                    });
                }

                item.hide();
                $("#playlistcontainer", $(el)).append(item);
                item.fadeIn();
            }

            //create pager
            var navigation = $("<div />").addClass("navigation").css("clear", "both");
            if (pageIndex > 1)
                navigation.append($("<a><span class='imgPrev'><!-- Vorige button --></span></a>").click(function() { previous(el); }));
            /*
			if (pageCount > 1) {
                for (var i = 1; i <= pageCount; i++) {
                    navigation.append($("<div class='button'>" + i + "</div>").click(function() { gotoPage(el, $(this).text()); }));
                }
            }*/
            if (pageIndex < pageCount)
                navigation.append($("<a><span class='imgNext'><!-- Volgende button --></span></a>").click(function() { next(el); }));
            $("#playlistcontainer", $(el)).append(navigation);

            //$(el).append($("<div />").css({ 'clear': 'both' }));
            clipIndex = -1;

            //ti = setTimeout(function() { thumbnailSwitch(el) }, 200);
        }

        thumbnailSwitch = function(el, item) {
            //loop through each item and change the thumbnail
            clipIndex++;
            if ($(".item:eq(" + clipIndex + ")", $(el)).length <= 0) clipIndex = 0;
            //$(".item:eq(" + clipIndex + ")", $(el)).each(function() {
            //$(".item:random", $(el)).each(function() {
                var thumbIndex = $(item).attr("thumbIndex");
                thumbIndex++;
                if (thumbIndex > 3) thumbIndex = 1;
                $(item).attr("thumbIndex", thumbIndex);

                var imgurl = playlist.feed.entry[$(item).attr("index")].media$group.media$thumbnail[thumbIndex].url;
                var item = $(item);
                $("<img />").attr("src", imgurl)
                            .load(function() {
                                $(".thumbnail", item).css("background-image", "url('" + imgurl + "')");


                            });
            //});
            ti = setTimeout(function() { thumbnailSwitch(el, item) }, 400);
        }

        hidePlaylist = function(el, item) {
            $("#playlistcontainer", $(el)).fadeOut(function() {
                loadPlayer($("#playerplaceholder", $(el)), $(item).attr("url"));
                $("#titlecontainer", $(el)).text($(item).attr("title")).css("visibility","visible");
				$("#controllerContainer", $(el)).css("visibility","visible");
                $("#playercontainer", $(el)).fadeIn();
            });
        }

        showPlaylist = function(el) {
            $("#playercontainer", $(el)).fadeOut(function() {
                unloadPlayer($("#playerplaceholder", $(el)));
				$("#titlecontainer", $(el)).css("visibility","hidden");
				$("#controllerContainer", $(el)).css("visibility","hidden");
                $("#playlistcontainer", $(el)).fadeIn();
            });
        }

        this.showP = function() {
            showPlaylist($(this));
        }

        loadPlayer = function(item, url) {
            var playerPlaceholder = $("<div />").attr("id", "innerplayerplaceholder").css("position", "relative");
            item.append(playerPlaceholder);

            var uniquePlayerId = "youtubeplayer" + item.attr("id");

            var flashvars = {
                rel: 0,
                color1: '0x2b405b',
                color2: '0x000000',
                border: 0,
                fs: 1,
                iv_load_policy: 3,
                showinfo: 0,
                showsearch: 0,
                hd: 1,
                enablejsapi: 1,
                playerapiid: uniquePlayerId
            };
            var params = {
                width: '100%',
                height: '100%',
                allowfullscreen: "true",
                allowscriptaccess: "always",
                wmode: 'opaque'
            };
            var attributes = {
                id: uniquePlayerId,
                name: uniquePlayerId,
                url: url
            };

            swfobject.embedSWF("http://www.youtube.com/apiplayer", "innerplayerplaceholder", "100%", "100%", "9.0.0", "http://localhost/kvh/swf/expressInstall.swf", flashvars, params, attributes);
        }

        unloadPlayer = function(item) {
            item.empty();
        }

        toggleMaximize = function(item) {
            if ($(item).attr("maximized") == "true") minimizePlayer(item); else maximizePlayer(item);
        }

        minimizePlayer = function(item) {
            if ($(item).attr("maximized") == "true") {
                $(item).attr("maximized", "false");
                /*$(item).css({ 'width': '120px', 'height': '90px',
                'position': 'static',
                'left': '0px',
                'top': '0px'
                });*/
                $(".thumbnail", $(item)).css({ width: '120px', height: '90px', 'margin-top': '5px', 'margin-bottom': '5px', 'margin-left': 'auto', 'margin-right': 'auto' });
                $(".caption", $(item)).show();
                $(item).css({ width: '140px', height: '140px' });
                $(".item").show();

                $(".navigation").show();
                item.mouseenter(function() {
                    loadPlayer($(".thumbnail", $(this)), $(this).attr("url"));
                });

                item.mouseleave(function() {
                    minimizePlayer($(this));
                    unloadPlayer($(".thumbnail", $(this)));
                });
            }
        }

        maximizePlayer = function(item) {
            if ($(item).attr("maximized") == "false") {
                /*$(item).css({ 'width': '100%', 'height': '100%',
                'position': 'absolute',
                'left': '0px',
                'top': '0px'
                });*/

                var height = $(item).parent().height();
                var width = $(item).parent().width();

                //hide all items
                $(".item").hide();
                $(item).show();
                $(item).css({ width: '100%', height: '100%' });
                $(".caption", $(item)).hide();
                //larger thumbnail
                $(".thumbnail", $(item)).css({ width: width + 'px', height: height + 'px', 'margin-top': '0', 'margin-bottom': '0', 'margin-left': '0', 'margin-right': '0' });

                $(".navigation").hide();

                //unbind mouseleave
                $(item).unbind('mouseleave');
                $(item).unbind('mouseenter');

                $(item).attr("maximized", "true");
            }
        }

        next = function(el) {
            clearTimeout(ti);
            $("#playlistcontainer", $(el)).fadeOut(function() {
                $("#playlistcontainer", $(el)).empty();
                currentPage++;
                renderPlaylist(el, currentPage);
                $("#playlistcontainer", $(el)).show();
            });
        }

        previous = function(el) {
            clearTimeout(ti);
            $("#playlistcontainer", $(el)).fadeOut(function() {
                $("#playlistcontainer", $(el)).empty();
                currentPage--;
                renderPlaylist(el, currentPage);
                $("#playlistcontainer", $(el)).show();
            });
        }

        gotoPage = function(el, i) {
        	clearTimeout(ti);
            $("#playlistcontainer", $(el)).fadeOut(function() {
                $("#playlistcontainer", $(el)).empty();
                currentPage=i;
                renderPlaylist(el, currentPage);
                $("#playlistcontainer", $(el)).show();
            });
        }

        this.each(function() {
            init(this);
        });
        
        $(this).data("playlistcomponent", this); 
        return this;
    };

})(jQuery);
