Fix mglaman mapping
[civicrm-core.git] / js / crm.ajax.js
CommitLineData
53f2643c
CW
1// https://civicrm.org/licensing
2/**
033af979
ML
3 * @see https://docs.civicrm.org/dev/en/latest/api/interfaces/#ajax
4 * @see https://docs.civicrm.org/dev/en/latest/framework/ajax/
53f2643c 5 */
0b873c9a 6(function($, CRM, _, undefined) {
53f2643c 7 /**
f0c9c7dd
CW
8 * @param string path
9 * @param string|object query
8d83b77c 10 * @param string mode - optionally specify "front" or "back"
53f2643c 11 */
0cc040cf 12 var tplURL;
f0c9c7dd
CW
13 CRM.url = function (path, query, mode) {
14 if (typeof path === 'object') {
f54254d8
TO
15 tplURL = path;
16 return path;
53f2643c 17 }
0cc040cf 18 if (!tplURL) {
bba9b4f0 19 CRM.console('error', 'Error: CRM.url called before initialization');
53f2643c 20 }
8d83b77c 21 if (!mode) {
f0c9c7dd 22 mode = CRM.config && CRM.config.isFrontend ? 'front' : 'back';
8d83b77c 23 }
f0c9c7dd 24 query = query || '';
29bc93ee 25 var frag = path.split('?');
cdef34e0 26 var url = tplURL[mode].replace("civicrm-placeholder-url-path", frag[0]);
53f2643c 27
f0c9c7dd 28 if (!query) {
cdef34e0 29 url = url.replace(/[?&]civicrm-placeholder-url-query=1/, '');
53f2643c
CW
30 }
31 else {
cdef34e0 32 url = url.replace("civicrm-placeholder-url-query=1", typeof query === 'string' ? query : $.param(query));
53f2643c
CW
33 }
34 if (frag[1]) {
f0c9c7dd 35 url += (url.indexOf('?') < 0 ? '?' : '&') + frag[1];
53f2643c
CW
36 }
37 return url;
38 };
39
53f2643c
CW
40 $.fn.crmURL = function () {
41 return this.each(function() {
42 if (this.href) {
43 this.href = CRM.url(this.href);
44 }
45 });
46 };
47
f0b90b06
C
48 // result is an array, but in js, an array is also an object
49 // Assign all the metadata properties to it, mirroring the results arrayObject in php
50 function arrayObject(data) {
51 var result = data.values || [];
52 if (_.isArray(result)) {
53 delete(data.values);
54 _.assign(result, data);
55 }
56 return result;
57 }
58
6f55e2a8 59 // https://docs.civicrm.org/dev/en/latest/api/interfaces/#ajax
f0b90b06
C
60 CRM.api4 = function(entity, action, params, index) {
61 return new Promise(function(resolve, reject) {
62 if (typeof entity === 'string') {
63 $.post(CRM.url('civicrm/ajax/api4/' + entity + '/' + action), {
64 params: JSON.stringify(params),
65 index: index
66 })
67 .done(function (data) {
68 resolve(arrayObject(data));
69 })
70 .fail(function (data) {
71 reject(data.responseJSON);
72 });
73 } else {
74 $.post(CRM.url('civicrm/ajax/api4'), {
75 calls: JSON.stringify(entity)
76 })
77 .done(function(data) {
78 _.each(data, function(item, key) {
79 data[key] = arrayObject(item);
80 });
81 resolve(data);
82 })
83 .fail(function (data) {
84 reject(data.responseJSON);
85 });
86 }
87 });
88 };
89
53f2643c
CW
90 /**
91 * AJAX api
6f55e2a8 92 * @link https://docs.civicrm.org/dev/en/latest/api/interfaces/#ajax
53f2643c
CW
93 */
94 CRM.api3 = function(entity, action, params, status) {
95 if (typeof(entity) === 'string') {
96 params = {
97 entity: entity,
98 action: action.toLowerCase(),
99 json: JSON.stringify(params || {})
100 };
101 } else {
102 params = {
103 entity: 'api3',
104 action: 'call',
105 json: JSON.stringify(entity)
e4f4dc22
CW
106 };
107 status = action;
53f2643c
CW
108 }
109 var ajax = $.ajax({
110 url: CRM.url('civicrm/ajax/rest'),
111 dataType: 'json',
112 data: params,
5c20e4c2 113 type: params.action.indexOf('get') === 0 ? 'GET' : 'POST'
53f2643c
CW
114 });
115 if (status) {
116 // Default status messages
117 if (status === true) {
118 status = {success: params.action === 'delete' ? ts('Removed') : ts('Saved')};
119 if (params.action.indexOf('get') === 0) {
120 status.start = ts('Loading...');
121 status.success = null;
122 }
123 }
124 var messages = status === true ? {} : status;
125 CRM.status(status, ajax);
126 }
127 return ajax;
128 };
129
130 /**
131 * @deprecated
132 * AJAX api
133 */
134 CRM.api = function(entity, action, params, options) {
135 // Default settings
136 var settings = {
137 context: null,
138 success: function(result, settings) {
139 return true;
140 },
141 error: function(result, settings) {
142 $().crmError(result.error_message, ts('Error'));
143 return false;
144 },
145 callBack: function(result, settings) {
146 if (result.is_error == 1) {
147 return settings.error.call(this, result, settings);
148 }
149 return settings.success.call(this, result, settings);
150 },
151 ajaxURL: 'civicrm/ajax/rest'
152 };
153 action = action.toLowerCase();
154 // Default success handler
155 switch (action) {
156 case "update":
157 case "create":
158 case "setvalue":
159 case "replace":
160 settings.success = function() {
161 CRM.status(ts('Saved'));
162 return true;
163 };
164 break;
165 case "delete":
166 settings.success = function() {
167 CRM.status(ts('Removed'));
168 return true;
169 };
170 }
171 params = {
172 entity: entity,
173 action: action,
174 json: JSON.stringify(params)
175 };
176 // Pass copy of settings into closure to preserve its value during multiple requests
177 (function(stg) {
178 $.ajax({
179 url: stg.ajaxURL.indexOf('http') === 0 ? stg.ajaxURL : CRM.url(stg.ajaxURL),
180 dataType: 'json',
181 data: params,
182 type: action.indexOf('get') < 0 ? 'POST' : 'GET',
183 success: function(result) {
184 stg.callBack.call(stg.context, result, stg);
185 }
186 });
187 })($.extend({}, settings, options));
188 };
189
53f2643c
CW
190 $.widget('civi.crmSnippet', {
191 options: {
192 url: null,
193 block: true,
194 crmForm: null
195 },
196 _originalContent: null,
197 _originalUrl: null,
198 isOriginalUrl: function() {
199 var
200 args = {},
201 same = true,
202 newUrl = this._formatUrl(this.options.url),
203 oldUrl = this._formatUrl(this._originalUrl);
204 // Compare path
205 if (newUrl.split('?')[0] !== oldUrl.split('?')[0]) {
206 return false;
207 }
208 // Compare arguments
c307a361 209 $.each((newUrl.split('?')[1] || '').split('&'), function(k, v) {
53f2643c
CW
210 var arg = v.split('=');
211 args[arg[0]] = arg[1];
212 });
c307a361 213 $.each((oldUrl.split('?')[1] || '').split('&'), function(k, v) {
53f2643c
CW
214 var arg = v.split('=');
215 if (args[arg[0]] !== undefined && arg[1] !== args[arg[0]]) {
216 same = false;
217 }
218 });
219 return same;
220 },
221 resetUrl: function() {
222 this.options.url = this._originalUrl;
223 },
224 _create: function() {
225 this.element.addClass('crm-ajax-container');
226 if (!this.element.is('.crm-container *')) {
227 this.element.addClass('crm-container');
228 }
229 this._handleOrderLinks();
230 // Set default if not supplied
231 this.options.url = this.options.url || document.location.href;
232 this._originalUrl = this.options.url;
233 },
3e897159
CW
234 _onFailure: function(data, status) {
235 var msg, title = ts('Network Error');
f54254d8 236 if (this.options.block) this.element.unblock();
53f2643c 237 this.element.trigger('crmAjaxFail', data);
3e897159
CW
238 switch (status) {
239 case 'Forbidden':
240 title = ts('Access Denied');
241 msg = ts('Ensure you are still logged in and have permission to access this feature.');
242 break;
243 default:
244 msg = ts('Unable to reach the server. Please refresh this page in your browser and try again.');
245 }
246 CRM.alert(msg, title, 'error');
53f2643c 247 },
61cab70a
CW
248 _onError: function(data) {
249 this.element.attr('data-unsaved-changes', 'false').trigger('crmAjaxError', data);
f7aaf23c 250 if (this.options.crmForm && this.options.crmForm.autoClose && this.element.data('uiDialog')) {
61cab70a
CW
251 this.element.dialog('close');
252 }
253 },
a7bc7b27 254 _formatUrl: function(url, snippetType) {
53f2643c
CW
255 // Strip hash
256 url = url.split('#')[0];
257 // Add snippet argument to url
a7bc7b27
CW
258 if (snippetType) {
259 if (url.search(/[&?]snippet=/) < 0) {
260 url += (url.indexOf('?') < 0 ? '?' : '&') + 'snippet=' + snippetType;
261 } else {
262 url = url.replace(/snippet=[^&]*/, 'snippet=' + snippetType);
263 }
53f2643c
CW
264 }
265 return url;
266 },
267 // Hack to deal with civicrm legacy sort functionality
268 _handleOrderLinks: function() {
269 var that = this;
270 $('a.crm-weight-arrow', that.element).click(function(e) {
f54254d8 271 if (that.options.block) that.element.block();
a7bc7b27 272 $.getJSON(that._formatUrl(this.href, 'json')).done(function() {
53f2643c
CW
273 that.refresh();
274 });
275 e.stopImmediatePropagation();
276 return false;
277 });
278 },
279 refresh: function() {
280 var that = this;
a7bc7b27 281 var url = this._formatUrl(this.options.url, 'json');
f54254d8 282 if (this.options.crmForm) $('form', this.element).ajaxFormUnbind();
f54254d8 283 if (this.options.block) this.element.block();
53f2643c 284 $.getJSON(url, function(data) {
217bfb2e
CW
285 if (data.status === 'redirect') {
286 that.options.url = data.userContext;
287 return that.refresh();
288 }
f54254d8 289 if (that.options.block) that.element.unblock();
61cab70a 290 if (!$.isPlainObject(data)) {
53f2643c
CW
291 that._onFailure(data);
292 return;
293 }
61cab70a
CW
294 if (data.status === 'error') {
295 that._onError(data);
296 return;
297 }
53f2643c 298 data.url = url;
deb6ebbb 299 that.element.trigger('crmUnload').trigger('crmBeforeLoad', data);
66663184
CW
300 that._beforeRemovingContent();
301 that.element.html(data.content);
53f2643c
CW
302 that._handleOrderLinks();
303 that.element.trigger('crmLoad', data);
f54254d8 304 if (that.options.crmForm) that.element.trigger('crmFormLoad', data);
0f0925b0
CW
305 // This is only needed by forms that load via ajax but submit without ajax, e.g. configure contribution page tabs
306 // TODO: remove this when those forms have been converted to use ajax submit
307 if (data.status === 'form_error' && $.isPlainObject(data.errors)) {
308 that.element.trigger('crmFormError', data);
309 $.each(data.errors, function(formElement, msg) {
310 $('[name="'+formElement+'"]', that.element).crmError(msg);
311 });
312 }
3e897159
CW
313 }).fail(function(data, msg, status) {
314 that._onFailure(data, status);
53f2643c
CW
315 });
316 },
66663184
CW
317 // Perform any cleanup needed before removing/replacing content
318 _beforeRemovingContent: function() {
319 var that = this;
8d6a3830
CW
320 // Save original content to be restored if widget is destroyed
321 if (this._originalContent === null) {
322 $('.blockUI', this.element).remove();
323 this._originalContent = this.element.contents().detach();
324 }
f54254d8 325 if (this.options.crmForm) $('form', this.element).ajaxFormUnbind();
66663184 326 },
53f2643c 327 _destroy: function() {
af8c0ebe 328 this.element.removeClass('crm-ajax-container').trigger('crmUnload');
66663184 329 this._beforeRemovingContent();
53f2643c
CW
330 if (this._originalContent !== null) {
331 this.element.empty().append(this._originalContent);
332 }
333 }
334 });
335
98465f9e
CW
336 var dialogCount = 0,
337 exclude = '[href^=#], [href^=javascript], [onclick], .no-popup, .cancel';
338
53f2643c
CW
339 CRM.loadPage = function(url, options) {
340 var settings = {
341 target: '#crm-ajax-dialog-' + (dialogCount++),
b1fc510d 342 dialog: (options && options.target) ? false : {}
53f2643c 343 };
f54254d8 344 if (options) $.extend(true, settings, options);
53f2643c
CW
345 settings.url = url;
346 // Create new dialog
347 if (settings.dialog) {
b1fc510d 348 settings.dialog = CRM.utils.adjustDialogDefaults(settings.dialog);
a7bc7b27
CW
349 $('<div id="' + settings.target.substring(1) + '"></div>')
350 .dialog(settings.dialog)
351 .parent().find('.ui-dialog-titlebar')
352 .append($('<a class="crm-dialog-titlebar-print ui-dialog-titlebar-close" title="'+ts('Print window')+'" target="_blank" style="right:3.8em;"/>')
d2f7ffaa 353 .button({icons: {primary: 'fa-print'}, text: false}));
202559b3 354 }
a7bc7b27 355 // Add handlers to new or existing dialog
202559b3 356 if ($(settings.target).data('uiDialog')) {
73d2716e
CW
357 $(settings.target)
358 .on('dialogclose', function() {
202559b3 359 if (settings.dialog && $(this).attr('data-unsaved-changes') !== 'true') {
73d2716e
CW
360 $(this).crmSnippet('destroy').dialog('destroy').remove();
361 }
362 })
363 .on('crmLoad', function(e, data) {
364 // Set title
365 if (e.target === $(settings.target)[0] && data && !settings.dialog.title && data.title) {
366 $(this).dialog('option', 'title', data.title);
367 }
a7bc7b27
CW
368 // Update print url
369 $(this).parent().find('a.crm-dialog-titlebar-print').attr('href', $(this).data('civiCrmSnippet')._formatUrl($(this).crmSnippet('option', 'url'), '2'));
73d2716e 370 });
53f2643c
CW
371 }
372 $(settings.target).crmSnippet(settings).crmSnippet('refresh');
373 return $(settings.target);
374 };
375 CRM.loadForm = function(url, options) {
55cb6db1 376 var formErrors = [], settings = {
53f2643c
CW
377 crmForm: {
378 ajaxForm: {},
379 autoClose: true,
380 validate: true,
02c82dda 381 refreshAction: ['next_new', 'submit_savenext', 'upload_new'],
98465f9e 382 cancelButton: '.cancel',
5fffbbe4 383 openInline: 'a.open-inline, a.button, a.action-item, a.open-inline-noreturn',
1c1c1ae2 384 onCancel: function(event) {}
53f2643c
CW
385 }
386 };
387 // Move options that belong to crmForm. Others will be passed through to crmSnippet
f54254d8 388 if (options) $.each(options, function(key, value) {
53f2643c
CW
389 if (typeof(settings.crmForm[key]) !== 'undefined') {
390 settings.crmForm[key] = value;
391 }
392 else {
393 settings[key] = value;
394 }
395 });
396
397 var widget = CRM.loadPage(url, settings).off('.crmForm');
398
f582fc8f 399 // CRM-14353 - Warn of unsaved changes for all forms except those which have opted out
88e9380e 400 function cancelAction() {
e9a3e054 401 var dirty = CRM.utils.initialValueChanged($('form:not([data-warn-changes=false])', widget));
c4e00dbb 402 widget.attr('data-unsaved-changes', dirty ? 'true' : 'false');
7c2110fd
CW
403 if (dirty) {
404 var id = widget.attr('id') + '-unsaved-alert',
e9a3e054 405 title = widget.dialog('option', 'title'),
15d60951 406 alert = CRM.alert('<p>' + ts('%1 has not been saved.', {1: title}) + '</p><p><a href="#" id="' + id + '">' + ts('Restore') + '</a></p>', ts('Unsaved Changes'), 'alert unsaved-dialog', {expires: 60000});
d2f7ffaa 407 $('#' + id).button({icons: {primary: 'fa-undo'}}).click(function(e) {
15d60951 408 widget.attr('data-unsaved-changes', 'false').dialog('open');
8537b332 409 e.preventDefault();
7c2110fd 410 });
88e9380e 411 }
88e9380e 412 }
c4e00dbb 413
f54254d8 414 if (widget.data('uiDialog')) widget.on('dialogbeforeclose', function(e) {
c4e00dbb
CW
415 // CRM-14353 - Warn unsaved changes if user clicks close button or presses "esc"
416 if (e.originalEvent) {
417 cancelAction();
418 }
419 });
88e9380e 420
53f2643c 421 widget.on('crmFormLoad.crmForm', function(event, data) {
298f69da
CW
422 var $el = $(this).attr('data-unsaved-changes', 'false'),
423 settings = $el.crmSnippet('option', 'crmForm');
f54254d8 424 if (settings.cancelButton) $(settings.cancelButton, this).click(function(e) {
7c2110fd
CW
425 e.preventDefault();
426 var returnVal = settings.onCancel.call($el, e);
53f2643c 427 if (returnVal !== false) {
7c2110fd 428 $el.trigger('crmFormCancel', e);
53f2643c 429 if ($el.data('uiDialog') && settings.autoClose) {
7c2110fd 430 cancelAction();
c4e00dbb 431 $el.dialog('close');
53f2643c
CW
432 }
433 else if (!settings.autoClose) {
434 $el.crmSnippet('resetUrl').crmSnippet('refresh');
435 }
436 }
53f2643c
CW
437 });
438 if (settings.validate) {
3d527838 439 $("form", this).crmValidate();
53f2643c 440 }
cae80d9f 441 $("form:not('[data-no-ajax-submit=true]')", this).ajaxForm($.extend({
53f2643c
CW
442 url: data.url.replace(/reset=1[&]?/, ''),
443 dataType: 'json',
444 success: function(response) {
1c1c1ae2 445 if (response.content === undefined) {
53f2643c
CW
446 $el.trigger('crmFormSuccess', response);
447 // Reset form for e.g. "save and new"
0a94ab7d 448 if (response.userContext && (response.status === 'redirect' || (settings.refreshAction && $.inArray(response.buttonName, settings.refreshAction) >= 0))) {
b305fb88
CW
449 // Force reset of original url
450 $el.data('civiCrmSnippet')._originalUrl = response.userContext;
451 $el.crmSnippet('resetUrl').crmSnippet('refresh');
53f2643c 452 }
9317128c
CW
453 // Close if we are on the original url or the action was "delete" (in which case returning to view may be inappropriate)
454 else if ($el.data('uiDialog') && (settings.autoClose || response.action === 8)) {
53f2643c
CW
455 $el.dialog('close');
456 }
457 else if (settings.autoClose === false) {
458 $el.crmSnippet('resetUrl').crmSnippet('refresh');
459 }
460 }
461 else {
f54254d8 462 if ($el.crmSnippet('option', 'block')) $el.unblock();
53f2643c 463 response.url = data.url;
1c1c1ae2
CW
464 $el.html(response.content).trigger('crmLoad', response).trigger('crmFormLoad', response);
465 if (response.status === 'form_error') {
55cb6db1 466 formErrors = [];
1c1c1ae2
CW
467 $el.trigger('crmFormError', response);
468 $.each(response.errors || [], function(formElement, msg) {
55cb6db1 469 formErrors.push($('[name="'+formElement+'"]', $el).crmError(msg));
1c1c1ae2
CW
470 });
471 }
53f2643c
CW
472 }
473 },
53f2643c 474 beforeSubmit: function(submission) {
55cb6db1 475 $.each(formErrors, function() {
f54254d8 476 if (this && this.close) this.close();
55cb6db1 477 });
f54254d8 478 if ($el.crmSnippet('option', 'block')) $el.block();
53f2643c
CW
479 $el.trigger('crmFormSubmit', submission);
480 }
481 }, settings.ajaxForm));
482 if (settings.openInline) {
483 settings.autoClose = $el.crmSnippet('isOriginalUrl');
217bfb2e 484 $(this).off('.openInline').on('click.openInline', settings.openInline, function(e) {
cf48cb00
CW
485 if ($(this).is(exclude + ', .crm-popup')) {
486 return;
487 }
5fffbbe4
CW
488 if ($(this).hasClass('open-inline-noreturn')) {
489 // Force reset of original url
490 $el.data('civiCrmSnippet')._originalUrl = $(this).attr('href');
491 }
53f2643c 492 $el.crmSnippet('option', 'url', $(this).attr('href')).crmSnippet('refresh');
cf48cb00 493 e.preventDefault();
53f2643c
CW
494 });
495 }
298f69da 496 if ($el.data('uiDialog')) {
ba05d50e 497 // Show form buttons as part of the dialog
d34e9db0
CW
498 var buttonContainers = '.crm-submit-buttons, .action-link',
499 buttons = [],
500 added = [];
15ef6755 501 $(buttonContainers, $el).find('.crm-form-submit, .crm-form-xbutton, a.button, button').each(function() {
298f69da
CW
502 var $el = $(this),
503 label = $el.is('input') ? $el.attr('value') : $el.text(),
504 identifier = $el.attr('name') || $el.attr('href');
505 if (!identifier || identifier === '#' || $.inArray(identifier, added) < 0) {
6431a032 506 var $icon = $el.find('.icon, .crm-i'),
abbecaf2 507 button = {'data-identifier': identifier, text: label, click: function() {
19ec1d6e 508 $el[0].click();
d34e9db0
CW
509 }};
510 if ($icon.length) {
511 button.icons = {primary: $icon.attr('class')};
298f69da 512 } else {
06d5018a
CW
513 var action = $el.attr('crm-icon') || ($el.hasClass('cancel') ? 'fa-times' : 'fa-check');
514 button.icons = {primary: action};
298f69da
CW
515 }
516 buttons.push(button);
517 added.push(identifier);
518 }
d34e9db0 519 // display:none causes the form to not submit when pressing "enter"
4bc72ff2 520 $el.parents(buttonContainers).css({height: 0, padding: 0, margin: 0, overflow: 'hidden'});
298f69da
CW
521 });
522 $el.dialog('option', 'buttons', buttons);
523 }
022d2163 524 // Allow a button to prevent ajax submit
15ef6755 525 $('input[data-no-ajax-submit=true], button[data-no-ajax-submit=true]').click(function() {
1e29624c
CW
526 $(this).closest('form').ajaxFormUnbind();
527 });
53f2643c 528 // For convenience, focus the first field
b18392cc 529 $('input[type=text], textarea, select', this).filter(':visible').first().not('.dateplugin').focus();
53f2643c
CW
530 });
531 return widget;
532 };
533 /**
022d2163 534 * Handler for jQuery click event e.g. $('a').click(CRM.popup);
53f2643c 535 */
35df910c 536 CRM.popup = function(e) {
53f2643c
CW
537 var $el = $(this).first(),
538 url = $el.attr('href'),
539 popup = $el.data('popup-type') === 'page' ? CRM.loadPage : CRM.loadForm,
540 settings = $el.data('popup-settings') || {},
d3cbd0a5 541 formData = false;
53f2643c 542 settings.dialog = settings.dialog || {};
71bdf27c 543 if (e.isDefaultPrevented() || !CRM.config.ajaxPopupsEnabled || !url || $el.is(exclude + ', .open-inline, .open-inline-noreturn')) {
53f2643c
CW
544 return;
545 }
a1c7d42f
CW
546 // Sized based on css class
547 if ($el.hasClass('small-popup')) {
53f2643c
CW
548 settings.dialog.width = 400;
549 settings.dialog.height = 300;
550 }
551 else if ($el.hasClass('medium-popup')) {
552 settings.dialog.width = settings.dialog.height = '50%';
553 }
53f2643c
CW
554 var dialog = popup(url, settings);
555 // Trigger events from the dialog on the original link element
556 $el.trigger('crmPopupOpen', [dialog]);
4b472ff2 557 // Listen for success events and buffer them so we only trigger once
d3cbd0a5
CW
558 dialog.on('crmFormSuccess.crmPopup crmPopupFormSuccess.crmPopup', function(e, data) {
559 formData = data;
7fe745d1
CW
560 });
561 dialog.on('dialogclose.crmPopup', function(e, data) {
d3cbd0a5
CW
562 if (formData) {
563 $el.trigger('crmPopupFormSuccess', [dialog, formData]);
7fe745d1
CW
564 }
565 $el.trigger('crmPopupClose', [dialog, data]);
53f2643c 566 });
35df910c 567 e.preventDefault();
53f2643c 568 };
554b1768 569 /**
7e9fdecf 570 * An event callback for CRM.popup or a standalone function to refresh the content around a given element
022d2163 571 * @param e {event|selector}
554b1768
CW
572 */
573 CRM.refreshParent = function(e) {
574 // Use e.target if input smells like an event, otherwise assume it's a jQuery selector
575 var $el = (e.stopPropagation && e.target) ? $(e.target) : $(e),
576 $table = $el.closest('.dataTable');
577 // Call native refresh method on ajax datatables
022d2163 578 if ($table.length && $.fn.DataTable.fnIsDataTable($table[0]) && $table.dataTable().fnSettings().sAjaxSource) {
554b1768
CW
579 // Refresh ALL datatables - needed for contact relationship tab
580 $.each($.fn.dataTable.fnTables(), function() {
f54254d8 581 if ($(this).dataTable().fnSettings().sAjaxSource) $(this).unblock().dataTable().fnDraw();
554b1768
CW
582 });
583 }
584 // Otherwise refresh the nearest crmSnippet
585 else {
586 $el.closest('.crm-ajax-container, #crm-main-content-wrapper').crmSnippet().crmSnippet('refresh');
587 }
588 };
a1c7d42f
CW
589
590 $(function($) {
15d60951
CW
591 $('body')
592 .on('click', 'a.crm-popup', CRM.popup)
593 // Close unsaved dialog messages
594 .on('dialogopen', function(e) {
595 $('.alert.unsaved-dialog .ui-notify-cross', '#crm-notification-container').click();
596 })
597 // Destroy old unsaved dialog
598 .on('dialogcreate', function(e) {
599 $('.ui-dialog-content.crm-ajax-container:hidden[data-unsaved-changes=true]').crmSnippet('destroy').dialog('destroy').remove();
e5e90ec9 600 })
f91b1c0c
CW
601 // Ensure wysiwyg content is updated prior to ajax submit
602 .on('form-pre-serialize', function(e) {
603 $('.crm-wysiwyg-enabled', e.target).each(function() {
604 CRM.wysiwyg.updateElement(this);
605 });
606 })
e5e90ec9 607 // Auto-resize dialogs when loading content
b1fc510d 608 .on('crmLoad dialogopen', 'div.ui-dialog.ui-resizable.crm-container', function(e) {
e5e90ec9
CW
609 var
610 $wrapper = $(this),
611 $dialog = $wrapper.children('.ui-dialog-content');
612 // small delay to allow contents to render
613 window.setTimeout(function() {
614 var currentHeight = $wrapper.outerHeight(),
615 padding = currentHeight - $dialog.height(),
616 newHeight = $dialog.prop('scrollHeight') + padding,
59007035
CW
617 menuHeight = $('#civicrm-menu').outerHeight();
618 if ($('body').hasClass('crm-menubar-below-cms-menu')) {
619 menuHeight += $('#civicrm-menu').offset().top;
620 }
621 var maxHeight = $(window).height() - menuHeight;
e5e90ec9
CW
622 newHeight = newHeight > maxHeight ? maxHeight : newHeight;
623 if (newHeight > (currentHeight + 15)) {
624 $dialog.dialog('option', {
625 position: {my: 'center', at: 'center center+' + (menuHeight / 2), of: window},
626 height: newHeight
627 });
628 }
629 }, 500);
15d60951 630 });
a1c7d42f
CW
631 });
632
0b873c9a 633}(jQuery, CRM, _));