var player = function(config, ele){
    var boss = this;
    boss.ele = ele;
    boss.havePlaylist = false;
    boss.requestPlaylist = function(param){
        $.get(config.jsoncFeed(), param,
        function(data){
            var d = eval('('+data+')');
            boss.onload(d);
        });
    }
    window.onYouTubePlayerReady = function(x){
        boss.havePlaylist = true;
    }
    boss.onload = function(feed){
        boss.playlistInit(feed);
    }
    boss.showMe = function(){
        var video = $(this).data('video');
        $(this).addClass('current').siblings('.current').removeClass('current');
        if (!config.playerReady){
            var id = $(config.rel + config.player).attr('id');
            swfobject.embedSWF('http://www.youtube.com/v/' + video.id + '?enablejsapi=1&version=3&playerapiid=ytplayer',
            id, '688', '410', '8', null, null, {
            	allowScriptAccess: 'always',
            	menu: 'false',
        		wmode: 'transparent' 
            },{id:id},
            function(e){
                $(e.ref).addClass(config.rel.replace('.', '')).addClass(config.player.replace('.', ''));
                config.playerReady = true;
            });
        } else{
            var player = $(config.rel + config.player).get(0);
            if (player.getPlayerState() === 1){
                player.loadVideoById(video.id);
            } else{
                player.cueVideoById(video.id);
            }
        }
    }

    boss.playlistInit = function(feed){
      
        boss.totalItems = feed.data.totalItems;
        boss.totalPages = Math.round(feed.data.totalItems / feed.data.itemsPerPage);
        boss.currentPage = Math.round(feed.data.startIndex / feed.data.itemsPerPage);
        boss.nextPageStart = feed.data.startIndex+feed.data.itemsPerPage;
        boss.maxPageStart = feed.data.totalItems-feed.data.itemsPerPage
        
       
        
        if (!boss.havePlaylist){
            $(config.rel + config.playlist).find(config.playlistItems).html('');
            if ($(config.rel + config.playlist).get(0)){
                var SIZE = config.itemsVisible;
                $(config.rel + config.playlist).scrollable({
                    keyboard: true,
                    onBeforeSeek: function(e, tab){
                        if ((tab == (this.getSize() - SIZE) || (this.getSize() - SIZE) < 1) && boss.havePlaylist){
                            boss.requestPlaylist({
                                'max-results': feed.data.itemsPerPage,
                                'start-index': boss.nextPageStart
                            })
                            return false;
                        }
                    }
                });
                boss.scrollerApi = $(config.rel + config.playlist).data('scrollable');
                $(config.rel + config.playlist).mousewheel(function(event, delta){
                    if (delta < 0){
                        boss.scrollerApi.next(100);
                    } else{
                        boss.scrollerApi.prev(100);
                    }
                });
            }
            
        }
        for (i = 0; i < feed.data.items.length; i++){
            boss.addItem(feed.data.items[i]);
        }
        $(config.rel + config.playlist).find(config.playlistItems + ' li:not(.visible)').click(boss.showMe).addClass('visible');
        if (!boss.havePlaylist){
            $(config.rel + config.playlist + ' ' + config.playlistItems + ' li:first').click();
        }       
    }
    boss.addItem = function(item){
        var li = $('<li><img src="' + item.video.thumbnail.sqDefault + '" title="' + item.video.title + '" /><strong>' + boss.clearTitle(item.video.title) + '</strong></li>').data('video', item.video);
        $(config.rel + config.playlist).find(config.playlistItems).append(li);
    }
    boss.clearTitle = function(title){
        return title.replace('Jolaby AW 10 Style ', '');
    }
   boss.requestPlaylist({
        'max-results': config.maxVideos,
        'start-index': 1
    });
}

$.fn.youtubeGallery = function(settings){
    var config = {
        rel: '.yg',
        player: '.player',
        playlist: '.playlist',
        playlistItems: 'ul',
        prev: '.prev',
        next: '.next',
        info: '.info',
        maxVideos: 10,
        itemsVisible : 5,
        playlistId: 'ECAB7E480A4C7C30',
        playerReady: false,
        jsoncFeed: function(){
            return 'https://'+document.location.host+'/youtube_playlist.php?playlistid=' + config.playlistId + '';
        }
    };
    if (settings) $.extend(config, settings);
    this.each(function(){
        $(this).data('player', new player(config, $(this)))
    });
    return this;
};

$(function(){
    $('#myVideoPlayer').youtubeGallery({
        user: 'jolaby'
    })
});
