1 // https://civicrm.org/licensing
6 * Short-named function for string translation, defined in global scope so it's available everywhere.
8 * @param text string for translating
9 * @param params object key:value of additional parameters
13 function ts(text
, params
) {
15 text
= CRM
.strings
[text
] || text
;
16 if (typeof(params
) === 'object') {
17 for (var i
in params
) {
18 if (typeof(params
[i
]) === 'string' || typeof(params
[i
]) === 'number') {
19 // sprintf emulation: escape % characters in the replacements to avoid conflicts
20 text
= text
.replace(new RegExp('%' + i
, 'g'), String(params
[i
]).replace(/%/g
, '%-crmescaped-'));
23 return text
.replace(/%-crmescaped-/g, '%');
29 * This function is called by default at the bottom of template files which have forms that have
30 * conditionally displayed/hidden sections and elements. The PHP is responsible for generating
31 * a list of 'blocks to show' and 'blocks to hide' and the template passes these parameters to
35 * @param showBlocks Array of element Id's to be displayed
36 * @param hideBlocks Array of element Id's to be hidden
37 * @param elementType Value to set display style to for showBlocks (e.g. 'block' or 'table-row' or ...)
39 function on_load_init_blocks(showBlocks
, hideBlocks
, elementType
) {
40 if (elementType
== null) {
41 var elementType
= 'block';
44 /* This loop is used to display the blocks whose IDs are present within the showBlocks array */
45 for (var i
= 0; i
< showBlocks
.length
; i
++) {
46 var myElement
= document
.getElementById(showBlocks
[i
]);
47 /* getElementById returns null if element id doesn't exist in the document */
48 if (myElement
!= null) {
49 myElement
.style
.display
= elementType
;
52 alert('showBlocks array item not in .tpl = ' + showBlocks
[i
]);
56 /* This loop is used to hide the blocks whose IDs are present within the hideBlocks array */
57 for (var i
= 0; i
< hideBlocks
.length
; i
++) {
58 var myElement
= document
.getElementById(hideBlocks
[i
]);
59 /* getElementById returns null if element id doesn't exist in the document */
60 if (myElement
!= null) {
61 myElement
.style
.display
= 'none';
64 alert('showBlocks array item not in .tpl = ' + hideBlocks
[i
]);
70 * This function is called when we need to show or hide a related form element (target_element)
71 * based on the value (trigger_value) of another form field (trigger_field).
74 * @param trigger_field_id HTML id of field whose onchange is the trigger
75 * @param trigger_value List of integers - option value(s) which trigger show-element action for target_field
76 * @param target_element_id HTML id of element to be shown or hidden
77 * @param target_element_type Type of element to be shown or hidden ('block' or 'table-row')
78 * @param field_type Type of element radio/select
79 * @param invert Boolean - if true, we HIDE target on value match; if false, we SHOW target on value match
81 function showHideByValue(trigger_field_id
, trigger_value
, target_element_id
, target_element_type
, field_type
, invert
) {
82 if (target_element_type
== null) {
83 var target_element_type
= 'block';
86 if (target_element_type
== 'table-row') {
87 var target_element_type
= '';
91 if (field_type
== 'select') {
92 var trigger
= trigger_value
.split("|");
93 var selectedOptionValue
= cj('#' + trigger_field_id
).val();
95 var target
= target_element_id
.split("|");
96 for (var j
= 0; j
< target
.length
; j
++) {
98 cj('#' + target
[j
]).show();
101 cj('#' + target
[j
]).hide();
103 for (var i
= 0; i
< trigger
.length
; i
++) {
104 if (selectedOptionValue
== trigger
[i
]) {
106 cj('#' + target
[j
]).hide();
109 cj('#' + target
[j
]).show();
117 if (field_type
== 'radio') {
118 var target
= target_element_id
.split("|");
119 for (var j
= 0; j
< target
.length
; j
++) {
120 if (cj('[name="' + trigger_field_id
+ '"]').is(':checked')) {
122 cj('#' + target
[j
]).hide();
125 cj('#' + target
[j
]).show();
130 cj('#' + target
[j
]).show();
133 cj('#' + target
[j
]).hide();
142 * Function to change button text and disable one it is clicked
144 * @param obj object - the button clicked
145 * @param formID string - the id of the form being submitted
146 * @param string procText - button text after user clicks it
150 /* Changes button label on submit, and disables button after submit for newer browsers.
151 Puts up alert for older browsers. */
152 function submitOnce(obj
, formId
, procText
) {
153 // if named button clicked, change text
154 if (obj
.value
!= null) {
155 obj
.value
= procText
+ " ...";
157 if (document
.getElementById
) { // disable submit button for newer browsers
159 document
.getElementById(formId
).submit();
162 else { // for older browsers
163 if (submitcount
== 0) {
168 alert("Your request is currently being processed ... Please wait.");
176 function popUp(URL
) {
179 eval("page" + id
+ " = window.open(URL, '" + id
+ "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=640,height=420,left = 202,top = 184');");
183 * Function to show / hide the row in optionFields
185 * @param index string, element whose innerHTML is to hide else will show the hidden row.
187 function showHideRow(index
) {
189 cj('tr#optionField_' + index
).hide();
190 if (cj('table#optionField tr:hidden:first').length
) {
191 cj('div#optionFieldLink').show();
195 cj('table#optionField tr:hidden:first').show();
196 if (!cj('table#optionField tr:hidden:last').length
) {
197 cj('div#optionFieldLink').hide();
203 CRM
.utils
= CRM
.utils
|| {};
204 CRM
.strings
= CRM
.strings
|| {};
205 CRM
.validate
= CRM
.validate
|| {
210 (function ($, undefined) {
213 $.fn
.select2
.defaults
.dropdownCssClass
= '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').length
;
223 * Populate a select list, overwriting the existing options except for the placeholder.
224 * @param $el jquery collection - 1 or more select elements
225 * @param options array in format returned by api.getoptions
226 * @param removePlaceholder bool
228 CRM
.utils
.setOptions = function($el
, options
, removePlaceholder
) {
229 $el
.each(function() {
232 val
= $elect
.val() || [],
233 opts
= removePlaceholder
? '' : '[value!=""]';
234 if (typeof(val
) !== 'array') {
237 $elect
.find('option' + opts
).remove();
238 _
.each(options
, function(option
) {
239 var selected
= ($.inArray(''+option
.key
, val
) > -1) ? 'selected="selected"' : '';
240 $elect
.append('<option value="' + option
.key
+ '"' + selected
+ '>' + option
.value
+ '</option>');
242 $elect
.trigger('crmOptionsUpdated', $.extend({}, options
)).trigger('change');
247 * Wrapper for select2 initialization function; supplies defaults
248 * @param options object
250 $.fn
.crmSelect2 = function(options
) {
251 return $(this).each(function () {
254 defaults
= {allowClear
: !$el
.hasClass('required')};
255 // quickform doesn't support optgroups so here's a hack :(
256 $('option[value^=crm_optgroup]', this).each(function () {
257 $(this).nextUntil('option[value^=crm_optgroup]').wrapAll('<optgroup label="' + $(this).text() + '" />');
260 // Defaults for single-selects
261 if ($el
.is('select:not([multiple])')) {
262 defaults
.minimumResultsForSearch
= 10;
263 if ($('option:first', this).val() === '') {
264 defaults
.placeholderOption
= 'first';
267 $el
.select2($.extend(defaults
, $el
.data('select-params') || {}, options
|| {}));
272 * @see CRM_Core_Form::addEntityRef for docs
273 * @param options object
275 $.fn
.crmEntityRef = function(options
) {
276 options
= options
|| {};
277 options
.select
= options
.select
|| {};
278 return $(this).each(function() {
281 entity
= options
.entity
|| $el
.data('api-entity') || 'contact',
283 $el
.data('api-entity', entity
);
284 $el
.data('select-params', $.extend({}, $el
.data('select-params') || {}, options
.select
));
285 $el
.data('api-params', $.extend({}, $el
.data('api-params') || {}, options
.api
));
286 $el
.data('create-links', options
.create
|| $el
.data('create-links'));
287 $el
.addClass('crm-ajax-select crm-' + entity
+ '-ref');
289 // Use select2 ajax helper instead of CRM.api because it provides more value
291 url
: CRM
.url('civicrm/ajax/rest'),
292 data: function (input
, page_num
) {
293 var params
= $el
.data('api-params') || {};
294 params
.input
= input
;
295 params
.page_num
= page_num
;
297 entity
: $el
.data('api-entity'),
299 json
: JSON
.stringify(params
)
302 results: function(data
) {
303 return {more
: data
.more_results
, results
: data
.values
|| []};
306 minimumInputLength
: 1,
307 formatResult
: formatSelect2Result
,
308 formatSelection: function(row
) {
311 escapeMarkup: function (m
) {return m
;},
312 initSelection: function($el
, callback
) {
314 multiple
= !!$el
.data('select-params').multiple
,
316 stored
= $el
.data('entity-value') || [];
320 // If we already have this data, just return it
321 if (!_
.xor(val
.split(','), _
.pluck(stored
, 'id')).length
) {
322 callback(multiple
? stored
: stored
[0]);
324 var params
= $.extend({}, $el
.data('api-params') || {}, {id
: val
});
325 CRM
.api3($el
.data('api-entity'), 'getlist', params
).done(function(result
) {
326 callback(multiple
? result
.values
: result
.values
[0])
331 if ($el
.data('create-links')) {
332 selectParams
.formatInputTooShort = function() {
333 var txt
= $el
.data('select-params').formatInputTooShort
|| $.fn
.select2
.defaults
.formatInputTooShort
.call(this);
334 if ($el
.data('create-links')) {
335 txt
+= ' ' + ts('or') + '<br />' + formatSelect2CreateLinks($el
);
339 selectParams
.formatNoMatches = function() {
340 var txt
= $el
.data('select-params').formatNoMatches
|| $.fn
.select2
.defaults
.formatNoMatches
;
341 return txt
+ '<br />' + formatSelect2CreateLinks($el
);
343 $el
.off('.createLinks').on('select2-open.createLinks', function() {
345 $('#select2-drop').off('.crmEntity').on('click.crmEntity', 'a.crm-add-entity', function(e
) {
346 $el
.select2('close');
347 CRM
.loadForm($(this).attr('href'), {
348 dialog
: {width
: 500, height
: 'auto'}
349 }).on('crmFormSuccess', function(e
, data
) {
350 if (data
.status
=== 'success' && data
.id
) {
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 $el
.crmSelect2($.extend(settings
, $el
.data('select-params'), selectParams
));
368 function formatSelect2Result(row
) {
369 var markup
= '<div class="crm-select2-row">';
370 if (row
.image
!== undefined) {
371 markup
+= '<div class="crm-select2-image"><img src="' + row
.image
+ '"/></div>';
373 else if (row
.icon_class
) {
374 markup
+= '<div class="crm-select2-icon"><div class="crm-icon ' + row
.icon_class
+ '-icon"></div></div>';
376 markup
+= '<div><div class="crm-select2-row-label">' + row
.label
+ '</div>';
377 markup
+= '<div class="crm-select2-row-description">';
378 $.each(row
.description
|| [], function(k
, text
) {
379 markup
+= '<p>' + text
+ '</p>';
381 markup
+= '</div></div></div>';
385 function formatSelect2CreateLinks($el
) {
387 createLinks
= $el
.data('create-links'),
388 api
= $el
.data('api-params') || {},
389 type
= api
.params
? api
.params
.contact_type
: null;
390 if (createLinks
=== true) {
391 createLinks
= type
? _
.where(CRM
.profile
.contactCreate
, {type
: type
}) : CRM
.profile
.contactCreate
;
394 _
.each(createLinks
, function(link
) {
395 markup
+= ' <a class="crm-add-entity crm-hover-button" href="' + link
.url
+ '">';
397 markup
+= '<span class="icon ' + link
.type
+ '-profile-icon"></span> ';
399 markup
+= link
.label
+ '</a>';
404 // Initialize widgets
406 .on('crmLoad', function(e
) {
407 $('table.row-highlight', e
.target
)
408 .off('.rowHighlight')
409 .on('change.rowHighlight', 'input.select-row, input.select-rows', function () {
410 var target
, table
= $(this).closest('table');
411 if ($(this).hasClass('select-rows')) {
412 target
= $('tbody tr', table
);
413 $('input.select-row', table
).prop('checked', $(this).prop('checked'));
416 target
= $(this).closest('tr');
417 $('input.select-rows', table
).prop('checked', $(".select-row:not(':checked')", table
).length
< 1);
419 target
.toggleClass('crm-row-selected', $(this).is(':checked'));
421 .find('input.select-row:checked').parents('tr').addClass('crm-row-selected');
422 $('.crm-select2:not(.select2-offscreen)', e
.target
).crmSelect2();
423 $('.crm-form-entityref:not(.select2-offscreen)', e
.target
).crmEntityRef();
425 // Modal dialogs should disable scrollbars
426 .on('dialogopen', function(e
) {
427 if ($(e
.target
).dialog('option', 'modal')) {
428 $(e
.target
).addClass('modal-dialog');
429 $('body').css({overflow
: 'hidden'});
432 .on('dialogclose', function(e
) {
433 if ($('.ui-dialog .modal-dialog').not(e
.target
).length
< 1) {
434 $('body').css({overflow
: ''});
439 * Function to make multiselect boxes behave as fields in small screens
441 function advmultiselectResize() {
442 var amswidth
= $("#crm-container form:has(table.advmultiselect)").width();
443 if (amswidth
< 700) {
444 $("form table.advmultiselect td").css('display', 'block');
447 $("form table.advmultiselect td").css('display', 'table-cell');
449 var contactwidth
= $('#crm-container #mainTabContainer').width();
450 if (contactwidth
< 600) {
451 $('#crm-container #mainTabContainer').addClass('narrowpage');
452 $('#crm-container #mainTabContainer.narrowpage #contactTopBar td').each(function (index
) {
454 if (index
% 2 == 0) {
455 $(this).parent().after('<tr class="narrowadded"></tr>');
458 $(this).parent().next().append(item
);
463 $('#crm-container #mainTabContainer.narrowpage').removeClass('narrowpage');
464 $('#crm-container #mainTabContainer #contactTopBar tr.narrowadded td').each(function () {
466 var parent
= $(this).parent();
467 $(this).parent().prev().append(nitem
);
468 if (parent
.children().size() == 0) {
472 $('#crm-container #mainTabContainer.narrowpage #contactTopBar tr.added').detach();
474 var cformwidth
= $('#crm-container #Contact .contact_basic_information-section').width();
476 if (cformwidth
< 720) {
477 $('#crm-container .contact_basic_information-section').addClass('narrowform');
478 $('#crm-container .contact_basic_information-section table.form-layout-compressed td .helpicon').parent().addClass('hashelpicon');
479 if (cformwidth
< 480) {
480 $('#crm-container .contact_basic_information-section').addClass('xnarrowform');
483 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
487 $('#crm-container .contact_basic_information-section.narrowform').removeClass('narrowform');
488 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
492 advmultiselectResize();
493 $(window
).resize(function () {
494 advmultiselectResize();
497 $.fn
.crmtooltip = function () {
499 .on('mouseover', 'a.crm-summary-link:not(.crm-processed)', function (e
) {
500 $(this).addClass('crm-processed');
501 $(this).addClass('crm-tooltip-active');
502 var topDistance
= e
.pageY
- $(window
).scrollTop();
503 if (topDistance
< 300 | topDistance
< $(this).children('.crm-tooltip-wrapper').height()) {
504 $(this).addClass('crm-tooltip-down');
506 if (!$(this).children('.crm-tooltip-wrapper').length
) {
507 $(this).append('<div class="crm-tooltip-wrapper"><div class="crm-tooltip"></div></div>');
508 $(this).children().children('.crm-tooltip')
509 .html('<div class="crm-loading-element"></div>')
513 .on('mouseout', 'a.crm-summary-link', function () {
514 $(this).removeClass('crm-processed');
515 $(this).removeClass('crm-tooltip-active crm-tooltip-down');
517 .on('click', 'a.crm-summary-link', false);
520 var helpDisplay
, helpPrevious
;
521 CRM
.help = function (title
, params
, url
) {
522 if (helpDisplay
&& helpDisplay
.close
) {
523 // If the same link is clicked twice, just close the display - todo use underscore method for this comparison
524 if (helpDisplay
.isOpen
&& helpPrevious
=== JSON
.stringify(params
)) {
530 helpPrevious
= JSON
.stringify(params
);
531 params
.class_name
= 'CRM_Core_Page_Inline_Help';
532 params
.type
= 'page';
533 helpDisplay
= CRM
.alert('...', title
, 'crm-help crm-msg-loading', {expires
: 0});
534 $.ajax(url
|| CRM
.url('civicrm/ajax/inline'),
538 success: function (data
) {
539 $('#crm-notification-container .crm-help .notify-content:last').html(data
);
540 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('info');
543 $('#crm-notification-container .crm-help .notify-content:last').html('Unable to load help file.');
544 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('error');
550 * @param startMsg string
551 * @param endMsg string|function
552 * @param deferred optional jQuery deferred object
553 * @return jQuery deferred object - if not supplied a new one will be created
556 CRM
.status = function(startMsg
, endMsg
, deferred
) {
557 var $bar
= $('#civicrm-menu');
559 console
&& console
.log
&& console
.log('CRM.status called on a page with no menubar');
562 $('.crm-menubar-status-container', $bar
).remove();
563 fadeOut
&& window
.clearTimeout(fadeOut
);
564 $bar
.append('<li class="crm-menubar-status-container status-busy"><div class="crm-menubar-status-progressbar"><div class="crm-menubar-status-msg">' + startMsg
+ '</div></div></li>');
565 $('.crm-menubar-status-container', $bar
).css('min-width', $('.crm-menubar-status-container', $bar
).width());
566 deferred
|| (deferred
= new $.Deferred());
567 deferred
.done(function(data
) {
568 var msg
= typeof(endMsg
) === 'function' ? endMsg(data
) : endMsg
;
569 $('.crm-menubar-status-container', $bar
).removeClass('status-busy').addClass('status-done').show().find('.crm-menubar-status-msg').html(msg
);
571 fadeOut
= window
.setTimeout(function() {
572 $('.crm-menubar-status-container', $bar
).fadeOut('slow');
575 $('.crm-menubar-status-container', $bar
).hide();
582 * @param string text Displayable message
583 * @param string title Displayable title
584 * @param string type 'alert'|'info'|'success'|'error' (default: 'alert')
585 * @param {object} options
587 * @see http://wiki.civicrm.org/confluence/display/CRM/Notifications+in+CiviCRM
589 CRM
.alert = function (text
, title
, type
, options
) {
590 type
= type
|| 'alert';
592 options
= options
|| {};
593 if ($('#crm-notification-container').length
) {
599 // By default, don't expire errors and messages containing links
601 expires
: (type
== 'error' || text
.indexOf('<a ') > -1) ? 0 : (text
? 10000 : 5000),
604 options
= $.extend(extra
, options
);
605 options
.expires
= options
.expires
=== false ? 0 : parseInt(options
.expires
, 10);
606 if (options
.unique
&& options
.unique
!== '0') {
607 $('#crm-notification-container .ui-notify-message').each(function () {
608 if (title
=== $('h1', this).html() && text
=== $('.notify-content', this).html()) {
609 $('.icon.ui-notify-close', this).click();
613 return $('#crm-notification-container').notify('create', params
, options
);
617 text
= title
+ "\n" + text
;
625 * Close whichever alert contains the given node
629 CRM
.closeAlertByChild = function (node
) {
630 $(node
).closest('.ui-notify-message').find('.icon.ui-notify-close').click();
634 * Prompt the user for confirmation.
636 * @param buttons {object|function} key|value pairs where key == button label and value == callback function
637 * passing in a function instead of an object is a shortcut for a sinlgle button labeled "Continue"
638 * @param options {object|void} Override defaults, keys include 'title', 'message',
639 * see jQuery.dialog for full list of available params
640 * @param cancelLabel {string}
642 CRM
.confirm = function (buttons
, options
, cancelLabel
) {
643 var dialog
, callbacks
= {};
644 cancelLabel
= cancelLabel
|| ts('Cancel');
646 title
: ts('Confirm Action'),
647 message
: ts('Are you sure you want to continue?'),
657 settings
.buttons
[cancelLabel
] = function () {
658 dialog
.dialog('close');
660 options
= options
|| {};
661 $.extend(settings
, options
);
662 if (typeof(buttons
) === 'function') {
663 callbacks
[ts('Continue')] = buttons
;
668 $.each(callbacks
, function (label
, callback
) {
669 settings
.buttons
[label
] = function () {
670 if (callback
.call(dialog
) !== false) {
671 dialog
.dialog('close');
675 dialog
= $('<div class="crm-container crm-confirm-dialog"></div>')
676 .html(options
.message
)
683 * Sets an error message
684 * If called for a form item, title and removal condition will be handled automatically
686 $.fn
.crmError = function (text
, title
, options
) {
689 options
= options
|| {};
694 if ($(this).length
) {
696 var label
= $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]').not('[generated=true]');
698 label
.addClass('crm-error');
699 var $label
= label
.clone();
700 if (text
== '' && $('.crm-marker', $label
).length
> 0) {
701 text
= $('.crm-marker', $label
).attr('title');
703 $('.crm-marker', $label
).remove();
704 title
= $label
.text();
707 $(this).addClass('error');
709 var msg
= CRM
.alert(text
, title
, 'error', $.extend(extra
, options
));
710 if ($(this).length
) {
712 setTimeout(function () {
713 ele
.one('change', function () {
714 msg
&& msg
.close
&& msg
.close();
715 ele
.removeClass('error');
716 label
.removeClass('crm-error');
723 // Display system alerts through js notifications
724 function messagesFromMarkup() {
725 $('div.messages:visible', this).not('.help').not('.no-popup').each(function () {
726 var text
, title
= '';
727 $(this).removeClass('status messages');
728 var type
= $(this).attr('class').split(' ')[0] || 'alert';
729 type
= type
.replace('crm-', '');
730 $('.icon', this).remove();
731 if ($('.msg-text', this).length
> 0) {
732 text
= $('.msg-text', this).html();
733 title
= $('.msg-title', this).html();
736 text
= $(this).html();
738 var options
= $(this).data('options') || {};
740 // Duplicates were already removed server-side
741 options
.unique
= false;
742 CRM
.alert(text
, title
, type
, options
);
744 // Handle qf form errors
745 $('form :input.error', this).one('blur', function() {
746 // ignore autocomplete fields
747 if ($(this).is('.ac_input')) {
751 $('.ui-notify-message.error a.ui-notify-close').click();
752 $(this).removeClass('error');
753 $(this).next('span.crm-error').remove();
754 $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]')
755 .removeClass('crm-error')
756 .find('.crm-error').removeClass('crm-error');
760 $.widget('civi.crmSnippet', {
766 _originalContent
: null,
768 isOriginalUrl: function() {
772 newUrl
= this._formatUrl(this.options
.url
),
773 oldUrl
= this._formatUrl(this._originalUrl
);
775 if (newUrl
.split('?')[0] !== oldUrl
.split('?')[0]) {
779 $.each(newUrl
.split('?')[1].split('&'), function(k
, v
) {
780 var arg
= v
.split('=');
781 args
[arg
[0]] = arg
[1];
783 $.each(oldUrl
.split('?')[1].split('&'), function(k
, v
) {
784 var arg
= v
.split('=');
785 if (args
[arg
[0]] !== undefined && arg
[1] !== args
[arg
[0]]) {
791 resetUrl: function() {
792 this.options
.url
= this._originalUrl
;
794 _create: function() {
795 this.element
.addClass('crm-ajax-container');
796 if (!this.element
.is('.crm-container *')) {
797 this.element
.addClass('crm-container');
799 this._handleOrderLinks();
800 // Set default if not supplied
801 this.options
.url
= this.options
.url
|| document
.location
.href
;
802 this._originalUrl
= this.options
.url
;
804 _onFailure: function(data
) {
805 this.options
.block
&& this.element
.unblock();
806 this.element
.trigger('crmAjaxFail', data
);
807 CRM
.alert(ts('Unable to reach the server. Please refresh this page in your browser and try again.'), ts('Network Error'), 'error');
809 _formatUrl: function(url
) {
811 url
= url
.split('#')[0];
812 // Add snippet argument to url
813 if (url
.search(/[&?]snippet=/) < 0) {
814 url
+= (url
.indexOf('?') < 0 ? '?' : '&') + 'snippet=json';
816 url
= url
.replace(/snippet=[^&]*/, 'snippet=json');
820 // Hack to deal with civicrm legacy sort functionality
821 _handleOrderLinks: function() {
823 $('a.crm-weight-arrow', that
.element
).click(function(e
) {
824 that
.options
.block
&& that
.element
.block();
825 $.getJSON(that
._formatUrl(this.href
)).done(function() {
828 e
.stopImmediatePropagation();
832 refresh: function() {
834 var url
= this._formatUrl(this.options
.url
);
835 this.options
.block
&& $('.blockOverlay', this.element
).length
< 1 && this.element
.block();
836 $.getJSON(url
, function(data
) {
837 if (typeof(data
) != 'object' || typeof(data
.content
) != 'string') {
838 that
._onFailure(data
);
842 that
.element
.trigger('crmBeforeLoad', data
);
843 if (that
._originalContent
=== null) {
844 that
._originalContent
= that
.element
.contents().detach();
846 that
.element
.html(data
.content
);
847 that
._handleOrderLinks();
848 that
.element
.trigger('crmLoad', data
);
849 that
.options
.crmForm
&& that
.element
.trigger('crmFormLoad', data
);
854 _destroy: function() {
855 this.element
.removeClass('crm-ajax-container');
856 if (this._originalContent
!== null) {
857 this.element
.empty().append(this._originalContent
);
863 CRM
.loadPage = function(url
, options
) {
865 target
: '#crm-ajax-dialog-' + (dialogCount
++),
868 if (!options
|| !options
.target
) {
872 height
: parseInt($(window
).height() * .75)
875 options
&& $.extend(true, settings
, options
);
878 if (settings
.dialog
) {
879 $('<div id="'+ settings
.target
.substring(1) +'"><div class="crm-loading-element">' + ts('Loading') + '...</div></div>').dialog(settings
.dialog
);
880 $(settings
.target
).on('dialogclose', function() {
881 $(this).dialog('destroy').remove();
884 if (settings
.dialog
&& !settings
.dialog
.title
) {
885 $(settings
.target
).on('crmLoad', function(e
, data
) {
886 if (e
.target
=== $(settings
.target
)[0] && data
&& data
.title
) {
887 $(this).dialog('option', 'title', data
.title
);
891 $(settings
.target
).crmSnippet(settings
).crmSnippet('refresh');
892 return $(settings
.target
);
895 CRM
.loadForm = function(url
, options
) {
901 refreshAction
: ['next_new', 'submit_savenext'],
902 cancelButton
: '.cancel.form-submit',
903 openInline
: 'a.button:not("[href=#], .no-popup")',
904 onCancel: function(event
) {},
905 onError: function(data
) {
907 $el
.html(data
.content
).trigger('crmLoad', data
).trigger('crmFormLoad', data
).trigger('crmFormError', data
);
908 if (typeof(data
.errors
) == 'object') {
909 $.each(data
.errors
, function(formElement
, msg
) {
910 $('[name="'+formElement
+'"]', $el
).crmError(msg
);
916 // Hack to make delete dialogs smaller
917 if (url
.indexOf('/delete') > 0 || url
.indexOf('action=delete') > 0) {
923 // Move options that belong to crmForm. Others will be passed through to crmSnippet
924 options
&& $.each(options
, function(key
, value
) {
925 if (typeof(settings
.crmForm
[key
]) !== 'undefined') {
926 settings
.crmForm
[key
] = value
;
929 settings
[key
] = value
;
933 var widget
= CRM
.loadPage(url
, settings
);
935 widget
.on('crmFormLoad', function(event
, data
) {
937 var settings
= $el
.crmSnippet('option', 'crmForm');
938 settings
.cancelButton
&& $(settings
.cancelButton
, this).click(function(event
) {
939 var returnVal
= settings
.onCancel
.call($el
, event
);
940 if (returnVal
!== false) {
941 $el
.trigger('crmFormCancel', event
);
942 if ($el
.data('uiDialog') && settings
.autoClose
) {
945 else if (!settings
.autoClose
) {
946 $el
.crmSnippet('resetUrl').crmSnippet('refresh');
949 return returnVal
=== false;
951 if (settings
.validate
) {
952 $("form", this).validate(typeof(settings
.validate
) == 'object' ? settings
.validate
: CRM
.validate
.params
);
954 $("form", this).ajaxForm($.extend({
955 url
: data
.url
.replace(/reset=1[&]?/, ''),
957 success: function(response
) {
958 if (response
.status
!== 'form_error') {
959 $el
.crmSnippet('option', 'block') && $el
.unblock();
960 $el
.trigger('crmFormSuccess', response
);
961 // Reset form for e.g. "save and new"
962 if (response
.userContext
&& settings
.refreshAction
&& $.inArray(response
.buttonName
, settings
.refreshAction
) >= 0) {
963 $el
.crmSnippet('option', 'url', response
.userContext
).crmSnippet('refresh');
965 else if ($el
.data('uiDialog') && settings
.autoClose
) {
968 else if (settings
.autoClose
=== false) {
969 $el
.crmSnippet('resetUrl').crmSnippet('refresh');
973 response
.url
= data
.url
;
974 settings
.onError
.call($el
, response
);
977 beforeSerialize: function(form
, options
) {
978 if (window
.CKEDITOR
&& window
.CKEDITOR
.instances
) {
979 $.each(CKEDITOR
.instances
, function() {
980 this.updateElement
&& this.updateElement();
984 beforeSubmit: function(submission
) {
985 $el
.crmSnippet('option', 'block') && $el
.block();
986 $el
.trigger('crmFormSubmit', submission
);
988 }, settings
.ajaxForm
));
989 if (settings
.openInline
) {
990 settings
.autoClose
= $el
.crmSnippet('isOriginalUrl');
991 $(settings
.openInline
, this).click(function(event
) {
992 $el
.crmSnippet('option', 'url', $(this).attr('href')).crmSnippet('refresh');
996 // For convenience, focus the first field
997 $('input[type=text], textarea, select', this).filter(':visible').first().focus();
1002 // Preprocess all cj ajax calls to display messages
1003 $(document
).ajaxSuccess(function(event
, xhr
, settings
) {
1005 if ((!settings
.dataType
|| settings
.dataType
== 'json') && xhr
.responseText
) {
1006 var response
= $.parseJSON(xhr
.responseText
);
1007 if (typeof(response
.crmMessages
) == 'object') {
1008 $.each(response
.crmMessages
, function(n
, msg
) {
1009 CRM
.alert(msg
.text
, msg
.title
, msg
.type
, msg
.options
);
1019 * Temporary stub to get around name conflict with legacy jQuery.autocomplete plugin
1021 $.widget('civi.crmAutocomplete', $.ui
.autocomplete
, {});
1024 // Trigger crmLoad on initial content for consistency. It will also be triggered for ajax-loaded content.
1025 $('.crm-container').trigger('crmLoad');
1027 if ($('#crm-notification-container').length
) {
1028 // Initialize notifications
1029 $('#crm-notification-container').notify();
1030 messagesFromMarkup
.call($('#crm-container'));
1033 // bind the event for image popup
1035 .on('click', 'a.crm-image-popup', function() {
1036 var o
= $('<div class="crm-container crm-custom-image-popup"><img src=' + $(this).attr('href') + '></div>');
1040 title
: ts('Preview'),
1048 .on('click', function (event
) {
1049 $('.btn-slide-active').removeClass('btn-slide-active').find('.panel').hide();
1050 if ($(event
.target
).is('.btn-slide')) {
1051 $(event
.target
).addClass('btn-slide-active').find('.panel').show();
1055 .on('click', 'a.crm-option-edit-link', function() {
1058 optionsChanged
= false;
1059 CRM
.loadForm(this.href
, {openInline
: 'a:not("[href=#], .no-popup")'})
1060 .on('crmFormSuccess', function() {
1061 optionsChanged
= true;
1063 .on('dialogclose', function() {
1064 if (optionsChanged
) {
1065 link
.trigger('crmOptionsEdited');
1066 var $elects
= $('select[data-option-edit-path="' + link
.data('option-edit-path') + '"]');
1067 if ($elects
.data('api-entity') && $elects
.data('api-field')) {
1068 CRM
.api3($elects
.data('api-entity'), 'getoptions', {sequential
: 1, field
: $elects
.data('api-field')})
1069 .done(function (data
) {
1070 CRM
.utils
.setOptions($elects
, data
.values
);
1077 // Handle clear button for form elements
1078 .on('click', 'a.crm-clear-link', function() {
1079 $(this).css({visibility
: 'hidden'}).siblings('.crm-form-radio:checked').prop('checked', false).change();
1080 $(this).siblings('input:text').val('').change();
1083 .on('change', 'input.crm-form-radio:checked', function() {
1084 $(this).siblings('.crm-clear-link').css({visibility
: ''});
1089 $.fn
.crmAccordions = function (speed
) {
1090 var container
= $(this).length
> 0 ? $(this) : $('.crm-container');
1091 speed
= speed
=== undefined ? 200 : speed
;
1093 .off('click.crmAccordions')
1094 // Allow normal clicking of links
1095 .on('click.crmAccordions', 'div.crm-accordion-header a', function (e
) {
1096 e
.stopPropagation
&& e
.stopPropagation();
1098 .on('click.crmAccordions', '.crm-accordion-header, .crm-collapsible .collapsible-title', function () {
1099 if ($(this).parent().hasClass('collapsed')) {
1100 $(this).next().css('display', 'none').slideDown(speed
);
1103 $(this).next().css('display', 'block').slideUp(speed
);
1105 $(this).parent().toggleClass('collapsed');
1109 $.fn
.crmAccordionToggle = function (speed
) {
1110 $(this).each(function () {
1111 if ($(this).hasClass('collapsed')) {
1112 $('.crm-accordion-body', this).first().css('display', 'none').slideDown(speed
);
1115 $('.crm-accordion-body', this).first().css('display', 'block').slideUp(speed
);
1117 $(this).toggleClass('collapsed');
1122 * Clientside currency formatting
1124 * @param format - currency representation of the number 1234.56
1126 * @see CRM_Core_Resources::addCoreResources
1128 var currencyTemplate
;
1129 CRM
.formatMoney = function(value
, format
) {
1130 var decimal, separator
, sign
, i
, j
, result
;
1131 if (value
=== 'init' && format
) {
1132 currencyTemplate
= format
;
1135 format
= format
|| currencyTemplate
;
1136 result
= /1(.?)234(.?)56/.exec(format
);
1137 if (result
=== null) {
1138 return 'Invalid format passed to CRM.formatMoney';
1140 separator
= result
[1];
1141 decimal = result
[2];
1142 sign
= (value
< 0) ? '-' : '';
1143 //extracting the absolute value of the integer part of the number and converting to string
1144 i
= parseInt(value
= Math
.abs(value
).toFixed(2)) + '';
1145 j
= ((j
= i
.length
) > 3) ? j
% 3 : 0;
1146 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) : '');
1147 return format
.replace(/1.*234.*56/, result
);