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