(function($)
{
	if (typeof $.telligent === 'undefined')
	        $.telligent = {};

	if (typeof $.telligent.evolution === 'undefined')
	    $.telligent.evolution = {};

	if (typeof $.telligent.evolution.widgets === 'undefined')
	    $.telligent.evolution.widgets = {};

	var _tabClick = function(context, tab)
	{
		context.list.empty();
		context.loading.show();
		context.pager.hide();
		context.startDate = new Date();
		context.currentTab = tab;
		
		$.telligent.evolution.get({
			url: context.listUrl,
			data: {
				w_filterType: context.filterType,
				w_tab: tab,
				w_userId: context.userId,
				w_group: context.groupId
			},
			success: function(response)
			{
				context.loading.hide();
				var hasContent = false;

				if ($.trim(response))
				{
					var r = $(response);
					var e = r.filter('input.end-date');
					if (e.length > 0)
					{
						context.startDate = e.val();
						context.list.append(r);
						_attachHandlers(context, r);
						e.remove();
						context.pager.show();
						hasContent = true;
					}
				}
				
				if (!hasContent)
				{
					context.list.append($('<div class="message norecords message__norecords">' + context.noResults + '</div>'));
				}
			},
			defaultErrorMessage: context.error,
			error: function(xhr, desc, ex) 
			{  
				context.loading.hide();
				context.list.append($('<div class="message error error__message">' + desc + '</div>'));
			}
		});
	}, 
	_showMessage = function(context, messageId)
	{
		context.list.empty();
		context.loading.show();
		context.pager.hide();
		context.startDate = new Date();
		
		$.telligent.evolution.get({
			url: context.listUrl,
			data: {
				w_filterType: context.filterType,
				w_messageId: messageId
			},
			success: function(response)
			{
				context.loading.hide();
				var hasContent = false;

				if ($.trim(response))
				{
					var r = $(response);
					var e = r.filter('input.end-date');
					if (e.length > 0)
					{
						context.list.append(r);
						_attachHandlers(context, r);
						e.remove();
						hasContent = true;
					}
				}

				if (!hasContent)
				{
					context.list.append($('<div class="message norecords message__norecords">' + context.noResults + '</div>'));
				}
			},
			defaultErrorMessage: context.error,
			error: function(xhr, desc, ex) 
			{  
				context.loading.hide();
				context.list.append($('<div class="message error error__message">' + desc + '</div>'));
			}
		});
	},
	_showMore = function(context)
	{
		context.loading.show();
		context.pager.hide();
		
		$.telligent.evolution.get({
			url: context.listUrl,
			data: {
				w_filterType: context.filterType,
				w_tab: context.currentTab,
				w_startDate: context.startDate,
				w_userId: context.userId,
				w_group: context.groupId
			},
			success: function(response)
			{
				context.loading.hide();
				var hasContent = false;

				if ($.trim(response))
				{
					var r = $(response);
					_attachHandlers(context, r);
					var e = r.filter('input.end-date');
					if (e.length > 0)
					{
						context.startDate = e.val();
						
						var e = r.filter('input.extend-list');
						if (e.length > 0 && e.val() == '1' && context.list.children('.content-list:last').length > 0)
						{
							context.list.children('.content-list:last').append(r.filter('.content-list:first').children());
							context.list.append(r);
							r.filter('content-list-header:first, .content-list-name:first, .content-list:first, .content-list-footer:first').remove();
						}
						else
						{
							context.list.append(r);
						}						

						e.remove();
						context.pager.show();
					}
				}
			},
			defaultErrorMessage: context.error,
			error: function(xhr, desc, ex) 
			{  
				context.loading.hide();
				context.list.append($('<div class="message error error__message">' + desc + '</div>'));
			}
		});	
	}, 
	_attachHandlers = function(context, elements)
	{
		elements.find('.internal-link.delete').click(function()
		{
			var p = $(this).parents('.content-item');
			if (p.length > 0 && window.confirm(context.deleteConfirmation))
			{
				var url, data = { };
				var messageId = '';
				
				if (p.hasClass('reply'))
				{
					url = $.telligent.evolution.site.getBaseUrl() + 'api.ashx/v2/activities/{ParentMessageId}/replies/{ReplyMessageId}.json?IncludeFields=ReplyMessage.Id';
					data.ParentMessageId = p.attr('data-replyto-id');
					data.ReplyMessageId = p.attr('data-reply-id');
					messageId = p.attr('data-replyto-id');
				}
				else 
				{
					url = $.telligent.evolution.site.getBaseUrl() + 'api.ashx/v2/activities/{MessageId}.json?IncludeFields=ReplyMessage.Id';
					data.MessageId = p.attr('data-id');
					messageId = p.attr('data-id');
				}
				
				$.telligent.evolution.del({
					url: url,
					data: data,
					success: function(response)
					{
						if (p.hasClass('reply'))
						{
							p.slideUp('fast', function() { p.remove(); });
						}
						else
						{
							var old = context.list.find('.content-item[data-id="' + messageId + '"], .content-item[data-replyto-id="' + messageId + '"], .content-item[data-replyform-id="' + messageId + '"]');
							old.slideUp('fast', function() { old.remove(); });
						}							
					}
				});
			}
			
			return false;
		});
		
		elements.find('.internal-link.reply').click(function()
		{
			var p = $(this).parents('.content-item');
			if (p.length > 0)
			{
				var messageId = '';
				if (p.hasClass('reply'))
				{
					messageId = p.attr('data-replyto-id');
				}
				else
				{
					messageId = p.attr('data-id');
				}
				
				var f = elements.find('.content-item[data-replyform-id="' + messageId + '"]');
				if (f.length > 0)
				{
					f.slideDown('fast', function() { f.find('input').focus(); });
				}
			}
			
			return false;
		});
		
		elements.find('.field-list input').keydown(function(event)
		{
			if (event.keyCode == 13)
			{
				$(this).parents('.content-item').find('.field-list a').click();
			}
		});
		
		elements.find('.field-list a').click(function()
		{
			var p = $(this).parents('.content-item');
			if (p.length > 0 && !$(this).data('busy'))
			{
				var messageId = p.attr('data-replyform-id');
				var body = p.find('.field-list input').val();
				if ($.trim(body) == '')
					return false;
				
				$(this).data('busy', true);
				
				$.telligent.evolution.post({
					url: $.telligent.evolution.site.getBaseUrl() + 'api.ashx/v2/users/{AuthorId}/statuses/{MessageId}/replies.json?IncludeFields=ReplyMessage.Id',
					data: {
						AuthorId: context.accessingUserId,
						MessageId: messageId,
						MessageBody: body
					},
					success: function(response) {
						$(this).data('busy', false);
						var old = context.list.find('.content-item[data-id="' + messageId + '"], .content-item[data-replyto-id="' + messageId + '"], .content-item[data-replyform-id="' + messageId + '"]').fadeTo('fast',.4);
						
						$.telligent.evolution.get({
							url: context.listUrl,
							cache: false,
							data: {
								w_filterType: context.filterType,
								w_messageId: messageId
							},
							success: function(response)
							{
								context.loading.hide();
								
								var r = $(response);
								var e = r.filter('input.end-date');
								if (e.length > 0)
								{
									var n = r.find('.content-item');
									n.fadeTo(0, .4);
									old.filter(':first').before(n);
									old.hide().remove();
									n.fadeTo('fast',1);			
									_attachHandlers(context, n);
									e.remove();
								}
							},
							error: function(xhr, desc, ex) 
							{  
								$.telligent.evolution.notifications.show(desc,{type:'error'});
								old.stop().fadeTo('fast',1);
							}
						});							

						p.find('.field-list input').val('').blur();
					},
					error: function(xhr, desc, ex) {
						$(this).data('busy', false);
						$.telligent.evolution.notifications.show(desc,{type:'error'});
					}
				});
			}
			
			return false;
		});
	};

	$.telligent.evolution.widgets.activityMessageList = 
	{
		register: function(context) 
		{
			if (context.messageId)
				_showMessage(context, context.messageId);
			else
				_tabClick(context, context.defaultTab)
			
			$('a', context.tabs).click(function()
			{
				$('span.filter-option', context.tabs).removeClass('selected');
				$(this).parent().addClass('selected');
				_tabClick(context, $(this).attr('data-filter'));
				return false;
			});
			
			$('a', context.pager).click(function()
			{
				_showMore(context);
				return false;
			});
			
			$(document).bind('telligent_messaging_activitymessageupdated', function(e, message) 
			{ 
				if (!context.messageId)
					_tabClick(context, context.currentTab);
			});
		}
	};
})(jQuery);

