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 cj('input[name=' + obj
.name
+ ']').val(procText
+ " ...");
163 cj(obj
).closest('form').attr('data-warn-changes', 'false');
164 if (document
.getElementById
) { // disable submit button for newer browsers
165 cj('input[name=' + obj
.name
+ ']').attr("disabled", true);
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, #civicrm-menu').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
);
233 if ($(el
).is('.crm-form-date-wrapper .crm-hidden-date')) {
234 $(el
).siblings().prop('disabled', value
);
240 * Populate a select list, overwriting the existing options except for the placeholder.
241 * @param select jquery selector - 1 or more select elements
242 * @param options array in format returned by api.getoptions
243 * @param placeholder string|bool - new placeholder or false (default) to keep the old one
244 * @param value string|array - will silently update the element with new value without triggering change
246 CRM
.utils
.setOptions = function(select
, options
, placeholder
, value
) {
247 $(select
).each(function() {
250 val
= value
|| $elect
.val() || [],
251 opts
= placeholder
|| placeholder
=== '' ? '' : '[value!=""]';
252 $elect
.find('option' + opts
).remove();
253 var newOptions
= CRM
.utils
.renderOptions(options
, val
);
254 if (typeof placeholder
=== 'string') {
255 if ($elect
.is('[multiple]')) {
256 select
.attr('placeholder', placeholder
);
258 newOptions
= '<option value="">' + placeholder
+ '</option>' + newOptions
;
261 $elect
.append(newOptions
);
263 $elect
.trigger('crmOptionsUpdated', $.extend({}, options
)).trigger('change');
269 * Render an option list
270 * @param options {array}
271 * @param val {string} default value
272 * @param escapeHtml {bool}
275 CRM
.utils
.renderOptions = function(options
, val
, escapeHtml
) {
277 esc
= escapeHtml
=== false ? _
.identity
: _
.escape
;
278 if (!$.isArray(val
)) {
281 _
.each(options
, function(option
) {
282 if (option
.children
) {
283 rendered
+= '<optgroup label="' + esc(option
.value
) + '">' +
284 CRM
.utils
.renderOptions(option
.children
, val
) +
287 var selected
= ($.inArray('' + option
.key
, val
) > -1) ? 'selected="selected"' : '';
288 rendered
+= '<option value="' + esc(option
.key
) + '"' + selected
+ '>' + esc(option
.value
) + '</option>';
294 function chainSelect() {
295 var $form
= $(this).closest('form'),
296 $target
= $('select[data-name="' + $(this).data('target') + '"]', $form
),
297 data
= $target
.data(),
299 $target
.prop('disabled', true);
300 if ($target
.is('select.crm-chain-select-control')) {
301 $('select[data-name="' + $target
.data('target') + '"]', $form
).prop('disabled', true).blur();
303 if (!(val
&& val
.length
)) {
304 CRM
.utils
.setOptions($target
.blur(), [], data
.emptyPrompt
);
306 $target
.addClass('loading');
307 $.getJSON(CRM
.url(data
.callback
), {_value
: val
}, function(vals
) {
308 $target
.prop('disabled', false).removeClass('loading');
309 CRM
.utils
.setOptions($target
, vals
|| [], (vals
&& vals
.length
? data
.selectPrompt
: data
.nonePrompt
));
315 * Compare Form Input values against cached initial value.
317 * @return {Boolean} true if changes have been made.
319 CRM
.utils
.initialValueChanged = function(el
) {
321 $(':input:visible, .select2-container:visible+:input:hidden', el
).not('[type=submit], [type=button], .crm-action-menu, :disabled').each(function () {
323 initialValue
= $(this).data('crm-initial-value'),
324 currentValue
= $(this).is(':checkbox, :radio') ? $(this).prop('checked') : $(this).val();
325 // skip change of value for submit buttons
326 if (initialValue
!== undefined && !_
.isEqual(initialValue
, currentValue
)) {
334 * This provides defaults for ui.dialog which either need to be calculated or are different from global defaults
339 CRM
.utils
.adjustDialogDefaults = function(settings
) {
340 settings
= $.extend({width
: '65%', height
: '65%', modal
: true}, settings
|| {});
341 // Support relative height
342 if (typeof settings
.height
=== 'string' && settings
.height
.indexOf('%') > 0) {
343 settings
.height
= parseInt($(window
).height() * (parseFloat(settings
.height
)/100), 10);
345 // Responsive adjustment - increase percent width on small screens
346 if (typeof settings
.width
=== 'string' && settings
.width
.indexOf('%') > 0) {
347 var screenWidth
= $(window
).width(),
348 percentage
= parseInt(settings
.width
.replace('%', ''), 10),
349 gap
= 100-percentage
;
350 if (screenWidth
< 701) {
351 settings
.width
= '100%';
353 else if (screenWidth
< 1400) {
354 settings
.width
= '' + parseInt(percentage
+gap
-((screenWidth
- 700)/7*(gap)/100), 10) + '%';
361 * Wrapper for select2 initialization function; supplies defaults
362 * @param options object
364 $.fn
.crmSelect2 = function(options
) {
365 return $(this).each(function () {
368 settings
= {allowClear
: !$el
.hasClass('required')};
369 // quickform doesn't support optgroups so here's a hack :(
370 $('option[value^=crm_optgroup]', this).each(function () {
371 $(this).nextUntil('option[value^=crm_optgroup]').wrapAll('<optgroup label="' + $(this).text() + '" />');
375 // quickform does not support disabled option, so yet another hack to
376 // add disabled property for option values
377 $('option[value^=crm_disabled_opt]', this).attr('disabled', 'disabled');
379 // Defaults for single-selects
380 if ($el
.is('select:not([multiple])')) {
381 settings
.minimumResultsForSearch
= 10;
382 if ($('option:first', this).val() === '') {
383 settings
.placeholderOption
= 'first';
386 $.extend(settings
, $el
.data('select-params') || {}, options
|| {});
388 $el
.addClass('crm-ajax-select');
390 $el
.select2(settings
);
395 * @see CRM_Core_Form::addEntityRef for docs
396 * @param options object
398 $.fn
.crmEntityRef = function(options
) {
399 options
= options
|| {};
400 options
.select
= options
.select
|| {};
401 return $(this).each(function() {
403 $el
= $(this).off('.crmEntity'),
404 entity
= options
.entity
|| $el
.data('api-entity') || 'contact',
406 $el
.data('api-entity', entity
);
407 $el
.data('select-params', $.extend({}, $el
.data('select-params') || {}, options
.select
));
408 $el
.data('api-params', $.extend({}, $el
.data('api-params') || {}, options
.api
));
409 $el
.data('create-links', options
.create
|| $el
.data('create-links'));
410 $el
.addClass('crm-form-entityref crm-' + entity
.toLowerCase() + '-ref');
412 // Use select2 ajax helper instead of CRM.api3 because it provides more value
414 url
: CRM
.url('civicrm/ajax/rest'),
415 data: function (input
, page_num
) {
416 var params
= getEntityRefApiParams($el
);
417 params
.input
= input
;
418 params
.page_num
= page_num
;
420 entity
: $el
.data('api-entity'),
422 json
: JSON
.stringify(params
)
425 results: function(data
) {
426 return {more
: data
.more_results
, results
: data
.values
|| []};
429 minimumInputLength
: 1,
430 formatResult
: CRM
.utils
.formatSelect2Result
,
431 formatSelection: function(row
) {
432 return (row
.prefix
!== undefined ? row
.prefix
+ ' ' : '') + row
.label
+ (row
.suffix
!== undefined ? ' ' + row
.suffix
: '');
434 escapeMarkup: function (m
) {return m
;},
435 initSelection: function($el
, callback
) {
437 multiple
= !!$el
.data('select-params').multiple
,
439 stored
= $el
.data('entity-value') || [];
443 // If we already have this data, just return it
444 if (!_
.xor(val
.split(','), _
.pluck(stored
, 'id')).length
) {
445 callback(multiple
? stored
: stored
[0]);
447 var params
= $.extend({}, $el
.data('api-params') || {}, {id
: val
});
448 CRM
.api3($el
.data('api-entity'), 'getlist', params
).done(function(result
) {
449 callback(multiple
? result
.values
: result
.values
[0]);
450 // Trigger change (store data to avoid an infinite loop of lookups)
451 $el
.data('entity-value', result
.values
).trigger('change');
456 // Create new items inline - works for tags
457 if ($el
.data('create-links') && entity
.toLowerCase() === 'tag') {
458 selectParams
.createSearchChoice = function(term
, data
) {
459 if (!_
.findKey(data
, {label
: term
})) {
460 return {id
: "0", term
: term
, label
: term
+ ' (' + ts('new tag') + ')'};
463 selectParams
.tokenSeparators
= [','];
464 selectParams
.createSearchChoicePosition
= 'bottom';
465 $el
.on('select2-selecting.crmEntity', function(e
) {
468 e
.object
.label
= e
.object
.term
;
469 CRM
.api3(entity
, 'create', $.extend({name
: e
.object
.term
}, $el
.data('api-params').params
|| {}))
470 .done(function(created
) {
472 val
= $el
.select2('val'),
473 data
= $el
.select2('data'),
474 item
= {id
: created
.id
, label
: e
.object
.term
};
476 $el
.select2('data', item
, true);
478 else if ($.isArray(val
) && $.inArray("0", val
) > -1) {
479 _
.remove(data
, {id
: "0"});
481 $el
.select2('data', data
, true);
488 selectParams
.formatInputTooShort = function() {
489 var txt
= $el
.data('select-params').formatInputTooShort
|| $.fn
.select2
.defaults
.formatInputTooShort
.call(this);
490 txt
+= renderEntityRefFilters($el
) + renderEntityRefCreateLinks($el
);
493 selectParams
.formatNoMatches = function() {
494 var txt
= $el
.data('select-params').formatNoMatches
|| $.fn
.select2
.defaults
.formatNoMatches
;
495 txt
+= renderEntityRefFilters($el
) + renderEntityRefCreateLinks($el
);
498 $el
.on('select2-open.crmEntity', function() {
500 loadEntityRefFilterOptions($el
);
503 .on('click.crmEntity', 'a.crm-add-entity', function(e
) {
504 $el
.select2('close');
505 CRM
.loadForm($(this).attr('href'), {
506 dialog
: {width
: 500, height
: 220}
507 }).on('crmFormSuccess', function(e
, data
) {
508 if (data
.status
=== 'success' && data
.id
) {
509 CRM
.status(ts('%1 Created', {1: data
.label
}));
510 if ($el
.select2('container').hasClass('select2-container-multi')) {
511 var selection
= $el
.select2('data');
512 selection
.push(data
);
513 $el
.select2('data', selection
, true);
515 $el
.select2('data', data
, true);
521 .on('change.crmEntity', 'select.crm-entityref-filter-value', function() {
522 var filter
= $el
.data('user-filter') || {};
523 filter
.value
= $(this).val();
524 $(this).toggleClass('active', !!filter
.value
);
525 $el
.data('user-filter', filter
);
527 // Once a filter has been chosen, rerender create links and refocus the search box
528 $el
.select2('close');
532 .on('change.crmEntity', 'select.crm-entityref-filter-key', function() {
533 var filter
= $el
.data('user-filter') || {};
534 filter
.key
= $(this).val();
535 $(this).toggleClass('active', !!filter
.key
);
536 $el
.data('user-filter', filter
);
537 loadEntityRefFilterOptions($el
);
541 $el
.crmSelect2($.extend(settings
, $el
.data('select-params'), selectParams
));
546 * Combine api-params with user-filter
550 function getEntityRefApiParams($el
) {
552 params
= $.extend({params
: {}}, $el
.data('api-params') || {}),
553 // Prevent original data from being modified - $.extend and _.clone don't cut it, they pass nested objects by reference!
554 combined
= _
.cloneDeep(params
),
555 filter
= $.extend({}, $el
.data('user-filter') || {});
556 if (filter
.key
&& filter
.value
) {
557 // Special case for contact type/sub-type combo
558 if (filter
.key
=== 'contact_type' && (filter
.value
.indexOf('__') > 0)) {
559 combined
.params
.contact_type
= filter
.value
.split('__')[0];
560 combined
.params
.contact_sub_type
= filter
.value
.split('__')[1];
562 // Allow json-encoded api filters e.g. {"BETWEEN":[123,456]}
563 combined
.params
[filter
.key
] = filter
.value
.charAt(0) === '{' ? $.parseJSON(filter
.value
) : filter
.value
;
569 function copyAttributes($source
, $target
, attributes
) {
570 _
.each(attributes
, function(name
) {
571 if ($source
.attr(name
)) {
572 $target
.attr(name
, $source
.attr(name
));
577 $.fn
.crmDatepicker = function(options
) {
578 return $(this).each(function() {
579 if ($(this).is('.crm-form-date-wrapper .crm-hidden-date')) {
580 // Already initialized
584 $dataField
= $(this).wrap('<span class="crm-form-date-wrapper" />'),
585 settings
= $.extend({}, $dataField
.data('datepicker') || {}, options
|| {}),
590 if (settings
.allowClear
!== undefined ? settings
.allowClear
: !$dataField
.hasClass('required')) {
591 $clearLink
= $('<a class="crm-hover-button crm-clear-link" title="'+ ts('Clear') +'"><span class="icon ui-icon-close"></span></a>')
592 .insertAfter($dataField
);
594 if (settings
.time
!== false) {
595 $timeField
= $('<input>').insertAfter($dataField
);
596 copyAttributes($dataField
, $timeField
, ['class', 'disabled']);
598 .addClass('crm-form-text crm-form-time')
599 .attr('placeholder', $dataField
.attr('time-placeholder') === undefined ? ts('Time') : $dataField
.attr('time-placeholder'))
600 .change(updateDataField
)
603 show24Hours
: settings
.time
=== true || settings
.time
=== undefined ? CRM
.config
.timeIs24Hr
: settings
.time
== '24'
606 if (settings
.date
!== false) {
607 $dateField
= $('<input>').insertAfter($dataField
);
608 copyAttributes($dataField
, $dateField
, ['placeholder', 'style', 'class', 'disabled']);
609 $dateField
.addClass('crm-form-text crm-form-date');
610 settings
.dateFormat
= settings
.dateFormat
|| CRM
.config
.dateInputFormat
;
611 settings
.changeMonth
= _
.includes('m', settings
.dateFormat
);
612 settings
.changeYear
= _
.includes('y', settings
.dateFormat
);
613 $dateField
.datepicker(settings
).change(updateDataField
);
615 // Rudimentary validation. TODO: Roll into use of jQUery validate and ui.datepicker.validation
616 function isValidDate() {
618 $.datepicker
.parseDate(settings
.dateFormat
, $dateField
.val());
624 function updateInputFields(e
, context
) {
625 var val
= $dataField
.val(),
627 if (context
!== 'userInput' && context
!== 'crmClear') {
628 if ($dateField
.length
) {
629 $dateField
.datepicker('setDate', _
.includes(val
, '-') ? $.datepicker
.parseDate('yy-mm-dd', val
) : null);
631 if ($timeField
.length
) {
632 if (val
.length
=== 8) {
634 } else if (val
.length
=== 19) {
635 time
= val
.split(' ')[1];
637 $timeField
.timeEntry('setTime', time
);
640 $clearLink
.css('visibility', val
? 'visible' : 'hidden');
642 function updateDataField(e
, context
) {
643 // The crmClear event wipes all the field values anyway, so no need to respond
644 if (context
!== 'crmClear') {
646 if ($dateField
.val()) {
648 val
= $.datepicker
.formatDate('yy-mm-dd', $dateField
.datepicker('getDate'));
649 $dateField
.removeClass('crm-error');
651 $dateField
.addClass('crm-error');
654 if ($timeField
.val()) {
655 val
+= (val
? ' ' : '') + $timeField
.timeEntry('getTime').toTimeString().substr(0, 8);
657 $dataField
.val(val
).trigger('change', ['userInput']);
660 $dataField
.hide().addClass('crm-hidden-date').on('change', updateInputFields
);
665 $.fn
.crmAjaxTable = function() {
666 return $(this).each(function() {
667 //Declare the defaults for DataTables
671 "dom": '<"crm-datatable-pager-top"lfp>rt<"crm-datatable-pager-bottom"ip>',
673 "drawCallback": function(settings
) {
674 //Add data attributes to cells
675 $('thead th', settings
.nTable
).each( function( index
) {
676 $.each(this.attributes
, function() {
677 if(this.name
.match("^cell-")) {
678 var cellAttr
= this.name
.substring(5);
679 var cellValue
= this.value
;
680 $('tbody tr', settings
.nTable
).each( function() {
681 $('td:eq('+ index
+')', this).attr( cellAttr
, cellValue
);
686 //Reload table after draw
687 $(settings
.nTable
).trigger('crmLoad');
690 //Include any table specific data
691 var settings
= $.extend(true, defaults
, $(this).data('table'));
692 //Make the DataTables call
693 $(this).DataTable(settings
);
697 CRM
.utils
.formatSelect2Result = function (row
) {
698 var markup
= '<div class="crm-select2-row">';
699 if (row
.image
!== undefined) {
700 markup
+= '<div class="crm-select2-image"><img src="' + row
.image
+ '"/></div>';
702 else if (row
.icon_class
) {
703 markup
+= '<div class="crm-select2-icon"><div class="crm-icon ' + row
.icon_class
+ '-icon"></div></div>';
705 markup
+= '<div><div class="crm-select2-row-label '+(row
.label_class
|| '')+'">' +
706 (row
.prefix
!== undefined ? row
.prefix
+ ' ' : '') + row
.label
+ (row
.suffix
!== undefined ? ' ' + row
.suffix
: '') +
708 '<div class="crm-select2-row-description">';
709 $.each(row
.description
|| [], function(k
, text
) {
710 markup
+= '<p>' + text
+ '</p>';
712 markup
+= '</div></div></div>';
716 function renderEntityRefCreateLinks($el
) {
718 createLinks
= $el
.data('create-links'),
719 params
= getEntityRefApiParams($el
).params
,
720 markup
= '<div class="crm-entityref-links">';
721 if (!createLinks
|| $el
.data('api-entity').toLowerCase() !== 'contact') {
724 if (createLinks
=== true) {
725 createLinks
= params
.contact_type
? _
.where(CRM
.config
.entityRef
.contactCreate
, {type
: params
.contact_type
}) : CRM
.config
.entityRef
.contactCreate
;
727 _
.each(createLinks
, function(link
) {
728 markup
+= ' <a class="crm-add-entity crm-hover-button" href="' + link
.url
+ '">';
730 markup
+= '<span class="icon ' + link
.type
+ '-profile-icon"></span> ';
732 markup
+= link
.label
+ '</a>';
738 function getEntityRefFilters($el
) {
740 entity
= $el
.data('api-entity').toLowerCase(),
741 filters
= $.extend([], CRM
.config
.entityRef
.filters
[entity
] || []),
742 filter
= $el
.data('user-filter') || {},
743 params
= $.extend({params
: {}}, $el
.data('api-params') || {}).params
,
745 $.each(filters
, function() {
746 if (typeof params
[this.key
] === 'undefined') {
749 else if (this.key
== 'contact_type' && typeof params
.contact_sub_type
=== 'undefined') {
750 this.options
= _
.remove(this.options
, function(option
) {
751 return option
.key
.indexOf(params
.contact_type
+ '__') === 0;
759 function renderEntityRefFilters($el
) {
761 filters
= getEntityRefFilters($el
),
762 filter
= $el
.data('user-filter') || {},
763 filterSpec
= filter
.key
? _
.find(filters
, {key
: filter
.key
}) : null;
764 if (!filters
.length
) {
767 var markup
= '<div class="crm-entityref-filters">' +
768 '<select class="crm-entityref-filter-key' + (filter
.key
? ' active' : '') + '">' +
769 '<option value="">' + ts('Refine search...') + '</option>' +
770 CRM
.utils
.renderOptions(filters
, filter
.key
) +
771 '</select> ' +
772 '<select class="crm-entityref-filter-value' + (filter
.key
? ' active"' : '"') + (filter
.key
? '' : ' style="display:none;"') + '>' +
773 '<option value="">' + ts('- select -') + '</option>';
774 if (filterSpec
&& filterSpec
.options
) {
775 markup
+= CRM
.utils
.renderOptions(filterSpec
.options
, filter
.value
);
777 markup
+= '</select></div>';
782 * Fetch options for a filter (via ajax if necessary) and populate the appropriate select list
785 function loadEntityRefFilterOptions($el
) {
787 filters
= getEntityRefFilters($el
),
788 filter
= $el
.data('user-filter') || {},
789 filterSpec
= filter
.key
? _
.find(filters
, {key
: filter
.key
}) : null,
790 $valField
= $('.crm-entityref-filter-value', '#select2-drop');
792 $valField
.show().val('');
793 if (filterSpec
.options
) {
794 CRM
.utils
.setOptions($valField
, filterSpec
.options
, false, filter
.value
);
796 $valField
.prop('disabled', true);
797 CRM
.api3(filterSpec
.entity
|| $el
.data('api-entity'), 'getoptions', {field
: filter
.key
, context
: 'search', sequential
: 1})
798 .done(function(result
) {
799 var entity
= $el
.data('api-entity').toLowerCase(),
800 globalFilterSpec
= _
.find(CRM
.config
.entityRef
.filters
[entity
], {key
: filter
.key
}) || {};
801 // Store options globally so we don't have to look them up again
802 globalFilterSpec
.options
= result
.values
;
803 $valField
.prop('disabled', false);
804 CRM
.utils
.setOptions($valField
, result
.values
);
805 $valField
.val(filter
.value
|| '');
813 //CRM-15598 - Override url validator method to allow relative url's (e.g. /index.htm)
814 $.validator
.addMethod("url", function(value
, element
) {
815 if (/^\//.test(value
)) {
816 // Relative url: prepend dummy path for validation.
817 value
= 'http://domain.tld' + value
;
819 // From jQuery Validation Plugin v1.12.0
820 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
);
824 * Wrapper for jQuery validate initialization function; supplies defaults
826 $.fn
.crmValidate = function(params
) {
827 return $(this).each(function () {
829 settings
= $.extend({}, CRM
.validate
._defaults
, CRM
.validate
.params
);
830 $(this).validate(settings
);
831 // Call any post-initialization callbacks
832 if (CRM
.validate
.functions
&& CRM
.validate
.functions
.length
) {
833 $.each(CRM
.validate
.functions
, function(i
, func
) {
840 // Initialize widgets
842 .on('crmLoad', function(e
) {
843 $('table.row-highlight', e
.target
)
844 .off('.rowHighlight')
845 .on('change.rowHighlight', 'input.select-row, input.select-rows', function (e
, data
) {
846 var filter
, $table
= $(this).closest('table');
847 if ($(this).hasClass('select-rows')) {
848 filter
= $(this).prop('checked') ? ':not(:checked)' : ':checked';
849 $('input.select-row' + filter
, $table
).prop('checked', $(this).prop('checked')).trigger('change', 'master-selected');
852 $(this).closest('tr').toggleClass('crm-row-selected', $(this).prop('checked'));
853 if (data
!== 'master-selected') {
854 $('input.select-rows', $table
).prop('checked', $(".select-row:not(':checked')", $table
).length
< 1);
858 .find('input.select-row:checked').parents('tr').addClass('crm-row-selected');
859 $('table.crm-sortable', e
.target
).DataTable();
860 $('table.crm-ajax-table', e
.target
).crmAjaxTable();
861 if ($("input:radio[name=radio_ts]").size() == 1) {
862 $("input:radio[name=radio_ts]").prop("checked", true);
864 $('.crm-select2:not(.select2-offscreen, .select2-container)', e
.target
).crmSelect2();
865 $('.crm-form-entityref:not(.select2-offscreen, .select2-container)', e
.target
).crmEntityRef();
866 $('select.crm-chain-select-control', e
.target
).off('.chainSelect').on('change.chainSelect', chainSelect
);
867 // Cache Form Input initial values
868 $('form[data-warn-changes] :input', e
.target
).each(function() {
869 $(this).data('crm-initial-value', $(this).is(':checkbox, :radio') ? $(this).prop('checked') : $(this).val());
871 $('textarea.crm-form-wysiwyg', e
.target
)
872 .not('.crm-wysiwyg-enabled')
873 .addClass('crm-wysiwyg-enabled')
875 if ($(this).hasClass("collapsed")) {
876 CRM
.wysiwyg
.createCollapsed(this);
878 CRM
.wysiwyg
.create(this);
882 .on('dialogopen', function(e
) {
883 var $el
= $(e
.target
);
884 // Modal dialogs should disable scrollbars
885 if ($el
.dialog('option', 'modal')) {
886 $el
.addClass('modal-dialog');
887 $('body').css({overflow
: 'hidden'});
890 if ($el
.parent().hasClass('crm-container') && $el
.dialog('option', 'resizable')) {
891 $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}));
892 $('.crm-dialog-titlebar-resize', $el
.parent()).click(function(e
) {
893 if ($el
.data('origSize')) {
894 $el
.dialog('option', $el
.data('origSize'));
895 $el
.data('origSize', null);
897 var menuHeight
= $('#civicrm-menu').outerHeight();
898 $el
.data('origSize', {
899 position
: {my
: 'center', at
: 'center center+' + (menuHeight
/ 2), of: window
},
900 width
: $el
.dialog('option', 'width'),
901 height
: $el
.dialog('option', 'height')
903 $el
.dialog('option', {width
: '100%', height
: ($(window
).height() - menuHeight
), position
: {my
: "top", at
: "top+"+menuHeight
, of: window
}});
905 $el
.trigger('dialogresize');
910 .on('dialogclose', function(e
) {
911 // Restore scrollbars when closing modal
912 if ($('.ui-dialog .modal-dialog:visible').not(e
.target
).length
< 1) {
913 $('body').css({overflow
: ''});
916 .on('submit', function(e
) {
917 // CRM-14353 - disable changes warn when submitting a form
918 $('[data-warn-changes]').attr('data-warn-changes', 'false');
921 // CRM-14353 - Warn of unsaved changes for forms which have opted in
922 window
.onbeforeunload = function() {
923 if (CRM
.utils
.initialValueChanged($('form[data-warn-changes=true]:visible'))) {
924 return ts('You have unsaved changes.');
928 $.fn
.crmtooltip = function () {
930 .on('mouseover', 'a.crm-summary-link:not(.crm-processed)', function (e
) {
931 $(this).addClass('crm-processed');
932 $(this).addClass('crm-tooltip-active');
933 var topDistance
= e
.pageY
- $(window
).scrollTop();
934 if (topDistance
< 300 || topDistance
< $(this).children('.crm-tooltip-wrapper').height()) {
935 $(this).addClass('crm-tooltip-down');
937 if (!$(this).children('.crm-tooltip-wrapper').length
) {
938 $(this).append('<div class="crm-tooltip-wrapper"><div class="crm-tooltip"></div></div>');
939 $(this).children().children('.crm-tooltip')
940 .html('<div class="crm-loading-element"></div>')
944 .on('mouseout', 'a.crm-summary-link', function () {
945 $(this).removeClass('crm-processed');
946 $(this).removeClass('crm-tooltip-active crm-tooltip-down');
948 .on('click', 'a.crm-summary-link', false);
951 var helpDisplay
, helpPrevious
;
952 CRM
.help = function (title
, params
, url
) {
953 if (helpDisplay
&& helpDisplay
.close
) {
954 // If the same link is clicked twice, just close the display - todo use underscore method for this comparison
955 if (helpDisplay
.isOpen
&& helpPrevious
=== JSON
.stringify(params
)) {
961 helpPrevious
= JSON
.stringify(params
);
962 params
.class_name
= 'CRM_Core_Page_Inline_Help';
963 params
.type
= 'page';
964 helpDisplay
= CRM
.alert('...', title
, 'crm-help crm-msg-loading', {expires
: 0});
965 $.ajax(url
|| CRM
.url('civicrm/ajax/inline'),
969 success: function (data
) {
970 $('#crm-notification-container .crm-help .notify-content:last').html(data
);
971 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('info');
974 $('#crm-notification-container .crm-help .notify-content:last').html('Unable to load help file.');
975 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('error');
981 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
983 CRM
.status = function(options
, deferred
) {
984 // 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.
985 if (typeof options
=== 'string') {
986 return CRM
.status({start
: options
, success
: options
, error
: options
})[deferred
=== 'error' ? 'reject' : 'resolve']();
988 var opts
= $.extend({
989 start
: ts('Saving...'),
990 success
: ts('Saved'),
991 error: function(data
) {
992 var msg
= $.isPlainObject(data
) && data
.error_message
;
993 CRM
.alert(msg
|| ts('Sorry an error occurred and your information was not saved'), ts('Error'), 'error');
996 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>')
998 $msg
.css('min-width', $msg
.width());
999 function handle(status
, data
) {
1000 var endMsg
= typeof(opts
[status
]) === 'function' ? opts
[status
](data
) : opts
[status
];
1002 $msg
.removeClass('status-start').addClass('status-' + status
).find('.crm-status-box-msg').html(endMsg
);
1003 window
.setTimeout(function() {
1004 $msg
.fadeOut('slow', function() {
1012 return (deferred
|| new $.Deferred())
1013 .done(function(data
) {
1014 // If the server returns an error msg call the error handler
1015 var status
= $.isPlainObject(data
) && (data
.is_error
|| data
.status
=== 'error') ? 'error' : 'success';
1016 handle(status
, data
);
1018 .fail(function(data
) {
1019 handle('error', data
);
1023 // Convert an Angular promise to a jQuery promise
1024 CRM
.toJqPromise = function(aPromise
) {
1025 var jqDeferred
= $.Deferred();
1027 function(data
) { jqDeferred
.resolve(data
); },
1028 function(data
) { jqDeferred
.reject(data
); }
1029 // should we also handle progress events?
1031 return jqDeferred
.promise();
1034 CRM
.toAPromise = function($q
, jqPromise
) {
1035 var aDeferred
= $q
.defer();
1037 function(data
) { aDeferred
.resolve(data
); },
1038 function(data
) { aDeferred
.reject(data
); }
1039 // should we also handle progress events?
1041 return aDeferred
.promise
;
1045 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
1047 CRM
.alert = function (text
, title
, type
, options
) {
1048 type
= type
|| 'alert';
1049 title
= title
|| '';
1050 options
= options
|| {};
1051 if ($('#crm-notification-container').length
) {
1057 // By default, don't expire errors and messages containing links
1059 expires
: (type
== 'error' || text
.indexOf('<a ') > -1) ? 0 : (text
? 10000 : 5000),
1062 options
= $.extend(extra
, options
);
1063 options
.expires
= options
.expires
=== false ? 0 : parseInt(options
.expires
, 10);
1064 if (options
.unique
&& options
.unique
!== '0') {
1065 $('#crm-notification-container .ui-notify-message').each(function () {
1066 if (title
=== $('h1', this).html() && text
=== $('.notify-content', this).html()) {
1067 $('.icon.ui-notify-close', this).click();
1071 return $('#crm-notification-container').notify('create', params
, options
);
1075 text
= title
+ "\n" + text
;
1083 * Close whichever alert contains the given node
1087 CRM
.closeAlertByChild = function (node
) {
1088 $(node
).closest('.ui-notify-message').find('.icon.ui-notify-close').click();
1092 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
1094 CRM
.confirm = function (options
) {
1095 var dialog
, url
, msg
, buttons
= [], settings
= {
1096 title
: ts('Confirm'),
1097 message
: ts('Are you sure you want to continue?'),
1102 dialogClass
: 'crm-container crm-confirm',
1103 close: function () {
1104 $(this).dialog('destroy').remove();
1111 if (options
&& options
.url
) {
1112 settings
.resizable
= true;
1113 settings
.height
= '50%';
1115 $.extend(settings
, ($.isFunction(options
) ? arguments
[1] : options
) || {});
1116 settings
= CRM
.utils
.adjustDialogDefaults(settings
);
1117 if (!settings
.buttons
&& $.isPlainObject(settings
.options
)) {
1118 $.each(settings
.options
, function(op
, label
) {
1122 icons
: {primary
: op
=== 'no' ? 'ui-icon-close' : 'ui-icon-check'},
1124 var event
= $.Event('crmConfirm:' + op
);
1125 $(this).trigger(event
);
1126 if (!event
.isDefaultPrevented()) {
1127 dialog
.dialog('close');
1132 // Order buttons so that "no" goes on the right-hand side
1133 settings
.buttons
= _
.sortBy(buttons
, 'data-op').reverse();
1136 msg
= url
? '' : settings
.message
;
1137 delete settings
.options
;
1138 delete settings
.message
;
1139 delete settings
.url
;
1140 dialog
= $('<div class="crm-confirm-dialog"></div>').html(msg
|| '').dialog(settings
);
1141 if ($.isFunction(options
)) {
1142 dialog
.on('crmConfirm:yes', options
);
1145 CRM
.loadPage(url
, {target
: dialog
});
1148 dialog
.trigger('crmLoad');
1153 /** provides a local copy of ts for a domain */
1154 CRM
.ts = function(domain
) {
1155 return function(message
, options
) {
1157 options
= $.extend(options
|| {}, {domain
: domain
});
1159 return ts(message
, options
);
1163 CRM
.addStrings = function(domain
, strings
) {
1164 var bucket
= (domain
== 'civicrm' ? 'strings' : 'strings::' + domain
);
1165 CRM
[bucket
] = CRM
[bucket
] || {};
1166 _
.extend(CRM
[bucket
], strings
);
1170 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
1172 $.fn
.crmError = function (text
, title
, options
) {
1173 title
= title
|| '';
1175 options
= options
|| {};
1180 if ($(this).length
) {
1182 var label
= $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]').not('[generated=true]');
1184 label
.addClass('crm-error');
1185 var $label
= label
.clone();
1186 if (text
=== '' && $('.crm-marker', $label
).length
> 0) {
1187 text
= $('.crm-marker', $label
).attr('title');
1189 $('.crm-marker', $label
).remove();
1190 title
= $label
.text();
1193 $(this).addClass('crm-error');
1195 var msg
= CRM
.alert(text
, title
, 'error', $.extend(extra
, options
));
1196 if ($(this).length
) {
1198 setTimeout(function () {
1199 ele
.one('change', function () {
1200 if (msg
&& msg
.close
) msg
.close();
1201 ele
.removeClass('error');
1202 label
.removeClass('crm-error');
1209 // Display system alerts through js notifications
1210 function messagesFromMarkup() {
1211 $('div.messages:visible', this).not('.help').not('.no-popup').each(function () {
1212 var text
, title
= '';
1213 $(this).removeClass('status messages');
1214 var type
= $(this).attr('class').split(' ')[0] || 'alert';
1215 type
= type
.replace('crm-', '');
1216 $('.icon', this).remove();
1217 if ($('.msg-text', this).length
> 0) {
1218 text
= $('.msg-text', this).html();
1219 title
= $('.msg-title', this).html();
1222 text
= $(this).html();
1224 var options
= $(this).data('options') || {};
1226 // Duplicates were already removed server-side
1227 options
.unique
= false;
1228 CRM
.alert(text
, title
, type
, options
);
1230 // Handle qf form errors
1231 $('form :input.error', this).one('blur', function() {
1232 $('.ui-notify-message.error a.ui-notify-close').click();
1233 $(this).removeClass('error');
1234 $(this).next('span.crm-error').remove();
1235 $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]')
1236 .removeClass('crm-error')
1237 .find('.crm-error').removeClass('crm-error');
1242 * Improve blockUI when used with jQuery dialog
1244 var originalBlock
= $.fn
.block
,
1245 originalUnblock
= $.fn
.unblock
;
1247 $.fn
.block = function(opts
) {
1248 if ($(this).is('.ui-dialog-content')) {
1249 originalBlock
.call($(this).parents('.ui-dialog'), opts
);
1252 return originalBlock
.call(this, opts
);
1254 $.fn
.unblock = function(opts
) {
1255 if ($(this).is('.ui-dialog-content')) {
1256 originalUnblock
.call($(this).parents('.ui-dialog'), opts
);
1259 return originalUnblock
.call(this, opts
);
1262 // Preprocess all CRM ajax calls to display messages
1263 $(document
).ajaxSuccess(function(event
, xhr
, settings
) {
1265 if ((!settings
.dataType
|| settings
.dataType
== 'json') && xhr
.responseText
) {
1266 var response
= $.parseJSON(xhr
.responseText
);
1267 if (typeof(response
.crmMessages
) == 'object') {
1268 $.each(response
.crmMessages
, function(n
, msg
) {
1269 CRM
.alert(msg
.text
, msg
.title
, msg
.type
, msg
.options
);
1272 if (response
.backtrace
) {
1273 CRM
.console('log', response
.backtrace
);
1275 if (typeof response
.deprecated
=== 'string') {
1276 CRM
.console('warn', response
.deprecated
);
1280 // Ignore errors thrown by parseJSON
1285 $.blockUI
.defaults
.message
= null;
1286 $.blockUI
.defaults
.ignoreIfBlocked
= true;
1288 if ($('#crm-container').hasClass('crm-public')) {
1289 $.fn
.select2
.defaults
.dropdownCssClass
= $.ui
.dialog
.prototype.options
.dialogClass
= 'crm-container crm-public';
1292 // Trigger crmLoad on initial content for consistency. It will also be triggered for ajax-loaded content.
1293 $('.crm-container').trigger('crmLoad');
1295 if ($('#crm-notification-container').length
) {
1296 // Initialize notifications
1297 $('#crm-notification-container').notify();
1298 messagesFromMarkup
.call($('#crm-container'));
1301 // Hide CiviCRM menubar when editor is fullscreen
1302 if (window
.CKEDITOR
) {
1303 CKEDITOR
.on('instanceCreated', function (e
) {
1304 e
.editor
.on('maximize', function (e
) {
1305 $('#civicrm-menu').toggle(e
.data
=== 2);
1311 // bind the event for image popup
1312 .on('click', 'a.crm-image-popup', function(e
) {
1314 title
: ts('Preview'),
1316 // Prevent overlap with the menubar
1317 maxHeight
: $(window
).height() - 30,
1318 position
: {my
: 'center', at
: 'center center+15', of: window
},
1319 message
: '<div class="crm-custom-image-popup"><img style="max-width: 100%" src="' + $(this).attr('href') + '"></div>',
1325 .on('click', function (event
) {
1326 $('.btn-slide-active').removeClass('btn-slide-active').find('.panel').hide();
1327 if ($(event
.target
).is('.btn-slide')) {
1328 $(event
.target
).addClass('btn-slide-active').find('.panel').show();
1332 // Handle clear button for form elements
1333 .on('click', 'a.crm-clear-link', function() {
1334 $(this).css({visibility
: 'hidden'}).siblings('.crm-form-radio:checked').prop('checked', false).trigger('change', ['crmClear']);
1335 $(this).siblings('input:text').val('').trigger('change', ['crmClear']);
1338 .on('change', 'input.crm-form-radio:checked', function() {
1339 $(this).siblings('.crm-clear-link').css({visibility
: ''});
1342 // Allow normal clicking of links within accordions
1343 .on('click.crmAccordions', 'div.crm-accordion-header a', function (e
) {
1344 e
.stopPropagation();
1346 // Handle accordions
1347 .on('click.crmAccordions', '.crm-accordion-header, .crm-collapsible .collapsible-title', function (e
) {
1348 if ($(this).parent().hasClass('collapsed')) {
1349 $(this).next().css('display', 'none').slideDown(200);
1352 $(this).next().css('display', 'block').slideUp(200);
1354 $(this).parent().toggleClass('collapsed');
1362 * Collapse or expand an accordion
1365 $.fn
.crmAccordionToggle = function (speed
) {
1366 $(this).each(function () {
1367 if ($(this).hasClass('collapsed')) {
1368 $('.crm-accordion-body', this).first().css('display', 'none').slideDown(speed
);
1371 $('.crm-accordion-body', this).first().css('display', 'block').slideUp(speed
);
1373 $(this).toggleClass('collapsed');
1378 * Clientside currency formatting
1379 * @param number value
1380 * @param [optional] boolean onlyNumber - if true, we return formatted amount without currency sign
1381 * @param [optional] string format - currency representation of the number 1234.56
1384 var currencyTemplate
;
1385 CRM
.formatMoney = function(value
, onlyNumber
, format
) {
1386 var decimal, separator
, sign
, i
, j
, result
;
1387 if (value
=== 'init' && format
) {
1388 currencyTemplate
= format
;
1391 format
= format
|| currencyTemplate
;
1392 result
= /1(.?)234(.?)56/.exec(format
);
1393 if (result
=== null) {
1394 return 'Invalid format passed to CRM.formatMoney';
1396 separator
= result
[1];
1397 decimal = result
[2];
1398 sign
= (value
< 0) ? '-' : '';
1399 //extracting the absolute value of the integer part of the number and converting to string
1400 i
= parseInt(value
= Math
.abs(value
).toFixed(2)) + '';
1401 j
= ((j
= i
.length
) > 3) ? j
% 3 : 0;
1402 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) : '');
1406 return format
.replace(/1.*234.*56/, result
);
1409 CRM
.console = function(method
, title
, msg
) {
1410 if (window
.console
) {
1411 method
= $.isFunction(console
[method
]) ? method
: 'log';
1412 if (msg
=== undefined) {
1413 return console
[method
](title
);
1415 return console
[method
](title
, msg
);
1420 // Determine if a user has a given permission.
1421 // @see CRM_Core_Resources::addPermissions
1422 CRM
.checkPerm = function(perm
) {
1423 return CRM
.permissions
[perm
];
1426 // Round while preserving sigfigs
1427 CRM
.utils
.sigfig = function(n
, digits
) {
1428 var len
= ("" + n
).length
;
1429 var scale
= Math
.pow(10.0, len
-digits
);
1430 return Math
.round(n
/ scale
) * scale
;