
$( document ).ready( function()
{
  FB.init({ appId: '110561875652351', status: true, cookie: true, xfbml: true });
  FB.Event.subscribe( 'auth.sessionChange', function( response )
  {
    if ( response.session )
    {
              window.location.href = 'http://xgewinnt.de/einloggen';
          }
    else
    {
              window.location.href = 'http://xgewinnt.de/ausloggen';
          }
  });
  $( '#btn-fb-logout' ).click( function()
  {
    FB.logout();
    return false;
  });
  ////////////////////////////////////////////////////////////////////////////////////////
  // Check whether we still have all needed permissions for a particular user operation //
  // (do that with PHP server-side and if not so, add classes to buttons as necessary)  //
  ////////////////////////////////////////////////////////////////////////////////////////
  var permissions = [
    'email','publish_stream'  ];
  $( '.fbNeedsPermission' ).bind( 'click.fbPermissions', function()
  {
    var tmp = [];
    var elementId = this;
    for ( var it in permissions )
    {
      if ( $( elementId ).hasClass( permissions[it] ) ) { tmp.push( permissions[it] ); }
    }
    var permString = tmp.join( ',' );
    console.log( 'asking fb for permission(s) ' + permString );
    FB.login( function( response )
    {
      if ( response.perms )
      {
        console.log( 'permissions in response: ' + response.perms );
        var permissionsFoundInResponse = 0;
        var perms = response.perms.split( ',' );
        for ( var it in perms )
        {
          for ( var jt in tmp )
          {
            if ( tmp[jt] == perms[it] )
            {
              console.log( 'found permission in response: ' + tmp[it] );
              permissionsFoundInResponse++;
              break;
            }
          }
        }
        if ( permissionsFoundInResponse == tmp.length ) $( elementId ).unbind( 'click.fbPermissions' );
        else console.log( 'did not find needed permissions in response' );
      }
    }, { perms: permString });
    return false;
  });
});
