// plugin to load recent tweets
$.fn.tweet = function() {
  var $this = $(this);
  
  return this.each(function() {
    var $ul = $('<ul />');
    
    $.getJSON('http://twitter.com/statuses/user_timeline/formedfunction.json?count=3&callback=?', function(data) {
      for (var i=0; i<3; i++) {
        var tweet = data[i].text;
        if (tweet.search(/(https?:\/\/[-\w\.]+:?\/[\w\/_\.]*(\?\S+)?)/) > -1)
          tweet = tweet.replace(/(https?:\/\/[-\w\.]+:?\/[\w\/_\.]*(\?\S+)?)/, "<a href=\"$1\">$1</a>");
        $ul.append("<li>" + tweet + "</li>");
      }
      
      $this.html($ul);
    });
    
  });
}

// plugin to load dribbble shots
$.fn.dribbble = function() {
  var $this = $(this);
  
  return this.each(function() {
    var $ul = $('<ul />'), per_page = 4;
    
    $.getJSON('http://api.dribbble.com/players/rpheath/shots?per_page=' + per_page + '&callback=?', function(data) {
      for (var i=0; i<per_page; i++) {
        var css = i == (per_page - 1) ? 'last' : 'thumb';
        var thumb = new Image();
        thumb.src = data.shots[i].image_teaser_url;
        $ul.append('<li class="' + css + '"><a href="' + data.shots[i].short_url + '" rel="external"><img src="' + thumb.src + '" alt="' + data.shots[i].title + '" /></a></li>');
      }
    });
    
    $this.html($ul);
  });
}

// plugin to load github repos
$.fn.github = function() {
  var $this = $(this);
  
  return this.each(function() {
    var $ul = $('<ul />');
    
    $.getJSON('http://github.com/api/v1/json/rpheath?callback=?', function(data) {
      $(data.user.repositories).each(function(i, repo) {
        var link = '<a href="' + repo.url + '" title="">' + repo.name + '</a>';
        $ul.append('<li>' + link + '<p>' + repo.description + '</p></li>');
      });
    });
    
    $this.html($ul)
  });
}

$(function() {
  $('a[rel=facebox]').facebox();
  $('#tweets').tweet();  
  $('#dribbble .shots').dribbble();
  $('a[rel=external]').live('click', function() {
    $(this).attr('target', '_blank');
  });
  $('#github').github();
});
