Merge pull request #3991 from colemanw/CRM-13966
[civicrm-core.git] / js / Common.js
CommitLineData
353ea873 1// https://civicrm.org/licensing
6a488035 2var CRM = CRM || {};
4b513f23
CW
3var cj = CRM.$ = jQuery;
4CRM._ = _;
6a488035
TO
5
6/**
7 * Short-named function for string translation, defined in global scope so it's available everywhere.
8 *
353ea873
CW
9 * @param text string for translating
10 * @param params object key:value of additional parameters
6a488035 11 *
353ea873 12 * @return string
6a488035
TO
13 */
14function ts(text, params) {
7553cf23 15 "use strict";
6a488035 16 text = CRM.strings[text] || text;
2788147f 17 if (typeof(params) === 'object') {
6a488035 18 for (var i in params) {
32155ad6 19 if (typeof(params[i]) === 'string' || typeof(params[i]) === 'number') {
2788147f 20 // sprintf emulation: escape % characters in the replacements to avoid conflicts
32155ad6 21 text = text.replace(new RegExp('%' + i, 'g'), String(params[i]).replace(/%/g, '%-crmescaped-'));
2788147f 22 }
6a488035
TO
23 }
24 return text.replace(/%-crmescaped-/g, '%');
25 }
26 return text;
27}
28
29/**
30 * This function is called by default at the bottom of template files which have forms that have
31 * conditionally displayed/hidden sections and elements. The PHP is responsible for generating
32 * a list of 'blocks to show' and 'blocks to hide' and the template passes these parameters to
33 * this function.
34 *
353ea873 35 * @deprecated
6a488035
TO
36 * @param showBlocks Array of element Id's to be displayed
37 * @param hideBlocks Array of element Id's to be hidden
38 * @param elementType Value to set display style to for showBlocks (e.g. 'block' or 'table-row' or ...)
6a488035 39 */
0f5816a6
KJ
40function on_load_init_blocks(showBlocks, hideBlocks, elementType) {
41 if (elementType == null) {
42 var elementType = 'block';
43 }
44
45 /* This loop is used to display the blocks whose IDs are present within the showBlocks array */
46 for (var i = 0; i < showBlocks.length; i++) {
47 var myElement = document.getElementById(showBlocks[i]);
48 /* getElementById returns null if element id doesn't exist in the document */
49 if (myElement != null) {
50 myElement.style.display = elementType;
6a488035 51 }
0f5816a6
KJ
52 else {
53 alert('showBlocks array item not in .tpl = ' + showBlocks[i]);
54 }
55 }
6a488035 56
0f5816a6
KJ
57 /* This loop is used to hide the blocks whose IDs are present within the hideBlocks array */
58 for (var i = 0; i < hideBlocks.length; i++) {
59 var myElement = document.getElementById(hideBlocks[i]);
60 /* getElementById returns null if element id doesn't exist in the document */
61 if (myElement != null) {
62 myElement.style.display = 'none';
63 }
64 else {
65 alert('showBlocks array item not in .tpl = ' + hideBlocks[i]);
6a488035 66 }
0f5816a6 67 }
6a488035
TO
68}
69
70/**
71 * This function is called when we need to show or hide a related form element (target_element)
72 * based on the value (trigger_value) of another form field (trigger_field).
73 *
353ea873 74 * @deprecated
6a488035
TO
75 * @param trigger_field_id HTML id of field whose onchange is the trigger
76 * @param trigger_value List of integers - option value(s) which trigger show-element action for target_field
77 * @param target_element_id HTML id of element to be shown or hidden
78 * @param target_element_type Type of element to be shown or hidden ('block' or 'table-row')
79 * @param field_type Type of element radio/select
80 * @param invert Boolean - if true, we HIDE target on value match; if false, we SHOW target on value match
0f5816a6
KJ
81 */
82function showHideByValue(trigger_field_id, trigger_value, target_element_id, target_element_type, field_type, invert) {
83 if (target_element_type == null) {
84 var target_element_type = 'block';
85 }
86 else {
87 if (target_element_type == 'table-row') {
88 var target_element_type = '';
89 }
90 }
91
92 if (field_type == 'select') {
93 var trigger = trigger_value.split("|");
24cc4545 94 var selectedOptionValue = cj('#' + trigger_field_id).val();
0f5816a6
KJ
95
96 var target = target_element_id.split("|");
97 for (var j = 0; j < target.length; j++) {
98 if (invert) {
99 cj('#' + target[j]).show();
100 }
101 else {
102 cj('#' + target[j]).hide();
103 }
104 for (var i = 0; i < trigger.length; i++) {
105 if (selectedOptionValue == trigger[i]) {
106 if (invert) {
107 cj('#' + target[j]).hide();
108 }
109 else {
110 cj('#' + target[j]).show();
111 }
6a488035 112 }
0f5816a6
KJ
113 }
114 }
6a488035 115
0f5816a6
KJ
116 }
117 else {
118 if (field_type == 'radio') {
119 var target = target_element_id.split("|");
120 for (var j = 0; j < target.length; j++) {
5fb3af09 121 if (cj('[name="' + trigger_field_id + '"]:first').is(':checked')) {
0f5816a6
KJ
122 if (invert) {
123 cj('#' + target[j]).hide();
124 }
125 else {
126 cj('#' + target[j]).show();
127 }
6a488035 128 }
0f5816a6
KJ
129 else {
130 if (invert) {
131 cj('#' + target[j]).show();
132 }
133 else {
134 cj('#' + target[j]).hide();
135 }
136 }
137 }
6a488035 138 }
0f5816a6 139 }
6a488035
TO
140}
141
6a488035
TO
142/**
143 * Function to change button text and disable one it is clicked
353ea873 144 * @deprecated
6a488035
TO
145 * @param obj object - the button clicked
146 * @param formID string - the id of the form being submitted
147 * @param string procText - button text after user clicks it
353ea873 148 * @return bool
6a488035 149 */
0f5816a6 150var submitcount = 0;
c6edd786 151/* Changes button label on submit, and disables button after submit for newer browsers.
152 Puts up alert for older browsers. */
0f5816a6
KJ
153function submitOnce(obj, formId, procText) {
154 // if named button clicked, change text
155 if (obj.value != null) {
156 obj.value = procText + " ...";
157 }
47ea29e3 158 cj(obj).closest('form').attr('data-warn-changes', 'false');
0f5816a6
KJ
159 if (document.getElementById) { // disable submit button for newer browsers
160 obj.disabled = true;
161 document.getElementById(formId).submit();
162 return true;
163 }
164 else { // for older browsers
165 if (submitcount == 0) {
166 submitcount++;
167 return true;
168 }
169 else {
170 alert("Your request is currently being processed ... Please wait.");
171 return false;
6a488035 172 }
0f5816a6 173 }
6a488035 174}
6a488035 175
6a488035
TO
176/**
177 * Function to show / hide the row in optionFields
353ea873
CW
178 * @deprecated
179 * @param index string, element whose innerHTML is to hide else will show the hidden row.
6a488035 180 */
0f5816a6
KJ
181function showHideRow(index) {
182 if (index) {
183 cj('tr#optionField_' + index).hide();
184 if (cj('table#optionField tr:hidden:first').length) {
185 cj('div#optionFieldLink').show();
6a488035 186 }
0f5816a6
KJ
187 }
188 else {
189 cj('table#optionField tr:hidden:first').show();
190 if (!cj('table#optionField tr:hidden:last').length) {
191 cj('div#optionFieldLink').hide();
192 }
193 }
194 return false;
6a488035
TO
195}
196
475e9f44 197CRM.utils = CRM.utils || {};
6a488035 198CRM.strings = CRM.strings || {};
6a488035 199
4b513f23 200(function ($, _, undefined) {
7553cf23 201 "use strict";
d664f648 202
3f586963
CW
203 // Theme classes for unattached elements
204 $.fn.select2.defaults.dropdownCssClass = $.ui.dialog.prototype.options.dialogClass = 'crm-container';
205
47f21f3a
CW
206 // https://github.com/ivaynberg/select2/pull/2090
207 $.fn.select2.defaults.width = 'resolve';
208
e20523a8
CW
209 // Workaround for https://github.com/ivaynberg/select2/issues/1246
210 $.ui.dialog.prototype._allowInteraction = function(e) {
a7c4a5a8 211 return !!$(e.target).closest('.ui-dialog, .ui-datepicker, .select2-drop, .cke_dialog').length;
e20523a8
CW
212 };
213
475e9f44
CW
214 /**
215 * Populate a select list, overwriting the existing options except for the placeholder.
216 * @param $el jquery collection - 1 or more select elements
217 * @param options array in format returned by api.getoptions
1d07e7ab 218 * @param placeholder string
475e9f44 219 */
1d07e7ab 220 CRM.utils.setOptions = function($el, options, placeholder) {
475e9f44
CW
221 $el.each(function() {
222 var
223 $elect = $(this),
23e8a31b 224 val = $elect.val() || [],
1d07e7ab
CW
225 multiple = $el.is('[multiple]'),
226 opts = placeholder || placeholder === '' ? '' : '[value!=""]',
227 newOptions = '',
228 theme = function(options) {
229 _.each(options, function(option) {
230 if (option.children) {
231 newOptions += '<optgroup label="' + option.value + '">';
232 theme(option.children);
233 newOptions += '</optgroup>';
234 } else {
235 var selected = ($.inArray('' + option.key, val) > -1) ? 'selected="selected"' : '';
236 newOptions += '<option value="' + option.key + '"' + selected + '>' + option.value + '</option>';
237 }
238 });
239 };
46ed212b 240 if (!$.isArray(val)) {
475e9f44
CW
241 val = [val];
242 }
23e8a31b 243 $elect.find('option' + opts).remove();
1d07e7ab
CW
244 theme(options);
245 if (typeof placeholder === 'string') {
246 if (multiple) {
247 $el.attr('placeholder', placeholder);
248 } else {
249 newOptions = '<option value="">' + placeholder + '</option>' + newOptions;
250 }
251 }
252 $elect.append(newOptions);
e6f4ac36 253 $elect.trigger('crmOptionsUpdated', $.extend({}, options)).trigger('change');
475e9f44
CW
254 });
255 };
256
1d07e7ab
CW
257 function chainSelect() {
258 var $form = $(this).closest('form'),
259 $target = $('select[data-name="' + $(this).data('target') + '"]', $form),
260 data = $target.data(),
261 val = $(this).val();
262 $target.prop('disabled', true);
263 if ($target.is('select.crm-chain-select-control')) {
264 $('select[data-name="' + $target.data('target') + '"]', $form).prop('disabled', true).blur();
265 }
266 if (!(val && val.length)) {
267 CRM.utils.setOptions($target.blur(), [], data.emptyPrompt);
268 } else {
269 $target.addClass('loading');
270 $.getJSON(CRM.url(data.callback), {_value: val}, function(vals) {
271 $target.prop('disabled', false).removeClass('loading');
272 CRM.utils.setOptions($target, vals || [], (vals && vals.length ? data.selectPrompt : data.nonePrompt));
273 });
274 }
275 }
276
3e201321 277/**
278 * Compare Form Input values against cached initial value.
88e9380e
CW
279 *
280 * @return {Boolean} true if changes have been made.
3e201321 281 */
282 CRM.utils.initialValueChanged = function(el) {
88e9380e 283 var isDirty = false;
18469bf2 284 $(':input:visible, .select2-container:visible+:input.select2-offscreen', el).not('[type=submit], [type=button], .crm-action-menu').each(function () {
88e9380e 285 var initialValue = $(this).data('crm-initial-value');
3c0624e2 286 // skip change of value for submit buttons
bf7a4fbc 287 if (initialValue !== undefined && !_.isEqual(initialValue, $(this).val())) {
88e9380e
CW
288 isDirty = true;
289 }
3e201321 290 });
291 return isDirty;
8d36b801 292 };
3e201321 293
ba4fb2b2 294 /**
353ea873 295 * Wrapper for select2 initialization function; supplies defaults
a88cf11a 296 * @param options object
ba4fb2b2 297 */
a88cf11a
CW
298 $.fn.crmSelect2 = function(options) {
299 return $(this).each(function () {
300 var
301 $el = $(this),
a243158e 302 settings = {allowClear: !$el.hasClass('required')};
a88cf11a
CW
303 // quickform doesn't support optgroups so here's a hack :(
304 $('option[value^=crm_optgroup]', this).each(function () {
305 $(this).nextUntil('option[value^=crm_optgroup]').wrapAll('<optgroup label="' + $(this).text() + '" />');
306 $(this).remove();
307 });
308 // Defaults for single-selects
309 if ($el.is('select:not([multiple])')) {
a243158e 310 settings.minimumResultsForSearch = 10;
a88cf11a 311 if ($('option:first', this).val() === '') {
a243158e 312 settings.placeholderOption = 'first';
a88cf11a 313 }
ba4fb2b2 314 }
a243158e
CW
315 $.extend(settings, $el.data('select-params') || {}, options || {});
316 if (settings.ajax) {
317 $el.addClass('crm-ajax-select');
318 }
319 $el.select2(settings);
a88cf11a
CW
320 });
321 };
322
323 /**
353ea873 324 * @see CRM_Core_Form::addEntityRef for docs
a88cf11a
CW
325 * @param options object
326 */
327 $.fn.crmEntityRef = function(options) {
328 options = options || {};
329 options.select = options.select || {};
330 return $(this).each(function() {
331 var
4c993609 332 $el = $(this).off('.crmEntity'),
a88cf11a
CW
333 entity = options.entity || $el.data('api-entity') || 'contact',
334 selectParams = {};
335 $el.data('api-entity', entity);
336 $el.data('select-params', $.extend({}, $el.data('select-params') || {}, options.select));
337 $el.data('api-params', $.extend({}, $el.data('api-params') || {}, options.api));
a4799f04 338 $el.data('create-links', options.create || $el.data('create-links'));
a243158e 339 $el.addClass('crm-form-entityref crm-' + entity + '-ref');
ba4fb2b2
CW
340 var settings = {
341 // Use select2 ajax helper instead of CRM.api because it provides more value
342 ajax: {
343 url: CRM.url('civicrm/ajax/rest'),
344 data: function (input, page_num) {
345 var params = $el.data('api-params') || {};
346 params.input = input;
347 params.page_num = page_num;
348 return {
349 entity: $el.data('api-entity'),
350 action: 'getlist',
351 json: JSON.stringify(params)
352 };
353 },
354 results: function(data) {
355 return {more: data.more_results, results: data.values || []};
356 }
357 },
a88cf11a 358 minimumInputLength: 1,
3c0b6a40 359 formatResult: CRM.utils.formatSelect2Result,
ba4fb2b2
CW
360 formatSelection: function(row) {
361 return row.label;
362 },
363 escapeMarkup: function (m) {return m;},
a88cf11a
CW
364 initSelection: function($el, callback) {
365 var
366 multiple = !!$el.data('select-params').multiple,
367 val = $el.val(),
368 stored = $el.data('entity-value') || [];
369 if (val === '') {
370 return;
371 }
372 // If we already have this data, just return it
373 if (!_.xor(val.split(','), _.pluck(stored, 'id')).length) {
374 callback(multiple ? stored : stored[0]);
375 } else {
78b203e5 376 var params = $.extend({}, $el.data('api-params') || {}, {id: val});
a88cf11a 377 CRM.api3($el.data('api-entity'), 'getlist', params).done(function(result) {
d2b4810b
CW
378 callback(multiple ? result.values : result.values[0]);
379 // Trigger change (store data to avoid an infinite loop of lookups)
380 $el.data('entity-value', result.values).trigger('change');
a88cf11a
CW
381 });
382 }
ba4fb2b2
CW
383 }
384 };
4c993609 385 if ($el.data('create-links') && entity.toLowerCase() === 'contact') {
a88cf11a
CW
386 selectParams.formatInputTooShort = function() {
387 var txt = $el.data('select-params').formatInputTooShort || $.fn.select2.defaults.formatInputTooShort.call(this);
d706958c 388 if ($el.data('create-links') && CRM.profileCreate && CRM.profileCreate.length) {
a4799f04 389 txt += ' ' + ts('or') + '<br />' + formatSelect2CreateLinks($el);
ba4fb2b2
CW
390 }
391 return txt;
392 };
a88cf11a 393 selectParams.formatNoMatches = function() {
ba4fb2b2 394 var txt = $el.data('select-params').formatNoMatches || $.fn.select2.defaults.formatNoMatches;
4e56e743 395 return txt + (CRM.profileCreate ? ('<br />' + formatSelect2CreateLinks($el)) : '');
ba4fb2b2 396 };
4c993609 397 $el.on('select2-open.crmEntity', function() {
ba4fb2b2
CW
398 var $el = $(this);
399 $('#select2-drop').off('.crmEntity').on('click.crmEntity', 'a.crm-add-entity', function(e) {
400 $el.select2('close');
401 CRM.loadForm($(this).attr('href'), {
402 dialog: {width: 500, height: 'auto'}
403 }).on('crmFormSuccess', function(e, data) {
c92f6436 404 if (data.status === 'success' && data.id) {
e11b84ce 405 CRM.status(ts('%1 Created', {1: data.label}));
c92f6436
CW
406 if ($el.select2('container').hasClass('select2-container-multi')) {
407 var selection = $el.select2('data');
408 selection.push(data);
409 $el.select2('data', selection, true);
410 } else {
411 $el.select2('data', data, true);
412 }
ba4fb2b2
CW
413 }
414 });
415 return false;
416 });
417 });
418 }
4c993609
CW
419 // Create new items inline - works for tags
420 else if ($el.data('create-links')) {
421 selectParams.createSearchChoice = function(term, data) {
422 if (!_.findKey(data, {label: term})) {
423 return {id: "0", term: term, label: term + ' (' + ts('new tag') + ')'};
424 }
425 };
e4f4dc22 426 selectParams.tokenSeparators = [','];
4c993609
CW
427 selectParams.createSearchChoicePosition = 'bottom';
428 }
429 $el.crmSelect2($.extend(settings, $el.data('select-params'), selectParams))
430 .on('select2-selecting.crmEntity', function(e) {
431 if (e.val === "0") {
432 e.object.label = e.object.term;
433 CRM.api3(entity, 'create', $.extend({name: e.object.term}, $el.data('api-params').params || {}))
434 .done(function(created) {
435 var
436 multiple = !!$el.data('select-params').multiple,
437 val = $el.select2('val'),
438 data = $el.select2('data'),
439 item = {id: created.id, label: e.object.term};
440 if (val === "0") {
e4f4dc22 441 $el.select2('data', item, true);
4c993609
CW
442 }
443 else if ($.isArray(val) && $.inArray("0", val) > -1) {
444 _.remove(data, {id: "0"});
445 data.push(item);
e4f4dc22 446 $el.select2('data', data, true);
4c993609
CW
447 }
448 });
449 }
450 });
a88cf11a 451 });
ba4fb2b2
CW
452 };
453
3c0b6a40 454 CRM.utils.formatSelect2Result = function (row) {
88881f79 455 var markup = '<div class="crm-select2-row">';
ff88d165 456 if (row.image !== undefined) {
88881f79 457 markup += '<div class="crm-select2-image"><img src="' + row.image + '"/></div>';
ff88d165 458 }
54bee7df 459 else if (row.icon_class) {
88881f79 460 markup += '<div class="crm-select2-icon"><div class="crm-icon ' + row.icon_class + '-icon"></div></div>';
54bee7df 461 }
3c0b6a40 462 markup += '<div><div class="crm-select2-row-label '+(row.label_class || '')+'">' + row.label + '</div>';
88881f79
CW
463 markup += '<div class="crm-select2-row-description">';
464 $.each(row.description || [], function(k, text) {
465 markup += '<p>' + text + '</p>';
466 });
467 markup += '</div></div></div>';
ff88d165 468 return markup;
3c0b6a40 469 };
a4799f04
CW
470
471 function formatSelect2CreateLinks($el) {
472 var
473 createLinks = $el.data('create-links'),
474 api = $el.data('api-params') || {},
475 type = api.params ? api.params.contact_type : null;
476 if (createLinks === true) {
4e56e743 477 createLinks = type ? _.where(CRM.profileCreate, {type: type}) : CRM.profileCreate;
a4799f04 478 }
79ae07d9 479 var markup = '';
a4799f04 480 _.each(createLinks, function(link) {
79ae07d9 481 markup += ' <a class="crm-add-entity crm-hover-button" href="' + link.url + '">';
a4799f04
CW
482 if (link.type) {
483 markup += '<span class="icon ' + link.type + '-profile-icon"></span> ';
79ae07d9
CW
484 }
485 markup += link.label + '</a>';
486 });
487 return markup;
a4799f04 488 }
ff88d165 489
3d527838
CW
490 /**
491 * Wrapper for jQuery validate initialization function; supplies defaults
492 * @param options object
493 */
494 $.fn.crmValidate = function(params) {
495 return $(this).each(function () {
496 var that = this,
497 settings = $.extend({}, CRM.validate._defaults, CRM.validate.params);
498 $(this).validate(settings);
499 // Call any post-initialization callbacks
500 if (CRM.validate.functions && CRM.validate.functions.length) {
501 $.each(CRM.validate.functions, function(i, func) {
502 func.call(that);
503 });
504 }
505 });
506 }
507
f7b92fcd 508 // Initialize widgets
eb90857a
CW
509 $(document)
510 .on('crmLoad', function(e) {
511 $('table.row-highlight', e.target)
512 .off('.rowHighlight')
7e13d44e
CW
513 .on('change.rowHighlight', 'input.select-row, input.select-rows', function (e, data) {
514 var filter, $table = $(this).closest('table');
eb90857a 515 if ($(this).hasClass('select-rows')) {
7e13d44e
CW
516 filter = $(this).prop('checked') ? ':not(:checked)' : ':checked';
517 $('input.select-row' + filter, $table).prop('checked', $(this).prop('checked')).trigger('change', 'master-selected');
eb90857a
CW
518 }
519 else {
7e13d44e
CW
520 $(this).closest('tr').toggleClass('crm-row-selected', $(this).prop('checked'));
521 if (data !== 'master-selected') {
522 $('input.select-rows', $table).prop('checked', $(".select-row:not(':checked')", $table).length < 1);
523 }
eb90857a 524 }
eb90857a
CW
525 })
526 .find('input.select-row:checked').parents('tr').addClass('crm-row-selected');
82661158
JP
527 if ($("input:radio[name=radio_ts]").size() == 1) {
528 $("input:radio[name=radio_ts]").prop("checked", true);
529 }
5f34e50b
CW
530 $('.crm-select2:not(.select2-offscreen, .select2-container)', e.target).crmSelect2();
531 $('.crm-form-entityref:not(.select2-offscreen, .select2-container)', e.target).crmEntityRef();
1d07e7ab 532 $('select.crm-chain-select-control', e.target).off('.chainSelect').on('change.chainSelect', chainSelect);
3e201321 533 // Cache Form Input initial values
88e9380e 534 $('form[data-warn-changes] :input', e.target).each(function() {
329758bb 535 $(this).data('crm-initial-value', $(this).val());
3e201321 536 });
eb90857a 537 })
eb90857a 538 .on('dialogopen', function(e) {
f292709b
CW
539 var $el = $(e.target);
540 // Modal dialogs should disable scrollbars
541 if ($el.dialog('option', 'modal')) {
542 $el.addClass('modal-dialog');
eb90857a
CW
543 $('body').css({overflow: 'hidden'});
544 }
f292709b
CW
545 $el.parent().find('.ui-dialog-titlebar-close').attr('title', ts('Close'));
546 // Add resize button
a243158e 547 if ($el.parent().hasClass('crm-container') && $el.dialog('option', 'resizable')) {
77a8d7f9 548 $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
549 $('.crm-dialog-titlebar-resize', $el.parent()).click(function(e) {
550 if ($el.data('origSize')) {
551 $el.dialog('option', $el.data('origSize'));
552 $el.data('origSize', null);
553 } else {
28d510ab 554 var menuHeight = $('#civicrm-menu').outerHeight();
f292709b 555 $el.data('origSize', {
28d510ab 556 position: {my: 'center', at: 'center center+' + (menuHeight / 2), of: window},
f292709b
CW
557 width: $el.dialog('option', 'width'),
558 height: $el.dialog('option', 'height')
559 });
f2f191fe 560 $el.dialog('option', {width: '100%', height: ($(window).height() - menuHeight), position: {my: "top", at: "top+"+menuHeight, of: window}});
f292709b
CW
561 }
562 e.preventDefault();
563 });
564 }
eb90857a
CW
565 })
566 .on('dialogclose', function(e) {
f292709b 567 // Restore scrollbars when closing modal
5a6148a0 568 if ($('.ui-dialog .modal-dialog:visible').not(e.target).length < 1) {
eb90857a
CW
569 $('body').css({overflow: ''});
570 }
afc021d8 571 })
572 .on('submit', function(e) {
f582fc8f 573 // CRM-14353 - disable changes warn when submitting a form
abb6e044 574 $('[data-warn-changes]').attr('data-warn-changes', 'false');
afc021d8 575 })
f582fc8f
CW
576 ;
577
578 // CRM-14353 - Warn of unsaved changes for forms which have opted in
579 window.onbeforeunload = function() {
18469bf2 580 if (CRM.utils.initialValueChanged($('form[data-warn-changes=true]:visible'))) {
f582fc8f
CW
581 return ts('You have unsaved changes.');
582 }
583 };
148c4e8d
CW
584
585 /**
586 * Function to make multiselect boxes behave as fields in small screens
587 */
588 function advmultiselectResize() {
589 var amswidth = $("#crm-container form:has(table.advmultiselect)").width();
590 if (amswidth < 700) {
591 $("form table.advmultiselect td").css('display', 'block');
0f5816a6
KJ
592 }
593 else {
148c4e8d
CW
594 $("form table.advmultiselect td").css('display', 'table-cell');
595 }
596 var contactwidth = $('#crm-container #mainTabContainer').width();
597 if (contactwidth < 600) {
598 $('#crm-container #mainTabContainer').addClass('narrowpage');
0f5816a6 599 $('#crm-container #mainTabContainer.narrowpage #contactTopBar td').each(function (index) {
148c4e8d 600 if (index > 1) {
0f5816a6 601 if (index % 2 == 0) {
148c4e8d
CW
602 $(this).parent().after('<tr class="narrowadded"></tr>');
603 }
604 var item = $(this);
605 $(this).parent().next().append(item);
606 }
607 });
0f5816a6
KJ
608 }
609 else {
148c4e8d 610 $('#crm-container #mainTabContainer.narrowpage').removeClass('narrowpage');
0f5816a6 611 $('#crm-container #mainTabContainer #contactTopBar tr.narrowadded td').each(function () {
148c4e8d
CW
612 var nitem = $(this);
613 var parent = $(this).parent();
614 $(this).parent().prev().append(nitem);
0f5816a6 615 if (parent.children().size() == 0) {
148c4e8d
CW
616 parent.remove();
617 }
618 });
619 $('#crm-container #mainTabContainer.narrowpage #contactTopBar tr.added').detach();
620 }
621 var cformwidth = $('#crm-container #Contact .contact_basic_information-section').width();
0f5816a6 622
148c4e8d
CW
623 if (cformwidth < 720) {
624 $('#crm-container .contact_basic_information-section').addClass('narrowform');
625 $('#crm-container .contact_basic_information-section table.form-layout-compressed td .helpicon').parent().addClass('hashelpicon');
626 if (cformwidth < 480) {
627 $('#crm-container .contact_basic_information-section').addClass('xnarrowform');
0f5816a6
KJ
628 }
629 else {
148c4e8d
CW
630 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
631 }
0f5816a6
KJ
632 }
633 else {
148c4e8d
CW
634 $('#crm-container .contact_basic_information-section.narrowform').removeClass('narrowform');
635 $('#crm-container .contact_basic_information-section.xnarrowform').removeClass('xnarrowform');
636 }
637 }
0f5816a6 638
148c4e8d 639 advmultiselectResize();
0f5816a6 640 $(window).resize(function () {
6a488035
TO
641 advmultiselectResize();
642 });
643
0f5816a6 644 $.fn.crmtooltip = function () {
2c29c2ac
RN
645 $(document)
646 .on('mouseover', 'a.crm-summary-link:not(.crm-processed)', function (e) {
647 $(this).addClass('crm-processed');
e24b17b9
CW
648 $(this).addClass('crm-tooltip-active');
649 var topDistance = e.pageY - $(window).scrollTop();
650 if (topDistance < 300 | topDistance < $(this).children('.crm-tooltip-wrapper').height()) {
651 $(this).addClass('crm-tooltip-down');
652 }
653 if (!$(this).children('.crm-tooltip-wrapper').length) {
6a488035
TO
654 $(this).append('<div class="crm-tooltip-wrapper"><div class="crm-tooltip"></div></div>');
655 $(this).children().children('.crm-tooltip')
656 .html('<div class="crm-loading-element"></div>')
657 .load(this.href);
658 }
659 })
2c29c2ac
RN
660 .on('mouseout', 'a.crm-summary-link', function () {
661 $(this).removeClass('crm-processed');
e24b17b9
CW
662 $(this).removeClass('crm-tooltip-active crm-tooltip-down');
663 })
2c29c2ac 664 .on('click', 'a.crm-summary-link', false);
6a488035
TO
665 };
666
b0ca6188 667 var helpDisplay, helpPrevious;
8e3272a1 668 CRM.help = function (title, params, url) {
55a93b02 669 if (helpDisplay && helpDisplay.close) {
b0ca6188 670 // If the same link is clicked twice, just close the display - todo use underscore method for this comparison
55a93b02
CW
671 if (helpDisplay.isOpen && helpPrevious === JSON.stringify(params)) {
672 helpDisplay.close();
b0ca6188
CW
673 return;
674 }
55a93b02 675 helpDisplay.close();
b0ca6188
CW
676 }
677 helpPrevious = JSON.stringify(params);
6a488035
TO
678 params.class_name = 'CRM_Core_Page_Inline_Help';
679 params.type = 'page';
b0ca6188 680 helpDisplay = CRM.alert('...', title, 'crm-help crm-msg-loading', {expires: 0});
8e3272a1 681 $.ajax(url || CRM.url('civicrm/ajax/inline'),
6a488035
TO
682 {
683 data: params,
684 dataType: 'html',
e24b17b9 685 success: function (data) {
6a488035
TO
686 $('#crm-notification-container .crm-help .notify-content:last').html(data);
687 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('info');
688 },
e24b17b9 689 error: function () {
6a488035
TO
690 $('#crm-notification-container .crm-help .notify-content:last').html('Unable to load help file.');
691 $('#crm-notification-container .crm-help').removeClass('crm-msg-loading').addClass('error');
692 }
693 }
694 );
695 };
8960d9b9 696 /**
7442e8f6 697 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
8960d9b9 698 */
1b2475e1 699 CRM.status = function(options, deferred) {
9a7ef94f 700 // 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
701 if (typeof options === 'string') {
702 return CRM.status({start: options, success: options, error: options})[deferred === 'error' ? 'reject' : 'resolve']();
8960d9b9 703 }
1b2475e1
CW
704 var opts = $.extend({
705 start: ts('Saving...'),
9a7ef94f 706 success: ts('Saved'),
1b2475e1
CW
707 error: function() {
708 CRM.alert(ts('Sorry an error occurred and your information was not saved'), ts('Error'));
709 }
710 }, options || {});
711 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>')
712 .appendTo('body');
713 $msg.css('min-width', $msg.width());
714 function handle(status, data) {
715 var endMsg = typeof(opts[status]) === 'function' ? opts[status](data) : opts[status];
716 if (endMsg) {
717 $msg.removeClass('status-start').addClass('status-' + status).find('.crm-status-box-msg').html(endMsg);
718 window.setTimeout(function() {
719 $msg.fadeOut('slow', function() {$msg.remove()});
4bad157e
CW
720 }, 2000);
721 } else {
1b2475e1 722 $msg.remove();
4bad157e 723 }
1b2475e1
CW
724 }
725 return (deferred || new $.Deferred())
726 .done(function(data) {
727 // If the server returns an error msg call the error handler
728 var status = $.isPlainObject(data) && (data.is_error || data.status === 'error') ? 'error' : 'success';
729 handle(status, data);
730 })
731 .fail(function(data) {
732 handle('error', data);
733 });
8960d9b9 734 };
6a488035
TO
735
736 /**
7442e8f6 737 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
6a488035 738 */
0f5816a6 739 CRM.alert = function (text, title, type, options) {
6a488035
TO
740 type = type || 'alert';
741 title = title || '';
742 options = options || {};
743 if ($('#crm-notification-container').length) {
744 var params = {
745 text: text,
746 title: title,
747 type: type
748 };
749 // By default, don't expire errors and messages containing links
750 var extra = {
751 expires: (type == 'error' || text.indexOf('<a ') > -1) ? 0 : (text ? 10000 : 5000),
752 unique: true
753 };
754 options = $.extend(extra, options);
e24b17b9 755 options.expires = options.expires === false ? 0 : parseInt(options.expires, 10);
6a488035 756 if (options.unique && options.unique !== '0') {
0f5816a6 757 $('#crm-notification-container .ui-notify-message').each(function () {
6a488035
TO
758 if (title === $('h1', this).html() && text === $('.notify-content', this).html()) {
759 $('.icon.ui-notify-close', this).click();
760 }
761 });
762 }
763 return $('#crm-notification-container').notify('create', params, options);
764 }
765 else {
766 if (title.length) {
767 text = title + "\n" + text;
768 }
769 alert(text);
770 return null;
771 }
e24b17b9 772 };
6a488035
TO
773
774 /**
775 * Close whichever alert contains the given node
776 *
777 * @param node
778 */
0f5816a6 779 CRM.closeAlertByChild = function (node) {
6a488035 780 $(node).closest('.ui-notify-message').find('.icon.ui-notify-close').click();
e24b17b9 781 };
6a488035
TO
782
783 /**
7442e8f6 784 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
6a488035 785 */
5fb83680
CW
786 CRM.confirm = function (options) {
787 var dialog, settings = {
a65e5f52 788 title: ts('Confirm'),
7553cf23 789 message: ts('Are you sure you want to continue?'),
0d5f99d4 790 width: 'auto',
5fb83680 791 modal: true,
a243158e 792 resizable: false,
5fb83680 793 dialogClass: 'crm-container crm-confirm',
0f5816a6 794 close: function () {
5fb83680 795 $(this).dialog('destroy').remove();
0f5816a6 796 },
5fb83680
CW
797 options: {
798 no: ts('Cancel'),
799 yes: ts('Continue')
800 }
0f5816a6 801 };
5fb83680
CW
802 $.extend(settings, ($.isFunction(options) ? arguments[1] : options) || {});
803 if (!settings.buttons && $.isPlainObject(settings.options)) {
804 settings.buttons = [];
805 $.each(settings.options, function(key, label) {
806 settings.buttons.push({
807 text: label,
808 click: function() {
809 var event = $.Event('crmConfirm:' + key);
810 $(this).trigger(event);
811 if (!event.isDefaultPrevented()) {
812 dialog.dialog('close');
813 }
814 }
815 });
816 });
2a06342c 817 }
5fb83680
CW
818 dialog = $('<div class="crm-confirm-dialog"></div>').html(settings.message);
819 delete settings.options;
820 delete settings.message;
821 if ($.isFunction(options)) {
822 dialog.on('crmConfirm:yes', options);
7553cf23 823 }
5fb83680 824 return dialog.dialog(settings).trigger('crmLoad');
e24b17b9 825 };
6a488035 826
ed7225e6
CW
827 /** provides a local copy of ts for a domain */
828 CRM.ts = function(domain) {
829 return function(message, options) {
830 if (domain) {
831 options = $.extend(options || {}, {domain: domain});
832 }
f97524d9
TO
833 return ts(message, options);
834 };
f97524d9
TO
835 };
836
6a488035 837 /**
7442e8f6 838 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Notification+Reference
6a488035 839 */
0f5816a6 840 $.fn.crmError = function (text, title, options) {
6a488035
TO
841 title = title || '';
842 text = text || '';
843 options = options || {};
844
845 var extra = {
846 expires: 0
847 };
848 if ($(this).length) {
849 if (title == '') {
850 var label = $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]').not('[generated=true]');
851 if (label.length) {
852 label.addClass('crm-error');
853 var $label = label.clone();
854 if (text == '' && $('.crm-marker', $label).length > 0) {
855 text = $('.crm-marker', $label).attr('title');
856 }
857 $('.crm-marker', $label).remove();
858 title = $label.text();
859 }
860 }
861 $(this).addClass('error');
862 }
863 var msg = CRM.alert(text, title, 'error', $.extend(extra, options));
864 if ($(this).length) {
865 var ele = $(this);
0f5816a6
KJ
866 setTimeout(function () {
867 ele.one('change', function () {
868 msg && msg.close && msg.close();
869 ele.removeClass('error');
870 label.removeClass('crm-error');
871 });
872 }, 1000);
6a488035
TO
873 }
874 return msg;
e24b17b9 875 };
6a488035
TO
876
877 // Display system alerts through js notifications
878 function messagesFromMarkup() {
0f5816a6 879 $('div.messages:visible', this).not('.help').not('.no-popup').each(function () {
e24b17b9 880 var text, title = '';
6a488035
TO
881 $(this).removeClass('status messages');
882 var type = $(this).attr('class').split(' ')[0] || 'alert';
883 type = type.replace('crm-', '');
884 $('.icon', this).remove();
6a488035 885 if ($('.msg-text', this).length > 0) {
e24b17b9 886 text = $('.msg-text', this).html();
6a488035
TO
887 title = $('.msg-title', this).html();
888 }
889 else {
e24b17b9 890 text = $(this).html();
6a488035
TO
891 }
892 var options = $(this).data('options') || {};
893 $(this).remove();
894 // Duplicates were already removed server-side
895 options.unique = false;
896 CRM.alert(text, title, type, options);
897 });
898 // Handle qf form errors
899 $('form :input.error', this).one('blur', function() {
900 $('.ui-notify-message.error a.ui-notify-close').click();
901 $(this).removeClass('error');
902 $(this).next('span.crm-error').remove();
903 $('label[for="' + $(this).attr('name') + '"], label[for="' + $(this).attr('id') + '"]')
904 .removeClass('crm-error')
905 .find('.crm-error').removeClass('crm-error');
906 });
907 }
908
03a7ec8f
CW
909 // Preprocess all cj ajax calls to display messages
910 $(document).ajaxSuccess(function(event, xhr, settings) {
911 try {
912 if ((!settings.dataType || settings.dataType == 'json') && xhr.responseText) {
913 var response = $.parseJSON(xhr.responseText);
914 if (typeof(response.crmMessages) == 'object') {
915 $.each(response.crmMessages, function(n, msg) {
916 CRM.alert(msg.text, msg.title, msg.type, msg.options);
917 })
918 }
919 }
920 }
921 // Suppress errors
922 catch (e) {}
923 });
924
0f5816a6 925 $(function () {
fdeb4de2
CW
926 $.blockUI.defaults.message = null;
927
65b86482
CW
928 if ($('#crm-container').hasClass('crm-public')) {
929 $.fn.select2.defaults.dropdownCssClass = $.ui.dialog.prototype.options.dialogClass = 'crm-container crm-public';
930 }
931
205bb8ae 932 // Trigger crmLoad on initial content for consistency. It will also be triggered for ajax-loaded content.
8547369d 933 $('.crm-container').trigger('crmLoad');
205bb8ae 934
ef3309b6 935 if ($('#crm-notification-container').length) {
6a488035
TO
936 // Initialize notifications
937 $('#crm-notification-container').notify();
938 messagesFromMarkup.call($('#crm-container'));
6a488035 939 }
ebb9197b 940
475e9f44 941 $('body')
5fb83680
CW
942 // bind the event for image popup
943 .on('click', 'a.crm-image-popup', function(e) {
944 CRM.confirm({
945 title: ts('Preview'),
a243158e 946 resizable: true,
5fb83680
CW
947 message: '<div class="crm-custom-image-popup"><img src=' + $(this).attr('href') + '></div>',
948 options: null
949 });
950 e.preventDefault();
475e9f44 951 })
ebb9197b 952
475e9f44
CW
953 .on('click', function (event) {
954 $('.btn-slide-active').removeClass('btn-slide-active').find('.panel').hide();
955 if ($(event.target).is('.btn-slide')) {
956 $(event.target).addClass('btn-slide-active').find('.panel').show();
957 }
958 })
d664f648 959
4a143c04
CW
960 // Handle clear button for form elements
961 .on('click', 'a.crm-clear-link', function() {
962 $(this).css({visibility: 'hidden'}).siblings('.crm-form-radio:checked').prop('checked', false).change();
bcb4280c 963 $(this).siblings('input:text').val('').change();
4a143c04
CW
964 return false;
965 })
966 .on('change', 'input.crm-form-radio:checked', function() {
967 $(this).siblings('.crm-clear-link').css({visibility: ''});
843bfb07 968 })
6a488035 969
843bfb07 970 // Allow normal clicking of links within accordions
cf021bc5 971 .on('click.crmAccordions', 'div.crm-accordion-header a', function (e) {
843bfb07 972 e.stopPropagation();
cf021bc5 973 })
843bfb07
CW
974 // Handle accordions
975 .on('click.crmAccordions', '.crm-accordion-header, .crm-collapsible .collapsible-title', function (e) {
6a488035 976 if ($(this).parent().hasClass('collapsed')) {
843bfb07 977 $(this).next().css('display', 'none').slideDown(200);
6a488035
TO
978 }
979 else {
843bfb07 980 $(this).next().css('display', 'block').slideUp(200);
6a488035
TO
981 }
982 $(this).parent().toggleClass('collapsed');
843bfb07 983 e.preventDefault();
6a488035 984 });
843bfb07
CW
985
986 $().crmtooltip();
987 });
988 /**
989 * @deprecated
990 */
991 $.fn.crmAccordions = function () {};
992 /**
993 * Collapse or expand an accordion
994 * @param speed
995 */
0f5816a6
KJ
996 $.fn.crmAccordionToggle = function (speed) {
997 $(this).each(function () {
6a488035
TO
998 if ($(this).hasClass('collapsed')) {
999 $('.crm-accordion-body', this).first().css('display', 'none').slideDown(speed);
1000 }
1001 else {
1002 $('.crm-accordion-body', this).first().css('display', 'block').slideUp(speed);
1003 }
1004 $(this).toggleClass('collapsed');
1005 });
1006 };
5ec182d9
CW
1007
1008 /**
1009 * Clientside currency formatting
1010 * @param value
3bdb644f 1011 * @param format - currency representation of the number 1234.56
5ec182d9 1012 * @return string
3bdb644f 1013 * @see CRM_Core_Resources::addCoreResources
5ec182d9
CW
1014 */
1015 var currencyTemplate;
1016 CRM.formatMoney = function(value, format) {
1017 var decimal, separator, sign, i, j, result;
1018 if (value === 'init' && format) {
1019 currencyTemplate = format;
1020 return;
1021 }
1022 format = format || currencyTemplate;
1023 result = /1(.?)234(.?)56/.exec(format);
1024 if (result === null) {
1025 return 'Invalid format passed to CRM.formatMoney';
1026 }
1027 separator = result[1];
1028 decimal = result[2];
1029 sign = (value < 0) ? '-' : '';
1030 //extracting the absolute value of the integer part of the number and converting to string
1031 i = parseInt(value = Math.abs(value).toFixed(2)) + '';
5ec182d9
CW
1032 j = ((j = i.length) > 3) ? j % 3 : 0;
1033 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) : '');
1034 return format.replace(/1.*234.*56/, result);
1035 };
4b513f23 1036})(jQuery, _);