Send `is_default` data as boolean, not rendered icon; add js icon helper
[civicrm-core.git] / js / Common.js
CommitLineData
353ea873 1// https://civicrm.org/licensing
2b3ddf6e 2/* global CRM:true */
b7f93874 3var CRM = CRM || {};
4b513f23
CW
4var cj = CRM.$ = jQuery;
5CRM._ = _;
6a488035
TO
6
7/**
8 * Short-named function for string translation, defined in global scope so it's available everywhere.
9 *
353ea873
CW
10 * @param text string for translating
11 * @param params object key:value of additional parameters
6a488035 12 *
353ea873 13 * @return string
6a488035
TO
14 */
15function ts(text, params) {
7553cf23 16 "use strict";
3f3bba82
TO
17 var d = (params && params.domain) ? ('strings::' + params.domain) : null;
18 if (d && CRM[d] && CRM[d][text]) {
19 text = CRM[d][text];
20 }
0d75c29c
CW
21 else if (CRM.strings[text]) {
22 text = CRM.strings[text];
3f3bba82 23 }
2788147f 24 if (typeof(params) === 'object') {
6a488035 25 for (var i in params) {
32155ad6 26 if (typeof(params[i]) === 'string' || typeof(params[i]) === 'number') {
2788147f 27 // sprintf emulation: escape % characters in the replacements to avoid conflicts
32155ad6 28 text = text.replace(new RegExp('%' + i, 'g'), String(params[i]).replace(/%/g, '%-crmescaped-'));
2788147f 29 }
6a488035
TO
30 }
31 return text.replace(/%-crmescaped-/g, '%');
32 }
33 return text;
34}
35
2b3ddf6e
CW
36// Legacy code - ignore warnings
37/* jshint ignore:start */
38
6a488035
TO
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 *
353ea873 45 * @deprecated
6a488035
TO
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 ...)
6a488035 49 */
0f5816a6 50function on_load_init_blocks(showBlocks, hideBlocks, elementType) {
2b3ddf6e 51 if (elementType == null) {
f54254d8 52 elementType = 'block';
0f5816a6
KJ
53 }
54
f54254d8
TO
55 var myElement, i;
56
0f5816a6 57 /* This loop is used to display the blocks whose IDs are present within the showBlocks array */
f54254d8
TO
58 for (i = 0; i < showBlocks.length; i++) {
59 myElement = document.getElementById(showBlocks[i]);
0f5816a6 60 /* getElementById returns null if element id doesn't exist in the document */
2b3ddf6e 61 if (myElement != null) {
0f5816a6 62 myElement.style.display = elementType;
6a488035 63 }
0f5816a6
KJ
64 else {
65 alert('showBlocks array item not in .tpl = ' + showBlocks[i]);
66 }
67 }
6a488035 68
0f5816a6 69 /* This loop is used to hide the blocks whose IDs are present within the hideBlocks array */
f54254d8
TO
70 for (i = 0; i < hideBlocks.length; i++) {
71 myElement = document.getElementById(hideBlocks[i]);
0f5816a6 72 /* getElementById returns null if element id doesn't exist in the document */
2b3ddf6e 73 if (myElement != null) {
0f5816a6
KJ
74 myElement.style.display = 'none';
75 }
76 else {
77 alert('showBlocks array item not in .tpl = ' + hideBlocks[i]);
6a488035 78 }
0f5816a6 79 }
6a488035
TO
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 *
353ea873 86 * @deprecated
6a488035
TO
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
0f5816a6
KJ
93 */
94function showHideByValue(trigger_field_id, trigger_value, target_element_id, target_element_type, field_type, invert) {
f54254d8 95 var target, j;
0f5816a6
KJ
96
97 if (field_type == 'select') {
98 var trigger = trigger_value.split("|");
24cc4545 99 var selectedOptionValue = cj('#' + trigger_field_id).val();
0f5816a6 100
f54254d8
TO
101 target = target_element_id.split("|");
102 for (j = 0; j < target.length; j++) {
0f5816a6
KJ
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 }
6a488035 117 }
0f5816a6
KJ
118 }
119 }
6a488035 120
0f5816a6
KJ
121 }
122 else {
123 if (field_type == 'radio') {
f54254d8
TO
124 target = target_element_id.split("|");
125 for (j = 0; j < target.length; j++) {
5fb3af09 126 if (cj('[name="' + trigger_field_id + '"]:first').is(':checked')) {
0f5816a6
KJ
127 if (invert) {
128 cj('#' + target[j]).hide();
129 }
130 else {
131 cj('#' + target[j]).show();
132 }
6a488035 133 }
0f5816a6
KJ
134 else {
135 if (invert) {
136 cj('#' + target[j]).show();
137 }
138 else {
139 cj('#' + target[j]).hide();
140 }
141 }
142 }
6a488035 143 }
0f5816a6 144 }
6a488035
TO
145}
146
423616fa 147var submitcount = 0;
6a488035 148/**
423616fa 149 * Old submit-once function. Will be removed soon.
353ea873 150 * @deprecated
6a488035 151 */
0f5816a6
KJ
152function submitOnce(obj, formId, procText) {
153 // if named button clicked, change text
154 if (obj.value != null) {
42579c28 155 cj('input[name=' + obj.name + ']').val(procText + " ...");
0f5816a6 156 }
47ea29e3 157 cj(obj).closest('form').attr('data-warn-changes', 'false');
0f5816a6 158 if (document.getElementById) { // disable submit button for newer browsers
42579c28 159 cj('input[name=' + obj.name + ']').attr("disabled", true);
0f5816a6
KJ
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;
6a488035 171 }
0f5816a6 172 }
6a488035 173}
6a488035 174
6a488035
TO
175/**
176 * Function to show / hide the row in optionFields
353ea873
CW
177 * @deprecated
178 * @param index string, element whose innerHTML is to hide else will show the hidden row.
6a488035 179 */
0f5816a6
KJ
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();
6a488035 185 }
0f5816a6
KJ
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;
6a488035
TO
194}
195
2b3ddf6e
CW
196/* jshint ignore:end */
197
1711f01c
CW
198if (!CRM.utils) CRM.utils = {};
199if (!CRM.strings) CRM.strings = {};
200if (!CRM.vars) CRM.vars = {};
6a488035 201
4b513f23 202(function ($, _, undefined) {
7553cf23 203 "use strict";
0d75c29c 204 /* jshint validthis: true */
d664f648 205
3f586963
CW
206 // Theme classes for unattached elements
207 $.fn.select2.defaults.dropdownCssClass = $.ui.dialog.prototype.options.dialogClass = 'crm-container';
208
47f21f3a
CW
209 // https://github.com/ivaynberg/select2/pull/2090
210 $.fn.select2.defaults.width = 'resolve';
211
e20523a8
CW
212 // Workaround for https://github.com/ivaynberg/select2/issues/1246
213 $.ui.dialog.prototype._allowInteraction = function(e) {
e5b38290 214 return !!$(e.target).closest('.ui-dialog, .ui-datepicker, .select2-drop, .cke_dialog, #civicrm-menu').length;
e20523a8
CW
215 };
216
9f8862e1
CW
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')) {
9bce560a
CW
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);
9f8862e1
CW
230 }
231 }
232 };
233
286a7e5a 234 var scriptsLoaded = {};
2bdce12c 235 CRM.loadScript = function(url, appendCacheCode) {
286a7e5a 236 if (!scriptsLoaded[url]) {
2bdce12c
CW
237 var script = document.createElement('script'),
238 src = url;
239 if (appendCacheCode !== false) {
240 src += (_.includes(url, '?') ? '&r=' : '?r=') + CRM.config.resourceCacheCode;
241 }
286a7e5a
CW
242 scriptsLoaded[url] = $.Deferred();
243 script.onload = function () {
0d730261
CW
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);
286a7e5a 251 };
30b7642c
CW
252 // Make jQuery global available while script is loading
253 if (window.jQuery !== CRM.$) {
254 CRM.CMSjQuery = window.jQuery;
255 window.jQuery = CRM.$;
256 }
2bdce12c 257 script.src = src;
286a7e5a
CW
258 document.getElementsByTagName("head")[0].appendChild(script);
259 }
260 return scriptsLoaded[url];
261 };
262
475e9f44
CW
263 /**
264 * Populate a select list, overwriting the existing options except for the placeholder.
581c7be2 265 * @param select jquery selector - 1 or more select elements
475e9f44 266 * @param options array in format returned by api.getoptions
b7ceb253
CW
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
475e9f44 269 */
b7ceb253 270 CRM.utils.setOptions = function(select, options, placeholder, value) {
581c7be2 271 $(select).each(function() {
475e9f44
CW
272 var
273 $elect = $(this),
b7ceb253
CW
274 val = value || $elect.val() || [],
275 opts = placeholder || placeholder === '' ? '' : '[value!=""]';
23e8a31b 276 $elect.find('option' + opts).remove();
b7ceb253 277 var newOptions = CRM.utils.renderOptions(options, val);
1d07e7ab 278 if (typeof placeholder === 'string') {
581c7be2
CW
279 if ($elect.is('[multiple]')) {
280 select.attr('placeholder', placeholder);
1d07e7ab
CW
281 } else {
282 newOptions = '<option value="">' + placeholder + '</option>' + newOptions;
283 }
284 }
285 $elect.append(newOptions);
b7ceb253
CW
286 if (!value) {
287 $elect.trigger('crmOptionsUpdated', $.extend({}, options)).trigger('change');
288 }
475e9f44
CW
289 });
290 };
291
b7ceb253
CW
292 /**
293 * Render an option list
8decea37
CW
294 * @param options {array}
295 * @param val {string} default value
296 * @param escapeHtml {bool}
b7ceb253
CW
297 * @return string
298 */
8decea37
CW
299 CRM.utils.renderOptions = function(options, val, escapeHtml) {
300 var rendered = '',
301 esc = escapeHtml === false ? _.identity : _.escape;
b7ceb253
CW
302 if (!$.isArray(val)) {
303 val = [val];
304 }
305 _.each(options, function(option) {
306 if (option.children) {
8decea37 307 rendered += '<optgroup label="' + esc(option.value) + '">' +
52e6588d
CW
308 CRM.utils.renderOptions(option.children, val) +
309 '</optgroup>';
b7ceb253
CW
310 } else {
311 var selected = ($.inArray('' + option.key, val) > -1) ? 'selected="selected"' : '';
8decea37 312 rendered += '<option value="' + esc(option.key) + '"' + selected + '>' + esc(option.value) + '</option>';
b7ceb253 313 }
475e9f44 314 });
b7ceb253 315 return rendered;
475e9f44
CW
316 };
317
1d07e7ab
CW
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
52e6588d
CW
338 /**
339 * Compare Form Input values against cached initial value.
340 *
341 * @return {Boolean} true if changes have been made.
342 */
3e201321 343 CRM.utils.initialValueChanged = function(el) {
88e9380e 344 var isDirty = false;
d4fa3633 345 $(':input:visible, .select2-container:visible+:input:hidden', el).not('[type=submit], [type=button], .crm-action-menu, :disabled').each(function () {
603f899a
CW
346 var
347 initialValue = $(this).data('crm-initial-value'),
348 currentValue = $(this).is(':checkbox, :radio') ? $(this).prop('checked') : $(this).val();
3c0624e2 349 // skip change of value for submit buttons
603f899a 350 if (initialValue !== undefined && !_.isEqual(initialValue, currentValue)) {
88e9380e
CW
351 isDirty = true;
352 }
3e201321 353 });
354 return isDirty;
8d36b801 355 };
52e6588d 356
b1fc510d
CW
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 };
52e6588d 383
00c2ff9e 384 function formatCrmSelect2(row) {
b733747a
CW
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>' : '');
00c2ff9e
CW
396 }
397
bc37053c
AH
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
ba4fb2b2 426 /**
353ea873 427 * Wrapper for select2 initialization function; supplies defaults
a88cf11a 428 * @param options object
ba4fb2b2 429 */
a88cf11a 430 $.fn.crmSelect2 = function(options) {
4cd02904
CW
431 if (options === 'destroy') {
432 return $(this).each(function() {
433 $(this)
434 .removeClass('crm-ajax-select')
be677a1c 435 .off('.crmSelect2')
4cd02904
CW
436 .select2('destroy');
437 });
438 }
a88cf11a
CW
439 return $(this).each(function () {
440 var
441 $el = $(this),
9597c394 442 iconClass,
00c2ff9e
CW
443 settings = {
444 allowClear: !$el.hasClass('required'),
445 formatResult: formatCrmSelect2,
446 formatSelection: formatCrmSelect2
447 };
a88cf11a
CW
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 });
47358d92 453
454 // quickform does not support disabled option, so yet another hack to
455 // add disabled property for option values
711da13f 456 $('option[value^=crm_disabled_opt]', this).attr('disabled', 'disabled');
27a6b676 457
8c3a97ed 458 // Placeholder icon - total hack hikacking the escapeMarkup function but select2 3.5 dosn't have any other callbacks for this :(
9597c394 459 if ($el.is('[class*=fa-]')) {
8c3a97ed
CW
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 };
9597c394
CW
469 }
470
be677a1c
CW
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
a88cf11a
CW
478 // Defaults for single-selects
479 if ($el.is('select:not([multiple])')) {
a243158e 480 settings.minimumResultsForSearch = 10;
a88cf11a 481 if ($('option:first', this).val() === '') {
a243158e 482 settings.placeholderOption = 'first';
a88cf11a 483 }
ba4fb2b2 484 }
a243158e
CW
485 $.extend(settings, $el.data('select-params') || {}, options || {});
486 if (settings.ajax) {
487 $el.addClass('crm-ajax-select');
488 }
489 $el.select2(settings);
a88cf11a
CW
490 });
491 };
492
493 /**
353ea873 494 * @see CRM_Core_Form::addEntityRef for docs
a88cf11a
CW
495 * @param options object
496 */
497 $.fn.crmEntityRef = function(options) {
4cd02904
CW
498 if (options === 'destroy') {
499 return $(this).each(function() {
500 var entity = $(this).data('api-entity') || '';
501 $(this)
502 .off('.crmEntity')
2229cf4f 503 .removeClass('crm-form-entityref crm-' + _.kebabCase(entity) + '-ref')
4cd02904
CW
504 .crmSelect2('destroy');
505 });
506 }
a88cf11a
CW
507 options = options || {};
508 options.select = options.select || {};
509 return $(this).each(function() {
510 var
4c993609 511 $el = $(this).off('.crmEntity'),
2229cf4f 512 entity = options.entity || $el.data('api-entity') || 'Contact',
a88cf11a 513 selectParams = {};
2229cf4f
CW
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 }
a88cf11a
CW
518 $el.data('api-entity', entity);
519 $el.data('select-params', $.extend({}, $el.data('select-params') || {}, options.select));
0ed35ef8 520 $el.data('api-params', $.extend(true, {}, $el.data('api-params') || {}, options.api));
a4799f04 521 $el.data('create-links', options.create || $el.data('create-links'));
2229cf4f 522 $el.addClass('crm-form-entityref crm-' + _.kebabCase(entity) + '-ref');
ba4fb2b2 523 var settings = {
b7ceb253 524 // Use select2 ajax helper instead of CRM.api3 because it provides more value
ba4fb2b2
CW
525 ajax: {
526 url: CRM.url('civicrm/ajax/rest'),
3d06f63c 527 quietMillis: 300,
ba4fb2b2 528 data: function (input, page_num) {
b7ceb253 529 var params = getEntityRefApiParams($el);
ba4fb2b2
CW
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 },
a88cf11a 542 minimumInputLength: 1,
3c0b6a40 543 formatResult: CRM.utils.formatSelect2Result,
4fcc9877 544 formatSelection: formatEntityRefSelection,
7a5edd0a 545 escapeMarkup: _.identity,
a88cf11a
CW
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 {
78b203e5 558 var params = $.extend({}, $el.data('api-params') || {}, {id: val});
a88cf11a 559 CRM.api3($el.data('api-entity'), 'getlist', params).done(function(result) {
d2b4810b
CW
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');
a88cf11a
CW
563 });
564 }
ba4fb2b2
CW
565 }
566 };
4c993609 567 // Create new items inline - works for tags
2229cf4f 568 if ($el.data('create-links') && entity === 'Tag') {
4c993609
CW
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 };
e4f4dc22 574 selectParams.tokenSeparators = [','];
4c993609 575 selectParams.createSearchChoicePosition = 'bottom';
05b21c58 576 $el.on('select2-selecting.crmEntity', function(e) {
4c993609 577 if (e.val === "0") {
a2c28a94 578 // Create a new term
4c993609
CW
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
4c993609
CW
583 val = $el.select2('val'),
584 data = $el.select2('data'),
585 item = {id: created.id, label: e.object.term};
586 if (val === "0") {
e4f4dc22 587 $el.select2('data', item, true);
4c993609
CW
588 }
589 else if ($.isArray(val) && $.inArray("0", val) > -1) {
590 _.remove(data, {id: "0"});
591 data.push(item);
e4f4dc22 592 $el.select2('data', data, true);
4c993609
CW
593 }
594 });
595 }
596 });
b7ceb253
CW
597 }
598 else {
a88cf11a
CW
599 selectParams.formatInputTooShort = function() {
600 var txt = $el.data('select-params').formatInputTooShort || $.fn.select2.defaults.formatInputTooShort.call(this);
fd7c068f 601 txt += entityRefFiltersMarkup($el) + renderEntityRefCreateLinks($el);
ba4fb2b2
CW
602 return txt;
603 };
a88cf11a 604 selectParams.formatNoMatches = function() {
ba4fb2b2 605 var txt = $el.data('select-params').formatNoMatches || $.fn.select2.defaults.formatNoMatches;
fd7c068f 606 txt += entityRefFiltersMarkup($el) + renderEntityRefCreateLinks($el);
b7ceb253 607 return txt;
ba4fb2b2 608 };
4c993609 609 $el.on('select2-open.crmEntity', function() {
ba4fb2b2 610 var $el = $(this);
b7ceb253
CW
611 $('#select2-drop')
612 .off('.crmEntity')
613 .on('click.crmEntity', 'a.crm-add-entity', function(e) {
882a1be2 614 var extra = $el.data('api-params').extra,
2b63c577 615 formUrl = $(this).attr('href') + '&returnExtra=display_name,sort_name' + (extra ? (',' + extra) : '');
b7ceb253 616 $el.select2('close');
882a1be2 617 CRM.loadForm(formUrl, {
8dbd6052 618 dialog: {width: '50%', height: 220}
b7ceb253
CW
619 }).on('crmFormSuccess', function(e, data) {
620 if (data.status === 'success' && data.id) {
8dbd6052
CW
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;
b7ceb253
CW
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 }
c92f6436 632 }
b7ceb253
CW
633 });
634 return false;
635 })
fd7c068f 636 .on('change.crmEntity', '.crm-entityref-filter-value', function() {
b7ceb253
CW
637 var filter = $el.data('user-filter') || {};
638 filter.value = $(this).val();
639 $(this).toggleClass('active', !!filter.value);
640 $el.data('user-filter', filter);
0943a2d8 641 if (filter.value && $(this).is('select')) {
b7ceb253
CW
642 // Once a filter has been chosen, rerender create links and refocus the search box
643 $el.select2('close');
644 $el.select2('open');
38558375
CW
645 } else {
646 $('.crm-entityref-links', '#select2-drop').replaceWith(renderEntityRefCreateLinks($el));
ba4fb2b2 647 }
b7ceb253
CW
648 })
649 .on('change.crmEntity', 'select.crm-entityref-filter-key', function() {
38558375 650 var filter = {key: $(this).val()};
b7ceb253
CW
651 $(this).toggleClass('active', !!filter.key);
652 $el.data('user-filter', filter);
fd7c068f
CW
653 renderEntityRefFilterValue($el);
654 $('.crm-entityref-filter-key', '#select2-drop').focus();
ba4fb2b2 655 });
ba4fb2b2
CW
656 });
657 }
05b21c58 658 $el.crmSelect2($.extend(settings, $el.data('select-params'), selectParams));
a88cf11a 659 });
ba4fb2b2
CW
660 };
661
b7ceb253
CW
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) {
06606cd1
CW
674 // Fieldname may be prefixed with joins
675 var fieldName = _.last(filter.key.split('.'));
b7ceb253 676 // Special case for contact type/sub-type combo
06606cd1
CW
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];
b7ceb253 680 } else {
cdc8d05f
CW
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;
b7ceb253
CW
683 }
684 }
685 return combined;
686 }
687
403c52ac 688 CRM.utils.copyAttributes = function ($source, $target, attributes) {
9bce560a 689 _.each(attributes, function(name) {
a2973721 690 if ($source.attr(name) !== undefined) {
9bce560a
CW
691 $target.attr(name, $source.attr(name));
692 }
693 });
9bce560a
CW
694 };
695
3c0b6a40 696 CRM.utils.formatSelect2Result = function (row) {
88881f79 697 var markup = '<div class="crm-select2-row">';
ff88d165 698 if (row.image !== undefined) {
88881f79 699 markup += '<div class="crm-select2-image"><img src="' + row.image + '"/></div>';
ff88d165 700 }
54bee7df 701 else if (row.icon_class) {
88881f79 702 markup += '<div class="crm-select2-icon"><div class="crm-icon ' + row.icon_class + '-icon"></div></div>';
54bee7df 703 }
8a938c69 704 markup += '<div><div class="crm-select2-row-label '+(row.label_class || '')+'">' +
4fcc9877 705 (row.color ? '<span class="crm-select-item-color" style="background-color: ' + row.color + '"></span> ' : '') +
7a5edd0a 706 _.escape((row.prefix !== undefined ? row.prefix + ' ' : '') + row.label + (row.suffix !== undefined ? ' ' + row.suffix : '')) +
8a938c69
CW
707 '</div>' +
708 '<div class="crm-select2-row-description">';
88881f79 709 $.each(row.description || [], function(k, text) {
3eb539fd 710 markup += '<p>' + _.escape(text) + '</p> ';
88881f79
CW
711 });
712 markup += '</div></div></div>';
ff88d165 713 return markup;
3c0b6a40 714 };
a4799f04 715
4fcc9877
CW
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
b7ceb253 721 function renderEntityRefCreateLinks($el) {
a4799f04
CW
722 var
723 createLinks = $el.data('create-links'),
b7ceb253 724 params = getEntityRefApiParams($el).params,
2229cf4f 725 entity = $el.data('api-entity'),
b7ceb253 726 markup = '<div class="crm-entityref-links">';
e695ee7c 727 if (!createLinks || (createLinks === true && !CRM.config.entityRef.links[entity])) {
b7ceb253
CW
728 return '';
729 }
a4799f04 730 if (createLinks === true) {
e695ee7c 731 createLinks = params.contact_type ? _.where(CRM.config.entityRef.links[entity], {type: params.contact_type}) : CRM.config.entityRef.links[entity];
a4799f04 732 }
a4799f04 733 _.each(createLinks, function(link) {
8dbd6052
CW
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>';
79ae07d9 737 });
b7ceb253
CW
738 markup += '</div>';
739 return markup;
740 }
741
742 function getEntityRefFilters($el) {
743 var
2229cf4f 744 entity = $el.data('api-entity'),
11f907d4 745 filters = CRM.config.entityRef.filters[entity] || [],
b7ceb253
CW
746 params = $.extend({params: {}}, $el.data('api-params') || {}).params,
747 result = [];
74e8320f
CW
748 _.each(filters, function(filter) {
749 _.defaults(filter, {type: 'select', 'attributes': {}, entity: entity});
11f907d4 750 if (!params[filter.key]) {
7fd621e8
CW
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 }
fd7c068f 755 result.push(filter);
b7ceb253 756 }
fd7c068f 757 else if (filter.key == 'contact_type' && typeof params.contact_sub_type === 'undefined') {
fd7c068f 758 result.push(filter);
b7ceb253
CW
759 }
760 });
761 return result;
762 }
763
fd7c068f
CW
764 /**
765 * Provide markup for entity ref filters
766 */
767 function entityRefFiltersMarkup($el) {
b7ceb253
CW
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' : '') + '">' +
7a5edd0a 777 '<option value="">' + _.escape(ts('Refine search...')) + '</option>' +
52e6588d 778 CRM.utils.renderOptions(filters, filter.key) +
0943a2d8 779 '</select>' + entityRefFilterValueMarkup($el, filter, filterSpec) + '</div>';
fd7c068f
CW
780 return markup;
781 }
782
783 /**
784 * Provide markup for entity ref filter value field
785 */
0943a2d8 786 function entityRefFilterValueMarkup($el, filter, filterSpec) {
fd7c068f
CW
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') {
0943a2d8
CW
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>';
fd7c068f
CW
806 } else {
807 markup = '<input' + attrs + '/>';
808 }
b7ceb253 809 }
79ae07d9 810 return markup;
a4799f04 811 }
ff88d165 812
b7ceb253 813 /**
fd7c068f 814 * Render the entity ref filter value field
b7ceb253 815 */
fd7c068f 816 function renderEntityRefFilterValue($el) {
b7ceb253 817 var
b7ceb253 818 filter = $el.data('user-filter') || {},
fd7c068f
CW
819 filterSpec = filter.key ? _.find(getEntityRefFilters($el), {key: filter.key}) : null,
820 $keyField = $('.crm-entityref-filter-key', '#select2-drop'),
821 $valField = null;
b7ceb253 822 if (filterSpec) {
fd7c068f 823 $('.crm-entityref-filter-value', '#select2-drop').remove();
0943a2d8 824 $valField = $(entityRefFilterValueMarkup($el, filter, filterSpec));
fd7c068f 825 $keyField.after($valField);
11f907d4 826 if (filterSpec.type === 'select') {
fd7c068f 827 loadEntityRefFilterOptions(filter, filterSpec, $valField, $el);
b7ceb253
CW
828 }
829 } else {
fd7c068f 830 $('.crm-entityref-filter-value', '#select2-drop').hide().val('').change();
b7ceb253
CW
831 }
832 }
833
fd7c068f 834 /**
11f907d4 835 * Fetch options for a filter from cache or ajax api
fd7c068f
CW
836 */
837 function loadEntityRefFilterOptions(filter, filterSpec, $valField, $el) {
fd7c068f 838 // Fieldname may be prefixed with joins - strip those out
0943a2d8 839 var fieldName = _.last(filter.key.split('.'));
11f907d4 840 if (filterSpec.options) {
0943a2d8 841 CRM.utils.setOptions($valField, getEntityRefFilterOptions(fieldName, $el, filterSpec), false, filter.value);
11f907d4
CW
842 return;
843 }
844 $('.crm-entityref-filters select', '#select2-drop').prop('disabled', true);
fd7c068f
CW
845 CRM.api3(filterSpec.entity, 'getoptions', {field: fieldName, context: 'search', sequential: 1})
846 .done(function(result) {
11f907d4 847 var entity = $el.data('api-entity').toLowerCase();
fd7c068f 848 // Store options globally so we don't have to look them up again
11f907d4
CW
849 filterSpec.options = result.values;
850 $('.crm-entityref-filters select', '#select2-drop').prop('disabled', false);
0943a2d8 851 CRM.utils.setOptions($valField, getEntityRefFilterOptions(fieldName, $el, filterSpec), false, filter.value);
fd7c068f
CW
852 });
853 }
854
0943a2d8
CW
855 function getEntityRefFilterOptions(fieldName, $el, filterSpec) {
856 var values = _.cloneDeep(filterSpec.options),
857 params = $.extend({params: {}}, $el.data('api-params') || {}).params;
11f907d4
CW
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 }
0943a2d8 863 return values;
11f907d4
CW
864 }
865
1136a401 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
3d527838
CW
876 /**
877 * Wrapper for jQuery validate initialization function; supplies defaults
3d527838
CW
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 });
b7ceb253 891 };
3d527838 892
423616fa
CW
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 }
c53716ff
CW
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');
423616fa
CW
915 }
916 }
917
c53716ff
CW
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
f7b92fcd 928 // Initialize widgets
eb90857a
CW
929 $(document)
930 .on('crmLoad', function(e) {
931 $('table.row-highlight', e.target)
932 .off('.rowHighlight')
7e13d44e
CW
933 .on('change.rowHighlight', 'input.select-row, input.select-rows', function (e, data) {
934 var filter, $table = $(this).closest('table');
eb90857a 935 if ($(this).hasClass('select-rows')) {
7e13d44e
CW
936 filter = $(this).prop('checked') ? ':not(:checked)' : ':checked';
937 $('input.select-row' + filter, $table).prop('checked', $(this).prop('checked')).trigger('change', 'master-selected');
eb90857a
CW
938 }
939 else {
7e13d44e
CW
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 }
eb90857a 944 }
eb90857a
CW
945 })
946 .find('input.select-row:checked').parents('tr').addClass('crm-row-selected');
4e086328 947 $('.crm-sortable-list', e.target).sortable();
7d12de7f 948 $('table.crm-sortable', e.target).DataTable();
16f4d319
CW
949 $('table.crm-ajax-table', e.target).each(function() {
950 var
951 $table = $(this),
1c952f13 952 script = CRM.config.resourceBase + 'js/jquery/jquery.crmAjaxTable.js',
16f4d319
CW
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() {
1c952f13
CW
957 CRM.loadScript(script).done(function() {
958 $table.crmAjaxTable();
959 });
16f4d319
CW
960 });
961 } else {
1c952f13
CW
962 CRM.loadScript(script).done(function() {
963 $table.crmAjaxTable();
964 });
16f4d319
CW
965 }
966 });
82661158
JP
967 if ($("input:radio[name=radio_ts]").size() == 1) {
968 $("input:radio[name=radio_ts]").prop("checked", true);
969 }
5f34e50b
CW
970 $('.crm-select2:not(.select2-offscreen, .select2-container)', e.target).crmSelect2();
971 $('.crm-form-entityref:not(.select2-offscreen, .select2-container)', e.target).crmEntityRef();
1d07e7ab 972 $('select.crm-chain-select-control', e.target).off('.chainSelect').on('change.chainSelect', chainSelect);
238fee7f
CW
973 $('.crm-form-text[data-crm-datepicker]', e.target).each(function() {
974 $(this).crmDatepicker($(this).data('crmDatepicker'));
975 });
30b7642c
CW
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 });
3e201321 982 // Cache Form Input initial values
88e9380e 983 $('form[data-warn-changes] :input', e.target).each(function() {
603f899a 984 $(this).data('crm-initial-value', $(this).is(':checkbox, :radio') ? $(this).prop('checked') : $(this).val());
3e201321 985 });
9db15279
CW
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 });
c53716ff
CW
993 // Submit once handlers
994 $('form[data-submit-once]', e.target)
995 .submit(submitOnceForm)
996 .on('invalid-form', submitFormInvalid);
423616fa
CW
997 $('form[data-submit-once] input[type=submit]', e.target).click(function(e) {
998 submitButton = e.target;
999 });
eb90857a 1000 })
eb90857a 1001 .on('dialogopen', function(e) {
f292709b 1002 var $el = $(e.target);
89696a2f 1003 $('body').addClass('ui-dialog-open');
f292709b
CW
1004 // Modal dialogs should disable scrollbars
1005 if ($el.dialog('option', 'modal')) {
1006 $el.addClass('modal-dialog');
eb90857a
CW
1007 $('body').css({overflow: 'hidden'});
1008 }
3479049c 1009 $el.parent().find('.ui-dialog-titlebar .ui-icon-closethick').removeClass('ui-icon-closethick').addClass('fa-times');
f292709b 1010 // Add resize button
a243158e 1011 if ($el.parent().hasClass('crm-container') && $el.dialog('option', 'resizable')) {
7a5edd0a 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}));
f292709b
CW
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);
e915be1d 1017 $(this).button('option', 'icons', {primary: 'fa-expand'});
f292709b 1018 } else {
28d510ab 1019 var menuHeight = $('#civicrm-menu').outerHeight();
59007035
CW
1020 if ($('body').hasClass('crm-menubar-below-cms-menu')) {
1021 menuHeight += $('#civicrm-menu').offset().top;
1022 }
f292709b 1023 $el.data('origSize', {
28d510ab 1024 position: {my: 'center', at: 'center center+' + (menuHeight / 2), of: window},
f292709b
CW
1025 width: $el.dialog('option', 'width'),
1026 height: $el.dialog('option', 'height')
1027 });
f2f191fe 1028 $el.dialog('option', {width: '100%', height: ($(window).height() - menuHeight), position: {my: "top", at: "top+"+menuHeight, of: window}});
e915be1d 1029 $(this).button('option', 'icons', {primary: 'fa-compress'});
f292709b 1030 }
02cd9764 1031 $el.trigger('dialogresize');
f292709b
CW
1032 e.preventDefault();
1033 });
1034 }
eb90857a
CW
1035 })
1036 .on('dialogclose', function(e) {
f292709b 1037 // Restore scrollbars when closing modal
5a6148a0 1038 if ($('.ui-dialog .modal-dialog:visible').not(e.target).length < 1) {
eb90857a
CW
1039 $('body').css({overflow: ''});
1040 }
89696a2f
CW
1041 if ($('.ui-dialog-content:visible').not(e.target).length < 1) {
1042 $('body').removeClass('ui-dialog-open');
1043 }
afc021d8 1044 })
1045 .on('submit', function(e) {
f582fc8f 1046 // CRM-14353 - disable changes warn when submitting a form
abb6e044 1047 $('[data-warn-changes]').attr('data-warn-changes', 'false');
52e6588d 1048 });
f582fc8f
CW
1049
1050 // CRM-14353 - Warn of unsaved changes for forms which have opted in
1051 window.onbeforeunload = function() {
18469bf2 1052 if (CRM.utils.initialValueChanged($('form[data-warn-changes=true]:visible'))) {
f582fc8f 1053 return ts('You have unsaved changes.');
0f5816a6 1054 }
f582fc8f 1055 };
6a488035 1056
0f5816a6 1057 $.fn.crmtooltip = function () {
2c29c2ac
RN
1058 $(document)
1059 .on('mouseover', 'a.crm-summary-link:not(.crm-processed)', function (e) {
73ed0c3f 1060 $(this).addClass('crm-processed crm-tooltip-active');
e24b17b9 1061 var topDistance = e.pageY - $(window).scrollTop();
2b3ddf6e 1062 if (topDistance < 300 || topDistance < $(this).children('.crm-tooltip-wrapper').height()) {
e24b17b9
CW
1063 $(this).addClass('crm-tooltip-down');
1064 }
1065 if (!$(this).children('.crm-tooltip-wrapper').length) {
6a488035
TO
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 })
2c29c2ac 1072 .on('mouseout', 'a.crm-summary-link', function () {
73ed0c3f 1073 $(this).removeClass('crm-processed crm-tooltip-active crm-tooltip-down');
e24b17b9 1074 })
2c29c2ac 1075 .on('click', 'a.crm-summary-link', false);
6a488035
TO
1076 };
1077
b0ca6188 1078 var helpDisplay, helpPrevious;
2a243675
CW
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'});
8e3272a1 1083 CRM.help = function (title, params, url) {
2a243675 1084 var ajax = typeof params !== 'string';
55a93b02 1085 if (helpDisplay && helpDisplay.close) {
2a243675
CW
1086 // If the same link is clicked twice, just close the display
1087 if (helpDisplay.isOpen && _.isEqual(helpPrevious, params)) {
55a93b02 1088 helpDisplay.close();
b0ca6188
CW
1089 return;
1090 }
55a93b02 1091 helpDisplay.close();
b0ca6188 1092 }
2a243675
CW
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, {
6a488035
TO
1102 data: params,
1103 dataType: 'html',
e24b17b9 1104 success: function (data) {
6a488035
TO
1105 $('#crm-notification-container .crm-help .notify-content:last').html(data);
1106 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('info');
1107 },
e24b17b9 1108 error: function () {
6a488035
TO
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 }
2a243675
CW
1112 });
1113 }
6a488035 1114 };
8960d9b9 1115 /**
7442e8f6 1116 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
8960d9b9 1117 */
1b2475e1 1118 CRM.status = function(options, deferred) {
9a7ef94f 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.
1b2475e1
CW
1120 if (typeof options === 'string') {
1121 return CRM.status({start: options, success: options, error: options})[deferred === 'error' ? 'reject' : 'resolve']();
8960d9b9 1122 }
1b2475e1
CW
1123 var opts = $.extend({
1124 start: ts('Saving...'),
9a7ef94f 1125 success: ts('Saved'),
47737104
CW
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');
1b2475e1
CW
1129 }
1130 }, options || {});
7a5edd0a 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>')
1b2475e1
CW
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) {
7a5edd0a 1137 $msg.removeClass('status-start').addClass('status-' + status).find('.crm-status-box-msg').text(endMsg);
1b2475e1 1138 window.setTimeout(function() {
f54254d8
TO
1139 $msg.fadeOut('slow', function() {
1140 $msg.remove();
1141 });
4bad157e
CW
1142 }, 2000);
1143 } else {
1b2475e1 1144 $msg.remove();
4bad157e 1145 }
1b2475e1
CW
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 });
8960d9b9 1156 };
6a488035 1157
beab9d1b
TO
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
705c61e9
TO
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
6a488035 1179 /**
7442e8f6 1180 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
6a488035 1181 */
0f5816a6 1182 CRM.alert = function (text, title, type, options) {
6a488035
TO
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);
d19abfd1 1198 options.expires = (options.expires === false || !CRM.config.allowAlertAutodismissal) ? 0 : parseInt(options.expires, 10);
6a488035 1199 if (options.unique && options.unique !== '0') {
0f5816a6 1200 $('#crm-notification-container .ui-notify-message').each(function () {
6a488035
TO
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 }
a0a0f60d
N
1212 // strip html tags as they are not parsed in standard alerts
1213 alert($("<div/>").html(text).text());
6a488035
TO
1214 return null;
1215 }
e24b17b9 1216 };
6a488035
TO
1217
1218 /**
1219 * Close whichever alert contains the given node
1220 *
1221 * @param node
1222 */
0f5816a6 1223 CRM.closeAlertByChild = function (node) {
6a488035 1224 $(node).closest('.ui-notify-message').find('.icon.ui-notify-close').click();
e24b17b9 1225 };
6a488035
TO
1226
1227 /**
7442e8f6 1228 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
6a488035 1229 */
5fb83680 1230 CRM.confirm = function (options) {
27f190b4 1231 var dialog, url, msg, buttons = [], settings = {
a65e5f52 1232 title: ts('Confirm'),
7553cf23 1233 message: ts('Are you sure you want to continue?'),
3f4328da 1234 url: null,
0d5f99d4 1235 width: 'auto',
a8a8ddac 1236 height: 'auto',
a243158e 1237 resizable: false,
5fb83680 1238 dialogClass: 'crm-container crm-confirm',
0f5816a6 1239 close: function () {
5fb83680 1240 $(this).dialog('destroy').remove();
0f5816a6 1241 },
5fb83680
CW
1242 options: {
1243 no: ts('Cancel'),
1244 yes: ts('Continue')
1245 }
0f5816a6 1246 };
a8a8ddac
CW
1247 if (options && options.url) {
1248 settings.resizable = true;
1249 settings.height = '50%';
1250 }
5fb83680 1251 $.extend(settings, ($.isFunction(options) ? arguments[1] : options) || {});
a8a8ddac 1252 settings = CRM.utils.adjustDialogDefaults(settings);
5fb83680 1253 if (!settings.buttons && $.isPlainObject(settings.options)) {
27f190b4
CW
1254 $.each(settings.options, function(op, label) {
1255 buttons.push({
5fb83680 1256 text: label,
27f190b4 1257 'data-op': op,
972bd897 1258 icons: {primary: op === 'no' ? 'fa-times' : 'fa-check'},
5fb83680 1259 click: function() {
27f190b4 1260 var event = $.Event('crmConfirm:' + op);
5fb83680
CW
1261 $(this).trigger(event);
1262 if (!event.isDefaultPrevented()) {
1263 dialog.dialog('close');
1264 }
1265 }
1266 });
1267 });
27f190b4
CW
1268 // Order buttons so that "no" goes on the right-hand side
1269 settings.buttons = _.sortBy(buttons, 'data-op').reverse();
2a06342c 1270 }
3f4328da 1271 url = settings.url;
c0b7c815 1272 msg = url ? '' : settings.message;
5fb83680
CW
1273 delete settings.options;
1274 delete settings.message;
3f4328da 1275 delete settings.url;
c0b7c815 1276 dialog = $('<div class="crm-confirm-dialog"></div>').html(msg || '').dialog(settings);
5fb83680
CW
1277 if ($.isFunction(options)) {
1278 dialog.on('crmConfirm:yes', options);
7553cf23 1279 }
3f4328da
CW
1280 if (url) {
1281 CRM.loadPage(url, {target: dialog});
1282 }
c0b7c815
CW
1283 else {
1284 dialog.trigger('crmLoad');
3f4328da
CW
1285 }
1286 return dialog;
e24b17b9 1287 };
6a488035 1288
ed7225e6
CW
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 }
f97524d9
TO
1295 return ts(message, options);
1296 };
f97524d9
TO
1297 };
1298
e3d90d6c
TO
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
6a488035 1305 /**
7442e8f6 1306 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
6a488035 1307 */
0f5816a6 1308 $.fn.crmError = function (text, title, options) {
6a488035
TO
1309 title = title || '';
1310 text = text || '';
1311 options = options || {};
1312
1313 var extra = {
1314 expires: 0
1315 };
1316 if ($(this).length) {
0d75c29c 1317 if (title === '') {
6a488035
TO
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();
0d75c29c 1322 if (text === '' && $('.crm-marker', $label).length > 0) {
6a488035
TO
1323 text = $('.crm-marker', $label).attr('title');
1324 }
1325 $('.crm-marker', $label).remove();
1326 title = $label.text();
1327 }
1328 }
47737104 1329 $(this).addClass('crm-error');
6a488035
TO
1330 }
1331 var msg = CRM.alert(text, title, 'error', $.extend(extra, options));
1332 if ($(this).length) {
1333 var ele = $(this);
0f5816a6
KJ
1334 setTimeout(function () {
1335 ele.one('change', function () {
f54254d8 1336 if (msg && msg.close) msg.close();
0f5816a6
KJ
1337 ele.removeClass('error');
1338 label.removeClass('crm-error');
1339 });
1340 }, 1000);
6a488035
TO
1341 }
1342 return msg;
e24b17b9 1343 };
6a488035
TO
1344
1345 // Display system alerts through js notifications
1346 function messagesFromMarkup() {
0f5816a6 1347 $('div.messages:visible', this).not('.help').not('.no-popup').each(function () {
e24b17b9 1348 var text, title = '';
6a488035
TO
1349 $(this).removeClass('status messages');
1350 var type = $(this).attr('class').split(' ')[0] || 'alert';
1351 type = type.replace('crm-', '');
1352 $('.icon', this).remove();
6a488035 1353 if ($('.msg-text', this).length > 0) {
e24b17b9 1354 text = $('.msg-text', this).html();
6a488035
TO
1355 title = $('.msg-title', this).html();
1356 }
1357 else {
e24b17b9 1358 text = $(this).html();
6a488035
TO
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
e4762285
CW
1377 /**
1378 * Improve blockUI when used with jQuery dialog
1379 */
1adbbe2d
CW
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);
e4762285 1389 };
1adbbe2d
CW
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);
e4762285 1396 };
1adbbe2d 1397
e4762285 1398 // Preprocess all CRM ajax calls to display messages
03a7ec8f
CW
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);
f54254d8 1406 });
03a7ec8f 1407 }
bba9b4f0
CW
1408 if (response.backtrace) {
1409 CRM.console('log', response.backtrace);
1410 }
82983331
CW
1411 if (typeof response.deprecated === 'string') {
1412 CRM.console('warn', response.deprecated);
1413 }
03a7ec8f
CW
1414 }
1415 }
82983331 1416 // Ignore errors thrown by parseJSON
03a7ec8f
CW
1417 catch (e) {}
1418 });
1419
0f5816a6 1420 $(function () {
fdeb4de2 1421 $.blockUI.defaults.message = null;
1adbbe2d 1422 $.blockUI.defaults.ignoreIfBlocked = true;
fdeb4de2 1423
65b86482
CW
1424 if ($('#crm-container').hasClass('crm-public')) {
1425 $.fn.select2.defaults.dropdownCssClass = $.ui.dialog.prototype.options.dialogClass = 'crm-container crm-public';
1426 }
1427
205bb8ae 1428 // Trigger crmLoad on initial content for consistency. It will also be triggered for ajax-loaded content.
8547369d 1429 $('.crm-container').trigger('crmLoad');
205bb8ae 1430
ef3309b6 1431 if ($('#crm-notification-container').length) {
6a488035
TO
1432 // Initialize notifications
1433 $('#crm-notification-container').notify();
1434 messagesFromMarkup.call($('#crm-container'));
6a488035 1435 }
ebb9197b 1436
475e9f44 1437 $('body')
5fb83680
CW
1438 // bind the event for image popup
1439 .on('click', 'a.crm-image-popup', function(e) {
1440 CRM.confirm({
1441 title: ts('Preview'),
a243158e 1442 resizable: true,
135880c6
CW
1443 // Prevent overlap with the menubar
1444 maxHeight: $(window).height() - 30,
1445 position: {my: 'center', at: 'center center+15', of: window},
e4762285 1446 message: '<div class="crm-custom-image-popup"><img style="max-width: 100%" src="' + $(this).attr('href') + '"></div>',
5fb83680
CW
1447 options: null
1448 });
1449 e.preventDefault();
475e9f44 1450 })
ebb9197b 1451
475e9f44
CW
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 })
d664f648 1458
4a143c04
CW
1459 // Handle clear button for form elements
1460 .on('click', 'a.crm-clear-link', function() {
9bce560a
CW
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']);
4a143c04
CW
1463 return false;
1464 })
754affae 1465 .on('change keyup', 'input.crm-form-radio:checked, input[allowclear=1]', function(e, context) {
0c6fe5b5
CW
1466 if (context !== 'crmClear' && ($(this).is(':checked') || ($(this).is('[allowclear=1]') && $(this).val()))) {
1467 $(this).siblings('.crm-clear-link').css({visibility: ''});
1468 }
754affae
CW
1469 if (context !== 'crmClear' && $(this).is('[allowclear=1]') && $(this).val() === '') {
1470 $(this).siblings('.crm-clear-link').css({visibility: 'hidden'});
1471 }
843bfb07 1472 })
6a488035 1473
843bfb07 1474 // Allow normal clicking of links within accordions
25ce04ec 1475 .on('click.crmAccordions', 'div.crm-accordion-header a, .collapsible-title a', function (e) {
843bfb07 1476 e.stopPropagation();
cf021bc5 1477 })
843bfb07
CW
1478 // Handle accordions
1479 .on('click.crmAccordions', '.crm-accordion-header, .crm-collapsible .collapsible-title', function (e) {
16f4d319 1480 var action = 'open';
6a488035 1481 if ($(this).parent().hasClass('collapsed')) {
843bfb07 1482 $(this).next().css('display', 'none').slideDown(200);
6a488035
TO
1483 }
1484 else {
843bfb07 1485 $(this).next().css('display', 'block').slideUp(200);
16f4d319 1486 action = 'close';
6a488035 1487 }
16f4d319 1488 $(this).parent().toggleClass('collapsed').trigger('crmAccordion:' + action);
843bfb07 1489 e.preventDefault();
6a488035 1490 });
843bfb07
CW
1491
1492 $().crmtooltip();
1493 });
d5768733 1494
843bfb07
CW
1495 /**
1496 * Collapse or expand an accordion
1497 * @param speed
1498 */
0f5816a6
KJ
1499 $.fn.crmAccordionToggle = function (speed) {
1500 $(this).each(function () {
16f4d319 1501 var action = 'open';
6a488035
TO
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);
16f4d319 1507 action = 'close';
6a488035 1508 }
16f4d319 1509 $(this).toggleClass('collapsed').trigger('crmAccordion:' + action);
6a488035
TO
1510 });
1511 };
5ec182d9
CW
1512
1513 /**
1514 * Clientside currency formatting
e4762285 1515 * @param number value
e4f46be0 1516 * @param [optional] boolean onlyNumber - if true, we return formatted amount without currency sign
e4762285 1517 * @param [optional] string format - currency representation of the number 1234.56
5ec182d9
CW
1518 * @return string
1519 */
1520 var currencyTemplate;
7f92cfa9 1521 CRM.formatMoney = function(value, onlyNumber, format) {
db9e0947 1522 var precision, decimal, separator, sign, i, j, result;
5ec182d9
CW
1523 if (value === 'init' && format) {
1524 currencyTemplate = format;
1525 return;
1526 }
1527 format = format || currencyTemplate;
db9e0947
SS
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 {
5ec182d9
CW
1538 return 'Invalid format passed to CRM.formatMoney';
1539 }
1540 separator = result[1];
db9e0947 1541 decimal = precision ? result[2] : false;
5ec182d9
CW
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)) + '';
5ec182d9 1545 j = ((j = i.length) > 3) ? j % 3 : 0;
db9e0947
SS
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) {
567e9eea 1548 return result;
1549 }
db9e0947
SS
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 }
5ec182d9 1558 };
bba9b4f0 1559
5438399c
TO
1560 CRM.angRequires = function(name) {
1561 return CRM.angular.requires[name] || [];
1562 };
1563
bba9b4f0
CW
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 }
e4762285 1573 };
90efc417 1574
6cfd220b
CW
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
90efc417
TO
1602 // Determine if a user has a given permission.
1603 // @see CRM_Core_Resources::addPermissions
1604 CRM.checkPerm = function(perm) {
3d6e14f0 1605 return CRM.permissions && CRM.permissions[perm];
90efc417 1606 };
2cfa1092
TO
1607
1608 // Round while preserving sigfigs
b24d5a1e 1609 CRM.utils.sigfig = function(n, digits) {
2cfa1092
TO
1610 var len = ("" + n).length;
1611 var scale = Math.pow(10.0, len-digits);
1612 return Math.round(n / scale) * scale;
1613 };
4cf9188e 1614
3c68de9d
CW
1615 // Create a js Date object from a unix timestamp or a yyyy-mm-dd string
1616 CRM.utils.makeDate = function(input) {
4cf9188e
CW
1617 switch (typeof input) {
1618 case 'object':
1619 // already a date object
3c68de9d 1620 return input;
4cf9188e
CW
1621
1622 case 'string':
d3cbd0a5
CW
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));
4cf9188e
CW
1628
1629 case 'number':
1630 // convert unix timestamp
3c68de9d 1631 return new Date(input * 1000);
4cf9188e 1632 }
3c68de9d
CW
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)) : '';
232785ea 1640 };
8cc43365
CW
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
279877e8
CW
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
4b513f23 1659})(jQuery, _);