if (!window.Evri) window.Evri = {};

Evri.FacebookShare = {

  shareArticle: function(title, link, description) {
    if (this.loggedIn()) {
      var shortLink = EvriShortener.shortenUrl(link);
      $.cookie(Evri.Constants.FACEBOOK_LOGIN_COOKIE_NAME, '');

      FB.Connect.showFeedDialog(Evri.FACEBOOK_SHARE_TEMPLATE,
      { "title": decodeURIComponent(title), "link": shortLink, "description": description},
        null, null, null, FB.RequireConnect.promptConnect);
    } else {
      this.logIn(title, link, description);
    }

    return false;
  },

  loggedIn: function() {
    return (FB.Connect.get_status().result != FB.ConnectState.userNotLoggedIn);
  },

  logIn: function(title, link, description) {
    var articleParams = {
      'title': title,
      'link': link,
      'description': description
    };

    $.cookie(Evri.Constants.FACEBOOK_LOGIN_COOKIE_NAME, JSON.stringify(articleParams));

    var tokenUrl = 'http://' + top.location.host + '/rpx/process_token' + URI.toQueryString({'redirect_url': top.location.href});
    var action = 'https://' + Evri.RPX_NOW_TARGET_HOST + '/facebook/start' + URI.toQueryString({'token_url': tokenUrl});

    // can't be ajax, need to refresh this page
    var $form = $('<form/>').attr('action', action).attr('method', 'POST');

    $('body').append($form);
    $form.submit();
    return false;
  },


  /**
   * If we've been redirected here after a facebook login, we should
   * have a FACEBOOK_LOGIN_COOKIE_NAME cookie that contains all the
   * info about the article we're trying to share and we should pop
   * the facebook share box
   */
  checkForShare: function() {
    var cookieValue = $.cookie(Evri.Constants.FACEBOOK_LOGIN_COOKIE_NAME);
    if (cookieValue) {
      var articleParams = JSON.parse(cookieValue);
      Evri.FacebookShare.shareArticle(articleParams.title, articleParams.link, articleParams.description);
    }
  }
};
