Merge pull request #3317 from eileenmcnaughton/CRM-14197-postprocesfn
[civicrm-core.git] / js / Common.js
1 // https://civicrm.org/licensing
2 var CRM = CRM || {};
3 var cj = CRM.$ = jQuery;
4 CRM._ = _;
5
6 /**
7 * Short-named function for string translation, defined in global scope so it's available everywhere.
8 *
9 * @param text string for translating
10 * @param params object key:value of additional parameters
11 *
12 * @return string
13 */
14 function ts(text, params) {
15 "use strict";
16 text = CRM.strings[text] || text;
17 if (typeof(params) === 'object') {
18 for (var i in params) {
19 if (typeof(params[i]) === 'string' || typeof(params[i]) === 'number') {
20 // sprintf emulation: escape % characters in the replacements to avoid conflicts
21 text = text.replace(new RegExp('%' + i, 'g'), String(params[i]).replace(/%/g, '%-crmescaped-'));
22 }
23 }
24 return text.replace(/%-crmescaped-/g, '%');
25 }
26 return text;
27 }
28
29 /**
30 * This function is called by default at the bottom of template files which have forms that have
31 * conditionally displayed/hidden sections and elements. The PHP is responsible for generating
32 * a list of 'blocks to show' and 'blocks to hide' and the template passes these parameters to
33 * this function.
34 *
35 * @deprecated
36 * @param showBlocks Array of element Id's to be displayed
37 * @param hideBlocks Array of element Id's to be hidden
38 * @param elementType Value to set display style to for showBlocks (e.g. 'block' or 'table-row' or ...)
39 */
40 function on_load_init_blocks(showBlocks, hideBlocks, elementType) {
41 if (elementType == null) {
42 var elementType = 'block';
43 }
44
45 /* This loop is used to display the blocks whose IDs are present within the showBlocks array */
46 for (var i = 0; i < showBlocks.length; i++) {
47 var myElement = document.getElementById(showBlocks[i]);
48 /* getElementById returns null if element id doesn't exist in the document */
49 if (myElement != null) {
50 myElement.style.display = elementType;
51 }
52 else {
53 alert('showBlocks array item not in .tpl = ' + showBlocks[i]);
54 }
55 }
56
57 /* This loop is used to hide the blocks whose IDs are present within the hideBlocks array */
58 for (var i = 0; i < hideBlocks.length; i++) {
59 var myElement = document.getElementById(hideBlocks[i]);
60 /* getElementById returns null if element id doesn't exist in the document */
61 if (myElement != null) {
62 myElement.style.display = 'none';
63 }
64 else {
65 alert('showBlocks array item not in .tpl = ' + hideBlocks[i]);
66 }
67 }
68 }
69
70 /**
71 * This function is called when we need to show or hide a related form element (target_element)
72 * based on the value (trigger_value) of another form field (trigger_field).
73 *
74 * @deprecated
75 * @param trigger_field_id HTML id of field whose onchange is the trigger
76 * @param trigger_value List of integers - option value(s) which trigger show-element action for target_field
77 * @param target_element_id HTML id of element to be shown or hidden
78 * @param target_element_type Type of element to be shown or hidden ('block' or 'table-row')
79 * @param field_type Type of element radio/select
80 * @param invert Boolean - if true, we HIDE target on value match; if false, we SHOW target on value match
81 */
82 function showHideByValue(trigger_field_id, trigger_value, target_element_id, target_element_type, field_type, invert) {
83 if (target_element_type == null) {
84 var target_element_type = 'block';
85 }
86 else {
87 if (target_element_type == 'table-row') {
88 var target_element_type = '';
89 }
90 }
91
92 if (field_type == 'select') {
93 var trigger = trigger_value.split("|");
94 var selectedOptionValue = cj('#' + trigger_field_id).val();
95
96 var target = target_element_id.split("|");
97 for (var j = 0; j < target.length; j++) {
98 if (invert) {
99 cj('#' + target[j]).show();
100 }
101 else {
102 cj('#' + target[j]).hide();
103 }
104 for (var i = 0; i < trigger.length; i++) {
105 if (selectedOptionValue == trigger[i]) {
106 if (invert) {
107 cj('#' + target[j]).hide();
108 }
109 else {
110 cj('#' + target[j]).show();
111 }
112 }
113 }
114 }
115
116 }
117 else {
118 if (field_type == 'radio') {
119 var target = target_element_id.split("|");
120 for (var j = 0; j < target.length; j++) {
121 if (cj('[name="' + trigger_field_id + '"]').is(':checked')) {
122 if (invert) {
123 cj('#' + target[j]).hide();
124 }
125 else {
126 cj('#' + target[j]).show();
127 }
128 }
129 else {
130 if (invert) {
131 cj('#' + target[j]).show();
132 }
133 else {
134 cj('#' + target[j]).hide();
135 }
136 }
137 }
138 }
139 }
140 }
141
142 /**
143 * Function to change button text and disable one it is clicked
144 * @deprecated
145 * @param obj object - the button clicked
146 * @param formID string - the id of the form being submitted
147 * @param string procText - button text after user clicks it
148 * @return bool
149 */
150 var submitcount = 0;
151 /* Changes button label on submit, and disables button after submit for newer browsers.
152 Puts up alert for older browsers. */
153 function submitOnce(obj, formId, procText) {
154 // if named button clicked, change text
155 if (obj.value != null) {
156 obj.value = procText + " ...";
157 }
158 if (document.getElementById) { // disable submit button for newer browsers
159 obj.disabled = true;
160 document.getElementById(formId).submit();
161 return true;
162 }
163 else { // for older browsers
164 if (submitcount == 0) {
165 submitcount++;
166 return true;
167 }
168 else {
169 alert("Your request is currently being processed ... Please wait.");
170 return false;
171 }
172 }
173 }
174
175 /**
176 * Function to show / hide the row in optionFields
177 * @deprecated
178 * @param index string, element whose innerHTML is to hide else will show the hidden row.
179 */
180 function showHideRow(index) {
181 if (index) {
182 cj('tr#optionField_' + index).hide();
183 if (cj('table#optionField tr:hidden:first').length) {
184 cj('div#optionFieldLink').show();
185 }
186 }
187 else {
188 cj('table#optionField tr:hidden:first').show();
189 if (!cj('table#optionField tr:hidden:last').length) {
190 cj('div#optionFieldLink').hide();
191 }
192 }
193 return false;
194 }
195
196 CRM.utils = CRM.utils || {};
197 CRM.strings = CRM.strings || {};
198 CRM.validate = CRM.validate || {
199 params: {},
200 functions: []
201 };
202
203 (function ($, _, undefined) {
204 "use strict";
205
206 // Theme classes for unattached elements
207 $.fn.select2.defaults.dropdownCssClass = $.ui.dialog.prototype.options.dialogClass = 'crm-container';
208
209 // https://github.com/ivaynberg/select2/pull/2090
210 $.fn.select2.defaults.width = 'resolve';
211
212 // Workaround for https://github.com/ivaynberg/select2/issues/1246
213 $.ui.dialog.prototype._allowInteraction = function(e) {
214 return !!$(e.target).closest('.ui-dialog, .ui-datepicker, .select2-drop').length;
215 };
216
217 /**
218 * Populate a select list, overwriting the existing options except for the placeholder.
219 * @param $el jquery collection - 1 or more select elements
220 * @param options array in format returned by api.getoptions
221 * @param removePlaceholder bool
222 */
223 CRM.utils.setOptions = function($el, options, removePlaceholder) {
224 $el.each(function() {
225 var
226 $elect = $(this),
227 val = $elect.val() || [],
228 opts = removePlaceholder ? '' : '[value!=""]';
229 if (!$.isArray(val)) {
230 val = [val];
231 }
232 $elect.find('option' + opts).remove();
233 _.each(options, function(option) {
234 var selected = ($.inArray(''+option.key, val) > -1) ? 'selected="selected"' : '';
235 $elect.append('<option value="' + option.key + '"' + selected + '>' + option.value + '</option>');
236 });
237 $elect.trigger('crmOptionsUpdated', $.extend({}, options)).trigger('change');
238 });
239 };
240
241 /**
242 * Compare Form Input values against cached initial value.
243 *
244 * @return {Boolean} true if changes have been made.
245 */
246 CRM.utils.initialValueChanged = function(el) {
247 var isDirty = false;
248 $(':input:visible, :input.select2-offscreen', el).each(function () {
249 var initialValue = $(this).data('crm-initial-value');
250 // skip change of value for submit buttons
251 if (initialValue !== undefined && !$(this).hasClass('form-submit') && initialValue != $(this).val()) {
252 isDirty = true;
253 }
254 });
255 return isDirty;
256 }
257
258 /**
259 * Wrapper for select2 initialization function; supplies defaults
260 * @param options object
261 */
262 $.fn.crmSelect2 = function(options) {
263 return $(this).each(function () {
264 var
265 $el = $(this),
266 settings = {allowClear: !$el.hasClass('required')};
267 // quickform doesn't support optgroups so here's a hack :(
268 $('option[value^=crm_optgroup]', this).each(function () {
269 $(this).nextUntil('option[value^=crm_optgroup]').wrapAll('<optgroup label="' + $(this).text() + '" />');
270 $(this).remove();
271 });
272 // Defaults for single-selects
273 if ($el.is('select:not([multiple])')) {
274 settings.minimumResultsForSearch = 10;
275 if ($('option:first', this).val() === '') {
276 settings.placeholderOption = 'first';
277 }
278 }
279 $.extend(settings, $el.data('select-params') || {}, options || {});
280 if (settings.ajax) {
281 $el.addClass('crm-ajax-select');
282 }
283 $el.select2(settings);
284 });
285 };
286
287 /**
288 * @see CRM_Core_Form::addEntityRef for docs
289 * @param options object
290 */
291 $.fn.crmEntityRef = function(options) {
292 options = options || {};
293 options.select = options.select || {};
294 return $(this).each(function() {
295 var
296 $el = $(this).off('.crmEntity'),
297 entity = options.entity || $el.data('api-entity') || 'contact',
298 selectParams = {};
299 $el.data('api-entity', entity);
300 $el.data('select-params', $.extend({}, $el.data('select-params') || {}, options.select));
301 $el.data('api-params', $.extend({}, $el.data('api-params') || {}, options.api));
302 $el.data('create-links', options.create || $el.data('create-links'));
303 $el.addClass('crm-form-entityref crm-' + entity + '-ref');
304 var settings = {
305 // Use select2 ajax helper instead of CRM.api because it provides more value
306 ajax: {
307 url: CRM.url('civicrm/ajax/rest'),
308 data: function (input, page_num) {
309 var params = $el.data('api-params') || {};
310 params.input = input;
311 params.page_num = page_num;
312 return {
313 entity: $el.data('api-entity'),
314 action: 'getlist',
315 json: JSON.stringify(params)
316 };
317 },
318 results: function(data) {
319 return {more: data.more_results, results: data.values || []};
320 }
321 },
322 minimumInputLength: 1,
323 formatResult: formatSelect2Result,
324 formatSelection: function(row) {
325 return row.label;
326 },
327 escapeMarkup: function (m) {return m;},
328 initSelection: function($el, callback) {
329 var
330 multiple = !!$el.data('select-params').multiple,
331 val = $el.val(),
332 stored = $el.data('entity-value') || [];
333 if (val === '') {
334 return;
335 }
336 // If we already have this data, just return it
337 if (!_.xor(val.split(','), _.pluck(stored, 'id')).length) {
338 callback(multiple ? stored : stored[0]);
339 } else {
340 var params = $.extend({}, $el.data('api-params') || {}, {id: val});
341 CRM.api3($el.data('api-entity'), 'getlist', params).done(function(result) {
342 callback(multiple ? result.values : result.values[0])
343 });
344 }
345 }
346 };
347 if ($el.data('create-links') && entity.toLowerCase() === 'contact') {
348 selectParams.formatInputTooShort = function() {
349 var txt = $el.data('select-params').formatInputTooShort || $.fn.select2.defaults.formatInputTooShort.call(this);
350 if ($el.data('create-links')) {
351 txt += ' ' + ts('or') + '<br />' + formatSelect2CreateLinks($el);
352 }
353 return txt;
354 };
355 selectParams.formatNoMatches = function() {
356 var txt = $el.data('select-params').formatNoMatches || $.fn.select2.defaults.formatNoMatches;
357 return txt + '<br />' + formatSelect2CreateLinks($el);
358 };
359 $el.on('select2-open.crmEntity', function() {
360 var $el = $(this);
361 $('#select2-drop').off('.crmEntity').on('click.crmEntity', 'a.crm-add-entity', function(e) {
362 $el.select2('close');
363 CRM.loadForm($(this).attr('href'), {
364 dialog: {width: 500, height: 'auto'}
365 }).on('crmFormSuccess', function(e, data) {
366 if (data.status === 'success' && data.id) {
367 CRM.status(ts('%1 Created', {1: data.label}));
368 if ($el.select2('container').hasClass('select2-container-multi')) {
369 var selection = $el.select2('data');
370 selection.push(data);
371 $el.select2('data', selection, true);
372 } else {
373 $el.select2('data', data, true);
374 }
375 }
376 });
377 return false;
378 });
379 });
380 }
381 // Create new items inline - works for tags
382 else if ($el.data('create-links')) {
383 selectParams.createSearchChoice = function(term, data) {
384 if (!_.findKey(data, {label: term})) {
385 return {id: "0", term: term, label: term + ' (' + ts('new tag') + ')'};
386 }
387 };
388 selectParams.tokenSeparators = [','];
389 selectParams.createSearchChoicePosition = 'bottom';
390 }
391 $el.crmSelect2($.extend(settings, $el.data('select-params'), selectParams))
392 .on('select2-selecting.crmEntity', function(e) {
393 if (e.val === "0") {
394 e.object.label = e.object.term;
395 CRM.api3(entity, 'create', $.extend({name: e.object.term}, $el.data('api-params').params || {}))
396 .done(function(created) {
397 var
398 multiple = !!$el.data('select-params').multiple,
399 val = $el.select2('val'),
400 data = $el.select2('data'),
401 item = {id: created.id, label: e.object.term};
402 if (val === "0") {
403 $el.select2('data', item, true);
404 }
405 else if ($.isArray(val) && $.inArray("0", val) > -1) {
406 _.remove(data, {id: "0"});
407 data.push(item);
408 $el.select2('data', data, true);
409 }
410 });
411 }
412 });
413 });
414 };
415
416 function formatSelect2Result(row) {
417 var markup = '<div class="crm-select2-row">';
418 if (row.image !== undefined) {
419 markup += '<div class="crm-select2-image"><img src="' + row.image + '"/></div>';
420 }
421 else if (row.icon_class) {
422 markup += '<div class="crm-select2-icon"><div class="crm-icon ' + row.icon_class + '-icon"></div></div>';
423 }
424 markup += '<div><div class="crm-select2-row-label">' + row.label + '</div>';
425 markup += '<div class="crm-select2-row-description">';
426 $.each(row.description || [], function(k, text) {
427 markup += '<p>' + text + '</p>';
428 });
429 markup += '</div></div></div>';
430 return markup;
431 }
432
433 function formatSelect2CreateLinks($el) {
434 var
435 createLinks = $el.data('create-links'),
436 api = $el.data('api-params') || {},
437 type = api.params ? api.params.contact_type : null;
438 if (createLinks === true) {
439 createLinks = type ? _.where(CRM.profile.contactCreate, {type: type}) : CRM.profile.contactCreate;
440 }
441 var markup = '';
442 _.each(createLinks, function(link) {
443 markup += ' <a class="crm-add-entity crm-hover-button" href="' + link.url + '">';
444 if (link.type) {
445 markup += '<span class="icon ' + link.type + '-profile-icon"></span> ';
446 }
447 markup += link.label + '</a>';
448 });
449 return markup;
450 }
451
452 // Initialize widgets
453 $(document)
454 .on('crmLoad', function(e) {
455 $('table.form-layout-compressed')
456 .on('change', 'input.select-rows', function () {
457 if ($(this).prop('checked')) {
458 $('input#toggleSelect:checked').prop('checked', false);
459 $('input.select-row:checked').prop('checked', false);
460 }
461 })
462 $('table.row-highlight', e.target)
463 .off('.rowHighlight')
464 .on('change.rowHighlight', 'input.select-row, input.select-rows', function (e, data) {
465 var filter, $table = $(this).closest('table');
466 if ($(this).hasClass('select-rows')) {
467 filter = $(this).prop('checked') ? ':not(:checked)' : ':checked';
468 $('input.select-row' + filter, $table).prop('checked', $(this).prop('checked')).trigger('change', 'master-selected');
469 }
470 else {
471 $(this).closest('tr').toggleClass('crm-row-selected', $(this).prop('checked'));
472 if (data !== 'master-selected') {
473 $('input.select-rows', $table).prop('checked', $(".select-row:not(':checked')", $table).length < 1);
474 }
475 if ($(this).prop('checked')) {
476 $('input[value=ts_sel]:radio').prop('checked', true);
477 }
478 }
479 })
480 .find('input.select-row:checked').parents('tr').addClass('crm-row-selected');
481 $('.crm-select2:not(.select2-offscreen, .select2-container)', e.target).crmSelect2();
482 $('.crm-form-entityref:not(.select2-offscreen, .select2-container)', e.target).crmEntityRef();
483 // Cache Form Input initial values
484 $('form[data-warn-changes] :input', e.target).each(function() {
485 $(this).data('crm-initial-value', $(this).val());
486 });
487 })
488 .on('dialogopen', function(e) {
489 var $el = $(e.target);
490 // Modal dialogs should disable scrollbars
491 if ($el.dialog('option', 'modal')) {
492 $el.addClass('modal-dialog');
493 $('body').css({overflow: 'hidden'});
494 }
495 $el.parent().find('.ui-dialog-titlebar-close').attr('title', ts('Close'));
496 // Add resize button
497 if ($el.parent().hasClass('crm-container') && $el.dialog('option', 'resizable')) {
498 $el.parent().find('.ui-dialog-titlebar').append($('<button class="crm-dialog-titlebar-resize ui-dialog-titlebar-close" title="'+ts('Toggle fullscreen')+'" style="right:2em;"/>').button({icons: {primary: 'ui-icon-newwin'}, text: false}));
499 $('.crm-dialog-titlebar-resize', $el.parent()).click(function(e) {
500 if ($el.data('origSize')) {
501 $el.dialog('option', $el.data('origSize'));
502 $el.data('origSize', null);
503 } else {
504 $el.data('origSize', {
505 position: 'center',
506 width: $el.dialog('option', 'width'),
507 height: $el.dialog('option', 'height')
508 });
509 var menuHeight = $('#civicrm-menu').height();
510 $el.dialog('option', {width: '100%', height: ($(window).height() - menuHeight), position: [0, menuHeight]});
511 }
512 e.preventDefault();
513 });
514 }
515 })
516 .on('dialogclose', function(e) {
517 // Restore scrollbars when closing modal
518 if ($('.ui-dialog .modal-dialog').not(e.target).length < 1) {
519 $('body').css({overflow: ''});
520 }
521 })
522 .on('submit', function(e) {
523 // CRM-14353 - disable changes warn when submitting the form
524 $('[data-warn-changes]').removeAttr('data-warn-changes');
525 })
526 ;
527
528 window.onbeforeunload = function() {
529 if (CRM.utils.initialValueChanged($('form[data-warn-changes=true]'))) {
530 return ts('You have unsaved changes.');
531 }
532 };
533
534 /**
535 * Function to make multiselect boxes behave as fields in small screens
536 */
537 function advmultiselectResize() {
538 var amswidth = $("#crm-container form:has(table.advmultiselect)").width();
539 if (amswidth < 700) {
540 $("form table.advmultiselect td").css('display', 'block');
541 }
542 else {
543 $("form table.advmultiselect td").css('display', 'table-cell');
544 }
545 var contactwidth = $('#crm-container #mainTabContainer').width();
546 if (contactwidth < 600) {
547 $('#crm-container #mainTabContainer').addClass('narrowpage');
548 $('#crm-container #mainTabContainer.narrowpage #contactTopBar td').each(function (index) {
549 if (index > 1) {
550 if (index % 2 == 0) {
551 $(this).parent().after('<tr class="narrowadded"></tr>');
552 }
553 var item = $(this);
554 $(this).parent().next().append(item);
555 }
556 });
557 }
558 else {
559 $('#crm-container #mainTabContainer.narrowpage').removeClass('narrowpage');
560 $('#crm-container #mainTabContainer #contactTopBar tr.narrowadded td').each(function () {
561 var nitem = $(this);
562 var parent = $(this).parent();
563 $(this).parent().prev().append(nitem);
564 if (parent.children().size() == 0) {
565 parent.remove();
566 }
567 });
568 $('#crm-container #mainTabContainer.narrowpage #contactTopBar tr.added').detach();
569 }
570 var cformwidth = $('#crm-container #Contact .contact_basic_information-section').width();
571
572 if (cformwidth < 720) {
573 $('#crm-container .contact_basic_information-section').addClass('narrowform');
574 $('#crm-container .contact_basic_information-section table.form-layout-compressed td .helpicon').parent().addClass('hashelpicon');
575 if (cformwidth < 480) {
576 $('#crm-container .contact_basic_information-section').addClass('xnarrowform');
577 }
578 else {
579 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
580 }
581 }
582 else {
583 $('#crm-container .contact_basic_information-section.narrowform').removeClass('narrowform');
584 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
585 }
586 }
587
588 advmultiselectResize();
589 $(window).resize(function () {
590 advmultiselectResize();
591 });
592
593 $.fn.crmtooltip = function () {
594 $(document)
595 .on('mouseover', 'a.crm-summary-link:not(.crm-processed)', function (e) {
596 $(this).addClass('crm-processed');
597 $(this).addClass('crm-tooltip-active');
598 var topDistance = e.pageY - $(window).scrollTop();
599 if (topDistance < 300 | topDistance < $(this).children('.crm-tooltip-wrapper').height()) {
600 $(this).addClass('crm-tooltip-down');
601 }
602 if (!$(this).children('.crm-tooltip-wrapper').length) {
603 $(this).append('<div class="crm-tooltip-wrapper"><div class="crm-tooltip"></div></div>');
604 $(this).children().children('.crm-tooltip')
605 .html('<div class="crm-loading-element"></div>')
606 .load(this.href);
607 }
608 })
609 .on('mouseout', 'a.crm-summary-link', function () {
610 $(this).removeClass('crm-processed');
611 $(this).removeClass('crm-tooltip-active crm-tooltip-down');
612 })
613 .on('click', 'a.crm-summary-link', false);
614 };
615
616 var helpDisplay, helpPrevious;
617 CRM.help = function (title, params, url) {
618 if (helpDisplay && helpDisplay.close) {
619 // If the same link is clicked twice, just close the display - todo use underscore method for this comparison
620 if (helpDisplay.isOpen && helpPrevious === JSON.stringify(params)) {
621 helpDisplay.close();
622 return;
623 }
624 helpDisplay.close();
625 }
626 helpPrevious = JSON.stringify(params);
627 params.class_name = 'CRM_Core_Page_Inline_Help';
628 params.type = 'page';
629 helpDisplay = CRM.alert('...', title, 'crm-help crm-msg-loading', {expires: 0});
630 $.ajax(url || CRM.url('civicrm/ajax/inline'),
631 {
632 data: params,
633 dataType: 'html',
634 success: function (data) {
635 $('#crm-notification-container .crm-help .notify-content:last').html(data);
636 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('info');
637 },
638 error: function () {
639 $('#crm-notification-container .crm-help .notify-content:last').html('Unable to load help file.');
640 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('error');
641 }
642 }
643 );
644 };
645 /**
646 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
647 */
648 CRM.status = function(options, deferred) {
649 // For simple usage without async operations you can pass in a string. 2nd param is optional string 'error' if this is not a success msg.
650 if (typeof options === 'string') {
651 return CRM.status({start: options, success: options, error: options})[deferred === 'error' ? 'reject' : 'resolve']();
652 }
653 var opts = $.extend({
654 start: ts('Saving...'),
655 success: ts('Saved'),
656 error: function() {
657 CRM.alert(ts('Sorry an error occurred and your information was not saved'), ts('Error'));
658 }
659 }, options || {});
660 var $msg = $('<div class="crm-status-box-outer status-start"><div class="crm-status-box-inner"><div class="crm-status-box-msg">' + opts.start + '</div></div></div>')
661 .appendTo('body');
662 $msg.css('min-width', $msg.width());
663 function handle(status, data) {
664 var endMsg = typeof(opts[status]) === 'function' ? opts[status](data) : opts[status];
665 if (endMsg) {
666 $msg.removeClass('status-start').addClass('status-' + status).find('.crm-status-box-msg').html(endMsg);
667 window.setTimeout(function() {
668 $msg.fadeOut('slow', function() {$msg.remove()});
669 }, 2000);
670 } else {
671 $msg.remove();
672 }
673 }
674 return (deferred || new $.Deferred())
675 .done(function(data) {
676 // If the server returns an error msg call the error handler
677 var status = $.isPlainObject(data) && (data.is_error || data.status === 'error') ? 'error' : 'success';
678 handle(status, data);
679 })
680 .fail(function(data) {
681 handle('error', data);
682 });
683 };
684
685 /**
686 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
687 */
688 CRM.alert = function (text, title, type, options) {
689 type = type || 'alert';
690 title = title || '';
691 options = options || {};
692 if ($('#crm-notification-container').length) {
693 var params = {
694 text: text,
695 title: title,
696 type: type
697 };
698 // By default, don't expire errors and messages containing links
699 var extra = {
700 expires: (type == 'error' || text.indexOf('<a ') > -1) ? 0 : (text ? 10000 : 5000),
701 unique: true
702 };
703 options = $.extend(extra, options);
704 options.expires = options.expires === false ? 0 : parseInt(options.expires, 10);
705 if (options.unique && options.unique !== '0') {
706 $('#crm-notification-container .ui-notify-message').each(function () {
707 if (title === $('h1', this).html() && text === $('.notify-content', this).html()) {
708 $('.icon.ui-notify-close', this).click();
709 }
710 });
711 }
712 return $('#crm-notification-container').notify('create', params, options);
713 }
714 else {
715 if (title.length) {
716 text = title + "\n" + text;
717 }
718 alert(text);
719 return null;
720 }
721 };
722
723 /**
724 * Close whichever alert contains the given node
725 *
726 * @param node
727 */
728 CRM.closeAlertByChild = function (node) {
729 $(node).closest('.ui-notify-message').find('.icon.ui-notify-close').click();
730 };
731
732 /**
733 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
734 */
735 CRM.confirm = function (options) {
736 var dialog, settings = {
737 title: ts('Confirm Action'),
738 message: ts('Are you sure you want to continue?'),
739 width: 'auto',
740 modal: true,
741 resizable: false,
742 dialogClass: 'crm-container crm-confirm',
743 close: function () {
744 $(this).dialog('destroy').remove();
745 },
746 options: {
747 no: ts('Cancel'),
748 yes: ts('Continue')
749 }
750 };
751 $.extend(settings, ($.isFunction(options) ? arguments[1] : options) || {});
752 if (!settings.buttons && $.isPlainObject(settings.options)) {
753 settings.buttons = [];
754 $.each(settings.options, function(key, label) {
755 settings.buttons.push({
756 text: label,
757 click: function() {
758 var event = $.Event('crmConfirm:' + key);
759 $(this).trigger(event);
760 if (!event.isDefaultPrevented()) {
761 dialog.dialog('close');
762 }
763 }
764 });
765 });
766 }
767 dialog = $('<div class="crm-confirm-dialog"></div>').html(settings.message);
768 delete settings.options;
769 delete settings.message;
770 if ($.isFunction(options)) {
771 dialog.on('crmConfirm:yes', options);
772 }
773 return dialog.dialog(settings).trigger('crmLoad');
774 };
775
776 /** provides a local copy of ts for a domain */
777 CRM.ts = function(domain) {
778 return function(message, options) {
779 if (domain) {
780 options = $.extend(options || {}, {domain: domain});
781 }
782 return ts(message, options);
783 };
784 };
785
786 /**
787 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
788 */
789 $.fn.crmError = function (text, title, options) {
790 title = title || '';
791 text = text || '';
792 options = options || {};
793
794 var extra = {
795 expires: 0
796 };
797 if ($(this).length) {
798 if (title == '') {
799 var label = $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]').not('[generated=true]');
800 if (label.length) {
801 label.addClass('crm-error');
802 var $label = label.clone();
803 if (text == '' && $('.crm-marker', $label).length > 0) {
804 text = $('.crm-marker', $label).attr('title');
805 }
806 $('.crm-marker', $label).remove();
807 title = $label.text();
808 }
809 }
810 $(this).addClass('error');
811 }
812 var msg = CRM.alert(text, title, 'error', $.extend(extra, options));
813 if ($(this).length) {
814 var ele = $(this);
815 setTimeout(function () {
816 ele.one('change', function () {
817 msg && msg.close && msg.close();
818 ele.removeClass('error');
819 label.removeClass('crm-error');
820 });
821 }, 1000);
822 }
823 return msg;
824 };
825
826 // Display system alerts through js notifications
827 function messagesFromMarkup() {
828 $('div.messages:visible', this).not('.help').not('.no-popup').each(function () {
829 var text, title = '';
830 $(this).removeClass('status messages');
831 var type = $(this).attr('class').split(' ')[0] || 'alert';
832 type = type.replace('crm-', '');
833 $('.icon', this).remove();
834 if ($('.msg-text', this).length > 0) {
835 text = $('.msg-text', this).html();
836 title = $('.msg-title', this).html();
837 }
838 else {
839 text = $(this).html();
840 }
841 var options = $(this).data('options') || {};
842 $(this).remove();
843 // Duplicates were already removed server-side
844 options.unique = false;
845 CRM.alert(text, title, type, options);
846 });
847 // Handle qf form errors
848 $('form :input.error', this).one('blur', function() {
849 $('.ui-notify-message.error a.ui-notify-close').click();
850 $(this).removeClass('error');
851 $(this).next('span.crm-error').remove();
852 $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]')
853 .removeClass('crm-error')
854 .find('.crm-error').removeClass('crm-error');
855 });
856 }
857
858 // Preprocess all cj ajax calls to display messages
859 $(document).ajaxSuccess(function(event, xhr, settings) {
860 try {
861 if ((!settings.dataType || settings.dataType == 'json') && xhr.responseText) {
862 var response = $.parseJSON(xhr.responseText);
863 if (typeof(response.crmMessages) == 'object') {
864 $.each(response.crmMessages, function(n, msg) {
865 CRM.alert(msg.text, msg.title, msg.type, msg.options);
866 })
867 }
868 }
869 }
870 // Suppress errors
871 catch (e) {}
872 });
873
874 $(function () {
875 // Trigger crmLoad on initial content for consistency. It will also be triggered for ajax-loaded content.
876 $('.crm-container').trigger('crmLoad');
877
878 if ($('#crm-notification-container').length) {
879 // Initialize notifications
880 $('#crm-notification-container').notify();
881 messagesFromMarkup.call($('#crm-container'));
882 }
883
884 $('body')
885 // bind the event for image popup
886 .on('click', 'a.crm-image-popup', function(e) {
887 CRM.confirm({
888 title: ts('Preview'),
889 resizable: true,
890 message: '<div class="crm-custom-image-popup"><img src=' + $(this).attr('href') + '></div>',
891 options: null
892 });
893 e.preventDefault();
894 })
895
896 .on('click', function (event) {
897 $('.btn-slide-active').removeClass('btn-slide-active').find('.panel').hide();
898 if ($(event.target).is('.btn-slide')) {
899 $(event.target).addClass('btn-slide-active').find('.panel').show();
900 }
901 })
902
903 // Handle clear button for form elements
904 .on('click', 'a.crm-clear-link', function() {
905 $(this).css({visibility: 'hidden'}).siblings('.crm-form-radio:checked').prop('checked', false).change();
906 $(this).siblings('input:text').val('').change();
907 return false;
908 })
909 .on('change', 'input.crm-form-radio:checked', function() {
910 $(this).siblings('.crm-clear-link').css({visibility: ''});
911 })
912
913 // Allow normal clicking of links within accordions
914 .on('click.crmAccordions', 'div.crm-accordion-header a', function (e) {
915 e.stopPropagation();
916 })
917 // Handle accordions
918 .on('click.crmAccordions', '.crm-accordion-header, .crm-collapsible .collapsible-title', function (e) {
919 if ($(this).parent().hasClass('collapsed')) {
920 $(this).next().css('display', 'none').slideDown(200);
921 }
922 else {
923 $(this).next().css('display', 'block').slideUp(200);
924 }
925 $(this).parent().toggleClass('collapsed');
926 e.preventDefault();
927 });
928
929 $().crmtooltip();
930 });
931 /**
932 * @deprecated
933 */
934 $.fn.crmAccordions = function () {};
935 /**
936 * Collapse or expand an accordion
937 * @param speed
938 */
939 $.fn.crmAccordionToggle = function (speed) {
940 $(this).each(function () {
941 if ($(this).hasClass('collapsed')) {
942 $('.crm-accordion-body', this).first().css('display', 'none').slideDown(speed);
943 }
944 else {
945 $('.crm-accordion-body', this).first().css('display', 'block').slideUp(speed);
946 }
947 $(this).toggleClass('collapsed');
948 });
949 };
950
951 /**
952 * Clientside currency formatting
953 * @param value
954 * @param format - currency representation of the number 1234.56
955 * @return string
956 * @see CRM_Core_Resources::addCoreResources
957 */
958 var currencyTemplate;
959 CRM.formatMoney = function(value, format) {
960 var decimal, separator, sign, i, j, result;
961 if (value === 'init' && format) {
962 currencyTemplate = format;
963 return;
964 }
965 format = format || currencyTemplate;
966 result = /1(.?)234(.?)56/.exec(format);
967 if (result === null) {
968 return 'Invalid format passed to CRM.formatMoney';
969 }
970 separator = result[1];
971 decimal = result[2];
972 sign = (value < 0) ? '-' : '';
973 //extracting the absolute value of the integer part of the number and converting to string
974 i = parseInt(value = Math.abs(value).toFixed(2)) + '';
975 j = ((j = i.length) > 3) ? j % 3 : 0;
976 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) : '');
977 return format.replace(/1.*234.*56/, result);
978 };
979 })(jQuery, _);