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