
var ShoutOutsManager = new Class({
	ClassName: 'ShoutOutsManager',
	Extends: Base,

	initialize: function(){
		this.parent();
		this.gid = MonsterUser.groupId;

		this.shoutOuts = $('shoutout-comments');
		if (this.shoutOuts) {
			this.shoutOutList = this.shoutOuts.getElement('ul');
			this.scroll = new ScrollBar(this.shoutOuts.getElement('div.viewport'));
			this.loadShouts();
		}
	},

	loadShouts: function() {
		if (!Liferay) return;
		Liferay.Service.shouts.Shout.getShoutsSort({
			className: "com.liferay.portal.model.Group",
			classPK:   this.gid,
			sort:      0,
			asc:       false,
			start:     0,
			end:       50
		},
		function(data) {
			// console.log('ShoutOut List:');
			if (!data.length) {
				console.warn('ShoutOut list is empty.');
				return;
			}
			// console.dir(data);
			if (this.shoutOuts) {
				this.shoutOutList.empty();
				data.each(function(item, index){
					// console.log('Shout:');
					// console.dir(item);
					if ($defined($('shout-'+item.shoutId))) return;
					var el = new Element('li', {id: 'shout-'+item.shoutId});
					el.grab(new Element('h4', { text: item.name }));
					var location = Monster.location('', item.location, item.region, item.country);
					if (location) location = ' - ' + location;
					el.grab(new Element('p',  { text: new Date(item.createDate.toInt()).format('%x %X') + location }));
					el.grab(new Element('p',  { text: item.message }));
					el.inject(this.shoutOutList, 'top');
					this.scroll.update();
					this.scroll.scrollToTop();
				}.bind(this));
			}
			else if (Monster.flashMovie('linkin-park-hero-flash') && Monster.flashMovie('linkin-park-hero-flash').loadShoutOuts) {
				Monster.flashMovie('linkin-park-hero-flash').loadShoutOuts(data);
			}
		}.bind(this));
	},

	processMessage: function(msg) {
		if (msg.msg == 'shoutoutSubmit') {
			if (!this.gid) return;
			Liferay.Service.shouts.Shout.addShout({
				className: "com.liferay.portal.model.Group",
				classPK:   this.gid,
				name:      msg.data.name || themeDisplay.getUserName() || 'Anonnymous',
				location:  msg.data.location || '',
				region:    msg.data.state || '',
				country:   msg.data.country || '',
				title:     '',
				message:   msg.data.comment
			},
			function(data) {
				// console.log('Shoutout Posted:');
				// console.dir(data);
				this.loadShouts();
			}.bind(this));
		}
		else if (msg.msg == 'tabChanged' && msg.data.hasClass('shoutouts')) {
			if (this.scroll) this.scroll.update();
		}
		else if (msg.msg == 'shoutOutSetGid') {
			this.gid = msg.data;
			this.loadShouts();
		}
		else if (msg.msg == 'linkinParkShoutOutsReady') {
			this.loadShouts();
		}
	}
});

new ShoutOutsManager();
