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:hidden', el
).not('[type=submit], [type=button], .crm-action-menu, :disabled').each(function () {
320 initialValue
= $(this).data('crm-initial-value'),
321 currentValue
= $(this).is(':checkbox, :radio') ? $(this).prop('checked') : $(this).val();
322 // skip change of value for submit buttons
323 if (initialValue
!== undefined && !_
.isEqual(initialValue
, currentValue
)) {
331 * This provides defaults for ui.dialog which either need to be calculated or are different from global defaults
336 CRM
.utils
.adjustDialogDefaults = function(settings
) {
337 settings
= $.extend({width
: '65%', height
: '65%', modal
: true}, settings
|| {});
338 // Support relative height
339 if (typeof settings
.height
=== 'string' && settings
.height
.indexOf('%') > 0) {
340 settings
.height
= parseInt($(window
).height() * (parseFloat(settings
.height
)/100), 10);
342 // Responsive adjustment - increase percent width on small screens
343 if (typeof settings
.width
=== 'string' && settings
.width
.indexOf('%') > 0) {
344 var screenWidth
= $(window
).width(),
345 percentage
= parseInt(settings
.width
.replace('%', ''), 10),
346 gap
= 100-percentage
;
347 if (screenWidth
< 701) {
348 settings
.width
= '100%';
350 else if (screenWidth
< 1400) {
351 settings
.width
= '' + parseInt(percentage
+gap
-((screenWidth
- 700)/7*(gap)/100), 10) + '%';
358 * Wrapper for select2 initialization function; supplies defaults
359 * @param options object
361 $.fn
.crmSelect2 = function(options
) {
362 return $(this).each(function () {
365 settings
= {allowClear
: !$el
.hasClass('required')};
366 // quickform doesn't support optgroups so here's a hack :(
367 $('option[value^=crm_optgroup]', this).each(function () {
368 $(this).nextUntil('option[value^=crm_optgroup]').wrapAll('<optgroup label="' + $(this).text() + '" />');
372 // quickform does not support disabled option, so yet another hack to
373 // add disabled property for option values
374 $('option[value^=crm_disabled_opt]', this).attr('disabled', 'disabled');
376 // Defaults for single-selects
377 if ($el
.is('select:not([multiple])')) {
378 settings
.minimumResultsForSearch
= 10;
379 if ($('option:first', this).val() === '') {
380 settings
.placeholderOption
= 'first';
383 $.extend(settings
, $el
.data('select-params') || {}, options
|| {});
385 $el
.addClass('crm-ajax-select');
387 $el
.select2(settings
);
392 * @see CRM_Core_Form::addEntityRef for docs
393 * @param options object
395 $.fn
.crmEntityRef = function(options
) {
396 options
= options
|| {};
397 options
.select
= options
.select
|| {};
398 return $(this).each(function() {
400 $el
= $(this).off('.crmEntity'),
401 entity
= options
.entity
|| $el
.data('api-entity') || 'contact',
403 $el
.data('api-entity', entity
);
404 $el
.data('select-params', $.extend({}, $el
.data('select-params') || {}, options
.select
));
405 $el
.data('api-params', $.extend({}, $el
.data('api-params') || {}, options
.api
));
406 $el
.data('create-links', options
.create
|| $el
.data('create-links'));
407 $el
.addClass('crm-form-entityref crm-' + entity
.toLowerCase() + '-ref');
409 // Use select2 ajax helper instead of CRM.api3 because it provides more value
411 url
: CRM
.url('civicrm/ajax/rest'),
412 data: function (input
, page_num
) {
413 var params
= getEntityRefApiParams($el
);
414 params
.input
= input
;
415 params
.page_num
= page_num
;
417 entity
: $el
.data('api-entity'),
419 json
: JSON
.stringify(params
)
422 results: function(data
) {
423 return {more
: data
.more_results
, results
: data
.values
|| []};
426 minimumInputLength
: 1,
427 formatResult
: CRM
.utils
.formatSelect2Result
,
428 formatSelection: function(row
) {
431 escapeMarkup: function (m
) {return m
;},
432 initSelection: function($el
, callback
) {
434 multiple
= !!$el
.data('select-params').multiple
,
436 stored
= $el
.data('entity-value') || [];
440 // If we already have this data, just return it
441 if (!_
.xor(val
.split(','), _
.pluck(stored
, 'id')).length
) {
442 callback(multiple
? stored
: stored
[0]);
444 var params
= $.extend({}, $el
.data('api-params') || {}, {id
: val
});
445 CRM
.api3($el
.data('api-entity'), 'getlist', params
).done(function(result
) {
446 callback(multiple
? result
.values
: result
.values
[0]);
447 // Trigger change (store data to avoid an infinite loop of lookups)
448 $el
.data('entity-value', result
.values
).trigger('change');
453 // Create new items inline - works for tags
454 if ($el
.data('create-links') && entity
.toLowerCase() === 'tag') {
455 selectParams
.createSearchChoice = function(term
, data
) {
456 if (!_
.findKey(data
, {label
: term
})) {
457 return {id
: "0", term
: term
, label
: term
+ ' (' + ts('new tag') + ')'};
460 selectParams
.tokenSeparators
= [','];
461 selectParams
.createSearchChoicePosition
= 'bottom';
462 $el
.on('select2-selecting.crmEntity', function(e
) {
465 e
.object
.label
= e
.object
.term
;
466 CRM
.api3(entity
, 'create', $.extend({name
: e
.object
.term
}, $el
.data('api-params').params
|| {}))
467 .done(function(created
) {
469 val
= $el
.select2('val'),
470 data
= $el
.select2('data'),
471 item
= {id
: created
.id
, label
: e
.object
.term
};
473 $el
.select2('data', item
, true);
475 else if ($.isArray(val
) && $.inArray("0", val
) > -1) {
476 _
.remove(data
, {id
: "0"});
478 $el
.select2('data', data
, true);
485 selectParams
.formatInputTooShort = function() {
486 var txt
= $el
.data('select-params').formatInputTooShort
|| $.fn
.select2
.defaults
.formatInputTooShort
.call(this);
487 txt
+= renderEntityRefFilters($el
) + renderEntityRefCreateLinks($el
);
490 selectParams
.formatNoMatches = function() {
491 var txt
= $el
.data('select-params').formatNoMatches
|| $.fn
.select2
.defaults
.formatNoMatches
;
492 txt
+= renderEntityRefFilters($el
) + renderEntityRefCreateLinks($el
);
495 $el
.on('select2-open.crmEntity', function() {
497 loadEntityRefFilterOptions($el
);
500 .on('click.crmEntity', 'a.crm-add-entity', function(e
) {
501 $el
.select2('close');
502 CRM
.loadForm($(this).attr('href'), {
503 dialog
: {width
: 500, height
: 'auto'}
504 }).on('crmFormSuccess', function(e
, data
) {
505 if (data
.status
=== 'success' && data
.id
) {
506 CRM
.status(ts('%1 Created', {1: data
.label
}));
507 if ($el
.select2('container').hasClass('select2-container-multi')) {
508 var selection
= $el
.select2('data');
509 selection
.push(data
);
510 $el
.select2('data', selection
, true);
512 $el
.select2('data', data
, true);
518 .on('change.crmEntity', 'select.crm-entityref-filter-value', function() {
519 var filter
= $el
.data('user-filter') || {};
520 filter
.value
= $(this).val();
521 $(this).toggleClass('active', !!filter
.value
);
522 $el
.data('user-filter', filter
);
524 // Once a filter has been chosen, rerender create links and refocus the search box
525 $el
.select2('close');
529 .on('change.crmEntity', 'select.crm-entityref-filter-key', function() {
530 var filter
= $el
.data('user-filter') || {};
531 filter
.key
= $(this).val();
532 $(this).toggleClass('active', !!filter
.key
);
533 $el
.data('user-filter', filter
);
534 loadEntityRefFilterOptions($el
);
538 $el
.crmSelect2($.extend(settings
, $el
.data('select-params'), selectParams
));
543 * Combine api-params with user-filter
547 function getEntityRefApiParams($el
) {
549 params
= $.extend({params
: {}}, $el
.data('api-params') || {}),
550 // Prevent original data from being modified - $.extend and _.clone don't cut it, they pass nested objects by reference!
551 combined
= _
.cloneDeep(params
),
552 filter
= $.extend({}, $el
.data('user-filter') || {});
553 if (filter
.key
&& filter
.value
) {
554 // Special case for contact type/sub-type combo
555 if (filter
.key
=== 'contact_type' && (filter
.value
.indexOf('__') > 0)) {
556 combined
.params
.contact_type
= filter
.value
.split('__')[0];
557 combined
.params
.contact_sub_type
= filter
.value
.split('__')[1];
559 // Allow json-encoded api filters e.g. {"BETWEEN":[123,456]}
560 combined
.params
[filter
.key
] = filter
.value
.charAt(0) === '{' ? $.parseJSON(filter
.value
) : filter
.value
;
566 CRM
.utils
.formatSelect2Result = function (row
) {
567 var markup
= '<div class="crm-select2-row">';
568 if (row
.image
!== undefined) {
569 markup
+= '<div class="crm-select2-image"><img src="' + row
.image
+ '"/></div>';
571 else if (row
.icon_class
) {
572 markup
+= '<div class="crm-select2-icon"><div class="crm-icon ' + row
.icon_class
+ '-icon"></div></div>';
574 markup
+= '<div><div class="crm-select2-row-label '+(row
.label_class
|| '')+'">' + row
.label
+ '</div>';
575 markup
+= '<div class="crm-select2-row-description">';
576 $.each(row
.description
|| [], function(k
, text
) {
577 markup
+= '<p>' + text
+ '</p>';
579 markup
+= '</div></div></div>';
583 function renderEntityRefCreateLinks($el
) {
585 createLinks
= $el
.data('create-links'),
586 params
= getEntityRefApiParams($el
).params
,
587 markup
= '<div class="crm-entityref-links">';
588 if (!createLinks
|| $el
.data('api-entity').toLowerCase() !== 'contact') {
591 if (createLinks
=== true) {
592 createLinks
= params
.contact_type
? _
.where(CRM
.config
.entityRef
.contactCreate
, {type
: params
.contact_type
}) : CRM
.config
.entityRef
.contactCreate
;
594 _
.each(createLinks
, function(link
) {
595 markup
+= ' <a class="crm-add-entity crm-hover-button" href="' + link
.url
+ '">';
597 markup
+= '<span class="icon ' + link
.type
+ '-profile-icon"></span> ';
599 markup
+= link
.label
+ '</a>';
605 function getEntityRefFilters($el
) {
607 entity
= $el
.data('api-entity').toLowerCase(),
608 filters
= $.extend([], CRM
.config
.entityRef
.filters
[entity
] || []),
609 filter
= $el
.data('user-filter') || {},
610 params
= $.extend({params
: {}}, $el
.data('api-params') || {}).params
,
612 $.each(filters
, function() {
613 if (typeof params
[this.key
] === 'undefined') {
616 else if (this.key
== 'contact_type' && typeof params
.contact_sub_type
=== 'undefined') {
617 this.options
= _
.remove(this.options
, function(option
) {
618 return option
.key
.indexOf(params
.contact_type
+ '__') === 0;
626 function renderEntityRefFilters($el
) {
628 filters
= getEntityRefFilters($el
),
629 filter
= $el
.data('user-filter') || {},
630 filterSpec
= filter
.key
? _
.find(filters
, {key
: filter
.key
}) : null;
631 if (!filters
.length
) {
634 var markup
= '<div class="crm-entityref-filters">' +
635 '<select class="crm-entityref-filter-key' + (filter
.key
? ' active' : '') + '">' +
636 '<option value="">' + ts('Refine search...') + '</option>' +
637 CRM
.utils
.renderOptions(filters
, filter
.key
) +
638 '</select> ' +
639 '<select class="crm-entityref-filter-value' + (filter
.key
? ' active"' : '"') + (filter
.key
? '' : ' style="display:none;"') + '>' +
640 '<option value="">' + ts('- select -') + '</option>';
641 if (filterSpec
&& filterSpec
.options
) {
642 markup
+= CRM
.utils
.renderOptions(filterSpec
.options
, filter
.value
);
644 markup
+= '</select></div>';
649 * Fetch options for a filter (via ajax if necessary) and populate the appropriate select list
652 function loadEntityRefFilterOptions($el
) {
654 filters
= getEntityRefFilters($el
),
655 filter
= $el
.data('user-filter') || {},
656 filterSpec
= filter
.key
? _
.find(filters
, {key
: filter
.key
}) : null,
657 $valField
= $('.crm-entityref-filter-value', '#select2-drop');
659 $valField
.show().val('');
660 if (filterSpec
.options
) {
661 CRM
.utils
.setOptions($valField
, filterSpec
.options
, false, filter
.value
);
663 $valField
.prop('disabled', true);
664 CRM
.api3(filterSpec
.entity
|| $el
.data('api-entity'), 'getoptions', {field
: filter
.key
, context
: 'search', sequential
: 1})
665 .done(function(result
) {
666 var entity
= $el
.data('api-entity').toLowerCase(),
667 globalFilterSpec
= _
.find(CRM
.config
.entityRef
.filters
[entity
], {key
: filter
.key
}) || {};
668 // Store options globally so we don't have to look them up again
669 globalFilterSpec
.options
= result
.values
;
670 $valField
.prop('disabled', false);
671 CRM
.utils
.setOptions($valField
, result
.values
);
672 $valField
.val(filter
.value
|| '');
680 //CRM-15598 - Override url validator method to allow relative url's (e.g. /index.htm)
681 $.validator
.addMethod("url", function(value
, element
) {
682 if (/^\//.test(value
)) {
683 // Relative url: prepend dummy path for validation.
684 value
= 'http://domain.tld' + value
;
686 // From jQuery Validation Plugin v1.12.0
687 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
);
691 * Wrapper for jQuery validate initialization function; supplies defaults
693 $.fn
.crmValidate = function(params
) {
694 return $(this).each(function () {
696 settings
= $.extend({}, CRM
.validate
._defaults
, CRM
.validate
.params
);
697 $(this).validate(settings
);
698 // Call any post-initialization callbacks
699 if (CRM
.validate
.functions
&& CRM
.validate
.functions
.length
) {
700 $.each(CRM
.validate
.functions
, function(i
, func
) {
707 // Initialize widgets
709 .on('crmLoad', function(e
) {
710 $('table.row-highlight', e
.target
)
711 .off('.rowHighlight')
712 .on('change.rowHighlight', 'input.select-row, input.select-rows', function (e
, data
) {
713 var filter
, $table
= $(this).closest('table');
714 if ($(this).hasClass('select-rows')) {
715 filter
= $(this).prop('checked') ? ':not(:checked)' : ':checked';
716 $('input.select-row' + filter
, $table
).prop('checked', $(this).prop('checked')).trigger('change', 'master-selected');
719 $(this).closest('tr').toggleClass('crm-row-selected', $(this).prop('checked'));
720 if (data
!== 'master-selected') {
721 $('input.select-rows', $table
).prop('checked', $(".select-row:not(':checked')", $table
).length
< 1);
725 .find('input.select-row:checked').parents('tr').addClass('crm-row-selected');
726 if ($("input:radio[name=radio_ts]").size() == 1) {
727 $("input:radio[name=radio_ts]").prop("checked", true);
729 $('.crm-select2:not(.select2-offscreen, .select2-container)', e
.target
).crmSelect2();
730 $('.crm-form-entityref:not(.select2-offscreen, .select2-container)', e
.target
).crmEntityRef();
731 $('select.crm-chain-select-control', e
.target
).off('.chainSelect').on('change.chainSelect', chainSelect
);
732 // Cache Form Input initial values
733 $('form[data-warn-changes] :input', e
.target
).each(function() {
734 $(this).data('crm-initial-value', $(this).is(':checkbox, :radio') ? $(this).prop('checked') : $(this).val());
737 .on('dialogopen', function(e
) {
738 var $el
= $(e
.target
);
739 // Modal dialogs should disable scrollbars
740 if ($el
.dialog('option', 'modal')) {
741 $el
.addClass('modal-dialog');
742 $('body').css({overflow
: 'hidden'});
745 if ($el
.parent().hasClass('crm-container') && $el
.dialog('option', 'resizable')) {
746 $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}));
747 $('.crm-dialog-titlebar-resize', $el
.parent()).click(function(e
) {
748 if ($el
.data('origSize')) {
749 $el
.dialog('option', $el
.data('origSize'));
750 $el
.data('origSize', null);
752 var menuHeight
= $('#civicrm-menu').outerHeight();
753 $el
.data('origSize', {
754 position
: {my
: 'center', at
: 'center center+' + (menuHeight
/ 2), of: window
},
755 width
: $el
.dialog('option', 'width'),
756 height
: $el
.dialog('option', 'height')
758 $el
.dialog('option', {width
: '100%', height
: ($(window
).height() - menuHeight
), position
: {my
: "top", at
: "top+"+menuHeight
, of: window
}});
760 $el
.trigger('dialogresize');
765 .on('dialogclose', function(e
) {
766 // Restore scrollbars when closing modal
767 if ($('.ui-dialog .modal-dialog:visible').not(e
.target
).length
< 1) {
768 $('body').css({overflow
: ''});
771 .on('submit', function(e
) {
772 // CRM-14353 - disable changes warn when submitting a form
773 $('[data-warn-changes]').attr('data-warn-changes', 'false');
777 // CRM-14353 - Warn of unsaved changes for forms which have opted in
778 window
.onbeforeunload = function() {
779 if (CRM
.utils
.initialValueChanged($('form[data-warn-changes=true]:visible'))) {
780 return ts('You have unsaved changes.');
785 * Function to make multiselect boxes behave as fields in small screens
787 function advmultiselectResize() {
788 var amswidth
= $("#crm-container form:has(table.advmultiselect)").width();
789 if (amswidth
< 700) {
790 $("form table.advmultiselect td").css('display', 'block');
793 $("form table.advmultiselect td").css('display', 'table-cell');
795 var contactwidth
= $('#crm-container #mainTabContainer').width();
796 if (contactwidth
< 600) {
797 $('#crm-container #mainTabContainer').addClass('narrowpage');
798 $('#crm-container #mainTabContainer.narrowpage #contactTopBar td').each(function (index
) {
800 if (index
% 2 === 0) {
801 $(this).parent().after('<tr class="narrowadded"></tr>');
804 $(this).parent().next().append(item
);
809 $('#crm-container #mainTabContainer.narrowpage').removeClass('narrowpage');
810 $('#crm-container #mainTabContainer #contactTopBar tr.narrowadded td').each(function () {
812 var parent
= $(this).parent();
813 $(this).parent().prev().append(nitem
);
814 if (parent
.children().size() === 0) {
818 $('#crm-container #mainTabContainer.narrowpage #contactTopBar tr.added').detach();
820 var cformwidth
= $('#crm-container #Contact .contact_basic_information-section').width();
822 if (cformwidth
< 720) {
823 $('#crm-container .contact_basic_information-section').addClass('narrowform');
824 $('#crm-container .contact_basic_information-section table.form-layout-compressed td .helpicon').parent().addClass('hashelpicon');
825 if (cformwidth
< 480) {
826 $('#crm-container .contact_basic_information-section').addClass('xnarrowform');
829 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
833 $('#crm-container .contact_basic_information-section.narrowform').removeClass('narrowform');
834 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
838 advmultiselectResize();
839 $(window
).resize(advmultiselectResize
);
841 $.fn
.crmtooltip = function () {
843 .on('mouseover', 'a.crm-summary-link:not(.crm-processed)', function (e
) {
844 $(this).addClass('crm-processed');
845 $(this).addClass('crm-tooltip-active');
846 var topDistance
= e
.pageY
- $(window
).scrollTop();
847 if (topDistance
< 300 || topDistance
< $(this).children('.crm-tooltip-wrapper').height()) {
848 $(this).addClass('crm-tooltip-down');
850 if (!$(this).children('.crm-tooltip-wrapper').length
) {
851 $(this).append('<div class="crm-tooltip-wrapper"><div class="crm-tooltip"></div></div>');
852 $(this).children().children('.crm-tooltip')
853 .html('<div class="crm-loading-element"></div>')
857 .on('mouseout', 'a.crm-summary-link', function () {
858 $(this).removeClass('crm-processed');
859 $(this).removeClass('crm-tooltip-active crm-tooltip-down');
861 .on('click', 'a.crm-summary-link', false);
864 var helpDisplay
, helpPrevious
;
865 CRM
.help = function (title
, params
, url
) {
866 if (helpDisplay
&& helpDisplay
.close
) {
867 // If the same link is clicked twice, just close the display - todo use underscore method for this comparison
868 if (helpDisplay
.isOpen
&& helpPrevious
=== JSON
.stringify(params
)) {
874 helpPrevious
= JSON
.stringify(params
);
875 params
.class_name
= 'CRM_Core_Page_Inline_Help';
876 params
.type
= 'page';
877 helpDisplay
= CRM
.alert('...', title
, 'crm-help crm-msg-loading', {expires
: 0});
878 $.ajax(url
|| CRM
.url('civicrm/ajax/inline'),
882 success: function (data
) {
883 $('#crm-notification-container .crm-help .notify-content:last').html(data
);
884 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('info');
887 $('#crm-notification-container .crm-help .notify-content:last').html('Unable to load help file.');
888 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('error');
894 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
896 CRM
.status = function(options
, deferred
) {
897 // 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.
898 if (typeof options
=== 'string') {
899 return CRM
.status({start
: options
, success
: options
, error
: options
})[deferred
=== 'error' ? 'reject' : 'resolve']();
901 var opts
= $.extend({
902 start
: ts('Saving...'),
903 success
: ts('Saved'),
904 error: function(data
) {
905 var msg
= $.isPlainObject(data
) && data
.error_message
;
906 CRM
.alert(msg
|| ts('Sorry an error occurred and your information was not saved'), ts('Error'), 'error');
909 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>')
911 $msg
.css('min-width', $msg
.width());
912 function handle(status
, data
) {
913 var endMsg
= typeof(opts
[status
]) === 'function' ? opts
[status
](data
) : opts
[status
];
915 $msg
.removeClass('status-start').addClass('status-' + status
).find('.crm-status-box-msg').html(endMsg
);
916 window
.setTimeout(function() {
917 $msg
.fadeOut('slow', function() {
925 return (deferred
|| new $.Deferred())
926 .done(function(data
) {
927 // If the server returns an error msg call the error handler
928 var status
= $.isPlainObject(data
) && (data
.is_error
|| data
.status
=== 'error') ? 'error' : 'success';
929 handle(status
, data
);
931 .fail(function(data
) {
932 handle('error', data
);
936 // Convert an Angular promise to a jQuery promise
937 CRM
.toJqPromise = function(aPromise
) {
938 var jqDeferred
= $.Deferred();
940 function(data
) { jqDeferred
.resolve(data
); },
941 function(data
) { jqDeferred
.reject(data
); }
942 // should we also handle progress events?
944 return jqDeferred
.promise();
947 CRM
.toAPromise = function($q
, jqPromise
) {
948 var aDeferred
= $q
.defer();
950 function(data
) { aDeferred
.resolve(data
); },
951 function(data
) { aDeferred
.reject(data
); }
952 // should we also handle progress events?
954 return aDeferred
.promise
;
958 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
960 CRM
.alert = function (text
, title
, type
, options
) {
961 type
= type
|| 'alert';
963 options
= options
|| {};
964 if ($('#crm-notification-container').length
) {
970 // By default, don't expire errors and messages containing links
972 expires
: (type
== 'error' || text
.indexOf('<a ') > -1) ? 0 : (text
? 10000 : 5000),
975 options
= $.extend(extra
, options
);
976 options
.expires
= options
.expires
=== false ? 0 : parseInt(options
.expires
, 10);
977 if (options
.unique
&& options
.unique
!== '0') {
978 $('#crm-notification-container .ui-notify-message').each(function () {
979 if (title
=== $('h1', this).html() && text
=== $('.notify-content', this).html()) {
980 $('.icon.ui-notify-close', this).click();
984 return $('#crm-notification-container').notify('create', params
, options
);
988 text
= title
+ "\n" + text
;
996 * Close whichever alert contains the given node
1000 CRM
.closeAlertByChild = function (node
) {
1001 $(node
).closest('.ui-notify-message').find('.icon.ui-notify-close').click();
1005 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
1007 CRM
.confirm = function (options
) {
1008 var dialog
, url
, msg
, buttons
= [], settings
= {
1009 title
: ts('Confirm'),
1010 message
: ts('Are you sure you want to continue?'),
1015 dialogClass
: 'crm-container crm-confirm',
1016 close: function () {
1017 $(this).dialog('destroy').remove();
1024 if (options
&& options
.url
) {
1025 settings
.resizable
= true;
1026 settings
.height
= '50%';
1028 $.extend(settings
, ($.isFunction(options
) ? arguments
[1] : options
) || {});
1029 settings
= CRM
.utils
.adjustDialogDefaults(settings
);
1030 if (!settings
.buttons
&& $.isPlainObject(settings
.options
)) {
1031 $.each(settings
.options
, function(op
, label
) {
1035 icons
: {primary
: op
=== 'no' ? 'ui-icon-close' : 'ui-icon-check'},
1037 var event
= $.Event('crmConfirm:' + op
);
1038 $(this).trigger(event
);
1039 if (!event
.isDefaultPrevented()) {
1040 dialog
.dialog('close');
1045 // Order buttons so that "no" goes on the right-hand side
1046 settings
.buttons
= _
.sortBy(buttons
, 'data-op').reverse();
1049 msg
= url
? '' : settings
.message
;
1050 delete settings
.options
;
1051 delete settings
.message
;
1052 delete settings
.url
;
1053 dialog
= $('<div class="crm-confirm-dialog"></div>').html(msg
|| '').dialog(settings
);
1054 if ($.isFunction(options
)) {
1055 dialog
.on('crmConfirm:yes', options
);
1058 CRM
.loadPage(url
, {target
: dialog
});
1061 dialog
.trigger('crmLoad');
1066 /** provides a local copy of ts for a domain */
1067 CRM
.ts = function(domain
) {
1068 return function(message
, options
) {
1070 options
= $.extend(options
|| {}, {domain
: domain
});
1072 return ts(message
, options
);
1076 CRM
.addStrings = function(domain
, strings
) {
1077 var bucket
= (domain
== 'civicrm' ? 'strings' : 'strings::' + domain
);
1078 CRM
[bucket
] = CRM
[bucket
] || {};
1079 _
.extend(CRM
[bucket
], strings
);
1083 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
1085 $.fn
.crmError = function (text
, title
, options
) {
1086 title
= title
|| '';
1088 options
= options
|| {};
1093 if ($(this).length
) {
1095 var label
= $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]').not('[generated=true]');
1097 label
.addClass('crm-error');
1098 var $label
= label
.clone();
1099 if (text
=== '' && $('.crm-marker', $label
).length
> 0) {
1100 text
= $('.crm-marker', $label
).attr('title');
1102 $('.crm-marker', $label
).remove();
1103 title
= $label
.text();
1106 $(this).addClass('crm-error');
1108 var msg
= CRM
.alert(text
, title
, 'error', $.extend(extra
, options
));
1109 if ($(this).length
) {
1111 setTimeout(function () {
1112 ele
.one('change', function () {
1113 if (msg
&& msg
.close
) msg
.close();
1114 ele
.removeClass('error');
1115 label
.removeClass('crm-error');
1122 // Display system alerts through js notifications
1123 function messagesFromMarkup() {
1124 $('div.messages:visible', this).not('.help').not('.no-popup').each(function () {
1125 var text
, title
= '';
1126 $(this).removeClass('status messages');
1127 var type
= $(this).attr('class').split(' ')[0] || 'alert';
1128 type
= type
.replace('crm-', '');
1129 $('.icon', this).remove();
1130 if ($('.msg-text', this).length
> 0) {
1131 text
= $('.msg-text', this).html();
1132 title
= $('.msg-title', this).html();
1135 text
= $(this).html();
1137 var options
= $(this).data('options') || {};
1139 // Duplicates were already removed server-side
1140 options
.unique
= false;
1141 CRM
.alert(text
, title
, type
, options
);
1143 // Handle qf form errors
1144 $('form :input.error', this).one('blur', function() {
1145 $('.ui-notify-message.error a.ui-notify-close').click();
1146 $(this).removeClass('error');
1147 $(this).next('span.crm-error').remove();
1148 $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]')
1149 .removeClass('crm-error')
1150 .find('.crm-error').removeClass('crm-error');
1155 * Improve blockUI when used with jQuery dialog
1157 var originalBlock
= $.fn
.block
,
1158 originalUnblock
= $.fn
.unblock
;
1160 $.fn
.block = function(opts
) {
1161 if ($(this).is('.ui-dialog-content')) {
1162 originalBlock
.call($(this).parents('.ui-dialog'), opts
);
1165 return originalBlock
.call(this, opts
);
1167 $.fn
.unblock = function(opts
) {
1168 if ($(this).is('.ui-dialog-content')) {
1169 originalUnblock
.call($(this).parents('.ui-dialog'), opts
);
1172 return originalUnblock
.call(this, opts
);
1175 // Preprocess all CRM ajax calls to display messages
1176 $(document
).ajaxSuccess(function(event
, xhr
, settings
) {
1178 if ((!settings
.dataType
|| settings
.dataType
== 'json') && xhr
.responseText
) {
1179 var response
= $.parseJSON(xhr
.responseText
);
1180 if (typeof(response
.crmMessages
) == 'object') {
1181 $.each(response
.crmMessages
, function(n
, msg
) {
1182 CRM
.alert(msg
.text
, msg
.title
, msg
.type
, msg
.options
);
1185 if (response
.backtrace
) {
1186 CRM
.console('log', response
.backtrace
);
1188 if (typeof response
.deprecated
=== 'string') {
1189 CRM
.console('warn', response
.deprecated
);
1193 // Ignore errors thrown by parseJSON
1198 $.blockUI
.defaults
.message
= null;
1199 $.blockUI
.defaults
.ignoreIfBlocked
= true;
1201 if ($('#crm-container').hasClass('crm-public')) {
1202 $.fn
.select2
.defaults
.dropdownCssClass
= $.ui
.dialog
.prototype.options
.dialogClass
= 'crm-container crm-public';
1205 // Trigger crmLoad on initial content for consistency. It will also be triggered for ajax-loaded content.
1206 $('.crm-container').trigger('crmLoad');
1208 if ($('#crm-notification-container').length
) {
1209 // Initialize notifications
1210 $('#crm-notification-container').notify();
1211 messagesFromMarkup
.call($('#crm-container'));
1215 // bind the event for image popup
1216 .on('click', 'a.crm-image-popup', function(e
) {
1218 title
: ts('Preview'),
1220 message
: '<div class="crm-custom-image-popup"><img style="max-width: 100%" src="' + $(this).attr('href') + '"></div>',
1226 .on('click', function (event
) {
1227 $('.btn-slide-active').removeClass('btn-slide-active').find('.panel').hide();
1228 if ($(event
.target
).is('.btn-slide')) {
1229 $(event
.target
).addClass('btn-slide-active').find('.panel').show();
1233 // Handle clear button for form elements
1234 .on('click', 'a.crm-clear-link', function() {
1235 $(this).css({visibility
: 'hidden'}).siblings('.crm-form-radio:checked').prop('checked', false).change();
1236 $(this).siblings('input:text').val('').change();
1239 .on('change', 'input.crm-form-radio:checked', function() {
1240 $(this).siblings('.crm-clear-link').css({visibility
: ''});
1243 // Allow normal clicking of links within accordions
1244 .on('click.crmAccordions', 'div.crm-accordion-header a', function (e
) {
1245 e
.stopPropagation();
1247 // Handle accordions
1248 .on('click.crmAccordions', '.crm-accordion-header, .crm-collapsible .collapsible-title', function (e
) {
1249 if ($(this).parent().hasClass('collapsed')) {
1250 $(this).next().css('display', 'none').slideDown(200);
1253 $(this).next().css('display', 'block').slideUp(200);
1255 $(this).parent().toggleClass('collapsed');
1264 $.fn
.crmAccordions = function () {
1265 CRM
.console('warn', 'Warning: $.crmAccordions was called. This function is deprecated and should not be used.');
1268 * Collapse or expand an accordion
1271 $.fn
.crmAccordionToggle = function (speed
) {
1272 $(this).each(function () {
1273 if ($(this).hasClass('collapsed')) {
1274 $('.crm-accordion-body', this).first().css('display', 'none').slideDown(speed
);
1277 $('.crm-accordion-body', this).first().css('display', 'block').slideUp(speed
);
1279 $(this).toggleClass('collapsed');
1284 * Clientside currency formatting
1285 * @param number value
1286 * @param [optional] string format - currency representation of the number 1234.56
1289 var currencyTemplate
;
1290 CRM
.formatMoney = function(value
, format
) {
1291 var decimal, separator
, sign
, i
, j
, result
;
1292 if (value
=== 'init' && format
) {
1293 currencyTemplate
= format
;
1296 format
= format
|| currencyTemplate
;
1297 result
= /1(.?)234(.?)56/.exec(format
);
1298 if (result
=== null) {
1299 return 'Invalid format passed to CRM.formatMoney';
1301 separator
= result
[1];
1302 decimal = result
[2];
1303 sign
= (value
< 0) ? '-' : '';
1304 //extracting the absolute value of the integer part of the number and converting to string
1305 i
= parseInt(value
= Math
.abs(value
).toFixed(2)) + '';
1306 j
= ((j
= i
.length
) > 3) ? j
% 3 : 0;
1307 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) : '');
1308 return format
.replace(/1.*234.*56/, result
);
1311 CRM
.console = function(method
, title
, msg
) {
1312 if (window
.console
) {
1313 method
= $.isFunction(console
[method
]) ? method
: 'log';
1314 if (msg
=== undefined) {
1315 return console
[method
](title
);
1317 return console
[method
](title
, msg
);
1322 // Determine if a user has a given permission.
1323 // @see CRM_Core_Resources::addPermissions
1324 CRM
.checkPerm = function(perm
) {
1325 return CRM
.permissions
[perm
];