var Audiencc = {};

Audiencc.parseJSON = function(rawData) {
  return eval('(' + rawData + ')');
};

Audiencc.Twitter = {
  'conversationFeed': function (user) {
    return new google.feeds.Feed(
      'http://search.twitter.com/search.rss?q=' // tweets
       + encodeURIComponent('from:'   + user    // from user
                          + ' OR to:' + user    // or to user         
                          + ' OR @'   + user    // or with mentions of user
       )
    );
  },
  'reactionFeed': function(from, to) {
    return new google.feeds.Feed(
      'http://search.twitter.com/search.rss?q=' // tweets
       + encodeURIComponent('from:'   + from    // from user
                          + ' @'   + to    // or with mentions of user
       )
    );
  },
  'feed': function (user) {
    return new google.feeds.Feed(
      'http://search.twitter.com/search.rss?q=' // tweets
       + encodeURIComponent('from:'   + user)    // from user
       );
  },
  'FeedEntry': {
    'author': function(entry) {
      // "audiencc@twitter.com (Audiencc)" before split
      return entry.author.split('@', 2)[0];
    },
    'contentText': function(entry) {
      // do you know a clearer way to strip tags?
      return $("<p></p>").html(entry.content).text();
    }
  },
  'tweetsCount': function(url, callback) {
    Audiencc.jsonp(
      "http://api.tweetmeme.com/url_info.json?url=" + url,
      function(data) {
        var tweetsCount = 0;
        if (data.status == 'success') {
          tweetsCount = data.story.url_count;
        }
        callback(tweetsCount);
      }
    );
  }
};

Audiencc.updateBlogPostStatsHtml = function(post) {
  Audiencc.discoverPostCommentsFeed(
    post.link,
    function (commentsFeedUrl) {
      var postFeed = new google.feeds.Feed(commentsFeedUrl);
      postFeed.setNumEntries(-1);
      postFeed.load(
        function(result) {
          var commentsCount = 0;
          if (!result.error) {
            commentsCount = result.feed.entries.length;
          }

          Audiencc.Twitter.tweetsCount(
            post.link,
            function (tweetsCount) {
              var statsText = Audiencc.blogPostStatsText(commentsCount, tweetsCount);
              if (statsText != '') {
                $('#' + post.statsId).html(statsText).show();
              }
            }
          );
        }
      );
    }
  )  
};

Audiencc.discoverPostCommentsFeed = function (postLink, onDiscovery) {
  $.getJSON(
    "/api/blog_post_comments_feed_url?callback=?&url=" + encodeURIComponent(postLink),
    function (result) {
      if (result.status == "ok") {
        onDiscovery(result.url);
      }
    }
  );
}
    

Audiencc.ensureTrailingSlash = function (url) {
  var urlWithTrailingSlash = url;
  if (url.substring(url.length - 1) != '/') {
    urlWithTrailingSlash += '/';
  }

  return urlWithTrailingSlash;
}

Audiencc.blogPostStatsText = function (commentsCount, tweetsCount) {
  if (commentsCount == 0 && tweetsCount == 0) {
    return '';
  }

  var stats = '';
  if (commentsCount > 0) {
    stats += commentsCount + ' Comment';
  }
  if (commentsCount > 1) {
    stats += 's';
  }

  if (tweetsCount > 0) {
    if (commentsCount > 0) {
      stats += ' and ';
    }
    stats += tweetsCount + ' Reaction';
  }
  if (tweetsCount > 1) {
    stats += 's';
  }

  return stats;
};

Audiencc.jsonp = function (url, callback) {
  $.getJSON(
    "/api/jsonp?callback=?&url=" + encodeURIComponent(url),
    function (result) {
      if (result.status == "ok") {
        callback(result.json);
      }
    }
  );
};

Audiencc.endUrl = function (url, callback) {
  $.getJSON(
    "/api/end_url?callback=?&url=" + encodeURIComponent(url),
    function (result) {
      if (result.status == "ok") {
        callback(result.url);
      }
    }
  );
}

Audiencc.filterBlogPostNonsense = function (postContent) {
  var nonsenseStartPos = postContent.indexOf("<div>\n<a href=\"http://feeds.feedburner.com/~ff");
  if (nonsenseStartPos != -1) {
    var nonsenseEnd = '</div>'
    var nonsenseEndPos = postContent.indexOf(nonsenseEnd, nonsenseStartPos);
    if (nonsenseEndPos != -1) {
      return postContent.substring(0 ,nonsenseStartPos) +
        postContent.substring(nonsenseEndPos + nonsenseEnd.length);
    }
  }

  return postContent;
}

Audiencc.pluralize = function (singularForm, amount) {
  return singularForm + (amount > 1 ? 's' : '');
}

String.prototype.supplant = function (o) {
    return this.replace(/{([^{}]*)}/g,
        function (a, b) {
            var r = o[b];
            return typeof r === 'string' || typeof r === 'number' ? r : a;
        }
    );
};
