
if (window.disqus === undefined) {
	var disqus = {};
}
if (disqus.handler === undefined) {
	disqus.handler = {};
}

(function () {
	// shared state

	disqus.handler.urls = {
		'comments': '/auth/json/get_comments_list/'
	};

	// HACK fake username if anonymous.
	if (context.userhash) {
		context.username = context.userhash;
	}
})();

(function () {
	// initialization

	disqus.handler.initialize = function () {

		if (context.userhash) {
			$('#unsubscribe, #subscribe').remove();
		}

		if (context.following) {
			$('#unsubscribe').show();
		} else {
			$('#subscribe').show();
		}

		$('#report-abuse-link a').click(function (event) {
		    var title = '<h3>Report ' + context.username + ' as a spammer?</h3>';
		    var message = 'This will alert Disqus to review this profile as possible spam. ' +
		                  'Please note that this is only meant to report spam. It is not meant to report offensive, obscene, or even annoying comments. ' +
		                  '<br /><br />' +
		                  '<button class="button small confirm-report" type="button"><span>Report ' + context.username + '</span></button>&nbsp&nbsp;' +
		                  '<button class="button small cancel-report" type="button"><span>Never mind</span></button>';
            $.facebox(title + message);
            
            $('button.confirm-report').click(function (event) {
               	reportAbuse(context.username);
    			$('#report-abuse-link').html('<img src="' + context.mediaUrl + '/images/loading-small.gif" />');
            });
            $('button').click(function (event) {
               $.facebox.close(); 
            });
            
			return false;
		});

		$('#subscribe button.subscribe').click(function (event) {
			userSubscribe(context.username);
		});

		$('#unsubscribe button.unsubscribe').click(function (event) {
			userUnsubscribe(context.username);
		});

		// set up claim profile linke.
		$('button.claim').click(function (event) {
			profileClaim(context.username);
		});

		$('#mark-spammer').click(function (event) {
			markSpammerConfirm(context.username);
		});
	};

	// private json calls.
	var urls = {
		'claim': '/auth/json/profile_claim/',
		'markspammer': '/auth/json/mark_spammer/',
		'subscribe': '/auth/json/user_follow/',
		'unsubscribe': '/auth/json/user_unfollow/',
		'reportabuse': '/auth/json/report_abuse/'
	};

	var reportAbuse = function(username) {
		$.post(urls.reportabuse, {
			'username': username
		}, function (data) {
			$.facebox(
				'Thanks for reporting this profile. We will take a look as soon as possible.' +
				'<br /><br />If you\'ve reported this profile by mistake, no worries &mdash; a person reviews each report.');
			$('#report-abuse-link').hide();
			return false;
		}, 'json');
	};

	var userSubscribe = function (username) {
		$.post(urls.subscribe, {
			'username': username
		}, function (data) {
			if (data.succeeded) {
				$('#subscribe').hide();
				$('#unsubscribe').show();
			}
		}, 'json');
	};

	var userUnsubscribe = function (username) {
		$.post(urls.unsubscribe, {
			'username': username
		}, function (data) {
			if (data.succeeded) {
				$('#subscribe').show();
				$('#unsubscribe').hide();
			}
		}, 'json');
	};

	var profileClaim = function (username) {
		$.post(urls.claim, {
			'username': username
		}, function (data) {
			if (data.succeeded) {
				$('div.profile-alert').html(data.message);
			}
		}, 'json');
	};

	var markSpammerConfirm = function(username) {
		$.facebox('<div id="mark-spammer-confirm">' +
				'<span>This will delete the user and mark all of their comments as spam.<br />Are you sure?</span>' +
				'<br />' +
				'<span>' +
				'<a href="#" class="no">No, cancel</a>' +
				'&nbsp;&nbsp;/&nbsp;&nbsp;' +
				'<a href="#" class="yes">Yes, delete this user</a>' +
				'</span>' +
				'</div>');
		$("#mark-spammer-confirm a.no").click(function () { $.facebox.close(); return false; });
		$("#mark-spammer-confirm a.yes").click(function () { markSpammer(username); return false; });
	};


	var markSpammer = function(username) {
		$.post(urls.markspammer, {
			'username': username
		}, function (data) {
			if (data.succeeded) {
				$.facebox.close();
				$('#mark-spammer').before('<p>' + context.username + ' was marked as a spammer.</p>');
			}
		}, 'json');
	};
})();


