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