/* Infite Scroll
 * Version: 1.1
 * Author: Christian Reed (christian@rgbfab.com)
 * This code allows for an infinitely scrolling WordPress site. It's for client work and not intended for a wide audience.
 * Feel free to crib and learn from it, but know that it relies on custom modifications to the template, so some things may
 * not completely make sense out of that context. The basics of this came from Pro Javascript Techniques by John Resig, but
 * needed some significant changes to become truly viable.
*/

var curPage = 1;
var loading = false;


(function($) {
		
	$.fn.prep_infinite_scroll = function() {
		
		$(this).each(function() {
			$(this)
				.attr('id','infinite_scroll')
				.find('.nav-above, .nav-below').remove().end()
				.find('#infinite_more').show().click(function() {
					loadInfiniteContent();
				});
		});

		window.onscroll = function() {
			loadInfiniteContent();
		}
		return this;
	}

	function loadInfiniteContent() {
		if ( curPage >= 1 && !loading
			&& $(document).height() - $(document).scrollTop() - $(window).height() < $(window).height() ) {

			loading = true;

			$('#infinite_more').stop(true,true).fadeOut("fast", function(){
				$('#infinite_loading').stop(true,true).fadeIn("fast");
			});

			var window_location = window.location + "";
					
			if ( window_location.indexOf("?") > -1 )
				window_location += "&";
			else
				window_location += "?";
	
			var url_string = window_location + 'format_type=scroll&paged=' + (++curPage);
					
			$.get( url_string, function(data) {

				if ( data.search("no_more_posts") >= 0 ) {
					curPage = 0;
					$('#infinite_more, #infinite_loading').stop(true,true).fadeOut("fast", function(){
						$('#infinite_end').stop(true,true).fadeIn("fast");
					});
				}
				else {
					$(data).prep_content().insertBefore('#infinite_more');
					
					$('#infinite_loading, #infinite_end').stop(true,true).fadeOut("fast", function(){
						$('#infinite_more').stop(true,true).fadeIn("fast");
					});
				}
	
				loading = false;
			});
		}
	}

})(jQuery);

