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