(function($){
	$(function() {
		$("#page-selector").hide();

		$("#page-selector").before("<div id=\"pageless-indicator\"></div>");
		var spinner = {
			start: function() {
				$("#pageless-indicator").spinner({height:32,width:32,speed:50,image:"http://www.greym0nk.com/habari/system/plugins/pageless/spinnersmalldark.png"});
				$("#pageless-indicator").show();
			},
			stop: function() {
				$("#pageless-indicator").spinner("stop");
				$("#pageless-indicator").hide();
			}
		}

		var the_end = false;

		function appendEntries() {
			if ($(window).scrollTop() >= $(document).height() - ($(window).height() * 2)) {
				var slug = $(".hentry:last").attr("id").replace(/^(?:entry|page)-/, "");
				$.ajax({
					url: "http://www.greym0nk.com/habari/pageless/{$slug}".replace("{$slug}", slug),
					beforeSend: function() {
						spinner.start();
						$(window).unbind("scroll", appendEntries);
					},
					success: function(response) {
						if (response.length > 100) {
							$(".hentry:last").after(response);
						} else {
							the_end = true;
						}
					},
					complete: function() {
						spinner.stop();
						if (!the_end && activated) {
							$(window).bind("scroll", appendEntries);
						}
					}
				});
			}
		}
		$(window).bind("scroll", appendEntries);

		var activated = true;

		function toggleScroll() {
			activated = !activated;
			if (!the_end && activated) {
				$(window).bind("scroll", appendEntries);
				$("#page-selector").hide();
				appendEntries();
			} else {
				$(window).unbind("scroll", appendEntries);
				$("#page-selector").show();
			}
		}
		$(document).bind("dblclick", toggleScroll);
	});
})(jQuery);