AppRegistry.registerBundle({applicationId:'youtubePlayer|0.1.5',bundle: {}});
AppRegistry.registerModule({applicationId:'youtubePlayer|0.1.5',path:'/reducer',module:function(define){'use strict';define(function (require) {
    'use strict';

    var _ = require('underscore');

    var reducer = function (state, action) {
        switch (action.type) {
            case 'CHANGE':
                return _.extend({}, state, {
                    videos:action.videos
                });
            case 'SET_CURRENT_VIDEO':
                return _.extend({}, state, {
                    videoList: _.map(state.videoList, function(videoData){
                        return {
                            videos: _.map(videoData.videos, function(video){
                                if (video.id === action.id) {
                                    return _.extend({}, videoData, {
                                        isCurrent: true
                                    })
                                }
                                if (video.isCurrent && video.id != action.id){
                                    return _.extend({}, videoData, {
                                        isCurrent: false
                                    })
                                }
                                return video;
                            })
                        }

                    })
                })
            default:
                return state
        }

    }

    return reducer;
});}});
AppRegistry.registerModule({applicationId:'youtubePlayer|0.1.5',path:'/template/video',module:function(define){define(function(require){var _=require('underscore');return function(obj){
var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};
with(obj||{}){
__p+='<h3 class="youtube-playlist-group-header">'+
((__t=(header))==null?'':_.escape(__t))+
'</h3>\r\n';
 _.each(videos, function(video){
__p+='\r\n    <p class="youtube-playlist-video youtube-playlist-video-'+
((__t=(video.url))==null?'':_.escape(__t))+
'" data-nb-url-id="'+
((__t=(video.url))==null?'':_.escape(__t))+
'">'+
((__t=(video.name))==null?'':_.escape(__t))+
'</p>\r\n';
}) 
__p+='';
}
return __p;
};});}});
AppRegistry.registerModule({applicationId:'youtubePlayer|0.1.5',path:'/template/player',module:function(define){define(function(require){var _=require('underscore');return function(obj){
var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};
with(obj||{}){
__p+='';
}
return __p;
};});}});
AppRegistry.registerModule({applicationId:'youtubePlayer|0.1.5',path:'/component/Player',module:function(define){'use strict';define(function (require) {
    'use strict';

    var
        _ = require('underscore'),
        Component = require('Component'),
        template = require('/template/player');

    return Component.extend({

        template: template,

        events: {
            global: {
                'source:update:single': 'globalPlaySingleVideo'
            },
            app: {
                'youtubeApi:loaded': 'handleYoutubeApiLoaded',
                'video:play:single': 'playSingleVideo'
            }
        },

        handleYoutubeApiLoaded: function () {
            let that = this;
            this.currentVideo = this.state.options.firstVideo;
            this.player = new YT.Player('player', {
                height: that.state.options.height,
                width: that.state.options.width,
                videoId: that.state.playList[that.initVideo()],
                playerVars: {
                    rel: 0,
                },
                events: {
                    'onReady': onPlayerReady,
                    'onStateChange': onPlayerStateChange
                }
            });
            function onPlayerReady(event) {
                if (that.state.options.autoplay && that.state.online ) {
                    that.play(event.target);
                    // event.target.loadVideoById(that.state.playList[that.currentVideo]);
                    // store.dispatch({
                    //     type: 'SET_CURRENT_VIDEO',
                    //     id: that.state.playList[that.currentVideo]
                    // });
                    //that.currentVideoClass(that.state.playList[that.currentVideo])
                }
            }
            function onPlayerStateChange(event) {
                let playerState = that.state;

                if (event.data === YT.PlayerState.ENDED) {
                    playerState.options.shuffle ? that.shuffle() : that.currentVideo++;

                    if (that.currentVideo < playerState.playList.length) {
                        that.player.loadVideoById(playerState.playList[that.currentVideo]);
                    }
                    else {
                        if (playerState.options.loop || playerState.shuffle) {
                            that.currentVideo = 0;
                            that.player.loadVideoById(playerState.playList[that.currentVideo]);
                        }
                    }
                    
                    //that.currentVideoClass(playerState.playList[that.currentVideo])
                }
            }
        },

        //Player
        initVideo: function(){
            if (this.state.options.shuffle && !this.state.options.hasFirstVideo) {
                this.shuffle();
            }
            return this.currentVideo;
        },

        play: function(){
            this.player.loadVideoById(this.state.playList[this.currentVideo]);
            //set current target, remove old target

            // store.dispatch({
            //     type: 'SET_CURRENT_VIDEO',
            //     id: this.state.playList[this.currentVideo]
            // });
        },

        shuffle: function() {
            let newVideo = this.currentVideo;
            while (newVideo === this.currentVideo) {
                newVideo = Math.floor(Math.random() * this.state.playList.length);
            }
            this.currentVideo = newVideo;
        },

        //Handlers
        playSingleVideo: function (event) {
            this.player.loadVideoById(event.videoUrl);
            this.currentVideoClass(event.videoUrl);
            this.scrollToVideo();
        },

        //temp handler
        globalPlaySingleVideo:function(event){
            this.player.loadVideoById(event.videos);
            this.scrollToVideo();
        },

        scrollToVideo: function(){
            var playerElement = document.getElementsByClassName('youtube-playlist-player')[0];
            playerElement.scrollIntoView({ behavior: "smooth" });
        },

        //Init State
        filterState: function (state) {
            return _.extend({}, {
                playList: state.playList,
                options: state.options,
                online: state.online,
                firstVideo: state.firstVideo
            });
        },

        // currentVideoClass: function (currentVideoId) {
        //     var videoElements = document.getElementsByClassName('youtube-playlist-video');
        //     for (var i = 0; i < videoElements.length; i++) {
        //         videoElements[i].classList.remove('youtube-playlist-video-current');
        //     }
        //     var videoCurrent = document.getElementsByClassName('youtube-playlist-video-' + currentVideoId)[0];
        //     videoCurrent.classList.add('youtube-playlist-video-current');
        // },
    });
});}});
AppRegistry.registerModule({applicationId:'youtubePlayer|0.1.5',path:'/template/main',module:function(define){define(function(require){var _=require('underscore');return function(obj){
var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};
with(obj||{}){
__p+='<div class="youtube-playlist">\r\n    <div class="youtube-playlist-player">\r\n        <div id="player"></div>\r\n    </div>\r\n\r\n    '+
((__t=( renderer.renderComponent('Player') ))==null?'':__t)+
'\r\n    ';
 if(!options.hidePlayList) {
__p+='\r\n        <div class="youtube-playlist-groups youtube-playlist-groups-3">\r\n            '+
((__t=( renderer.renderComponent('PlayLists') ))==null?'':__t)+
'\r\n        </div>\r\n    ';
}
__p+='\r\n</div>';
}
return __p;
};});}});
AppRegistry.registerModule({applicationId:'youtubePlayer|0.1.5',path:'/component/PlayLists',module:function(define){'use strict';define(function (require) {
    'use strict';

    var
        _ = require('underscore'),
        ListComponent = require('ListComponent');

    return ListComponent.extend({


        tagName: 'div',

        className: 'youtube-playlist-group-items',

        childProperty: 'playList',

        childComponentPath: 'PlayList',


        filterState: function (state) {
            return _.extend({}, {
                playList: state.videoList
            });
        }
    });
});}});
AppRegistry.registerModule({applicationId:'youtubePlayer|0.1.5',path:'/component/PlayList',module:function(define){'use strict';define(function (require) {
    'use strict';

    var
        Component = require('Component'),
        app = require('app'),
        template = require('/template/video');

    return Component.extend({

        className:'youtube-playlist-group-item',

        template: template,

        events: {
            dom:{
                'click .youtube-playlist-video': 'playVideo'
            },

        },

        playVideo: function(target){
            let url = this.$(target.currentTarget).attr('data-nb-url-id');
            app.trigger('video:play:single', {
                videoUrl: url,
                target: target.currentTarget
            });
        }

    });
});}});
AppRegistry.registerModule({applicationId:'youtubePlayer|0.1.5',path:'/main',module:function(define){'use strict';define(function (require) {
	'use strict';

	var
		_ = require('underscore'),
		Component = require('Component'),
		app = require('app'),
		template = require('/template/main');
	


	return Component.extend({
		template: template,
		onInit: function () {
			this.createYoutubeScript();
		},

		createYoutubeScript: function () {
			var youtubeScript = document.createElement('script');
			youtubeScript.src = '//www.youtube.com/iframe_api';
			var firstScriptTag = document.getElementById('player');
			firstScriptTag.parentNode.insertBefore(youtubeScript, firstScriptTag);
			youtubeScript.addEventListener('load', function () {
				window.onYouTubeIframeAPIReady = function () {
					app.trigger('youtubeApi:loaded');
				};		
			});

		},
	});
});}});