Send `is_default` data as boolean, not rendered icon; add js icon helper
[civicrm-core.git] / js / Common.js
... / ...
CommitLineData
1// https://civicrm.org/licensing
2/* global CRM:true */
3var CRM = CRM || {};
4var cj = CRM.$ = jQuery;
5CRM._ = _;
6
7/**
8 * Short-named function for string translation, defined in global scope so it's available everywhere.
9 *
10 * @param text string for translating
11 * @param params object key:value of additional parameters
12 *
13 * @return string
14 */
15function ts(text, params) {
16 "use strict";
17 var d = (params && params.domain) ? ('strings::' + params.domain) : null;
18 if (d && CRM[d] && CRM[d][text]) {
19 text = CRM[d][text];
20 }
21 else if (CRM.strings[text]) {
22 text = CRM.strings[text];
23 }
24 if (typeof(params) === 'object') {
25 for (var i in params) {
26 if (typeof(params[i]) === 'string' || typeof(params[i]) === 'number') {
27 // sprintf emulation: escape % characters in the replacements to avoid conflicts
28 text = text.replace(new RegExp('%' + i, 'g'), String(params[i]).replace(/%/g, '%-crmescaped-'));
29 }
30 }
31 return text.replace(/%-crmescaped-/g, '%');
32 }
33 return text;
34}
35
36// Legacy code - ignore warnings
37/* jshint ignore:start */
38
39/**
40 * This function is called by default at the bottom of template files which have forms that have
41 * conditionally displayed/hidden sections and elements. The PHP is responsible for generating
42 * a list of 'blocks to show' and 'blocks to hide' and the template passes these parameters to
43 * this function.
44 *
45 * @deprecated
46 * @param showBlocks Array of element Id's to be displayed
47 * @param hideBlocks Array of element Id's to be hidden
48 * @param elementType Value to set display style to for showBlocks (e.g. 'block' or 'table-row' or ...)
49 */
50function on_load_init_blocks(showBlocks, hideBlocks, elementType) {
51 if (elementType == null) {
52 elementType = 'block';
53 }
54
55 var myElement, i;
56
57 /* This loop is used to display the blocks whose IDs are present within the showBlocks array */
58 for (i = 0; i < showBlocks.length; i++) {
59 myElement = document.getElementById(showBlocks[i]);
60 /* getElementById returns null if element id doesn't exist in the document */
61 if (myElement != null) {
62 myElement.style.display = elementType;
63 }
64 else {
65 alert('showBlocks array item not in .tpl = ' + showBlocks[i]);
66 }
67 }
68
69 /* This loop is used to hide the blocks whose IDs are present within the hideBlocks array */
70 for (i = 0; i < hideBlocks.length; i++) {
71 myElement = document.getElementById(hideBlocks[i]);
72 /* getElementById returns null if element id doesn't exist in the document */
73 if (myElement != null) {
74 myElement.style.display = 'none';
75 }
76 else {
77 alert('showBlocks array item not in .tpl = ' + hideBlocks[i]);
78 }
79 }
80}
81
82/**
83 * This function is called when we need to show or hide a related form element (target_element)
84 * based on the value (trigger_value) of another form field (trigger_field).
85 *
86 * @deprecated
87 * @param trigger_field_id HTML id of field whose onchange is the trigger
88 * @param trigger_value List of integers - option value(s) which trigger show-element action for target_field
89 * @param target_element_id HTML id of element to be shown or hidden
90 * @param target_element_type Type of element to be shown or hidden ('block' or 'table-row')
91 * @param field_type Type of element radio/select
92 * @param invert Boolean - if true, we HIDE target on value match; if false, we SHOW target on value match
93 */
94function showHideByValue(trigger_field_id, trigger_value, target_element_id, target_element_type, field_type, invert) {
95 var target, j;
96
97 if (field_type == 'select') {
98 var trigger = trigger_value.split("|");
99 var selectedOptionValue = cj('#' + trigger_field_id).val();
100
101 target = target_element_id.split("|");
102 for (j = 0; j < target.length; j++) {
103 if (invert) {
104 cj('#' + target[j]).show();
105 }
106 else {
107 cj('#' + target[j]).hide();
108 }
109 for (var i = 0; i < trigger.length; i++) {
110 if (selectedOptionValue == trigger[i]) {
111 if (invert) {
112 cj('#' + target[j]).hide();
113 }
114 else {
115 cj('#' + target[j]).show();
116 }
117 }
118 }
119 }
120
121 }
122 else {
123 if (field_type == 'radio') {
124 target = target_element_id.split("|");
125 for (j = 0; j < target.length; j++) {
126 if (cj('[name="' + trigger_field_id + '"]:first').is(':checked')) {
127 if (invert) {
128 cj('#' + target[j]).hide();
129 }
130 else {
131 cj('#' + target[j]).show();
132 }
133 }
134 else {
135 if (invert) {
136 cj('#' + target[j]).show();
137 }
138 else {
139 cj('#' + target[j]).hide();
140 }
141 }
142 }
143 }
144 }
145}
146
147var submitcount = 0;
148/**
149 * Old submit-once function. Will be removed soon.
150 * @deprecated
151 */
152function submitOnce(obj, formId, procText) {
153 // if named button clicked, change text
154 if (obj.value != null) {
155 cj('input[name=' + obj.name + ']').val(procText + " ...");
156 }
157 cj(obj).closest('form').attr('data-warn-changes', 'false');
158 if (document.getElementById) { // disable submit button for newer browsers
159 cj('input[name=' + obj.name + ']').attr("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 */
180function 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/* jshint ignore:end */
197
198if (!CRM.utils) CRM.utils = {};
199if (!CRM.strings) CRM.strings = {};
200if (!CRM.vars) CRM.vars = {};
201
202(function ($, _, undefined) {
203 "use strict";
204 /* jshint validthis: true */
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, .cke_dialog, #civicrm-menu').length;
215 };
216
217 // Implements jQuery hook.prop
218 $.propHooks.disabled = {
219 set: function (el, value, name) {
220 // Sync button enabled status with wrapper css
221 if ($(el).is('span.crm-button > input.crm-form-submit')) {
222 $(el).parent().toggleClass('crm-button-disabled', !!value);
223 }
224 // Sync button enabled status with dialog button
225 if ($(el).is('.ui-dialog input.crm-form-submit')) {
226 $(el).closest('.ui-dialog').find('.ui-dialog-buttonset button[data-identifier='+ $(el).attr('name') +']').prop('disabled', value);
227 }
228 if ($(el).is('.crm-form-date-wrapper .crm-hidden-date')) {
229 $(el).siblings().prop('disabled', value);
230 }
231 }
232 };
233
234 var scriptsLoaded = {};
235 CRM.loadScript = function(url, appendCacheCode) {
236 if (!scriptsLoaded[url]) {
237 var script = document.createElement('script'),
238 src = url;
239 if (appendCacheCode !== false) {
240 src += (_.includes(url, '?') ? '&r=' : '?r=') + CRM.config.resourceCacheCode;
241 }
242 scriptsLoaded[url] = $.Deferred();
243 script.onload = function () {
244 // Give the script time to execute
245 window.setTimeout(function () {
246 if (window.jQuery === CRM.$ && CRM.CMSjQuery) {
247 window.jQuery = CRM.CMSjQuery;
248 }
249 scriptsLoaded[url].resolve();
250 }, 100);
251 };
252 // Make jQuery global available while script is loading
253 if (window.jQuery !== CRM.$) {
254 CRM.CMSjQuery = window.jQuery;
255 window.jQuery = CRM.$;
256 }
257 script.src = src;
258 document.getElementsByTagName("head")[0].appendChild(script);
259 }
260 return scriptsLoaded[url];
261 };
262
263 /**
264 * Populate a select list, overwriting the existing options except for the placeholder.
265 * @param select jquery selector - 1 or more select elements
266 * @param options array in format returned by api.getoptions
267 * @param placeholder string|bool - new placeholder or false (default) to keep the old one
268 * @param value string|array - will silently update the element with new value without triggering change
269 */
270 CRM.utils.setOptions = function(select, options, placeholder, value) {
271 $(select).each(function() {
272 var
273 $elect = $(this),
274 val = value || $elect.val() || [],
275 opts = placeholder || placeholder === '' ? '' : '[value!=""]';
276 $elect.find('option' + opts).remove();
277 var newOptions = CRM.utils.renderOptions(options, val);
278 if (typeof placeholder === 'string') {
279 if ($elect.is('[multiple]')) {
280 select.attr('placeholder', placeholder);
281 } else {
282 newOptions = '<option value="">' + placeholder + '</option>' + newOptions;
283 }
284 }
285 $elect.append(newOptions);
286 if (!value) {
287 $elect.trigger('crmOptionsUpdated', $.extend({}, options)).trigger('change');
288 }
289 });
290 };
291
292 /**
293 * Render an option list
294 * @param options {array}
295 * @param val {string} default value
296 * @param escapeHtml {bool}
297 * @return string
298 */
299 CRM.utils.renderOptions = function(options, val, escapeHtml) {
300 var rendered = '',
301 esc = escapeHtml === false ? _.identity : _.escape;
302 if (!$.isArray(val)) {
303 val = [val];
304 }
305 _.each(options, function(option) {
306 if (option.children) {
307 rendered += '<optgroup label="' + esc(option.value) + '">' +
308 CRM.utils.renderOptions(option.children, val) +
309 '</optgroup>';
310 } else {
311 var selected = ($.inArray('' + option.key, val) > -1) ? 'selected="selected"' : '';
312 rendered += '<option value="' + esc(option.key) + '"' + selected + '>' + esc(option.value) + '</option>';
313 }
314 });
315 return rendered;
316 };
317
318 function chainSelect() {
319 var $form = $(this).closest('form'),
320 $target = $('select[data-name="' + $(this).data('target') + '"]', $form),
321 data = $target.data(),
322 val = $(this).val();
323 $target.prop('disabled', true);
324 if ($target.is('select.crm-chain-select-control')) {
325 $('select[data-name="' + $target.data('target') + '"]', $form).prop('disabled', true).blur();
326 }
327 if (!(val && val.length)) {
328 CRM.utils.setOptions($target.blur(), [], data.emptyPrompt);
329 } else {
330 $target.addClass('loading');
331 $.getJSON(CRM.url(data.callback), {_value: val}, function(vals) {
332 $target.prop('disabled', false).removeClass('loading');
333 CRM.utils.setOptions($target, vals || [], (vals && vals.length ? data.selectPrompt : data.nonePrompt));
334 });
335 }
336 }
337
338 /**
339 * Compare Form Input values against cached initial value.
340 *
341 * @return {Boolean} true if changes have been made.
342 */
343 CRM.utils.initialValueChanged = function(el) {
344 var isDirty = false;
345 $(':input:visible, .select2-container:visible+:input:hidden', el).not('[type=submit], [type=button], .crm-action-menu, :disabled').each(function () {
346 var
347 initialValue = $(this).data('crm-initial-value'),
348 currentValue = $(this).is(':checkbox, :radio') ? $(this).prop('checked') : $(this).val();
349 // skip change of value for submit buttons
350 if (initialValue !== undefined && !_.isEqual(initialValue, currentValue)) {
351 isDirty = true;
352 }
353 });
354 return isDirty;
355 };
356
357 /**
358 * This provides defaults for ui.dialog which either need to be calculated or are different from global defaults
359 *
360 * @param settings
361 * @returns {*}
362 */
363 CRM.utils.adjustDialogDefaults = function(settings) {
364 settings = $.extend({width: '65%', height: '65%', modal: true}, settings || {});
365 // Support relative height
366 if (typeof settings.height === 'string' && settings.height.indexOf('%') > 0) {
367 settings.height = parseInt($(window).height() * (parseFloat(settings.height)/100), 10);
368 }
369 // Responsive adjustment - increase percent width on small screens
370 if (typeof settings.width === 'string' && settings.width.indexOf('%') > 0) {
371 var screenWidth = $(window).width(),
372 percentage = parseInt(settings.width.replace('%', ''), 10),
373 gap = 100-percentage;
374 if (screenWidth < 701) {
375 settings.width = '100%';
376 }
377 else if (screenWidth < 1400) {
378 settings.width = '' + parseInt(percentage+gap-((screenWidth - 700)/7*(gap)/100), 10) + '%';
379 }
380 }
381 return settings;
382 };
383
384 function formatCrmSelect2(row) {
385 var icon = row.icon || $(row.element).data('icon'),
386 color = row.color || $(row.element).data('color'),
387 description = row.description || $(row.element).data('description'),
388 ret = '';
389 if (icon) {
390 ret += '<i class="crm-i ' + icon + '"></i> ';
391 }
392 if (color) {
393 ret += '<span class="crm-select-item-color" style="background-color: ' + color + '"></span> ';
394 }
395 return ret + _.escape(row.text) + (description ? '<div class="crm-select2-row-description"><p>' + _.escape(description) + '</p></div>' : '');
396 }
397
398 /**
399 * Helper to generate an icon with alt text.
400 *
401 * See also smarty `{icon}` and CRM_Core_Page::crmIcon() functions
402 *
403 * @param string icon
404 * The Font Awesome icon class to use.
405 * @param string text
406 * Alt text to display.
407 * @param mixed condition
408 * This will only display if this is truthy.
409 *
410 * @return string
411 * The formatted icon markup.
412 */
413 CRM.utils.formatConditionalIcon = function (icon, text, condition) {
414 if (!condition) {
415 return '';
416 }
417 var title = '';
418 var sr = '';
419 if (text) {
420 title = ' title="' + text + '"';
421 sr = '<span class="sr-only">' + text + '</span>';
422 }
423 return '<i class="crm-i ' + icon + '"' + title + '></i>' + sr;
424 };
425
426 /**
427 * Wrapper for select2 initialization function; supplies defaults
428 * @param options object
429 */
430 $.fn.crmSelect2 = function(options) {
431 if (options === 'destroy') {
432 return $(this).each(function() {
433 $(this)
434 .removeClass('crm-ajax-select')
435 .off('.crmSelect2')
436 .select2('destroy');
437 });
438 }
439 return $(this).each(function () {
440 var
441 $el = $(this),
442 iconClass,
443 settings = {
444 allowClear: !$el.hasClass('required'),
445 formatResult: formatCrmSelect2,
446 formatSelection: formatCrmSelect2
447 };
448 // quickform doesn't support optgroups so here's a hack :(
449 $('option[value^=crm_optgroup]', this).each(function () {
450 $(this).nextUntil('option[value^=crm_optgroup]').wrapAll('<optgroup label="' + $(this).text() + '" />');
451 $(this).remove();
452 });
453
454 // quickform does not support disabled option, so yet another hack to
455 // add disabled property for option values
456 $('option[value^=crm_disabled_opt]', this).attr('disabled', 'disabled');
457
458 // Placeholder icon - total hack hikacking the escapeMarkup function but select2 3.5 dosn't have any other callbacks for this :(
459 if ($el.is('[class*=fa-]')) {
460 settings.escapeMarkup = function (m) {
461 var out = _.escape(m),
462 placeholder = settings.placeholder || $el.data('placeholder') || $el.attr('placeholder') || $('option[value=""]', $el).text();
463 if (m.length && placeholder === m) {
464 iconClass = $el.attr('class').match(/(fa-\S*)/)[1];
465 out = '<i class="crm-i ' + iconClass + '"></i> ' + out;
466 }
467 return out;
468 };
469 }
470
471 // Use description as title for each option
472 $el.on('select2-loaded.crmSelect2', function() {
473 $('.crm-select2-row-description', '#select2-drop').each(function() {
474 $(this).closest('.select2-result-label').attr('title', $(this).text());
475 });
476 });
477
478 // Defaults for single-selects
479 if ($el.is('select:not([multiple])')) {
480 settings.minimumResultsForSearch = 10;
481 if ($('option:first', this).val() === '') {
482 settings.placeholderOption = 'first';
483 }
484 }
485 $.extend(settings, $el.data('select-params') || {}, options || {});
486 if (settings.ajax) {
487 $el.addClass('crm-ajax-select');
488 }
489 $el.select2(settings);
490 });
491 };
492
493 /**
494 * @see CRM_Core_Form::addEntityRef for docs
495 * @param options object
496 */
497 $.fn.crmEntityRef = function(options) {
498 if (options === 'destroy') {
499 return $(this).each(function() {
500 var entity = $(this).data('api-entity') || '';
501 $(this)
502 .off('.crmEntity')
503 .removeClass('crm-form-entityref crm-' + _.kebabCase(entity) + '-ref')
504 .crmSelect2('destroy');
505 });
506 }
507 options = options || {};
508 options.select = options.select || {};
509 return $(this).each(function() {
510 var
511 $el = $(this).off('.crmEntity'),
512 entity = options.entity || $el.data('api-entity') || 'Contact',
513 selectParams = {};
514 // Legacy: fix entity name if passed in as snake case
515 if (entity.charAt(0).toUpperCase() !== entity.charAt(0)) {
516 entity = _.capitalize(_.camelCase(entity));
517 }
518 $el.data('api-entity', entity);
519 $el.data('select-params', $.extend({}, $el.data('select-params') || {}, options.select));
520 $el.data('api-params', $.extend(true, {}, $el.data('api-params') || {}, options.api));
521 $el.data('create-links', options.create || $el.data('create-links'));
522 $el.addClass('crm-form-entityref crm-' + _.kebabCase(entity) + '-ref');
523 var settings = {
524 // Use select2 ajax helper instead of CRM.api3 because it provides more value
525 ajax: {
526 url: CRM.url('civicrm/ajax/rest'),
527 quietMillis: 300,
528 data: function (input, page_num) {
529 var params = getEntityRefApiParams($el);
530 params.input = input;
531 params.page_num = page_num;
532 return {
533 entity: $el.data('api-entity'),
534 action: 'getlist',
535 json: JSON.stringify(params)
536 };
537 },
538 results: function(data) {
539 return {more: data.more_results, results: data.values || []};
540 }
541 },
542 minimumInputLength: 1,
543 formatResult: CRM.utils.formatSelect2Result,
544 formatSelection: formatEntityRefSelection,
545 escapeMarkup: _.identity,
546 initSelection: function($el, callback) {
547 var
548 multiple = !!$el.data('select-params').multiple,
549 val = $el.val(),
550 stored = $el.data('entity-value') || [];
551 if (val === '') {
552 return;
553 }
554 // If we already have this data, just return it
555 if (!_.xor(val.split(','), _.pluck(stored, 'id')).length) {
556 callback(multiple ? stored : stored[0]);
557 } else {
558 var params = $.extend({}, $el.data('api-params') || {}, {id: val});
559 CRM.api3($el.data('api-entity'), 'getlist', params).done(function(result) {
560 callback(multiple ? result.values : result.values[0]);
561 // Trigger change (store data to avoid an infinite loop of lookups)
562 $el.data('entity-value', result.values).trigger('change');
563 });
564 }
565 }
566 };
567 // Create new items inline - works for tags
568 if ($el.data('create-links') && entity === 'Tag') {
569 selectParams.createSearchChoice = function(term, data) {
570 if (!_.findKey(data, {label: term})) {
571 return {id: "0", term: term, label: term + ' (' + ts('new tag') + ')'};
572 }
573 };
574 selectParams.tokenSeparators = [','];
575 selectParams.createSearchChoicePosition = 'bottom';
576 $el.on('select2-selecting.crmEntity', function(e) {
577 if (e.val === "0") {
578 // Create a new term
579 e.object.label = e.object.term;
580 CRM.api3(entity, 'create', $.extend({name: e.object.term}, $el.data('api-params').params || {}))
581 .done(function(created) {
582 var
583 val = $el.select2('val'),
584 data = $el.select2('data'),
585 item = {id: created.id, label: e.object.term};
586 if (val === "0") {
587 $el.select2('data', item, true);
588 }
589 else if ($.isArray(val) && $.inArray("0", val) > -1) {
590 _.remove(data, {id: "0"});
591 data.push(item);
592 $el.select2('data', data, true);
593 }
594 });
595 }
596 });
597 }
598 else {
599 selectParams.formatInputTooShort = function() {
600 var txt = $el.data('select-params').formatInputTooShort || $.fn.select2.defaults.formatInputTooShort.call(this);
601 txt += entityRefFiltersMarkup($el) + renderEntityRefCreateLinks($el);
602 return txt;
603 };
604 selectParams.formatNoMatches = function() {
605 var txt = $el.data('select-params').formatNoMatches || $.fn.select2.defaults.formatNoMatches;
606 txt += entityRefFiltersMarkup($el) + renderEntityRefCreateLinks($el);
607 return txt;
608 };
609 $el.on('select2-open.crmEntity', function() {
610 var $el = $(this);
611 $('#select2-drop')
612 .off('.crmEntity')
613 .on('click.crmEntity', 'a.crm-add-entity', function(e) {
614 var extra = $el.data('api-params').extra,
615 formUrl = $(this).attr('href') + '&returnExtra=display_name,sort_name' + (extra ? (',' + extra) : '');
616 $el.select2('close');
617 CRM.loadForm(formUrl, {
618 dialog: {width: '50%', height: 220}
619 }).on('crmFormSuccess', function(e, data) {
620 if (data.status === 'success' && data.id) {
621 if (!data.crmMessages) {
622 CRM.status(ts('%1 Created', {1: data.label || data.extra.display_name}));
623 }
624 data.label = data.label || data.extra.sort_name;
625 if ($el.select2('container').hasClass('select2-container-multi')) {
626 var selection = $el.select2('data');
627 selection.push(data);
628 $el.select2('data', selection, true);
629 } else {
630 $el.select2('data', data, true);
631 }
632 }
633 });
634 return false;
635 })
636 .on('change.crmEntity', '.crm-entityref-filter-value', function() {
637 var filter = $el.data('user-filter') || {};
638 filter.value = $(this).val();
639 $(this).toggleClass('active', !!filter.value);
640 $el.data('user-filter', filter);
641 if (filter.value && $(this).is('select')) {
642 // Once a filter has been chosen, rerender create links and refocus the search box
643 $el.select2('close');
644 $el.select2('open');
645 } else {
646 $('.crm-entityref-links', '#select2-drop').replaceWith(renderEntityRefCreateLinks($el));
647 }
648 })
649 .on('change.crmEntity', 'select.crm-entityref-filter-key', function() {
650 var filter = {key: $(this).val()};
651 $(this).toggleClass('active', !!filter.key);
652 $el.data('user-filter', filter);
653 renderEntityRefFilterValue($el);
654 $('.crm-entityref-filter-key', '#select2-drop').focus();
655 });
656 });
657 }
658 $el.crmSelect2($.extend(settings, $el.data('select-params'), selectParams));
659 });
660 };
661
662 /**
663 * Combine api-params with user-filter
664 * @param $el
665 * @returns {*}
666 */
667 function getEntityRefApiParams($el) {
668 var
669 params = $.extend({params: {}}, $el.data('api-params') || {}),
670 // Prevent original data from being modified - $.extend and _.clone don't cut it, they pass nested objects by reference!
671 combined = _.cloneDeep(params),
672 filter = $.extend({}, $el.data('user-filter') || {});
673 if (filter.key && filter.value) {
674 // Fieldname may be prefixed with joins
675 var fieldName = _.last(filter.key.split('.'));
676 // Special case for contact type/sub-type combo
677 if (fieldName === 'contact_type' && (filter.value.indexOf('__') > 0)) {
678 combined.params[filter.key] = filter.value.split('__')[0];
679 combined.params[filter.key.replace('contact_type', 'contact_sub_type')] = filter.value.split('__')[1];
680 } else {
681 // Allow json-encoded api filters e.g. {"BETWEEN":[123,456]}
682 combined.params[filter.key] = filter.value.charAt(0) === '{' ? $.parseJSON(filter.value) : filter.value;
683 }
684 }
685 return combined;
686 }
687
688 CRM.utils.copyAttributes = function ($source, $target, attributes) {
689 _.each(attributes, function(name) {
690 if ($source.attr(name) !== undefined) {
691 $target.attr(name, $source.attr(name));
692 }
693 });
694 };
695
696 CRM.utils.formatSelect2Result = function (row) {
697 var markup = '<div class="crm-select2-row">';
698 if (row.image !== undefined) {
699 markup += '<div class="crm-select2-image"><img src="' + row.image + '"/></div>';
700 }
701 else if (row.icon_class) {
702 markup += '<div class="crm-select2-icon"><div class="crm-icon ' + row.icon_class + '-icon"></div></div>';
703 }
704 markup += '<div><div class="crm-select2-row-label '+(row.label_class || '')+'">' +
705 (row.color ? '<span class="crm-select-item-color" style="background-color: ' + row.color + '"></span> ' : '') +
706 _.escape((row.prefix !== undefined ? row.prefix + ' ' : '') + row.label + (row.suffix !== undefined ? ' ' + row.suffix : '')) +
707 '</div>' +
708 '<div class="crm-select2-row-description">';
709 $.each(row.description || [], function(k, text) {
710 markup += '<p>' + _.escape(text) + '</p> ';
711 });
712 markup += '</div></div></div>';
713 return markup;
714 };
715
716 function formatEntityRefSelection(row) {
717 return (row.color ? '<span class="crm-select-item-color" style="background-color: ' + row.color + '"></span> ' : '') +
718 _.escape((row.prefix !== undefined ? row.prefix + ' ' : '') + row.label + (row.suffix !== undefined ? ' ' + row.suffix : ''));
719 }
720
721 function renderEntityRefCreateLinks($el) {
722 var
723 createLinks = $el.data('create-links'),
724 params = getEntityRefApiParams($el).params,
725 entity = $el.data('api-entity'),
726 markup = '<div class="crm-entityref-links">';
727 if (!createLinks || (createLinks === true && !CRM.config.entityRef.links[entity])) {
728 return '';
729 }
730 if (createLinks === true) {
731 createLinks = params.contact_type ? _.where(CRM.config.entityRef.links[entity], {type: params.contact_type}) : CRM.config.entityRef.links[entity];
732 }
733 _.each(createLinks, function(link) {
734 markup += ' <a class="crm-add-entity crm-hover-button" href="' + link.url + '">' +
735 '<i class="crm-i ' + (link.icon || 'fa-plus-circle') + '"></i> ' +
736 _.escape(link.label) + '</a>';
737 });
738 markup += '</div>';
739 return markup;
740 }
741
742 function getEntityRefFilters($el) {
743 var
744 entity = $el.data('api-entity'),
745 filters = CRM.config.entityRef.filters[entity] || [],
746 params = $.extend({params: {}}, $el.data('api-params') || {}).params,
747 result = [];
748 _.each(filters, function(filter) {
749 _.defaults(filter, {type: 'select', 'attributes': {}, entity: entity});
750 if (!params[filter.key]) {
751 // Filter out options if params don't match its condition
752 if (filter.condition && !_.isMatch(params, _.pick(filter.condition, _.keys(params)))) {
753 return;
754 }
755 result.push(filter);
756 }
757 else if (filter.key == 'contact_type' && typeof params.contact_sub_type === 'undefined') {
758 result.push(filter);
759 }
760 });
761 return result;
762 }
763
764 /**
765 * Provide markup for entity ref filters
766 */
767 function entityRefFiltersMarkup($el) {
768 var
769 filters = getEntityRefFilters($el),
770 filter = $el.data('user-filter') || {},
771 filterSpec = filter.key ? _.find(filters, {key: filter.key}) : null;
772 if (!filters.length) {
773 return '';
774 }
775 var markup = '<div class="crm-entityref-filters">' +
776 '<select class="crm-entityref-filter-key' + (filter.key ? ' active' : '') + '">' +
777 '<option value="">' + _.escape(ts('Refine search...')) + '</option>' +
778 CRM.utils.renderOptions(filters, filter.key) +
779 '</select>' + entityRefFilterValueMarkup($el, filter, filterSpec) + '</div>';
780 return markup;
781 }
782
783 /**
784 * Provide markup for entity ref filter value field
785 */
786 function entityRefFilterValueMarkup($el, filter, filterSpec) {
787 var markup = '';
788 if (filterSpec) {
789 var attrs = '',
790 attributes = _.cloneDeep(filterSpec.attributes);
791 if (filterSpec.type !== 'select') {
792 attributes.type = filterSpec.type;
793 attributes.value = typeof filter.value !== 'undefined' ? filter.value : '';
794 }
795 attributes.class = 'crm-entityref-filter-value' + (filter.value ? ' active' : '');
796 $.each(attributes, function (attr, val) {
797 attrs += ' ' + attr + '="' + val + '"';
798 });
799 if (filterSpec.type === 'select') {
800 var fieldName = _.last(filter.key.split('.')),
801 options = [{key: '', value: ts('- select -')}];
802 if (filterSpec.options) {
803 options = options.concat(getEntityRefFilterOptions(fieldName, $el, filterSpec));
804 }
805 markup = '<select' + attrs + '>' + CRM.utils.renderOptions(options, filter.value) + '</select>';
806 } else {
807 markup = '<input' + attrs + '/>';
808 }
809 }
810 return markup;
811 }
812
813 /**
814 * Render the entity ref filter value field
815 */
816 function renderEntityRefFilterValue($el) {
817 var
818 filter = $el.data('user-filter') || {},
819 filterSpec = filter.key ? _.find(getEntityRefFilters($el), {key: filter.key}) : null,
820 $keyField = $('.crm-entityref-filter-key', '#select2-drop'),
821 $valField = null;
822 if (filterSpec) {
823 $('.crm-entityref-filter-value', '#select2-drop').remove();
824 $valField = $(entityRefFilterValueMarkup($el, filter, filterSpec));
825 $keyField.after($valField);
826 if (filterSpec.type === 'select') {
827 loadEntityRefFilterOptions(filter, filterSpec, $valField, $el);
828 }
829 } else {
830 $('.crm-entityref-filter-value', '#select2-drop').hide().val('').change();
831 }
832 }
833
834 /**
835 * Fetch options for a filter from cache or ajax api
836 */
837 function loadEntityRefFilterOptions(filter, filterSpec, $valField, $el) {
838 // Fieldname may be prefixed with joins - strip those out
839 var fieldName = _.last(filter.key.split('.'));
840 if (filterSpec.options) {
841 CRM.utils.setOptions($valField, getEntityRefFilterOptions(fieldName, $el, filterSpec), false, filter.value);
842 return;
843 }
844 $('.crm-entityref-filters select', '#select2-drop').prop('disabled', true);
845 CRM.api3(filterSpec.entity, 'getoptions', {field: fieldName, context: 'search', sequential: 1})
846 .done(function(result) {
847 var entity = $el.data('api-entity').toLowerCase();
848 // Store options globally so we don't have to look them up again
849 filterSpec.options = result.values;
850 $('.crm-entityref-filters select', '#select2-drop').prop('disabled', false);
851 CRM.utils.setOptions($valField, getEntityRefFilterOptions(fieldName, $el, filterSpec), false, filter.value);
852 });
853 }
854
855 function getEntityRefFilterOptions(fieldName, $el, filterSpec) {
856 var values = _.cloneDeep(filterSpec.options),
857 params = $.extend({params: {}}, $el.data('api-params') || {}).params;
858 if (fieldName === 'contact_type' && params.contact_type) {
859 values = _.remove(values, function(option) {
860 return option.key.indexOf(params.contact_type + '__') === 0;
861 });
862 }
863 return values;
864 }
865
866 //CRM-15598 - Override url validator method to allow relative url's (e.g. /index.htm)
867 $.validator.addMethod("url", function(value, element) {
868 if (/^\//.test(value)) {
869 // Relative url: prepend dummy path for validation.
870 value = 'http://domain.tld' + value;
871 }
872 // From jQuery Validation Plugin v1.12.0
873 return this.optional(element) || /^(https?|s?ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value);
874 });
875
876 /**
877 * Wrapper for jQuery validate initialization function; supplies defaults
878 */
879 $.fn.crmValidate = function(params) {
880 return $(this).each(function () {
881 var that = this,
882 settings = $.extend({}, CRM.validate._defaults, CRM.validate.params);
883 $(this).validate(settings);
884 // Call any post-initialization callbacks
885 if (CRM.validate.functions && CRM.validate.functions.length) {
886 $.each(CRM.validate.functions, function(i, func) {
887 func.call(that);
888 });
889 }
890 });
891 };
892
893 // Submit-once
894 var submitted = [],
895 submitButton;
896 function submitOnceForm(e) {
897 if (e.isDefaultPrevented()) {
898 return;
899 }
900 if (_.contains(submitted, e.target)) {
901 return false;
902 }
903 submitted.push(e.target);
904 // Spin submit button icon
905 if (submitButton && $(submitButton, e.target).length) {
906 // Dialog button
907 if ($(e.target).closest('.ui-dialog .crm-ajax-container')) {
908 var identifier = $(submitButton).attr('name') || $(submitButton).attr('href');
909 if (identifier) {
910 submitButton = $(e.target).closest('.ui-dialog').find('button[data-identifier="' + identifier + '"]')[0] || submitButton;
911 }
912 }
913 var $icon = $(submitButton).siblings('.crm-i').add('.crm-i, .ui-icon', submitButton);
914 $icon.data('origClass', $icon.attr('class')).removeClass().addClass('crm-i crm-submit-icon fa-spinner fa-pulse');
915 }
916 }
917
918 // If form fails validation, restore button icon and reset the submitted array
919 function submitFormInvalid(form) {
920 submitted = [];
921 $('.crm-i.crm-submit-icon').each(function() {
922 if ($(this).data('origClass')) {
923 $(this).removeClass().addClass($(this).data('origClass'));
924 }
925 });
926 }
927
928 // Initialize widgets
929 $(document)
930 .on('crmLoad', function(e) {
931 $('table.row-highlight', e.target)
932 .off('.rowHighlight')
933 .on('change.rowHighlight', 'input.select-row, input.select-rows', function (e, data) {
934 var filter, $table = $(this).closest('table');
935 if ($(this).hasClass('select-rows')) {
936 filter = $(this).prop('checked') ? ':not(:checked)' : ':checked';
937 $('input.select-row' + filter, $table).prop('checked', $(this).prop('checked')).trigger('change', 'master-selected');
938 }
939 else {
940 $(this).closest('tr').toggleClass('crm-row-selected', $(this).prop('checked'));
941 if (data !== 'master-selected') {
942 $('input.select-rows', $table).prop('checked', $(".select-row:not(':checked')", $table).length < 1);
943 }
944 }
945 })
946 .find('input.select-row:checked').parents('tr').addClass('crm-row-selected');
947 $('.crm-sortable-list', e.target).sortable();
948 $('table.crm-sortable', e.target).DataTable();
949 $('table.crm-ajax-table', e.target).each(function() {
950 var
951 $table = $(this),
952 script = CRM.config.resourceBase + 'js/jquery/jquery.crmAjaxTable.js',
953 $accordion = $table.closest('.crm-accordion-wrapper.collapsed, .crm-collapsible.collapsed');
954 // For tables hidden by collapsed accordions, wait.
955 if ($accordion.length) {
956 $accordion.one('crmAccordion:open', function() {
957 CRM.loadScript(script).done(function() {
958 $table.crmAjaxTable();
959 });
960 });
961 } else {
962 CRM.loadScript(script).done(function() {
963 $table.crmAjaxTable();
964 });
965 }
966 });
967 if ($("input:radio[name=radio_ts]").size() == 1) {
968 $("input:radio[name=radio_ts]").prop("checked", true);
969 }
970 $('.crm-select2:not(.select2-offscreen, .select2-container)', e.target).crmSelect2();
971 $('.crm-form-entityref:not(.select2-offscreen, .select2-container)', e.target).crmEntityRef();
972 $('select.crm-chain-select-control', e.target).off('.chainSelect').on('change.chainSelect', chainSelect);
973 $('.crm-form-text[data-crm-datepicker]', e.target).each(function() {
974 $(this).crmDatepicker($(this).data('crmDatepicker'));
975 });
976 $('.crm-editable', e.target).not('thead *').each(function() {
977 var $el = $(this);
978 CRM.loadScript(CRM.config.resourceBase + 'js/jquery/jquery.crmEditable.js').done(function() {
979 $el.crmEditable();
980 });
981 });
982 // Cache Form Input initial values
983 $('form[data-warn-changes] :input', e.target).each(function() {
984 $(this).data('crm-initial-value', $(this).is(':checkbox, :radio') ? $(this).prop('checked') : $(this).val());
985 });
986 $('textarea.crm-form-wysiwyg', e.target).each(function() {
987 if ($(this).hasClass("collapsed")) {
988 CRM.wysiwyg.createCollapsed(this);
989 } else {
990 CRM.wysiwyg.create(this);
991 }
992 });
993 // Submit once handlers
994 $('form[data-submit-once]', e.target)
995 .submit(submitOnceForm)
996 .on('invalid-form', submitFormInvalid);
997 $('form[data-submit-once] input[type=submit]', e.target).click(function(e) {
998 submitButton = e.target;
999 });
1000 })
1001 .on('dialogopen', function(e) {
1002 var $el = $(e.target);
1003 $('body').addClass('ui-dialog-open');
1004 // Modal dialogs should disable scrollbars
1005 if ($el.dialog('option', 'modal')) {
1006 $el.addClass('modal-dialog');
1007 $('body').css({overflow: 'hidden'});
1008 }
1009 $el.parent().find('.ui-dialog-titlebar .ui-icon-closethick').removeClass('ui-icon-closethick').addClass('fa-times');
1010 // Add resize button
1011 if ($el.parent().hasClass('crm-container') && $el.dialog('option', 'resizable')) {
1012 $el.parent().find('.ui-dialog-titlebar').append($('<button class="crm-dialog-titlebar-resize ui-dialog-titlebar-close" title="'+ _.escape(ts('Toggle fullscreen'))+'" style="right:2em;"/>').button({icons: {primary: 'fa-expand'}, text: false}));
1013 $('.crm-dialog-titlebar-resize', $el.parent()).click(function(e) {
1014 if ($el.data('origSize')) {
1015 $el.dialog('option', $el.data('origSize'));
1016 $el.data('origSize', null);
1017 $(this).button('option', 'icons', {primary: 'fa-expand'});
1018 } else {
1019 var menuHeight = $('#civicrm-menu').outerHeight();
1020 if ($('body').hasClass('crm-menubar-below-cms-menu')) {
1021 menuHeight += $('#civicrm-menu').offset().top;
1022 }
1023 $el.data('origSize', {
1024 position: {my: 'center', at: 'center center+' + (menuHeight / 2), of: window},
1025 width: $el.dialog('option', 'width'),
1026 height: $el.dialog('option', 'height')
1027 });
1028 $el.dialog('option', {width: '100%', height: ($(window).height() - menuHeight), position: {my: "top", at: "top+"+menuHeight, of: window}});
1029 $(this).button('option', 'icons', {primary: 'fa-compress'});
1030 }
1031 $el.trigger('dialogresize');
1032 e.preventDefault();
1033 });
1034 }
1035 })
1036 .on('dialogclose', function(e) {
1037 // Restore scrollbars when closing modal
1038 if ($('.ui-dialog .modal-dialog:visible').not(e.target).length < 1) {
1039 $('body').css({overflow: ''});
1040 }
1041 if ($('.ui-dialog-content:visible').not(e.target).length < 1) {
1042 $('body').removeClass('ui-dialog-open');
1043 }
1044 })
1045 .on('submit', function(e) {
1046 // CRM-14353 - disable changes warn when submitting a form
1047 $('[data-warn-changes]').attr('data-warn-changes', 'false');
1048 });
1049
1050 // CRM-14353 - Warn of unsaved changes for forms which have opted in
1051 window.onbeforeunload = function() {
1052 if (CRM.utils.initialValueChanged($('form[data-warn-changes=true]:visible'))) {
1053 return ts('You have unsaved changes.');
1054 }
1055 };
1056
1057 $.fn.crmtooltip = function () {
1058 $(document)
1059 .on('mouseover', 'a.crm-summary-link:not(.crm-processed)', function (e) {
1060 $(this).addClass('crm-processed crm-tooltip-active');
1061 var topDistance = e.pageY - $(window).scrollTop();
1062 if (topDistance < 300 || topDistance < $(this).children('.crm-tooltip-wrapper').height()) {
1063 $(this).addClass('crm-tooltip-down');
1064 }
1065 if (!$(this).children('.crm-tooltip-wrapper').length) {
1066 $(this).append('<div class="crm-tooltip-wrapper"><div class="crm-tooltip"></div></div>');
1067 $(this).children().children('.crm-tooltip')
1068 .html('<div class="crm-loading-element"></div>')
1069 .load(this.href);
1070 }
1071 })
1072 .on('mouseout', 'a.crm-summary-link', function () {
1073 $(this).removeClass('crm-processed crm-tooltip-active crm-tooltip-down');
1074 })
1075 .on('click', 'a.crm-summary-link', false);
1076 };
1077
1078 var helpDisplay, helpPrevious;
1079 // Non-ajax example:
1080 // CRM.help('Example title', 'Here is some text to describe this example');
1081 // Ajax example (will load help id "foo" from templates/CRM/bar.tpl):
1082 // CRM.help('Example title', {id: 'foo', file: 'CRM/bar'});
1083 CRM.help = function (title, params, url) {
1084 var ajax = typeof params !== 'string';
1085 if (helpDisplay && helpDisplay.close) {
1086 // If the same link is clicked twice, just close the display
1087 if (helpDisplay.isOpen && _.isEqual(helpPrevious, params)) {
1088 helpDisplay.close();
1089 return;
1090 }
1091 helpDisplay.close();
1092 }
1093 helpPrevious = _.cloneDeep(params);
1094 helpDisplay = CRM.alert(ajax ? '...' : params, title, 'crm-help ' + (ajax ? 'crm-msg-loading' : 'info'), {expires: 0});
1095 if (ajax) {
1096 if (!url) {
1097 url = CRM.url('civicrm/ajax/inline');
1098 params.class_name = 'CRM_Core_Page_Inline_Help';
1099 params.type = 'page';
1100 }
1101 $.ajax(url, {
1102 data: params,
1103 dataType: 'html',
1104 success: function (data) {
1105 $('#crm-notification-container .crm-help .notify-content:last').html(data);
1106 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('info');
1107 },
1108 error: function () {
1109 $('#crm-notification-container .crm-help .notify-content:last').html('Unable to load help file.');
1110 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('error');
1111 }
1112 });
1113 }
1114 };
1115 /**
1116 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
1117 */
1118 CRM.status = function(options, deferred) {
1119 // 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.
1120 if (typeof options === 'string') {
1121 return CRM.status({start: options, success: options, error: options})[deferred === 'error' ? 'reject' : 'resolve']();
1122 }
1123 var opts = $.extend({
1124 start: ts('Saving...'),
1125 success: ts('Saved'),
1126 error: function(data) {
1127 var msg = $.isPlainObject(data) && data.error_message;
1128 CRM.alert(msg || ts('Sorry an error occurred and your information was not saved'), ts('Error'), 'error');
1129 }
1130 }, options || {});
1131 var $msg = $('<div class="crm-status-box-outer status-start"><div class="crm-status-box-inner"><div class="crm-status-box-msg">' + _.escape(opts.start) + '</div></div></div>')
1132 .appendTo('body');
1133 $msg.css('min-width', $msg.width());
1134 function handle(status, data) {
1135 var endMsg = typeof(opts[status]) === 'function' ? opts[status](data) : opts[status];
1136 if (endMsg) {
1137 $msg.removeClass('status-start').addClass('status-' + status).find('.crm-status-box-msg').text(endMsg);
1138 window.setTimeout(function() {
1139 $msg.fadeOut('slow', function() {
1140 $msg.remove();
1141 });
1142 }, 2000);
1143 } else {
1144 $msg.remove();
1145 }
1146 }
1147 return (deferred || new $.Deferred())
1148 .done(function(data) {
1149 // If the server returns an error msg call the error handler
1150 var status = $.isPlainObject(data) && (data.is_error || data.status === 'error') ? 'error' : 'success';
1151 handle(status, data);
1152 })
1153 .fail(function(data) {
1154 handle('error', data);
1155 });
1156 };
1157
1158 // Convert an Angular promise to a jQuery promise
1159 CRM.toJqPromise = function(aPromise) {
1160 var jqDeferred = $.Deferred();
1161 aPromise.then(
1162 function(data) { jqDeferred.resolve(data); },
1163 function(data) { jqDeferred.reject(data); }
1164 // should we also handle progress events?
1165 );
1166 return jqDeferred.promise();
1167 };
1168
1169 CRM.toAPromise = function($q, jqPromise) {
1170 var aDeferred = $q.defer();
1171 jqPromise.then(
1172 function(data) { aDeferred.resolve(data); },
1173 function(data) { aDeferred.reject(data); }
1174 // should we also handle progress events?
1175 );
1176 return aDeferred.promise;
1177 };
1178
1179 /**
1180 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
1181 */
1182 CRM.alert = function (text, title, type, options) {
1183 type = type || 'alert';
1184 title = title || '';
1185 options = options || {};
1186 if ($('#crm-notification-container').length) {
1187 var params = {
1188 text: text,
1189 title: title,
1190 type: type
1191 };
1192 // By default, don't expire errors and messages containing links
1193 var extra = {
1194 expires: (type == 'error' || text.indexOf('<a ') > -1) ? 0 : (text ? 10000 : 5000),
1195 unique: true
1196 };
1197 options = $.extend(extra, options);
1198 options.expires = (options.expires === false || !CRM.config.allowAlertAutodismissal) ? 0 : parseInt(options.expires, 10);
1199 if (options.unique && options.unique !== '0') {
1200 $('#crm-notification-container .ui-notify-message').each(function () {
1201 if (title === $('h1', this).html() && text === $('.notify-content', this).html()) {
1202 $('.icon.ui-notify-close', this).click();
1203 }
1204 });
1205 }
1206 return $('#crm-notification-container').notify('create', params, options);
1207 }
1208 else {
1209 if (title.length) {
1210 text = title + "\n" + text;
1211 }
1212 // strip html tags as they are not parsed in standard alerts
1213 alert($("<div/>").html(text).text());
1214 return null;
1215 }
1216 };
1217
1218 /**
1219 * Close whichever alert contains the given node
1220 *
1221 * @param node
1222 */
1223 CRM.closeAlertByChild = function (node) {
1224 $(node).closest('.ui-notify-message').find('.icon.ui-notify-close').click();
1225 };
1226
1227 /**
1228 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
1229 */
1230 CRM.confirm = function (options) {
1231 var dialog, url, msg, buttons = [], settings = {
1232 title: ts('Confirm'),
1233 message: ts('Are you sure you want to continue?'),
1234 url: null,
1235 width: 'auto',
1236 height: 'auto',
1237 resizable: false,
1238 dialogClass: 'crm-container crm-confirm',
1239 close: function () {
1240 $(this).dialog('destroy').remove();
1241 },
1242 options: {
1243 no: ts('Cancel'),
1244 yes: ts('Continue')
1245 }
1246 };
1247 if (options && options.url) {
1248 settings.resizable = true;
1249 settings.height = '50%';
1250 }
1251 $.extend(settings, ($.isFunction(options) ? arguments[1] : options) || {});
1252 settings = CRM.utils.adjustDialogDefaults(settings);
1253 if (!settings.buttons && $.isPlainObject(settings.options)) {
1254 $.each(settings.options, function(op, label) {
1255 buttons.push({
1256 text: label,
1257 'data-op': op,
1258 icons: {primary: op === 'no' ? 'fa-times' : 'fa-check'},
1259 click: function() {
1260 var event = $.Event('crmConfirm:' + op);
1261 $(this).trigger(event);
1262 if (!event.isDefaultPrevented()) {
1263 dialog.dialog('close');
1264 }
1265 }
1266 });
1267 });
1268 // Order buttons so that "no" goes on the right-hand side
1269 settings.buttons = _.sortBy(buttons, 'data-op').reverse();
1270 }
1271 url = settings.url;
1272 msg = url ? '' : settings.message;
1273 delete settings.options;
1274 delete settings.message;
1275 delete settings.url;
1276 dialog = $('<div class="crm-confirm-dialog"></div>').html(msg || '').dialog(settings);
1277 if ($.isFunction(options)) {
1278 dialog.on('crmConfirm:yes', options);
1279 }
1280 if (url) {
1281 CRM.loadPage(url, {target: dialog});
1282 }
1283 else {
1284 dialog.trigger('crmLoad');
1285 }
1286 return dialog;
1287 };
1288
1289 /** provides a local copy of ts for a domain */
1290 CRM.ts = function(domain) {
1291 return function(message, options) {
1292 if (domain) {
1293 options = $.extend(options || {}, {domain: domain});
1294 }
1295 return ts(message, options);
1296 };
1297 };
1298
1299 CRM.addStrings = function(domain, strings) {
1300 var bucket = (domain == 'civicrm' ? 'strings' : 'strings::' + domain);
1301 CRM[bucket] = CRM[bucket] || {};
1302 _.extend(CRM[bucket], strings);
1303 };
1304
1305 /**
1306 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
1307 */
1308 $.fn.crmError = function (text, title, options) {
1309 title = title || '';
1310 text = text || '';
1311 options = options || {};
1312
1313 var extra = {
1314 expires: 0
1315 };
1316 if ($(this).length) {
1317 if (title === '') {
1318 var label = $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]').not('[generated=true]');
1319 if (label.length) {
1320 label.addClass('crm-error');
1321 var $label = label.clone();
1322 if (text === '' && $('.crm-marker', $label).length > 0) {
1323 text = $('.crm-marker', $label).attr('title');
1324 }
1325 $('.crm-marker', $label).remove();
1326 title = $label.text();
1327 }
1328 }
1329 $(this).addClass('crm-error');
1330 }
1331 var msg = CRM.alert(text, title, 'error', $.extend(extra, options));
1332 if ($(this).length) {
1333 var ele = $(this);
1334 setTimeout(function () {
1335 ele.one('change', function () {
1336 if (msg && msg.close) msg.close();
1337 ele.removeClass('error');
1338 label.removeClass('crm-error');
1339 });
1340 }, 1000);
1341 }
1342 return msg;
1343 };
1344
1345 // Display system alerts through js notifications
1346 function messagesFromMarkup() {
1347 $('div.messages:visible', this).not('.help').not('.no-popup').each(function () {
1348 var text, title = '';
1349 $(this).removeClass('status messages');
1350 var type = $(this).attr('class').split(' ')[0] || 'alert';
1351 type = type.replace('crm-', '');
1352 $('.icon', this).remove();
1353 if ($('.msg-text', this).length > 0) {
1354 text = $('.msg-text', this).html();
1355 title = $('.msg-title', this).html();
1356 }
1357 else {
1358 text = $(this).html();
1359 }
1360 var options = $(this).data('options') || {};
1361 $(this).remove();
1362 // Duplicates were already removed server-side
1363 options.unique = false;
1364 CRM.alert(text, title, type, options);
1365 });
1366 // Handle qf form errors
1367 $('form :input.error', this).one('blur', function() {
1368 $('.ui-notify-message.error a.ui-notify-close').click();
1369 $(this).removeClass('error');
1370 $(this).next('span.crm-error').remove();
1371 $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]')
1372 .removeClass('crm-error')
1373 .find('.crm-error').removeClass('crm-error');
1374 });
1375 }
1376
1377 /**
1378 * Improve blockUI when used with jQuery dialog
1379 */
1380 var originalBlock = $.fn.block,
1381 originalUnblock = $.fn.unblock;
1382
1383 $.fn.block = function(opts) {
1384 if ($(this).is('.ui-dialog-content')) {
1385 originalBlock.call($(this).parents('.ui-dialog'), opts);
1386 return $(this);
1387 }
1388 return originalBlock.call(this, opts);
1389 };
1390 $.fn.unblock = function(opts) {
1391 if ($(this).is('.ui-dialog-content')) {
1392 originalUnblock.call($(this).parents('.ui-dialog'), opts);
1393 return $(this);
1394 }
1395 return originalUnblock.call(this, opts);
1396 };
1397
1398 // Preprocess all CRM ajax calls to display messages
1399 $(document).ajaxSuccess(function(event, xhr, settings) {
1400 try {
1401 if ((!settings.dataType || settings.dataType == 'json') && xhr.responseText) {
1402 var response = $.parseJSON(xhr.responseText);
1403 if (typeof(response.crmMessages) == 'object') {
1404 $.each(response.crmMessages, function(n, msg) {
1405 CRM.alert(msg.text, msg.title, msg.type, msg.options);
1406 });
1407 }
1408 if (response.backtrace) {
1409 CRM.console('log', response.backtrace);
1410 }
1411 if (typeof response.deprecated === 'string') {
1412 CRM.console('warn', response.deprecated);
1413 }
1414 }
1415 }
1416 // Ignore errors thrown by parseJSON
1417 catch (e) {}
1418 });
1419
1420 $(function () {
1421 $.blockUI.defaults.message = null;
1422 $.blockUI.defaults.ignoreIfBlocked = true;
1423
1424 if ($('#crm-container').hasClass('crm-public')) {
1425 $.fn.select2.defaults.dropdownCssClass = $.ui.dialog.prototype.options.dialogClass = 'crm-container crm-public';
1426 }
1427
1428 // Trigger crmLoad on initial content for consistency. It will also be triggered for ajax-loaded content.
1429 $('.crm-container').trigger('crmLoad');
1430
1431 if ($('#crm-notification-container').length) {
1432 // Initialize notifications
1433 $('#crm-notification-container').notify();
1434 messagesFromMarkup.call($('#crm-container'));
1435 }
1436
1437 $('body')
1438 // bind the event for image popup
1439 .on('click', 'a.crm-image-popup', function(e) {
1440 CRM.confirm({
1441 title: ts('Preview'),
1442 resizable: true,
1443 // Prevent overlap with the menubar
1444 maxHeight: $(window).height() - 30,
1445 position: {my: 'center', at: 'center center+15', of: window},
1446 message: '<div class="crm-custom-image-popup"><img style="max-width: 100%" src="' + $(this).attr('href') + '"></div>',
1447 options: null
1448 });
1449 e.preventDefault();
1450 })
1451
1452 .on('click', function (event) {
1453 $('.btn-slide-active').removeClass('btn-slide-active').find('.panel').hide();
1454 if ($(event.target).is('.btn-slide')) {
1455 $(event.target).addClass('btn-slide-active').find('.panel').show();
1456 }
1457 })
1458
1459 // Handle clear button for form elements
1460 .on('click', 'a.crm-clear-link', function() {
1461 $(this).css({visibility: 'hidden'}).siblings('.crm-form-radio:checked').prop('checked', false).trigger('change', ['crmClear']);
1462 $(this).siblings('input:text').val('').trigger('change', ['crmClear']);
1463 return false;
1464 })
1465 .on('change keyup', 'input.crm-form-radio:checked, input[allowclear=1]', function(e, context) {
1466 if (context !== 'crmClear' && ($(this).is(':checked') || ($(this).is('[allowclear=1]') && $(this).val()))) {
1467 $(this).siblings('.crm-clear-link').css({visibility: ''});
1468 }
1469 if (context !== 'crmClear' && $(this).is('[allowclear=1]') && $(this).val() === '') {
1470 $(this).siblings('.crm-clear-link').css({visibility: 'hidden'});
1471 }
1472 })
1473
1474 // Allow normal clicking of links within accordions
1475 .on('click.crmAccordions', 'div.crm-accordion-header a, .collapsible-title a', function (e) {
1476 e.stopPropagation();
1477 })
1478 // Handle accordions
1479 .on('click.crmAccordions', '.crm-accordion-header, .crm-collapsible .collapsible-title', function (e) {
1480 var action = 'open';
1481 if ($(this).parent().hasClass('collapsed')) {
1482 $(this).next().css('display', 'none').slideDown(200);
1483 }
1484 else {
1485 $(this).next().css('display', 'block').slideUp(200);
1486 action = 'close';
1487 }
1488 $(this).parent().toggleClass('collapsed').trigger('crmAccordion:' + action);
1489 e.preventDefault();
1490 });
1491
1492 $().crmtooltip();
1493 });
1494
1495 /**
1496 * Collapse or expand an accordion
1497 * @param speed
1498 */
1499 $.fn.crmAccordionToggle = function (speed) {
1500 $(this).each(function () {
1501 var action = 'open';
1502 if ($(this).hasClass('collapsed')) {
1503 $('.crm-accordion-body', this).first().css('display', 'none').slideDown(speed);
1504 }
1505 else {
1506 $('.crm-accordion-body', this).first().css('display', 'block').slideUp(speed);
1507 action = 'close';
1508 }
1509 $(this).toggleClass('collapsed').trigger('crmAccordion:' + action);
1510 });
1511 };
1512
1513 /**
1514 * Clientside currency formatting
1515 * @param number value
1516 * @param [optional] boolean onlyNumber - if true, we return formatted amount without currency sign
1517 * @param [optional] string format - currency representation of the number 1234.56
1518 * @return string
1519 */
1520 var currencyTemplate;
1521 CRM.formatMoney = function(value, onlyNumber, format) {
1522 var precision, decimal, separator, sign, i, j, result;
1523 if (value === 'init' && format) {
1524 currencyTemplate = format;
1525 return;
1526 }
1527 format = format || currencyTemplate;
1528 if ((result = /1(.?)234(.?)56/.exec(format)) !== null) { // If value is formatted to 2 decimals
1529 precision = 2;
1530 }
1531 else if ((result = /1(.?)234(.?)6/.exec(format)) !== null) { // If value is formatted to 1 decimal
1532 precision = 1;
1533 }
1534 else if ((result = /1(.?)235/.exec(format)) !== null) { // If value is formatted to zero decimals
1535 precision = false;
1536 }
1537 else {
1538 return 'Invalid format passed to CRM.formatMoney';
1539 }
1540 separator = result[1];
1541 decimal = precision ? result[2] : false;
1542 sign = (value < 0) ? '-' : '';
1543 //extracting the absolute value of the integer part of the number and converting to string
1544 i = parseInt(value = Math.abs(value).toFixed(2)) + '';
1545 j = ((j = i.length) > 3) ? j % 3 : 0;
1546 result = sign + (j ? i.substr(0, j) + separator : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + separator) + (precision ? decimal + Math.abs(value - i).toFixed(precision).slice(2) : '');
1547 if (onlyNumber) {
1548 return result;
1549 }
1550 switch (precision) {
1551 case 2:
1552 return format.replace(/1.*234.*56/, result);
1553 case 1:
1554 return format.replace(/1.*234.*6/, result);
1555 case false:
1556 return format.replace(/1.*235/, result);
1557 }
1558 };
1559
1560 CRM.angRequires = function(name) {
1561 return CRM.angular.requires[name] || [];
1562 };
1563
1564 CRM.console = function(method, title, msg) {
1565 if (window.console) {
1566 method = $.isFunction(console[method]) ? method : 'log';
1567 if (msg === undefined) {
1568 return console[method](title);
1569 } else {
1570 return console[method](title, msg);
1571 }
1572 }
1573 };
1574
1575 // Sugar methods for window.localStorage, with a fallback for older browsers
1576 var cacheItems = {};
1577 CRM.cache = {
1578 get: function (name, defaultValue) {
1579 try {
1580 if (localStorage.getItem('CRM' + name) !== null) {
1581 return JSON.parse(localStorage.getItem('CRM' + name));
1582 }
1583 } catch(e) {}
1584 return cacheItems[name] === undefined ? defaultValue : cacheItems[name];
1585 },
1586 set: function (name, value) {
1587 try {
1588 localStorage.setItem('CRM' + name, JSON.stringify(value));
1589 } catch(e) {}
1590 cacheItems[name] = value;
1591 },
1592 clear: function(name) {
1593 try {
1594 localStorage.removeItem('CRM' + name);
1595 } catch(e) {}
1596 delete cacheItems[name];
1597 }
1598 };
1599
1600
1601
1602 // Determine if a user has a given permission.
1603 // @see CRM_Core_Resources::addPermissions
1604 CRM.checkPerm = function(perm) {
1605 return CRM.permissions && CRM.permissions[perm];
1606 };
1607
1608 // Round while preserving sigfigs
1609 CRM.utils.sigfig = function(n, digits) {
1610 var len = ("" + n).length;
1611 var scale = Math.pow(10.0, len-digits);
1612 return Math.round(n / scale) * scale;
1613 };
1614
1615 // Create a js Date object from a unix timestamp or a yyyy-mm-dd string
1616 CRM.utils.makeDate = function(input) {
1617 switch (typeof input) {
1618 case 'object':
1619 // already a date object
1620 return input;
1621
1622 case 'string':
1623 // convert iso format with or without dashes
1624 if (input.indexOf('-') > 0) {
1625 return $.datepicker.parseDate('yy-mm-dd', input.substr(0, 10));
1626 }
1627 return $.datepicker.parseDate('yymmdd', input.substr(0, 8));
1628
1629 case 'number':
1630 // convert unix timestamp
1631 return new Date(input * 1000);
1632 }
1633 throw 'Invalid input passed to CRM.utils.makeDate';
1634 };
1635
1636 // Format a date for output to the user
1637 // Input may be a js Date object, a unix timestamp or a yyyy-mm-dd string
1638 CRM.utils.formatDate = function(input, outputFormat) {
1639 return input ? $.datepicker.formatDate(outputFormat || CRM.config.dateInputFormat, CRM.utils.makeDate(input)) : '';
1640 };
1641
1642 // Used to set appropriate text color for a given background
1643 CRM.utils.colorContrast = function (hexcolor) {
1644 hexcolor = hexcolor.replace(/[ #]/g, '');
1645 var r = parseInt(hexcolor.substr(0, 2), 16),
1646 g = parseInt(hexcolor.substr(2, 2), 16),
1647 b = parseInt(hexcolor.substr(4, 2), 16),
1648 yiq = ((r * 299) + (g * 587) + (b * 114)) / 1000;
1649 return (yiq >= 128) ? 'black' : 'white';
1650 };
1651
1652 // CVE-2015-9251 - Prevent auto-execution of scripts when no explicit dataType was provided
1653 $.ajaxPrefilter(function(s) {
1654 if (s.crossDomain) {
1655 s.contents.script = false;
1656 }
1657 });
1658
1659})(jQuery, _);