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