$(document).ready(function() {
  window.fbAsyncInit = function() {
    var fbLogin;

    FB.init({
      appId: _pm.FACEBOOK_APP_ID,
      cookie: true
    });

    fbLogin = function(redirect_url) {
      FB.login(function(response) {
        var url;
        if (response.authResponse) {
          url = '/auth/facebook/callback';
          if (redirect_url) {
            url = "" + url + "?redirect=" + redirect_url;
          }
          window.location = url;
        }
      }, { scope: 'email,user_birthday' });
    };

    // Auto redirect
    if (_pm.REDIRECT_URL) {
      fbLogin(_pm.REDIRECT_URL);
    }

    // Signin
    $('.facebook_sign_in').click(function(e) {
      var redirect_url = $(this).attr('data-fb-redirect');
      e.preventDefault();
      fbLogin(redirect_url);
    });

    // Signout
    $('#facebook_sign_out').click(function(e) {
      FB.getLoginStatus(function(response) {
        if (response.authResponse) {
          FB.logout();
        }
      });
      return true;
    });
  };

  $('body').prepend('<div id="fb-root"></div>');
  $.ajax({
    url: "" + window.location.protocol + "//connect.facebook.net/en_US/all.js",
    dataType: 'script',
    cache: true
  });
});  