1 // https://civicrm.org/licensing
3 var cj
= CRM
.$ = jQuery
;
7 * Short-named function for string translation, defined in global scope so it's available everywhere.
9 * @param text string for translating
10 * @param params object key:value of additional parameters
14 function ts(text
, params
) {
16 text
= CRM
.strings
[text
] || text
;
17 if (typeof(params
) === 'object') {
18 for (var i
in params
) {
19 if (typeof(params
[i
]) === 'string' || typeof(params
[i
]) === 'number') {
20 // sprintf emulation: escape % characters in the replacements to avoid conflicts
21 text
= text
.replace(new RegExp('%' + i
, 'g'), String(params
[i
]).replace(/%/g
, '%-crmescaped-'));
24 return text
.replace(/%-crmescaped-/g, '%');
30 * This function is called by default at the bottom of template files which have forms that have
31 * conditionally displayed/hidden sections and elements. The PHP is responsible for generating
32 * a list of 'blocks to show' and 'blocks to hide' and the template passes these parameters to
36 * @param showBlocks Array of element Id's to be displayed
37 * @param hideBlocks Array of element Id's to be hidden
38 * @param elementType Value to set display style to for showBlocks (e.g. 'block' or 'table-row' or ...)
40 function on_load_init_blocks(showBlocks
, hideBlocks
, elementType
) {
41 if (elementType
== null) {
42 elementType
= 'block';
47 /* This loop is used to display the blocks whose IDs are present within the showBlocks array */
48 for (i
= 0; i
< showBlocks
.length
; i
++) {
49 myElement
= document
.getElementById(showBlocks
[i
]);
50 /* getElementById returns null if element id doesn't exist in the document */
51 if (myElement
!= null) {
52 myElement
.style
.display
= elementType
;
55 alert('showBlocks array item not in .tpl = ' + showBlocks
[i
]);
59 /* This loop is used to hide the blocks whose IDs are present within the hideBlocks array */
60 for (i
= 0; i
< hideBlocks
.length
; i
++) {
61 myElement
= document
.getElementById(hideBlocks
[i
]);
62 /* getElementById returns null if element id doesn't exist in the document */
63 if (myElement
!= null) {
64 myElement
.style
.display
= 'none';
67 alert('showBlocks array item not in .tpl = ' + hideBlocks
[i
]);
73 * This function is called when we need to show or hide a related form element (target_element)
74 * based on the value (trigger_value) of another form field (trigger_field).
77 * @param trigger_field_id HTML id of field whose onchange is the trigger
78 * @param trigger_value List of integers - option value(s) which trigger show-element action for target_field
79 * @param target_element_id HTML id of element to be shown or hidden
80 * @param target_element_type Type of element to be shown or hidden ('block' or 'table-row')
81 * @param field_type Type of element radio/select
82 * @param invert Boolean - if true, we HIDE target on value match; if false, we SHOW target on value match
84 function showHideByValue(trigger_field_id
, trigger_value
, target_element_id
, target_element_type
, field_type
, invert
) {
87 if (field_type
== 'select') {
88 var trigger
= trigger_value
.split("|");
89 var selectedOptionValue
= cj('#' + trigger_field_id
).val();
91 target
= target_element_id
.split("|");
92 for (j
= 0; j
< target
.length
; j
++) {
94 cj('#' + target
[j
]).show();
97 cj('#' + target
[j
]).hide();
99 for (var i
= 0; i
< trigger
.length
; i
++) {
100 if (selectedOptionValue
== trigger
[i
]) {
102 cj('#' + target
[j
]).hide();
105 cj('#' + target
[j
]).show();
113 if (field_type
== 'radio') {
114 target
= target_element_id
.split("|");
115 for (j
= 0; j
< target
.length
; j
++) {
116 if (cj('[name="' + trigger_field_id
+ '"]:first').is(':checked')) {
118 cj('#' + target
[j
]).hide();
121 cj('#' + target
[j
]).show();
126 cj('#' + target
[j
]).show();
129 cj('#' + target
[j
]).hide();
138 * Function to change button text and disable one it is clicked
140 * @param obj object - the button clicked
141 * @param formID string - the id of the form being submitted
142 * @param string procText - button text after user clicks it
146 /* Changes button label on submit, and disables button after submit for newer browsers.
147 Puts up alert for older browsers. */
148 function submitOnce(obj
, formId
, procText
) {
149 // if named button clicked, change text
150 if (obj
.value
!= null) {
151 obj
.value
= procText
+ " ...";
153 cj(obj
).closest('form').attr('data-warn-changes', 'false');
154 if (document
.getElementById
) { // disable submit button for newer browsers
156 document
.getElementById(formId
).submit();
159 else { // for older browsers
160 if (submitcount
== 0) {
165 alert("Your request is currently being processed ... Please wait.");
172 * Function to show / hide the row in optionFields
174 * @param index string, element whose innerHTML is to hide else will show the hidden row.
176 function showHideRow(index
) {
178 cj('tr#optionField_' + index
).hide();
179 if (cj('table#optionField tr:hidden:first').length
) {
180 cj('div#optionFieldLink').show();
184 cj('table#optionField tr:hidden:first').show();
185 if (!cj('table#optionField tr:hidden:last').length
) {
186 cj('div#optionFieldLink').hide();
192 CRM
.utils
= CRM
.utils
|| {};
193 CRM
.strings
= CRM
.strings
|| {};
195 (function ($, _
, undefined) {
198 // Theme classes for unattached elements
199 $.fn
.select2
.defaults
.dropdownCssClass
= $.ui
.dialog
.prototype.options
.dialogClass
= 'crm-container';
201 // https://github.com/ivaynberg/select2/pull/2090
202 $.fn
.select2
.defaults
.width
= 'resolve';
204 // Workaround for https://github.com/ivaynberg/select2/issues/1246
205 $.ui
.dialog
.prototype._allowInteraction = function(e
) {
206 return !!$(e
.target
).closest('.ui-dialog, .ui-datepicker, .select2-drop, .cke_dialog').length
;
210 * Populate a select list, overwriting the existing options except for the placeholder.
211 * @param select jquery selector - 1 or more select elements
212 * @param options array in format returned by api.getoptions
213 * @param placeholder string|bool - new placeholder or false (default) to keep the old one
214 * @param value string|array - will silently update the element with new value without triggering change
216 CRM
.utils
.setOptions = function(select
, options
, placeholder
, value
) {
217 $(select
).each(function() {
220 val
= value
|| $elect
.val() || [],
221 opts
= placeholder
|| placeholder
=== '' ? '' : '[value!=""]';
222 $elect
.find('option' + opts
).remove();
223 var newOptions
= CRM
.utils
.renderOptions(options
, val
);
224 if (typeof placeholder
=== 'string') {
225 if ($elect
.is('[multiple]')) {
226 select
.attr('placeholder', placeholder
);
228 newOptions
= '<option value="">' + placeholder
+ '</option>' + newOptions
;
231 $elect
.append(newOptions
);
233 $elect
.trigger('crmOptionsUpdated', $.extend({}, options
)).trigger('change');
239 * Render an option list
240 * @param options {array}
241 * @param val {string} default value
242 * @param escapeHtml {bool}
245 CRM
.utils
.renderOptions = function(options
, val
, escapeHtml
) {
247 esc
= escapeHtml
=== false ? _
.identity
: _
.escape
;
248 if (!$.isArray(val
)) {
251 _
.each(options
, function(option
) {
252 if (option
.children
) {
253 rendered
+= '<optgroup label="' + esc(option
.value
) + '">' +
254 CRM
.utils
.renderOptions(option
.children
, val
) +
257 var selected
= ($.inArray('' + option
.key
, val
) > -1) ? 'selected="selected"' : '';
258 rendered
+= '<option value="' + esc(option
.key
) + '"' + selected
+ '>' + esc(option
.value
) + '</option>';
264 function chainSelect() {
265 var $form
= $(this).closest('form'),
266 $target
= $('select[data-name="' + $(this).data('target') + '"]', $form
),
267 data
= $target
.data(),
269 $target
.prop('disabled', true);
270 if ($target
.is('select.crm-chain-select-control')) {
271 $('select[data-name="' + $target
.data('target') + '"]', $form
).prop('disabled', true).blur();
273 if (!(val
&& val
.length
)) {
274 CRM
.utils
.setOptions($target
.blur(), [], data
.emptyPrompt
);
276 $target
.addClass('loading');
277 $.getJSON(CRM
.url(data
.callback
), {_value
: val
}, function(vals
) {
278 $target
.prop('disabled', false).removeClass('loading');
279 CRM
.utils
.setOptions($target
, vals
|| [], (vals
&& vals
.length
? data
.selectPrompt
: data
.nonePrompt
));
285 * Compare Form Input values against cached initial value.
287 * @return {Boolean} true if changes have been made.
289 CRM
.utils
.initialValueChanged = function(el
) {
291 $(':input:visible, .select2-container:visible+:input.select2-offscreen', el
).not('[type=submit], [type=button], .crm-action-menu').each(function () {
292 var initialValue
= $(this).data('crm-initial-value');
293 // skip change of value for submit buttons
294 if (initialValue
!== undefined && !_
.isEqual(initialValue
, $(this).val())) {
302 * Wrapper for select2 initialization function; supplies defaults
303 * @param options object
305 $.fn
.crmSelect2 = function(options
) {
306 return $(this).each(function () {
309 settings
= {allowClear
: !$el
.hasClass('required')};
310 // quickform doesn't support optgroups so here's a hack :(
311 $('option[value^=crm_optgroup]', this).each(function () {
312 $(this).nextUntil('option[value^=crm_optgroup]').wrapAll('<optgroup label="' + $(this).text() + '" />');
316 // quickform does not support disabled option, so yet another hack to
317 // add disabled property for option values
318 $('option[value^=crm_disabled_opt]', this).attr('disabled', 'disabled');
320 // Defaults for single-selects
321 if ($el
.is('select:not([multiple])')) {
322 settings
.minimumResultsForSearch
= 10;
323 if ($('option:first', this).val() === '') {
324 settings
.placeholderOption
= 'first';
327 $.extend(settings
, $el
.data('select-params') || {}, options
|| {});
329 $el
.addClass('crm-ajax-select');
331 $el
.select2(settings
);
336 * @see CRM_Core_Form::addEntityRef for docs
337 * @param options object
339 $.fn
.crmEntityRef = function(options
) {
340 options
= options
|| {};
341 options
.select
= options
.select
|| {};
342 return $(this).each(function() {
344 $el
= $(this).off('.crmEntity'),
345 entity
= options
.entity
|| $el
.data('api-entity') || 'contact',
347 $el
.data('api-entity', entity
);
348 $el
.data('select-params', $.extend({}, $el
.data('select-params') || {}, options
.select
));
349 $el
.data('api-params', $.extend({}, $el
.data('api-params') || {}, options
.api
));
350 $el
.data('create-links', options
.create
|| $el
.data('create-links'));
351 $el
.addClass('crm-form-entityref crm-' + entity
.toLowerCase() + '-ref');
353 // Use select2 ajax helper instead of CRM.api3 because it provides more value
355 url
: CRM
.url('civicrm/ajax/rest'),
356 data: function (input
, page_num
) {
357 var params
= getEntityRefApiParams($el
);
358 params
.input
= input
;
359 params
.page_num
= page_num
;
361 entity
: $el
.data('api-entity'),
363 json
: JSON
.stringify(params
)
366 results: function(data
) {
367 return {more
: data
.more_results
, results
: data
.values
|| []};
370 minimumInputLength
: 1,
371 formatResult
: CRM
.utils
.formatSelect2Result
,
372 formatSelection: function(row
) {
375 escapeMarkup: function (m
) {return m
;},
376 initSelection: function($el
, callback
) {
378 multiple
= !!$el
.data('select-params').multiple
,
380 stored
= $el
.data('entity-value') || [];
384 // If we already have this data, just return it
385 if (!_
.xor(val
.split(','), _
.pluck(stored
, 'id')).length
) {
386 callback(multiple
? stored
: stored
[0]);
388 var params
= $.extend({}, $el
.data('api-params') || {}, {id
: val
});
389 CRM
.api3($el
.data('api-entity'), 'getlist', params
).done(function(result
) {
390 callback(multiple
? result
.values
: result
.values
[0]);
391 // Trigger change (store data to avoid an infinite loop of lookups)
392 $el
.data('entity-value', result
.values
).trigger('change');
397 // Create new items inline - works for tags
398 if ($el
.data('create-links') && entity
.toLowerCase() === 'tag') {
399 selectParams
.createSearchChoice = function(term
, data
) {
400 if (!_
.findKey(data
, {label
: term
})) {
401 return {id
: "0", term
: term
, label
: term
+ ' (' + ts('new tag') + ')'};
404 selectParams
.tokenSeparators
= [','];
405 selectParams
.createSearchChoicePosition
= 'bottom';
406 $el
.on('select2-selecting.crmEntity', function(e
) {
409 e
.object
.label
= e
.object
.term
;
410 CRM
.api3(entity
, 'create', $.extend({name
: e
.object
.term
}, $el
.data('api-params').params
|| {}))
411 .done(function(created
) {
413 val
= $el
.select2('val'),
414 data
= $el
.select2('data'),
415 item
= {id
: created
.id
, label
: e
.object
.term
};
417 $el
.select2('data', item
, true);
419 else if ($.isArray(val
) && $.inArray("0", val
) > -1) {
420 _
.remove(data
, {id
: "0"});
422 $el
.select2('data', data
, true);
429 selectParams
.formatInputTooShort = function() {
430 var txt
= $el
.data('select-params').formatInputTooShort
|| $.fn
.select2
.defaults
.formatInputTooShort
.call(this);
431 txt
+= renderEntityRefFilters($el
) + renderEntityRefCreateLinks($el
);
434 selectParams
.formatNoMatches = function() {
435 var txt
= $el
.data('select-params').formatNoMatches
|| $.fn
.select2
.defaults
.formatNoMatches
;
436 txt
+= renderEntityRefFilters($el
) + renderEntityRefCreateLinks($el
);
439 $el
.on('select2-open.crmEntity', function() {
441 loadEntityRefFilterOptions($el
);
444 .on('click.crmEntity', 'a.crm-add-entity', function(e
) {
445 $el
.select2('close');
446 CRM
.loadForm($(this).attr('href'), {
447 dialog
: {width
: 500, height
: 'auto'}
448 }).on('crmFormSuccess', function(e
, data
) {
449 if (data
.status
=== 'success' && data
.id
) {
450 CRM
.status(ts('%1 Created', {1: data
.label
}));
451 if ($el
.select2('container').hasClass('select2-container-multi')) {
452 var selection
= $el
.select2('data');
453 selection
.push(data
);
454 $el
.select2('data', selection
, true);
456 $el
.select2('data', data
, true);
462 .on('change.crmEntity', 'select.crm-entityref-filter-value', function() {
463 var filter
= $el
.data('user-filter') || {};
464 filter
.value
= $(this).val();
465 $(this).toggleClass('active', !!filter
.value
);
466 $el
.data('user-filter', filter
);
468 // Once a filter has been chosen, rerender create links and refocus the search box
469 $el
.select2('close');
473 .on('change.crmEntity', 'select.crm-entityref-filter-key', function() {
474 var filter
= $el
.data('user-filter') || {};
475 filter
.key
= $(this).val();
476 $(this).toggleClass('active', !!filter
.key
);
477 $el
.data('user-filter', filter
);
478 loadEntityRefFilterOptions($el
);
482 $el
.crmSelect2($.extend(settings
, $el
.data('select-params'), selectParams
));
487 * Combine api-params with user-filter
491 function getEntityRefApiParams($el
) {
493 params
= $.extend({params
: {}}, $el
.data('api-params') || {}),
494 // Prevent original data from being modified - $.extend and _.clone don't cut it, they pass nested objects by reference!
495 combined
= _
.cloneDeep(params
),
496 filter
= $.extend({}, $el
.data('user-filter') || {});
497 if (filter
.key
&& filter
.value
) {
498 // Special case for contact type/sub-type combo
499 if (filter
.key
=== 'contact_type' && (filter
.value
.indexOf('__') > 0)) {
500 combined
.params
.contact_type
= filter
.value
.split('__')[0];
501 combined
.params
.contact_sub_type
= filter
.value
.split('__')[1];
503 // Allow json-encoded api filters e.g. {"BETWEEN":[123,456]}
504 combined
.params
[filter
.key
] = filter
.value
.charAt(0) === '{' ? $.parseJSON(filter
.value
) : filter
.value
;
510 CRM
.utils
.formatSelect2Result = function (row
) {
511 var markup
= '<div class="crm-select2-row">';
512 if (row
.image
!== undefined) {
513 markup
+= '<div class="crm-select2-image"><img src="' + row
.image
+ '"/></div>';
515 else if (row
.icon_class
) {
516 markup
+= '<div class="crm-select2-icon"><div class="crm-icon ' + row
.icon_class
+ '-icon"></div></div>';
518 markup
+= '<div><div class="crm-select2-row-label '+(row
.label_class
|| '')+'">' + row
.label
+ '</div>';
519 markup
+= '<div class="crm-select2-row-description">';
520 $.each(row
.description
|| [], function(k
, text
) {
521 markup
+= '<p>' + text
+ '</p>';
523 markup
+= '</div></div></div>';
527 function renderEntityRefCreateLinks($el
) {
529 createLinks
= $el
.data('create-links'),
530 params
= getEntityRefApiParams($el
).params
,
531 markup
= '<div class="crm-entityref-links">';
532 if (!createLinks
|| $el
.data('api-entity').toLowerCase() !== 'contact') {
535 if (createLinks
=== true) {
536 createLinks
= params
.contact_type
? _
.where(CRM
.config
.entityRef
.contactCreate
, {type
: params
.contact_type
}) : CRM
.config
.entityRef
.contactCreate
;
538 _
.each(createLinks
, function(link
) {
539 markup
+= ' <a class="crm-add-entity crm-hover-button" href="' + link
.url
+ '">';
541 markup
+= '<span class="icon ' + link
.type
+ '-profile-icon"></span> ';
543 markup
+= link
.label
+ '</a>';
549 function getEntityRefFilters($el
) {
551 entity
= $el
.data('api-entity').toLowerCase(),
552 filters
= $.extend([], CRM
.config
.entityRef
.filters
[entity
] || []),
553 filter
= $el
.data('user-filter') || {},
554 params
= $.extend({params
: {}}, $el
.data('api-params') || {}).params
,
556 $.each(filters
, function() {
557 if (typeof params
[this.key
] === 'undefined') {
560 else if (this.key
== 'contact_type' && typeof params
.contact_sub_type
=== 'undefined') {
561 this.options
= _
.remove(this.options
, function(option
) {
562 return option
.key
.indexOf(params
.contact_type
+ '__') === 0;
570 function renderEntityRefFilters($el
) {
572 filters
= getEntityRefFilters($el
),
573 filter
= $el
.data('user-filter') || {},
574 filterSpec
= filter
.key
? _
.find(filters
, {key
: filter
.key
}) : null;
575 if (!filters
.length
) {
578 var markup
= '<div class="crm-entityref-filters">' +
579 '<select class="crm-entityref-filter-key' + (filter
.key
? ' active' : '') + '">' +
580 '<option value="">' + ts('Refine search...') + '</option>' +
581 CRM
.utils
.renderOptions(filters
, filter
.key
) +
582 '</select> ' +
583 '<select class="crm-entityref-filter-value' + (filter
.key
? ' active"' : '"') + (filter
.key
? '' : ' style="display:none;"') + '>' +
584 '<option value="">' + ts('- select -') + '</option>';
585 if (filterSpec
&& filterSpec
.options
) {
586 markup
+= CRM
.utils
.renderOptions(filterSpec
.options
, filter
.value
);
588 markup
+= '</select></div>';
593 * Fetch options for a filter (via ajax if necessary) and populate the appropriate select list
596 function loadEntityRefFilterOptions($el
) {
598 filters
= getEntityRefFilters($el
),
599 filter
= $el
.data('user-filter') || {},
600 filterSpec
= filter
.key
? _
.find(filters
, {key
: filter
.key
}) : null,
601 $valField
= $('.crm-entityref-filter-value', '#select2-drop');
603 $valField
.show().val('');
604 if (filterSpec
.options
) {
605 CRM
.utils
.setOptions($valField
, filterSpec
.options
, false, filter
.value
);
607 $valField
.prop('disabled', true);
608 CRM
.api3(filterSpec
.entity
|| $el
.data('api-entity'), 'getoptions', {field
: filter
.key
, context
: 'search', sequential
: 1})
609 .done(function(result
) {
610 var entity
= $el
.data('api-entity').toLowerCase(),
611 globalFilterSpec
= _
.find(CRM
.config
.entityRef
.filters
[entity
], {key
: filter
.key
}) || {};
612 // Store options globally so we don't have to look them up again
613 globalFilterSpec
.options
= result
.values
;
614 $valField
.prop('disabled', false);
615 CRM
.utils
.setOptions($valField
, result
.values
);
616 $valField
.val(filter
.value
|| '');
624 //CRM-15598 - Override url validator method to allow relative url's (e.g. /index.htm)
625 $.validator
.addMethod("url", function(value
, element
) {
626 if (/^\//.test(value
)) {
627 // Relative url: prepend dummy path for validation.
628 value
= 'http://domain.tld' + value
;
630 // From jQuery Validation Plugin v1.12.0
631 return this.optional(element
) || /^(https?|s?ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value
);
635 * Wrapper for jQuery validate initialization function; supplies defaults
637 $.fn
.crmValidate = function(params
) {
638 return $(this).each(function () {
640 settings
= $.extend({}, CRM
.validate
._defaults
, CRM
.validate
.params
);
641 $(this).validate(settings
);
642 // Call any post-initialization callbacks
643 if (CRM
.validate
.functions
&& CRM
.validate
.functions
.length
) {
644 $.each(CRM
.validate
.functions
, function(i
, func
) {
651 // Initialize widgets
653 .on('crmLoad', function(e
) {
654 $('table.row-highlight', e
.target
)
655 .off('.rowHighlight')
656 .on('change.rowHighlight', 'input.select-row, input.select-rows', function (e
, data
) {
657 var filter
, $table
= $(this).closest('table');
658 if ($(this).hasClass('select-rows')) {
659 filter
= $(this).prop('checked') ? ':not(:checked)' : ':checked';
660 $('input.select-row' + filter
, $table
).prop('checked', $(this).prop('checked')).trigger('change', 'master-selected');
663 $(this).closest('tr').toggleClass('crm-row-selected', $(this).prop('checked'));
664 if (data
!== 'master-selected') {
665 $('input.select-rows', $table
).prop('checked', $(".select-row:not(':checked')", $table
).length
< 1);
669 .find('input.select-row:checked').parents('tr').addClass('crm-row-selected');
670 if ($("input:radio[name=radio_ts]").size() == 1) {
671 $("input:radio[name=radio_ts]").prop("checked", true);
673 $('.crm-select2:not(.select2-offscreen, .select2-container)', e
.target
).crmSelect2();
674 $('.crm-form-entityref:not(.select2-offscreen, .select2-container)', e
.target
).crmEntityRef();
675 $('select.crm-chain-select-control', e
.target
).off('.chainSelect').on('change.chainSelect', chainSelect
);
676 // Cache Form Input initial values
677 $('form[data-warn-changes] :input', e
.target
).each(function() {
678 $(this).data('crm-initial-value', $(this).val());
681 .on('dialogopen', function(e
) {
682 var $el
= $(e
.target
);
683 // Modal dialogs should disable scrollbars
684 if ($el
.dialog('option', 'modal')) {
685 $el
.addClass('modal-dialog');
686 $('body').css({overflow
: 'hidden'});
689 if ($el
.parent().hasClass('crm-container') && $el
.dialog('option', 'resizable')) {
690 $el
.parent().find('.ui-dialog-titlebar').append($('<button class="crm-dialog-titlebar-resize ui-dialog-titlebar-close" title="'+ts('Toggle fullscreen')+'" style="right:2em;"/>').button({icons
: {primary
: 'ui-icon-newwin'}, text
: false}));
691 $('.crm-dialog-titlebar-resize', $el
.parent()).click(function(e
) {
692 if ($el
.data('origSize')) {
693 $el
.dialog('option', $el
.data('origSize'));
694 $el
.data('origSize', null);
696 var menuHeight
= $('#civicrm-menu').outerHeight();
697 $el
.data('origSize', {
698 position
: {my
: 'center', at
: 'center center+' + (menuHeight
/ 2), of: window
},
699 width
: $el
.dialog('option', 'width'),
700 height
: $el
.dialog('option', 'height')
702 $el
.dialog('option', {width
: '100%', height
: ($(window
).height() - menuHeight
), position
: {my
: "top", at
: "top+"+menuHeight
, of: window
}});
708 .on('dialogclose', function(e
) {
709 // Restore scrollbars when closing modal
710 if ($('.ui-dialog .modal-dialog:visible').not(e
.target
).length
< 1) {
711 $('body').css({overflow
: ''});
714 .on('submit', function(e
) {
715 // CRM-14353 - disable changes warn when submitting a form
716 $('[data-warn-changes]').attr('data-warn-changes', 'false');
720 // CRM-14353 - Warn of unsaved changes for forms which have opted in
721 window
.onbeforeunload = function() {
722 if (CRM
.utils
.initialValueChanged($('form[data-warn-changes=true]:visible'))) {
723 return ts('You have unsaved changes.');
728 * Function to make multiselect boxes behave as fields in small screens
730 function advmultiselectResize() {
731 var amswidth
= $("#crm-container form:has(table.advmultiselect)").width();
732 if (amswidth
< 700) {
733 $("form table.advmultiselect td").css('display', 'block');
736 $("form table.advmultiselect td").css('display', 'table-cell');
738 var contactwidth
= $('#crm-container #mainTabContainer').width();
739 if (contactwidth
< 600) {
740 $('#crm-container #mainTabContainer').addClass('narrowpage');
741 $('#crm-container #mainTabContainer.narrowpage #contactTopBar td').each(function (index
) {
743 if (index
% 2 == 0) {
744 $(this).parent().after('<tr class="narrowadded"></tr>');
747 $(this).parent().next().append(item
);
752 $('#crm-container #mainTabContainer.narrowpage').removeClass('narrowpage');
753 $('#crm-container #mainTabContainer #contactTopBar tr.narrowadded td').each(function () {
755 var parent
= $(this).parent();
756 $(this).parent().prev().append(nitem
);
757 if (parent
.children().size() == 0) {
761 $('#crm-container #mainTabContainer.narrowpage #contactTopBar tr.added').detach();
763 var cformwidth
= $('#crm-container #Contact .contact_basic_information-section').width();
765 if (cformwidth
< 720) {
766 $('#crm-container .contact_basic_information-section').addClass('narrowform');
767 $('#crm-container .contact_basic_information-section table.form-layout-compressed td .helpicon').parent().addClass('hashelpicon');
768 if (cformwidth
< 480) {
769 $('#crm-container .contact_basic_information-section').addClass('xnarrowform');
772 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
776 $('#crm-container .contact_basic_information-section.narrowform').removeClass('narrowform');
777 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
781 advmultiselectResize();
782 $(window
).resize(advmultiselectResize
);
784 $.fn
.crmtooltip = function () {
786 .on('mouseover', 'a.crm-summary-link:not(.crm-processed)', function (e
) {
787 $(this).addClass('crm-processed');
788 $(this).addClass('crm-tooltip-active');
789 var topDistance
= e
.pageY
- $(window
).scrollTop();
790 if (topDistance
< 300 | topDistance
< $(this).children('.crm-tooltip-wrapper').height()) {
791 $(this).addClass('crm-tooltip-down');
793 if (!$(this).children('.crm-tooltip-wrapper').length
) {
794 $(this).append('<div class="crm-tooltip-wrapper"><div class="crm-tooltip"></div></div>');
795 $(this).children().children('.crm-tooltip')
796 .html('<div class="crm-loading-element"></div>')
800 .on('mouseout', 'a.crm-summary-link', function () {
801 $(this).removeClass('crm-processed');
802 $(this).removeClass('crm-tooltip-active crm-tooltip-down');
804 .on('click', 'a.crm-summary-link', false);
807 var helpDisplay
, helpPrevious
;
808 CRM
.help = function (title
, params
, url
) {
809 if (helpDisplay
&& helpDisplay
.close
) {
810 // If the same link is clicked twice, just close the display - todo use underscore method for this comparison
811 if (helpDisplay
.isOpen
&& helpPrevious
=== JSON
.stringify(params
)) {
817 helpPrevious
= JSON
.stringify(params
);
818 params
.class_name
= 'CRM_Core_Page_Inline_Help';
819 params
.type
= 'page';
820 helpDisplay
= CRM
.alert('...', title
, 'crm-help crm-msg-loading', {expires
: 0});
821 $.ajax(url
|| CRM
.url('civicrm/ajax/inline'),
825 success: function (data
) {
826 $('#crm-notification-container .crm-help .notify-content:last').html(data
);
827 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('info');
830 $('#crm-notification-container .crm-help .notify-content:last').html('Unable to load help file.');
831 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('error');
837 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
839 CRM
.status = function(options
, deferred
) {
840 // For simple usage without async operations you can pass in a string. 2nd param is optional string 'error' if this is not a success msg.
841 if (typeof options
=== 'string') {
842 return CRM
.status({start
: options
, success
: options
, error
: options
})[deferred
=== 'error' ? 'reject' : 'resolve']();
844 var opts
= $.extend({
845 start
: ts('Saving...'),
846 success
: ts('Saved'),
847 error: function(data
) {
848 var msg
= $.isPlainObject(data
) && data
.error_message
;
849 CRM
.alert(msg
|| ts('Sorry an error occurred and your information was not saved'), ts('Error'), 'error');
852 var $msg
= $('<div class="crm-status-box-outer status-start"><div class="crm-status-box-inner"><div class="crm-status-box-msg">' + opts
.start
+ '</div></div></div>')
854 $msg
.css('min-width', $msg
.width());
855 function handle(status
, data
) {
856 var endMsg
= typeof(opts
[status
]) === 'function' ? opts
[status
](data
) : opts
[status
];
858 $msg
.removeClass('status-start').addClass('status-' + status
).find('.crm-status-box-msg').html(endMsg
);
859 window
.setTimeout(function() {
860 $msg
.fadeOut('slow', function() {
868 return (deferred
|| new $.Deferred())
869 .done(function(data
) {
870 // If the server returns an error msg call the error handler
871 var status
= $.isPlainObject(data
) && (data
.is_error
|| data
.status
=== 'error') ? 'error' : 'success';
872 handle(status
, data
);
874 .fail(function(data
) {
875 handle('error', data
);
879 // Convert an Angular promise to a jQuery promise
880 CRM
.toJqPromise = function(aPromise
) {
881 var jqDeferred
= $.Deferred();
883 function(data
) { jqDeferred
.resolve(data
); },
884 function(data
) { jqDeferred
.reject(data
); }
885 // should we also handle progress events?
887 return jqDeferred
.promise();
890 CRM
.toAPromise = function($q
, jqPromise
) {
891 var aDeferred
= $q
.defer();
893 function(data
) { aDeferred
.resolve(data
); },
894 function(data
) { aDeferred
.reject(data
); }
895 // should we also handle progress events?
897 return aDeferred
.promise
;
901 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
903 CRM
.alert = function (text
, title
, type
, options
) {
904 type
= type
|| 'alert';
906 options
= options
|| {};
907 if ($('#crm-notification-container').length
) {
913 // By default, don't expire errors and messages containing links
915 expires
: (type
== 'error' || text
.indexOf('<a ') > -1) ? 0 : (text
? 10000 : 5000),
918 options
= $.extend(extra
, options
);
919 options
.expires
= options
.expires
=== false ? 0 : parseInt(options
.expires
, 10);
920 if (options
.unique
&& options
.unique
!== '0') {
921 $('#crm-notification-container .ui-notify-message').each(function () {
922 if (title
=== $('h1', this).html() && text
=== $('.notify-content', this).html()) {
923 $('.icon.ui-notify-close', this).click();
927 return $('#crm-notification-container').notify('create', params
, options
);
931 text
= title
+ "\n" + text
;
939 * Close whichever alert contains the given node
943 CRM
.closeAlertByChild = function (node
) {
944 $(node
).closest('.ui-notify-message').find('.icon.ui-notify-close').click();
948 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
950 CRM
.confirm = function (options
) {
951 var dialog
, url
, msg
, buttons
= [], settings
= {
952 title
: ts('Confirm'),
953 message
: ts('Are you sure you want to continue?'),
958 dialogClass
: 'crm-container crm-confirm',
960 $(this).dialog('destroy').remove();
967 $.extend(settings
, ($.isFunction(options
) ? arguments
[1] : options
) || {});
968 if (!settings
.buttons
&& $.isPlainObject(settings
.options
)) {
969 $.each(settings
.options
, function(op
, label
) {
973 icons
: {primary
: op
=== 'no' ? 'ui-icon-close' : 'ui-icon-check'},
975 var event
= $.Event('crmConfirm:' + op
);
976 $(this).trigger(event
);
977 if (!event
.isDefaultPrevented()) {
978 dialog
.dialog('close');
983 // Order buttons so that "no" goes on the right-hand side
984 settings
.buttons
= _
.sortBy(buttons
, 'data-op').reverse();
987 msg
= url
? '' : settings
.message
;
988 delete settings
.options
;
989 delete settings
.message
;
991 dialog
= $('<div class="crm-confirm-dialog"></div>').html(msg
|| '').dialog(settings
);
992 if ($.isFunction(options
)) {
993 dialog
.on('crmConfirm:yes', options
);
996 CRM
.loadPage(url
, {target
: dialog
});
999 dialog
.trigger('crmLoad');
1004 /** provides a local copy of ts for a domain */
1005 CRM
.ts = function(domain
) {
1006 return function(message
, options
) {
1008 options
= $.extend(options
|| {}, {domain
: domain
});
1010 return ts(message
, options
);
1015 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
1017 $.fn
.crmError = function (text
, title
, options
) {
1018 title
= title
|| '';
1020 options
= options
|| {};
1025 if ($(this).length
) {
1027 var label
= $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]').not('[generated=true]');
1029 label
.addClass('crm-error');
1030 var $label
= label
.clone();
1031 if (text
== '' && $('.crm-marker', $label
).length
> 0) {
1032 text
= $('.crm-marker', $label
).attr('title');
1034 $('.crm-marker', $label
).remove();
1035 title
= $label
.text();
1038 $(this).addClass('crm-error');
1040 var msg
= CRM
.alert(text
, title
, 'error', $.extend(extra
, options
));
1041 if ($(this).length
) {
1043 setTimeout(function () {
1044 ele
.one('change', function () {
1045 if (msg
&& msg
.close
) msg
.close();
1046 ele
.removeClass('error');
1047 label
.removeClass('crm-error');
1054 // Display system alerts through js notifications
1055 function messagesFromMarkup() {
1056 $('div.messages:visible', this).not('.help').not('.no-popup').each(function () {
1057 var text
, title
= '';
1058 $(this).removeClass('status messages');
1059 var type
= $(this).attr('class').split(' ')[0] || 'alert';
1060 type
= type
.replace('crm-', '');
1061 $('.icon', this).remove();
1062 if ($('.msg-text', this).length
> 0) {
1063 text
= $('.msg-text', this).html();
1064 title
= $('.msg-title', this).html();
1067 text
= $(this).html();
1069 var options
= $(this).data('options') || {};
1071 // Duplicates were already removed server-side
1072 options
.unique
= false;
1073 CRM
.alert(text
, title
, type
, options
);
1075 // Handle qf form errors
1076 $('form :input.error', this).one('blur', function() {
1077 $('.ui-notify-message.error a.ui-notify-close').click();
1078 $(this).removeClass('error');
1079 $(this).next('span.crm-error').remove();
1080 $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]')
1081 .removeClass('crm-error')
1082 .find('.crm-error').removeClass('crm-error');
1087 * Improve blockUI when used with jQuery dialog
1089 var originalBlock
= $.fn
.block
,
1090 originalUnblock
= $.fn
.unblock
;
1092 $.fn
.block = function(opts
) {
1093 if ($(this).is('.ui-dialog-content')) {
1094 originalBlock
.call($(this).parents('.ui-dialog'), opts
);
1097 return originalBlock
.call(this, opts
);
1099 $.fn
.unblock = function(opts
) {
1100 if ($(this).is('.ui-dialog-content')) {
1101 originalUnblock
.call($(this).parents('.ui-dialog'), opts
);
1104 return originalUnblock
.call(this, opts
);
1107 // Preprocess all CRM ajax calls to display messages
1108 $(document
).ajaxSuccess(function(event
, xhr
, settings
) {
1110 if ((!settings
.dataType
|| settings
.dataType
== 'json') && xhr
.responseText
) {
1111 var response
= $.parseJSON(xhr
.responseText
);
1112 if (typeof(response
.crmMessages
) == 'object') {
1113 $.each(response
.crmMessages
, function(n
, msg
) {
1114 CRM
.alert(msg
.text
, msg
.title
, msg
.type
, msg
.options
);
1117 if (response
.backtrace
) {
1118 CRM
.console('log', response
.backtrace
);
1120 if (typeof response
.deprecated
=== 'string') {
1121 CRM
.console('warn', response
.deprecated
);
1125 // Ignore errors thrown by parseJSON
1130 $.blockUI
.defaults
.message
= null;
1131 $.blockUI
.defaults
.ignoreIfBlocked
= true;
1133 if ($('#crm-container').hasClass('crm-public')) {
1134 $.fn
.select2
.defaults
.dropdownCssClass
= $.ui
.dialog
.prototype.options
.dialogClass
= 'crm-container crm-public';
1137 // Trigger crmLoad on initial content for consistency. It will also be triggered for ajax-loaded content.
1138 $('.crm-container').trigger('crmLoad');
1140 if ($('#crm-notification-container').length
) {
1141 // Initialize notifications
1142 $('#crm-notification-container').notify();
1143 messagesFromMarkup
.call($('#crm-container'));
1147 // bind the event for image popup
1148 .on('click', 'a.crm-image-popup', function(e
) {
1150 title
: ts('Preview'),
1152 message
: '<div class="crm-custom-image-popup"><img style="max-width: 100%" src="' + $(this).attr('href') + '"></div>',
1158 .on('click', function (event
) {
1159 $('.btn-slide-active').removeClass('btn-slide-active').find('.panel').hide();
1160 if ($(event
.target
).is('.btn-slide')) {
1161 $(event
.target
).addClass('btn-slide-active').find('.panel').show();
1165 // Handle clear button for form elements
1166 .on('click', 'a.crm-clear-link', function() {
1167 $(this).css({visibility
: 'hidden'}).siblings('.crm-form-radio:checked').prop('checked', false).change();
1168 $(this).siblings('input:text').val('').change();
1171 .on('change', 'input.crm-form-radio:checked', function() {
1172 $(this).siblings('.crm-clear-link').css({visibility
: ''});
1175 // Allow normal clicking of links within accordions
1176 .on('click.crmAccordions', 'div.crm-accordion-header a', function (e
) {
1177 e
.stopPropagation();
1179 // Handle accordions
1180 .on('click.crmAccordions', '.crm-accordion-header, .crm-collapsible .collapsible-title', function (e
) {
1181 if ($(this).parent().hasClass('collapsed')) {
1182 $(this).next().css('display', 'none').slideDown(200);
1185 $(this).next().css('display', 'block').slideUp(200);
1187 $(this).parent().toggleClass('collapsed');
1196 $.fn
.crmAccordions = function () {
1197 CRM
.console('warn', 'Warning: $.crmAccordions was called. This function is deprecated and should not be used.');
1200 * Collapse or expand an accordion
1203 $.fn
.crmAccordionToggle = function (speed
) {
1204 $(this).each(function () {
1205 if ($(this).hasClass('collapsed')) {
1206 $('.crm-accordion-body', this).first().css('display', 'none').slideDown(speed
);
1209 $('.crm-accordion-body', this).first().css('display', 'block').slideUp(speed
);
1211 $(this).toggleClass('collapsed');
1216 * Clientside currency formatting
1217 * @param number value
1218 * @param [optional] string format - currency representation of the number 1234.56
1221 var currencyTemplate
;
1222 CRM
.formatMoney = function(value
, format
) {
1223 var decimal, separator
, sign
, i
, j
, result
;
1224 if (value
=== 'init' && format
) {
1225 currencyTemplate
= format
;
1228 format
= format
|| currencyTemplate
;
1229 result
= /1(.?)234(.?)56/.exec(format
);
1230 if (result
=== null) {
1231 return 'Invalid format passed to CRM.formatMoney';
1233 separator
= result
[1];
1234 decimal = result
[2];
1235 sign
= (value
< 0) ? '-' : '';
1236 //extracting the absolute value of the integer part of the number and converting to string
1237 i
= parseInt(value
= Math
.abs(value
).toFixed(2)) + '';
1238 j
= ((j
= i
.length
) > 3) ? j
% 3 : 0;
1239 result
= sign
+ (j
? i
.substr(0, j
) + separator
: '') + i
.substr(j
).replace(/(\d{3})(?=\d)/g, "$1" + separator
) + (2 ? decimal + Math
.abs(value
- i
).toFixed(2).slice(2) : '');
1240 return format
.replace(/1.*234.*56/, result
);
1243 CRM
.console = function(method
, title
, msg
) {
1244 if (window
.console
) {
1245 method
= $.isFunction(console
[method
]) ? method
: 'log';
1246 if (msg
=== undefined) {
1247 return console
[method
](title
);
1249 return console
[method
](title
, msg
);