2 +--------------------------------------------------------------------+
3 | CiviCRM version 4.4 |
4 +--------------------------------------------------------------------+
5 | Copyright CiviCRM LLC (c) 2004-2013 |
6 +--------------------------------------------------------------------+
7 | This file is a part of CiviCRM. |
9 | CiviCRM is free software; you can copy, modify, and distribute it |
10 | under the terms of the GNU Affero General Public License |
11 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | CiviCRM is distributed in the hope that it will be useful, but |
14 | WITHOUT ANY WARRANTY; without even the implied warranty of |
15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
16 | See the GNU Affero General Public License for more details. |
18 | You should have received a copy of the GNU Affero General Public |
19 | License and the CiviCRM Licensing Exception along |
20 | with this program; if not, contact CiviCRM LLC |
21 | at info[AT]civicrm[DOT]org. If you have questions about the |
22 | GNU Affero General Public License or the licensing of CiviCRM, |
23 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
24 +--------------------------------------------------------------------+
28 * @file: global functions for CiviCRM
29 * FIXME: We are moving away from using global functions. DO NOT ADD MORE.
30 * @see CRM object - the better alternative to adding global functions
37 * Short-named function for string translation, defined in global scope so it's available everywhere.
39 * @param $text string string for translating
40 * @param $params object key:value of additional parameters
42 * @return string the translated string
44 function ts(text
, params
) {
46 text
= CRM
.strings
[text
] || text
;
47 if (typeof(params
) === 'object') {
48 for (var i
in params
) {
49 if (typeof(params
[i
]) === 'string' || typeof(params
[i
]) === 'number') {
50 // sprintf emulation: escape % characters in the replacements to avoid conflicts
51 text
= text
.replace(new RegExp('%' + i
, 'g'), String(params
[i
]).replace(/%/g
, '%-crmescaped-'));
54 return text
.replace(/%-crmescaped-/g, '%');
60 * This function is called by default at the bottom of template files which have forms that have
61 * conditionally displayed/hidden sections and elements. The PHP is responsible for generating
62 * a list of 'blocks to show' and 'blocks to hide' and the template passes these parameters to
66 * @param showBlocks Array of element Id's to be displayed
67 * @param hideBlocks Array of element Id's to be hidden
68 * @param elementType Value to set display style to for showBlocks (e.g. 'block' or 'table-row' or ...)
71 function on_load_init_blocks(showBlocks
, hideBlocks
, elementType
) {
72 if (elementType
== null) {
73 var elementType
= 'block';
76 /* This loop is used to display the blocks whose IDs are present within the showBlocks array */
77 for (var i
= 0; i
< showBlocks
.length
; i
++) {
78 var myElement
= document
.getElementById(showBlocks
[i
]);
79 /* getElementById returns null if element id doesn't exist in the document */
80 if (myElement
!= null) {
81 myElement
.style
.display
= elementType
;
84 alert('showBlocks array item not in .tpl = ' + showBlocks
[i
]);
88 /* This loop is used to hide the blocks whose IDs are present within the hideBlocks array */
89 for (var i
= 0; i
< hideBlocks
.length
; i
++) {
90 var myElement
= document
.getElementById(hideBlocks
[i
]);
91 /* getElementById returns null if element id doesn't exist in the document */
92 if (myElement
!= null) {
93 myElement
.style
.display
= 'none';
96 alert('showBlocks array item not in .tpl = ' + hideBlocks
[i
]);
102 * This function is called when we need to show or hide a related form element (target_element)
103 * based on the value (trigger_value) of another form field (trigger_field).
106 * @param trigger_field_id HTML id of field whose onchange is the trigger
107 * @param trigger_value List of integers - option value(s) which trigger show-element action for target_field
108 * @param target_element_id HTML id of element to be shown or hidden
109 * @param target_element_type Type of element to be shown or hidden ('block' or 'table-row')
110 * @param field_type Type of element radio/select
111 * @param invert Boolean - if true, we HIDE target on value match; if false, we SHOW target on value match
114 function showHideByValue(trigger_field_id
, trigger_value
, target_element_id
, target_element_type
, field_type
, invert
) {
115 if (target_element_type
== null) {
116 var target_element_type
= 'block';
119 if (target_element_type
== 'table-row') {
120 var target_element_type
= '';
124 if (field_type
== 'select') {
125 var trigger
= trigger_value
.split("|");
126 var selectedOptionValue
= cj('#' + trigger_field_id
).val();
128 var target
= target_element_id
.split("|");
129 for (var j
= 0; j
< target
.length
; j
++) {
131 cj('#' + target
[j
]).show();
134 cj('#' + target
[j
]).hide();
136 for (var i
= 0; i
< trigger
.length
; i
++) {
137 if (selectedOptionValue
== trigger
[i
]) {
139 cj('#' + target
[j
]).hide();
142 cj('#' + target
[j
]).show();
150 if (field_type
== 'radio') {
151 var target
= target_element_id
.split("|");
152 for (var j
= 0; j
< target
.length
; j
++) {
153 if (cj('[name="' + trigger_field_id
+ '"]').is(':checked')) {
155 cj('#' + target
[j
]).hide();
158 cj('#' + target
[j
]).show();
163 cj('#' + target
[j
]).show();
166 cj('#' + target
[j
]).hide();
175 * Function to change button text and disable one it is clicked
177 * @param obj object - the button clicked
178 * @param formID string - the id of the form being submitted
179 * @param string procText - button text after user clicks it
183 /* Changes button label on submit, and disables button after submit for newer browsers.
184 Puts up alert for older browsers. */
185 function submitOnce(obj
, formId
, procText
) {
186 // if named button clicked, change text
187 if (obj
.value
!= null) {
188 obj
.value
= procText
+ " ...";
190 if (document
.getElementById
) { // disable submit button for newer browsers
192 document
.getElementById(formId
).submit();
195 else { // for older browsers
196 if (submitcount
== 0) {
201 alert("Your request is currently being processed ... Please wait.");
207 function popUp(URL
) {
210 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');");
214 * Function to show / hide the row in optionFields
216 * @param element name index, that whose innerHTML is to hide else will show the hidden row.
218 function showHideRow(index
) {
220 cj('tr#optionField_' + index
).hide();
221 if (cj('table#optionField tr:hidden:first').length
) {
222 cj('div#optionFieldLink').show();
226 cj('table#optionField tr:hidden:first').show();
227 if (!cj('table#optionField tr:hidden:last').length
) {
228 cj('div#optionFieldLink').hide();
234 CRM
.utils
= CRM
.utils
|| {};
235 CRM
.strings
= CRM
.strings
|| {};
236 CRM
.validate
= CRM
.validate
|| {
241 (function ($, undefined) {
244 // Set select2 defaults
245 $.fn
.select2
.defaults
.minimumResultsForSearch
= 10;
246 // https://github.com/ivaynberg/select2/pull/2090
247 $.fn
.select2
.defaults
.width
= 'resolve';
249 // Workaround for https://github.com/ivaynberg/select2/issues/1246
250 $.ui
.dialog
.prototype._allowInteraction = function(e
) {
251 return !!$(e
.target
).closest('.ui-dialog, .ui-datepicker, .select2-drop').length
;
255 * Populate a select list, overwriting the existing options except for the placeholder.
256 * @param $el jquery collection - 1 or more select elements
257 * @param options array in format returned by api.getoptions
259 CRM
.utils
.setOptions = function($el
, options
) {
260 $el
.each(function() {
263 val
= $elect
.val() || [];
264 if (typeof(val
) !== 'array') {
267 $elect
.find('option[value!=""]').remove();
268 $.each(options
, function(key
, option
) {
269 var selected
= ($.inArray(''+option
.key
, val
) > -1) ? 'selected="selected"' : '';
270 $elect
.append('<option value="' + option
.key
+ '"' + selected
+ '>' + option
.value
+ '</option>');
272 $elect
.trigger('crmOptionsUpdated').trigger('change');
276 CRM
.utils
.formatSelect2Result = function(row
) {
277 var markup
= '<table class="crm-select2-row"><tr>';
278 if (row
.image
!== undefined) {
279 markup
+= '<td class="crm-select2-image"><img src="' + row
.image
+ '"/></td>';
281 else if (row
.icon_class
) {
282 markup
+= '<td class="crm-select2-icon"><div class="crm-icon ' + row
.icon_class
+ '-icon"></div></td>';
284 markup
+= '<td><div class="crm-select2-row-label">' + row
.label
+ '</div>';
285 markup
+= '<div class="crm-select2-row-description">' + (row
.description
|| '') + '</div>';
286 markup
+= '</td></tr></table>';
290 CRM
.utils
.formatSelect2CreateLinks = function($el
) {
292 $.each($el
.data('create-links'), function(k
, link
) {
293 markup
+= ' <a class="crm-add-entity crm-hover-button" href="' + link
.url
+ '">';
295 markup
+= '<span class="icon ' + link
.name
+ '-icon"></span> ';
297 markup
+= link
.label
+ '</a>';
302 // Initialize widgets
303 $(document
).on('crmLoad', function(e
) {
304 $('table.row-highlight', e
.target
)
305 .off('.rowHighlight')
306 .on('change.rowHighlight', 'input.select-row, input.select-rows', function () {
307 var target
, table
= $(this).closest('table');
308 if ($(this).hasClass('select-rows')) {
309 target
= $('tbody tr', table
);
310 $('input.select-row', table
).prop('checked', $(this).prop('checked'));
313 target
= $(this).closest('tr');
314 $('input.select-rows', table
).prop('checked', $(".select-row:not(':checked')", table
).length
< 1);
316 target
.toggleClass('crm-row-selected', $(this).is(':checked'));
318 .find('input.select-row:checked').parents('tr').addClass('crm-row-selected');
319 $('.crm-select2', e
.target
).each(function() {
321 // quickform doesn't support optgroups so here's a hack :(
322 $('option[value^=crm_optgroup]', this).each(function() {
323 $(this).nextUntil('option[value^=crm_optgroup]').wrapAll('<optgroup label="' + $(this).text() + '" />');
326 // Get a copy of the data rather than a reference
327 var options
= $.extend({}, $el
.data('select-params') || {});
328 // Set placeholder from markup if not specified
329 if ($el
.is('select:not([multiple])')) {
330 options
.allowClear
= options
.allowClear
!== undefined ? options
.allowClear
: !($el
.hasClass('required'));
331 if (options
.placeHolder
=== undefined && $('option:first', this).val() === '') {
332 options
.placeholderOption
= 'first';
335 // Autocomplete using the getlist api
336 if ($el
.data('api-entity') && $el
.hasClass('crm-form-entityref')) {
337 $el
.addClass('crm-ajax-select');
339 // Use select2 ajax helper instead of CRM.api because it provides more value
341 url
: CRM
.url('civicrm/ajax/rest'),
342 data: function (input
, page_num
) {
343 var params
= $el
.data('api-params') || {};
344 params
.input
= input
;
345 params
.page_num
= page_num
;
347 entity
: $el
.data('api-entity'),
349 json
: JSON
.stringify(params
)
352 results: function(data
) {
353 return {more
: data
.more_results
, results
: data
.values
|| []};
356 formatResult
: CRM
.utils
.formatSelect2Result
,
357 formatSelection: function(row
) {
360 escapeMarkup: function (m
) {return m
;},
361 initSelection: function(el
, callback
) {
362 callback(el
.data('entity-value'));
365 if ($el
.data('create-links')) {
366 options
.formatInputTooShort = function() {
367 var txt
= $el
.data('select-params').formatInputTooShort
|| $.fn
.select2
.defaults
.formatInputTooShort
;
368 return txt
+ ' ' + ts('or') + '<br />' + CRM
.utils
.formatSelect2CreateLinks($el
);
370 options
.formatNoMatches = function() {
371 var txt
= $el
.data('select-params').formatNoMatches
|| $.fn
.select2
.defaults
.formatNoMatches
;
372 return txt
+ '<br />' + CRM
.utils
.formatSelect2CreateLinks($el
);
374 $el
.on('select2-open', function() {
376 $('#select2-drop').off('.crmEntity').on('click.crmEntity', 'a.crm-add-entity', function(e
) {
377 $el
.select2('close');
378 CRM
.loadForm($(this).attr('href'), {
379 dialog
: {width
: 500, height
: 'auto'}
380 }).on('crmFormSuccess', function(e
, data
) {
381 if ($el
.select2('container').hasClass('select2-container-multi')) {
382 var selection
= $el
.select2('data');
383 selection
.push(data
);
384 $el
.select2('data', selection
);
386 $el
.select2('data', data
);
393 options
= $.extend(settings
, options
);
395 options
.dropdownCssClass
= 'crm-container';
396 $(this).select2(options
).removeClass('crm-select2');
401 * Function to make multiselect boxes behave as fields in small screens
403 function advmultiselectResize() {
404 var amswidth
= $("#crm-container form:has(table.advmultiselect)").width();
405 if (amswidth
< 700) {
406 $("form table.advmultiselect td").css('display', 'block');
409 $("form table.advmultiselect td").css('display', 'table-cell');
411 var contactwidth
= $('#crm-container #mainTabContainer').width();
412 if (contactwidth
< 600) {
413 $('#crm-container #mainTabContainer').addClass('narrowpage');
414 $('#crm-container #mainTabContainer.narrowpage #contactTopBar td').each(function (index
) {
416 if (index
% 2 == 0) {
417 $(this).parent().after('<tr class="narrowadded"></tr>');
420 $(this).parent().next().append(item
);
425 $('#crm-container #mainTabContainer.narrowpage').removeClass('narrowpage');
426 $('#crm-container #mainTabContainer #contactTopBar tr.narrowadded td').each(function () {
428 var parent
= $(this).parent();
429 $(this).parent().prev().append(nitem
);
430 if (parent
.children().size() == 0) {
434 $('#crm-container #mainTabContainer.narrowpage #contactTopBar tr.added').detach();
436 var cformwidth
= $('#crm-container #Contact .contact_basic_information-section').width();
438 if (cformwidth
< 720) {
439 $('#crm-container .contact_basic_information-section').addClass('narrowform');
440 $('#crm-container .contact_basic_information-section table.form-layout-compressed td .helpicon').parent().addClass('hashelpicon');
441 if (cformwidth
< 480) {
442 $('#crm-container .contact_basic_information-section').addClass('xnarrowform');
445 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
449 $('#crm-container .contact_basic_information-section.narrowform').removeClass('narrowform');
450 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
454 advmultiselectResize();
455 $(window
).resize(function () {
456 advmultiselectResize();
459 $.fn
.crmtooltip = function () {
461 .on('mouseover', 'a.crm-summary-link:not(.crm-processed)', function (e
) {
462 $(this).addClass('crm-processed');
463 $(this).addClass('crm-tooltip-active');
464 var topDistance
= e
.pageY
- $(window
).scrollTop();
465 if (topDistance
< 300 | topDistance
< $(this).children('.crm-tooltip-wrapper').height()) {
466 $(this).addClass('crm-tooltip-down');
468 if (!$(this).children('.crm-tooltip-wrapper').length
) {
469 $(this).append('<div class="crm-tooltip-wrapper"><div class="crm-tooltip"></div></div>');
470 $(this).children().children('.crm-tooltip')
471 .html('<div class="crm-loading-element"></div>')
475 .on('mouseout', 'a.crm-summary-link', function () {
476 $(this).removeClass('crm-processed');
477 $(this).removeClass('crm-tooltip-active crm-tooltip-down');
479 .on('click', 'a.crm-summary-link', false);
482 var helpDisplay
, helpPrevious
;
483 CRM
.help = function (title
, params
, url
) {
484 if (helpDisplay
&& helpDisplay
.close
) {
485 // If the same link is clicked twice, just close the display - todo use underscore method for this comparison
486 if (helpDisplay
.isOpen
&& helpPrevious
=== JSON
.stringify(params
)) {
492 helpPrevious
= JSON
.stringify(params
);
493 params
.class_name
= 'CRM_Core_Page_Inline_Help';
494 params
.type
= 'page';
495 helpDisplay
= CRM
.alert('...', title
, 'crm-help crm-msg-loading', {expires
: 0});
496 $.ajax(url
|| CRM
.url('civicrm/ajax/inline'),
500 success: function (data
) {
501 $('#crm-notification-container .crm-help .notify-content:last').html(data
);
502 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('info');
505 $('#crm-notification-container .crm-help .notify-content:last').html('Unable to load help file.');
506 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('error');
512 * @param startMsg string
513 * @param endMsg string|function
514 * @param deferred optional jQuery deferred object
515 * @return jQuery deferred object - if not supplied a new one will be created
518 CRM
.status = function(startMsg
, endMsg
, deferred
) {
519 var $bar
= $('#civicrm-menu');
521 console
&& console
.log
&& console
.log('CRM.status called on a page with no menubar');
524 $('.crm-menubar-status-container', $bar
).remove();
525 fadeOut
&& window
.clearTimeout(fadeOut
);
526 $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>');
527 $('.crm-menubar-status-container', $bar
).css('min-width', $('.crm-menubar-status-container', $bar
).width());
528 deferred
|| (deferred
= new $.Deferred());
529 deferred
.done(function(data
) {
530 var msg
= typeof(endMsg
) === 'function' ? endMsg(data
) : endMsg
;
531 $('.crm-menubar-status-container', $bar
).removeClass('status-busy').addClass('status-done').show().find('.crm-menubar-status-msg').html(msg
);
533 fadeOut
= window
.setTimeout(function() {
534 $('.crm-menubar-status-container', $bar
).fadeOut('slow');
537 $('.crm-menubar-status-container', $bar
).hide();
544 * @param string text Displayable message
545 * @param string title Displayable title
546 * @param string type 'alert'|'info'|'success'|'error' (default: 'alert')
547 * @param {object} options
549 * @see http://wiki.civicrm.org/confluence/display/CRM/Notifications+in+CiviCRM
551 CRM
.alert = function (text
, title
, type
, options
) {
552 type
= type
|| 'alert';
554 options
= options
|| {};
555 if ($('#crm-notification-container').length
) {
561 // By default, don't expire errors and messages containing links
563 expires
: (type
== 'error' || text
.indexOf('<a ') > -1) ? 0 : (text
? 10000 : 5000),
566 options
= $.extend(extra
, options
);
567 options
.expires
= options
.expires
=== false ? 0 : parseInt(options
.expires
, 10);
568 if (options
.unique
&& options
.unique
!== '0') {
569 $('#crm-notification-container .ui-notify-message').each(function () {
570 if (title
=== $('h1', this).html() && text
=== $('.notify-content', this).html()) {
571 $('.icon.ui-notify-close', this).click();
575 return $('#crm-notification-container').notify('create', params
, options
);
579 text
= title
+ "\n" + text
;
587 * Close whichever alert contains the given node
591 CRM
.closeAlertByChild = function (node
) {
592 $(node
).closest('.ui-notify-message').find('.icon.ui-notify-close').click();
596 * Prompt the user for confirmation.
598 * @param buttons {object|function} key|value pairs where key == button label and value == callback function
599 * passing in a function instead of an object is a shortcut for a sinlgle button labeled "Continue"
600 * @param options {object|void} Override defaults, keys include 'title', 'message',
601 * see jQuery.dialog for full list of available params
603 CRM
.confirm = function (buttons
, options
, cancelLabel
) {
604 var dialog
, callbacks
= {};
605 cancelLabel
= cancelLabel
|| ts('Cancel');
607 title
: ts('Confirm Action'),
608 message
: ts('Are you sure you want to continue?'),
618 settings
.buttons
[cancelLabel
] = function () {
619 dialog
.dialog('close');
621 options
= options
|| {};
622 $.extend(settings
, options
);
623 if (typeof(buttons
) === 'function') {
624 callbacks
[ts('Continue')] = buttons
;
629 $.each(callbacks
, function (label
, callback
) {
630 settings
.buttons
[label
] = function () {
631 callback
.call(dialog
);
632 dialog
.dialog('close');
635 dialog
= $('<div class="crm-container crm-confirm-dialog"></div>')
636 .html(options
.message
)
643 * Sets an error message
644 * If called for a form item, title and removal condition will be handled automatically
646 $.fn
.crmError = function (text
, title
, options
) {
649 options
= options
|| {};
654 if ($(this).length
) {
656 var label
= $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]').not('[generated=true]');
658 label
.addClass('crm-error');
659 var $label
= label
.clone();
660 if (text
== '' && $('.crm-marker', $label
).length
> 0) {
661 text
= $('.crm-marker', $label
).attr('title');
663 $('.crm-marker', $label
).remove();
664 title
= $label
.text();
667 $(this).addClass('error');
669 var msg
= CRM
.alert(text
, title
, 'error', $.extend(extra
, options
));
670 if ($(this).length
) {
672 setTimeout(function () {
673 ele
.one('change', function () {
674 msg
&& msg
.close
&& msg
.close();
675 ele
.removeClass('error');
676 label
.removeClass('crm-error');
683 // Display system alerts through js notifications
684 function messagesFromMarkup() {
685 $('div.messages:visible', this).not('.help').not('.no-popup').each(function () {
686 var text
, title
= '';
687 $(this).removeClass('status messages');
688 var type
= $(this).attr('class').split(' ')[0] || 'alert';
689 type
= type
.replace('crm-', '');
690 $('.icon', this).remove();
691 if ($('.msg-text', this).length
> 0) {
692 text
= $('.msg-text', this).html();
693 title
= $('.msg-title', this).html();
696 text
= $(this).html();
698 var options
= $(this).data('options') || {};
700 // Duplicates were already removed server-side
701 options
.unique
= false;
702 CRM
.alert(text
, title
, type
, options
);
704 // Handle qf form errors
705 $('form :input.error', this).one('blur', function() {
706 // ignore autocomplete fields
707 if ($(this).is('.ac_input')) {
711 $('.ui-notify-message.error a.ui-notify-close').click();
712 $(this).removeClass('error');
713 $(this).next('span.crm-error').remove();
714 $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]')
715 .removeClass('crm-error')
716 .find('.crm-error').removeClass('crm-error');
720 $.widget('civi.crmSnippet', {
726 _originalContent
: null,
728 isOriginalUrl: function() {
732 newUrl
= this._formatUrl(this.options
.url
),
733 oldUrl
= this._formatUrl(this._originalUrl
);
735 if (newUrl
.split('?')[0] !== oldUrl
.split('?')[0]) {
739 $.each(newUrl
.split('?')[1].split('&'), function(k
, v
) {
740 var arg
= v
.split('=');
741 args
[arg
[0]] = arg
[1];
743 $.each(oldUrl
.split('?')[1].split('&'), function(k
, v
) {
744 var arg
= v
.split('=');
745 if (args
[arg
[0]] !== undefined && arg
[1] !== args
[arg
[0]]) {
751 resetUrl: function() {
752 this.options
.url
= this._originalUrl
;
754 _create: function() {
755 this.element
.addClass('crm-ajax-container');
756 if (!this.element
.is('.crm-container *')) {
757 this.element
.addClass('crm-container');
759 this._handleOrderLinks();
760 // Set default if not supplied
761 this.options
.url
= this.options
.url
|| document
.location
.href
;
762 this._originalUrl
= this.options
.url
;
764 _onFailure: function(data
) {
765 this.options
.block
&& this.element
.unblock();
766 this.element
.trigger('crmAjaxFail', data
);
767 CRM
.alert(ts('Unable to reach the server. Please refresh this page in your browser and try again.'), ts('Network Error'), 'error');
769 _formatUrl: function(url
) {
771 url
= url
.split('#')[0];
772 // Add snippet argument to url
773 if (url
.search(/[&?]snippet=/) < 0) {
774 url
+= (url
.indexOf('?') < 0 ? '?' : '&') + 'snippet=json';
776 url
= url
.replace(/snippet=[^&]*/, 'snippet=json');
780 // Hack to deal with civicrm legacy sort functionality
781 _handleOrderLinks: function() {
783 $('a.crm-weight-arrow', that
.element
).click(function(e
) {
784 that
.options
.block
&& that
.element
.block();
785 $.getJSON(that
._formatUrl(this.href
)).done(function() {
788 e
.stopImmediatePropagation();
792 refresh: function() {
794 var url
= this._formatUrl(this.options
.url
);
795 this.options
.block
&& $('.blockOverlay', this.element
).length
< 1 && this.element
.block();
796 $.getJSON(url
, function(data
) {
797 if (typeof(data
) != 'object' || typeof(data
.content
) != 'string') {
798 that
._onFailure(data
);
802 that
.element
.trigger('crmBeforeLoad', data
);
803 if (that
._originalContent
=== null) {
804 that
._originalContent
= that
.element
.contents().detach();
806 that
.element
.html(data
.content
);
807 that
._handleOrderLinks();
808 that
.element
.trigger('crmLoad', data
);
809 that
.options
.crmForm
&& that
.element
.trigger('crmFormLoad', data
);
814 _destroy: function() {
815 this.element
.removeClass('crm-ajax-container');
816 if (this._originalContent
!== null) {
817 this.element
.empty().append(this._originalContent
);
823 CRM
.loadPage = function(url
, options
) {
825 target
: '#crm-ajax-dialog-' + (dialogCount
++),
828 if (!options
|| !options
.target
) {
832 height
: parseInt($(window
).height() * .75),
834 $(this).dialog('destroy').remove();
838 options
&& $.extend(true, settings
, options
);
841 if (settings
.dialog
) {
842 $('<div id="'+ settings
.target
.substring(1) +'"><div class="crm-loading-element">' + ts('Loading') + '...</div></div>').dialog(settings
.dialog
);
844 if (settings
.dialog
&& !settings
.dialog
.title
) {
845 $(settings
.target
).on('crmLoad', function(event
, data
) {
846 data
.title
&& $(this).dialog('option', 'title', data
.title
);
849 $(settings
.target
).crmSnippet(settings
).crmSnippet('refresh');
850 return $(settings
.target
);
853 CRM
.loadForm = function(url
, options
) {
859 refreshAction
: ['next_new', 'submit_savenext'],
860 cancelButton
: '.cancel.form-submit',
861 openInline
: 'a.button:not("[href=#], .no-popup")',
862 onCancel: function(event
) {},
863 onError: function(data
) {
865 $el
.html(data
.content
).trigger('crmLoad', data
).trigger('crmFormLoad', data
).trigger('crmFormError', data
);
866 if (typeof(data
.errors
) == 'object') {
867 $.each(data
.errors
, function(formElement
, msg
) {
868 $('[name="'+formElement
+'"]', $el
).crmError(msg
);
874 // Hack to make delete dialogs smaller
875 if (url
.indexOf('/delete') > 0 || url
.indexOf('action=delete') > 0) {
881 // Move options that belong to crmForm. Others will be passed through to crmSnippet
882 options
&& $.each(options
, function(key
, value
) {
883 if (typeof(settings
.crmForm
[key
]) !== 'undefined') {
884 settings
.crmForm
[key
] = value
;
887 settings
[key
] = value
;
891 var widget
= CRM
.loadPage(url
, settings
);
893 widget
.on('crmFormLoad', function(event
, data
) {
895 var settings
= $el
.crmSnippet('option', 'crmForm');
896 settings
.cancelButton
&& $(settings
.cancelButton
, this).click(function(event
) {
897 var returnVal
= settings
.onCancel
.call($el
, event
);
898 if (returnVal
!== false) {
899 $el
.trigger('crmFormCancel', event
);
900 if ($el
.data('uiDialog') && settings
.autoClose
) {
903 else if (!settings
.autoClose
) {
904 $el
.crmSnippet('resetUrl').crmSnippet('refresh');
907 return returnVal
=== false;
909 if (settings
.validate
) {
910 $("form", this).validate(typeof(settings
.validate
) == 'object' ? settings
.validate
: CRM
.validate
.params
);
912 $("form", this).ajaxForm($.extend({
913 url
: data
.url
.replace(/reset=1[&]?/, ''),
915 success: function(response
) {
916 if (response
.status
!== 'form_error') {
917 $el
.crmSnippet('option', 'block') && $el
.unblock();
918 $el
.trigger('crmFormSuccess', response
);
919 // Reset form for e.g. "save and new"
920 if (response
.userContext
&& settings
.refreshAction
&& $.inArray(response
.buttonName
, settings
.refreshAction
) >= 0) {
921 $el
.crmSnippet('option', 'url', response
.userContext
).crmSnippet('refresh');
923 else if ($el
.data('uiDialog') && settings
.autoClose
) {
926 else if (settings
.autoClose
=== false) {
927 $el
.crmSnippet('resetUrl').crmSnippet('refresh');
931 response
.url
= data
.url
;
932 settings
.onError
.call($el
, response
);
935 beforeSerialize: function(form
, options
) {
936 if (window
.CKEDITOR
&& window
.CKEDITOR
.instances
) {
937 $.each(CKEDITOR
.instances
, function() {
938 this.updateElement
&& this.updateElement();
942 beforeSubmit: function(submission
) {
943 $el
.crmSnippet('option', 'block') && $el
.block();
944 $el
.trigger('crmFormSubmit', submission
);
946 }, settings
.ajaxForm
));
947 if (settings
.openInline
) {
948 settings
.autoClose
= $el
.crmSnippet('isOriginalUrl');
949 $(settings
.openInline
, this).click(function(event
) {
950 $el
.crmSnippet('option', 'url', $(this).attr('href')).crmSnippet('refresh');
958 // Preprocess all cj ajax calls to display messages
959 $(document
).ajaxSuccess(function(event
, xhr
, settings
) {
961 if ((!settings
.dataType
|| settings
.dataType
== 'json') && xhr
.responseText
) {
962 var response
= $.parseJSON(xhr
.responseText
);
963 if (typeof(response
.crmMessages
) == 'object') {
964 $.each(response
.crmMessages
, function(n
, msg
) {
965 CRM
.alert(msg
.text
, msg
.title
, msg
.type
, msg
.options
);
975 * Temporary stub to get around name conflict with legacy jQuery.autocomplete plugin
977 $.widget('civi.crmAutocomplete', $.ui
.autocomplete
, {});
980 // Trigger crmLoad on initial content for consistency. It will also be triggered for ajax-loaded content.
981 $('.crm-container').trigger('crmLoad');
983 if ($('#crm-notification-container').length
) {
984 // Initialize notifications
985 $('#crm-notification-container').notify();
986 messagesFromMarkup
.call($('#crm-container'));
989 // bind the event for image popup
991 .on('click', 'a.crm-image-popup', function() {
992 var o
= $('<div class="crm-container crm-custom-image-popup"><img src=' + $(this).attr('href') + '></div>');
996 title
: ts('Preview'),
1004 .on('click', function (event
) {
1005 $('.btn-slide-active').removeClass('btn-slide-active').find('.panel').hide();
1006 if ($(event
.target
).is('.btn-slide')) {
1007 $(event
.target
).addClass('btn-slide-active').find('.panel').show();
1011 .on('click', 'a.crm-option-edit-link', function() {
1013 CRM
.loadForm(this.href
, {openInline
: 'a:not("[href=#], .no-popup")'})
1014 // Lots of things can happen once the form opens, this is the only event we can really rely on
1015 .on('dialogclose', function() {
1016 link
.trigger('crmOptionsEdited');
1017 var $elects
= $('select[data-option-edit-path="' + link
.data('option-edit-path') + '"]');
1018 if ($elects
.data('api-entity') && $elects
.data('api-field')) {
1019 CRM
.api3($elects
.data('api-entity'), 'getoptions', {sequential
: 1, field
: $elects
.data('api-field')})
1020 .done(function(data
) {
1021 CRM
.utils
.setOptions($elects
, data
.values
);
1027 // Handle clear button for form elements
1028 .on('click', 'a.crm-clear-link', function() {
1029 $(this).css({visibility
: 'hidden'}).siblings('.crm-form-radio:checked').prop('checked', false).change();
1030 $(this).siblings('input:text').val('').change();
1033 .on('change', 'input.crm-form-radio:checked', function() {
1034 $(this).siblings('.crm-clear-link').css({visibility
: ''});
1039 $.fn
.crmAccordions = function (speed
) {
1040 var container
= $(this).length
> 0 ? $(this) : $('.crm-container');
1041 speed
= speed
=== undefined ? 200 : speed
;
1043 .off('click.crmAccordions')
1044 // Allow normal clicking of links
1045 .on('click.crmAccordions', 'div.crm-accordion-header a', function (e
) {
1046 e
.stopPropagation
&& e
.stopPropagation();
1048 .on('click.crmAccordions', '.crm-accordion-header, .crm-collapsible .collapsible-title', function () {
1049 if ($(this).parent().hasClass('collapsed')) {
1050 $(this).next().css('display', 'none').slideDown(speed
);
1053 $(this).next().css('display', 'block').slideUp(speed
);
1055 $(this).parent().toggleClass('collapsed');
1059 $.fn
.crmAccordionToggle = function (speed
) {
1060 $(this).each(function () {
1061 if ($(this).hasClass('collapsed')) {
1062 $('.crm-accordion-body', this).first().css('display', 'none').slideDown(speed
);
1065 $('.crm-accordion-body', this).first().css('display', 'block').slideUp(speed
);
1067 $(this).toggleClass('collapsed');
1072 * Clientside currency formatting
1074 * @param format - currency representation of the number 1234.56
1076 * @see CRM_Core_Resources::addCoreResources
1078 var currencyTemplate
;
1079 CRM
.formatMoney = function(value
, format
) {
1080 var decimal, separator
, sign
, i
, j
, result
;
1081 if (value
=== 'init' && format
) {
1082 currencyTemplate
= format
;
1085 format
= format
|| currencyTemplate
;
1086 result
= /1(.?)234(.?)56/.exec(format
);
1087 if (result
=== null) {
1088 return 'Invalid format passed to CRM.formatMoney';
1090 separator
= result
[1];
1091 decimal = result
[2];
1092 sign
= (value
< 0) ? '-' : '';
1093 //extracting the absolute value of the integer part of the number and converting to string
1094 i
= parseInt(value
= Math
.abs(value
).toFixed(2)) + '';
1095 j
= ((j
= i
.length
) > 3) ? j
% 3 : 0;
1096 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) : '');
1097 return format
.replace(/1.*234.*56/, result
);