
var PersonalityVideosManager = new Class({
	ClassName: 'PersonalityVideosManager',
	Extends: Base,

	options: {
		commentsPerPage: 10
	},

	initialize: function() {
		this.parent();

		/* Media Player */
		this.mediaPlayer = $('media-player');
		this.gid      = MonsterUser.groupId;
		this.account  = this.mediaPlayer.get('account');
		this.videosTv = this.mediaPlayer.getElement('#videos-tv');
		this.playerCt = this.videosTv.getElement('div.kyte-player');
		this.videoTab = $$('h2.videos')[0];

		/* Video Share & Produce */
		this.videosTv.getElement('a.share').addEvent('click', function(event) { event.stop(); this.kyteplayer.display('ShareEmbed'); }.bind(this));
		this.videosTv.getElement('a.produce').addEvent('click', function(event) { event.stop(); this.kyteplayer.display('Producer'); }.bind(this)).hide();

		/* Video rating */
		this.videoRateStars = new RatingStars({
			container: this.videosTv,
			label: true,
			readOnly: !themeDisplay.isSignedIn(),
			onRecordRating: function(userRating) { this.recordVideoRating(userRating); }.bind(this)
		});

		/* Comments */
		this.commentCt   = this.mediaPlayer.getElement('div.player-comments');
		this.commentList = this.commentCt.getElement('ul');
		this.commentBox  = this.commentCt.getElement('input.comment-box');
		this.commentBtn  = this.commentCt.getElement('input.comment-submit');
		this.commentCt.getElement('span.prev').addEvent('click', function(event) { event.stop(); this.prevCommentPage(); }.bind(this));
		this.commentCt.getElement('span.next').addEvent('click', function(event) { event.stop(); this.nextCommentPage(); }.bind(this));
		this.commentScroll = new ScrollBar(this.commentCt.getElement('div.viewport'));
		this.commentCount    = 0;
		this.commentCountLbl = this.commentCt.getElement('span.commentcount');

		/* Thumb Gallery */
		this.mediaGallery = $('media-gallery');
		this.thumbList = this.mediaGallery.getElement('ul.thumb-list');
		this.gallery = {
			itemsPerPage: 8,
			numVideoItems: 0,
			videoPages: new Hash()
		}

		/* Video sorting */
		this.currentVideoSort = "created";
		this.videoSorting = new DropDown({
			id: 'video-sorting',
			container: this.mediaGallery.getElement('div.top'),
			items: [
				{text:'Most recent',  value: 'created'},
				{text:'Most popular', value: 'popular'},
				{text:'Most watched', value: 'mostwatched'},
				{text:'Top rated',    value: 'toprated'}
			],
			onItemSelected: function(sort) {
				// console.log('New videos sort:', sort);
				if (sort == this.currentVideoSort) return;
				this.currentVideoSort = sort;
				this.gallery.videoPages.empty();
				this.thumbList.getElements('li.show').destroy();
				this.setPagination();
				this.activeShow = null;
				this.loadPage(1);
			}.bind(this)
		});

		this.mediaPlayer.getElement('div.login')[MonsterUser.loggedIn?'hide':'show']();

		this.kyteAPI = new KyteAPI({
			gid: this.gid,
			onKyteReady: function(){
				// console.log('Kyte ready.');
				this.loadPage(1);
			}.bind(this)
		});
	},

	processMessage: function(msg) {
		if (msg.msg == 'pageChanged') {
			this.loadPage(msg.data.page);
		}
		else if (msg.msg == 'tabChanged' && msg.data.className != 'videos') {
			if (this.kyteplayer) 
				this.kyteplayer.queue("controllerAction", "player.stop");
		}
	},

	setPagination: function() {
		this.gallery.numPages = Math.ceil(this.gallery.numVideoItems / this.gallery.itemsPerPage);
		// console.log('Setting flash pagination: numPages=%d', this.gallery.numPages);
		if (Monster.flashMovie('flashpagination').initPagination && Monster.flashMovie('flashpagination').initPagination(this.gallery.numPages)) {
			this.paginationSet = true;
		} else {
			setTimeout(function(){this.setPagination.call(this)}.bind(this), 1000);
		}
	},

	loadPage: function(page) {
		// console.log('loading page...', page);
		this.thumbList.getChildren().each(function(item){item.hide()});
		if (this.gallery.videoPages.has(page)) {
			this.displayVideosPage(page);
		} else {
			this.loadVideos(page);
		}
	},

	displayVideosPage: function(page) {
		// console.log('showing videos page', page);
		if (page > 1 || this.gallery.videoPages.get(page).length > 0) {
			if (!this.paginationSet) this.setPagination();
			this.gallery.videoPages.get(page).each(function(thumb) { thumb.element.show(); }.bind(this));
			if (!this.activeShow) this.gallery.videoPages.get(page)[0].activate();
		}
	},

	loadVideos: function(page) {
		if (!this.kyteAPI.ready) {
			console.warn('KyteAPI not ready.');
			return;
		}

		// console.log('loading videos (page %d)...', page);

		var sort = ',"orderSpec":"createdTime-d"';
		if (this.currentVideoSort == "popular")     sort = ',"orderSpec":"totalMessageCount-d"'; else
		if (this.currentVideoSort == "mostwatched") sort = ',"orderSpec":"totalWatches-d"';      else
		if (this.currentVideoSort == "toprated")    sort = ',"orderSpec":"averageTenths-d"';

		var channelId = '';

		if (this.kyteAPI.data.groupChannels) {
			var channelId = ",\"parentUri\":\""+this.kyteAPI.data.groupChannels.restricted.uri+"\"";
			// console.log('channelId', channelId);
			// If user has procude permissions...
			if (themeDisplay.isSignedIn() && MonsterUser.videoProducer) {
				this.setPlayerUri(this.kyteAPI.data.groupChannels.restricted.uri);
				if (this.videoTab) this.videoTab.show();
				this.videosTv.getElement('a.produce').show();
			}
		}

		this.kyteAPI.request({
			account:    this.account,
			handler:    'channelService',
			command:    'findShows',
			parameters: '&frt=' + (page-1)*this.gallery.itemsPerPage + '&mrs=' + this.gallery.itemsPerPage +
						'&cta={"accountUri":"account/apikey"' + sort + channelId + '}',
			onComplete: function(request, data) {
				this.gallery.videoPages.set(page, []);
				this.gallery.numVideoItems = data.result.totalSize;
				// console.log('Event shows:');
				if (data.result.items.length) {
					data.result.items.each(function(show) {
						this.gallery.videoPages.get(page).push(new KyteShow(this, show));
						// console.dir(show);
					}.bind(this));
					if (this.videoTab) this.videoTab.show();
				}
				this.displayVideosPage(page);
			}.bind(this)
		});
	},

	setPlayerUri: function(uri) {
		// console.log('setPlayerUri', uri);
		if (this.kyteplayer) {
			this.kyteplayer.setURI(uri);
		} else {
			this.kyteplayer = new Kyte.Player(uri, 
				$extend(this.kyteAPI.options.playerSettings, {
					ak: this.kyteAPI.data.accounts.embed.ak,
					as: this.kyteAPI.data.accounts.embed.as,
					tk: this.kyteAPI.ticket
				}), this.playerCt);
		}
		// window.kyteplayer = this.kyteplayer;
		// console.log('setUserTicket', this.kyteAPI.ticket);
		//this.kyteplayer.queue('setUserTicket', [this.kyteAPI.ticket, false]);
	},

	setShow: function(activeShow) {
		this.activeShow = activeShow;
		// console.log('setShow', this.activeShow.data.uri);
		this.setPlayerUri(this.activeShow.data.uri);
		this.videoRateStars.setRating((this.activeShow.data.rateSum||0) / (this.activeShow.data.rateCount||1));
	},

	recordVideoRating: function(userRating) {
		if (!this.activeShow) return;
		this.kyteAPI.request({
			handler:    this.activeShow.data.uri,
			command:    'recordRating',
			parameters: '&rv=' + userRating
		});
		// this.activeShow.fetchMetaData();
	},

	updateCommentLbl: function() {
		this.commentCountLbl.set('text', this.commentCount + ' comments (' + (this.currentCommentPage||1) + '/' + (this.commentPageCount||1) + ')');
	},

	nextCommentPage: function() {
		if (this.currentCommentPage*this.options.commentsPerPage >= this.commentCount) return;
		if (!this.activeShow) return;
		this.currentCommentPage++;
		this.activeShow.clearMessages();
		this.activeShow.loadComments();
		this.updateCommentLbl();
	},

	prevCommentPage: function() {
		if (this.currentCommentPage <= 1) return;
		if (!this.activeShow) return;
		this.currentCommentPage--;
		this.activeShow.clearMessages();
		this.activeShow.loadComments();
		this.updateCommentLbl();
	}
});

new PersonalityVideosManager();
