(function() {
  var twitter,
    facebook;
  twitter = function() {
    elem = $(this);
    
    // Taken from http://platform.twitter.com/widgets.js
    var G = "scrollbars=yes,resizable=yes,toolbar=no,location=yes",
    U = 550,
    Q = 250,
    C = screen.height,
    P = screen.width;
    a = function(i) {
      i = i || window.event;
      var h = i.target || i.srcElement,
      d,
      g,
      f;
      while (h && h.nodeName.toLowerCase() !== "a") {
        h = h.parentNode
      }
      if (h && h.nodeName.toLowerCase() === "a" && h.href) {
        g = Math.round((P / 2) - (U / 2));
        f = 0;
        if (C > Q) {
          f = Math.round((C / 2) - (Q / 2))
        }
        window.open(h.href, "intent", G + ",width=" + U + ",height=" + Q + ",left=" + g + ",top=" + f);
        i.returnValue = false;
        i.preventDefault && i.preventDefault()
      }
    }
    
    elem.click(a);
  }
  
  facebook = function(opts) {
    elem = $(this);
    
    if (opts == null || !opts.hasOwnProperty('app_id') || opts.app_id === undefined) {
      throw "Need to specify a Facebook app id";
    }
    
    window.fbAsyncInit = function() {
      FB.init({
        appId: opts.app_id,
        cookie: true,
        status: true
      })
    }
    
    var e = document.createElement('script');
    e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
    e.async = true;
    $('body').append('<div id="fb-root"></div>').append(e);
    
    elem.click(function(){
      var params = {
        method: 'feed'
      }
      
      if (opts.link) {
        params.link = opts.link;
      }
      
      if (opts.message) {
        params.message = opts.message;
      }
      
      FB.ui(params)
      return false;
    })
  }
  
  $.extend($.fn, {
    twitter: twitter,
    facebook: facebook
  });
}).call(this);
