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