Merge pull request #6643 from davecivicrm/CRM-17031
[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
6a488035
TO
147/**
148 * Function to change button text and disable one it is clicked
353ea873 149 * @deprecated
6a488035
TO
150 * @param obj object - the button clicked
151 * @param formID string - the id of the form being submitted
152 * @param string procText - button text after user clicks it
353ea873 153 * @return bool
6a488035 154 */
0f5816a6 155var submitcount = 0;
c6edd786 156/* Changes button label on submit, and disables button after submit for newer browsers.
157 Puts up alert for older browsers. */
0f5816a6
KJ
158function submitOnce(obj, formId, procText) {
159 // if named button clicked, change text
160 if (obj.value != null) {
42579c28 161 cj('input[name=' + obj.name + ']').val(procText + " ...");
0f5816a6 162 }
47ea29e3 163 cj(obj).closest('form').attr('data-warn-changes', 'false');
0f5816a6 164 if (document.getElementById) { // disable submit button for newer browsers
42579c28 165 cj('input[name=' + obj.name + ']').attr("disabled", true);
0f5816a6
KJ
166 document.getElementById(formId).submit();
167 return true;
168 }
169 else { // for older browsers
170 if (submitcount == 0) {
171 submitcount++;
172 return true;
173 }
174 else {
175 alert("Your request is currently being processed ... Please wait.");
176 return false;
6a488035 177 }
0f5816a6 178 }
6a488035 179}
6a488035 180
6a488035
TO
181/**
182 * Function to show / hide the row in optionFields
353ea873
CW
183 * @deprecated
184 * @param index string, element whose innerHTML is to hide else will show the hidden row.
6a488035 185 */
0f5816a6
KJ
186function showHideRow(index) {
187 if (index) {
188 cj('tr#optionField_' + index).hide();
189 if (cj('table#optionField tr:hidden:first').length) {
190 cj('div#optionFieldLink').show();
6a488035 191 }
0f5816a6
KJ
192 }
193 else {
194 cj('table#optionField tr:hidden:first').show();
195 if (!cj('table#optionField tr:hidden:last').length) {
196 cj('div#optionFieldLink').hide();
197 }
198 }
199 return false;
6a488035
TO
200}
201
2b3ddf6e
CW
202/* jshint ignore:end */
203
1711f01c
CW
204if (!CRM.utils) CRM.utils = {};
205if (!CRM.strings) CRM.strings = {};
206if (!CRM.vars) CRM.vars = {};
6a488035 207
4b513f23 208(function ($, _, undefined) {
7553cf23 209 "use strict";
0d75c29c 210 /* jshint validthis: true */
d664f648 211
3f586963
CW
212 // Theme classes for unattached elements
213 $.fn.select2.defaults.dropdownCssClass = $.ui.dialog.prototype.options.dialogClass = 'crm-container';
214
47f21f3a
CW
215 // https://github.com/ivaynberg/select2/pull/2090
216 $.fn.select2.defaults.width = 'resolve';
217
e20523a8
CW
218 // Workaround for https://github.com/ivaynberg/select2/issues/1246
219 $.ui.dialog.prototype._allowInteraction = function(e) {
e5b38290 220 return !!$(e.target).closest('.ui-dialog, .ui-datepicker, .select2-drop, .cke_dialog, #civicrm-menu').length;
e20523a8
CW
221 };
222
9f8862e1
CW
223 // Implements jQuery hook.prop
224 $.propHooks.disabled = {
225 set: function (el, value, name) {
226 // Sync button enabled status with wrapper css
227 if ($(el).is('span.crm-button > input.crm-form-submit')) {
228 $(el).parent().toggleClass('crm-button-disabled', !!value);
229 }
230 // Sync button enabled status with dialog button
231 if ($(el).is('.ui-dialog input.crm-form-submit')) {
9bce560a
CW
232 $(el).closest('.ui-dialog').find('.ui-dialog-buttonset button[data-identifier='+ $(el).attr('name') +']').prop('disabled', value);
233 }
234 if ($(el).is('.crm-form-date-wrapper .crm-hidden-date')) {
235 $(el).siblings().prop('disabled', value);
9f8862e1
CW
236 }
237 }
238 };
239
475e9f44
CW
240 /**
241 * Populate a select list, overwriting the existing options except for the placeholder.
581c7be2 242 * @param select jquery selector - 1 or more select elements
475e9f44 243 * @param options array in format returned by api.getoptions
b7ceb253
CW
244 * @param placeholder string|bool - new placeholder or false (default) to keep the old one
245 * @param value string|array - will silently update the element with new value without triggering change
475e9f44 246 */
b7ceb253 247 CRM.utils.setOptions = function(select, options, placeholder, value) {
581c7be2 248 $(select).each(function() {
475e9f44
CW
249 var
250 $elect = $(this),
b7ceb253
CW
251 val = value || $elect.val() || [],
252 opts = placeholder || placeholder === '' ? '' : '[value!=""]';
23e8a31b 253 $elect.find('option' + opts).remove();
b7ceb253 254 var newOptions = CRM.utils.renderOptions(options, val);
1d07e7ab 255 if (typeof placeholder === 'string') {
581c7be2
CW
256 if ($elect.is('[multiple]')) {
257 select.attr('placeholder', placeholder);
1d07e7ab
CW
258 } else {
259 newOptions = '<option value="">' + placeholder + '</option>' + newOptions;
260 }
261 }
262 $elect.append(newOptions);
b7ceb253
CW
263 if (!value) {
264 $elect.trigger('crmOptionsUpdated', $.extend({}, options)).trigger('change');
265 }
475e9f44
CW
266 });
267 };
268
b7ceb253
CW
269 /**
270 * Render an option list
8decea37
CW
271 * @param options {array}
272 * @param val {string} default value
273 * @param escapeHtml {bool}
b7ceb253
CW
274 * @return string
275 */
8decea37
CW
276 CRM.utils.renderOptions = function(options, val, escapeHtml) {
277 var rendered = '',
278 esc = escapeHtml === false ? _.identity : _.escape;
b7ceb253
CW
279 if (!$.isArray(val)) {
280 val = [val];
281 }
282 _.each(options, function(option) {
283 if (option.children) {
8decea37 284 rendered += '<optgroup label="' + esc(option.value) + '">' +
52e6588d
CW
285 CRM.utils.renderOptions(option.children, val) +
286 '</optgroup>';
b7ceb253
CW
287 } else {
288 var selected = ($.inArray('' + option.key, val) > -1) ? 'selected="selected"' : '';
8decea37 289 rendered += '<option value="' + esc(option.key) + '"' + selected + '>' + esc(option.value) + '</option>';
b7ceb253 290 }
475e9f44 291 });
b7ceb253 292 return rendered;
475e9f44
CW
293 };
294
1d07e7ab
CW
295 function chainSelect() {
296 var $form = $(this).closest('form'),
297 $target = $('select[data-name="' + $(this).data('target') + '"]', $form),
298 data = $target.data(),
299 val = $(this).val();
300 $target.prop('disabled', true);
301 if ($target.is('select.crm-chain-select-control')) {
302 $('select[data-name="' + $target.data('target') + '"]', $form).prop('disabled', true).blur();
303 }
304 if (!(val && val.length)) {
305 CRM.utils.setOptions($target.blur(), [], data.emptyPrompt);
306 } else {
307 $target.addClass('loading');
308 $.getJSON(CRM.url(data.callback), {_value: val}, function(vals) {
309 $target.prop('disabled', false).removeClass('loading');
310 CRM.utils.setOptions($target, vals || [], (vals && vals.length ? data.selectPrompt : data.nonePrompt));
311 });
312 }
313 }
314
52e6588d
CW
315 /**
316 * Compare Form Input values against cached initial value.
317 *
318 * @return {Boolean} true if changes have been made.
319 */
3e201321 320 CRM.utils.initialValueChanged = function(el) {
88e9380e 321 var isDirty = false;
d4fa3633 322 $(':input:visible, .select2-container:visible+:input:hidden', el).not('[type=submit], [type=button], .crm-action-menu, :disabled').each(function () {
603f899a
CW
323 var
324 initialValue = $(this).data('crm-initial-value'),
325 currentValue = $(this).is(':checkbox, :radio') ? $(this).prop('checked') : $(this).val();
3c0624e2 326 // skip change of value for submit buttons
603f899a 327 if (initialValue !== undefined && !_.isEqual(initialValue, currentValue)) {
88e9380e
CW
328 isDirty = true;
329 }
3e201321 330 });
331 return isDirty;
8d36b801 332 };
52e6588d 333
b1fc510d
CW
334 /**
335 * This provides defaults for ui.dialog which either need to be calculated or are different from global defaults
336 *
337 * @param settings
338 * @returns {*}
339 */
340 CRM.utils.adjustDialogDefaults = function(settings) {
341 settings = $.extend({width: '65%', height: '65%', modal: true}, settings || {});
342 // Support relative height
343 if (typeof settings.height === 'string' && settings.height.indexOf('%') > 0) {
344 settings.height = parseInt($(window).height() * (parseFloat(settings.height)/100), 10);
345 }
346 // Responsive adjustment - increase percent width on small screens
347 if (typeof settings.width === 'string' && settings.width.indexOf('%') > 0) {
348 var screenWidth = $(window).width(),
349 percentage = parseInt(settings.width.replace('%', ''), 10),
350 gap = 100-percentage;
351 if (screenWidth < 701) {
352 settings.width = '100%';
353 }
354 else if (screenWidth < 1400) {
355 settings.width = '' + parseInt(percentage+gap-((screenWidth - 700)/7*(gap)/100), 10) + '%';
356 }
357 }
358 return settings;
359 };
52e6588d 360
ba4fb2b2 361 /**
353ea873 362 * Wrapper for select2 initialization function; supplies defaults
a88cf11a 363 * @param options object
ba4fb2b2 364 */
a88cf11a 365 $.fn.crmSelect2 = function(options) {
4cd02904
CW
366 if (options === 'destroy') {
367 return $(this).each(function() {
368 $(this)
369 .removeClass('crm-ajax-select')
370 .select2('destroy');
371 });
372 }
a88cf11a
CW
373 return $(this).each(function () {
374 var
375 $el = $(this),
a243158e 376 settings = {allowClear: !$el.hasClass('required')};
a88cf11a
CW
377 // quickform doesn't support optgroups so here's a hack :(
378 $('option[value^=crm_optgroup]', this).each(function () {
379 $(this).nextUntil('option[value^=crm_optgroup]').wrapAll('<optgroup label="' + $(this).text() + '" />');
380 $(this).remove();
381 });
47358d92 382
383 // quickform does not support disabled option, so yet another hack to
384 // add disabled property for option values
711da13f 385 $('option[value^=crm_disabled_opt]', this).attr('disabled', 'disabled');
27a6b676 386
a88cf11a
CW
387 // Defaults for single-selects
388 if ($el.is('select:not([multiple])')) {
a243158e 389 settings.minimumResultsForSearch = 10;
a88cf11a 390 if ($('option:first', this).val() === '') {
a243158e 391 settings.placeholderOption = 'first';
a88cf11a 392 }
ba4fb2b2 393 }
a243158e
CW
394 $.extend(settings, $el.data('select-params') || {}, options || {});
395 if (settings.ajax) {
396 $el.addClass('crm-ajax-select');
397 }
398 $el.select2(settings);
a88cf11a
CW
399 });
400 };
401
402 /**
353ea873 403 * @see CRM_Core_Form::addEntityRef for docs
a88cf11a
CW
404 * @param options object
405 */
406 $.fn.crmEntityRef = function(options) {
4cd02904
CW
407 if (options === 'destroy') {
408 return $(this).each(function() {
409 var entity = $(this).data('api-entity') || '';
410 $(this)
411 .off('.crmEntity')
412 .removeClass('crm-form-entityref crm-' + entity.toLowerCase() + '-ref')
413 .crmSelect2('destroy');
414 });
415 }
a88cf11a
CW
416 options = options || {};
417 options.select = options.select || {};
418 return $(this).each(function() {
419 var
4c993609 420 $el = $(this).off('.crmEntity'),
a88cf11a
CW
421 entity = options.entity || $el.data('api-entity') || 'contact',
422 selectParams = {};
423 $el.data('api-entity', entity);
424 $el.data('select-params', $.extend({}, $el.data('select-params') || {}, options.select));
425 $el.data('api-params', $.extend({}, $el.data('api-params') || {}, options.api));
a4799f04 426 $el.data('create-links', options.create || $el.data('create-links'));
b7ceb253 427 $el.addClass('crm-form-entityref crm-' + entity.toLowerCase() + '-ref');
ba4fb2b2 428 var settings = {
b7ceb253 429 // Use select2 ajax helper instead of CRM.api3 because it provides more value
ba4fb2b2
CW
430 ajax: {
431 url: CRM.url('civicrm/ajax/rest'),
432 data: function (input, page_num) {
b7ceb253 433 var params = getEntityRefApiParams($el);
ba4fb2b2
CW
434 params.input = input;
435 params.page_num = page_num;
436 return {
437 entity: $el.data('api-entity'),
438 action: 'getlist',
439 json: JSON.stringify(params)
440 };
441 },
442 results: function(data) {
443 return {more: data.more_results, results: data.values || []};
444 }
445 },
a88cf11a 446 minimumInputLength: 1,
3c0b6a40 447 formatResult: CRM.utils.formatSelect2Result,
ba4fb2b2 448 formatSelection: function(row) {
8a938c69 449 return (row.prefix !== undefined ? row.prefix + ' ' : '') + row.label + (row.suffix !== undefined ? ' ' + row.suffix : '');
ba4fb2b2
CW
450 },
451 escapeMarkup: function (m) {return m;},
a88cf11a
CW
452 initSelection: function($el, callback) {
453 var
454 multiple = !!$el.data('select-params').multiple,
455 val = $el.val(),
456 stored = $el.data('entity-value') || [];
457 if (val === '') {
458 return;
459 }
460 // If we already have this data, just return it
461 if (!_.xor(val.split(','), _.pluck(stored, 'id')).length) {
462 callback(multiple ? stored : stored[0]);
463 } else {
78b203e5 464 var params = $.extend({}, $el.data('api-params') || {}, {id: val});
a88cf11a 465 CRM.api3($el.data('api-entity'), 'getlist', params).done(function(result) {
d2b4810b
CW
466 callback(multiple ? result.values : result.values[0]);
467 // Trigger change (store data to avoid an infinite loop of lookups)
468 $el.data('entity-value', result.values).trigger('change');
a88cf11a
CW
469 });
470 }
ba4fb2b2
CW
471 }
472 };
4c993609 473 // Create new items inline - works for tags
b7ceb253 474 if ($el.data('create-links') && entity.toLowerCase() === 'tag') {
4c993609
CW
475 selectParams.createSearchChoice = function(term, data) {
476 if (!_.findKey(data, {label: term})) {
477 return {id: "0", term: term, label: term + ' (' + ts('new tag') + ')'};
478 }
479 };
e4f4dc22 480 selectParams.tokenSeparators = [','];
4c993609 481 selectParams.createSearchChoicePosition = 'bottom';
05b21c58 482 $el.on('select2-selecting.crmEntity', function(e) {
4c993609 483 if (e.val === "0") {
a2c28a94 484 // Create a new term
4c993609
CW
485 e.object.label = e.object.term;
486 CRM.api3(entity, 'create', $.extend({name: e.object.term}, $el.data('api-params').params || {}))
487 .done(function(created) {
488 var
4c993609
CW
489 val = $el.select2('val'),
490 data = $el.select2('data'),
491 item = {id: created.id, label: e.object.term};
492 if (val === "0") {
e4f4dc22 493 $el.select2('data', item, true);
4c993609
CW
494 }
495 else if ($.isArray(val) && $.inArray("0", val) > -1) {
496 _.remove(data, {id: "0"});
497 data.push(item);
e4f4dc22 498 $el.select2('data', data, true);
4c993609
CW
499 }
500 });
501 }
502 });
b7ceb253
CW
503 }
504 else {
a88cf11a
CW
505 selectParams.formatInputTooShort = function() {
506 var txt = $el.data('select-params').formatInputTooShort || $.fn.select2.defaults.formatInputTooShort.call(this);
cdc8d05f 507 txt += renderEntityRefFilters($el) + renderEntityRefCreateLinks($el);
ba4fb2b2
CW
508 return txt;
509 };
a88cf11a 510 selectParams.formatNoMatches = function() {
ba4fb2b2 511 var txt = $el.data('select-params').formatNoMatches || $.fn.select2.defaults.formatNoMatches;
cdc8d05f 512 txt += renderEntityRefFilters($el) + renderEntityRefCreateLinks($el);
b7ceb253 513 return txt;
ba4fb2b2 514 };
4c993609 515 $el.on('select2-open.crmEntity', function() {
ba4fb2b2 516 var $el = $(this);
b7ceb253
CW
517 loadEntityRefFilterOptions($el);
518 $('#select2-drop')
519 .off('.crmEntity')
520 .on('click.crmEntity', 'a.crm-add-entity', function(e) {
521 $el.select2('close');
522 CRM.loadForm($(this).attr('href'), {
776ff7a0 523 dialog: {width: 500, height: 220}
b7ceb253
CW
524 }).on('crmFormSuccess', function(e, data) {
525 if (data.status === 'success' && data.id) {
526 CRM.status(ts('%1 Created', {1: data.label}));
527 if ($el.select2('container').hasClass('select2-container-multi')) {
528 var selection = $el.select2('data');
529 selection.push(data);
530 $el.select2('data', selection, true);
531 } else {
532 $el.select2('data', data, true);
533 }
c92f6436 534 }
b7ceb253
CW
535 });
536 return false;
537 })
538 .on('change.crmEntity', 'select.crm-entityref-filter-value', function() {
539 var filter = $el.data('user-filter') || {};
540 filter.value = $(this).val();
541 $(this).toggleClass('active', !!filter.value);
542 $el.data('user-filter', filter);
543 if (filter.value) {
544 // Once a filter has been chosen, rerender create links and refocus the search box
545 $el.select2('close');
546 $el.select2('open');
ba4fb2b2 547 }
b7ceb253
CW
548 })
549 .on('change.crmEntity', 'select.crm-entityref-filter-key', function() {
550 var filter = $el.data('user-filter') || {};
551 filter.key = $(this).val();
552 $(this).toggleClass('active', !!filter.key);
553 $el.data('user-filter', filter);
554 loadEntityRefFilterOptions($el);
ba4fb2b2 555 });
ba4fb2b2
CW
556 });
557 }
05b21c58 558 $el.crmSelect2($.extend(settings, $el.data('select-params'), selectParams));
a88cf11a 559 });
ba4fb2b2
CW
560 };
561
b7ceb253
CW
562 /**
563 * Combine api-params with user-filter
564 * @param $el
565 * @returns {*}
566 */
567 function getEntityRefApiParams($el) {
568 var
569 params = $.extend({params: {}}, $el.data('api-params') || {}),
570 // Prevent original data from being modified - $.extend and _.clone don't cut it, they pass nested objects by reference!
571 combined = _.cloneDeep(params),
572 filter = $.extend({}, $el.data('user-filter') || {});
573 if (filter.key && filter.value) {
574 // Special case for contact type/sub-type combo
bee6039a
CW
575 if (filter.key === 'contact_type' && (filter.value.indexOf('__') > 0)) {
576 combined.params.contact_type = filter.value.split('__')[0];
577 combined.params.contact_sub_type = filter.value.split('__')[1];
b7ceb253 578 } else {
cdc8d05f
CW
579 // Allow json-encoded api filters e.g. {"BETWEEN":[123,456]}
580 combined.params[filter.key] = filter.value.charAt(0) === '{' ? $.parseJSON(filter.value) : filter.value;
b7ceb253
CW
581 }
582 }
583 return combined;
584 }
585
9bce560a
CW
586 function copyAttributes($source, $target, attributes) {
587 _.each(attributes, function(name) {
588 if ($source.attr(name)) {
589 $target.attr(name, $source.attr(name));
590 }
591 });
592 }
593
594 $.fn.crmDatepicker = function(options) {
595 return $(this).each(function() {
596 if ($(this).is('.crm-form-date-wrapper .crm-hidden-date')) {
597 // Already initialized
598 return;
599 }
600 var
601 $dataField = $(this).wrap('<span class="crm-form-date-wrapper" />'),
602 settings = $.extend({}, $dataField.data('datepicker') || {}, options || {}),
603 $dateField = $(),
604 $timeField = $(),
605 $clearLink = $();
606
607 if (settings.allowClear !== undefined ? settings.allowClear : !$dataField.hasClass('required')) {
608 $clearLink = $('<a class="crm-hover-button crm-clear-link" title="'+ ts('Clear') +'"><span class="icon ui-icon-close"></span></a>')
609 .insertAfter($dataField);
610 }
611 if (settings.time !== false) {
612 $timeField = $('<input>').insertAfter($dataField);
613 copyAttributes($dataField, $timeField, ['class', 'disabled']);
614 $timeField
615 .addClass('crm-form-text crm-form-time')
616 .attr('placeholder', $dataField.attr('time-placeholder') === undefined ? ts('Time') : $dataField.attr('time-placeholder'))
617 .change(updateDataField)
618 .timeEntry({
619 spinnerImage: '',
0d05e8a1 620 show24Hours: settings.time === true || settings.time === undefined ? CRM.config.timeIs24Hr : settings.time == '24'
9bce560a
CW
621 });
622 }
623 if (settings.date !== false) {
624 $dateField = $('<input>').insertAfter($dataField);
625 copyAttributes($dataField, $dateField, ['placeholder', 'style', 'class', 'disabled']);
626 $dateField.addClass('crm-form-text crm-form-date');
627 settings.dateFormat = settings.dateFormat || CRM.config.dateInputFormat;
628 settings.changeMonth = _.includes('m', settings.dateFormat);
629 settings.changeYear = _.includes('y', settings.dateFormat);
630 $dateField.datepicker(settings).change(updateDataField);
631 }
8e2e2658
CW
632 // Rudimentary validation. TODO: Roll into use of jQUery validate and ui.datepicker.validation
633 function isValidDate() {
634 try {
635 $.datepicker.parseDate(settings.dateFormat, $dateField.val());
636 return true;
637 } catch (e) {
638 return false;
639 }
640 }
9bce560a 641 function updateInputFields(e, context) {
ac5009c1
CW
642 var val = $dataField.val(),
643 time = null;
9bce560a 644 if (context !== 'userInput' && context !== 'crmClear') {
ac5009c1
CW
645 if ($dateField.length) {
646 $dateField.datepicker('setDate', _.includes(val, '-') ? $.datepicker.parseDate('yy-mm-dd', val) : null);
647 }
648 if ($timeField.length) {
649 if (val.length === 8) {
650 time = val;
651 } else if (val.length === 19) {
652 time = val.split(' ')[1];
9bce560a 653 }
ac5009c1 654 $timeField.timeEntry('setTime', time);
9bce560a
CW
655 }
656 }
ac5009c1 657 $clearLink.css('visibility', val ? 'visible' : 'hidden');
9bce560a
CW
658 }
659 function updateDataField(e, context) {
8e2e2658 660 // The crmClear event wipes all the field values anyway, so no need to respond
9bce560a
CW
661 if (context !== 'crmClear') {
662 var val = '';
663 if ($dateField.val()) {
8e2e2658
CW
664 if (isValidDate()) {
665 val = $.datepicker.formatDate('yy-mm-dd', $dateField.datepicker('getDate'));
666 $dateField.removeClass('crm-error');
667 } else {
668 $dateField.addClass('crm-error');
669 }
9bce560a
CW
670 }
671 if ($timeField.val()) {
ac5009c1 672 val += (val ? ' ' : '') + $timeField.timeEntry('getTime').toTimeString().substr(0, 8);
9bce560a
CW
673 }
674 $dataField.val(val).trigger('change', ['userInput']);
675 }
676 }
677 $dataField.hide().addClass('crm-hidden-date').on('change', updateInputFields);
678 updateInputFields();
679 });
680 };
681
7d12de7f
JL
682 $.fn.crmAjaxTable = function() {
683 return $(this).each(function() {
684 //Declare the defaults for DataTables
685 var defaults = {
686 "processing": true,
687 "serverSide": true,
688 "dom": '<"crm-datatable-pager-top"lfp>rt<"crm-datatable-pager-bottom"ip>',
689 "pageLength": 25,
690 "drawCallback": function(settings) {
691 //Add data attributes to cells
692 $('thead th', settings.nTable).each( function( index ) {
693 $.each(this.attributes, function() {
694 if(this.name.match("^cell-")) {
cf595fa5 695 var cellAttr = this.name.substring(5);
1dc5cc17 696 var cellValue = this.value;
cf595fa5
JL
697 $('tbody tr', settings.nTable).each( function() {
698 $('td:eq('+ index +')', this).attr( cellAttr, cellValue );
699 });
7d12de7f
JL
700 }
701 });
702 });
703 //Reload table after draw
704 $(settings.nTable).trigger('crmLoad');
705 }
706 };
707 //Include any table specific data
708 var settings = $.extend(true, defaults, $(this).data('table'));
709 //Make the DataTables call
710 $(this).DataTable(settings);
711 });
712 };
713
3c0b6a40 714 CRM.utils.formatSelect2Result = function (row) {
88881f79 715 var markup = '<div class="crm-select2-row">';
ff88d165 716 if (row.image !== undefined) {
88881f79 717 markup += '<div class="crm-select2-image"><img src="' + row.image + '"/></div>';
ff88d165 718 }
54bee7df 719 else if (row.icon_class) {
88881f79 720 markup += '<div class="crm-select2-icon"><div class="crm-icon ' + row.icon_class + '-icon"></div></div>';
54bee7df 721 }
8a938c69
CW
722 markup += '<div><div class="crm-select2-row-label '+(row.label_class || '')+'">' +
723 (row.prefix !== undefined ? row.prefix + ' ' : '') + row.label + (row.suffix !== undefined ? ' ' + row.suffix : '') +
724 '</div>' +
725 '<div class="crm-select2-row-description">';
88881f79
CW
726 $.each(row.description || [], function(k, text) {
727 markup += '<p>' + text + '</p>';
728 });
729 markup += '</div></div></div>';
ff88d165 730 return markup;
3c0b6a40 731 };
a4799f04 732
b7ceb253 733 function renderEntityRefCreateLinks($el) {
a4799f04
CW
734 var
735 createLinks = $el.data('create-links'),
b7ceb253
CW
736 params = getEntityRefApiParams($el).params,
737 markup = '<div class="crm-entityref-links">';
738 if (!createLinks || $el.data('api-entity').toLowerCase() !== 'contact') {
739 return '';
740 }
a4799f04 741 if (createLinks === true) {
b7ceb253 742 createLinks = params.contact_type ? _.where(CRM.config.entityRef.contactCreate, {type: params.contact_type}) : CRM.config.entityRef.contactCreate;
a4799f04 743 }
a4799f04 744 _.each(createLinks, function(link) {
79ae07d9 745 markup += ' <a class="crm-add-entity crm-hover-button" href="' + link.url + '">';
a4799f04
CW
746 if (link.type) {
747 markup += '<span class="icon ' + link.type + '-profile-icon"></span> ';
79ae07d9
CW
748 }
749 markup += link.label + '</a>';
750 });
b7ceb253
CW
751 markup += '</div>';
752 return markup;
753 }
754
755 function getEntityRefFilters($el) {
756 var
757 entity = $el.data('api-entity').toLowerCase(),
758 filters = $.extend([], CRM.config.entityRef.filters[entity] || []),
759 filter = $el.data('user-filter') || {},
760 params = $.extend({params: {}}, $el.data('api-params') || {}).params,
761 result = [];
762 $.each(filters, function() {
763 if (typeof params[this.key] === 'undefined') {
764 result.push(this);
765 }
766 else if (this.key == 'contact_type' && typeof params.contact_sub_type === 'undefined') {
767 this.options = _.remove(this.options, function(option) {
bee6039a 768 return option.key.indexOf(params.contact_type + '__') === 0;
b7ceb253
CW
769 });
770 result.push(this);
771 }
772 });
773 return result;
774 }
775
776 function renderEntityRefFilters($el) {
777 var
778 filters = getEntityRefFilters($el),
779 filter = $el.data('user-filter') || {},
780 filterSpec = filter.key ? _.find(filters, {key: filter.key}) : null;
781 if (!filters.length) {
782 return '';
783 }
784 var markup = '<div class="crm-entityref-filters">' +
785 '<select class="crm-entityref-filter-key' + (filter.key ? ' active' : '') + '">' +
52e6588d
CW
786 '<option value="">' + ts('Refine search...') + '</option>' +
787 CRM.utils.renderOptions(filters, filter.key) +
b7ceb253
CW
788 '</select> &nbsp; ' +
789 '<select class="crm-entityref-filter-value' + (filter.key ? ' active"' : '"') + (filter.key ? '' : ' style="display:none;"') + '>' +
52e6588d 790 '<option value="">' + ts('- select -') + '</option>';
b7ceb253
CW
791 if (filterSpec && filterSpec.options) {
792 markup += CRM.utils.renderOptions(filterSpec.options, filter.value);
793 }
794 markup += '</select></div>';
79ae07d9 795 return markup;
a4799f04 796 }
ff88d165 797
b7ceb253
CW
798 /**
799 * Fetch options for a filter (via ajax if necessary) and populate the appropriate select list
800 * @param $el
801 */
802 function loadEntityRefFilterOptions($el) {
803 var
804 filters = getEntityRefFilters($el),
805 filter = $el.data('user-filter') || {},
806 filterSpec = filter.key ? _.find(filters, {key: filter.key}) : null,
807 $valField = $('.crm-entityref-filter-value', '#select2-drop');
808 if (filterSpec) {
809 $valField.show().val('');
810 if (filterSpec.options) {
811 CRM.utils.setOptions($valField, filterSpec.options, false, filter.value);
812 } else {
813 $valField.prop('disabled', true);
bee6039a 814 CRM.api3(filterSpec.entity || $el.data('api-entity'), 'getoptions', {field: filter.key, context: 'search', sequential: 1})
b7ceb253
CW
815 .done(function(result) {
816 var entity = $el.data('api-entity').toLowerCase(),
817 globalFilterSpec = _.find(CRM.config.entityRef.filters[entity], {key: filter.key}) || {};
818 // Store options globally so we don't have to look them up again
819 globalFilterSpec.options = result.values;
820 $valField.prop('disabled', false);
821 CRM.utils.setOptions($valField, result.values);
822 $valField.val(filter.value || '');
823 });
824 }
825 } else {
826 $valField.hide();
827 }
828 }
829
1136a401 830 //CRM-15598 - Override url validator method to allow relative url's (e.g. /index.htm)
831 $.validator.addMethod("url", function(value, element) {
832 if (/^\//.test(value)) {
833 // Relative url: prepend dummy path for validation.
834 value = 'http://domain.tld' + value;
835 }
836 // From jQuery Validation Plugin v1.12.0
837 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);
838 });
839
3d527838
CW
840 /**
841 * Wrapper for jQuery validate initialization function; supplies defaults
3d527838
CW
842 */
843 $.fn.crmValidate = function(params) {
844 return $(this).each(function () {
845 var that = this,
846 settings = $.extend({}, CRM.validate._defaults, CRM.validate.params);
847 $(this).validate(settings);
848 // Call any post-initialization callbacks
849 if (CRM.validate.functions && CRM.validate.functions.length) {
850 $.each(CRM.validate.functions, function(i, func) {
851 func.call(that);
852 });
853 }
854 });
b7ceb253 855 };
3d527838 856
f7b92fcd 857 // Initialize widgets
eb90857a
CW
858 $(document)
859 .on('crmLoad', function(e) {
860 $('table.row-highlight', e.target)
861 .off('.rowHighlight')
7e13d44e
CW
862 .on('change.rowHighlight', 'input.select-row, input.select-rows', function (e, data) {
863 var filter, $table = $(this).closest('table');
eb90857a 864 if ($(this).hasClass('select-rows')) {
7e13d44e
CW
865 filter = $(this).prop('checked') ? ':not(:checked)' : ':checked';
866 $('input.select-row' + filter, $table).prop('checked', $(this).prop('checked')).trigger('change', 'master-selected');
eb90857a
CW
867 }
868 else {
7e13d44e
CW
869 $(this).closest('tr').toggleClass('crm-row-selected', $(this).prop('checked'));
870 if (data !== 'master-selected') {
871 $('input.select-rows', $table).prop('checked', $(".select-row:not(':checked')", $table).length < 1);
872 }
eb90857a 873 }
eb90857a
CW
874 })
875 .find('input.select-row:checked').parents('tr').addClass('crm-row-selected');
7d12de7f
JL
876 $('table.crm-sortable', e.target).DataTable();
877 $('table.crm-ajax-table', e.target).crmAjaxTable();
82661158
JP
878 if ($("input:radio[name=radio_ts]").size() == 1) {
879 $("input:radio[name=radio_ts]").prop("checked", true);
880 }
5f34e50b
CW
881 $('.crm-select2:not(.select2-offscreen, .select2-container)', e.target).crmSelect2();
882 $('.crm-form-entityref:not(.select2-offscreen, .select2-container)', e.target).crmEntityRef();
1d07e7ab 883 $('select.crm-chain-select-control', e.target).off('.chainSelect').on('change.chainSelect', chainSelect);
3e201321 884 // Cache Form Input initial values
88e9380e 885 $('form[data-warn-changes] :input', e.target).each(function() {
603f899a 886 $(this).data('crm-initial-value', $(this).is(':checkbox, :radio') ? $(this).prop('checked') : $(this).val());
3e201321 887 });
66659cd7 888 $('textarea.crm-form-wysiwyg', e.target)
f91b1c0c
CW
889 .not('.crm-wysiwyg-enabled')
890 .addClass('crm-wysiwyg-enabled')
4d49c3a2
TC
891 .each(function() {
892 if ($(this).hasClass("collapsed")) {
f91b1c0c 893 CRM.wysiwyg.createCollapsed(this);
4d49c3a2
TC
894 } else {
895 CRM.wysiwyg.create(this);
896 }
897 });
eb90857a 898 })
eb90857a 899 .on('dialogopen', function(e) {
f292709b
CW
900 var $el = $(e.target);
901 // Modal dialogs should disable scrollbars
902 if ($el.dialog('option', 'modal')) {
903 $el.addClass('modal-dialog');
eb90857a
CW
904 $('body').css({overflow: 'hidden'});
905 }
f292709b 906 // Add resize button
a243158e 907 if ($el.parent().hasClass('crm-container') && $el.dialog('option', 'resizable')) {
77a8d7f9 908 $el.parent().find('.ui-dialog-titlebar').append($('<button class="crm-dialog-titlebar-resize ui-dialog-titlebar-close" title="'+ts('Toggle fullscreen')+'" style="right:2em;"/>').button({icons: {primary: 'ui-icon-newwin'}, text: false}));
f292709b
CW
909 $('.crm-dialog-titlebar-resize', $el.parent()).click(function(e) {
910 if ($el.data('origSize')) {
911 $el.dialog('option', $el.data('origSize'));
912 $el.data('origSize', null);
913 } else {
28d510ab 914 var menuHeight = $('#civicrm-menu').outerHeight();
f292709b 915 $el.data('origSize', {
28d510ab 916 position: {my: 'center', at: 'center center+' + (menuHeight / 2), of: window},
f292709b
CW
917 width: $el.dialog('option', 'width'),
918 height: $el.dialog('option', 'height')
919 });
f2f191fe 920 $el.dialog('option', {width: '100%', height: ($(window).height() - menuHeight), position: {my: "top", at: "top+"+menuHeight, of: window}});
f292709b 921 }
02cd9764 922 $el.trigger('dialogresize');
f292709b
CW
923 e.preventDefault();
924 });
925 }
eb90857a
CW
926 })
927 .on('dialogclose', function(e) {
f292709b 928 // Restore scrollbars when closing modal
5a6148a0 929 if ($('.ui-dialog .modal-dialog:visible').not(e.target).length < 1) {
eb90857a
CW
930 $('body').css({overflow: ''});
931 }
afc021d8 932 })
933 .on('submit', function(e) {
f582fc8f 934 // CRM-14353 - disable changes warn when submitting a form
abb6e044 935 $('[data-warn-changes]').attr('data-warn-changes', 'false');
52e6588d 936 });
f582fc8f
CW
937
938 // CRM-14353 - Warn of unsaved changes for forms which have opted in
939 window.onbeforeunload = function() {
18469bf2 940 if (CRM.utils.initialValueChanged($('form[data-warn-changes=true]:visible'))) {
f582fc8f 941 return ts('You have unsaved changes.');
0f5816a6 942 }
f582fc8f 943 };
6a488035 944
0f5816a6 945 $.fn.crmtooltip = function () {
2c29c2ac
RN
946 $(document)
947 .on('mouseover', 'a.crm-summary-link:not(.crm-processed)', function (e) {
73ed0c3f 948 $(this).addClass('crm-processed crm-tooltip-active');
e24b17b9 949 var topDistance = e.pageY - $(window).scrollTop();
2b3ddf6e 950 if (topDistance < 300 || topDistance < $(this).children('.crm-tooltip-wrapper').height()) {
e24b17b9
CW
951 $(this).addClass('crm-tooltip-down');
952 }
953 if (!$(this).children('.crm-tooltip-wrapper').length) {
6a488035
TO
954 $(this).append('<div class="crm-tooltip-wrapper"><div class="crm-tooltip"></div></div>');
955 $(this).children().children('.crm-tooltip')
956 .html('<div class="crm-loading-element"></div>')
957 .load(this.href);
958 }
959 })
2c29c2ac 960 .on('mouseout', 'a.crm-summary-link', function () {
73ed0c3f 961 $(this).removeClass('crm-processed crm-tooltip-active crm-tooltip-down');
e24b17b9 962 })
2c29c2ac 963 .on('click', 'a.crm-summary-link', false);
6a488035
TO
964 };
965
b0ca6188 966 var helpDisplay, helpPrevious;
8e3272a1 967 CRM.help = function (title, params, url) {
55a93b02 968 if (helpDisplay && helpDisplay.close) {
b0ca6188 969 // If the same link is clicked twice, just close the display - todo use underscore method for this comparison
55a93b02
CW
970 if (helpDisplay.isOpen && helpPrevious === JSON.stringify(params)) {
971 helpDisplay.close();
b0ca6188
CW
972 return;
973 }
55a93b02 974 helpDisplay.close();
b0ca6188
CW
975 }
976 helpPrevious = JSON.stringify(params);
6a488035
TO
977 params.class_name = 'CRM_Core_Page_Inline_Help';
978 params.type = 'page';
b0ca6188 979 helpDisplay = CRM.alert('...', title, 'crm-help crm-msg-loading', {expires: 0});
8e3272a1 980 $.ajax(url || CRM.url('civicrm/ajax/inline'),
6a488035
TO
981 {
982 data: params,
983 dataType: 'html',
e24b17b9 984 success: function (data) {
6a488035
TO
985 $('#crm-notification-container .crm-help .notify-content:last').html(data);
986 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('info');
987 },
e24b17b9 988 error: function () {
6a488035
TO
989 $('#crm-notification-container .crm-help .notify-content:last').html('Unable to load help file.');
990 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('error');
991 }
992 }
993 );
994 };
8960d9b9 995 /**
7442e8f6 996 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
8960d9b9 997 */
1b2475e1 998 CRM.status = function(options, deferred) {
9a7ef94f 999 // 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
1000 if (typeof options === 'string') {
1001 return CRM.status({start: options, success: options, error: options})[deferred === 'error' ? 'reject' : 'resolve']();
8960d9b9 1002 }
1b2475e1
CW
1003 var opts = $.extend({
1004 start: ts('Saving...'),
9a7ef94f 1005 success: ts('Saved'),
47737104
CW
1006 error: function(data) {
1007 var msg = $.isPlainObject(data) && data.error_message;
1008 CRM.alert(msg || ts('Sorry an error occurred and your information was not saved'), ts('Error'), 'error');
1b2475e1
CW
1009 }
1010 }, options || {});
1011 var $msg = $('<div class="crm-status-box-outer status-start"><div class="crm-status-box-inner"><div class="crm-status-box-msg">' + opts.start + '</div></div></div>')
1012 .appendTo('body');
1013 $msg.css('min-width', $msg.width());
1014 function handle(status, data) {
1015 var endMsg = typeof(opts[status]) === 'function' ? opts[status](data) : opts[status];
1016 if (endMsg) {
1017 $msg.removeClass('status-start').addClass('status-' + status).find('.crm-status-box-msg').html(endMsg);
1018 window.setTimeout(function() {
f54254d8
TO
1019 $msg.fadeOut('slow', function() {
1020 $msg.remove();
1021 });
4bad157e
CW
1022 }, 2000);
1023 } else {
1b2475e1 1024 $msg.remove();
4bad157e 1025 }
1b2475e1
CW
1026 }
1027 return (deferred || new $.Deferred())
1028 .done(function(data) {
1029 // If the server returns an error msg call the error handler
1030 var status = $.isPlainObject(data) && (data.is_error || data.status === 'error') ? 'error' : 'success';
1031 handle(status, data);
1032 })
1033 .fail(function(data) {
1034 handle('error', data);
1035 });
8960d9b9 1036 };
6a488035 1037
beab9d1b
TO
1038 // Convert an Angular promise to a jQuery promise
1039 CRM.toJqPromise = function(aPromise) {
1040 var jqDeferred = $.Deferred();
1041 aPromise.then(
1042 function(data) { jqDeferred.resolve(data); },
1043 function(data) { jqDeferred.reject(data); }
1044 // should we also handle progress events?
1045 );
1046 return jqDeferred.promise();
1047 };
1048
705c61e9
TO
1049 CRM.toAPromise = function($q, jqPromise) {
1050 var aDeferred = $q.defer();
1051 jqPromise.then(
1052 function(data) { aDeferred.resolve(data); },
1053 function(data) { aDeferred.reject(data); }
1054 // should we also handle progress events?
1055 );
1056 return aDeferred.promise;
1057 };
1058
6a488035 1059 /**
7442e8f6 1060 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
6a488035 1061 */
0f5816a6 1062 CRM.alert = function (text, title, type, options) {
6a488035
TO
1063 type = type || 'alert';
1064 title = title || '';
1065 options = options || {};
1066 if ($('#crm-notification-container').length) {
1067 var params = {
1068 text: text,
1069 title: title,
1070 type: type
1071 };
1072 // By default, don't expire errors and messages containing links
1073 var extra = {
1074 expires: (type == 'error' || text.indexOf('<a ') > -1) ? 0 : (text ? 10000 : 5000),
1075 unique: true
1076 };
1077 options = $.extend(extra, options);
e24b17b9 1078 options.expires = options.expires === false ? 0 : parseInt(options.expires, 10);
6a488035 1079 if (options.unique && options.unique !== '0') {
0f5816a6 1080 $('#crm-notification-container .ui-notify-message').each(function () {
6a488035
TO
1081 if (title === $('h1', this).html() && text === $('.notify-content', this).html()) {
1082 $('.icon.ui-notify-close', this).click();
1083 }
1084 });
1085 }
1086 return $('#crm-notification-container').notify('create', params, options);
1087 }
1088 else {
1089 if (title.length) {
1090 text = title + "\n" + text;
1091 }
1092 alert(text);
1093 return null;
1094 }
e24b17b9 1095 };
6a488035
TO
1096
1097 /**
1098 * Close whichever alert contains the given node
1099 *
1100 * @param node
1101 */
0f5816a6 1102 CRM.closeAlertByChild = function (node) {
6a488035 1103 $(node).closest('.ui-notify-message').find('.icon.ui-notify-close').click();
e24b17b9 1104 };
6a488035
TO
1105
1106 /**
7442e8f6 1107 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
6a488035 1108 */
5fb83680 1109 CRM.confirm = function (options) {
27f190b4 1110 var dialog, url, msg, buttons = [], settings = {
a65e5f52 1111 title: ts('Confirm'),
7553cf23 1112 message: ts('Are you sure you want to continue?'),
3f4328da 1113 url: null,
0d5f99d4 1114 width: 'auto',
a8a8ddac 1115 height: 'auto',
a243158e 1116 resizable: false,
5fb83680 1117 dialogClass: 'crm-container crm-confirm',
0f5816a6 1118 close: function () {
5fb83680 1119 $(this).dialog('destroy').remove();
0f5816a6 1120 },
5fb83680
CW
1121 options: {
1122 no: ts('Cancel'),
1123 yes: ts('Continue')
1124 }
0f5816a6 1125 };
a8a8ddac
CW
1126 if (options && options.url) {
1127 settings.resizable = true;
1128 settings.height = '50%';
1129 }
5fb83680 1130 $.extend(settings, ($.isFunction(options) ? arguments[1] : options) || {});
a8a8ddac 1131 settings = CRM.utils.adjustDialogDefaults(settings);
5fb83680 1132 if (!settings.buttons && $.isPlainObject(settings.options)) {
27f190b4
CW
1133 $.each(settings.options, function(op, label) {
1134 buttons.push({
5fb83680 1135 text: label,
27f190b4
CW
1136 'data-op': op,
1137 icons: {primary: op === 'no' ? 'ui-icon-close' : 'ui-icon-check'},
5fb83680 1138 click: function() {
27f190b4 1139 var event = $.Event('crmConfirm:' + op);
5fb83680
CW
1140 $(this).trigger(event);
1141 if (!event.isDefaultPrevented()) {
1142 dialog.dialog('close');
1143 }
1144 }
1145 });
1146 });
27f190b4
CW
1147 // Order buttons so that "no" goes on the right-hand side
1148 settings.buttons = _.sortBy(buttons, 'data-op').reverse();
2a06342c 1149 }
3f4328da 1150 url = settings.url;
c0b7c815 1151 msg = url ? '' : settings.message;
5fb83680
CW
1152 delete settings.options;
1153 delete settings.message;
3f4328da 1154 delete settings.url;
c0b7c815 1155 dialog = $('<div class="crm-confirm-dialog"></div>').html(msg || '').dialog(settings);
5fb83680
CW
1156 if ($.isFunction(options)) {
1157 dialog.on('crmConfirm:yes', options);
7553cf23 1158 }
3f4328da
CW
1159 if (url) {
1160 CRM.loadPage(url, {target: dialog});
1161 }
c0b7c815
CW
1162 else {
1163 dialog.trigger('crmLoad');
3f4328da
CW
1164 }
1165 return dialog;
e24b17b9 1166 };
6a488035 1167
ed7225e6
CW
1168 /** provides a local copy of ts for a domain */
1169 CRM.ts = function(domain) {
1170 return function(message, options) {
1171 if (domain) {
1172 options = $.extend(options || {}, {domain: domain});
1173 }
f97524d9
TO
1174 return ts(message, options);
1175 };
f97524d9
TO
1176 };
1177
e3d90d6c
TO
1178 CRM.addStrings = function(domain, strings) {
1179 var bucket = (domain == 'civicrm' ? 'strings' : 'strings::' + domain);
1180 CRM[bucket] = CRM[bucket] || {};
1181 _.extend(CRM[bucket], strings);
1182 };
1183
6a488035 1184 /**
7442e8f6 1185 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
6a488035 1186 */
0f5816a6 1187 $.fn.crmError = function (text, title, options) {
6a488035
TO
1188 title = title || '';
1189 text = text || '';
1190 options = options || {};
1191
1192 var extra = {
1193 expires: 0
1194 };
1195 if ($(this).length) {
0d75c29c 1196 if (title === '') {
6a488035
TO
1197 var label = $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]').not('[generated=true]');
1198 if (label.length) {
1199 label.addClass('crm-error');
1200 var $label = label.clone();
0d75c29c 1201 if (text === '' && $('.crm-marker', $label).length > 0) {
6a488035
TO
1202 text = $('.crm-marker', $label).attr('title');
1203 }
1204 $('.crm-marker', $label).remove();
1205 title = $label.text();
1206 }
1207 }
47737104 1208 $(this).addClass('crm-error');
6a488035
TO
1209 }
1210 var msg = CRM.alert(text, title, 'error', $.extend(extra, options));
1211 if ($(this).length) {
1212 var ele = $(this);
0f5816a6
KJ
1213 setTimeout(function () {
1214 ele.one('change', function () {
f54254d8 1215 if (msg && msg.close) msg.close();
0f5816a6
KJ
1216 ele.removeClass('error');
1217 label.removeClass('crm-error');
1218 });
1219 }, 1000);
6a488035
TO
1220 }
1221 return msg;
e24b17b9 1222 };
6a488035
TO
1223
1224 // Display system alerts through js notifications
1225 function messagesFromMarkup() {
0f5816a6 1226 $('div.messages:visible', this).not('.help').not('.no-popup').each(function () {
e24b17b9 1227 var text, title = '';
6a488035
TO
1228 $(this).removeClass('status messages');
1229 var type = $(this).attr('class').split(' ')[0] || 'alert';
1230 type = type.replace('crm-', '');
1231 $('.icon', this).remove();
6a488035 1232 if ($('.msg-text', this).length > 0) {
e24b17b9 1233 text = $('.msg-text', this).html();
6a488035
TO
1234 title = $('.msg-title', this).html();
1235 }
1236 else {
e24b17b9 1237 text = $(this).html();
6a488035
TO
1238 }
1239 var options = $(this).data('options') || {};
1240 $(this).remove();
1241 // Duplicates were already removed server-side
1242 options.unique = false;
1243 CRM.alert(text, title, type, options);
1244 });
1245 // Handle qf form errors
1246 $('form :input.error', this).one('blur', function() {
1247 $('.ui-notify-message.error a.ui-notify-close').click();
1248 $(this).removeClass('error');
1249 $(this).next('span.crm-error').remove();
1250 $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]')
1251 .removeClass('crm-error')
1252 .find('.crm-error').removeClass('crm-error');
1253 });
1254 }
1255
e4762285
CW
1256 /**
1257 * Improve blockUI when used with jQuery dialog
1258 */
1adbbe2d
CW
1259 var originalBlock = $.fn.block,
1260 originalUnblock = $.fn.unblock;
1261
1262 $.fn.block = function(opts) {
1263 if ($(this).is('.ui-dialog-content')) {
1264 originalBlock.call($(this).parents('.ui-dialog'), opts);
1265 return $(this);
1266 }
1267 return originalBlock.call(this, opts);
e4762285 1268 };
1adbbe2d
CW
1269 $.fn.unblock = function(opts) {
1270 if ($(this).is('.ui-dialog-content')) {
1271 originalUnblock.call($(this).parents('.ui-dialog'), opts);
1272 return $(this);
1273 }
1274 return originalUnblock.call(this, opts);
e4762285 1275 };
1adbbe2d 1276
e4762285 1277 // Preprocess all CRM ajax calls to display messages
03a7ec8f
CW
1278 $(document).ajaxSuccess(function(event, xhr, settings) {
1279 try {
1280 if ((!settings.dataType || settings.dataType == 'json') && xhr.responseText) {
1281 var response = $.parseJSON(xhr.responseText);
1282 if (typeof(response.crmMessages) == 'object') {
1283 $.each(response.crmMessages, function(n, msg) {
1284 CRM.alert(msg.text, msg.title, msg.type, msg.options);
f54254d8 1285 });
03a7ec8f 1286 }
bba9b4f0
CW
1287 if (response.backtrace) {
1288 CRM.console('log', response.backtrace);
1289 }
82983331
CW
1290 if (typeof response.deprecated === 'string') {
1291 CRM.console('warn', response.deprecated);
1292 }
03a7ec8f
CW
1293 }
1294 }
82983331 1295 // Ignore errors thrown by parseJSON
03a7ec8f
CW
1296 catch (e) {}
1297 });
1298
0f5816a6 1299 $(function () {
fdeb4de2 1300 $.blockUI.defaults.message = null;
1adbbe2d 1301 $.blockUI.defaults.ignoreIfBlocked = true;
fdeb4de2 1302
65b86482
CW
1303 if ($('#crm-container').hasClass('crm-public')) {
1304 $.fn.select2.defaults.dropdownCssClass = $.ui.dialog.prototype.options.dialogClass = 'crm-container crm-public';
1305 }
1306
205bb8ae 1307 // Trigger crmLoad on initial content for consistency. It will also be triggered for ajax-loaded content.
8547369d 1308 $('.crm-container').trigger('crmLoad');
205bb8ae 1309
ef3309b6 1310 if ($('#crm-notification-container').length) {
6a488035
TO
1311 // Initialize notifications
1312 $('#crm-notification-container').notify();
1313 messagesFromMarkup.call($('#crm-container'));
6a488035 1314 }
ebb9197b 1315
475e9f44 1316 $('body')
5fb83680
CW
1317 // bind the event for image popup
1318 .on('click', 'a.crm-image-popup', function(e) {
1319 CRM.confirm({
1320 title: ts('Preview'),
a243158e 1321 resizable: true,
135880c6
CW
1322 // Prevent overlap with the menubar
1323 maxHeight: $(window).height() - 30,
1324 position: {my: 'center', at: 'center center+15', of: window},
e4762285 1325 message: '<div class="crm-custom-image-popup"><img style="max-width: 100%" src="' + $(this).attr('href') + '"></div>',
5fb83680
CW
1326 options: null
1327 });
1328 e.preventDefault();
475e9f44 1329 })
ebb9197b 1330
475e9f44
CW
1331 .on('click', function (event) {
1332 $('.btn-slide-active').removeClass('btn-slide-active').find('.panel').hide();
1333 if ($(event.target).is('.btn-slide')) {
1334 $(event.target).addClass('btn-slide-active').find('.panel').show();
1335 }
1336 })
d664f648 1337
4a143c04
CW
1338 // Handle clear button for form elements
1339 .on('click', 'a.crm-clear-link', function() {
9bce560a
CW
1340 $(this).css({visibility: 'hidden'}).siblings('.crm-form-radio:checked').prop('checked', false).trigger('change', ['crmClear']);
1341 $(this).siblings('input:text').val('').trigger('change', ['crmClear']);
4a143c04
CW
1342 return false;
1343 })
1344 .on('change', 'input.crm-form-radio:checked', function() {
1345 $(this).siblings('.crm-clear-link').css({visibility: ''});
843bfb07 1346 })
6a488035 1347
843bfb07 1348 // Allow normal clicking of links within accordions
cf021bc5 1349 .on('click.crmAccordions', 'div.crm-accordion-header a', function (e) {
843bfb07 1350 e.stopPropagation();
cf021bc5 1351 })
843bfb07
CW
1352 // Handle accordions
1353 .on('click.crmAccordions', '.crm-accordion-header, .crm-collapsible .collapsible-title', function (e) {
6a488035 1354 if ($(this).parent().hasClass('collapsed')) {
843bfb07 1355 $(this).next().css('display', 'none').slideDown(200);
6a488035
TO
1356 }
1357 else {
843bfb07 1358 $(this).next().css('display', 'block').slideUp(200);
6a488035
TO
1359 }
1360 $(this).parent().toggleClass('collapsed');
843bfb07 1361 e.preventDefault();
6a488035 1362 });
843bfb07
CW
1363
1364 $().crmtooltip();
1365 });
d5768733 1366
843bfb07
CW
1367 /**
1368 * Collapse or expand an accordion
1369 * @param speed
1370 */
0f5816a6
KJ
1371 $.fn.crmAccordionToggle = function (speed) {
1372 $(this).each(function () {
6a488035
TO
1373 if ($(this).hasClass('collapsed')) {
1374 $('.crm-accordion-body', this).first().css('display', 'none').slideDown(speed);
1375 }
1376 else {
1377 $('.crm-accordion-body', this).first().css('display', 'block').slideUp(speed);
1378 }
1379 $(this).toggleClass('collapsed');
1380 });
1381 };
5ec182d9
CW
1382
1383 /**
1384 * Clientside currency formatting
e4762285 1385 * @param number value
e4f46be0 1386 * @param [optional] boolean onlyNumber - if true, we return formatted amount without currency sign
e4762285 1387 * @param [optional] string format - currency representation of the number 1234.56
5ec182d9
CW
1388 * @return string
1389 */
1390 var currencyTemplate;
7f92cfa9 1391 CRM.formatMoney = function(value, onlyNumber, format) {
5ec182d9
CW
1392 var decimal, separator, sign, i, j, result;
1393 if (value === 'init' && format) {
1394 currencyTemplate = format;
1395 return;
1396 }
1397 format = format || currencyTemplate;
1398 result = /1(.?)234(.?)56/.exec(format);
1399 if (result === null) {
1400 return 'Invalid format passed to CRM.formatMoney';
1401 }
1402 separator = result[1];
1403 decimal = result[2];
1404 sign = (value < 0) ? '-' : '';
1405 //extracting the absolute value of the integer part of the number and converting to string
1406 i = parseInt(value = Math.abs(value).toFixed(2)) + '';
5ec182d9
CW
1407 j = ((j = i.length) > 3) ? j % 3 : 0;
1408 result = sign + (j ? i.substr(0, j) + separator : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + separator) + (2 ? decimal + Math.abs(value - i).toFixed(2).slice(2) : '');
567e9eea 1409 if ( onlyNumber ) {
1410 return result;
1411 }
5ec182d9
CW
1412 return format.replace(/1.*234.*56/, result);
1413 };
bba9b4f0
CW
1414
1415 CRM.console = function(method, title, msg) {
1416 if (window.console) {
1417 method = $.isFunction(console[method]) ? method : 'log';
1418 if (msg === undefined) {
1419 return console[method](title);
1420 } else {
1421 return console[method](title, msg);
1422 }
1423 }
e4762285 1424 };
90efc417
TO
1425
1426 // Determine if a user has a given permission.
1427 // @see CRM_Core_Resources::addPermissions
1428 CRM.checkPerm = function(perm) {
1429 return CRM.permissions[perm];
1430 };
2cfa1092
TO
1431
1432 // Round while preserving sigfigs
b24d5a1e 1433 CRM.utils.sigfig = function(n, digits) {
2cfa1092
TO
1434 var len = ("" + n).length;
1435 var scale = Math.pow(10.0, len-digits);
1436 return Math.round(n / scale) * scale;
1437 };
4b513f23 1438})(jQuery, _);