(function () {
	// methods that manipulate the posts list.

	// uses closure for private state.
	var posts = [];
	var posts_by_id = {};

	disqus.handler.loadList = function (input, reset) {
		// load post data into private variables.
		var i;

		posts_by_id = {};

		if (reset) {
			posts = input;
		} else {
			posts = posts.concat(input);
		}

		for (i=0; i<posts.length; i+=1) {
			posts_by_id[posts[i].id] = posts[i];
		}
	};

	disqus.handler.displayList = function (new_length) {
		// display the list of comments stored in the posts closure variable.
		var start = posts.length - new_length;
		var i;

		// display demo if no posts to show.
		if (posts.length===0) {
			$('#comments').empty();

			// XXX load something if no posts.

			return false;
		}

		if (posts.length===new_length) {
			$('#comments').empty();
		}

		for (i=start; i<posts.length; i+=1) {
			$('#comments').append(posts[i].markup);
		}

		// remove edit and delete buttons.
		$('button.edit, button.delete').remove();

		// remove reply links.
		for (i=start; i<posts.length; i+=1) {
			if (!posts[i].approved) {
				$('#comment-' + posts[i].id).find('button.reply').remove();
			}
		}

		// set up reply links.
		var showReplyPostCallback = function (id) {
			return function (event) {
				if ($('#comment-form-' + id).length > 0) {
					$('#comment-form-' + id).parent().show();
				} else {
					getReplyPost(id);
				}
			};
		};
		var hideReplyPostCallback = function (id) {
			return function (event) {
				$('#comment-form-' + id).parent().hide();
			};
		};
		for (i=start; i<posts.length; i+=1) {
			$('#comment-' + posts[i].id).find('button.reply').toggle(showReplyPostCallback(posts[i].id), hideReplyPostCallback(posts[i].id));
		}

		// set up context links.
		var showContextCallback = function (id) {
			return function (event) {
				getContext(id);

				return false;
			};
		};
		for (i=start; i<posts.length; i+=1) {
			$('#comment-' + posts[i].id).find('button.context').click(showContextCallback(posts[i].id));
		}
	};

	// private json calls for manipulating posts.
	var urls = {
		'reply': '/auth/json/post_create/',
		'context': '/forums/json/get_context/'
	};

	var getReplyPost = function (id) {
		$.get(urls.reply, {
			'parent_post_id': id
		}, function (data) {
			if (data.succeeded) {
				$('<div id="reply-post-' + id + '" class="reply-post">' + data.message + '</div>').appendTo('#comment-' + id + ' .content p');

				// initialize textarea
				var textarea = $('#reply-post-' + id + ' textarea');
				disqus.autogrow(textarea);
				textarea.css('color', '#aaa');
				textarea.html('Type your reply...');
				textarea.click(function (event) {
					textarea.empty();
					textarea.css('color', '#333');
				});

				$('#comment-form-' + id).submit(function (event) {
					postReplyPost(id);

					return false;
				});
			}
		}, 'json');
	};

	var postReplyPost = function (id) {
		var message = $('#comment-form-' + id + ' .post-create').val();

		if (message.length < 2) {

			$.facebox.settings.opacity = 0.8;
			$.facebox('Your reply message must contain at least two characters.');
			$.facebox.settings.opacity = 0; // Reset opacity

			return false;
		}

		$.post(urls.reply, {
			'parent_post_id': id,
			'message': message
		}, function (data) {
			if (data.succeeded) {
				$('#comment-form-' + id).parent().remove();

				// Get request user's avatar
				var requestAvatar = '<img src="' + $('a#top-account-username img').attr('src') + '" />';
				// Append reply message
				$('#comment-' + id + ' .content').append('<div class="comment-reply">' + requestAvatar + data.message + '</div>');
				// Success "Reply posted" message
				$('#comment-' + id + ' .comment-actions-left').prepend('<img src="' + context.mediaUrl + '/images/tick.png" /> <strong>Reply posted.</strong> ');
			}
		}, 'json');
	};


	var getContext = function (id) {
		$.get(urls.context, {
			'post_id': id,
			
			'parent_context': 2,
			'child_context': 2
		}, function (data) {
			var i, post;

			if (data.succeeded) {
				var contextList = '';
				for (i=0; i<data.message.objects.length; i+=1) {
					post = data.message.objects[i];

					contextList += post.markup;
				}

				$.facebox(contextList);

				// $('#comment-' + id).find('a.context').replaceWith(contextList);
			}
		}, 'json');
	};


})();

