test fixes, I feel it's caching issue
[civicrm-core.git] / js / Common.js
index b34348d89fa6780051bf3c087e0579dc7f901914..70b02c2c8390eb6c2bf78dd137af9ee14327a146 100644 (file)
@@ -1,45 +1,14 @@
-/*
- +--------------------------------------------------------------------+
- | CiviCRM version 4.4                                                |
- +--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2013                                |
- +--------------------------------------------------------------------+
- | This file is a part of CiviCRM.                                    |
- |                                                                    |
- | CiviCRM is free software; you can copy, modify, and distribute it  |
- | under the terms of the GNU Affero General Public License           |
- | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
- |                                                                    |
- | CiviCRM is distributed in the hope that it will be useful, but     |
- | WITHOUT ANY WARRANTY; without even the implied warranty of         |
- | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
- | See the GNU Affero General Public License for more details.        |
- |                                                                    |
- | You should have received a copy of the GNU Affero General Public   |
- | License and the CiviCRM Licensing Exception along                  |
- | with this program; if not, contact CiviCRM LLC                     |
- | at info[AT]civicrm[DOT]org. If you have questions about the        |
- | GNU Affero General Public License or the licensing of CiviCRM,     |
- | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
- +--------------------------------------------------------------------+
- */
-
-/**
- * @file: global functions for CiviCRM
- * FIXME: We are moving away from using global functions. DO NOT ADD MORE.
- * @see CRM object - the better alternative to adding global functions
- */
-
+// https://civicrm.org/licensing
 var CRM = CRM || {};
 var cj = jQuery;
 
 /**
  * Short-named function for string translation, defined in global scope so it's available everywhere.
  *
- * @param  $text   string  string for translating
- * @param  $params object  key:value of additional parameters
+ * @param text string for translating
+ * @param params object key:value of additional parameters
  *
- * @return         string  the translated string
+ * @return string
  */
 function ts(text, params) {
   "use strict";
@@ -62,11 +31,10 @@ function ts(text, params) {
  *  a list of 'blocks to show' and 'blocks to hide' and the template passes these parameters to
  *  this function.
  *
- * @access public
+ * @deprecated
  * @param  showBlocks Array of element Id's to be displayed
  * @param  hideBlocks Array of element Id's to be hidden
  * @param elementType Value to set display style to for showBlocks (e.g. 'block' or 'table-row' or ...)
- * @return none
  */
 function on_load_init_blocks(showBlocks, hideBlocks, elementType) {
   if (elementType == null) {
@@ -102,14 +70,13 @@ function on_load_init_blocks(showBlocks, hideBlocks, elementType) {
  *  This function is called when we need to show or hide a related form element (target_element)
  *  based on the value (trigger_value) of another form field (trigger_field).
  *
- * @access public
+ * @deprecated
  * @param  trigger_field_id     HTML id of field whose onchange is the trigger
  * @param  trigger_value        List of integers - option value(s) which trigger show-element action for target_field
  * @param  target_element_id    HTML id of element to be shown or hidden
  * @param  target_element_type  Type of element to be shown or hidden ('block' or 'table-row')
  * @param  field_type           Type of element radio/select
  * @param  invert               Boolean - if true, we HIDE target on value match; if false, we SHOW target on value match
- * @return none
  */
 function showHideByValue(trigger_field_id, trigger_value, target_element_id, target_element_type, field_type, invert) {
   if (target_element_type == null) {
@@ -173,11 +140,11 @@ function showHideByValue(trigger_field_id, trigger_value, target_element_id, tar
 
 /**
  * Function to change button text and disable one it is clicked
- *
+ * @deprecated
  * @param obj object - the button clicked
  * @param formID string - the id of the form being submitted
  * @param string procText - button text after user clicks it
- * @return null
+ * @return bool
  */
 var submitcount = 0;
 /* Changes button label on submit, and disables button after submit for newer browsers.
@@ -203,7 +170,9 @@ function submitOnce(obj, formId, procText) {
     }
   }
 }
-
+/**
+ * @deprecated
+ */
 function popUp(URL) {
   day = new Date();
   id = day.getTime();
@@ -212,8 +181,8 @@ function popUp(URL) {
 
 /**
  * Function to show / hide the row in optionFields
- *
- * @param element name index, that whose innerHTML is to hide else will show the hidden row.
+ * @deprecated
+ * @param index string, element whose innerHTML is to hide else will show the hidden row.
  */
 function showHideRow(index) {
   if (index) {
@@ -266,17 +235,16 @@ CRM.validate = CRM.validate || {
         val = [val];
       }
       $elect.find('option' + opts).remove();
-      $.each(options, function(key, option) {
+      _.each(options, function(option) {
         var selected = ($.inArray(''+option.key, val) > -1) ? 'selected="selected"' : '';
         $elect.append('<option value="' + option.key + '"' + selected + '>' + option.value + '</option>');
       });
-      $elect.trigger('crmOptionsUpdated').trigger('change');
+      $elect.trigger('crmOptionsUpdated', $.extend({}, options)).trigger('change');
     });
   };
 
   /**
-   * Select2 api leaves something to be desired. To alter options on-the-fly often requires re-rendering the whole thing.
-   * So making this function public in case anyone needs it.
+   * Wrapper for select2 initialization function; supplies defaults
    * @param options object
    */
   $.fn.crmSelect2 = function(options) {
@@ -301,7 +269,7 @@ CRM.validate = CRM.validate || {
   };
 
   /**
-   * Initialize a select2 autocomplete using the getlist api
+   * @see CRM_Core_Form::addEntityRef for docs
    * @param options object
    */
   $.fn.crmEntityRef = function(options) {
@@ -315,6 +283,7 @@ CRM.validate = CRM.validate || {
       $el.data('api-entity', entity);
       $el.data('select-params', $.extend({}, $el.data('select-params') || {}, options.select));
       $el.data('api-params', $.extend({}, $el.data('api-params') || {}, options.api));
+      $el.data('create-links', options.create || $el.data('create-links'));
       $el.addClass('crm-ajax-select crm-' + entity + '-ref');
       var settings = {
         // Use select2 ajax helper instead of CRM.api because it provides more value
@@ -335,7 +304,7 @@ CRM.validate = CRM.validate || {
           }
         },
         minimumInputLength: 1,
-        formatResult: CRM.utils.formatSelect2Result,
+        formatResult: formatSelect2Result,
         formatSelection: function(row) {
           return row.label;
         },
@@ -352,8 +321,7 @@ CRM.validate = CRM.validate || {
           if (!_.xor(val.split(','), _.pluck(stored, 'id')).length) {
             callback(multiple ? stored : stored[0]);
           } else {
-            var params = $el.data('api-params') || {};
-            params.id = val;
+            var params = $.extend({}, $el.data('api-params') || {}, {id: val});
             CRM.api3($el.data('api-entity'), 'getlist', params).done(function(result) {
               callback(multiple ? result.values : result.values[0])
             });
@@ -363,14 +331,14 @@ CRM.validate = CRM.validate || {
       if ($el.data('create-links')) {
         selectParams.formatInputTooShort = function() {
           var txt = $el.data('select-params').formatInputTooShort || $.fn.select2.defaults.formatInputTooShort.call(this);
-          if ($el.data('create-links').length) {
-            txt += ' ' + ts('or') + '<br />' + CRM.utils.formatSelect2CreateLinks($el);
+          if ($el.data('create-links')) {
+            txt += ' ' + ts('or') + '<br />' + formatSelect2CreateLinks($el);
           }
           return txt;
         };
         selectParams.formatNoMatches = function() {
           var txt = $el.data('select-params').formatNoMatches || $.fn.select2.defaults.formatNoMatches;
-          return txt + '<br />' + CRM.utils.formatSelect2CreateLinks($el);
+          return txt + '<br />' + formatSelect2CreateLinks($el);
         };
         $el.off('.createLinks').on('select2-open.createLinks', function() {
           var $el = $(this);
@@ -397,7 +365,7 @@ CRM.validate = CRM.validate || {
     });
   };
 
-  CRM.utils.formatSelect2Result = function(row) {
+  function formatSelect2Result(row) {
     var markup = '<div class="crm-select2-row">';
     if (row.image !== undefined) {
       markup += '<div class="crm-select2-image"><img src="' + row.image + '"/></div>';
@@ -412,40 +380,60 @@ CRM.validate = CRM.validate || {
     });
     markup += '</div></div></div>';
     return markup;
-  };
-  
-  CRM.utils.formatSelect2CreateLinks = function($el) {
+  }
+
+  function formatSelect2CreateLinks($el) {
+    var
+      createLinks = $el.data('create-links'),
+      api = $el.data('api-params') || {},
+      type = api.params ? api.params.contact_type : null;
+    if (createLinks === true) {
+      createLinks = type ? _.where(CRM.profile.contactCreate, {type: type}) : CRM.profile.contactCreate;
+    }
     var markup = '';
-    $.each($el.data('create-links'), function(k, link) {
+    _.each(createLinks, function(link) {
       markup += ' <a class="crm-add-entity crm-hover-button" href="' + link.url + '">';
-      if (link.name) {
-        markup += '<span class="icon ' + link.name + '-icon"></span> ';
+      if (link.type) {
+        markup += '<span class="icon ' + link.type + '-profile-icon"></span> ';
       }
       markup += link.label + '</a>';
     });
     return markup;
-  };
+  }
 
   // Initialize widgets
-  $(document).on('crmLoad', function(e) {
-    $('table.row-highlight', e.target)
-      .off('.rowHighlight')
-      .on('change.rowHighlight', 'input.select-row, input.select-rows', function () {
-        var target, table = $(this).closest('table');
-        if ($(this).hasClass('select-rows')) {
-          target = $('tbody tr', table);
-          $('input.select-row', table).prop('checked', $(this).prop('checked'));
-        }
-        else {
-          target = $(this).closest('tr');
-          $('input.select-rows', table).prop('checked', $(".select-row:not(':checked')", table).length < 1);
-        }
-        target.toggleClass('crm-row-selected', $(this).is(':checked'));
-      })
-      .find('input.select-row:checked').parents('tr').addClass('crm-row-selected');
-    $('.crm-select2:not(.select2-offscreen)', e.target).crmSelect2();
-    $('.crm-form-entityref:not(.select2-offscreen)', e.target).crmEntityRef();
-  });
+  $(document)
+    .on('crmLoad', function(e) {
+      $('table.row-highlight', e.target)
+        .off('.rowHighlight')
+        .on('change.rowHighlight', 'input.select-row, input.select-rows', function () {
+          var target, table = $(this).closest('table');
+          if ($(this).hasClass('select-rows')) {
+            target = $('tbody tr', table);
+            $('input.select-row', table).prop('checked', $(this).prop('checked'));
+          }
+          else {
+            target = $(this).closest('tr');
+            $('input.select-rows', table).prop('checked', $(".select-row:not(':checked')", table).length < 1);
+          }
+          target.toggleClass('crm-row-selected', $(this).is(':checked'));
+        })
+        .find('input.select-row:checked').parents('tr').addClass('crm-row-selected');
+      $('.crm-select2:not(.select2-offscreen)', e.target).crmSelect2();
+      $('.crm-form-entityref:not(.select2-offscreen)', e.target).crmEntityRef();
+    })
+    // Modal dialogs should disable scrollbars
+    .on('dialogopen', function(e) {
+      if ($(e.target).dialog('option', 'modal')) {
+        $(e.target).addClass('modal-dialog');
+        $('body').css({overflow: 'hidden'});
+      }
+    })
+    .on('dialogclose', function(e) {
+      if ($('.ui-dialog .modal-dialog').not(e.target).length < 1) {
+        $('body').css({overflow: ''});
+      }
+    });
 
   /**
    * Function to make multiselect boxes behave as fields in small screens
@@ -881,10 +869,7 @@ CRM.validate = CRM.validate || {
       settings.dialog = {
         modal: true,
         width: '65%',
-        height: parseInt($(window).height() * .75),
-        close: function() {
-          $(this).dialog('destroy').remove();
-        }
+        height: parseInt($(window).height() * .75)
       };
     }
     options && $.extend(true, settings, options);
@@ -892,10 +877,15 @@ CRM.validate = CRM.validate || {
     // Create new dialog
     if (settings.dialog) {
       $('<div id="'+ settings.target.substring(1) +'"><div class="crm-loading-element">' + ts('Loading') + '...</div></div>').dialog(settings.dialog);
+      $(settings.target).on('dialogclose', function() {
+        $(this).dialog('destroy').remove();
+      });
     }
     if (settings.dialog && !settings.dialog.title) {
-      $(settings.target).on('crmLoad', function(event, data) {
-        data.title && $(this).dialog('option', 'title', data.title);
+      $(settings.target).on('crmLoad', function(e, data) {
+        if (e.target === $(settings.target)[0] && data && data.title) {
+          $(this).dialog('option', 'title', data.title);
+        }
       });
     }
     $(settings.target).crmSnippet(settings).crmSnippet('refresh');
@@ -1063,17 +1053,23 @@ CRM.validate = CRM.validate || {
       })
 
       .on('click', 'a.crm-option-edit-link', function() {
-        var link = $(this);
+        var
+          link = $(this),
+          optionsChanged = false;
         CRM.loadForm(this.href, {openInline: 'a:not("[href=#], .no-popup")'})
-          // Lots of things can happen once the form opens, this is the only event we can really rely on
+          .on('crmFormSuccess', function() {
+            optionsChanged = true;
+          })
           .on('dialogclose', function() {
-            link.trigger('crmOptionsEdited');
-            var $elects = $('select[data-option-edit-path="' + link.data('option-edit-path') + '"]');
-            if ($elects.data('api-entity') && $elects.data('api-field')) {
-              CRM.api3($elects.data('api-entity'), 'getoptions', {sequential: 1, field: $elects.data('api-field')})
-                .done(function(data) {
-                  CRM.utils.setOptions($elects, data.values);
-                });
+            if (optionsChanged) {
+              link.trigger('crmOptionsEdited');
+              var $elects = $('select[data-option-edit-path="' + link.data('option-edit-path') + '"]');
+              if ($elects.data('api-entity') && $elects.data('api-field')) {
+                CRM.api3($elects.data('api-entity'), 'getoptions', {sequential: 1, field: $elects.data('api-field')})
+                  .done(function (data) {
+                    CRM.utils.setOptions($elects, data.values);
+                  });
+              }
             }
           });
         return false;