From d042503cd1b09247effd1f436d9119fc770862c5 Mon Sep 17 00:00:00 2001
From: Chris Hallberg <crhallberg@gmail.com>
Date: Fri, 4 Apr 2014 10:42:47 -0400
Subject: [PATCH] Account creation in lightbox. - Some related refactoring/bug
 fixes - Resolves VUFIND-960

---
 themes/bootstrap/js/cart.js                   |  13 ++
 themes/bootstrap/js/common.js                 | 145 ++++++++----------
 themes/bootstrap/js/lightbox.js               |  43 ++++++
 .../templates/Auth/AbstractBase/login.phtml   |   2 +-
 4 files changed, 118 insertions(+), 85 deletions(-)

diff --git a/themes/bootstrap/js/cart.js b/themes/bootstrap/js/cart.js
index 23c61e7afc8..3bf9fa3aa0f 100644
--- a/themes/bootstrap/js/cart.js
+++ b/themes/bootstrap/js/cart.js
@@ -147,7 +147,9 @@ function registerUpdateCart($form) {
 }
 
 // Ajax cart submission for the lightbox
+var lastCartSubmit = false;
 function cartSubmit($form) {
+  lastCartSubmit = $form;
   var submit = $form.find('input[type="submit"][clicked=true]').attr('name');
   if (submit == 'print') {
     //redirect page
@@ -193,6 +195,17 @@ $(document).ready(function() {
   $('#cartItems').click(function() {
     return Lightbox.get('Cart','Cart');
   });
+  // Overwrite 
+  Lightbox.addFormCallback('accountForm', function() {
+    updatePageForLogin();
+    if (lastCartSubmit !== false) {
+      cartSubmit(lastCartSubmit);
+      lastCartSubmit = false;
+    } else {
+      Lightbox.getByUrl(Lightbox.openingURL);
+      Lightbox.openingURL = false;
+    }
+  });
   Lightbox.addFormHandler('cartForm', function(evt) {
     cartSubmit($(evt.target));
     return false;
diff --git a/themes/bootstrap/js/common.js b/themes/bootstrap/js/common.js
index f12a3570123..6ede06761b4 100644
--- a/themes/bootstrap/js/common.js
+++ b/themes/bootstrap/js/common.js
@@ -77,6 +77,10 @@ function registerLightboxEvents() {
     get['id'] = 'NEW';
     return Lightbox.get('MyResearch', 'EditList', get);
   });
+  // New account link handler
+  $('.createAccountLink').click(function() {
+    return Lightbox.get('MyResearch', 'Account');
+  });
   // Select all checkboxes
   $(modal).find('.checkbox-select-all').change(function() {
     $(this).closest('.modal-body').find('.checkbox-select-item').attr('checked', this.checked);
@@ -89,7 +93,6 @@ function registerLightboxEvents() {
   // Highlight which submit button clicked
   $(modal).find("form input[type=submit]").click(function() {
     // Abort requests triggered by the lightbox
-    if(Lightbox.XHR) { Lightbox.XHR.abort(); }
     $('#modal .icon-spinner').remove();
     // Add useful information
     $(this).attr("clicked", "true");
@@ -106,42 +109,7 @@ function registerLightboxEvents() {
       $(op).hide();
     }
   });
-}
-/**
- * This function adds submission events to forms loaded inside the lightbox
- *
- * First, it will check for custom handlers, for those who want to handle everything.
- *
- * Then, it will check for custom form callbacks. These will be added to an anonymous
- * function that will call Lightbox.submit with the form and the callback.
- *
- * Finally, if nothing custom is setup, it will add the default function which
- * calls Lightbox.submit with a callback to close if there are no errors to display.
- *
- * This is a default open action, so it runs every time changeContent
- * is called and the 'shown' lightbox event is triggered
- */
-function registerLightboxForms() {
-  var form = $("#modal").find('form');
-  var name = $(form).attr('name');
-  // Assign form handler based on name
-  if(typeof name !== "undefined" && typeof Lightbox.formHandlers[name] !== "undefined") {
-    $(form).unbind('submit').submit(Lightbox.formHandlers[name]);
-  // Default action, with custom callback
-  } else if(typeof Lightbox.formCallbacks[name] !== "undefined") {
-    $(form).unbind('submit').submit(function(evt){
-      Lightbox.submit($(evt.target), Lightbox.formCallbacks[name]);
-      return false;
-    });
-  // Default
-  } else {
-    $(form).unbind('submit').submit(function(evt){
-      Lightbox.submit($(evt.target), function(html){
-        Lightbox.checkForError(html, Lightbox.close);
-      });
-      return false;
-    });
-  }
+  $('#modal .collapse').on('hidden', function(e){ e.stopPropagation(); });
 }
 /**
  * This is a full handler for the login form
@@ -167,10 +135,10 @@ function ajaxLogin(form) {
 
         // get any other form values
         for (var i = 0; i < form.length; i++) {
-            if (form.elements[i].name == 'password') {
-                continue;
-            }
-            params[form.elements[i].name] = form.elements[i].value;
+          if (form.elements[i].name == 'password') {
+            continue;
+          }
+          params[form.elements[i].name] = form.elements[i].value;
         }
 
         // login via ajax
@@ -181,48 +149,7 @@ function ajaxLogin(form) {
           data: params,
           success: function(response) {
             if (response.status == 'OK') {
-              // Hide "log in" options and show "log out" options:
-              $('#loginOptions').hide();
-              $('.logoutOptions').show();
-              
-              var recordId = $('#record_id').val();
-
-              // Update user save statuses if the current context calls for it:
-              if (typeof(checkSaveStatuses) == 'function') {
-                checkSaveStatuses();
-              }
-
-              // refresh the comment list so the "Delete" links will show
-              $('.commentList').each(function(){
-                var recordSource = extractSource($('#record'));
-                refreshCommentList(recordId, recordSource);
-              });
-              
-              var summon = false;
-              $('.hiddenSource').each(function(i, e) {
-                if(e.value == 'Summon') {
-                  summon = true;
-                  // If summon, queue reload for when we close
-                  Lightbox.addCloseAction(function(){document.location.reload(true);});
-                }
-              });
-              
-              // Refresh tab content
-              var recordTabs = $('.recordTabs');
-              if(!summon && recordTabs.length > 0) { // If summon, skip: about to reload anyway
-                var tab = recordTabs.find('.active a').attr('id');
-                $.ajax({ // Shouldn't be cancelled, not assigned to XHR
-                  type:'POST',
-                  url:path+'/AJAX/JSON?method=get&submodule=Record&subaction=AjaxTab&id='+recordId,
-                  data:{tab:tab},
-                  success:function(html) {
-                    recordTabs.next('.tab-container').html(html);
-                  },
-                  error:function(d,e) {
-                    console.log(d,e); // Error reporting
-                  }
-                });
-              }
+              updatePageForLogin();
               // and we update the modal
               if(Lightbox.lastPOST && Lightbox.lastPOST['loggingin']) {
                 Lightbox.close();
@@ -245,6 +172,52 @@ function ajaxLogin(form) {
   });
 }
 
+function updatePageForLogin()
+{
+  // Hide "log in" options and show "log out" options:
+  $('#loginOptions').hide();
+  $('.logoutOptions').show();
+  
+  var recordId = $('#record_id').val();
+
+  // Update user save statuses if the current context calls for it:
+  if (typeof(checkSaveStatuses) == 'function') {
+    checkSaveStatuses();
+  }
+
+  // refresh the comment list so the "Delete" links will show
+  $('.commentList').each(function(){
+    var recordSource = extractSource($('#record'));
+    refreshCommentList(recordId, recordSource);
+  });
+  
+  var summon = false;
+  $('.hiddenSource').each(function(i, e) {
+    if(e.value == 'Summon') {
+      summon = true;
+      // If summon, queue reload for when we close
+      Lightbox.addCloseAction(function(){document.location.reload(true);});
+    }
+  });
+  
+  // Refresh tab content
+  var recordTabs = $('.recordTabs');
+  if(!summon && recordTabs.length > 0) { // If summon, skip: about to reload anyway
+    var tab = recordTabs.find('.active a').attr('id');
+    $.ajax({ // Shouldn't be cancelled, not assigned to XHR
+      type:'POST',
+      url:path+'/AJAX/JSON?method=get&submodule=Record&subaction=AjaxTab&id='+recordId,
+      data:{tab:tab},
+      success:function(html) {
+        recordTabs.next('.tab-container').html(html);
+      },
+      error:function(d,e) {
+        console.log(d,e); // Error reporting
+      }
+    });
+  }
+}
+
 /* --- BOOTSTRAP LIBRARY TWEAKS --- */
 // Prevent typeahead highlighting
 $.fn.typeahead.Constructor.prototype.render = function(items) {
@@ -373,12 +346,16 @@ $(document).ready(function() {
    * LIGHTBOX DEFAULT BEHAVIOUR *
    ******************************/
   Lightbox.addOpenAction(registerLightboxEvents);
-  Lightbox.addOpenAction(registerLightboxForms);
   Lightbox.addFormCallback('newList', Lightbox.changeContent);
   Lightbox.addFormHandler('loginForm', function(evt) {
     ajaxLogin(evt.target);
     return false;
   });
+  Lightbox.addFormCallback('accountForm', function() {
+    updatePageForLogin();
+    Lightbox.getByUrl(Lightbox.openingURL);
+    Lightbox.openingURL = false;
+  });
   
   // Help links
   $('.help-link').click(function() {
diff --git a/themes/bootstrap/js/lightbox.js b/themes/bootstrap/js/lightbox.js
index a7971d49d50..61c7a447312 100644
--- a/themes/bootstrap/js/lightbox.js
+++ b/themes/bootstrap/js/lightbox.js
@@ -8,6 +8,7 @@ var Lightbox = {
    */
   lastURL: false,
   lastPOST: false,
+  openingURL: false,
   shown: false,      // Is the lightbox deployed?
   XHR: false,        // Used for current in-progress XHR lightbox request
   openStack: [],     // Array of functions to be called after changeContent or the lightbox event 'shown'
@@ -113,6 +114,7 @@ var Lightbox = {
    */
   closeActions: function() {
     Lightbox.shown = false;
+    Lightbox.openingURL = false;
     // Clean out stack
     while(Lightbox.closeStack.length > 0) {
       var f = Lightbox.closeStack.pop();
@@ -230,6 +232,9 @@ var Lightbox = {
       }
     });
     // Store current "page" context for empty targets
+    if(this.openingURL === false) {
+      this.openingURL = url;
+    }
     this.lastURL = url;
     this.lastPOST = post;
     //this.openActions();
@@ -298,6 +303,42 @@ var Lightbox = {
     }
     return data;
   },
+  /**
+   * This function adds submission events to forms loaded inside the lightbox
+   *
+   * First, it will check for custom handlers, for those who want to handle everything.
+   *
+   * Then, it will check for custom form callbacks. These will be added to an anonymous
+   * function that will call Lightbox.submit with the form and the callback.
+   *
+   * Finally, if nothing custom is setup, it will add the default function which
+   * calls Lightbox.submit with a callback to close if there are no errors to display.
+   *
+   * This is a default open action, so it runs every time changeContent
+   * is called and the 'shown' lightbox event is triggered
+   */
+  registerForms: function() {
+    var form = $("#modal").find('form');
+    var name = $(form).attr('name');
+    // Assign form handler based on name
+    if(typeof name !== "undefined" && typeof Lightbox.formHandlers[name] !== "undefined") {
+      $(form).unbind('submit').submit(Lightbox.formHandlers[name]);
+    // Default action, with custom callback
+    } else if(typeof Lightbox.formCallbacks[name] !== "undefined") {
+      $(form).unbind('submit').submit(function(evt){
+        Lightbox.submit($(evt.target), Lightbox.formCallbacks[name]);
+        return false;
+      });
+    // Default
+    } else {
+      $(form).unbind('submit').submit(function(evt){
+        Lightbox.submit($(evt.target), function(html){
+          Lightbox.checkForError(html, Lightbox.close);
+        });
+        return false;
+      });
+    }
+  },
   /**
    * The default, automatic form submission
    *
@@ -344,6 +385,8 @@ var Lightbox = {
  * We do it here so that non-JS users still have a good time.
  */
 $(document).ready(function() {
+  // Add handlers to the forms
+  Lightbox.addOpenAction(Lightbox.registerForms);
   /**
    * Hook into the Bootstrap close event
    *
diff --git a/themes/bootstrap/templates/Auth/AbstractBase/login.phtml b/themes/bootstrap/templates/Auth/AbstractBase/login.phtml
index 0d6ff932a77..1bee344cd83 100644
--- a/themes/bootstrap/templates/Auth/AbstractBase/login.phtml
+++ b/themes/bootstrap/templates/Auth/AbstractBase/login.phtml
@@ -8,7 +8,7 @@
       <div class="controls">
         <input class="btn btn-primary" type="submit" name="processLogin" value="Login">
         <? if ($account->supportsCreation()): ?>
-          <a class="btn btn-link" href="<?=$this->url('myresearch-account') ?>"><?=$this->transEsc('Create New Account')?></a>
+          <a class="btn btn-link createAccountLink" href="<?=$this->url('myresearch-account') ?>"><?=$this->transEsc('Create New Account')?></a>
         <? endif; ?>
       </div>
     </div>
-- 
GitLab