/* 

morePostsScroll

 */ 
 
 var NUM_SHOWPOSTS = 2;
 var OFFSET = 1;
 var fin_posts = false;
 var consulta_completa = true;

;(function($) {

	$.fn.morePostsScroll = function( options ) {		
	
		// default configuration properties
		var defaults = {
			path: "/",
			offset_inicial: OFFSET,
			showposts: NUM_SHOWPOSTS,
			debug: false
		};
		 
		var options = $.extend(defaults, options);
		
		var alto_maximo = $(document).height()  + 40;
									 
    // console log wrapper.
    function debug(){
      if (options.debug) { window.console && console.log.call(console,arguments)}
    }

		
		var $obj = $(this);
		var $current_offset = options.offset_inicial;
		
		var $prev_position = 0;
	
		(new Image()).src    = "http://www.francescmoret.com/wp-content/plugins/more-posts-scroll/images-support/ajax-loader.gif";
		
		$(window).bind ("scroll",  function(){ doMorePosts() });	
		
		$("#loading").ajaxStart(function(){
   			$(this).fadeIn();
		 });
		
		$("#loading").ajaxStop(function(){
   			$(this).fadeOut();
			$('div[id^="content-post"]').automaticWidth({});

		 });
		
		function doConsultaComplete() {
			consulta_completa = false;
			}
														  
		function doMorePosts() {
			var alto_actual = 0 + $(document).height() - ($(document).scrollTop() + $(window).height());
			debug ( $(document).height()  + ", " +  $(document).scrollTop() + ", " + $(window).height());
			
			if (fin_posts || !consulta_completa) return;
			
			// solo si hemos llegado al final del documento y el scroll es hacia abajo
			if (alto_actual < 100) {
						debug ("Alto actual: " + alto_actual + ", Alto Maximo: " + alto_maximo);
						consulta_completa = false;
						$.get(options.path + "queryMorePosts.php", 
							  
							{ offset: $current_offset,
							  showposts: options.showposts,
							  fin_posts: (fin_posts ? 1 : 0) },
							
							function (data){
											  $obj.append (data);
											  $current_offset = $current_offset + options.showposts;
											  if ($current_offset == options.offset_inicial)
											  	$obj.show();
											  consulta_completa = true;
											  }
						);
						
			}
			
		}
		 
		
		// loading
	
	};


})(jQuery);
