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