jQuery(function ($) {
  // Automatic browser upgrade warning via browser-update.org
  $.getScript('http://browser-update.org/update.js')

  // Load disqus code if a disqus shortname is set
  if (typeof disqus_shortname !== 'undefined') {
    $.getScript('http://disqus.com/forums/' + disqus_shortname + '/count.js');
    if ($('#disqus_thread').length > 0) {
      window.disqus_identifier = $('#disqus_thread').attr('data-identifier');
      window.disqus_url = $('#disqus_thread').attr('data-url');
      window.disqus_title = $('#disqus_thread').attr('data-title');
      window.disqus_developer = $('#disqus_thread').attr('data-developer');
      $.getScript('http://' + disqus_shortname + '.disqus.com/embed.js');
    }
  }

  // Load Twitter share button code if used (http://dev.twitter.com/pages/tweet_button)
  if ($('a.twitter-share-button').length > 0)
    $.getScript('http://platform.twitter.com/widgets.js')

  // Hide non-error flash message after some time
  $('#flash[class!=error]:visible').delay(7000).slideUp('slow');

  // Update list of latest tweets from Twitter
  $('ul[data-tweets-from]').each(function () {
    var list = $(this);
    var username = list.attr('data-tweets-from');
    var count = list.attr('data-tweets-count') || 4;
    list.parent().find('a.followme').attr('href', 'http://twitter.com/' + username);
    $.get('http://api.twitter.com/1/statuses/user_timeline.json', { screen_name: username, count: 5*count }, function (data) {
      list.empty();
      $.each(data, function () {
        if (this.text[0] == '@' || list.children().size() >= count) return;
        var url = 'http://twitter.com/' + this.user.screen_name + '/statuses/' + this.id;
        var time = new Date(Date.parse(this.created_at));
        time = Date.prototype.toRelativeTime ? time.toRelativeTime() : time.toLocaleString();
        var text = this.text;
        text = text.replace(/(https?:\/\/[a-z0-9.\/\?&_-]+)/gi, '<a href="$1">$1</a>');
        text = text.replace(/(@([a-z_]+))/gi, '<a href="http://twitter.com/$2">$1</a>');
        text = text.replace(/(#(\w+))/gi, '<a href="http://twitter.com/search?q=%23$2">$1</a>');
        list.append('<li>' + text + ' <a href="' + url + '" class="dimmed">' + time.toLocaleString() + '</a></li>');
      });
    }, 'jsonp');
  });

  // Automatically submit the OpenID login form with a common provider link
  $('a[data-openid-submit]').live('click', function (event) {
    event.preventDefault();
    var form = $(this).parents('form').first();
    form.find('input[type=text]#openid').val($(this).attr('data-openid-submit'));
    form.submit();
  });
});
