jQuery(document).ready(function() {
	//Set-up some constants.
	var scrollTimeout;
	var scrollUsePushStateInstead = false; //Set to true to make the history stack of the browser include every point when posts were loaded. It's kind of annoying.
	var scrollDelay = 200; //Milliseconds
	var scrollLoading = false;
	var triggerOffset = $(document).height() - $('#pagination').siblings().eq(-4).offset().top; //The point of this is to do one calculation up front instead of multiple calculations every time the infinite scroll is triggered. 
	
	// Simple feature detection for History Management (borrowed from Modernizr)
	function supportsHistory() {
		return !!(window.history && history.pushState);
	}
	
	if( supportsHistory() ) {
		$(window).on('scroll', function() {
			toInfinityAndBeyond();
		});
	}
	
	//The function that does all of the work.
	function toInfinityAndBeyond() {
		if( scrollLoading ) {
			return;
		}
		//if( scrollTrigger < $(document).scrollTop()) {
		if( $(document).height() - triggerOffset < $(document).scrollTop() + $(window).height() ) {
			var nextURL = $('#pagination').find('.next').eq(0).attr('href');
			if( !nextURL ) {
				return;
			}
			
			$.ajax({
				type: 'GET',
				url: nextURL,
				beforeSend: function() {
					// block potentially concurrent requests
					scrollLoading = true;
				},
				success: function(data) {
					$('#pagination').before( $(data).find('#content').html() ).remove();
					
					var newPageNum = nextURL.match(/\/page\/(\d+)\//)[1];
					
					regexp = /\/(pages?)\/([0-9]+)-?([0-9])*\/?$/;
					var newPath = window.location.href;
					if( regexp.test(newPath) ) {
						parts = regexp.exec(newPath);
						//Assign different parts to more understandable labels. Assume the following example: http://example.com/thing/pages/2-4/
						matchingPattern = parts[0]; // -> /pages/2-4/
						pageLabel = parts[1].toLowerCase(); // -> pages
						pageStart = parts[2]; // -> 2
						pageEnd = parts[3]; // -> 4
						
						if( pageEnd > 0 && pageStart == 1 ) {
							pageStart = pageEnd;
							pageEnd = false;
						}
						
						var blackMagic = new RegExp(matchingPattern, 'ig');
						
						//We're dealing with /pages/x-x/
						replacement = '/pages/' + pageStart + '-' + newPageNum + '/';
						if( !pageEnd ) {
							//We're dealing /page/x/ or /pages/x/
							replacement = '/pages/' + newPageNum + '/';
							if( pageLabel == 'page' ) {
								replacement = '/pages/' + pageStart + '-' + newPageNum + '/';
							}
							
						}
						
						newPath = newPath.replace( blackMagic, replacement);
					} else {
						//There is no /page/ or /pages/ in the URL. We'll assume we can just append a new /pages/ path to the current URL.
						newPath += 'pages/' + newPageNum + '/';
					}		
					
					newPath = '/' + newPath.split('/').slice(3).join('/');
					if( scrollUsePushStateInstead ) {
						window.history.pushState(null, null, path);
					} else {
						window.history.replaceState(null, null, newPath);
					}
					
					// unblock more requests (reset loading status)
					scrollLoading = false;
					
				},
				dataType: "html"
			});	
		}
	}
});