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 var d
= (params
&& params
.domain
) ? ('strings::' + params
.domain
) : null;
17 if (d
&& CRM
[d
] && CRM
[d
][text
]) {
20 else if (CRM
['strings'][text
]) {
21 text
= CRM
['strings'][text
];
23 if (typeof(params
) === 'object') {
24 for (var i
in params
) {
25 if (typeof(params
[i
]) === 'string' || typeof(params
[i
]) === 'number') {
26 // sprintf emulation: escape % characters in the replacements to avoid conflicts
27 text
= text
.replace(new RegExp('%' + i
, 'g'), String(params
[i
]).replace(/%/g
, '%-crmescaped-'));
30 return text
.replace(/%-crmescaped-/g, '%');
36 * This function is called by default at the bottom of template files which have forms that have
37 * conditionally displayed/hidden sections and elements. The PHP is responsible for generating
38 * a list of 'blocks to show' and 'blocks to hide' and the template passes these parameters to
42 * @param showBlocks Array of element Id's to be displayed
43 * @param hideBlocks Array of element Id's to be hidden
44 * @param elementType Value to set display style to for showBlocks (e.g. 'block' or 'table-row' or ...)
46 function on_load_init_blocks(showBlocks
, hideBlocks
, elementType
) {
47 if (elementType
== null) {
48 elementType
= 'block';
53 /* This loop is used to display the blocks whose IDs are present within the showBlocks array */
54 for (i
= 0; i
< showBlocks
.length
; i
++) {
55 myElement
= document
.getElementById(showBlocks
[i
]);
56 /* getElementById returns null if element id doesn't exist in the document */
57 if (myElement
!= null) {
58 myElement
.style
.display
= elementType
;
61 alert('showBlocks array item not in .tpl = ' + showBlocks
[i
]);
65 /* This loop is used to hide the blocks whose IDs are present within the hideBlocks array */
66 for (i
= 0; i
< hideBlocks
.length
; i
++) {
67 myElement
= document
.getElementById(hideBlocks
[i
]);
68 /* getElementById returns null if element id doesn't exist in the document */
69 if (myElement
!= null) {
70 myElement
.style
.display
= 'none';
73 alert('showBlocks array item not in .tpl = ' + hideBlocks
[i
]);
79 * This function is called when we need to show or hide a related form element (target_element)
80 * based on the value (trigger_value) of another form field (trigger_field).
83 * @param trigger_field_id HTML id of field whose onchange is the trigger
84 * @param trigger_value List of integers - option value(s) which trigger show-element action for target_field
85 * @param target_element_id HTML id of element to be shown or hidden
86 * @param target_element_type Type of element to be shown or hidden ('block' or 'table-row')
87 * @param field_type Type of element radio/select
88 * @param invert Boolean - if true, we HIDE target on value match; if false, we SHOW target on value match
90 function showHideByValue(trigger_field_id
, trigger_value
, target_element_id
, target_element_type
, field_type
, invert
) {
93 if (field_type
== 'select') {
94 var trigger
= trigger_value
.split("|");
95 var selectedOptionValue
= cj('#' + trigger_field_id
).val();
97 target
= target_element_id
.split("|");
98 for (j
= 0; j
< target
.length
; j
++) {
100 cj('#' + target
[j
]).show();
103 cj('#' + target
[j
]).hide();
105 for (var i
= 0; i
< trigger
.length
; i
++) {
106 if (selectedOptionValue
== trigger
[i
]) {
108 cj('#' + target
[j
]).hide();
111 cj('#' + target
[j
]).show();
119 if (field_type
== 'radio') {
120 target
= target_element_id
.split("|");
121 for (j
= 0; j
< target
.length
; j
++) {
122 if (cj('[name="' + trigger_field_id
+ '"]:first').is(':checked')) {
124 cj('#' + target
[j
]).hide();
127 cj('#' + target
[j
]).show();
132 cj('#' + target
[j
]).show();
135 cj('#' + target
[j
]).hide();
144 * Function to change button text and disable one it is clicked
146 * @param obj object - the button clicked
147 * @param formID string - the id of the form being submitted
148 * @param string procText - button text after user clicks it
152 /* Changes button label on submit, and disables button after submit for newer browsers.
153 Puts up alert for older browsers. */
154 function submitOnce(obj
, formId
, procText
) {
155 // if named button clicked, change text
156 if (obj
.value
!= null) {
157 obj
.value
= procText
+ " ...";
159 cj(obj
).closest('form').attr('data-warn-changes', 'false');
160 if (document
.getElementById
) { // disable submit button for newer browsers
162 document
.getElementById(formId
).submit();
165 else { // for older browsers
166 if (submitcount
== 0) {
171 alert("Your request is currently being processed ... Please wait.");
178 * Function to show / hide the row in optionFields
180 * @param index string, element whose innerHTML is to hide else will show the hidden row.
182 function showHideRow(index
) {
184 cj('tr#optionField_' + index
).hide();
185 if (cj('table#optionField tr:hidden:first').length
) {
186 cj('div#optionFieldLink').show();
190 cj('table#optionField tr:hidden:first').show();
191 if (!cj('table#optionField tr:hidden:last').length
) {
192 cj('div#optionFieldLink').hide();
198 CRM
.utils
= CRM
.utils
|| {};
199 CRM
.strings
= CRM
.strings
|| {};
201 (function ($, _
, undefined) {
204 // Theme classes for unattached elements
205 $.fn
.select2
.defaults
.dropdownCssClass
= $.ui
.dialog
.prototype.options
.dialogClass
= 'crm-container';
207 // https://github.com/ivaynberg/select2/pull/2090
208 $.fn
.select2
.defaults
.width
= 'resolve';
210 // Workaround for https://github.com/ivaynberg/select2/issues/1246
211 $.ui
.dialog
.prototype._allowInteraction = function(e
) {
212 return !!$(e
.target
).closest('.ui-dialog, .ui-datepicker, .select2-drop, .cke_dialog').length
;
216 * Populate a select list, overwriting the existing options except for the placeholder.
217 * @param select jquery selector - 1 or more select elements
218 * @param options array in format returned by api.getoptions
219 * @param placeholder string|bool - new placeholder or false (default) to keep the old one
220 * @param value string|array - will silently update the element with new value without triggering change
222 CRM
.utils
.setOptions = function(select
, options
, placeholder
, value
) {
223 $(select
).each(function() {
226 val
= value
|| $elect
.val() || [],
227 opts
= placeholder
|| placeholder
=== '' ? '' : '[value!=""]';
228 $elect
.find('option' + opts
).remove();
229 var newOptions
= CRM
.utils
.renderOptions(options
, val
);
230 if (typeof placeholder
=== 'string') {
231 if ($elect
.is('[multiple]')) {
232 select
.attr('placeholder', placeholder
);
234 newOptions
= '<option value="">' + placeholder
+ '</option>' + newOptions
;
237 $elect
.append(newOptions
);
239 $elect
.trigger('crmOptionsUpdated', $.extend({}, options
)).trigger('change');
245 * Render an option list
246 * @param options {array}
247 * @param val {string} default value
248 * @param escapeHtml {bool}
251 CRM
.utils
.renderOptions = function(options
, val
, escapeHtml
) {
253 esc
= escapeHtml
=== false ? _
.identity
: _
.escape
;
254 if (!$.isArray(val
)) {
257 _
.each(options
, function(option
) {
258 if (option
.children
) {
259 rendered
+= '<optgroup label="' + esc(option
.value
) + '">' +
260 CRM
.utils
.renderOptions(option
.children
, val
) +
263 var selected
= ($.inArray('' + option
.key
, val
) > -1) ? 'selected="selected"' : '';
264 rendered
+= '<option value="' + esc(option
.key
) + '"' + selected
+ '>' + esc(option
.value
) + '</option>';
270 function chainSelect() {
271 var $form
= $(this).closest('form'),
272 $target
= $('select[data-name="' + $(this).data('target') + '"]', $form
),
273 data
= $target
.data(),
275 $target
.prop('disabled', true);
276 if ($target
.is('select.crm-chain-select-control')) {
277 $('select[data-name="' + $target
.data('target') + '"]', $form
).prop('disabled', true).blur();
279 if (!(val
&& val
.length
)) {
280 CRM
.utils
.setOptions($target
.blur(), [], data
.emptyPrompt
);
282 $target
.addClass('loading');
283 $.getJSON(CRM
.url(data
.callback
), {_value
: val
}, function(vals
) {
284 $target
.prop('disabled', false).removeClass('loading');
285 CRM
.utils
.setOptions($target
, vals
|| [], (vals
&& vals
.length
? data
.selectPrompt
: data
.nonePrompt
));
291 * Compare Form Input values against cached initial value.
293 * @return {Boolean} true if changes have been made.
295 CRM
.utils
.initialValueChanged = function(el
) {
297 $(':input:visible, .select2-container:visible+:input.select2-offscreen', el
).not('[type=submit], [type=button], .crm-action-menu').each(function () {
298 var initialValue
= $(this).data('crm-initial-value');
299 // skip change of value for submit buttons
300 if (initialValue
!== undefined && !_
.isEqual(initialValue
, $(this).val())) {
308 * Wrapper for select2 initialization function; supplies defaults
309 * @param options object
311 $.fn
.crmSelect2 = function(options
) {
312 return $(this).each(function () {
315 settings
= {allowClear
: !$el
.hasClass('required')};
316 // quickform doesn't support optgroups so here's a hack :(
317 $('option[value^=crm_optgroup]', this).each(function () {
318 $(this).nextUntil('option[value^=crm_optgroup]').wrapAll('<optgroup label="' + $(this).text() + '" />');
322 // quickform does not support disabled option, so yet another hack to
323 // add disabled property for option values
324 $('option[value^=crm_disabled_opt]', this).attr('disabled', 'disabled');
326 // Defaults for single-selects
327 if ($el
.is('select:not([multiple])')) {
328 settings
.minimumResultsForSearch
= 10;
329 if ($('option:first', this).val() === '') {
330 settings
.placeholderOption
= 'first';
333 $.extend(settings
, $el
.data('select-params') || {}, options
|| {});
335 $el
.addClass('crm-ajax-select');
337 $el
.select2(settings
);
342 * @see CRM_Core_Form::addEntityRef for docs
343 * @param options object
345 $.fn
.crmEntityRef = function(options
) {
346 options
= options
|| {};
347 options
.select
= options
.select
|| {};
348 return $(this).each(function() {
350 $el
= $(this).off('.crmEntity'),
351 entity
= options
.entity
|| $el
.data('api-entity') || 'contact',
353 $el
.data('api-entity', entity
);
354 $el
.data('select-params', $.extend({}, $el
.data('select-params') || {}, options
.select
));
355 $el
.data('api-params', $.extend({}, $el
.data('api-params') || {}, options
.api
));
356 $el
.data('create-links', options
.create
|| $el
.data('create-links'));
357 $el
.addClass('crm-form-entityref crm-' + entity
.toLowerCase() + '-ref');
359 // Use select2 ajax helper instead of CRM.api3 because it provides more value
361 url
: CRM
.url('civicrm/ajax/rest'),
362 data: function (input
, page_num
) {
363 var params
= getEntityRefApiParams($el
);
364 params
.input
= input
;
365 params
.page_num
= page_num
;
367 entity
: $el
.data('api-entity'),
369 json
: JSON
.stringify(params
)
372 results: function(data
) {
373 return {more
: data
.more_results
, results
: data
.values
|| []};
376 minimumInputLength
: 1,
377 formatResult
: CRM
.utils
.formatSelect2Result
,
378 formatSelection: function(row
) {
381 escapeMarkup: function (m
) {return m
;},
382 initSelection: function($el
, callback
) {
384 multiple
= !!$el
.data('select-params').multiple
,
386 stored
= $el
.data('entity-value') || [];
390 // If we already have this data, just return it
391 if (!_
.xor(val
.split(','), _
.pluck(stored
, 'id')).length
) {
392 callback(multiple
? stored
: stored
[0]);
394 var params
= $.extend({}, $el
.data('api-params') || {}, {id
: val
});
395 CRM
.api3($el
.data('api-entity'), 'getlist', params
).done(function(result
) {
396 callback(multiple
? result
.values
: result
.values
[0]);
397 // Trigger change (store data to avoid an infinite loop of lookups)
398 $el
.data('entity-value', result
.values
).trigger('change');
403 // Create new items inline - works for tags
404 if ($el
.data('create-links') && entity
.toLowerCase() === 'tag') {
405 selectParams
.createSearchChoice = function(term
, data
) {
406 if (!_
.findKey(data
, {label
: term
})) {
407 return {id
: "0", term
: term
, label
: term
+ ' (' + ts('new tag') + ')'};
410 selectParams
.tokenSeparators
= [','];
411 selectParams
.createSearchChoicePosition
= 'bottom';
412 $el
.on('select2-selecting.crmEntity', function(e
) {
415 e
.object
.label
= e
.object
.term
;
416 CRM
.api3(entity
, 'create', $.extend({name
: e
.object
.term
}, $el
.data('api-params').params
|| {}))
417 .done(function(created
) {
419 val
= $el
.select2('val'),
420 data
= $el
.select2('data'),
421 item
= {id
: created
.id
, label
: e
.object
.term
};
423 $el
.select2('data', item
, true);
425 else if ($.isArray(val
) && $.inArray("0", val
) > -1) {
426 _
.remove(data
, {id
: "0"});
428 $el
.select2('data', data
, true);
435 selectParams
.formatInputTooShort = function() {
436 var txt
= $el
.data('select-params').formatInputTooShort
|| $.fn
.select2
.defaults
.formatInputTooShort
.call(this);
437 txt
+= renderEntityRefFilters($el
) + renderEntityRefCreateLinks($el
);
440 selectParams
.formatNoMatches = function() {
441 var txt
= $el
.data('select-params').formatNoMatches
|| $.fn
.select2
.defaults
.formatNoMatches
;
442 txt
+= renderEntityRefFilters($el
) + renderEntityRefCreateLinks($el
);
445 $el
.on('select2-open.crmEntity', function() {
447 loadEntityRefFilterOptions($el
);
450 .on('click.crmEntity', 'a.crm-add-entity', function(e
) {
451 $el
.select2('close');
452 CRM
.loadForm($(this).attr('href'), {
453 dialog
: {width
: 500, height
: 'auto'}
454 }).on('crmFormSuccess', function(e
, data
) {
455 if (data
.status
=== 'success' && data
.id
) {
456 CRM
.status(ts('%1 Created', {1: data
.label
}));
457 if ($el
.select2('container').hasClass('select2-container-multi')) {
458 var selection
= $el
.select2('data');
459 selection
.push(data
);
460 $el
.select2('data', selection
, true);
462 $el
.select2('data', data
, true);
468 .on('change.crmEntity', 'select.crm-entityref-filter-value', function() {
469 var filter
= $el
.data('user-filter') || {};
470 filter
.value
= $(this).val();
471 $(this).toggleClass('active', !!filter
.value
);
472 $el
.data('user-filter', filter
);
474 // Once a filter has been chosen, rerender create links and refocus the search box
475 $el
.select2('close');
479 .on('change.crmEntity', 'select.crm-entityref-filter-key', function() {
480 var filter
= $el
.data('user-filter') || {};
481 filter
.key
= $(this).val();
482 $(this).toggleClass('active', !!filter
.key
);
483 $el
.data('user-filter', filter
);
484 loadEntityRefFilterOptions($el
);
488 $el
.crmSelect2($.extend(settings
, $el
.data('select-params'), selectParams
));
493 * Combine api-params with user-filter
497 function getEntityRefApiParams($el
) {
499 params
= $.extend({params
: {}}, $el
.data('api-params') || {}),
500 // Prevent original data from being modified - $.extend and _.clone don't cut it, they pass nested objects by reference!
501 combined
= _
.cloneDeep(params
),
502 filter
= $.extend({}, $el
.data('user-filter') || {});
503 if (filter
.key
&& filter
.value
) {
504 // Special case for contact type/sub-type combo
505 if (filter
.key
=== 'contact_type' && (filter
.value
.indexOf('__') > 0)) {
506 combined
.params
.contact_type
= filter
.value
.split('__')[0];
507 combined
.params
.contact_sub_type
= filter
.value
.split('__')[1];
509 // Allow json-encoded api filters e.g. {"BETWEEN":[123,456]}
510 combined
.params
[filter
.key
] = filter
.value
.charAt(0) === '{' ? $.parseJSON(filter
.value
) : filter
.value
;
516 CRM
.utils
.formatSelect2Result = function (row
) {
517 var markup
= '<div class="crm-select2-row">';
518 if (row
.image
!== undefined) {
519 markup
+= '<div class="crm-select2-image"><img src="' + row
.image
+ '"/></div>';
521 else if (row
.icon_class
) {
522 markup
+= '<div class="crm-select2-icon"><div class="crm-icon ' + row
.icon_class
+ '-icon"></div></div>';
524 markup
+= '<div><div class="crm-select2-row-label '+(row
.label_class
|| '')+'">' + row
.label
+ '</div>';
525 markup
+= '<div class="crm-select2-row-description">';
526 $.each(row
.description
|| [], function(k
, text
) {
527 markup
+= '<p>' + text
+ '</p>';
529 markup
+= '</div></div></div>';
533 function renderEntityRefCreateLinks($el
) {
535 createLinks
= $el
.data('create-links'),
536 params
= getEntityRefApiParams($el
).params
,
537 markup
= '<div class="crm-entityref-links">';
538 if (!createLinks
|| $el
.data('api-entity').toLowerCase() !== 'contact') {
541 if (createLinks
=== true) {
542 createLinks
= params
.contact_type
? _
.where(CRM
.config
.entityRef
.contactCreate
, {type
: params
.contact_type
}) : CRM
.config
.entityRef
.contactCreate
;
544 _
.each(createLinks
, function(link
) {
545 markup
+= ' <a class="crm-add-entity crm-hover-button" href="' + link
.url
+ '">';
547 markup
+= '<span class="icon ' + link
.type
+ '-profile-icon"></span> ';
549 markup
+= link
.label
+ '</a>';
555 function getEntityRefFilters($el
) {
557 entity
= $el
.data('api-entity').toLowerCase(),
558 filters
= $.extend([], CRM
.config
.entityRef
.filters
[entity
] || []),
559 filter
= $el
.data('user-filter') || {},
560 params
= $.extend({params
: {}}, $el
.data('api-params') || {}).params
,
562 $.each(filters
, function() {
563 if (typeof params
[this.key
] === 'undefined') {
566 else if (this.key
== 'contact_type' && typeof params
.contact_sub_type
=== 'undefined') {
567 this.options
= _
.remove(this.options
, function(option
) {
568 return option
.key
.indexOf(params
.contact_type
+ '__') === 0;
576 function renderEntityRefFilters($el
) {
578 filters
= getEntityRefFilters($el
),
579 filter
= $el
.data('user-filter') || {},
580 filterSpec
= filter
.key
? _
.find(filters
, {key
: filter
.key
}) : null;
581 if (!filters
.length
) {
584 var markup
= '<div class="crm-entityref-filters">' +
585 '<select class="crm-entityref-filter-key' + (filter
.key
? ' active' : '') + '">' +
586 '<option value="">' + ts('Refine search...') + '</option>' +
587 CRM
.utils
.renderOptions(filters
, filter
.key
) +
588 '</select> ' +
589 '<select class="crm-entityref-filter-value' + (filter
.key
? ' active"' : '"') + (filter
.key
? '' : ' style="display:none;"') + '>' +
590 '<option value="">' + ts('- select -') + '</option>';
591 if (filterSpec
&& filterSpec
.options
) {
592 markup
+= CRM
.utils
.renderOptions(filterSpec
.options
, filter
.value
);
594 markup
+= '</select></div>';
599 * Fetch options for a filter (via ajax if necessary) and populate the appropriate select list
602 function loadEntityRefFilterOptions($el
) {
604 filters
= getEntityRefFilters($el
),
605 filter
= $el
.data('user-filter') || {},
606 filterSpec
= filter
.key
? _
.find(filters
, {key
: filter
.key
}) : null,
607 $valField
= $('.crm-entityref-filter-value', '#select2-drop');
609 $valField
.show().val('');
610 if (filterSpec
.options
) {
611 CRM
.utils
.setOptions($valField
, filterSpec
.options
, false, filter
.value
);
613 $valField
.prop('disabled', true);
614 CRM
.api3(filterSpec
.entity
|| $el
.data('api-entity'), 'getoptions', {field
: filter
.key
, context
: 'search', sequential
: 1})
615 .done(function(result
) {
616 var entity
= $el
.data('api-entity').toLowerCase(),
617 globalFilterSpec
= _
.find(CRM
.config
.entityRef
.filters
[entity
], {key
: filter
.key
}) || {};
618 // Store options globally so we don't have to look them up again
619 globalFilterSpec
.options
= result
.values
;
620 $valField
.prop('disabled', false);
621 CRM
.utils
.setOptions($valField
, result
.values
);
622 $valField
.val(filter
.value
|| '');
630 //CRM-15598 - Override url validator method to allow relative url's (e.g. /index.htm)
631 $.validator
.addMethod("url", function(value
, element
) {
632 if (/^\//.test(value
)) {
633 // Relative url: prepend dummy path for validation.
634 value
= 'http://domain.tld' + value
;
636 // From jQuery Validation Plugin v1.12.0
637 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
);
641 * Wrapper for jQuery validate initialization function; supplies defaults
643 $.fn
.crmValidate = function(params
) {
644 return $(this).each(function () {
646 settings
= $.extend({}, CRM
.validate
._defaults
, CRM
.validate
.params
);
647 $(this).validate(settings
);
648 // Call any post-initialization callbacks
649 if (CRM
.validate
.functions
&& CRM
.validate
.functions
.length
) {
650 $.each(CRM
.validate
.functions
, function(i
, func
) {
657 // Initialize widgets
659 .on('crmLoad', function(e
) {
660 $('table.row-highlight', e
.target
)
661 .off('.rowHighlight')
662 .on('change.rowHighlight', 'input.select-row, input.select-rows', function (e
, data
) {
663 var filter
, $table
= $(this).closest('table');
664 if ($(this).hasClass('select-rows')) {
665 filter
= $(this).prop('checked') ? ':not(:checked)' : ':checked';
666 $('input.select-row' + filter
, $table
).prop('checked', $(this).prop('checked')).trigger('change', 'master-selected');
669 $(this).closest('tr').toggleClass('crm-row-selected', $(this).prop('checked'));
670 if (data
!== 'master-selected') {
671 $('input.select-rows', $table
).prop('checked', $(".select-row:not(':checked')", $table
).length
< 1);
675 .find('input.select-row:checked').parents('tr').addClass('crm-row-selected');
676 if ($("input:radio[name=radio_ts]").size() == 1) {
677 $("input:radio[name=radio_ts]").prop("checked", true);
679 $('.crm-select2:not(.select2-offscreen, .select2-container)', e
.target
).crmSelect2();
680 $('.crm-form-entityref:not(.select2-offscreen, .select2-container)', e
.target
).crmEntityRef();
681 $('select.crm-chain-select-control', e
.target
).off('.chainSelect').on('change.chainSelect', chainSelect
);
682 // Cache Form Input initial values
683 $('form[data-warn-changes] :input', e
.target
).each(function() {
684 $(this).data('crm-initial-value', $(this).val());
687 .on('dialogopen', function(e
) {
688 var $el
= $(e
.target
);
689 // Modal dialogs should disable scrollbars
690 if ($el
.dialog('option', 'modal')) {
691 $el
.addClass('modal-dialog');
692 $('body').css({overflow
: 'hidden'});
695 if ($el
.parent().hasClass('crm-container') && $el
.dialog('option', 'resizable')) {
696 $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}));
697 $('.crm-dialog-titlebar-resize', $el
.parent()).click(function(e
) {
698 if ($el
.data('origSize')) {
699 $el
.dialog('option', $el
.data('origSize'));
700 $el
.data('origSize', null);
702 var menuHeight
= $('#civicrm-menu').outerHeight();
703 $el
.data('origSize', {
704 position
: {my
: 'center', at
: 'center center+' + (menuHeight
/ 2), of: window
},
705 width
: $el
.dialog('option', 'width'),
706 height
: $el
.dialog('option', 'height')
708 $el
.dialog('option', {width
: '100%', height
: ($(window
).height() - menuHeight
), position
: {my
: "top", at
: "top+"+menuHeight
, of: window
}});
714 .on('dialogclose', function(e
) {
715 // Restore scrollbars when closing modal
716 if ($('.ui-dialog .modal-dialog:visible').not(e
.target
).length
< 1) {
717 $('body').css({overflow
: ''});
720 .on('submit', function(e
) {
721 // CRM-14353 - disable changes warn when submitting a form
722 $('[data-warn-changes]').attr('data-warn-changes', 'false');
726 // CRM-14353 - Warn of unsaved changes for forms which have opted in
727 window
.onbeforeunload = function() {
728 if (CRM
.utils
.initialValueChanged($('form[data-warn-changes=true]:visible'))) {
729 return ts('You have unsaved changes.');
734 * Function to make multiselect boxes behave as fields in small screens
736 function advmultiselectResize() {
737 var amswidth
= $("#crm-container form:has(table.advmultiselect)").width();
738 if (amswidth
< 700) {
739 $("form table.advmultiselect td").css('display', 'block');
742 $("form table.advmultiselect td").css('display', 'table-cell');
744 var contactwidth
= $('#crm-container #mainTabContainer').width();
745 if (contactwidth
< 600) {
746 $('#crm-container #mainTabContainer').addClass('narrowpage');
747 $('#crm-container #mainTabContainer.narrowpage #contactTopBar td').each(function (index
) {
749 if (index
% 2 == 0) {
750 $(this).parent().after('<tr class="narrowadded"></tr>');
753 $(this).parent().next().append(item
);
758 $('#crm-container #mainTabContainer.narrowpage').removeClass('narrowpage');
759 $('#crm-container #mainTabContainer #contactTopBar tr.narrowadded td').each(function () {
761 var parent
= $(this).parent();
762 $(this).parent().prev().append(nitem
);
763 if (parent
.children().size() == 0) {
767 $('#crm-container #mainTabContainer.narrowpage #contactTopBar tr.added').detach();
769 var cformwidth
= $('#crm-container #Contact .contact_basic_information-section').width();
771 if (cformwidth
< 720) {
772 $('#crm-container .contact_basic_information-section').addClass('narrowform');
773 $('#crm-container .contact_basic_information-section table.form-layout-compressed td .helpicon').parent().addClass('hashelpicon');
774 if (cformwidth
< 480) {
775 $('#crm-container .contact_basic_information-section').addClass('xnarrowform');
778 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
782 $('#crm-container .contact_basic_information-section.narrowform').removeClass('narrowform');
783 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
787 advmultiselectResize();
788 $(window
).resize(advmultiselectResize
);
790 $.fn
.crmtooltip = function () {
792 .on('mouseover', 'a.crm-summary-link:not(.crm-processed)', function (e
) {
793 $(this).addClass('crm-processed');
794 $(this).addClass('crm-tooltip-active');
795 var topDistance
= e
.pageY
- $(window
).scrollTop();
796 if (topDistance
< 300 | topDistance
< $(this).children('.crm-tooltip-wrapper').height()) {
797 $(this).addClass('crm-tooltip-down');
799 if (!$(this).children('.crm-tooltip-wrapper').length
) {
800 $(this).append('<div class="crm-tooltip-wrapper"><div class="crm-tooltip"></div></div>');
801 $(this).children().children('.crm-tooltip')
802 .html('<div class="crm-loading-element"></div>')
806 .on('mouseout', 'a.crm-summary-link', function () {
807 $(this).removeClass('crm-processed');
808 $(this).removeClass('crm-tooltip-active crm-tooltip-down');
810 .on('click', 'a.crm-summary-link', false);
813 var helpDisplay
, helpPrevious
;
814 CRM
.help = function (title
, params
, url
) {
815 if (helpDisplay
&& helpDisplay
.close
) {
816 // If the same link is clicked twice, just close the display - todo use underscore method for this comparison
817 if (helpDisplay
.isOpen
&& helpPrevious
=== JSON
.stringify(params
)) {
823 helpPrevious
= JSON
.stringify(params
);
824 params
.class_name
= 'CRM_Core_Page_Inline_Help';
825 params
.type
= 'page';
826 helpDisplay
= CRM
.alert('...', title
, 'crm-help crm-msg-loading', {expires
: 0});
827 $.ajax(url
|| CRM
.url('civicrm/ajax/inline'),
831 success: function (data
) {
832 $('#crm-notification-container .crm-help .notify-content:last').html(data
);
833 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('info');
836 $('#crm-notification-container .crm-help .notify-content:last').html('Unable to load help file.');
837 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('error');
843 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
845 CRM
.status = function(options
, deferred
) {
846 // 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.
847 if (typeof options
=== 'string') {
848 return CRM
.status({start
: options
, success
: options
, error
: options
})[deferred
=== 'error' ? 'reject' : 'resolve']();
850 var opts
= $.extend({
851 start
: ts('Saving...'),
852 success
: ts('Saved'),
853 error: function(data
) {
854 var msg
= $.isPlainObject(data
) && data
.error_message
;
855 CRM
.alert(msg
|| ts('Sorry an error occurred and your information was not saved'), ts('Error'), 'error');
858 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>')
860 $msg
.css('min-width', $msg
.width());
861 function handle(status
, data
) {
862 var endMsg
= typeof(opts
[status
]) === 'function' ? opts
[status
](data
) : opts
[status
];
864 $msg
.removeClass('status-start').addClass('status-' + status
).find('.crm-status-box-msg').html(endMsg
);
865 window
.setTimeout(function() {
866 $msg
.fadeOut('slow', function() {
874 return (deferred
|| new $.Deferred())
875 .done(function(data
) {
876 // If the server returns an error msg call the error handler
877 var status
= $.isPlainObject(data
) && (data
.is_error
|| data
.status
=== 'error') ? 'error' : 'success';
878 handle(status
, data
);
880 .fail(function(data
) {
881 handle('error', data
);
885 // Convert an Angular promise to a jQuery promise
886 CRM
.toJqPromise = function(aPromise
) {
887 var jqDeferred
= $.Deferred();
889 function(data
) { jqDeferred
.resolve(data
); },
890 function(data
) { jqDeferred
.reject(data
); }
891 // should we also handle progress events?
893 return jqDeferred
.promise();
896 CRM
.toAPromise = function($q
, jqPromise
) {
897 var aDeferred
= $q
.defer();
899 function(data
) { aDeferred
.resolve(data
); },
900 function(data
) { aDeferred
.reject(data
); }
901 // should we also handle progress events?
903 return aDeferred
.promise
;
907 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
909 CRM
.alert = function (text
, title
, type
, options
) {
910 type
= type
|| 'alert';
912 options
= options
|| {};
913 if ($('#crm-notification-container').length
) {
919 // By default, don't expire errors and messages containing links
921 expires
: (type
== 'error' || text
.indexOf('<a ') > -1) ? 0 : (text
? 10000 : 5000),
924 options
= $.extend(extra
, options
);
925 options
.expires
= options
.expires
=== false ? 0 : parseInt(options
.expires
, 10);
926 if (options
.unique
&& options
.unique
!== '0') {
927 $('#crm-notification-container .ui-notify-message').each(function () {
928 if (title
=== $('h1', this).html() && text
=== $('.notify-content', this).html()) {
929 $('.icon.ui-notify-close', this).click();
933 return $('#crm-notification-container').notify('create', params
, options
);
937 text
= title
+ "\n" + text
;
945 * Close whichever alert contains the given node
949 CRM
.closeAlertByChild = function (node
) {
950 $(node
).closest('.ui-notify-message').find('.icon.ui-notify-close').click();
954 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
956 CRM
.confirm = function (options
) {
957 var dialog
, url
, msg
, buttons
= [], settings
= {
958 title
: ts('Confirm'),
959 message
: ts('Are you sure you want to continue?'),
964 dialogClass
: 'crm-container crm-confirm',
966 $(this).dialog('destroy').remove();
973 $.extend(settings
, ($.isFunction(options
) ? arguments
[1] : options
) || {});
974 if (!settings
.buttons
&& $.isPlainObject(settings
.options
)) {
975 $.each(settings
.options
, function(op
, label
) {
979 icons
: {primary
: op
=== 'no' ? 'ui-icon-close' : 'ui-icon-check'},
981 var event
= $.Event('crmConfirm:' + op
);
982 $(this).trigger(event
);
983 if (!event
.isDefaultPrevented()) {
984 dialog
.dialog('close');
989 // Order buttons so that "no" goes on the right-hand side
990 settings
.buttons
= _
.sortBy(buttons
, 'data-op').reverse();
993 msg
= url
? '' : settings
.message
;
994 delete settings
.options
;
995 delete settings
.message
;
997 dialog
= $('<div class="crm-confirm-dialog"></div>').html(msg
|| '').dialog(settings
);
998 if ($.isFunction(options
)) {
999 dialog
.on('crmConfirm:yes', options
);
1002 CRM
.loadPage(url
, {target
: dialog
});
1005 dialog
.trigger('crmLoad');
1010 /** provides a local copy of ts for a domain */
1011 CRM
.ts = function(domain
) {
1012 return function(message
, options
) {
1014 options
= $.extend(options
|| {}, {domain
: domain
});
1016 return ts(message
, options
);
1020 CRM
.addStrings = function(domain
, strings
) {
1021 var bucket
= (domain
== 'civicrm' ? 'strings' : 'strings::' + domain
);
1022 CRM
[bucket
] = CRM
[bucket
] || {};
1023 _
.extend(CRM
[bucket
], strings
);
1027 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
1029 $.fn
.crmError = function (text
, title
, options
) {
1030 title
= title
|| '';
1032 options
= options
|| {};
1037 if ($(this).length
) {
1039 var label
= $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]').not('[generated=true]');
1041 label
.addClass('crm-error');
1042 var $label
= label
.clone();
1043 if (text
== '' && $('.crm-marker', $label
).length
> 0) {
1044 text
= $('.crm-marker', $label
).attr('title');
1046 $('.crm-marker', $label
).remove();
1047 title
= $label
.text();
1050 $(this).addClass('crm-error');
1052 var msg
= CRM
.alert(text
, title
, 'error', $.extend(extra
, options
));
1053 if ($(this).length
) {
1055 setTimeout(function () {
1056 ele
.one('change', function () {
1057 if (msg
&& msg
.close
) msg
.close();
1058 ele
.removeClass('error');
1059 label
.removeClass('crm-error');
1066 // Display system alerts through js notifications
1067 function messagesFromMarkup() {
1068 $('div.messages:visible', this).not('.help').not('.no-popup').each(function () {
1069 var text
, title
= '';
1070 $(this).removeClass('status messages');
1071 var type
= $(this).attr('class').split(' ')[0] || 'alert';
1072 type
= type
.replace('crm-', '');
1073 $('.icon', this).remove();
1074 if ($('.msg-text', this).length
> 0) {
1075 text
= $('.msg-text', this).html();
1076 title
= $('.msg-title', this).html();
1079 text
= $(this).html();
1081 var options
= $(this).data('options') || {};
1083 // Duplicates were already removed server-side
1084 options
.unique
= false;
1085 CRM
.alert(text
, title
, type
, options
);
1087 // Handle qf form errors
1088 $('form :input.error', this).one('blur', function() {
1089 $('.ui-notify-message.error a.ui-notify-close').click();
1090 $(this).removeClass('error');
1091 $(this).next('span.crm-error').remove();
1092 $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]')
1093 .removeClass('crm-error')
1094 .find('.crm-error').removeClass('crm-error');
1099 * Improve blockUI when used with jQuery dialog
1101 var originalBlock
= $.fn
.block
,
1102 originalUnblock
= $.fn
.unblock
;
1104 $.fn
.block = function(opts
) {
1105 if ($(this).is('.ui-dialog-content')) {
1106 originalBlock
.call($(this).parents('.ui-dialog'), opts
);
1109 return originalBlock
.call(this, opts
);
1111 $.fn
.unblock = function(opts
) {
1112 if ($(this).is('.ui-dialog-content')) {
1113 originalUnblock
.call($(this).parents('.ui-dialog'), opts
);
1116 return originalUnblock
.call(this, opts
);
1119 // Preprocess all CRM ajax calls to display messages
1120 $(document
).ajaxSuccess(function(event
, xhr
, settings
) {
1122 if ((!settings
.dataType
|| settings
.dataType
== 'json') && xhr
.responseText
) {
1123 var response
= $.parseJSON(xhr
.responseText
);
1124 if (typeof(response
.crmMessages
) == 'object') {
1125 $.each(response
.crmMessages
, function(n
, msg
) {
1126 CRM
.alert(msg
.text
, msg
.title
, msg
.type
, msg
.options
);
1129 if (response
.backtrace
) {
1130 CRM
.console('log', response
.backtrace
);
1132 if (typeof response
.deprecated
=== 'string') {
1133 CRM
.console('warn', response
.deprecated
);
1137 // Ignore errors thrown by parseJSON
1142 $.blockUI
.defaults
.message
= null;
1143 $.blockUI
.defaults
.ignoreIfBlocked
= true;
1145 if ($('#crm-container').hasClass('crm-public')) {
1146 $.fn
.select2
.defaults
.dropdownCssClass
= $.ui
.dialog
.prototype.options
.dialogClass
= 'crm-container crm-public';
1149 // Trigger crmLoad on initial content for consistency. It will also be triggered for ajax-loaded content.
1150 $('.crm-container').trigger('crmLoad');
1152 if ($('#crm-notification-container').length
) {
1153 // Initialize notifications
1154 $('#crm-notification-container').notify();
1155 messagesFromMarkup
.call($('#crm-container'));
1159 // bind the event for image popup
1160 .on('click', 'a.crm-image-popup', function(e
) {
1162 title
: ts('Preview'),
1164 message
: '<div class="crm-custom-image-popup"><img style="max-width: 100%" src="' + $(this).attr('href') + '"></div>',
1170 .on('click', function (event
) {
1171 $('.btn-slide-active').removeClass('btn-slide-active').find('.panel').hide();
1172 if ($(event
.target
).is('.btn-slide')) {
1173 $(event
.target
).addClass('btn-slide-active').find('.panel').show();
1177 // Handle clear button for form elements
1178 .on('click', 'a.crm-clear-link', function() {
1179 $(this).css({visibility
: 'hidden'}).siblings('.crm-form-radio:checked').prop('checked', false).change();
1180 $(this).siblings('input:text').val('').change();
1183 .on('change', 'input.crm-form-radio:checked', function() {
1184 $(this).siblings('.crm-clear-link').css({visibility
: ''});
1187 // Allow normal clicking of links within accordions
1188 .on('click.crmAccordions', 'div.crm-accordion-header a', function (e
) {
1189 e
.stopPropagation();
1191 // Handle accordions
1192 .on('click.crmAccordions', '.crm-accordion-header, .crm-collapsible .collapsible-title', function (e
) {
1193 if ($(this).parent().hasClass('collapsed')) {
1194 $(this).next().css('display', 'none').slideDown(200);
1197 $(this).next().css('display', 'block').slideUp(200);
1199 $(this).parent().toggleClass('collapsed');
1208 $.fn
.crmAccordions = function () {
1209 CRM
.console('warn', 'Warning: $.crmAccordions was called. This function is deprecated and should not be used.');
1212 * Collapse or expand an accordion
1215 $.fn
.crmAccordionToggle = function (speed
) {
1216 $(this).each(function () {
1217 if ($(this).hasClass('collapsed')) {
1218 $('.crm-accordion-body', this).first().css('display', 'none').slideDown(speed
);
1221 $('.crm-accordion-body', this).first().css('display', 'block').slideUp(speed
);
1223 $(this).toggleClass('collapsed');
1228 * Clientside currency formatting
1229 * @param number value
1230 * @param [optional] string format - currency representation of the number 1234.56
1233 var currencyTemplate
;
1234 CRM
.formatMoney = function(value
, format
) {
1235 var decimal, separator
, sign
, i
, j
, result
;
1236 if (value
=== 'init' && format
) {
1237 currencyTemplate
= format
;
1240 format
= format
|| currencyTemplate
;
1241 result
= /1(.?)234(.?)56/.exec(format
);
1242 if (result
=== null) {
1243 return 'Invalid format passed to CRM.formatMoney';
1245 separator
= result
[1];
1246 decimal = result
[2];
1247 sign
= (value
< 0) ? '-' : '';
1248 //extracting the absolute value of the integer part of the number and converting to string
1249 i
= parseInt(value
= Math
.abs(value
).toFixed(2)) + '';
1250 j
= ((j
= i
.length
) > 3) ? j
% 3 : 0;
1251 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) : '');
1252 return format
.replace(/1.*234.*56/, result
);
1255 CRM
.console = function(method
, title
, msg
) {
1256 if (window
.console
) {
1257 method
= $.isFunction(console
[method
]) ? method
: 'log';
1258 if (msg
=== undefined) {
1259 return console
[method
](title
);
1261 return console
[method
](title
, msg
);