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

(function () {
	// initialization

	disqus.initialize = function () {
		// do all initialization for the moderate page
		// including calling comment or thread specific initialization

		// set up show more button.
		$('#show-more button').click(function (event) {

			// Hide button and display loading image
			$('#show-more button').hide();
			$('#show-more img.loading').show();

			disqus.getList();

			return false;
		});

		disqus.getList();

		disqus.handler.initialize();
	};
})();

(function () {
	// json call for populating comments page.
	var last = null;

	disqus.reset = function () {
		// reset the last parameter to start pagination fresh.
		last = null;
	};

	disqus.startLoading = function () {
		$('#loading-message').show();
		$('#loading-overlay').show();
	};

	disqus.stopLoading = function () {
		$('#loading-message').hide();
		$('#loading-overlay').hide();
	};

	disqus.getList = function (filters) {
		// load a list of comments from a json call to the url variable.

		disqus.startLoading();

		// build parameters.
		var data = {};

		// parameters from context.
		if (context.username) {
			data.username = context.username;
		}
		var key;
		if (context.extra_data) {
			for (key in context.extra_data) {
				if (context.extra_data.hasOwnProperty(key)) {
					data[key] = context.extra_data[key];
				}
			}
		}

		// parameters from query string.
		var query_obj = utils.query();
		if (query_obj.query) {
			data.query = query_obj.query;
		}

		// last loaded for show more.
		var reset = last === null;
		if (!reset) {
			data.last = last;
		}

		// hold ie's hand.
		data.ie = (new Date()).getTime();

		// make json call
		$.getJSON(disqus.handler.urls.comments, data, function (data) {
			if (data.succeeded) {
				if (data.message.last) {
					last = data.message.last;
				}
				// TODO use number today.

				disqus.handler.loadList(data.message.objects, reset);
				disqus.handler.displayList(data.message.objects.length);

				if (data.message.more_to_show) {
					$('#show-more img.loading').hide();
					$('#show-more button').show();
					$('#show-more').show();
				} else {
					$('#show-more').hide();
				}

				disqus.stopLoading();
			}
		});
	};
})();

// on document ready.
$(document).ready(function () {
	disqus.initialize();
});
