function process_facebook_sign_in() {
  FB_RequireFeatures(["XFBML"], function() {
	  FB.Facebook.init( FB_API_KEY, "xd_receiver" );
	  FB.Connect.requireSession(function(){
		  FB.Connect.ifUserConnected( function( uid ){
					 FB.Facebook.apiClient.users_hasAppPermission('email', function(perm){
						if (!perm) {
							FB.Connect.showPermissionDialog('email', function(accepted) { if (accepted) var a=1; else var a=0;
																							  refresh_page(a); });
						} else refresh_page(1);
					 });
		  }, function() {
			 
		  });
	  });
	});
}

function facebook_sign_in() {
	FB_RequireFeatures(["XFBML"], function() {
	  FB.Facebook.init( FB_API_KEY, "xd_receiver" );
	  FB.Connect.requireSession(function(){
		  FB.Connect.ifUserConnected( function( uid ){
					 FB.Facebook.apiClient.users_hasAppPermission('email', function(perm){
						if (!perm) {
							FB.Connect.showPermissionDialog('email', function(accepted) { if (accepted) var a=1; else var a=0;
																							  refresh_page(a); });
						} else refresh_page(1);
					 });
		  }, function() {
			 
		  });
	  });
	});
}

function facebook_onload(already_logged_into_facebook) {
  // user state is either: has a session, or does not.
  // if the state has changed, detect that and reload.
  FB.ensureInit(function() {
      FB.Facebook.get_sessionState().waitUntilReady(function(session) {
          var is_now_logged_into_facebook = session ? true : false;

          // if the new state is the same as the old (i.e., nothing changed)
          // then do nothing
          if (is_now_logged_into_facebook == already_logged_into_facebook) {
            return;
          }

          // otherwise, refresh to pick up the state change
          refresh_page(1);
        });
    });
}

/*
 * Our <fb:login-button> specifies this function in its onlogin attribute,
 * which is triggered after the user authenticates the app in the Connect
 * dialog and the Facebook session has been set in the cookies.
 */
function facebook_onlogin_ready() {
  // In this app, we redirect the user back to index.php. The server will read
  // the cookie and see that the user is logged in, and will deliver a new page
  // with content appropriate for a logged-in user.
  //
  // However, a more complex app could use this function to do AJAX calls
  // and/or in-place replacement of page contents to avoid a full page refresh.
  refresh_page(1);
}

/*
 * Do a page refresh after login state changes.
 * This is the easiest but not the only way to pick up changes.
 * If you have a small amount of Facebook-specific content on a large page,
 * then you could change it in Javascript without refresh.
 */
function refresh_page(email) {
  window.location = '/authentificate/?email='+email;
}

/*
 * Prompts the user to grant a permission to the application.
 */
function facebook_prompt_permission(permission) {
  FB.ensureInit(function() {
    FB.Connect.showPermissionDialog(permission);
  });
}
