
/*
	KyteMedia.js

	KyteMediaManager enables interaction between DOM objects, Kyte Video player,
	KyteShows, KyteChannels and KyteComments.

	KyteShow handles specific Kyte video functions

	KyteChannel handles specific Kyte channel functions

	Developed by Eneko Alonso
	ealonso@level-studios.com
	Copyright 2009 LEVEL Studios

*/


var KyteShow = new Class({
	ClassName: 'KyteShow',

	initialize: function(manager, show) {
		this.manager = manager;
		this.data = show;

		// Check if a comment thread has been created yet
		if (!this.data.commentThreadUri)
			this.fetchCommentThread();

		this.addToDOM();
		this.hookControls();
	},

	addToDOM: function() {
		this.element = new Element('li', {'class': 'thumb show'});
		this.element.grab(new Element('img', {src: this.data.thumb120x90Url}));
		this.element.grab(new Element('div', {'class': 'frame frame'+Random(1,4)}));
		this.element.grab(new Element('div', {'class': 'info', html: '<h4></h4><p class="owner"></p><p class="duration"></p><p class="posteddate"></p>'}))
		this.element.getElement('h4').set('text', this.data.title);
		this.element.getElement('p.owner').set('text', this.data.ownerName);
		if (this.data.mediaDurationMillis) this.element.getElement('p.duration').set('text', 'Length: ' + Monster.msecToMinSec(this.data.mediaDurationMillis));
		this.element.getElement('p.posteddate').set('text', Monster.dateFromISO8601(this.data.createdTime).format('%x %X'));
		this.manager.thumbList.grab(this.element);

		this.miniStars = new RatingStars({ container: this.element, readOnly: true, mini: true, rating: (this.data.rateSum||0) / (this.data.rateCount||1) });

		this.element.getElement('img').addEvent('click', function(event) { event.stop(); this.activate(); }.bind(this));
		this.element.getElement('div.frame').addEvent('click', function(event) { event.stop(); this.activate(); }.bind(this));
		this.element.getElement('h4').addEvent('click', function(event) { event.stop(); this.activate(); }.bind(this));
	},

	activate: function() {
		this.manager.thumbList.getChildren().removeClass('selected');
		this.element.addClass('selected');

		/* Comment form */
		if (MonsterUser.loggedIn) {
			this.manager.commentBtn.getParent('form').show();
			this.manager.commentBtn.getParent('form').removeEvents();
			this.manager.commentBtn.getParent('form').addEvent('submit', function(event) {
				event.preventDefault();
				this.postMessage();
			}.bind(this));
		}
		this.manager.commentList.empty();

		/* Player */
		this.manager.setShow(this);

		this.fetchMetaData();
	},

	showMetaData: function() {
		/* Load last page of messages */
		this.manager.commentCount = (this.data.totalMessageCount)? this.data.totalMessageCount : 0;
		this.manager.commentPageCount = Math.ceil(this.manager.commentCount/this.manager.options.commentsPerPage);
		this.manager.currentCommentPage = this.manager.commentPageCount;
		this.manager.updateCommentLbl();
		this.loadComments();
	},

	/* API Functions */

	fetchMetaData: function() {
		this.manager.kyteAPI.request({
			handler:    this.data.uri,
			command:    'fetchMetaData',
			parameters: '',
			onComplete: function(request, data) {
				this.data = data.result;
				this.showMetaData();
			}.bind(this)
		});
	},

	// listMedia: function() {
	// 	this.manager.kyteAPI.request({
	// 		handler:    this.data.uri,
	// 		command:    'listMedia',
	// 		parameters: '',
	// 		onComplete: function(request, data) {
	// 			this.media = data.result;
	// 		}.bind(this)
	// 	});
	// },


	/* API comments/chat functions */

	fetchCommentThread: function() {   /* Creates the thread if not exists */
		this.manager.kyteAPI.request({
			handler:    this.data.uri,
			command:    'fetchCommentThread',
			onComplete: function(request, data) {
				this.data.commentThreadUri = data.result.uri;
			}.bind(this)
		});
	},

	// fetchLatestMessages: function(max) {
	// 	if (!this.data.commentThreadUri) return;
	// 	this.manager.kyteAPI.request({
	// 		handler:    this.data.commentThreadUri,
	// 		command:    'fetchLatestMessages',
	// 		parameters: '&tk=' + KyteKeys.ticket + '&mrs=' + max,
	// 		onComplete: function(request, data) {
	// 			this.showMessages(data.result.items);
	// 		}.bind(this)
	// 	});
	// },

	fetchMessages: function(start, max, position) {
		if (!this.data.commentThreadUri) return;
		this.manager.kyteAPI.request({
			handler:    this.data.commentThreadUri,
			command:    'fetchMessages',
			parameters: '&tk=' + this.manager.kyteAPI.ticket + '&frt='+ start + '&mrs=' + max,
			onComplete: function(request, data) {
				this.showMessages(data.result.items, position);
			}.bind(this)
		});
	},

	postMessage: function() {
		if (!this.manager.activeShow) return;
		if (!this.data.commentThreadUri) return;
		if (this.manager.commentBox.value.trim() == '') return;
		this.manager.kyteAPI.request({
			handler:    this.data.commentThreadUri,
			command:    'postMessage',
			parameters: '&tk=' + this.manager.kyteAPI.ticket + '&mt=' + escape(this.manager.commentBox.value) + '&fromName=' + MonsterUser.userName,
			onComplete: function(request, data) {
				this.manager.commentCount++;
				this.manager.commentPageCount = Math.ceil(this.manager.commentCount/this.manager.options.commentsPerPage);
				this.manager.currentCommentPage = this.manager.commentPageCount;
				this.manager.updateCommentLbl();
				this.loadComments('bottom');
			}.bind(this)
		});
		this.manager.commentBox.set('value', '').focus();
	},

	loadComments: function(position) {
		this.fetchMessages((this.manager.currentCommentPage-1)*this.manager.options.commentsPerPage, this.manager.options.commentsPerPage, position);
	},

	showMessages: function(messages, position) {
		this.manager.commentList.empty(); // For consistency with photo comments
		if (position != 'bottom') this.manager.commentScroll.scrollToTop();
		messages.each(function(comment) {
			var id = 'comment-' + this.data.commentThreadUri.match(/\d+/) + '-' + comment.messageIndex;
			// if ($(id)) return;
			if (comment.fromName == 'monster-energy-drinks') comment.fromName = 'anonymous';

			var msg = new Element('li', {'class': 'comment', 'id': id});
			msg.grab(new Element('span', {'class': 'user', text: comment.fromName}));
			msg.grab(new Element('span', {'class': 'date', text: Monster.dateFromISO8601(comment.time).format('%x %X')}));
			msg.grab(new Element('p', {'class': 'content', text: comment.text}));
			this.manager.commentList.grab(msg);
			this.manager.commentScroll.update();
		}.bind(this));
		if (position == 'bottom') this.manager.commentScroll.scrollToBottom();
	},

	clearMessages: function() {
		this.manager.commentScroll.scrollToTop();
		this.manager.commentList.empty();
		this.manager.commentScroll.update();
	},

	hookControls: function() {
		if (!MonsterUser.loggedIn) return;
		// console.log('VideoThumb: user %s, video %s', this.manager.kyteAPI.data.currentUser.uri, this.data.ownerUri);
		if (this.manager.kyteAPI.data.currentUser.uri != this.data.ownerUri) return;

		this.controls = new Element('div', {'class': 'controls', html: '<a class="edit" href="">e</a><a class="delete" href="">d</a>', styles: {display:'none'}});
		this.element.grab(this.controls);

		this.element.addEvents({
			mouseenter: function() { this.controls.show() }.bind(this),
			mouseleave: function() { this.controls.hide() }.bind(this)
		});

		this.element.getElement('a.delete').addEvent('click', function(event) {
			event.stop();
			this.deleteShow();
		}.bind(this));

		this.element.getElement('a.edit').addEvent('click', function(event) {
			event.stop();
			var h4 = this.element.getElement('h4')
			var input = new Element('input', {type: 'text', value: h4.get('text')});
			input.replaces(h4).focus();
			input.select();
			input.addEvents({
				keyup: function(event) {
					switch (event.key) {
						case 'esc': {
							h4.replaces(input);
							break;
						}
						case 'enter': {
							this.saveTitle(h4, input);
							h4.replaces(input);
							break;
						}
					}
				}.bind(this),
				blur: function() {
					this.saveTitle(h4, input);
					h4.replaces(input);
				}.bind(this)
			});
		}.bind(this));
	},

	saveTitle: function(h4, input) {
		if (h4.get('text') != input.get('value')) {
			h4.set('text', input.get('value'));
			this.manager.kyteAPI.request({
				handler:    this.data.uri,
				command:    'update',
				parameters: '&tk=' + this.manager.kyteAPI.ticket +
							'&sda={"title":"'+ h4.get('text') +'"}',
				onComplete: function(request, data) {
					// console.log('show %s updated', this.data.uri);
				}.bind(this)
			});
		}
	},

	deleteShow: function() {
		if (confirm('Are you sure you want to delete this video?\nThis cannot be undone.')) {
			this.manager.kyteAPI.request({
				handler:    this.data.uri,
				command:    'delete',
				parameters: '&tk=' + this.manager.kyteAPI.ticket,
				onComplete: function(request, data) {
					// console.log('show %s deleted', this.data.uri);
					this.clearMessages();
					new Fx.Morph(this.element).start({opacity:0}).chain(function(){ this.element.destroy() }.bind(this));
				}.bind(this)
			});
		}
	}
});
