$(document).ready(function() {

  $('#fb_login').bind('click', function() {
    FB.login(handleSessionResponse, {perms:'email'});
  });

  $('#fb_logout').bind('click', function() {
    FB.logout(handleSessionResponse);
  });

  $('#fb_disconnect').bind('click', function() {
    FB.api({ method: 'Auth.revokeAuthorization' }, function(response) {
      clearDisplay();
    });
  });

  // no user, clear display
  function clearDisplay() {
    $('.fb_username').html("");
    $("img.fb_userphoto").attr("src", "");
    $("img.fb_userphoto").hide();
    $('#fb_login').show("fast");
    $('#fb_logout').hide();
    $('#fb_disconnect').hide();
  }

  // there is a user, set his data
  function showDisplay(session) {
    // if we have a session, query for the user's profile picture and name
    FB.api(
      {
        method: 'fql.query',
        query: 'SELECT name, pic FROM profile WHERE id=' + FB.getSession().uid
      },
      function(response) {
        var user = response[0];
        $('.fb_username').html(user.name);
        $("img.fb_userphoto").attr("src", user.pic);
        $("img.fb_userphoto").show("fast");
        $('#fb_login').hide();
        $('#fb_logout').show("fast");
        $('#fb_disconnect').show("fast");
      }
    )
  }

  // handle a session response from any of the auth related calls
  function handleSessionResponse(response) {
    // if we dont have a session, just hide the user info
    if (!response.session) {
      clearDisplay();
      return;
    }
    showDisplay(response.session);
  }

  FB.getLoginStatus(function(response) {
    if (response.session) {
      showDisplay(response.session);
    } else {
      clearDisplay();
    }
  });

});
