﻿  var fbc = {
    loggedIn: false,        // Tells if the user is currently logged in or not.
    userId: null,           // The Facebook user-ID of the logged in user.
    commentsLoaded: false,  // Tells if the comments have already been loaded.
    xid: null,              // The XID of the comment box.
    numPosts: 10,           // The max number of posts to display.
    retry: 3,               // The number of retries when an data loading error occurred.

    /*************************************************
    * Get comments from Facebook on the current XID.
    *************************************************/
    getFBComments: function(){
      var uri = jQuery.parseUri(document.location.href);
      var $fbComments = jQuery("#fbComments");
      jQuery.ajax({
        url: uri.protocol + "://" + uri.authority + uri.path + "?action=getcomments",
        dataType: 'html',
        error: fbc.dataLoadFailed,
        success: function(data){
          fbc.retry = 3;
          jQuery("#fbComments").html(data);
          if (!fbc.userId) return
          jQuery(".commment", this).each(function(){
            var uid = jQuery("input.fbUid", this).val();
            if (uid == fbc.userId){
              var $delete = jQuery(".delete", this);
              jQuery(".delete", this).append("<a href='#'>Delete</a>");
              $delete.children("a").click(function(){
                $this = jQuery(this).parent();
                if (confirm ('Delete the following comment?\n"' + $this.siblings(".commentbody").text() + '"')){
                  var $postcontent = jQuerythis.parent();
                  var postid = $postcontent.siblings("input.fbPostId").val();
                  FB.Facebook.apiClient.callMethod("Comments.remove", {'xid': fbc.xid, 'comment_id': postid}, function(result, exception){
                    if (!result){
                      alert("Error, comment not deleted.\n" + exception);
                      return;
                    }
                    $postcontent.parent().remove();
                  });
                }
                return false;
              });
            }
          });
        }
      });
    },

    dataLoadFailed: function(request, textStatus){
      if (--fbc.retry){
        fbc.getFBComments();
        return;
      }
      jQuery("#fbComments").hide();
    },

    onLoggedIn: function(){
      fbc.init();

      fbc.loggedIn = true;
      fbc.userId = FB.Facebook.apiClient.get_session().uid;

      jQuery("#fbLogin").hide();
      fbc.getFBComments();
    },

    onLoggedOut: function(){
      fbc.init();

      fbc.loggedIn = false;
      fbc.commentsLoaded = false;

      jQuery("#fbLogin").show();

      fbc.getFBComments();
    },

    init: function(){
      fbc.xid = jQuery("#fbXid").val();
      fbc.numPosts = jQuery("#fbNumPosts").val();
    }
  };
