jQuery(document).ready(function() {

  var tweetcountElement = jQuery('#tweetcount');
  var tweetcountDisplayed = parseInt(tweetcountElement.text());
  var tweetcountActual = tweetcountDisplayed + 40;
  var tweetcountDelta;

  tweetcountElement.text("");
  var tweetcounts = [];
  tweetcounts.push('<span id="tweetcount-'+tweetcountDisplayed.toString()+'">'+tweetcountDisplayed.toString()+'</span>');
  tweetcountDisplayed++;

  while (tweetcountActual > tweetcountDisplayed) {
    tweetcounts.push('<span id="tweetcount-'+tweetcountDisplayed.toString()+'" style="display:none;">'+tweetcountDisplayed.toString()+'</span>');
    tweetcountDisplayed++;
  }
  tweetcountElement.append(tweetcounts.join(''));

  function flip(countFrom, countTo, limit) {
    if (countTo == limit) {
      return true;
    }
    jQuery('#tweetcount-'+countFrom.toString()).animate({foo:1}, 2000+Math.random()*7000).fadeOut(300, function() {
      jQuery('#tweetcount-'+countTo.toString()).fadeIn(300, function() {
        flip(countTo, countTo+1, limit);
      });
    });
  }
  flip(tweetcountDisplayed-40, tweetcountDisplayed-39, tweetcountDisplayed);
  
});
