(function (latest_id) {
  var errorCount, template, parse, requestError, request, prettyDateUpdater;

  errorCount = 0;
  template = '<div class="post service-twitter"><p>{{{html}}}</p><div class="info"><a href="{{url}}" class="updated" title="{{{time_iso}}}">{{{time}}}</a> by <a href="http://twitter.com/{{screen_name}}">{{screen_name}}</a></div></div>';

  parse = function (tweets, textStatus, xhReq) {
    var i, length, box, old_height, old_margin, new_height, tweet;

    if (xhReq.status !== 200)  {
      requestError();
      return;
    }

    if (errorCount > 0) {
      errorCount -= 1;
    }

    box = jQuery('#feed');
    old_height = box.height();
    old_margin = parseInt(box.css('margin-top'), 10);
    new_height = 0;
    length = tweets.length;

    if (length) {
      latest_id = tweets[0].event_id;

      for (i = length - 1; i >= 0; i--) {
        tweet = jQuery(Mustache.to_html(template, tweets[i])).prependTo(box).find('.updated').prettyDate();

        new_height += tweet.outerHeight();
        box.css('margin-top', '-' + (new_height - old_margin) + 'px');
      }

      new_height =  box.height() - old_height;
      box.css('margin-top', '-' + (new_height - old_margin) + 'px');

      box.stop(true).animate({
        marginTop : 0
      }, 500);
      box.children(':gt(20)').animate({height:0,paddingBottom:0}, 600, 'linear', function () {
        jQuery(this).remove();
      });
    }

    request();
  };

  requestError = function () {
    if (errorCount < 10) {
      errorCount += 1;
    }
    setTimeout(request, Math.pow(2, errorCount / 2) * 1000);
  };

  request = function () {
    jQuery.ajax({
      data           : {'since_id' : latest_id},
      dataTypeString : 'json',
      success        : parse,
      timeoutNumber  : 11000,
      url            : '/wait',
      error          : requestError
    });
  };

  prettyDateUpdater = function () {
    jQuery('.post .updated').prettyDate();
    setTimeout(prettyDateUpdater, 5000);
  };

  prettyDateUpdater();
  request();
})(importClientLatestId ? importClientLatestId : 0);