1 // https://civicrm.org/licensing
3 var cj
= CRM
.$ = jQuery
;
7 * Short-named function for string translation, defined in global scope so it's available everywhere.
9 * @param text string for translating
10 * @param params object key:value of additional parameters
14 function ts(text
, params
) {
16 text
= CRM
.strings
[text
] || text
;
17 if (typeof(params
) === 'object') {
18 for (var i
in params
) {
19 if (typeof(params
[i
]) === 'string' || typeof(params
[i
]) === 'number') {
20 // sprintf emulation: escape % characters in the replacements to avoid conflicts
21 text
= text
.replace(new RegExp('%' + i
, 'g'), String(params
[i
]).replace(/%/g
, '%-crmescaped-'));
24 return text
.replace(/%-crmescaped-/g, '%');
30 * This function is called by default at the bottom of template files which have forms that have
31 * conditionally displayed/hidden sections and elements. The PHP is responsible for generating
32 * a list of 'blocks to show' and 'blocks to hide' and the template passes these parameters to
36 * @param showBlocks Array of element Id's to be displayed
37 * @param hideBlocks Array of element Id's to be hidden
38 * @param elementType Value to set display style to for showBlocks (e.g. 'block' or 'table-row' or ...)
40 function on_load_init_blocks(showBlocks
, hideBlocks
, elementType
) {
41 if (elementType
== null) {
42 var elementType
= 'block';
45 /* This loop is used to display the blocks whose IDs are present within the showBlocks array */
46 for (var i
= 0; i
< showBlocks
.length
; i
++) {
47 var myElement
= document
.getElementById(showBlocks
[i
]);
48 /* getElementById returns null if element id doesn't exist in the document */
49 if (myElement
!= null) {
50 myElement
.style
.display
= elementType
;
53 alert('showBlocks array item not in .tpl = ' + showBlocks
[i
]);
57 /* This loop is used to hide the blocks whose IDs are present within the hideBlocks array */
58 for (var i
= 0; i
< hideBlocks
.length
; i
++) {
59 var myElement
= document
.getElementById(hideBlocks
[i
]);
60 /* getElementById returns null if element id doesn't exist in the document */
61 if (myElement
!= null) {
62 myElement
.style
.display
= 'none';
65 alert('showBlocks array item not in .tpl = ' + hideBlocks
[i
]);
71 * This function is called when we need to show or hide a related form element (target_element)
72 * based on the value (trigger_value) of another form field (trigger_field).
75 * @param trigger_field_id HTML id of field whose onchange is the trigger
76 * @param trigger_value List of integers - option value(s) which trigger show-element action for target_field
77 * @param target_element_id HTML id of element to be shown or hidden
78 * @param target_element_type Type of element to be shown or hidden ('block' or 'table-row')
79 * @param field_type Type of element radio/select
80 * @param invert Boolean - if true, we HIDE target on value match; if false, we SHOW target on value match
82 function showHideByValue(trigger_field_id
, trigger_value
, target_element_id
, target_element_type
, field_type
, invert
) {
83 if (target_element_type
== null) {
84 var target_element_type
= 'block';
87 if (target_element_type
== 'table-row') {
88 var target_element_type
= '';
92 if (field_type
== 'select') {
93 var trigger
= trigger_value
.split("|");
94 var selectedOptionValue
= cj('#' + trigger_field_id
).val();
96 var target
= target_element_id
.split("|");
97 for (var j
= 0; j
< target
.length
; j
++) {
99 cj('#' + target
[j
]).show();
102 cj('#' + target
[j
]).hide();
104 for (var i
= 0; i
< trigger
.length
; i
++) {
105 if (selectedOptionValue
== trigger
[i
]) {
107 cj('#' + target
[j
]).hide();
110 cj('#' + target
[j
]).show();
118 if (field_type
== 'radio') {
119 var target
= target_element_id
.split("|");
120 for (var j
= 0; j
< target
.length
; j
++) {
121 if (cj('[name="' + trigger_field_id
+ '"]').is(':checked')) {
123 cj('#' + target
[j
]).hide();
126 cj('#' + target
[j
]).show();
131 cj('#' + target
[j
]).show();
134 cj('#' + target
[j
]).hide();
143 * Function to change button text and disable one it is clicked
145 * @param obj object - the button clicked
146 * @param formID string - the id of the form being submitted
147 * @param string procText - button text after user clicks it
151 /* Changes button label on submit, and disables button after submit for newer browsers.
152 Puts up alert for older browsers. */
153 function submitOnce(obj
, formId
, procText
) {
154 // if named button clicked, change text
155 if (obj
.value
!= null) {
156 obj
.value
= procText
+ " ...";
158 if (document
.getElementById
) { // disable submit button for newer browsers
160 document
.getElementById(formId
).submit();
163 else { // for older browsers
164 if (submitcount
== 0) {
169 alert("Your request is currently being processed ... Please wait.");
176 * Function to show / hide the row in optionFields
178 * @param index string, element whose innerHTML is to hide else will show the hidden row.
180 function showHideRow(index
) {
182 cj('tr#optionField_' + index
).hide();
183 if (cj('table#optionField tr:hidden:first').length
) {
184 cj('div#optionFieldLink').show();
188 cj('table#optionField tr:hidden:first').show();
189 if (!cj('table#optionField tr:hidden:last').length
) {
190 cj('div#optionFieldLink').hide();
196 CRM
.utils
= CRM
.utils
|| {};
197 CRM
.strings
= CRM
.strings
|| {};
198 CRM
.validate
= CRM
.validate
|| {
203 (function ($, _
, undefined) {
206 // Theme classes for unattached elements
207 $.fn
.select2
.defaults
.dropdownCssClass
= $.ui
.dialog
.prototype.options
.dialogClass
= 'crm-container';
209 // https://github.com/ivaynberg/select2/pull/2090
210 $.fn
.select2
.defaults
.width
= 'resolve';
212 // Workaround for https://github.com/ivaynberg/select2/issues/1246
213 $.ui
.dialog
.prototype._allowInteraction = function(e
) {
214 return !!$(e
.target
).closest('.ui-dialog, .ui-datepicker, .select2-drop').length
;
218 * Populate a select list, overwriting the existing options except for the placeholder.
219 * @param $el jquery collection - 1 or more select elements
220 * @param options array in format returned by api.getoptions
221 * @param removePlaceholder bool
223 CRM
.utils
.setOptions = function($el
, options
, removePlaceholder
) {
224 $el
.each(function() {
227 val
= $elect
.val() || [],
228 opts
= removePlaceholder
? '' : '[value!=""]';
229 if (!$.isArray(val
)) {
232 $elect
.find('option' + opts
).remove();
233 _
.each(options
, function(option
) {
234 var selected
= ($.inArray(''+option
.key
, val
) > -1) ? 'selected="selected"' : '';
235 $elect
.append('<option value="' + option
.key
+ '"' + selected
+ '>' + option
.value
+ '</option>');
237 $elect
.trigger('crmOptionsUpdated', $.extend({}, options
)).trigger('change');
242 * Wrapper for select2 initialization function; supplies defaults
243 * @param options object
245 $.fn
.crmSelect2 = function(options
) {
246 return $(this).each(function () {
249 settings
= {allowClear
: !$el
.hasClass('required')};
250 // quickform doesn't support optgroups so here's a hack :(
251 $('option[value^=crm_optgroup]', this).each(function () {
252 $(this).nextUntil('option[value^=crm_optgroup]').wrapAll('<optgroup label="' + $(this).text() + '" />');
255 // Defaults for single-selects
256 if ($el
.is('select:not([multiple])')) {
257 settings
.minimumResultsForSearch
= 10;
258 if ($('option:first', this).val() === '') {
259 settings
.placeholderOption
= 'first';
262 $.extend(settings
, $el
.data('select-params') || {}, options
|| {});
264 $el
.addClass('crm-ajax-select');
266 $el
.select2(settings
);
271 * @see CRM_Core_Form::addEntityRef for docs
272 * @param options object
274 $.fn
.crmEntityRef = function(options
) {
275 options
= options
|| {};
276 options
.select
= options
.select
|| {};
277 return $(this).each(function() {
279 $el
= $(this).off('.crmEntity'),
280 entity
= options
.entity
|| $el
.data('api-entity') || 'contact',
282 $el
.data('api-entity', entity
);
283 $el
.data('select-params', $.extend({}, $el
.data('select-params') || {}, options
.select
));
284 $el
.data('api-params', $.extend({}, $el
.data('api-params') || {}, options
.api
));
285 $el
.data('create-links', options
.create
|| $el
.data('create-links'));
286 $el
.addClass('crm-form-entityref crm-' + entity
+ '-ref');
288 // Use select2 ajax helper instead of CRM.api because it provides more value
290 url
: CRM
.url('civicrm/ajax/rest'),
291 data: function (input
, page_num
) {
292 var params
= $el
.data('api-params') || {};
293 params
.input
= input
;
294 params
.page_num
= page_num
;
296 entity
: $el
.data('api-entity'),
298 json
: JSON
.stringify(params
)
301 results: function(data
) {
302 return {more
: data
.more_results
, results
: data
.values
|| []};
305 minimumInputLength
: 1,
306 formatResult
: formatSelect2Result
,
307 formatSelection: function(row
) {
310 escapeMarkup: function (m
) {return m
;},
311 initSelection: function($el
, callback
) {
313 multiple
= !!$el
.data('select-params').multiple
,
315 stored
= $el
.data('entity-value') || [];
319 // If we already have this data, just return it
320 if (!_
.xor(val
.split(','), _
.pluck(stored
, 'id')).length
) {
321 callback(multiple
? stored
: stored
[0]);
323 var params
= $.extend({}, $el
.data('api-params') || {}, {id
: val
});
324 CRM
.api3($el
.data('api-entity'), 'getlist', params
).done(function(result
) {
325 callback(multiple
? result
.values
: result
.values
[0])
330 if ($el
.data('create-links') && entity
.toLowerCase() === 'contact') {
331 selectParams
.formatInputTooShort = function() {
332 var txt
= $el
.data('select-params').formatInputTooShort
|| $.fn
.select2
.defaults
.formatInputTooShort
.call(this);
333 if ($el
.data('create-links')) {
334 txt
+= ' ' + ts('or') + '<br />' + formatSelect2CreateLinks($el
);
338 selectParams
.formatNoMatches = function() {
339 var txt
= $el
.data('select-params').formatNoMatches
|| $.fn
.select2
.defaults
.formatNoMatches
;
340 return txt
+ '<br />' + formatSelect2CreateLinks($el
);
342 $el
.on('select2-open.crmEntity', function() {
344 $('#select2-drop').off('.crmEntity').on('click.crmEntity', 'a.crm-add-entity', function(e
) {
345 $el
.select2('close');
346 CRM
.loadForm($(this).attr('href'), {
347 dialog
: {width
: 500, height
: 'auto'}
348 }).on('crmFormSuccess', function(e
, data
) {
349 if (data
.status
=== 'success' && data
.id
) {
350 CRM
.status(ts('%1 Created', {1: data
.label
}));
351 if ($el
.select2('container').hasClass('select2-container-multi')) {
352 var selection
= $el
.select2('data');
353 selection
.push(data
);
354 $el
.select2('data', selection
, true);
356 $el
.select2('data', data
, true);
364 // Create new items inline - works for tags
365 else if ($el
.data('create-links')) {
366 selectParams
.createSearchChoice = function(term
, data
) {
367 if (!_
.findKey(data
, {label
: term
})) {
368 return {id
: "0", term
: term
, label
: term
+ ' (' + ts('new tag') + ')'};
371 selectParams
.tokenSeparators
= [','];
372 selectParams
.createSearchChoicePosition
= 'bottom';
374 $el
.crmSelect2($.extend(settings
, $el
.data('select-params'), selectParams
))
375 .on('select2-selecting.crmEntity', function(e
) {
377 e
.object
.label
= e
.object
.term
;
378 CRM
.api3(entity
, 'create', $.extend({name
: e
.object
.term
}, $el
.data('api-params').params
|| {}))
379 .done(function(created
) {
381 multiple
= !!$el
.data('select-params').multiple
,
382 val
= $el
.select2('val'),
383 data
= $el
.select2('data'),
384 item
= {id
: created
.id
, label
: e
.object
.term
};
386 $el
.select2('data', item
, true);
388 else if ($.isArray(val
) && $.inArray("0", val
) > -1) {
389 _
.remove(data
, {id
: "0"});
391 $el
.select2('data', data
, true);
399 function formatSelect2Result(row
) {
400 var markup
= '<div class="crm-select2-row">';
401 if (row
.image
!== undefined) {
402 markup
+= '<div class="crm-select2-image"><img src="' + row
.image
+ '"/></div>';
404 else if (row
.icon_class
) {
405 markup
+= '<div class="crm-select2-icon"><div class="crm-icon ' + row
.icon_class
+ '-icon"></div></div>';
407 markup
+= '<div><div class="crm-select2-row-label">' + row
.label
+ '</div>';
408 markup
+= '<div class="crm-select2-row-description">';
409 $.each(row
.description
|| [], function(k
, text
) {
410 markup
+= '<p>' + text
+ '</p>';
412 markup
+= '</div></div></div>';
416 function formatSelect2CreateLinks($el
) {
418 createLinks
= $el
.data('create-links'),
419 api
= $el
.data('api-params') || {},
420 type
= api
.params
? api
.params
.contact_type
: null;
421 if (createLinks
=== true) {
422 createLinks
= type
? _
.where(CRM
.profile
.contactCreate
, {type
: type
}) : CRM
.profile
.contactCreate
;
425 _
.each(createLinks
, function(link
) {
426 markup
+= ' <a class="crm-add-entity crm-hover-button" href="' + link
.url
+ '">';
428 markup
+= '<span class="icon ' + link
.type
+ '-profile-icon"></span> ';
430 markup
+= link
.label
+ '</a>';
435 // Initialize widgets
437 .on('crmLoad', function(e
) {
438 $('table.row-highlight', e
.target
)
439 .off('.rowHighlight')
440 .on('change.rowHighlight', 'input.select-row, input.select-rows', function (e
, data
) {
441 var filter
, $table
= $(this).closest('table');
442 if ($(this).hasClass('select-rows')) {
443 filter
= $(this).prop('checked') ? ':not(:checked)' : ':checked';
444 $('input.select-row' + filter
, $table
).prop('checked', $(this).prop('checked')).trigger('change', 'master-selected');
447 $(this).closest('tr').toggleClass('crm-row-selected', $(this).prop('checked'));
448 if (data
!== 'master-selected') {
449 $('input.select-rows', $table
).prop('checked', $(".select-row:not(':checked')", $table
).length
< 1);
453 .find('input.select-row:checked').parents('tr').addClass('crm-row-selected');
454 $('.crm-select2:not(.select2-offscreen, .select2-container)', e
.target
).crmSelect2();
455 $('.crm-form-entityref:not(.select2-offscreen, .select2-container)', e
.target
).crmEntityRef();
457 .on('dialogopen', function(e
) {
458 var $el
= $(e
.target
);
459 // Modal dialogs should disable scrollbars
460 if ($el
.dialog('option', 'modal')) {
461 $el
.addClass('modal-dialog');
462 $('body').css({overflow
: 'hidden'});
464 $el
.parent().find('.ui-dialog-titlebar-close').attr('title', ts('Close'));
466 if ($el
.parent().hasClass('crm-container') && $el
.dialog('option', 'resizable')) {
467 $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}));
468 $('.crm-dialog-titlebar-resize', $el
.parent()).click(function(e
) {
469 if ($el
.data('origSize')) {
470 $el
.dialog('option', $el
.data('origSize'));
471 $el
.data('origSize', null);
473 $el
.data('origSize', {
475 width
: $el
.dialog('option', 'width'),
476 height
: $el
.dialog('option', 'height')
478 var menuHeight
= $('#civicrm-menu').height();
479 $el
.dialog('option', {width
: '100%', height
: ($(window
).height() - menuHeight
), position
: [0, menuHeight
]});
485 .on('dialogclose', function(e
) {
486 // Restore scrollbars when closing modal
487 if ($('.ui-dialog .modal-dialog').not(e
.target
).length
< 1) {
488 $('body').css({overflow
: ''});
493 * Function to make multiselect boxes behave as fields in small screens
495 function advmultiselectResize() {
496 var amswidth
= $("#crm-container form:has(table.advmultiselect)").width();
497 if (amswidth
< 700) {
498 $("form table.advmultiselect td").css('display', 'block');
501 $("form table.advmultiselect td").css('display', 'table-cell');
503 var contactwidth
= $('#crm-container #mainTabContainer').width();
504 if (contactwidth
< 600) {
505 $('#crm-container #mainTabContainer').addClass('narrowpage');
506 $('#crm-container #mainTabContainer.narrowpage #contactTopBar td').each(function (index
) {
508 if (index
% 2 == 0) {
509 $(this).parent().after('<tr class="narrowadded"></tr>');
512 $(this).parent().next().append(item
);
517 $('#crm-container #mainTabContainer.narrowpage').removeClass('narrowpage');
518 $('#crm-container #mainTabContainer #contactTopBar tr.narrowadded td').each(function () {
520 var parent
= $(this).parent();
521 $(this).parent().prev().append(nitem
);
522 if (parent
.children().size() == 0) {
526 $('#crm-container #mainTabContainer.narrowpage #contactTopBar tr.added').detach();
528 var cformwidth
= $('#crm-container #Contact .contact_basic_information-section').width();
530 if (cformwidth
< 720) {
531 $('#crm-container .contact_basic_information-section').addClass('narrowform');
532 $('#crm-container .contact_basic_information-section table.form-layout-compressed td .helpicon').parent().addClass('hashelpicon');
533 if (cformwidth
< 480) {
534 $('#crm-container .contact_basic_information-section').addClass('xnarrowform');
537 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
541 $('#crm-container .contact_basic_information-section.narrowform').removeClass('narrowform');
542 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
546 advmultiselectResize();
547 $(window
).resize(function () {
548 advmultiselectResize();
551 $.fn
.crmtooltip = function () {
553 .on('mouseover', 'a.crm-summary-link:not(.crm-processed)', function (e
) {
554 $(this).addClass('crm-processed');
555 $(this).addClass('crm-tooltip-active');
556 var topDistance
= e
.pageY
- $(window
).scrollTop();
557 if (topDistance
< 300 | topDistance
< $(this).children('.crm-tooltip-wrapper').height()) {
558 $(this).addClass('crm-tooltip-down');
560 if (!$(this).children('.crm-tooltip-wrapper').length
) {
561 $(this).append('<div class="crm-tooltip-wrapper"><div class="crm-tooltip"></div></div>');
562 $(this).children().children('.crm-tooltip')
563 .html('<div class="crm-loading-element"></div>')
567 .on('mouseout', 'a.crm-summary-link', function () {
568 $(this).removeClass('crm-processed');
569 $(this).removeClass('crm-tooltip-active crm-tooltip-down');
571 .on('click', 'a.crm-summary-link', false);
574 var helpDisplay
, helpPrevious
;
575 CRM
.help = function (title
, params
, url
) {
576 if (helpDisplay
&& helpDisplay
.close
) {
577 // If the same link is clicked twice, just close the display - todo use underscore method for this comparison
578 if (helpDisplay
.isOpen
&& helpPrevious
=== JSON
.stringify(params
)) {
584 helpPrevious
= JSON
.stringify(params
);
585 params
.class_name
= 'CRM_Core_Page_Inline_Help';
586 params
.type
= 'page';
587 helpDisplay
= CRM
.alert('...', title
, 'crm-help crm-msg-loading', {expires
: 0});
588 $.ajax(url
|| CRM
.url('civicrm/ajax/inline'),
592 success: function (data
) {
593 $('#crm-notification-container .crm-help .notify-content:last').html(data
);
594 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('info');
597 $('#crm-notification-container .crm-help .notify-content:last').html('Unable to load help file.');
598 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('error');
604 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
606 CRM
.status = function(options
, deferred
) {
607 // 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.
608 if (typeof options
=== 'string') {
609 return CRM
.status({start
: options
, success
: options
, error
: options
})[deferred
=== 'error' ? 'reject' : 'resolve']();
611 var opts
= $.extend({
612 start
: ts('Saving...'),
613 success
: ts('Saved'),
615 CRM
.alert(ts('Sorry an error occurred and your information was not saved'), ts('Error'));
618 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>')
620 $msg
.css('min-width', $msg
.width());
621 function handle(status
, data
) {
622 var endMsg
= typeof(opts
[status
]) === 'function' ? opts
[status
](data
) : opts
[status
];
624 $msg
.removeClass('status-start').addClass('status-' + status
).find('.crm-status-box-msg').html(endMsg
);
625 window
.setTimeout(function() {
626 $msg
.fadeOut('slow', function() {$msg
.remove()});
632 return (deferred
|| new $.Deferred())
633 .done(function(data
) {
634 // If the server returns an error msg call the error handler
635 var status
= $.isPlainObject(data
) && (data
.is_error
|| data
.status
=== 'error') ? 'error' : 'success';
636 handle(status
, data
);
638 .fail(function(data
) {
639 handle('error', data
);
644 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
646 CRM
.alert = function (text
, title
, type
, options
) {
647 type
= type
|| 'alert';
649 options
= options
|| {};
650 if ($('#crm-notification-container').length
) {
656 // By default, don't expire errors and messages containing links
658 expires
: (type
== 'error' || text
.indexOf('<a ') > -1) ? 0 : (text
? 10000 : 5000),
661 options
= $.extend(extra
, options
);
662 options
.expires
= options
.expires
=== false ? 0 : parseInt(options
.expires
, 10);
663 if (options
.unique
&& options
.unique
!== '0') {
664 $('#crm-notification-container .ui-notify-message').each(function () {
665 if (title
=== $('h1', this).html() && text
=== $('.notify-content', this).html()) {
666 $('.icon.ui-notify-close', this).click();
670 return $('#crm-notification-container').notify('create', params
, options
);
674 text
= title
+ "\n" + text
;
682 * Close whichever alert contains the given node
686 CRM
.closeAlertByChild = function (node
) {
687 $(node
).closest('.ui-notify-message').find('.icon.ui-notify-close').click();
691 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
693 CRM
.confirm = function (options
) {
694 var dialog
, settings
= {
695 title
: ts('Confirm Action'),
696 message
: ts('Are you sure you want to continue?'),
700 dialogClass
: 'crm-container crm-confirm',
702 $(this).dialog('destroy').remove();
709 $.extend(settings
, ($.isFunction(options
) ? arguments
[1] : options
) || {});
710 if (!settings
.buttons
&& $.isPlainObject(settings
.options
)) {
711 settings
.buttons
= [];
712 $.each(settings
.options
, function(key
, label
) {
713 settings
.buttons
.push({
716 var event
= $.Event('crmConfirm:' + key
);
717 $(this).trigger(event
);
718 if (!event
.isDefaultPrevented()) {
719 dialog
.dialog('close');
725 dialog
= $('<div class="crm-confirm-dialog"></div>').html(settings
.message
);
726 delete settings
.options
;
727 delete settings
.message
;
728 if ($.isFunction(options
)) {
729 dialog
.on('crmConfirm:yes', options
);
731 return dialog
.dialog(settings
).trigger('crmLoad');
735 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
737 $.fn
.crmError = function (text
, title
, options
) {
740 options
= options
|| {};
745 if ($(this).length
) {
747 var label
= $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]').not('[generated=true]');
749 label
.addClass('crm-error');
750 var $label
= label
.clone();
751 if (text
== '' && $('.crm-marker', $label
).length
> 0) {
752 text
= $('.crm-marker', $label
).attr('title');
754 $('.crm-marker', $label
).remove();
755 title
= $label
.text();
758 $(this).addClass('error');
760 var msg
= CRM
.alert(text
, title
, 'error', $.extend(extra
, options
));
761 if ($(this).length
) {
763 setTimeout(function () {
764 ele
.one('change', function () {
765 msg
&& msg
.close
&& msg
.close();
766 ele
.removeClass('error');
767 label
.removeClass('crm-error');
774 // Display system alerts through js notifications
775 function messagesFromMarkup() {
776 $('div.messages:visible', this).not('.help').not('.no-popup').each(function () {
777 var text
, title
= '';
778 $(this).removeClass('status messages');
779 var type
= $(this).attr('class').split(' ')[0] || 'alert';
780 type
= type
.replace('crm-', '');
781 $('.icon', this).remove();
782 if ($('.msg-text', this).length
> 0) {
783 text
= $('.msg-text', this).html();
784 title
= $('.msg-title', this).html();
787 text
= $(this).html();
789 var options
= $(this).data('options') || {};
791 // Duplicates were already removed server-side
792 options
.unique
= false;
793 CRM
.alert(text
, title
, type
, options
);
795 // Handle qf form errors
796 $('form :input.error', this).one('blur', function() {
797 $('.ui-notify-message.error a.ui-notify-close').click();
798 $(this).removeClass('error');
799 $(this).next('span.crm-error').remove();
800 $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]')
801 .removeClass('crm-error')
802 .find('.crm-error').removeClass('crm-error');
806 // Preprocess all cj ajax calls to display messages
807 $(document
).ajaxSuccess(function(event
, xhr
, settings
) {
809 if ((!settings
.dataType
|| settings
.dataType
== 'json') && xhr
.responseText
) {
810 var response
= $.parseJSON(xhr
.responseText
);
811 if (typeof(response
.crmMessages
) == 'object') {
812 $.each(response
.crmMessages
, function(n
, msg
) {
813 CRM
.alert(msg
.text
, msg
.title
, msg
.type
, msg
.options
);
823 * Temporary stub to get around name conflict with legacy jQuery.autocomplete plugin
824 * FIXME: Remove this before 4.5 release
826 $.widget('civi.crmAutocomplete', $.ui
.autocomplete
, {});
829 // Trigger crmLoad on initial content for consistency. It will also be triggered for ajax-loaded content.
830 $('.crm-container').trigger('crmLoad');
832 if ($('#crm-notification-container').length
) {
833 // Initialize notifications
834 $('#crm-notification-container').notify();
835 messagesFromMarkup
.call($('#crm-container'));
839 // bind the event for image popup
840 .on('click', 'a.crm-image-popup', function(e
) {
842 title
: ts('Preview'),
844 message
: '<div class="crm-custom-image-popup"><img src=' + $(this).attr('href') + '></div>',
850 .on('click', function (event
) {
851 $('.btn-slide-active').removeClass('btn-slide-active').find('.panel').hide();
852 if ($(event
.target
).is('.btn-slide')) {
853 $(event
.target
).addClass('btn-slide-active').find('.panel').show();
857 // Handle clear button for form elements
858 .on('click', 'a.crm-clear-link', function() {
859 $(this).css({visibility
: 'hidden'}).siblings('.crm-form-radio:checked').prop('checked', false).change();
860 $(this).siblings('input:text').val('').change();
863 .on('change', 'input.crm-form-radio:checked', function() {
864 $(this).siblings('.crm-clear-link').css({visibility
: ''});
867 // Allow normal clicking of links within accordions
868 .on('click.crmAccordions', 'div.crm-accordion-header a', function (e
) {
872 .on('click.crmAccordions', '.crm-accordion-header, .crm-collapsible .collapsible-title', function (e
) {
873 if ($(this).parent().hasClass('collapsed')) {
874 $(this).next().css('display', 'none').slideDown(200);
877 $(this).next().css('display', 'block').slideUp(200);
879 $(this).parent().toggleClass('collapsed');
888 $.fn
.crmAccordions = function () {};
890 * Collapse or expand an accordion
893 $.fn
.crmAccordionToggle = function (speed
) {
894 $(this).each(function () {
895 if ($(this).hasClass('collapsed')) {
896 $('.crm-accordion-body', this).first().css('display', 'none').slideDown(speed
);
899 $('.crm-accordion-body', this).first().css('display', 'block').slideUp(speed
);
901 $(this).toggleClass('collapsed');
906 * Clientside currency formatting
908 * @param format - currency representation of the number 1234.56
910 * @see CRM_Core_Resources::addCoreResources
912 var currencyTemplate
;
913 CRM
.formatMoney = function(value
, format
) {
914 var decimal, separator
, sign
, i
, j
, result
;
915 if (value
=== 'init' && format
) {
916 currencyTemplate
= format
;
919 format
= format
|| currencyTemplate
;
920 result
= /1(.?)234(.?)56/.exec(format
);
921 if (result
=== null) {
922 return 'Invalid format passed to CRM.formatMoney';
924 separator
= result
[1];
926 sign
= (value
< 0) ? '-' : '';
927 //extracting the absolute value of the integer part of the number and converting to string
928 i
= parseInt(value
= Math
.abs(value
).toFixed(2)) + '';
929 j
= ((j
= i
.length
) > 3) ? j
% 3 : 0;
930 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) : '');
931 return format
.replace(/1.*234.*56/, result
);