$(document).ready(function(){  

  var queue = Array();
  var gray = false;
  var onhold = false;
  var lastrid = 0;
  
  // initialize
  fetchNewData(true)
  ticker(false);
  
  function ticker(check){
    if (check){
      checkForFetch();
    }
    bump(true);
    if (onhold){
      window.setTimeout(function(){
        checkForFetch();
        },20000);   
    } else {
      window.setTimeout(function(){
        ticker(true);
        },10000);    
    }
  };
  
  function bump(animate){
    x = queue.pop();
    if (x) {
      $('#queue').prepend(x.html);
      
      if (gray) {
        $('#' + x.domid).addClass("gray");
        gray = false;
      } else {
        gray = true;
      }
      
      if (animate){
        $('#' + x.domid).animate({ 
            marginTop: "0"
            }, 
            3000);
      } else {
        $('#' + x.domid).css("margin-top","0");
      }
      
      // cleanup
      /*
      $('.scroller').each(function(i){
        if (i > 7){
          $("#"+this.id).remove();
        }
      });
      */
    }
  }
  
  function checkForFetch(){
    if (queue.length < 2){
      fetchNewData(false);
    }
  }

  function fetchNewData(populate){
    url = "queue.json.php";
    $.getJSON(url,function( x ) {
      if (x){
        // we've got records
        
        // do we have anything new?
        newrows = Array();
        for (rid in x.rows){
          if (rid > lastrid){
            newrows.push(x.rows[rid]);
          }
        }
        
        if (newrows.length > 0) {
          // we have new records!

          // record the last record id
          lastrid = x.maxrid;
        
          // update the record count
          $('#bigcount #number').html(x.count);
        
          // continue animating
          if (onhold){
            onhold = false;
            ticker(false);
          }
        
          // put the new records into the queue
          queue = queue.concat(newrows);          
      
          // if the page has just been loaded, cram the first six into the queue without animating
          if (populate){
            for(i=0;i<6;i++){
              bump(false);
            }
          }
        } else {
          // the records are not new, so wait a little then check again
          onhold = true;
          ticker(false);
        }
      } else {
        // we've received no data, so wait a little then check again
        onhold = true;
        ticker(false);
      }
  	});
  };

});