Portal and core fixups. (#3525)
[openemr.git] / library / dialog.js
blobdfaa85366ebaf5eac643551b5a59f36f67b6225f
1 // Copyright (C) 2005 Rod Roark <rod@sunsetsystems.com>
2 // Copyright (C) 2018-2020 Jerry Padgett <sjpadgett@gmail.com>
3 //
4 // This program is free software; you can redistribute it and/or
5 // modify it under the terms of the GNU General Public License
6 // as published by the Free Software Foundation; either version 2
7 // of the License, or (at your option) any later version.
9 (function (define) {
10     define(['jquery'], function ($, root) {
11         let opts_default = {};
12         root = root || {};
13         root.alert = alert;
14         root.ajax = ajax;
15         root.closeAjax = closeAjax;
17         return root;
19         function ajax(data) {
20             let opts = {
21                 buttons: data.buttons,
22                 allowDrag: data.allowDrag,
23                 allowResize: data.allowResize,
24                 sizeHeight: data.sizeHeight,
25                 type: data.type,
26                 data: data.data,
27                 url: data.url,
28                 dataType: data.dataType // xml/json/text etc.
29             };
31             let title = data.title;
33             return dlgopen('', '', data.size, 300, '', title, opts);
34         }
36         function alert(data, title) {
37             title = title ? title : 'Alert';
38             let alertTitle = '<i class="fa fa-warning alert-danger"></i>&nbsp;<span>' + title + '</span>';
39             return dlgopen('', '', 675, 250, '', alertTitle, {
40                 buttons: [
41                     {text: '<i class="fa fa-thumbs-up">&nbsp;OK</i>', close: true, style: 'default'}
42                 ],
43                 type: 'Alert',
44                 html: '<blockquote class="blockquote">' + data + '</blockquote>'
45             });
46         }
48         function closeAjax() {
49             dlgCloseAjax();
50         }
51     });
53     if (typeof window.xl !== 'function') {
54         (async (utilfn) => {
55             await includeScript(utilfn, 'script');
56         })(top.webroot_url + '/library/js/utility.js').then(() => {
57             console.log('Utilities Unavailable! loading:[ ' + utilfn + ' ] For: [ ' + location + ' ]');
58         });
59     }
60 }(typeof define == 'function' && define.amd ?
61     define :
62     function (args, mName) {
63         this.dialog = typeof module != 'undefined' && module.exports ?
64             mName(require(args[0], {}), module.exports) :
65             mName(window.$);
66     }));
69 // open a new cascaded window
70 function cascwin(url, winname, width, height, options) {
71     var mywin = window.parent ? window.parent : window;
72     var newx = 25, newy = 25;
73     if (!isNaN(mywin.screenX)) {
74         newx += mywin.screenX;
75         newy += mywin.screenY;
76     } else if (!isNaN(mywin.screenLeft)) {
77         newx += mywin.screenLeft;
78         newy += mywin.screenTop;
79     }
80     if ((newx + width) > screen.width || (newy + height) > screen.height) {
81         newx = 0;
82         newy = 0;
83     }
84     top.restoreSession();
86     // MS IE version detection taken from
87     // http://msdn2.microsoft.com/en-us/library/ms537509.aspx
88     // to adjust the height of this box for IE only -- JRM
89     if (navigator.appName == 'Microsoft Internet Explorer') {
90         var ua = navigator.userAgent;
91         var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
92         if (re.exec(ua) != null)
93             rv = parseFloat(RegExp.$1); // this holds the version number
94         height = height + 28;
95     }
97     retval = window.open(url, winname, options +
98         ",width=" + width + ",height=" + height +
99         ",left=" + newx + ",top=" + newy +
100         ",screenX=" + newx + ",screenY=" + newy);
102     return retval;
105 // recursive window focus-event grabber
106 function grabfocus(w) {
107     for (var i = 0; i < w.frames.length; ++i) grabfocus(w.frames[i]);
108     w.onfocus = top.imfocused;
111 // Call this when a "modal" windowed dialog is desired.
112 // Note that the below function is free standing for either
113 // ui's.Use dlgopen() for responsive b.s modal dialogs.
114 // Can now use anywhere to cascade natives...12/1/17 sjp
116 function dlgOpenWindow(url, winname, width, height) {
117     if (top.modaldialog && !top.modaldialog.closed) {
118         if (window.focus) top.modaldialog.focus();
119         if (top.modaldialog.confirm(top.oemr_dialog_close_msg)) {
120             top.modaldialog.close();
121             top.modaldialog = null;
122         } else {
123             return false;
124         }
125     }
126     top.modaldialog = cascwin(url, winname, width, height,
127         "resizable=1,scrollbars=1,location=0,toolbar=0");
129     return false;
132 // This is called from del_related() which in turn is invoked by find_code_dynamic.php.
133 // Deletes the specified codetype:code from the indicated input text element.
134 function my_del_related(s, elem, usetitle) {
135     if (!s) {
136         // Deleting everything.
137         elem.value = '';
138         if (usetitle) {
139             elem.title = '';
140         }
141         return;
142     }
143     // Convert the codes and their descriptions to arrays for easy manipulation.
144     var acodes = elem.value.split(';');
145     var i = acodes.indexOf(s);
146     if (i < 0) {
147         return; // not found, should not happen
148     }
149     // Delete the indicated code and description and convert back to strings.
150     acodes.splice(i, 1);
151     elem.value = acodes.join(';');
152     if (usetitle) {
153         var atitles = elem.title.split(';');
154         atitles.splice(i, 1);
155         elem.title = atitles.join(';');
156     }
159 function dialogID() {
160     function s4() {
161         return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
162     }
164     return s4() + s4() + s4() + s4() + s4() + +s4() + s4() + s4();
167 // test for and/or remove dependency.
168 function inDom(dependency, type, remove) {
169     let el = type;
170     let attr = type === 'script' ? 'src' : type === 'link' ? 'href' : 'none';
171     let all = document.getElementsByTagName(el);
172     for (let i = all.length; i > -1; i--) {
173         if (all[i] && all[i].getAttribute(attr) !== null && all[i].getAttribute(attr).indexOf(dependency) !== -1) {
174             if (remove) {
175                 all[i].parentNode.removeChild(all[i]);
176                 console.log("Removed from DOM: " + dependency);
177                 return true;
178             } else {
179                 return true;
180             }
181         }
182     }
183     return false;
186 // test to see if bootstrap theming is loaded (via standard or custom bootstrap library)
187 //  Will check for the badge-secondary class
188 //   - if exist, then assume bootstrap loaded
189 //   - if not exist, then assume bootstrap not loaded
190 function isBootstrapCss() {
191     for (let i = 0; i < document.styleSheets.length; i++) {
192         let rules = document.styleSheets[i].rules || document.styleSheets[i].cssRules;
193         for (let x in rules) {
194             if (rules[x].selectorText == '.badge-secondary') {
195                 return true;
196             }
197         }
198     }
199     return false;
202 // These functions may be called from scripts that may be out of scope with top so...
203 // if opener is tab then we need to be in tabs UI scope and while we're at it, let's bring webroot along...
205 if (typeof top.webroot_url === "undefined" && opener) {
206     if (typeof opener.top.webroot_url !== "undefined") {
207         top.webroot_url = opener.top.webroot_url;
208     }
210 // We'll need these if out of scope
212 if (typeof top.set_opener !== "function") {
213     var opener_list = [];
215     function set_opener(window, opener) {
216         top.opener_list[window] = opener;
217     }
219     function get_opener(window) {
220         return top.opener_list[window];
221     }
224 // universal alert popup message
225 if (typeof alertMsg !== "function") {
226     function alertMsg(message, timer = 5000, type = 'danger', size = '', persist = '') {
227         // this xl() is just so cool.
228         let gotIt = xl("Got It");
229         let title = xl("Alert");
230         let dismiss = xl("Dismiss");
231         $('#alert_box').remove();
232         let oHidden = '';
233         oHidden = !persist ? "hidden" : '';
234         let oSize = (size == 'lg') ? 'left:10%;width:80%;' : 'left:25%;width:50%;';
235         let style = "position:fixed;top:25%;" + oSize + " bottom:0;z-index:9999;";
236         $("body").prepend("<div class='container text-center' id='alert_box' style='" + style + "'></div>");
237         let mHtml = '<div id="alertmsg" class="alert alert-' + type + ' alert-dismissable">' +
238             '<button type="button" class="btn btn-link ' + oHidden + '" id="dontShowAgain" data-dismiss="alert">' +
239             gotIt + '&nbsp;<i class="fa fa-thumbs-up"></i></button>' +
240             '<h4 class="alert-heading text-center">' + title + '!</h4><hr>' + '<p style="color:#000;">' + message + '</p>' +
241             '<button type="button" class="pull-right btn btn-link" data-dismiss="alert">' + dismiss + '</button><br /></div>';
242         $('#alert_box').append(mHtml);
243         $('#alertmsg').on('closed.bs.alert', function () {
244             clearTimeout(AlertMsg);
245             $('#alert_box').remove();
246             return false;
247         });
248         $('#dontShowAgain').on('click', function (e) {
249             persistUserOption(persist, 1);
250         });
251         let AlertMsg = setTimeout(function () {
252             $('#alertmsg').fadeOut(800, function () {
253                 $('#alert_box').remove();
254             });
255         }, timer);
256     }
258     const persistUserOption = function (option, value) {
259         return $.ajax({
260             url: top.webroot_url + "/library/ajax/user_settings.php",
261             type: 'post',
262             contentType: 'application/x-www-form-urlencoded',
263             data: {
264                 csrf_token_form: top.csrf_token_js,
265                 target: option,
266                 setting: value
267             },
268             beforeSend: function () {
269                 top.restoreSession();
270             },
271             error: function (jqxhr, status, errorThrown) {
272                 console.log(errorThrown);
273             }
274         });
275     };
279 // Test if supporting dialog callbacks and close dependencies are in scope.
280 // This is useful when opening and closing the dialog is in the same scope. Still use include_opener.js
281 // in script that will close a dialog that is not in the same scope dlgopen was used
282 // or use parent.dlgclose() if known decedent.
283 // dlgopen() will always have a name whether assigned by dev or created by function.
284 // Callback, onClosed and button clicks are still available either way.
285 // For a callback on close use: dlgclose(functionName, farg1, farg2 ...) which becomes: functionName(farg1,farg2, etc)
287 if (typeof dlgclose !== "function") {
288     if (!opener) {
289         opener = window;
290     }
292     function dlgclose(call, args) {
293         var frameName = window.name;
294         var wframe = top;
295         if (frameName === '') {
296             // try to find dialog. dialogModal is embedded dialog class
297             // It has to be here somewhere.
298             frameName = $(".dialogModal").attr('id');
299             if (!frameName) {
300                 frameName = parent.$(".dialogModal").attr('id');
301                 if (!frameName) {
302                     console.log("Unable to find dialog.");
303                     return false;
304                 }
305             }
306         }
307         var dialogModal = top.$('div#' + frameName);
309         var removeFrame = dialogModal.find("iframe[name='" + frameName + "']");
310         if (removeFrame.length > 0) {
311             removeFrame.remove();
312         }
314         if (dialogModal.length > 0) {
315             if (call) {
316                 wframe.setCallBack(call, args); // sets/creates callback function in dialogs scope.
317             }
318             dialogModal.modal('hide');
319         }
320     };
324 * function dlgopen(url, winname, width, height, forceNewWindow, title, opts)
326 * @summary Stackable, resizable and draggable responsive ajax/iframe dialog modal.
328 * @param {url} string Content location.
329 * @param {String} winname If set becomes modal id and/or iframes name. Or, one is created/assigned(iframes).
330 * @param {Number| String} width|modalSize(modal-xl) For sizing: an number will be converted to a percentage of view port width.
331 * @param {Number} height Initial minimum height. For iframe auto resize starts at this height.
332 * @param {boolean} forceNewWindow Force using a native window.
333 * @param {String} title If exist then header with title is created otherwise no header and content only.
334 * @param {Object} opts Dialogs options.
335 * @returns {Object} dialog object reference.
336 * */
337 function dlgopen(url, winname, width, height, forceNewWindow, title, opts) {
338     // First things first...
339     top.restoreSession();
340     // A matter of Legacy
341     if (forceNewWindow) {
342         return dlgOpenWindow(url, winname, width, height);
343     }
345     // wait for DOM then check dependencies needed to run this feature.
346     // dependency duration is while 'this' is in scope, temporary...
347     // seldom will this get used as more of U.I is moved to Bootstrap
348     // but better to continue than stop because of a dependency...
349     //
350     let jqurl = top.webroot_url + '/public/assets/jquery/dist/jquery.min.js';
351     if (typeof jQuery === 'undefined') {
352         (async (utilfn) => {
353             await includeScript(utilfn, 'script');
354         })(jqurl);
355     }
356     jQuery(function () {
357         // Check for dependencies we will need.
358         // webroot_url is a global defined in main_screen.php or main.php.
359         let bscss = top.webroot_url + '/public/assets/bootstrap/dist/css/bootstrap.min.css';
360         let bscssRtl = top.webroot_url + '/public/assets/bootstrap-v4-rtl/dist/css/bootstrap-rtl.min.css';
361         let bsurl = top.webroot_url + '/public/assets/bootstrap/dist/js/bootstrap.bundle.min.js';
363         let version = jQuery.fn.jquery.split(' ')[0].split('.');
364         if ((version[0] < 2 && version[1] < 9) || (version[0] === 1 && version[1] === 9 && version[2] < 1)) {
365             inDom('jquery-min', 'script', true);
366             (async (utilfn) => {
367                 await includeScript(utilfn, 'script');
368             })(jqurl).then(() => {
369                 console.log('Replacing jQuery version:[ ' + version + ' ]');
370             });
371         }
372         if (!isBootstrapCss()) {
373             (async (utilfn) => {
374                 await includeScript(utilfn, 'link');
375             })(bscss);
376             if (top.jsLanguageDirection == 'rtl') {
377                 (async (utilfn) => {
378                     await includeScript(utilfn, 'link');
379                 })(bscssRtl);
380             }
381         }
382         if (typeof jQuery.fn.modal === 'undefined') {
383             if (!inDom('bootstrap.bundle.min.js', 'script', false)) {
384                 (async (utilfn) => {
385                     await includeScript(utilfn, 'script');
386                 })(bsurl);
387             }
388         }
389     });
391     // onward
392     var opts_defaults = {
393         type: 'iframe', // POST, GET (ajax) or iframe
394         async: true,
395         frameContent: "", // for iframe embedded content
396         html: "", // content for alerts, comfirm etc ajax
397         allowDrag: true,
398         allowResize: true,
399         sizeHeight: 'auto', // 'full' will use as much height as allowed
400         // use is onClosed: fnName ... args not supported however, onClosed: 'reload' is auto defined and requires no function to be created.
401         onClosed: false,
402         callBack: false, // use {call: 'functionName, args: args, args} if known or use dlgclose.
403         resolvePromiseOn: 'init' // this may be useful values are init, shown, show and closed which coincide with dialog events.
404     };
406     if (!opts) {
407         opts = {};
408     }
409     opts = jQuery.extend({}, opts_defaults, opts);
410     opts.type = opts.type ? opts.type.toLowerCase() : '';
412     var mHeight, mWidth, mSize, msSize, dlgContainer, fullURL, where; // a growing list...
414     where = (opts.type === 'iframe') ? top : window;
416     // get url straight...
417     fullURL = "";
418     if (opts.url) {
419         url = opts.url;
420     }
421     if (url) {
422         if (url[0] === "/") {
423             fullURL = url
424         } else {
425             fullURL = window.location.href.substr(0, window.location.href.lastIndexOf("/") + 1) + url;
426         }
427     }
429     // what's a window without a name. important for stacking and opener.
430     winname = (winname === "_blank" || !winname) ? dialogID() : winname;
432     // for small screens or request width is larger than viewport.
433     if (where.innerWidth <= 768) {
434         width = "modal-xl";
435     }
436     // Convert dialog size to percentages and/or css class.
437     var sizeChoices = ['modal-sm', 'modal-md', 'modal-mlg', 'modal-lg', 'modal-xl'];
438     if (Math.abs(width) > 0) {
439         width = Math.abs(width);
440         mWidth = (width / where.innerWidth * 100).toFixed(1) + '%';
441         msSize = '<style>.modal-custom-' + winname + ' {max-width:' + mWidth + ' !important;}</style>';
442         mSize = 'modal-custom' + winname;
443     } else if (jQuery.inArray(width, sizeChoices) !== -1) {
444         mSize = width; // is a modal class
445     } else {
446         msSize = '<style>.modal-custom-' + winname + ' {max-width:35% !important;}</style>'; // standard B.S. modal default (modal-md)
447     }
448     // leave below for legacy
449     if (mSize === 'modal-sm') {
450         msSize = '<style>.modal-custom-' + winname + ' {max-width:25% !important;}</style>';
451     } else if (mSize === 'modal-md') {
452         msSize = '<style>.modal-custom-' + winname + ' {max-width:40% !important;}</style>';
453     } else if (mSize === 'modal-mlg') {
454         msSize = '<style>.modal-custom-' + winname + ' {max-width:55% !important;}</style>';
455     } else if (mSize === 'modal-lg') {
456         msSize = '<style>.modal-custom-' + winname + ' {max-width:75% !important;}</style>';
457     } else if (mSize === 'modal-xl') {
458         msSize = '<style>.modal-custom-' + winname + ' {max-width:92% !important;}</style>';
459     }
460     mSize = 'modal-custom-' + winname;
462     // Initial responsive height.
463     var vpht = where.innerHeight;
464     mHeight = height > 0 ? (height / vpht * 100).toFixed(1) + 'vh' : '';
466     // Build modal template. For now !title = !header and modal full height.
467     var mTitle = title > "" ? '<h5 class=modal-title>' + title + '</h5>' : '';
469     var waitHtml =
470         '<div class="loadProgress text-center">' +
471         '<span class="fa fa-circle-o-notch fa-spin fa-3x text-primary"></span>' +
472         '</div>';
474     var headerhtml =
475         ('<div class="modal-header">%title%<button type="button" class="close" data-dismiss="modal">' +
476             '&times;</button></div>').replace('%title%', mTitle);
478     var frameHtml =
479         ('<iframe id="modalframe" class="w-100 h-100 modalIframe" name="%winname%" %url% frameborder=0></iframe>').replace('%winname%', winname).replace('%url%', fullURL ? 'src=' + fullURL : '');
481     var bodyStyles = ('style="height:%initHeight%;"').replace('%initHeight%', opts.sizeHeight !== 'full' ? mHeight : '80vh');
483     var altClose = '<div class="closeDlgIframe" data-dismiss="modal" ></div>';
485     var mhtml =
486         ('<div id="%id%" class="modal fade dialogModal" tabindex="-1" role="dialog">%sizeStyle%' +
487             '<style>.drag-resize {touch-action:none;user-select:none;}</style>' +
488             '<div %dialogId% class="modal-dialog %drag-action% %sizeClass%" role="document">' +
489             '<div class="modal-content %resize-action%" style="max-height: 92vh">' + '%head%' + '%altclose%' + '%wait%' +
490             '<div class="modal-body overflow-auto px-1" %bodyStyles%>' + '%body%' + '</div></div></div></div>').replace('%id%', winname).replace('%sizeStyle%', msSize ? msSize : '').replace('%dialogId%', opts.dialogId ? ('id=' + opts.dialogId + '"') : '').replace('%sizeClass%', mSize ? mSize : '').replace('%head%', mTitle !== '' ? headerhtml : '').replace('%altclose%', mTitle === '' ? altClose : '').replace('%drag-action%', (opts.allowDrag) ? 'drag-action' : '').replace('%resize-action%', (opts.allowResize) ? 'resize-action' : '').replace('%wait%', '').replace('%bodyStyles%', bodyStyles).replace('%body%', opts.type === 'iframe' ? frameHtml : '');
492     // Write modal template.
493     dlgContainer = where.jQuery(mhtml);
494     dlgContainer.attr("name", winname);
496     // No url and just iframe content
497     if (opts.frameContent && opts.type === 'iframe') {
498         var ipath = 'data:text/html,' + encodeURIComponent(opts.frameContent);
499         dlgContainer.find("iframe[name='" + winname + "']").attr("src", ipath);
500     }
502     if (opts.buttons) {
503         dlgContainer.find('.modal-content').append(buildFooter());
504     }
505     // Ajax setup
506     if (opts.type === 'alert') {
507         dlgContainer.find('.modal-body').html(opts.html);
508     }
509     if (opts.type !== 'iframe' && opts.type !== 'alert') {
510         var params = {
511             async: opts.async,
512             method: opts.type || '', // if empty and has data object, then post else get.
513             content: opts.data || opts.html, // ajax loads fetched content.
514             url: opts.url || fullURL,
515             dataType: opts.dataType || '' // xml/json/text etc.
516         };
518         dialogAjax(params, dlgContainer, opts);
519     }
521     // let opener array know about us.
522     top.set_opener(winname, window);
524     // Write the completed template to calling document or 'where' window.
525     where.jQuery("body").append(dlgContainer);
527     // We promised
528     return new Promise((resolve, reject) => {
529         jQuery(function () {
530             // DOM Ready. Handle events and cleanup.
531             if (opts.type === 'iframe') {
532                 var modalwin = where.jQuery('body').find("[name='" + winname + "']");
533                 jQuery('div.modal-dialog', modalwin).css({'margin': '15px auto auto'});
534                 modalwin.on('load', function (e) {
535                     setTimeout(function () {
536                         if (opts.sizeHeight === 'auto') {
537                             SizeModaliFrame(e, height);
538                         } else if (opts.sizeHeight === 'fixed') {
539                             sizing(e, height);
540                         } else {
541                             sizing(e, height); // must be full height of container
542                         }
543                     }, 800);
544                 });
545             } else {
546                 var modalwin = where.jQuery('body').find("[name='" + winname + "']");
547                 jQuery('div.modal-dialog', modalwin).css({'margin': '15px auto auto'});
548                 modalwin.on('show.bs.modal', function (e) {
549                     setTimeout(function () {
550                         sizing(e, height);
551                     }, 800);
552                 });
553             }
555             // events chain.
556             dlgContainer.on('show.bs.modal', function () {
557                 if (opts.allowResize || opts.allowDrag) {
558                     initDragResize(where.document, where.document);
559                 }
561                 if (opts.resolvePromiseOn == 'show') {
562                     resolve(dlgContainer);
563                 }
564             }).on('shown.bs.modal', function () {
565                 // Remove waitHtml spinner/loader etc.
566                 jQuery(this).parent().find('div.loadProgress').fadeOut(function () {
567                     jQuery(this).remove();
568                 });
569                 dlgContainer.modal('handleUpdate'); // allow for scroll bar
571                 if (opts.resolvePromiseOn == 'shown') {
572                     resolve(dlgContainer);
573                 }
574             }).on('hidden.bs.modal', function (e) {
575                 // remove our dialog
576                 jQuery(this).remove();
577                 // now we can run functions in our window.
578                 if (opts.onClosed) {
579                     console.log('Doing onClosed:[' + opts.onClosed + ']');
580                     if (opts.onClosed === 'reload') {
581                         window.location.reload();
582                     } else {
583                         window[opts.onClosed]();
584                     }
585                 }
586                 if (opts.callBack.call) {
587                     console.log('Doing callBack:[' + opts.callBack.call + '|' + opts.callBack.args + ']');
588                     if (opts.callBack.call === 'reload') {
589                         window.location.reload();
590                     } else {
591                         window[opts.callBack.call](opts.callBack.args);
592                     }
593                 }
595                 if (opts.resolvePromiseOn == 'close') {
596                     resolve(dlgContainer);
597                 }
598             });
600             // define local dialog close() function. openers scope
601             window.dlgCloseAjax = function (calling, args) {
602                 if (calling) {
603                     opts.callBack = {call: calling, args: args};
604                 }
605                 dlgContainer.modal('hide'); // important to clean up in only one place, hide event....
606                 return false;
607             };
609             // define local callback function. Set with opener or from opener, will exe on hide.
610             window.dlgSetCallBack = function (calling, args) {
611                 opts.callBack = {call: calling, args: args};
612                 return false;
613             };
615             // in residents dialog scope
616             where.setCallBack = function (calling, args) {
617                 opts.callBack = {call: calling, args: args};
618                 return true;
619             };
621             where.getOpener = function () {
622                 return where;
623             };
624             // dialog is completely built and events set
625             // this is default returning our dialog container reference.
626             if (opts.resolvePromiseOn == 'init') {
627                 resolve(dlgContainer);
628             }
629             // Finally Show Dialog after DOM settles
630             dlgContainer.modal({backdrop: 'static', keyboard: true}, 'show');
631         }); // end events
632     }); /* Returning Promise */
634     // Ajax call with promise via dialog
635     function dialogAjax(data, $dialog, opts) {
636         var params = {
637             async: data.async,
638             method: data.method || '',
639             data: data.content,
640             url: data.url,
641             dataType: data.dataType || 'html'
642         };
644         if (data.url) {
645             jQuery.extend(params, data);
646         }
648         jQuery.ajax(params).done(aOkay).fail(oops);
650         return true;
652         function aOkay(html) {
653             opts.ajax = true;
654             $dialog.find('.modal-body').html(data.success ? data.success(html) : html);
656             return true;
657         }
659         function oops(r, s) {
660             var msg = data.error ?
661                 data.error(r, s, params) :
662                 '<div class="alert alert-danger">' +
663                 '<strong>XHR Failed:</strong> [ ' + params.url + '].' + '</div>';
665             $dialog.find('.modal-body').html(msg);
667             return false;
668         }
669     }
671     function buildFooter() {
672         if (opts.buttons === false) {
673             return '';
674         }
675         var oFoot = jQuery('<div>').addClass('modal-footer').prop('id', 'oefooter');
676         if (opts.buttons) {
677             for (var i = 0, k = opts.buttons.length; i < k; i++) {
678                 var btnOp = opts.buttons[i];
679                 if (typeof btnOp.class !== 'undefined') {
680                     btnOp.class = btnOp.class.replace(/default/gi, 'secondary');
681                     var btn = jQuery('<button>').addClass('btn ' + (btnOp.class || 'btn-primary'));
682                 } else { // legacy
683                     btnOp.style = btnOp.style.replace(/default/gi, 'secondary');
684                     var btn = jQuery('<button>').addClass('btn btn-' + (btnOp.style || 'primary'));
685                     btnOp.style = "";
686                 }
687                 for (var index in btnOp) {
688                     if (btnOp.hasOwnProperty(index)) {
689                         switch (index) {
690                             case 'close':
691                                 //add close event
692                                 if (btnOp[index]) {
693                                     btn.attr('data-dismiss', 'modal');
694                                 }
695                                 break;
696                             case 'click':
697                                 //binds button to click event of fn defined in calling document/form
698                                 var fn = btnOp.click.bind(dlgContainer.find('.modal-content'));
699                                 btn.click(fn);
700                                 break;
701                             case 'text':
702                                 btn.html(btnOp[index]);
703                                 break;
704                             case 'class':
705                                 break;
706                             default:
707                                 //all other possible HTML attributes to button element
708                                 // name, id etc
709                                 btn.attr(index, btnOp[index]);
710                         }
711                     }
712                 }
714                 oFoot.append(btn);
715             }
716         }
717         return oFoot; // jquery object of modal footer.
718     }
720     // dynamic sizing - special case for full height
721     function sizing(e, height) {
722         let viewPortHt = 0;
723         let $idoc = jQuery(e.currentTarget);
724         viewPortHt = Math.max(window.document.documentElement.clientHeight, window.innerHeight || 0);
725         let frameContentHt = opts.sizeHeight === 'full' ? viewPortHt : height;
726         frameContentHt = frameContentHt >= viewPortHt ? viewPortHt : frameContentHt;
727         size = (frameContentHt / viewPortHt * 100).toFixed(2);
728         size = size + 'vh';
729         $idoc.find('div.modal-content').css({'height': size});
731         return size;
732     }
734     // sizing for modals with iframes
735     function SizeModaliFrame(e, minSize) {
736         let viewPortHt;
737         let idoc = e.currentTarget.contentDocument ? e.currentTarget.contentDocument : e.currentTarget.contentWindow.document;
738         jQuery(e.currentTarget).parents('div.modal-body').css({'height': 0});
739         viewPortHt = top.window.innerHeight;
740         let frameContentHt = Math.max(jQuery(idoc).height(), idoc.body.offsetHeight) + 40;
741         frameContentHt = frameContentHt < minSize ? minSize : frameContentHt;
742         frameContentHt = frameContentHt >= viewPortHt ? viewPortHt : frameContentHt;
743         size = (frameContentHt / viewPortHt * 100).toFixed(1);
744         size = size + 'vh'; // will start the dialog as responsive. Any resize by user turns dialog to absolute positioning.
745         jQuery(e.currentTarget).parents('div.modal-body').css({'height': size});
747         return size;
748     }