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 $.fn
.select2
.defaults
.dropdownCssClass
= 'crm-container';
245 // https://github.com/ivaynberg/select2/pull/2090
246 $.fn
.select2
.defaults
.width
= 'resolve';
248 // Workaround for https://github.com/ivaynberg/select2/issues/1246
249 $.ui
.dialog
.prototype._allowInteraction = function(e
) {
250 return !!$(e
.target
).closest('.ui-dialog, .ui-datepicker, .select2-drop').length
;
254 * Populate a select list, overwriting the existing options except for the placeholder.
255 * @param $el jquery collection - 1 or more select elements
256 * @param options array in format returned by api.getoptions
257 * @param removePlaceholder bool
259 CRM
.utils
.setOptions = function($el
, options
, removePlaceholder
) {
260 $el
.each(function() {
263 val
= $elect
.val() || [],
264 opts
= removePlaceholder
? '' : '[value!=""]';
265 if (typeof(val
) !== 'array') {
268 $elect
.find('option' + opts
).remove();
269 $.each(options
, function(key
, option
) {
270 var selected
= ($.inArray(''+option
.key
, val
) > -1) ? 'selected="selected"' : '';
271 $elect
.append('<option value="' + option
.key
+ '"' + selected
+ '>' + option
.value
+ '</option>');
273 $elect
.trigger('crmOptionsUpdated').trigger('change');
278 * Wrapper around select2 initialization function; supplies defaults
279 * @param options object
281 $.fn
.crmSelect2 = function(options
) {
282 return $(this).each(function () {
285 defaults
= {allowClear
: !$el
.hasClass('required')};
286 // quickform doesn't support optgroups so here's a hack :(
287 $('option[value^=crm_optgroup]', this).each(function () {
288 $(this).nextUntil('option[value^=crm_optgroup]').wrapAll('<optgroup label="' + $(this).text() + '" />');
291 // Defaults for single-selects
292 if ($el
.is('select:not([multiple])')) {
293 defaults
.minimumResultsForSearch
= 10;
294 if ($('option:first', this).val() === '') {
295 defaults
.placeholderOption
= 'first';
298 $el
.select2($.extend(defaults
, $el
.data('select-params') || {}, options
|| {}));
303 * Initialize a select2 autocomplete using the getlist api
304 * @param options object
306 $.fn
.crmEntityRef = function(options
) {
307 options
= options
|| {};
308 options
.select
= options
.select
|| {};
309 return $(this).each(function() {
312 entity
= options
.entity
|| $el
.data('api-entity') || 'contact',
314 $el
.data('api-entity', entity
);
315 $el
.data('select-params', $.extend({}, $el
.data('select-params') || {}, options
.select
));
316 $el
.data('api-params', $.extend({}, $el
.data('api-params') || {}, options
.api
));
317 $el
.data('create-links', options
.create
|| $el
.data('create-links'));
318 $el
.addClass('crm-ajax-select crm-' + entity
+ '-ref');
320 // Use select2 ajax helper instead of CRM.api because it provides more value
322 url
: CRM
.url('civicrm/ajax/rest'),
323 data: function (input
, page_num
) {
324 var params
= $el
.data('api-params') || {};
325 params
.input
= input
;
326 params
.page_num
= page_num
;
328 entity
: $el
.data('api-entity'),
330 json
: JSON
.stringify(params
)
333 results: function(data
) {
334 return {more
: data
.more_results
, results
: data
.values
|| []};
337 minimumInputLength
: 1,
338 formatResult
: formatSelect2Result
,
339 formatSelection: function(row
) {
342 escapeMarkup: function (m
) {return m
;},
343 initSelection: function($el
, callback
) {
345 multiple
= !!$el
.data('select-params').multiple
,
347 stored
= $el
.data('entity-value') || [];
351 // If we already have this data, just return it
352 if (!_
.xor(val
.split(','), _
.pluck(stored
, 'id')).length
) {
353 callback(multiple
? stored
: stored
[0]);
355 var params
= $el
.data('api-params') || {};
357 CRM
.api3($el
.data('api-entity'), 'getlist', params
).done(function(result
) {
358 callback(multiple
? result
.values
: result
.values
[0])
363 if ($el
.data('create-links')) {
364 selectParams
.formatInputTooShort = function() {
365 var txt
= $el
.data('select-params').formatInputTooShort
|| $.fn
.select2
.defaults
.formatInputTooShort
.call(this);
366 if ($el
.data('create-links')) {
367 txt
+= ' ' + ts('or') + '<br />' + formatSelect2CreateLinks($el
);
371 selectParams
.formatNoMatches = function() {
372 var txt
= $el
.data('select-params').formatNoMatches
|| $.fn
.select2
.defaults
.formatNoMatches
;
373 return txt
+ '<br />' + formatSelect2CreateLinks($el
);
375 $el
.off('.createLinks').on('select2-open.createLinks', function() {
377 $('#select2-drop').off('.crmEntity').on('click.crmEntity', 'a.crm-add-entity', function(e
) {
378 $el
.select2('close');
379 CRM
.loadForm($(this).attr('href'), {
380 dialog
: {width
: 500, height
: 'auto'}
381 }).on('crmFormSuccess', function(e
, data
) {
382 if (data
.status
=== 'success' && data
.id
) {
383 if ($el
.select2('container').hasClass('select2-container-multi')) {
384 var selection
= $el
.select2('data');
385 selection
.push(data
);
386 $el
.select2('data', selection
, true);
388 $el
.select2('data', data
, true);
396 $el
.crmSelect2($.extend(settings
, $el
.data('select-params'), selectParams
));
400 function formatSelect2Result(row
) {
401 var markup
= '<div class="crm-select2-row">';
402 if (row
.image
!== undefined) {
403 markup
+= '<div class="crm-select2-image"><img src="' + row
.image
+ '"/></div>';
405 else if (row
.icon_class
) {
406 markup
+= '<div class="crm-select2-icon"><div class="crm-icon ' + row
.icon_class
+ '-icon"></div></div>';
408 markup
+= '<div><div class="crm-select2-row-label">' + row
.label
+ '</div>';
409 markup
+= '<div class="crm-select2-row-description">';
410 $.each(row
.description
|| [], function(k
, text
) {
411 markup
+= '<p>' + text
+ '</p>';
413 markup
+= '</div></div></div>';
417 function formatSelect2CreateLinks($el
) {
419 createLinks
= $el
.data('create-links'),
420 api
= $el
.data('api-params') || {},
421 type
= api
.params
? api
.params
.contact_type
: null;
422 if (createLinks
=== true) {
423 createLinks
= type
? _
.where(CRM
.profile
.contactCreate
, {type
: type
}) : CRM
.profile
.contactCreate
;
426 _
.each(createLinks
, function(link
) {
427 markup
+= ' <a class="crm-add-entity crm-hover-button" href="' + link
.url
+ '">';
429 markup
+= '<span class="icon ' + link
.type
+ '-profile-icon"></span> ';
431 markup
+= link
.label
+ '</a>';
436 // Initialize widgets
437 $(document
).on('crmLoad', function(e
) {
438 $('table.row-highlight', e
.target
)
439 .off('.rowHighlight')
440 .on('change.rowHighlight', 'input.select-row, input.select-rows', function () {
441 var target
, table
= $(this).closest('table');
442 if ($(this).hasClass('select-rows')) {
443 target
= $('tbody tr', table
);
444 $('input.select-row', table
).prop('checked', $(this).prop('checked'));
447 target
= $(this).closest('tr');
448 $('input.select-rows', table
).prop('checked', $(".select-row:not(':checked')", table
).length
< 1);
450 target
.toggleClass('crm-row-selected', $(this).is(':checked'));
452 .find('input.select-row:checked').parents('tr').addClass('crm-row-selected');
453 $('.crm-select2:not(.select2-offscreen)', e
.target
).crmSelect2();
454 $('.crm-form-entityref:not(.select2-offscreen)', e
.target
).crmEntityRef();
458 * Function to make multiselect boxes behave as fields in small screens
460 function advmultiselectResize() {
461 var amswidth
= $("#crm-container form:has(table.advmultiselect)").width();
462 if (amswidth
< 700) {
463 $("form table.advmultiselect td").css('display', 'block');
466 $("form table.advmultiselect td").css('display', 'table-cell');
468 var contactwidth
= $('#crm-container #mainTabContainer').width();
469 if (contactwidth
< 600) {
470 $('#crm-container #mainTabContainer').addClass('narrowpage');
471 $('#crm-container #mainTabContainer.narrowpage #contactTopBar td').each(function (index
) {
473 if (index
% 2 == 0) {
474 $(this).parent().after('<tr class="narrowadded"></tr>');
477 $(this).parent().next().append(item
);
482 $('#crm-container #mainTabContainer.narrowpage').removeClass('narrowpage');
483 $('#crm-container #mainTabContainer #contactTopBar tr.narrowadded td').each(function () {
485 var parent
= $(this).parent();
486 $(this).parent().prev().append(nitem
);
487 if (parent
.children().size() == 0) {
491 $('#crm-container #mainTabContainer.narrowpage #contactTopBar tr.added').detach();
493 var cformwidth
= $('#crm-container #Contact .contact_basic_information-section').width();
495 if (cformwidth
< 720) {
496 $('#crm-container .contact_basic_information-section').addClass('narrowform');
497 $('#crm-container .contact_basic_information-section table.form-layout-compressed td .helpicon').parent().addClass('hashelpicon');
498 if (cformwidth
< 480) {
499 $('#crm-container .contact_basic_information-section').addClass('xnarrowform');
502 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
506 $('#crm-container .contact_basic_information-section.narrowform').removeClass('narrowform');
507 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
511 advmultiselectResize();
512 $(window
).resize(function () {
513 advmultiselectResize();
516 $.fn
.crmtooltip = function () {
518 .on('mouseover', 'a.crm-summary-link:not(.crm-processed)', function (e
) {
519 $(this).addClass('crm-processed');
520 $(this).addClass('crm-tooltip-active');
521 var topDistance
= e
.pageY
- $(window
).scrollTop();
522 if (topDistance
< 300 | topDistance
< $(this).children('.crm-tooltip-wrapper').height()) {
523 $(this).addClass('crm-tooltip-down');
525 if (!$(this).children('.crm-tooltip-wrapper').length
) {
526 $(this).append('<div class="crm-tooltip-wrapper"><div class="crm-tooltip"></div></div>');
527 $(this).children().children('.crm-tooltip')
528 .html('<div class="crm-loading-element"></div>')
532 .on('mouseout', 'a.crm-summary-link', function () {
533 $(this).removeClass('crm-processed');
534 $(this).removeClass('crm-tooltip-active crm-tooltip-down');
536 .on('click', 'a.crm-summary-link', false);
539 var helpDisplay
, helpPrevious
;
540 CRM
.help = function (title
, params
, url
) {
541 if (helpDisplay
&& helpDisplay
.close
) {
542 // If the same link is clicked twice, just close the display - todo use underscore method for this comparison
543 if (helpDisplay
.isOpen
&& helpPrevious
=== JSON
.stringify(params
)) {
549 helpPrevious
= JSON
.stringify(params
);
550 params
.class_name
= 'CRM_Core_Page_Inline_Help';
551 params
.type
= 'page';
552 helpDisplay
= CRM
.alert('...', title
, 'crm-help crm-msg-loading', {expires
: 0});
553 $.ajax(url
|| CRM
.url('civicrm/ajax/inline'),
557 success: function (data
) {
558 $('#crm-notification-container .crm-help .notify-content:last').html(data
);
559 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('info');
562 $('#crm-notification-container .crm-help .notify-content:last').html('Unable to load help file.');
563 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('error');
569 * @param startMsg string
570 * @param endMsg string|function
571 * @param deferred optional jQuery deferred object
572 * @return jQuery deferred object - if not supplied a new one will be created
575 CRM
.status = function(startMsg
, endMsg
, deferred
) {
576 var $bar
= $('#civicrm-menu');
578 console
&& console
.log
&& console
.log('CRM.status called on a page with no menubar');
581 $('.crm-menubar-status-container', $bar
).remove();
582 fadeOut
&& window
.clearTimeout(fadeOut
);
583 $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>');
584 $('.crm-menubar-status-container', $bar
).css('min-width', $('.crm-menubar-status-container', $bar
).width());
585 deferred
|| (deferred
= new $.Deferred());
586 deferred
.done(function(data
) {
587 var msg
= typeof(endMsg
) === 'function' ? endMsg(data
) : endMsg
;
588 $('.crm-menubar-status-container', $bar
).removeClass('status-busy').addClass('status-done').show().find('.crm-menubar-status-msg').html(msg
);
590 fadeOut
= window
.setTimeout(function() {
591 $('.crm-menubar-status-container', $bar
).fadeOut('slow');
594 $('.crm-menubar-status-container', $bar
).hide();
601 * @param string text Displayable message
602 * @param string title Displayable title
603 * @param string type 'alert'|'info'|'success'|'error' (default: 'alert')
604 * @param {object} options
606 * @see http://wiki.civicrm.org/confluence/display/CRM/Notifications+in+CiviCRM
608 CRM
.alert = function (text
, title
, type
, options
) {
609 type
= type
|| 'alert';
611 options
= options
|| {};
612 if ($('#crm-notification-container').length
) {
618 // By default, don't expire errors and messages containing links
620 expires
: (type
== 'error' || text
.indexOf('<a ') > -1) ? 0 : (text
? 10000 : 5000),
623 options
= $.extend(extra
, options
);
624 options
.expires
= options
.expires
=== false ? 0 : parseInt(options
.expires
, 10);
625 if (options
.unique
&& options
.unique
!== '0') {
626 $('#crm-notification-container .ui-notify-message').each(function () {
627 if (title
=== $('h1', this).html() && text
=== $('.notify-content', this).html()) {
628 $('.icon.ui-notify-close', this).click();
632 return $('#crm-notification-container').notify('create', params
, options
);
636 text
= title
+ "\n" + text
;
644 * Close whichever alert contains the given node
648 CRM
.closeAlertByChild = function (node
) {
649 $(node
).closest('.ui-notify-message').find('.icon.ui-notify-close').click();
653 * Prompt the user for confirmation.
655 * @param buttons {object|function} key|value pairs where key == button label and value == callback function
656 * passing in a function instead of an object is a shortcut for a sinlgle button labeled "Continue"
657 * @param options {object|void} Override defaults, keys include 'title', 'message',
658 * see jQuery.dialog for full list of available params
659 * @param cancelLabel {string}
661 CRM
.confirm = function (buttons
, options
, cancelLabel
) {
662 var dialog
, callbacks
= {};
663 cancelLabel
= cancelLabel
|| ts('Cancel');
665 title
: ts('Confirm Action'),
666 message
: ts('Are you sure you want to continue?'),
676 settings
.buttons
[cancelLabel
] = function () {
677 dialog
.dialog('close');
679 options
= options
|| {};
680 $.extend(settings
, options
);
681 if (typeof(buttons
) === 'function') {
682 callbacks
[ts('Continue')] = buttons
;
687 $.each(callbacks
, function (label
, callback
) {
688 settings
.buttons
[label
] = function () {
689 if (callback
.call(dialog
) !== false) {
690 dialog
.dialog('close');
694 dialog
= $('<div class="crm-container crm-confirm-dialog"></div>')
695 .html(options
.message
)
702 * Sets an error message
703 * If called for a form item, title and removal condition will be handled automatically
705 $.fn
.crmError = function (text
, title
, options
) {
708 options
= options
|| {};
713 if ($(this).length
) {
715 var label
= $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]').not('[generated=true]');
717 label
.addClass('crm-error');
718 var $label
= label
.clone();
719 if (text
== '' && $('.crm-marker', $label
).length
> 0) {
720 text
= $('.crm-marker', $label
).attr('title');
722 $('.crm-marker', $label
).remove();
723 title
= $label
.text();
726 $(this).addClass('error');
728 var msg
= CRM
.alert(text
, title
, 'error', $.extend(extra
, options
));
729 if ($(this).length
) {
731 setTimeout(function () {
732 ele
.one('change', function () {
733 msg
&& msg
.close
&& msg
.close();
734 ele
.removeClass('error');
735 label
.removeClass('crm-error');
742 // Display system alerts through js notifications
743 function messagesFromMarkup() {
744 $('div.messages:visible', this).not('.help').not('.no-popup').each(function () {
745 var text
, title
= '';
746 $(this).removeClass('status messages');
747 var type
= $(this).attr('class').split(' ')[0] || 'alert';
748 type
= type
.replace('crm-', '');
749 $('.icon', this).remove();
750 if ($('.msg-text', this).length
> 0) {
751 text
= $('.msg-text', this).html();
752 title
= $('.msg-title', this).html();
755 text
= $(this).html();
757 var options
= $(this).data('options') || {};
759 // Duplicates were already removed server-side
760 options
.unique
= false;
761 CRM
.alert(text
, title
, type
, options
);
763 // Handle qf form errors
764 $('form :input.error', this).one('blur', function() {
765 // ignore autocomplete fields
766 if ($(this).is('.ac_input')) {
770 $('.ui-notify-message.error a.ui-notify-close').click();
771 $(this).removeClass('error');
772 $(this).next('span.crm-error').remove();
773 $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]')
774 .removeClass('crm-error')
775 .find('.crm-error').removeClass('crm-error');
779 $.widget('civi.crmSnippet', {
785 _originalContent
: null,
787 isOriginalUrl: function() {
791 newUrl
= this._formatUrl(this.options
.url
),
792 oldUrl
= this._formatUrl(this._originalUrl
);
794 if (newUrl
.split('?')[0] !== oldUrl
.split('?')[0]) {
798 $.each(newUrl
.split('?')[1].split('&'), function(k
, v
) {
799 var arg
= v
.split('=');
800 args
[arg
[0]] = arg
[1];
802 $.each(oldUrl
.split('?')[1].split('&'), function(k
, v
) {
803 var arg
= v
.split('=');
804 if (args
[arg
[0]] !== undefined && arg
[1] !== args
[arg
[0]]) {
810 resetUrl: function() {
811 this.options
.url
= this._originalUrl
;
813 _create: function() {
814 this.element
.addClass('crm-ajax-container');
815 if (!this.element
.is('.crm-container *')) {
816 this.element
.addClass('crm-container');
818 this._handleOrderLinks();
819 // Set default if not supplied
820 this.options
.url
= this.options
.url
|| document
.location
.href
;
821 this._originalUrl
= this.options
.url
;
823 _onFailure: function(data
) {
824 this.options
.block
&& this.element
.unblock();
825 this.element
.trigger('crmAjaxFail', data
);
826 CRM
.alert(ts('Unable to reach the server. Please refresh this page in your browser and try again.'), ts('Network Error'), 'error');
828 _formatUrl: function(url
) {
830 url
= url
.split('#')[0];
831 // Add snippet argument to url
832 if (url
.search(/[&?]snippet=/) < 0) {
833 url
+= (url
.indexOf('?') < 0 ? '?' : '&') + 'snippet=json';
835 url
= url
.replace(/snippet=[^&]*/, 'snippet=json');
839 // Hack to deal with civicrm legacy sort functionality
840 _handleOrderLinks: function() {
842 $('a.crm-weight-arrow', that
.element
).click(function(e
) {
843 that
.options
.block
&& that
.element
.block();
844 $.getJSON(that
._formatUrl(this.href
)).done(function() {
847 e
.stopImmediatePropagation();
851 refresh: function() {
853 var url
= this._formatUrl(this.options
.url
);
854 this.options
.block
&& $('.blockOverlay', this.element
).length
< 1 && this.element
.block();
855 $.getJSON(url
, function(data
) {
856 if (typeof(data
) != 'object' || typeof(data
.content
) != 'string') {
857 that
._onFailure(data
);
861 that
.element
.trigger('crmBeforeLoad', data
);
862 if (that
._originalContent
=== null) {
863 that
._originalContent
= that
.element
.contents().detach();
865 that
.element
.html(data
.content
);
866 that
._handleOrderLinks();
867 that
.element
.trigger('crmLoad', data
);
868 that
.options
.crmForm
&& that
.element
.trigger('crmFormLoad', data
);
873 _destroy: function() {
874 this.element
.removeClass('crm-ajax-container');
875 if (this._originalContent
!== null) {
876 this.element
.empty().append(this._originalContent
);
882 CRM
.loadPage = function(url
, options
) {
884 target
: '#crm-ajax-dialog-' + (dialogCount
++),
887 if (!options
|| !options
.target
) {
891 height
: parseInt($(window
).height() * .75),
893 $(this).dialog('destroy').remove();
897 options
&& $.extend(true, settings
, options
);
900 if (settings
.dialog
) {
901 $('<div id="'+ settings
.target
.substring(1) +'"><div class="crm-loading-element">' + ts('Loading') + '...</div></div>').dialog(settings
.dialog
);
903 if (settings
.dialog
&& !settings
.dialog
.title
) {
904 $(settings
.target
).on('crmLoad', function(e
, data
) {
905 if (e
.target
=== $(settings
.target
)[0] && data
&& data
.title
) {
906 $(this).dialog('option', 'title', data
.title
);
910 $(settings
.target
).crmSnippet(settings
).crmSnippet('refresh');
911 return $(settings
.target
);
914 CRM
.loadForm = function(url
, options
) {
920 refreshAction
: ['next_new', 'submit_savenext'],
921 cancelButton
: '.cancel.form-submit',
922 openInline
: 'a.button:not("[href=#], .no-popup")',
923 onCancel: function(event
) {},
924 onError: function(data
) {
926 $el
.html(data
.content
).trigger('crmLoad', data
).trigger('crmFormLoad', data
).trigger('crmFormError', data
);
927 if (typeof(data
.errors
) == 'object') {
928 $.each(data
.errors
, function(formElement
, msg
) {
929 $('[name="'+formElement
+'"]', $el
).crmError(msg
);
935 // Hack to make delete dialogs smaller
936 if (url
.indexOf('/delete') > 0 || url
.indexOf('action=delete') > 0) {
942 // Move options that belong to crmForm. Others will be passed through to crmSnippet
943 options
&& $.each(options
, function(key
, value
) {
944 if (typeof(settings
.crmForm
[key
]) !== 'undefined') {
945 settings
.crmForm
[key
] = value
;
948 settings
[key
] = value
;
952 var widget
= CRM
.loadPage(url
, settings
);
954 widget
.on('crmFormLoad', function(event
, data
) {
956 var settings
= $el
.crmSnippet('option', 'crmForm');
957 settings
.cancelButton
&& $(settings
.cancelButton
, this).click(function(event
) {
958 var returnVal
= settings
.onCancel
.call($el
, event
);
959 if (returnVal
!== false) {
960 $el
.trigger('crmFormCancel', event
);
961 if ($el
.data('uiDialog') && settings
.autoClose
) {
964 else if (!settings
.autoClose
) {
965 $el
.crmSnippet('resetUrl').crmSnippet('refresh');
968 return returnVal
=== false;
970 if (settings
.validate
) {
971 $("form", this).validate(typeof(settings
.validate
) == 'object' ? settings
.validate
: CRM
.validate
.params
);
973 $("form", this).ajaxForm($.extend({
974 url
: data
.url
.replace(/reset=1[&]?/, ''),
976 success: function(response
) {
977 if (response
.status
!== 'form_error') {
978 $el
.crmSnippet('option', 'block') && $el
.unblock();
979 $el
.trigger('crmFormSuccess', response
);
980 // Reset form for e.g. "save and new"
981 if (response
.userContext
&& settings
.refreshAction
&& $.inArray(response
.buttonName
, settings
.refreshAction
) >= 0) {
982 $el
.crmSnippet('option', 'url', response
.userContext
).crmSnippet('refresh');
984 else if ($el
.data('uiDialog') && settings
.autoClose
) {
987 else if (settings
.autoClose
=== false) {
988 $el
.crmSnippet('resetUrl').crmSnippet('refresh');
992 response
.url
= data
.url
;
993 settings
.onError
.call($el
, response
);
996 beforeSerialize: function(form
, options
) {
997 if (window
.CKEDITOR
&& window
.CKEDITOR
.instances
) {
998 $.each(CKEDITOR
.instances
, function() {
999 this.updateElement
&& this.updateElement();
1003 beforeSubmit: function(submission
) {
1004 $el
.crmSnippet('option', 'block') && $el
.block();
1005 $el
.trigger('crmFormSubmit', submission
);
1007 }, settings
.ajaxForm
));
1008 if (settings
.openInline
) {
1009 settings
.autoClose
= $el
.crmSnippet('isOriginalUrl');
1010 $(settings
.openInline
, this).click(function(event
) {
1011 $el
.crmSnippet('option', 'url', $(this).attr('href')).crmSnippet('refresh');
1015 // For convenience, focus the first field
1016 $('input[type=text], textarea, select', this).filter(':visible').first().focus();
1021 // Preprocess all cj ajax calls to display messages
1022 $(document
).ajaxSuccess(function(event
, xhr
, settings
) {
1024 if ((!settings
.dataType
|| settings
.dataType
== 'json') && xhr
.responseText
) {
1025 var response
= $.parseJSON(xhr
.responseText
);
1026 if (typeof(response
.crmMessages
) == 'object') {
1027 $.each(response
.crmMessages
, function(n
, msg
) {
1028 CRM
.alert(msg
.text
, msg
.title
, msg
.type
, msg
.options
);
1038 * Temporary stub to get around name conflict with legacy jQuery.autocomplete plugin
1040 $.widget('civi.crmAutocomplete', $.ui
.autocomplete
, {});
1043 // Trigger crmLoad on initial content for consistency. It will also be triggered for ajax-loaded content.
1044 $('.crm-container').trigger('crmLoad');
1046 if ($('#crm-notification-container').length
) {
1047 // Initialize notifications
1048 $('#crm-notification-container').notify();
1049 messagesFromMarkup
.call($('#crm-container'));
1052 // bind the event for image popup
1054 .on('click', 'a.crm-image-popup', function() {
1055 var o
= $('<div class="crm-container crm-custom-image-popup"><img src=' + $(this).attr('href') + '></div>');
1059 title
: ts('Preview'),
1067 .on('click', function (event
) {
1068 $('.btn-slide-active').removeClass('btn-slide-active').find('.panel').hide();
1069 if ($(event
.target
).is('.btn-slide')) {
1070 $(event
.target
).addClass('btn-slide-active').find('.panel').show();
1074 .on('click', 'a.crm-option-edit-link', function() {
1076 CRM
.loadForm(this.href
, {openInline
: 'a:not("[href=#], .no-popup")'})
1077 // Lots of things can happen once the form opens, this is the only event we can really rely on
1078 .on('dialogclose', function() {
1079 link
.trigger('crmOptionsEdited');
1080 var $elects
= $('select[data-option-edit-path="' + link
.data('option-edit-path') + '"]');
1081 if ($elects
.data('api-entity') && $elects
.data('api-field')) {
1082 CRM
.api3($elects
.data('api-entity'), 'getoptions', {sequential
: 1, field
: $elects
.data('api-field')})
1083 .done(function(data
) {
1084 CRM
.utils
.setOptions($elects
, data
.values
);
1090 // Handle clear button for form elements
1091 .on('click', 'a.crm-clear-link', function() {
1092 $(this).css({visibility
: 'hidden'}).siblings('.crm-form-radio:checked').prop('checked', false).change();
1093 $(this).siblings('input:text').val('').change();
1096 .on('change', 'input.crm-form-radio:checked', function() {
1097 $(this).siblings('.crm-clear-link').css({visibility
: ''});
1102 $.fn
.crmAccordions = function (speed
) {
1103 var container
= $(this).length
> 0 ? $(this) : $('.crm-container');
1104 speed
= speed
=== undefined ? 200 : speed
;
1106 .off('click.crmAccordions')
1107 // Allow normal clicking of links
1108 .on('click.crmAccordions', 'div.crm-accordion-header a', function (e
) {
1109 e
.stopPropagation
&& e
.stopPropagation();
1111 .on('click.crmAccordions', '.crm-accordion-header, .crm-collapsible .collapsible-title', function () {
1112 if ($(this).parent().hasClass('collapsed')) {
1113 $(this).next().css('display', 'none').slideDown(speed
);
1116 $(this).next().css('display', 'block').slideUp(speed
);
1118 $(this).parent().toggleClass('collapsed');
1122 $.fn
.crmAccordionToggle = function (speed
) {
1123 $(this).each(function () {
1124 if ($(this).hasClass('collapsed')) {
1125 $('.crm-accordion-body', this).first().css('display', 'none').slideDown(speed
);
1128 $('.crm-accordion-body', this).first().css('display', 'block').slideUp(speed
);
1130 $(this).toggleClass('collapsed');
1135 * Clientside currency formatting
1137 * @param format - currency representation of the number 1234.56
1139 * @see CRM_Core_Resources::addCoreResources
1141 var currencyTemplate
;
1142 CRM
.formatMoney = function(value
, format
) {
1143 var decimal, separator
, sign
, i
, j
, result
;
1144 if (value
=== 'init' && format
) {
1145 currencyTemplate
= format
;
1148 format
= format
|| currencyTemplate
;
1149 result
= /1(.?)234(.?)56/.exec(format
);
1150 if (result
=== null) {
1151 return 'Invalid format passed to CRM.formatMoney';
1153 separator
= result
[1];
1154 decimal = result
[2];
1155 sign
= (value
< 0) ? '-' : '';
1156 //extracting the absolute value of the integer part of the number and converting to string
1157 i
= parseInt(value
= Math
.abs(value
).toFixed(2)) + '';
1158 j
= ((j
= i
.length
) > 3) ? j
% 3 : 0;
1159 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) : '');
1160 return format
.replace(/1.*234.*56/, result
);