$(function(){
  /**
   * Fetches the URI of the current page, but trims the the relative page anchor
   * if it appears (e.g. "#something").
   * 
   * @return string
   */
  function getUri() {
    var pos = location.href.indexOf('#');
    return (pos == -1 ? location.href : location.href.substring(0, pos));
  }
  
  /**
   * Fetches the title of the current page, which is the document title up to
   * but not including the first colon character.  This ignores the corner case
   * where the desirable headline may contain a colon, but it handles the common
   * case of trimming the standard title suffix (e.g. ": FiLife (WSJ)").
   * 
   * @return string
   */
  function getTitle() {
    var pos = document.title.indexOf(':');
    return $.trim(pos == -1 ? document.title : document.title.substring(0, pos));
  }
  
  // Initialize links to share the current page via Facebook
  $('a.share-facebook').live('click', function(){
    var u = encodeURIComponent(getUri());
    var t = encodeURIComponent(getHeadline());
    
    window.open('http://www.facebook.com/sharer.php?u=' + u + '&t=' + t, 'share_facebook', 'toolbar=0,status=0,width=626,height=436');
    return false;
  });
  
  // Initialize links to share the current page via Twitter
  $('a.share-twitter').live('click', function(){
    // If the bitly API isn't loaded, fall back to the link's share URL
    if (typeof(BitlyClient) != 'object') {
      return true;
    }
    
    var $anchor = $(this);
    
    BitlyCB.sharingShortenCallback = function(data) {
      var result;
      
      // Fall back to the anchor's href if bitly API reported an error
      if (data.statusCode != 'OK') {
        window.location = $anchor.attr('href');
        return false;
      }
      
      $.each(data.results, function(){
        result = this;
        return false;
      });
      
      // Base tweet is the URL and "@FiLife" suffix
      var s = ' ' + result.shortUrl;
      
      // If 'rev' attribute is set, add it to the base tweet (see: #6581)
      if ($anchor.attr('rev')) {
        s += ' ' + $anchor.attr('rev');
      }
      
      var headline = "RT @FiLife " + getTitle();
      
      // Trim the headline if necessary
      if (headline.length > (140 - s.length)) {
        s = headline.substring(0, 139 - s.length) + '…' + s;
      } else {
        s = headline + s;
      }
      
      /* TODO: Setting window.location seems to break back-button functionality,
       * although it clearly shouldn't (only location.replace() should do that).
       */
      
      // Change the window location instead of generating a popup
      window.location = 'http://twitter.com/home?status=' + encodeURIComponent(s);
    };
    
    BitlyClient.shorten(getUri(), 'BitlyCB.sharingShortenCallback');
    return false;
  });
});
