diff --git a/fboauth.api.php b/fboauth.api.php
index bc744a6..c4981e4 100644
--- a/fboauth.api.php
+++ b/fboauth.api.php
@@ -25,7 +25,7 @@
  *   - callback: The name of a function to execute after gaining access.
  *   - permissions: A list of Facebook permissions to request.
  *
- * @see fboauth_fboauth_actions().
+ * @see fboauth_fboauth_actions()
  */
 function hook_fboauth_actions() {
   // Give each action a unique key, such as "mymodule_photo_import" for a photo
@@ -61,7 +61,7 @@ function hook_fboauth_actions() {
 /**
  * Alter the list of Facebook Actions provided through hook_fboauth_actions().
  *
- * @see fboauth_fboauth_actions().
+ * @see fboauth_fboauth_actions()
  */
 function hook_fboauth_actions_alter(&$actions) {
   // Replace the normal login callback with custom login callback.
diff --git a/fboauth.install b/fboauth.install
index 3043847..f7b60f1 100644
--- a/fboauth.install
+++ b/fboauth.install
@@ -20,6 +20,8 @@ function fboauth_install() {
 function fboauth_uninstall() {
   variable_del('fboauth_id');
   variable_del('fboauth_secret');
+  variable_del('fboauth_popup');
+  variable_del('fboauth_always_load_js');
   variable_del('fboauth_user_email');
   variable_del('fboauth_user_username');
   variable_del('fboauth_user_picture');
@@ -58,7 +60,7 @@ function fboauth_schema() {
 }
 
 /**
- * Implements hook_schema_alter()
+ * Implements hook_schema_alter().
  */
 function fboauth_schema_alter(&$schema) {
   $schema['users']['fields']['mail']['length'] = 320;
diff --git a/fboauth.module b/fboauth.module
index 0ef4138..6d0901e 100644
--- a/fboauth.module
+++ b/fboauth.module
@@ -1,6 +1,11 @@
 <?php
 
 /**
+ * @file
+ * Main file for the Facebook OAuth Module
+ */
+
+/**
  * Implements hook_menu().
  */
 function fboauth_menu() {
@@ -20,7 +25,7 @@ function fboauth_menu() {
     'type' => MENU_CALLBACK,
   );
   $items['admin/config/people/fboauth'] = array(
-    'title' => t('Facebook OAuth settings'),
+    'title' => 'Facebook OAuth settings',
     'page callback' => 'drupal_get_form',
     'page arguments' => array('fboauth_settings_form'),
     'access arguments' => array('administer users'),
@@ -29,7 +34,7 @@ function fboauth_menu() {
     'type' => MENU_NORMAL_ITEM,
   );
   $items['user/%user/fboauth'] = array(
-    'title' => t('Facebook settings'),
+    'title' => 'Facebook settings',
     'page callback' => 'fboauth_user_form',
     'page arguments' => array(1),
     'access callback' => 'user_edit_access',
@@ -40,6 +45,15 @@ function fboauth_menu() {
 }
 
 /**
+ * Implements hook_init().
+ */
+function fboauth_init() {
+  if (variable_get('fboauth_always_load_js', 0)) {
+    drupal_add_js(drupal_get_path('module', 'fboauth') . '/fboauth_popup.js');
+  }
+}
+
+/**
  * Implements hook_theme().
  */
 function fboauth_theme() {
@@ -78,8 +92,14 @@ function fboauth_block_view($delta) {
   $block = array();
   if (variable_get('fboauth_id', '') && !fboauth_fbid_load()) {
     // Set the redirect to the current page (unless we're on the login page).
-    $redirect = (arg(0) === 'user' && (arg(1) === 'login' || arg(1) == '')) ? NULL : $_GET['q'];
+    $destination = drupal_get_destination();
+    $redirect = (arg(0) === 'user' && (arg(1) === 'login' || arg(1) == '')) ? NULL : $destination['destination'];
     $block['content'] = fboauth_action_display('connect', $redirect);
+
+    if (variable_get('fboauth_popup', 0) &&
+        !variable_get('fboauth_always_load_js', 0) ) {
+      drupal_add_js(drupal_get_path('module', 'fboauth') . '/fboauth_popup.js');
+    }
   }
   return $block;
 }
@@ -130,6 +150,13 @@ function fboauth_form_user_profile_form_alter(&$form, &$form_state) {
     '#markup' => theme('fboauth_user_form_connect', array('uid' => $uid, 'fbid' => $fbid)),
   );
 
+  if (variable_get('fboauth_popup', 0) &&
+      !variable_get('fboauth_always_load_js', 0) ) {
+    $fboauth_form['#attached']['js'] = array(
+      drupal_get_path('module', 'fboauth') . '/fboauth_popup.js',
+    );
+  }
+
   // The account settings move around in this form.
   $account_form = isset($form['account']) ? $form['account'] : $form;
 
@@ -351,8 +378,14 @@ function fboauth_action_link_properties($action_name, $redirect = NULL, $app_id
       'redirect_uri' => fboauth_action_url('fboauth/' . $action_name, array('absolute' => TRUE, 'query' => $query)),
     ),
     'href' => 'https://www.facebook.com/dialog/oauth',
+    'attributes' => array(),
   );
 
+  if (variable_get('fboauth_popup', 0)) {
+    $return['attributes']['class'] = array('fboauth-popup');
+    $return['query']['display'] = 'popup';
+  }
+
   if ($permissions) {
     $return['query']['scope'] = implode(',', $permissions);
   }
@@ -420,7 +453,7 @@ function theme_fboauth_action__connect($variables) {
   $action = $variables['action'];
   $link = $variables['properties'];
   $url = url($link['href'], array('query' => $link['query']));
-  $link['attributes']['class'] = isset($link['attributes']['class']) ? $link['attributes']['class'] : 'facebook-action-connect';
+  $link['attributes']['class'][] = 'facebook-action-connect';
   $link['attributes']['rel'] = 'nofollow';
   $attributes = isset($link['attributes']) ? drupal_attributes($link['attributes']) : '';
   $title = isset($link['title']) ? check_plain($link['title']) : '';
diff --git a/fboauth_popup.js b/fboauth_popup.js
new file mode 100644
index 0000000..50bbe5c
--- /dev/null
+++ b/fboauth_popup.js
@@ -0,0 +1,37 @@
+(function ($) {
+
+  /**
+   * Add Drupal behaviors
+   */
+  Drupal.behaviors.fboauthPopup = {};
+  Drupal.behaviors.fboauthPopup.attach = function(context, settings) {
+    /**
+     * modify Facbook Oauth (fboauth) button with class "facebook-action-connect"
+     * to open in a popup window, instead of using the current window.
+     * References:
+     * http://thinkdiff.net/facebook/create-facebook-popup-authentication-window-using-php-and-javascript/
+     * http://developers.facebook.com/docs/authentication/
+     * http://developers.facebook.com/docs/authentication/server-side/
+     * http://developers.facebook.com/docs/reference/dialogs/oauth/
+     */
+    $('.fboauth-popup').click(function() {
+      var screenX    = typeof window.screenX != 'undefined' ? window.screenX : window.screenLeft,
+        screenY      = typeof window.screenY != 'undefined' ? window.screenY : window.screenTop,
+        outerWidth   = typeof window.outerWidth != 'undefined' ? window.outerWidth : document.body.clientWidth,
+        outerHeight  = typeof window.outerHeight != 'undefined' ? window.outerHeight : (document.body.clientHeight - 22),
+        width    = 500,
+        height   = 270,
+        left     = parseInt(screenX + ((outerWidth - width) / 2), 10),
+        top      = parseInt(screenY + ((outerHeight - height) / 2.5), 10),
+        features = 'width=' + width + ',height=' + height + ',left=' + left + ',top=' + top;
+
+      var popupWindow = window.open($(this).attr("href"), 'fboauth', features);
+      if (window.focus) {
+        popupWindow.focus();
+      }
+
+      return false;
+    });
+  };
+
+})(jQuery);
diff --git a/includes/fboauth.fboauth.inc b/includes/fboauth.fboauth.inc
index cc4b87e..fc28011 100644
--- a/includes/fboauth.fboauth.inc
+++ b/includes/fboauth.fboauth.inc
@@ -29,9 +29,20 @@ function fboauth_action_page($action) {
     watchdog('fboauth', 'A Facebook login was attempted but could not be processed because the module is not yet configured. Vist the <a href="!url">Facebook OAuth configuration</a> to set up the module.', array('!url' => url('admin/config/people/fboauth')));
   }
   elseif (isset($_REQUEST['error'])) {
-    $link = fboauth_action_link_properties($action_name, $app_id);
+    $url = !$user->uid ? url('<front>', array('absolute' => TRUE)) : url("user/{$user->uid}/edit", array('absolute' => TRUE));
+    $link = fboauth_action_link_properties($action_name, $url);
     watchdog('fboauth', 'A user refused to allow access to the necessary Facebook information (@permissions) to login to the site.', array('@permissions' => $link['query']['scope']));
-    $error_message = t('This site requires access to information in order to log you into the site. If you like you can <a href="!facebook">sign in with Facebook again</a> or <a href="!register">register normally</a>.', array('!facebook' => url($link['href'], array('query' => $link['query'])), '!register' => url('user/register')));
+
+    $html_class = variable_get('fboauth_popup') ? ' class="fboauth-popup"' : '';
+    $error_message = t('This site requires access to information in order to log you into the site. If you like you can <a href="!facebook"' . $html_class . '>sign in with Facebook again</a> or <a href="!register">register normally</a>.', array('!facebook' => url($link['href'], array('query' => $link['query'])), '!register' => url('user/register')));
+    drupal_set_message($error_message, 'error');
+
+    if (variable_get('fboauth_popup', 0)) {
+      // Close the popup and set the parent window to the target destination.
+      print fboauth_close_popup_window($url);
+      drupal_exit();
+    }
+    drupal_goto($url);
   }
   elseif (!isset($_REQUEST['code'])) {
     watchdog('fboauth', 'A Facebook request code was expected but no authorization was received.');
@@ -42,7 +53,16 @@ function fboauth_action_page($action) {
     if (empty($destination)) {
       $destination = isset($_REQUEST['destination']) ? $_REQUEST['destination'] : '<front>';
     }
-    drupal_goto($destination);
+
+    if (variable_get('fboauth_popup', 0)) {
+      // Close the popup and set the parent window to the target destination.
+      $url = $user->pass == '' ? url("user/{$user->uid}/edit", array('absolute' => TRUE)) : url($destination);
+      print fboauth_close_popup_window($url);
+      drupal_exit();
+    }
+    else {
+      drupal_goto($destination);
+    }
   }
 
   // In the event of an error, we stay on this page.
@@ -50,6 +70,29 @@ function fboauth_action_page($action) {
 }
 
 /**
+ * Returns a HTML string to close the popup modal window and redirect the opener window to the relevant URL.
+ *
+ * @param $url
+ * @return string
+ */
+function fboauth_close_popup_window($url) {
+  return "
+    <html>
+    <head>
+      <script type=\"text/javascript\">
+      if (window.opener) {
+        window.opener.location = '$url';
+        setTimeout(function(){ window.close(); }, 500);
+      }
+      else {
+        window.location = '$url';
+      }
+      </script>
+    </head>
+    </html>";
+}
+
+/**
  * Invoke an action specified through hook_fboauth_action_info().
  */
 function fboauth_action_invoke($action_name, $app_id, $access_token) {
@@ -213,7 +256,7 @@ function fboauth_create_user($fbuser, $options = array()) {
   // Retrieve the user's picture from Facebook and save it locally.
   if ($account->uid && $options['picture'] === 'picture') {
     $picture_directory =  file_default_scheme() . '://' . variable_get('user_picture_path', 'pictures');
-    if(file_prepare_directory($picture_directory, FILE_CREATE_DIRECTORY)){
+    if (file_prepare_directory($picture_directory, FILE_CREATE_DIRECTORY)) {
       $picture_result = drupal_http_request('https://graph.facebook.com/' . $fbuser->id . '/picture?type=large');
       $picture_path = file_stream_wrapper_uri_normalize($picture_directory . '/picture-' . $account->uid . '-' . REQUEST_TIME . '.jpg');
       $picture_file = file_save_data($picture_result->data, $picture_path, FILE_EXISTS_REPLACE);
@@ -303,7 +346,17 @@ function fboauth_access_token($code, $action_name, $app_id = NULL, $app_secret =
     'code' => $code,
   );
   $token_url = url('https://graph.facebook.com/oauth/access_token', array('absolute' => TRUE, 'query' => $query));
-  $authentication_result = drupal_http_request($token_url);
+
+  $attempts = 5;
+  do {
+      $authentication_result = drupal_http_request($token_url);
+      if ($authentication_result->code == 200) {
+          break;
+      }
+      // Facebook access code generation seems to take a lot of time. That's why we have to wait
+      // some seconds before the code can be acquired.
+      sleep(1);
+  } while (--$attempts > 0);
 
   if ($authentication_result->code != 200) {
     $error = !empty($authentication_result->error) ? $authentication_result->error : t('(no error returned)');
@@ -754,7 +807,7 @@ function fboauth_deauthorize() {
   // A signed_request key is used when a deauth url is provided by the app.
   if (isset($_POST['signed_request'])) {
     $app_secret = variable_get('fboauth_secret', '');
-    $signed_request = fboauth_parse_signed_request($_POST['signed_request'], $app_secret);
+    $signed_request = fboauth_parse_signed_request(check_plain($_POST['signed_request']), $app_secret);
 
     if ($signed_request && $deauth_uid = fboauth_uid_load($signed_request['user_id'])) {
       fboauth_save($deauth_uid, NULL);
@@ -776,18 +829,18 @@ function fboauth_parse_signed_request($signed_request, $secret) {
 
   // Decode the data.
   $signature = fboauth_base64_url_decode($encoded_signature);
-  $data = json_decode(fboauth_base64_url_decode($payload), true);
+  $data = json_decode(fboauth_base64_url_decode($payload), TRUE);
 
   if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
     watchdog('fboauth', 'A Facebook deauthorization request failed: Unknown signed request algorithm. Expected HMAC-SHA256.');
-    return null;
+    return NULL;
   }
 
   // Check the signature.
-  $expected_signature = hash_hmac('sha256', $payload, $secret, $raw = true);
+  $expected_signature = hash_hmac('sha256', $payload, $secret, $raw = TRUE);
   if ($signature !== $expected_signature) {
     watchdog('fboauth', 'A Facebook deauthorization request failed: Bad Signed JSON signature!');
-    return null;
+    return NULL;
   }
 
   return $data;
@@ -805,4 +858,4 @@ function fboauth_parse_signed_request($signed_request, $secret) {
  */
 function fboauth_base64_url_decode($input) {
   return base64_decode(strtr($input, '-_', '+/'));
-}
\ No newline at end of file
+}
diff --git a/includes/fboauth.field.inc b/includes/fboauth.field.inc
index 353def7..6c87ac3 100644
--- a/includes/fboauth.field.inc
+++ b/includes/fboauth.field.inc
@@ -36,7 +36,7 @@ function fboauth_field_form_alter(&$form, &$form_state) {
     if (isset($property_options[$field['type']])) {
       $options = array_merge(array('' => t('- Do not import -')), $property_options[$field['type']]);
       $form['fboauth_user_fields'][$field_name] = array(
-        '#title' => t($instance['label']),
+        '#title' => check_plain(t($instance['label'])),
         '#type' => 'select',
         '#options' => $options,
         '#default_value' => isset($field_defaults[$field_name]) ? $field_defaults[$field_name] : '',
@@ -44,7 +44,7 @@ function fboauth_field_form_alter(&$form, &$form_state) {
     }
     else {
       $form['fboauth_user_fields'][$field_name] = array(
-        '#title' => t($instance['label']),
+        '#title' => check_plain(t($instance['label'])),
         '#type' => 'form_element',
         '#children' => '<em>' . t('No mappable Facebook properties.') . '</em>',
         '#theme_wrappers' => array('form_element'),
diff --git a/includes/fboauth.pages.inc b/includes/fboauth.pages.inc
index dc37e44..f303ab6 100644
--- a/includes/fboauth.pages.inc
+++ b/includes/fboauth.pages.inc
@@ -19,6 +19,7 @@ function fboauth_settings_form($form, &$form_state) {
     '#description' => t('To use Facebook connect, a Facebook Application must be created. Set up your app in <a href="http://www.facebook.com/developers/apps.php">my apps</a> on Facebook.') . ' ' . t('Enter your App ID here.'),
     '#default_value' => variable_get('fboauth_id', ''),
   );
+
   $form['fboauth_secret'] = array(
     '#type' => 'textfield',
     '#title' => t('App Secret'),
@@ -28,6 +29,25 @@ function fboauth_settings_form($form, &$form_state) {
     '#default_value' => variable_get('fboauth_secret', ''),
   );
 
+  $form['fboauth_popup'] = array(
+    '#type' => 'checkbox',
+    '#title' => t('Use a popup window for Facebook authentication dialog'),
+    '#description' => t('This may provide a better user experience when logging into Facebook, but may also be blocked by browser popup blocker plugins.'),
+    '#default_value' => variable_get('fboauth_popup', 0),
+  );
+
+  $form['fboauth_always_load_js'] = array(
+    '#type' => 'checkbox',
+    '#title' => t('Always load the popup window javascript file'),
+    '#description' => t('This will load the popup window javascript file on every page load rather than only when the block is loaded. This is mainly for when you want to implement the Facebook button code manually.'),
+    '#default_value' => variable_get('fboauth_always_load_js', 0),
+    '#states' => array(
+      'invisible' => array(
+        ':input[name="fboauth_popup"]' => array('checked' => FALSE),
+      ),
+    ),
+  );
+
   $form['fboauth_basic_mapping'] = array(
     '#type' => 'fieldset',
     '#title' => t('Basic mapping'),
@@ -141,6 +161,15 @@ function fboauth_settings_form_validate($form, &$form_state) {
 function fboauth_settings_form_submit($form, &$form_state) {
   variable_set('fboauth_id', $form_state['values']['fboauth_id']);
   variable_set('fboauth_secret', $form_state['values']['fboauth_secret']);
+  variable_set('fboauth_popup', $form_state['values']['fboauth_popup']);
+
+  // Set fboauth_always_load_js to be FALSE if fboauth_always_load_js has been
+  // turned off as well.
+  $load_js = $form_state['values']['fboauth_always_load_js'];
+  if (!$form_state['values']['fboauth_popup']) {
+    $load_js = 0;
+  }
+  variable_set('fboauth_always_load_js', $load_js);
 
   variable_set('fboauth_user_email', $form_state['values']['fboauth_user_email']);
   variable_set('fboauth_user_username', $form_state['values']['fboauth_user_username']);
