var scroll_loop = 0;
var scroll_end = false;
var loading = false;

// Fonction qui load de nouveaux idems si on se trouve en bas de page.
function scrollalert(purl) {

  var scrolloffset = 100; // Nombre de pixel a partir de bas de l'ecran ou l'on doit chercher de nouveaux objets.
  var delais = 300; // Delais d'attente pour le setTimeout.
  
  if (!loading && $(window).scrollTop() >= $(document).height() - $(window).height() - scrolloffset) {
      //fetch new items
      scroll_loop = scroll_loop + 1;
    
      path = purl;
      pos = path.lastIndexOf('?');
    
      if (pos != -1) {
	  url = path.substr(0, pos);
	  get = path.substr(pos);
	  full_url = url+scroll_loop+'/'+get;
      } else {
	  if (path.slice(-1) != '/') {
	      path = path + '/';
	  }
	  full_url = path+scroll_loop+'/';
      }
    
      // Call asynchrone.
      $.ajax({ type: "GET",
		url: full_url,
		async: true,
		beforeSend:
	  function(xhr) {
	      loading = true;
	      $('#scroll_paginate').append('<li id=\"scroll_wait\"><img src=\"/images/wait.gif\" /></li>');
	  },
		success:
	  function(data) {
	      var elements = data.split("</li><!-- end -->");
	      
	      var finished = true;
	      interval_id = setInterval(
		  function(){
		      if (finished) {
			  finished = false;
			  var new_item = elements.shift()+'</li>';

			  $('#scroll_paginate').append(new_item);
			  
			  if (elements == '') {
			      clearInterval(interval_id);
			      loading = false;
			  }
			  finished = true;
		      }
		  }, 100
	      );
	      
	      $('#scroll_wait').remove();

	      if (data == '' || data.replace('\n','') == '' || data.trim() == '') {
		  scroll_end = true;
		  loading = true;
	      }
	  }
      });
      
  }
  if (!scroll_end) {
    setTimeout('scrollalert(\"'+purl+'\");', delais);
  }
}

