BLIP.Class.create("BLIP.Unit.ScrollingAjaxList", BLIP.Unit,
	function(config) {
		BLIP.Unit.call(this, config);
	},
	{
		init : function() {
			this.is(BLIP.Mixin.Scrollable)();
			this.currentPage = 1;
			this.currentlyLoading = false;
			this.addEventListeners();
			this.onAdditionalItems = new BLIP.Utils.LocalEvent("AdditionalItems");
		},

		addEventListeners: function () {
			this.on_scrollToBottom.addListener(this.delegate(this.onScrolledToBottom));
		},

		onScrolledToBottom: function () {
			this.queueNextPageToLoad();
		},

		//Loads up the next page as long as there is nothing already pending
		//Only increments currentPage when response has returned
		queueNextPageToLoad: function () {
			var thisContext = this;
			if(this.currentlyLoading || this.noMorePages) {
				return;
			}
			this.currentlyLoading = true;
			this.displayLoadingIndicator();
			$.get(this.buildListUrl((this.currentPage+1)), function (data) {
				thisContext.hideLoadingIndicator();
				thisContext.appendNewPage(data);
				thisContext.currentPage++;
				thisContext.recalculateScrollbar();
				thisContext.currentlyLoading = false;
				if(!thisContext.responseHasData(data)) {
					thisContext.noMorePages = true;
				}
				thisContext.onAdditionalItems.fire();
			});
		},

		appendNewPage : function(data) {
			var content = this.domRoot.find(this.responseContentSelector),
					newContent = $(data).find(this.responseContentSelector).children('li');

			content.append(newContent);
		},

		responseHasData : function(data) {
			return !!$(data).find(this.responseContentSelector).children('li').length;
		},

		buildListUrl: function (page) {
			var url =  new BLIP.Utils.UrlBuilder(this.getListUrl());
			url.addParam("no_wrap","1");
			url.addParam("page", page);
			return url.getFullUrl();
		},

		displayLoadingIndicator: function () {
			this.domRoot.find(".Scrollable").append($("<div class='Loading'>Loading...</li>"));
			this.recalculateScrollbar();
			this.scrollTo(this.getContentMaxY() - 1); // -1 so that we don't trigger a new load event
		},

		hideLoadingIndicator: function() {
			this.domRoot.find(".Loading").remove();
		}
	}
);

