(function($) {
	$.fn.scrollit = function(options,callback){  
	callback    = callback || function(){};
	var opts    = $.extend({}, $.fn.scrollit.defaults, options);
	var props   = $.fn.scrollit;
	
	$.fn.scrollit.loader = $("#core_loader");
	(new Image()).src = opts.loadingImg;
	$('<img alt="loading" src="'+opts.loadingImg+'" />').appendTo(props.loader);
	
	$(window).scroll(function() { scr(props, opts) });
		
	scr(props, opts);
	
	return this;
  }
  
  function loadEntry(props, opts, anim) {
	  props.isLoading = true;
	  var div =  $("<div/>");
	  props.calledArr.push(props.currentRow);
	  div.appendTo(opts.contentHolder);
	  div
		  .hide()
		  .load(opts.callScript + '?row=' + props.currentRow,null,function(){
																		 
		  	   props.isLoading = false;
			   $(this).fadeIn(200);

			   
			   if(anim) {
				   props.target = $(this);
				   animateScroll(props,opts);
			   }
			   
			   scr(props, opts); // double call to load additional entries if reached bottom
	  	  });
  }
  
  function isNearBottom(props, opts){
	return ($(document).height() - $(document).scrollTop() - $(window).height() < opts.topspace);    
  }
  
  function scr(props, opts){
	  if(props.isDone || props.isLoading) return;
	  if(props.currentRow > opts.limit) return;
	  if (isNearBottom(props, opts)) {
		 if(props.calledArr.indexOf(props.currentRow) < 0) {
			 loadEntry(props,opts,false);
		 } else {
			 var i = 1;
			 var noId = true;
			 while(noId) {
				 if(props.calledArr.indexOf(i) < 0) {
					 props.currentRow = i;
					 loadEntry(props,opts,false);
					 noId = false;
				 }
				 i++;
				 if(i > opts.limit) {
					 props.isDone = true;
					 return;   
				 }
			 }
		 } 
	  }
  }
  
  $.extend($.fn.scrollit,{ defaults : {
		   
	  callScript	  : "/core/getentry.php",
	  loadingImg      : "",
	  loadingText     : "",
	  contentHolder	  : "#core_content",
	  doneText        : "",
	  limit			  : 0,
	  topspace		  : 100,
	  scrollspeed	  : 0
  
  },
  
  calledArr		: [],
  currentRow	: 1,
  target		: null,
  isLoading		: false,
  isDone		: false
  
  });
  
})(jQuery);