1 // https://civicrm.org/licensing
4 var cj
= CRM
.$ = jQuery
;
8 * Short-named function for string translation, defined in global scope so it's available everywhere.
10 * @param text string for translating
11 * @param params object key:value of additional parameters
15 function ts(text
, params
) {
17 var d
= (params
&& params
.domain
) ? ('strings::' + params
.domain
) : null;
18 if (d
&& CRM
[d
] && CRM
[d
][text
]) {
21 else if (CRM
.strings
[text
]) {
22 text
= CRM
.strings
[text
];
24 if (typeof(params
) === 'object') {
25 for (var i
in params
) {
26 if (typeof(params
[i
]) === 'string' || typeof(params
[i
]) === 'number') {
27 // sprintf emulation: escape % characters in the replacements to avoid conflicts
28 text
= text
.replace(new RegExp('%' + i
, 'g'), String(params
[i
]).replace(/%/g
, '%-crmescaped-'));
31 return text
.replace(/%-crmescaped-/g, '%');
36 // Legacy code - ignore warnings
37 /* jshint ignore:start */
40 * This function is called by default at the bottom of template files which have forms that have
41 * conditionally displayed/hidden sections and elements. The PHP is responsible for generating
42 * a list of 'blocks to show' and 'blocks to hide' and the template passes these parameters to
46 * @param showBlocks Array of element Id's to be displayed
47 * @param hideBlocks Array of element Id's to be hidden
48 * @param elementType Value to set display style to for showBlocks (e.g. 'block' or 'table-row' or ...)
50 function on_load_init_blocks(showBlocks
, hideBlocks
, elementType
) {
51 if (elementType
== null) {
52 elementType
= 'block';
57 /* This loop is used to display the blocks whose IDs are present within the showBlocks array */
58 for (i
= 0; i
< showBlocks
.length
; i
++) {
59 myElement
= document
.getElementById(showBlocks
[i
]);
60 /* getElementById returns null if element id doesn't exist in the document */
61 if (myElement
!= null) {
62 myElement
.style
.display
= elementType
;
65 alert('showBlocks array item not in .tpl = ' + showBlocks
[i
]);
69 /* This loop is used to hide the blocks whose IDs are present within the hideBlocks array */
70 for (i
= 0; i
< hideBlocks
.length
; i
++) {
71 myElement
= document
.getElementById(hideBlocks
[i
]);
72 /* getElementById returns null if element id doesn't exist in the document */
73 if (myElement
!= null) {
74 myElement
.style
.display
= 'none';
77 alert('showBlocks array item not in .tpl = ' + hideBlocks
[i
]);
83 * This function is called when we need to show or hide a related form element (target_element)
84 * based on the value (trigger_value) of another form field (trigger_field).
87 * @param trigger_field_id HTML id of field whose onchange is the trigger
88 * @param trigger_value List of integers - option value(s) which trigger show-element action for target_field
89 * @param target_element_id HTML id of element to be shown or hidden
90 * @param target_element_type Type of element to be shown or hidden ('block' or 'table-row')
91 * @param field_type Type of element radio/select
92 * @param invert Boolean - if true, we HIDE target on value match; if false, we SHOW target on value match
94 function showHideByValue(trigger_field_id
, trigger_value
, target_element_id
, target_element_type
, field_type
, invert
) {
97 if (field_type
== 'select') {
98 var trigger
= trigger_value
.split("|");
99 var selectedOptionValue
= cj('#' + trigger_field_id
).val();
101 target
= target_element_id
.split("|");
102 for (j
= 0; j
< target
.length
; j
++) {
104 cj('#' + target
[j
]).show();
107 cj('#' + target
[j
]).hide();
109 for (var i
= 0; i
< trigger
.length
; i
++) {
110 if (selectedOptionValue
== trigger
[i
]) {
112 cj('#' + target
[j
]).hide();
115 cj('#' + target
[j
]).show();
123 if (field_type
== 'radio') {
124 target
= target_element_id
.split("|");
125 for (j
= 0; j
< target
.length
; j
++) {
126 if (cj('[name="' + trigger_field_id
+ '"]:first').is(':checked')) {
128 cj('#' + target
[j
]).hide();
131 cj('#' + target
[j
]).show();
136 cj('#' + target
[j
]).show();
139 cj('#' + target
[j
]).hide();
148 * Function to change button text and disable one it is clicked
150 * @param obj object - the button clicked
151 * @param formID string - the id of the form being submitted
152 * @param string procText - button text after user clicks it
156 /* Changes button label on submit, and disables button after submit for newer browsers.
157 Puts up alert for older browsers. */
158 function submitOnce(obj
, formId
, procText
) {
159 // if named button clicked, change text
160 if (obj
.value
!= null) {
161 obj
.value
= procText
+ " ...";
163 cj(obj
).closest('form').attr('data-warn-changes', 'false');
164 if (document
.getElementById
) { // disable submit button for newer browsers
166 document
.getElementById(formId
).submit();
169 else { // for older browsers
170 if (submitcount
== 0) {
175 alert("Your request is currently being processed ... Please wait.");
182 * Function to show / hide the row in optionFields
184 * @param index string, element whose innerHTML is to hide else will show the hidden row.
186 function showHideRow(index
) {
188 cj('tr#optionField_' + index
).hide();
189 if (cj('table#optionField tr:hidden:first').length
) {
190 cj('div#optionFieldLink').show();
194 cj('table#optionField tr:hidden:first').show();
195 if (!cj('table#optionField tr:hidden:last').length
) {
196 cj('div#optionFieldLink').hide();
202 /* jshint ignore:end */
204 CRM
.utils
= CRM
.utils
|| {};
205 CRM
.strings
= CRM
.strings
|| {};
207 (function ($, _
, undefined) {
209 /* jshint validthis: true */
211 // Theme classes for unattached elements
212 $.fn
.select2
.defaults
.dropdownCssClass
= $.ui
.dialog
.prototype.options
.dialogClass
= 'crm-container';
214 // https://github.com/ivaynberg/select2/pull/2090
215 $.fn
.select2
.defaults
.width
= 'resolve';
217 // Workaround for https://github.com/ivaynberg/select2/issues/1246
218 $.ui
.dialog
.prototype._allowInteraction = function(e
) {
219 return !!$(e
.target
).closest('.ui-dialog, .ui-datepicker, .select2-drop, .cke_dialog').length
;
222 // Implements jQuery hook.prop
223 $.propHooks
.disabled
= {
224 set: function (el
, value
, name
) {
225 // Sync button enabled status with wrapper css
226 if ($(el
).is('span.crm-button > input.crm-form-submit')) {
227 $(el
).parent().toggleClass('crm-button-disabled', !!value
);
229 // Sync button enabled status with dialog button
230 if ($(el
).is('.ui-dialog input.crm-form-submit')) {
231 $(el
).closest('.ui-dialog').find('.ui-dialog-buttonset button[data-identifier='+ $(el
).attr('name') +']').prop('disabled', !!value
);
237 * Populate a select list, overwriting the existing options except for the placeholder.
238 * @param select jquery selector - 1 or more select elements
239 * @param options array in format returned by api.getoptions
240 * @param placeholder string|bool - new placeholder or false (default) to keep the old one
241 * @param value string|array - will silently update the element with new value without triggering change
243 CRM
.utils
.setOptions = function(select
, options
, placeholder
, value
) {
244 $(select
).each(function() {
247 val
= value
|| $elect
.val() || [],
248 opts
= placeholder
|| placeholder
=== '' ? '' : '[value!=""]';
249 $elect
.find('option' + opts
).remove();
250 var newOptions
= CRM
.utils
.renderOptions(options
, val
);
251 if (typeof placeholder
=== 'string') {
252 if ($elect
.is('[multiple]')) {
253 select
.attr('placeholder', placeholder
);
255 newOptions
= '<option value="">' + placeholder
+ '</option>' + newOptions
;
258 $elect
.append(newOptions
);
260 $elect
.trigger('crmOptionsUpdated', $.extend({}, options
)).trigger('change');
266 * Render an option list
267 * @param options {array}
268 * @param val {string} default value
269 * @param escapeHtml {bool}
272 CRM
.utils
.renderOptions = function(options
, val
, escapeHtml
) {
274 esc
= escapeHtml
=== false ? _
.identity
: _
.escape
;
275 if (!$.isArray(val
)) {
278 _
.each(options
, function(option
) {
279 if (option
.children
) {
280 rendered
+= '<optgroup label="' + esc(option
.value
) + '">' +
281 CRM
.utils
.renderOptions(option
.children
, val
) +
284 var selected
= ($.inArray('' + option
.key
, val
) > -1) ? 'selected="selected"' : '';
285 rendered
+= '<option value="' + esc(option
.key
) + '"' + selected
+ '>' + esc(option
.value
) + '</option>';
291 function chainSelect() {
292 var $form
= $(this).closest('form'),
293 $target
= $('select[data-name="' + $(this).data('target') + '"]', $form
),
294 data
= $target
.data(),
296 $target
.prop('disabled', true);
297 if ($target
.is('select.crm-chain-select-control')) {
298 $('select[data-name="' + $target
.data('target') + '"]', $form
).prop('disabled', true).blur();
300 if (!(val
&& val
.length
)) {
301 CRM
.utils
.setOptions($target
.blur(), [], data
.emptyPrompt
);
303 $target
.addClass('loading');
304 $.getJSON(CRM
.url(data
.callback
), {_value
: val
}, function(vals
) {
305 $target
.prop('disabled', false).removeClass('loading');
306 CRM
.utils
.setOptions($target
, vals
|| [], (vals
&& vals
.length
? data
.selectPrompt
: data
.nonePrompt
));
312 * Compare Form Input values against cached initial value.
314 * @return {Boolean} true if changes have been made.
316 CRM
.utils
.initialValueChanged = function(el
) {
318 $(':input:visible, .select2-container:visible+:input.select2-offscreen', el
).not('[type=submit], [type=button], .crm-action-menu').each(function () {
319 var initialValue
= $(this).data('crm-initial-value');
320 // skip change of value for submit buttons
321 if (initialValue
!== undefined && !_
.isEqual(initialValue
, $(this).val())) {
329 * This provides defaults for ui.dialog which either need to be calculated or are different from global defaults
334 CRM
.utils
.adjustDialogDefaults = function(settings
) {
335 settings
= $.extend({width
: '65%', height
: '65%', modal
: true}, settings
|| {});
336 // Support relative height
337 if (typeof settings
.height
=== 'string' && settings
.height
.indexOf('%') > 0) {
338 settings
.height
= parseInt($(window
).height() * (parseFloat(settings
.height
)/100), 10);
340 // Responsive adjustment - increase percent width on small screens
341 if (typeof settings
.width
=== 'string' && settings
.width
.indexOf('%') > 0) {
342 var screenWidth
= $(window
).width(),
343 percentage
= parseInt(settings
.width
.replace('%', ''), 10),
344 gap
= 100-percentage
;
345 if (screenWidth
< 701) {
346 settings
.width
= '100%';
348 else if (screenWidth
< 1400) {
349 settings
.width
= '' + parseInt(percentage
+gap
-((screenWidth
- 700)/7*(gap)/100), 10) + '%';
356 * Wrapper for select2 initialization function; supplies defaults
357 * @param options object
359 $.fn
.crmSelect2 = function(options
) {
360 return $(this).each(function () {
363 settings
= {allowClear
: !$el
.hasClass('required')};
364 // quickform doesn't support optgroups so here's a hack :(
365 $('option[value^=crm_optgroup]', this).each(function () {
366 $(this).nextUntil('option[value^=crm_optgroup]').wrapAll('<optgroup label="' + $(this).text() + '" />');
370 // quickform does not support disabled option, so yet another hack to
371 // add disabled property for option values
372 $('option[value^=crm_disabled_opt]', this).attr('disabled', 'disabled');
374 // Defaults for single-selects
375 if ($el
.is('select:not([multiple])')) {
376 settings
.minimumResultsForSearch
= 10;
377 if ($('option:first', this).val() === '') {
378 settings
.placeholderOption
= 'first';
381 $.extend(settings
, $el
.data('select-params') || {}, options
|| {});
383 $el
.addClass('crm-ajax-select');
385 $el
.select2(settings
);
390 * @see CRM_Core_Form::addEntityRef for docs
391 * @param options object
393 $.fn
.crmEntityRef = function(options
) {
394 options
= options
|| {};
395 options
.select
= options
.select
|| {};
396 return $(this).each(function() {
398 $el
= $(this).off('.crmEntity'),
399 entity
= options
.entity
|| $el
.data('api-entity') || 'contact',
401 $el
.data('api-entity', entity
);
402 $el
.data('select-params', $.extend({}, $el
.data('select-params') || {}, options
.select
));
403 $el
.data('api-params', $.extend({}, $el
.data('api-params') || {}, options
.api
));
404 $el
.data('create-links', options
.create
|| $el
.data('create-links'));
405 $el
.addClass('crm-form-entityref crm-' + entity
.toLowerCase() + '-ref');
407 // Use select2 ajax helper instead of CRM.api3 because it provides more value
409 url
: CRM
.url('civicrm/ajax/rest'),
410 data: function (input
, page_num
) {
411 var params
= getEntityRefApiParams($el
);
412 params
.input
= input
;
413 params
.page_num
= page_num
;
415 entity
: $el
.data('api-entity'),
417 json
: JSON
.stringify(params
)
420 results: function(data
) {
421 return {more
: data
.more_results
, results
: data
.values
|| []};
424 minimumInputLength
: 1,
425 formatResult
: CRM
.utils
.formatSelect2Result
,
426 formatSelection: function(row
) {
429 escapeMarkup: function (m
) {return m
;},
430 initSelection: function($el
, callback
) {
432 multiple
= !!$el
.data('select-params').multiple
,
434 stored
= $el
.data('entity-value') || [];
438 // If we already have this data, just return it
439 if (!_
.xor(val
.split(','), _
.pluck(stored
, 'id')).length
) {
440 callback(multiple
? stored
: stored
[0]);
442 var params
= $.extend({}, $el
.data('api-params') || {}, {id
: val
});
443 CRM
.api3($el
.data('api-entity'), 'getlist', params
).done(function(result
) {
444 callback(multiple
? result
.values
: result
.values
[0]);
445 // Trigger change (store data to avoid an infinite loop of lookups)
446 $el
.data('entity-value', result
.values
).trigger('change');
451 // Create new items inline - works for tags
452 if ($el
.data('create-links') && entity
.toLowerCase() === 'tag') {
453 selectParams
.createSearchChoice = function(term
, data
) {
454 if (!_
.findKey(data
, {label
: term
})) {
455 return {id
: "0", term
: term
, label
: term
+ ' (' + ts('new tag') + ')'};
458 selectParams
.tokenSeparators
= [','];
459 selectParams
.createSearchChoicePosition
= 'bottom';
460 $el
.on('select2-selecting.crmEntity', function(e
) {
463 e
.object
.label
= e
.object
.term
;
464 CRM
.api3(entity
, 'create', $.extend({name
: e
.object
.term
}, $el
.data('api-params').params
|| {}))
465 .done(function(created
) {
467 val
= $el
.select2('val'),
468 data
= $el
.select2('data'),
469 item
= {id
: created
.id
, label
: e
.object
.term
};
471 $el
.select2('data', item
, true);
473 else if ($.isArray(val
) && $.inArray("0", val
) > -1) {
474 _
.remove(data
, {id
: "0"});
476 $el
.select2('data', data
, true);
483 selectParams
.formatInputTooShort = function() {
484 var txt
= $el
.data('select-params').formatInputTooShort
|| $.fn
.select2
.defaults
.formatInputTooShort
.call(this);
485 txt
+= renderEntityRefFilters($el
) + renderEntityRefCreateLinks($el
);
488 selectParams
.formatNoMatches = function() {
489 var txt
= $el
.data('select-params').formatNoMatches
|| $.fn
.select2
.defaults
.formatNoMatches
;
490 txt
+= renderEntityRefFilters($el
) + renderEntityRefCreateLinks($el
);
493 $el
.on('select2-open.crmEntity', function() {
495 loadEntityRefFilterOptions($el
);
498 .on('click.crmEntity', 'a.crm-add-entity', function(e
) {
499 $el
.select2('close');
500 CRM
.loadForm($(this).attr('href'), {
501 dialog
: {width
: 500, height
: 'auto'}
502 }).on('crmFormSuccess', function(e
, data
) {
503 if (data
.status
=== 'success' && data
.id
) {
504 CRM
.status(ts('%1 Created', {1: data
.label
}));
505 if ($el
.select2('container').hasClass('select2-container-multi')) {
506 var selection
= $el
.select2('data');
507 selection
.push(data
);
508 $el
.select2('data', selection
, true);
510 $el
.select2('data', data
, true);
516 .on('change.crmEntity', 'select.crm-entityref-filter-value', function() {
517 var filter
= $el
.data('user-filter') || {};
518 filter
.value
= $(this).val();
519 $(this).toggleClass('active', !!filter
.value
);
520 $el
.data('user-filter', filter
);
522 // Once a filter has been chosen, rerender create links and refocus the search box
523 $el
.select2('close');
527 .on('change.crmEntity', 'select.crm-entityref-filter-key', function() {
528 var filter
= $el
.data('user-filter') || {};
529 filter
.key
= $(this).val();
530 $(this).toggleClass('active', !!filter
.key
);
531 $el
.data('user-filter', filter
);
532 loadEntityRefFilterOptions($el
);
536 $el
.crmSelect2($.extend(settings
, $el
.data('select-params'), selectParams
));
541 * Combine api-params with user-filter
545 function getEntityRefApiParams($el
) {
547 params
= $.extend({params
: {}}, $el
.data('api-params') || {}),
548 // Prevent original data from being modified - $.extend and _.clone don't cut it, they pass nested objects by reference!
549 combined
= _
.cloneDeep(params
),
550 filter
= $.extend({}, $el
.data('user-filter') || {});
551 if (filter
.key
&& filter
.value
) {
552 // Special case for contact type/sub-type combo
553 if (filter
.key
=== 'contact_type' && (filter
.value
.indexOf('__') > 0)) {
554 combined
.params
.contact_type
= filter
.value
.split('__')[0];
555 combined
.params
.contact_sub_type
= filter
.value
.split('__')[1];
557 // Allow json-encoded api filters e.g. {"BETWEEN":[123,456]}
558 combined
.params
[filter
.key
] = filter
.value
.charAt(0) === '{' ? $.parseJSON(filter
.value
) : filter
.value
;
564 CRM
.utils
.formatSelect2Result = function (row
) {
565 var markup
= '<div class="crm-select2-row">';
566 if (row
.image
!== undefined) {
567 markup
+= '<div class="crm-select2-image"><img src="' + row
.image
+ '"/></div>';
569 else if (row
.icon_class
) {
570 markup
+= '<div class="crm-select2-icon"><div class="crm-icon ' + row
.icon_class
+ '-icon"></div></div>';
572 markup
+= '<div><div class="crm-select2-row-label '+(row
.label_class
|| '')+'">' + row
.label
+ '</div>';
573 markup
+= '<div class="crm-select2-row-description">';
574 $.each(row
.description
|| [], function(k
, text
) {
575 markup
+= '<p>' + text
+ '</p>';
577 markup
+= '</div></div></div>';
581 function renderEntityRefCreateLinks($el
) {
583 createLinks
= $el
.data('create-links'),
584 params
= getEntityRefApiParams($el
).params
,
585 markup
= '<div class="crm-entityref-links">';
586 if (!createLinks
|| $el
.data('api-entity').toLowerCase() !== 'contact') {
589 if (createLinks
=== true) {
590 createLinks
= params
.contact_type
? _
.where(CRM
.config
.entityRef
.contactCreate
, {type
: params
.contact_type
}) : CRM
.config
.entityRef
.contactCreate
;
592 _
.each(createLinks
, function(link
) {
593 markup
+= ' <a class="crm-add-entity crm-hover-button" href="' + link
.url
+ '">';
595 markup
+= '<span class="icon ' + link
.type
+ '-profile-icon"></span> ';
597 markup
+= link
.label
+ '</a>';
603 function getEntityRefFilters($el
) {
605 entity
= $el
.data('api-entity').toLowerCase(),
606 filters
= $.extend([], CRM
.config
.entityRef
.filters
[entity
] || []),
607 filter
= $el
.data('user-filter') || {},
608 params
= $.extend({params
: {}}, $el
.data('api-params') || {}).params
,
610 $.each(filters
, function() {
611 if (typeof params
[this.key
] === 'undefined') {
614 else if (this.key
== 'contact_type' && typeof params
.contact_sub_type
=== 'undefined') {
615 this.options
= _
.remove(this.options
, function(option
) {
616 return option
.key
.indexOf(params
.contact_type
+ '__') === 0;
624 function renderEntityRefFilters($el
) {
626 filters
= getEntityRefFilters($el
),
627 filter
= $el
.data('user-filter') || {},
628 filterSpec
= filter
.key
? _
.find(filters
, {key
: filter
.key
}) : null;
629 if (!filters
.length
) {
632 var markup
= '<div class="crm-entityref-filters">' +
633 '<select class="crm-entityref-filter-key' + (filter
.key
? ' active' : '') + '">' +
634 '<option value="">' + ts('Refine search...') + '</option>' +
635 CRM
.utils
.renderOptions(filters
, filter
.key
) +
636 '</select> ' +
637 '<select class="crm-entityref-filter-value' + (filter
.key
? ' active"' : '"') + (filter
.key
? '' : ' style="display:none;"') + '>' +
638 '<option value="">' + ts('- select -') + '</option>';
639 if (filterSpec
&& filterSpec
.options
) {
640 markup
+= CRM
.utils
.renderOptions(filterSpec
.options
, filter
.value
);
642 markup
+= '</select></div>';
647 * Fetch options for a filter (via ajax if necessary) and populate the appropriate select list
650 function loadEntityRefFilterOptions($el
) {
652 filters
= getEntityRefFilters($el
),
653 filter
= $el
.data('user-filter') || {},
654 filterSpec
= filter
.key
? _
.find(filters
, {key
: filter
.key
}) : null,
655 $valField
= $('.crm-entityref-filter-value', '#select2-drop');
657 $valField
.show().val('');
658 if (filterSpec
.options
) {
659 CRM
.utils
.setOptions($valField
, filterSpec
.options
, false, filter
.value
);
661 $valField
.prop('disabled', true);
662 CRM
.api3(filterSpec
.entity
|| $el
.data('api-entity'), 'getoptions', {field
: filter
.key
, context
: 'search', sequential
: 1})
663 .done(function(result
) {
664 var entity
= $el
.data('api-entity').toLowerCase(),
665 globalFilterSpec
= _
.find(CRM
.config
.entityRef
.filters
[entity
], {key
: filter
.key
}) || {};
666 // Store options globally so we don't have to look them up again
667 globalFilterSpec
.options
= result
.values
;
668 $valField
.prop('disabled', false);
669 CRM
.utils
.setOptions($valField
, result
.values
);
670 $valField
.val(filter
.value
|| '');
678 //CRM-15598 - Override url validator method to allow relative url's (e.g. /index.htm)
679 $.validator
.addMethod("url", function(value
, element
) {
680 if (/^\//.test(value
)) {
681 // Relative url: prepend dummy path for validation.
682 value
= 'http://domain.tld' + value
;
684 // From jQuery Validation Plugin v1.12.0
685 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
);
689 * Wrapper for jQuery validate initialization function; supplies defaults
691 $.fn
.crmValidate = function(params
) {
692 return $(this).each(function () {
694 settings
= $.extend({}, CRM
.validate
._defaults
, CRM
.validate
.params
);
695 $(this).validate(settings
);
696 // Call any post-initialization callbacks
697 if (CRM
.validate
.functions
&& CRM
.validate
.functions
.length
) {
698 $.each(CRM
.validate
.functions
, function(i
, func
) {
705 // Initialize widgets
707 .on('crmLoad', function(e
) {
708 $('table.row-highlight', e
.target
)
709 .off('.rowHighlight')
710 .on('change.rowHighlight', 'input.select-row, input.select-rows', function (e
, data
) {
711 var filter
, $table
= $(this).closest('table');
712 if ($(this).hasClass('select-rows')) {
713 filter
= $(this).prop('checked') ? ':not(:checked)' : ':checked';
714 $('input.select-row' + filter
, $table
).prop('checked', $(this).prop('checked')).trigger('change', 'master-selected');
717 $(this).closest('tr').toggleClass('crm-row-selected', $(this).prop('checked'));
718 if (data
!== 'master-selected') {
719 $('input.select-rows', $table
).prop('checked', $(".select-row:not(':checked')", $table
).length
< 1);
723 .find('input.select-row:checked').parents('tr').addClass('crm-row-selected');
724 if ($("input:radio[name=radio_ts]").size() == 1) {
725 $("input:radio[name=radio_ts]").prop("checked", true);
727 $('.crm-select2:not(.select2-offscreen, .select2-container)', e
.target
).crmSelect2();
728 $('.crm-form-entityref:not(.select2-offscreen, .select2-container)', e
.target
).crmEntityRef();
729 $('select.crm-chain-select-control', e
.target
).off('.chainSelect').on('change.chainSelect', chainSelect
);
730 // Cache Form Input initial values
731 $('form[data-warn-changes] :input', e
.target
).each(function() {
732 $(this).data('crm-initial-value', $(this).val());
735 .on('dialogopen', function(e
) {
736 var $el
= $(e
.target
);
737 // Modal dialogs should disable scrollbars
738 if ($el
.dialog('option', 'modal')) {
739 $el
.addClass('modal-dialog');
740 $('body').css({overflow
: 'hidden'});
743 if ($el
.parent().hasClass('crm-container') && $el
.dialog('option', 'resizable')) {
744 $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}));
745 $('.crm-dialog-titlebar-resize', $el
.parent()).click(function(e
) {
746 if ($el
.data('origSize')) {
747 $el
.dialog('option', $el
.data('origSize'));
748 $el
.data('origSize', null);
750 var menuHeight
= $('#civicrm-menu').outerHeight();
751 $el
.data('origSize', {
752 position
: {my
: 'center', at
: 'center center+' + (menuHeight
/ 2), of: window
},
753 width
: $el
.dialog('option', 'width'),
754 height
: $el
.dialog('option', 'height')
756 $el
.dialog('option', {width
: '100%', height
: ($(window
).height() - menuHeight
), position
: {my
: "top", at
: "top+"+menuHeight
, of: window
}});
758 $el
.trigger('dialogresize');
763 .on('dialogclose', function(e
) {
764 // Restore scrollbars when closing modal
765 if ($('.ui-dialog .modal-dialog:visible').not(e
.target
).length
< 1) {
766 $('body').css({overflow
: ''});
769 .on('submit', function(e
) {
770 // CRM-14353 - disable changes warn when submitting a form
771 $('[data-warn-changes]').attr('data-warn-changes', 'false');
775 // CRM-14353 - Warn of unsaved changes for forms which have opted in
776 window
.onbeforeunload = function() {
777 if (CRM
.utils
.initialValueChanged($('form[data-warn-changes=true]:visible'))) {
778 return ts('You have unsaved changes.');
783 * Function to make multiselect boxes behave as fields in small screens
785 function advmultiselectResize() {
786 var amswidth
= $("#crm-container form:has(table.advmultiselect)").width();
787 if (amswidth
< 700) {
788 $("form table.advmultiselect td").css('display', 'block');
791 $("form table.advmultiselect td").css('display', 'table-cell');
793 var contactwidth
= $('#crm-container #mainTabContainer').width();
794 if (contactwidth
< 600) {
795 $('#crm-container #mainTabContainer').addClass('narrowpage');
796 $('#crm-container #mainTabContainer.narrowpage #contactTopBar td').each(function (index
) {
798 if (index
% 2 === 0) {
799 $(this).parent().after('<tr class="narrowadded"></tr>');
802 $(this).parent().next().append(item
);
807 $('#crm-container #mainTabContainer.narrowpage').removeClass('narrowpage');
808 $('#crm-container #mainTabContainer #contactTopBar tr.narrowadded td').each(function () {
810 var parent
= $(this).parent();
811 $(this).parent().prev().append(nitem
);
812 if (parent
.children().size() === 0) {
816 $('#crm-container #mainTabContainer.narrowpage #contactTopBar tr.added').detach();
818 var cformwidth
= $('#crm-container #Contact .contact_basic_information-section').width();
820 if (cformwidth
< 720) {
821 $('#crm-container .contact_basic_information-section').addClass('narrowform');
822 $('#crm-container .contact_basic_information-section table.form-layout-compressed td .helpicon').parent().addClass('hashelpicon');
823 if (cformwidth
< 480) {
824 $('#crm-container .contact_basic_information-section').addClass('xnarrowform');
827 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
831 $('#crm-container .contact_basic_information-section.narrowform').removeClass('narrowform');
832 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
836 advmultiselectResize();
837 $(window
).resize(advmultiselectResize
);
839 $.fn
.crmtooltip = function () {
841 .on('mouseover', 'a.crm-summary-link:not(.crm-processed)', function (e
) {
842 $(this).addClass('crm-processed');
843 $(this).addClass('crm-tooltip-active');
844 var topDistance
= e
.pageY
- $(window
).scrollTop();
845 if (topDistance
< 300 || topDistance
< $(this).children('.crm-tooltip-wrapper').height()) {
846 $(this).addClass('crm-tooltip-down');
848 if (!$(this).children('.crm-tooltip-wrapper').length
) {
849 $(this).append('<div class="crm-tooltip-wrapper"><div class="crm-tooltip"></div></div>');
850 $(this).children().children('.crm-tooltip')
851 .html('<div class="crm-loading-element"></div>')
855 .on('mouseout', 'a.crm-summary-link', function () {
856 $(this).removeClass('crm-processed');
857 $(this).removeClass('crm-tooltip-active crm-tooltip-down');
859 .on('click', 'a.crm-summary-link', false);
862 var helpDisplay
, helpPrevious
;
863 CRM
.help = function (title
, params
, url
) {
864 if (helpDisplay
&& helpDisplay
.close
) {
865 // If the same link is clicked twice, just close the display - todo use underscore method for this comparison
866 if (helpDisplay
.isOpen
&& helpPrevious
=== JSON
.stringify(params
)) {
872 helpPrevious
= JSON
.stringify(params
);
873 params
.class_name
= 'CRM_Core_Page_Inline_Help';
874 params
.type
= 'page';
875 helpDisplay
= CRM
.alert('...', title
, 'crm-help crm-msg-loading', {expires
: 0});
876 $.ajax(url
|| CRM
.url('civicrm/ajax/inline'),
880 success: function (data
) {
881 $('#crm-notification-container .crm-help .notify-content:last').html(data
);
882 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('info');
885 $('#crm-notification-container .crm-help .notify-content:last').html('Unable to load help file.');
886 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('error');
892 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
894 CRM
.status = function(options
, deferred
) {
895 // 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.
896 if (typeof options
=== 'string') {
897 return CRM
.status({start
: options
, success
: options
, error
: options
})[deferred
=== 'error' ? 'reject' : 'resolve']();
899 var opts
= $.extend({
900 start
: ts('Saving...'),
901 success
: ts('Saved'),
902 error: function(data
) {
903 var msg
= $.isPlainObject(data
) && data
.error_message
;
904 CRM
.alert(msg
|| ts('Sorry an error occurred and your information was not saved'), ts('Error'), 'error');
907 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>')
909 $msg
.css('min-width', $msg
.width());
910 function handle(status
, data
) {
911 var endMsg
= typeof(opts
[status
]) === 'function' ? opts
[status
](data
) : opts
[status
];
913 $msg
.removeClass('status-start').addClass('status-' + status
).find('.crm-status-box-msg').html(endMsg
);
914 window
.setTimeout(function() {
915 $msg
.fadeOut('slow', function() {
923 return (deferred
|| new $.Deferred())
924 .done(function(data
) {
925 // If the server returns an error msg call the error handler
926 var status
= $.isPlainObject(data
) && (data
.is_error
|| data
.status
=== 'error') ? 'error' : 'success';
927 handle(status
, data
);
929 .fail(function(data
) {
930 handle('error', data
);
934 // Convert an Angular promise to a jQuery promise
935 CRM
.toJqPromise = function(aPromise
) {
936 var jqDeferred
= $.Deferred();
938 function(data
) { jqDeferred
.resolve(data
); },
939 function(data
) { jqDeferred
.reject(data
); }
940 // should we also handle progress events?
942 return jqDeferred
.promise();
945 CRM
.toAPromise = function($q
, jqPromise
) {
946 var aDeferred
= $q
.defer();
948 function(data
) { aDeferred
.resolve(data
); },
949 function(data
) { aDeferred
.reject(data
); }
950 // should we also handle progress events?
952 return aDeferred
.promise
;
956 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
958 CRM
.alert = function (text
, title
, type
, options
) {
959 type
= type
|| 'alert';
961 options
= options
|| {};
962 if ($('#crm-notification-container').length
) {
968 // By default, don't expire errors and messages containing links
970 expires
: (type
== 'error' || text
.indexOf('<a ') > -1) ? 0 : (text
? 10000 : 5000),
973 options
= $.extend(extra
, options
);
974 options
.expires
= options
.expires
=== false ? 0 : parseInt(options
.expires
, 10);
975 if (options
.unique
&& options
.unique
!== '0') {
976 $('#crm-notification-container .ui-notify-message').each(function () {
977 if (title
=== $('h1', this).html() && text
=== $('.notify-content', this).html()) {
978 $('.icon.ui-notify-close', this).click();
982 return $('#crm-notification-container').notify('create', params
, options
);
986 text
= title
+ "\n" + text
;
994 * Close whichever alert contains the given node
998 CRM
.closeAlertByChild = function (node
) {
999 $(node
).closest('.ui-notify-message').find('.icon.ui-notify-close').click();
1003 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
1005 CRM
.confirm = function (options
) {
1006 var dialog
, url
, msg
, buttons
= [], settings
= {
1007 title
: ts('Confirm'),
1008 message
: ts('Are you sure you want to continue?'),
1013 dialogClass
: 'crm-container crm-confirm',
1014 close: function () {
1015 $(this).dialog('destroy').remove();
1022 $.extend(settings
, ($.isFunction(options
) ? arguments
[1] : options
) || {});
1023 if (!settings
.buttons
&& $.isPlainObject(settings
.options
)) {
1024 $.each(settings
.options
, function(op
, label
) {
1028 icons
: {primary
: op
=== 'no' ? 'ui-icon-close' : 'ui-icon-check'},
1030 var event
= $.Event('crmConfirm:' + op
);
1031 $(this).trigger(event
);
1032 if (!event
.isDefaultPrevented()) {
1033 dialog
.dialog('close');
1038 // Order buttons so that "no" goes on the right-hand side
1039 settings
.buttons
= _
.sortBy(buttons
, 'data-op').reverse();
1042 msg
= url
? '' : settings
.message
;
1043 delete settings
.options
;
1044 delete settings
.message
;
1045 delete settings
.url
;
1046 dialog
= $('<div class="crm-confirm-dialog"></div>').html(msg
|| '').dialog(settings
);
1047 if ($.isFunction(options
)) {
1048 dialog
.on('crmConfirm:yes', options
);
1051 CRM
.loadPage(url
, {target
: dialog
});
1054 dialog
.trigger('crmLoad');
1059 /** provides a local copy of ts for a domain */
1060 CRM
.ts = function(domain
) {
1061 return function(message
, options
) {
1063 options
= $.extend(options
|| {}, {domain
: domain
});
1065 return ts(message
, options
);
1069 CRM
.addStrings = function(domain
, strings
) {
1070 var bucket
= (domain
== 'civicrm' ? 'strings' : 'strings::' + domain
);
1071 CRM
[bucket
] = CRM
[bucket
] || {};
1072 _
.extend(CRM
[bucket
], strings
);
1076 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
1078 $.fn
.crmError = function (text
, title
, options
) {
1079 title
= title
|| '';
1081 options
= options
|| {};
1086 if ($(this).length
) {
1088 var label
= $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]').not('[generated=true]');
1090 label
.addClass('crm-error');
1091 var $label
= label
.clone();
1092 if (text
=== '' && $('.crm-marker', $label
).length
> 0) {
1093 text
= $('.crm-marker', $label
).attr('title');
1095 $('.crm-marker', $label
).remove();
1096 title
= $label
.text();
1099 $(this).addClass('crm-error');
1101 var msg
= CRM
.alert(text
, title
, 'error', $.extend(extra
, options
));
1102 if ($(this).length
) {
1104 setTimeout(function () {
1105 ele
.one('change', function () {
1106 if (msg
&& msg
.close
) msg
.close();
1107 ele
.removeClass('error');
1108 label
.removeClass('crm-error');
1115 // Display system alerts through js notifications
1116 function messagesFromMarkup() {
1117 $('div.messages:visible', this).not('.help').not('.no-popup').each(function () {
1118 var text
, title
= '';
1119 $(this).removeClass('status messages');
1120 var type
= $(this).attr('class').split(' ')[0] || 'alert';
1121 type
= type
.replace('crm-', '');
1122 $('.icon', this).remove();
1123 if ($('.msg-text', this).length
> 0) {
1124 text
= $('.msg-text', this).html();
1125 title
= $('.msg-title', this).html();
1128 text
= $(this).html();
1130 var options
= $(this).data('options') || {};
1132 // Duplicates were already removed server-side
1133 options
.unique
= false;
1134 CRM
.alert(text
, title
, type
, options
);
1136 // Handle qf form errors
1137 $('form :input.error', this).one('blur', function() {
1138 $('.ui-notify-message.error a.ui-notify-close').click();
1139 $(this).removeClass('error');
1140 $(this).next('span.crm-error').remove();
1141 $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]')
1142 .removeClass('crm-error')
1143 .find('.crm-error').removeClass('crm-error');
1148 * Improve blockUI when used with jQuery dialog
1150 var originalBlock
= $.fn
.block
,
1151 originalUnblock
= $.fn
.unblock
;
1153 $.fn
.block = function(opts
) {
1154 if ($(this).is('.ui-dialog-content')) {
1155 originalBlock
.call($(this).parents('.ui-dialog'), opts
);
1158 return originalBlock
.call(this, opts
);
1160 $.fn
.unblock = function(opts
) {
1161 if ($(this).is('.ui-dialog-content')) {
1162 originalUnblock
.call($(this).parents('.ui-dialog'), opts
);
1165 return originalUnblock
.call(this, opts
);
1168 // Preprocess all CRM ajax calls to display messages
1169 $(document
).ajaxSuccess(function(event
, xhr
, settings
) {
1171 if ((!settings
.dataType
|| settings
.dataType
== 'json') && xhr
.responseText
) {
1172 var response
= $.parseJSON(xhr
.responseText
);
1173 if (typeof(response
.crmMessages
) == 'object') {
1174 $.each(response
.crmMessages
, function(n
, msg
) {
1175 CRM
.alert(msg
.text
, msg
.title
, msg
.type
, msg
.options
);
1178 if (response
.backtrace
) {
1179 CRM
.console('log', response
.backtrace
);
1181 if (typeof response
.deprecated
=== 'string') {
1182 CRM
.console('warn', response
.deprecated
);
1186 // Ignore errors thrown by parseJSON
1191 $.blockUI
.defaults
.message
= null;
1192 $.blockUI
.defaults
.ignoreIfBlocked
= true;
1194 if ($('#crm-container').hasClass('crm-public')) {
1195 $.fn
.select2
.defaults
.dropdownCssClass
= $.ui
.dialog
.prototype.options
.dialogClass
= 'crm-container crm-public';
1198 // Trigger crmLoad on initial content for consistency. It will also be triggered for ajax-loaded content.
1199 $('.crm-container').trigger('crmLoad');
1201 if ($('#crm-notification-container').length
) {
1202 // Initialize notifications
1203 $('#crm-notification-container').notify();
1204 messagesFromMarkup
.call($('#crm-container'));
1208 // bind the event for image popup
1209 .on('click', 'a.crm-image-popup', function(e
) {
1211 title
: ts('Preview'),
1213 message
: '<div class="crm-custom-image-popup"><img style="max-width: 100%" src="' + $(this).attr('href') + '"></div>',
1219 .on('click', function (event
) {
1220 $('.btn-slide-active').removeClass('btn-slide-active').find('.panel').hide();
1221 if ($(event
.target
).is('.btn-slide')) {
1222 $(event
.target
).addClass('btn-slide-active').find('.panel').show();
1226 // Handle clear button for form elements
1227 .on('click', 'a.crm-clear-link', function() {
1228 $(this).css({visibility
: 'hidden'}).siblings('.crm-form-radio:checked').prop('checked', false).change();
1229 $(this).siblings('input:text').val('').change();
1232 .on('change', 'input.crm-form-radio:checked', function() {
1233 $(this).siblings('.crm-clear-link').css({visibility
: ''});
1236 // Allow normal clicking of links within accordions
1237 .on('click.crmAccordions', 'div.crm-accordion-header a', function (e
) {
1238 e
.stopPropagation();
1240 // Handle accordions
1241 .on('click.crmAccordions', '.crm-accordion-header, .crm-collapsible .collapsible-title', function (e
) {
1242 if ($(this).parent().hasClass('collapsed')) {
1243 $(this).next().css('display', 'none').slideDown(200);
1246 $(this).next().css('display', 'block').slideUp(200);
1248 $(this).parent().toggleClass('collapsed');
1257 $.fn
.crmAccordions = function () {
1258 CRM
.console('warn', 'Warning: $.crmAccordions was called. This function is deprecated and should not be used.');
1261 * Collapse or expand an accordion
1264 $.fn
.crmAccordionToggle = function (speed
) {
1265 $(this).each(function () {
1266 if ($(this).hasClass('collapsed')) {
1267 $('.crm-accordion-body', this).first().css('display', 'none').slideDown(speed
);
1270 $('.crm-accordion-body', this).first().css('display', 'block').slideUp(speed
);
1272 $(this).toggleClass('collapsed');
1277 * Clientside currency formatting
1278 * @param number value
1279 * @param [optional] string format - currency representation of the number 1234.56
1282 var currencyTemplate
;
1283 CRM
.formatMoney = function(value
, format
) {
1284 var decimal, separator
, sign
, i
, j
, result
;
1285 if (value
=== 'init' && format
) {
1286 currencyTemplate
= format
;
1289 format
= format
|| currencyTemplate
;
1290 result
= /1(.?)234(.?)56/.exec(format
);
1291 if (result
=== null) {
1292 return 'Invalid format passed to CRM.formatMoney';
1294 separator
= result
[1];
1295 decimal = result
[2];
1296 sign
= (value
< 0) ? '-' : '';
1297 //extracting the absolute value of the integer part of the number and converting to string
1298 i
= parseInt(value
= Math
.abs(value
).toFixed(2)) + '';
1299 j
= ((j
= i
.length
) > 3) ? j
% 3 : 0;
1300 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) : '');
1301 return format
.replace(/1.*234.*56/, result
);
1304 CRM
.console = function(method
, title
, msg
) {
1305 if (window
.console
) {
1306 method
= $.isFunction(console
[method
]) ? method
: 'log';
1307 if (msg
=== undefined) {
1308 return console
[method
](title
);
1310 return console
[method
](title
, msg
);
1315 // Determine if a user has a given permission.
1316 // @see CRM_Core_Resources::addPermissions
1317 CRM
.checkPerm = function(perm
) {
1318 return CRM
.permissions
[perm
];