diff --git a/fboauth.install b/fboauth.install
index 4f06ac8..d99faf9 100755
--- a/fboauth.install
+++ b/fboauth.install
@@ -20,6 +20,8 @@
 function fboauth_uninstall() {
   variable_del('fboauth_id');
   variable_del('fboauth_secret');
+  variable_del('fboauth_popup');
+  variable_del('fboauth_always_load_js');
   variable_del('fboauth_anon_connect');
   variable_del('fboauth_user_email');
   variable_del('fboauth_user_username');
diff --git a/fboauth.module b/fboauth.module
index 103fda8..a5315f4 100755
--- a/fboauth.module
+++ b/fboauth.module
@@ -40,6 +40,30 @@
 }
 
 /**
+ * Implements hook_init().
+ */
+function fboauth_init() {
+  global $user;
+  if (variable_get('fboauth_always_load_js', 0)) {
+    $url = drupal_parse_url(request_uri());
+
+    if (drupal_match_path($url['path'], '/user/' . $user->uid . '/fboauth')) {
+      $fbid = fboauth_fbid_load($user->uid);
+      if ($fbid !== FALSE) {
+        // We have a fbid so must be displaying the deauth button, no need for
+        // the popup window.
+      }
+      else {
+        drupal_add_js(drupal_get_path('module', 'fboauth') . '/fboauth_popup.js');
+      }
+    }
+    elseif (!drupal_match_path($url['path'], '/user/' . $user->uid . '/fboauth')) {
+      drupal_add_js(drupal_get_path('module', 'fboauth') . '/fboauth_popup.js');
+    }
+  }
+}
+
+/**
  * Implements hook_theme().
  */
 function fboauth_theme() {
@@ -78,8 +102,14 @@
   $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;
 }
@@ -129,6 +159,13 @@
     '#title' => t('Facebook connect'),
     '#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;
@@ -376,7 +413,13 @@
       'redirect_uri' => fboauth_action_url('fboauth/' . $action_name, array('absolute' => TRUE, 'query' => $query)),
     ),
     'href' => 'https://www.facebook.com/v2.2/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);
@@ -445,7 +488,7 @@
   $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..3626955
--- /dev/null
+++ b/fboauth_popup.js
@@ -0,0 +1,39 @@
+(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() {
+	$('.facebook-action-connect').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);
\ No newline at end of file
diff --git a/includes/fboauth.fboauth.inc b/includes/fboauth.fboauth.inc
index dee43e4..47923da 100755
--- a/includes/fboauth.fboauth.inc
+++ b/includes/fboauth.fboauth.inc
@@ -29,18 +29,29 @@
     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']));
+    $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">sign in with Facebook again</a> or 
+    	<a href="!facebook"' . $html_class . '>sign in with Facebook again</a> or 
       <a href="!register">through the standard username/password registration</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.');
@@ -51,11 +62,42 @@
     if (empty($destination)) {
       $destination = isset($_REQUEST['destination']) ? $_REQUEST['destination'] : '<front>';
     }
+    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.
   return $error_message;
+}
+
+/**
+ * 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>";
 }
 
 /**
@@ -432,7 +474,17 @@
     'code' => $code,
   );
   $token_url = url('https://graph.facebook.com/v2.2/oauth/access_token', array('absolute' => TRUE, 'query' => $query));
+
+   $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)');
@@ -910,7 +962,7 @@
   // 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);
diff --git a/includes/fboauth.pages.inc b/includes/fboauth.pages.inc
index 10e9f96..10a285a 100755
--- a/includes/fboauth.pages.inc
+++ b/includes/fboauth.pages.inc
@@ -28,6 +28,25 @@
     '#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_anon_connect'] = array(
     '#type' => 'checkbox',
     '#title' => t('Allow anonymous users to connect an existing unconnected drupal account to their Facebook account?'),
@@ -132,6 +151,15 @@
   // Remove trailing spaces from keys.
   $form_state['values']['fboauth_id'] = trim($form_state['values']['fboauth_id']);
   $form_state['values']['fboauth_secret'] = trim($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);
 
   // Do some basic data input validation.
   if (!is_numeric($form_state['values']['fboauth_id']) || strlen($form_state['values']['fboauth_id']) > 20) {