Fix for exporting a large number of lists.
[openemr.git] / library / dialog.js
blob3b693e3249fa71a4396e7e4c534654a8777165e4
1 // Copyright (C) 2005 Rod Roark <rod@sunsetsystems.com>
2 // Copyright (C) 2018-2021 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.confirm = confirm;
16         root.closeAjax = closeAjax;
17         root.close = close;
18         root.popUp = popUp;
19         return root;
21         function ajax(data) {
22             let opts = {
23                 buttons: data.buttons,
24                 allowDrag: data.allowDrag,
25                 allowResize: data.allowResize,
26                 sizeHeight: data.sizeHeight,
27                 type: data.type,
28                 resolvePromiseOn: data.resolvePromiseOn,
29                 data: data.data,
30                 url: data.url,
31                 dataType: data.dataType // xml/json/text etc.
32             };
34             let title = data.title;
36             return dlgopen('', '', data.size, 0, '', title, opts);
37         }
39         function alert(data, title) {
40             title = title ? title : 'Alert';
41             let alertTitle = '<span class="text-danger bg-light"><i class="fa fa-exclamation-triangle"></i>&nbsp;' + title + '</span>';
42             return dlgopen('', '', 675, 0, '', alertTitle, {
43                 buttons: [
44                     {text: 'OK', close: true, style: 'primary'}
45                 ],
46                 type: 'Alert',
47                 sizeHeight: 'auto',
48                 resolvePromiseOn: 'close',
49                 html: '<p class="text-center">' + data + '</p>'
50             });
51         }
53         function confirm(data, title) {
54             title = title ? title : 'Confirm';
55             let alertTitle = '<span class="text-info bg-light"><i class="fa fa-exclamation-triangle"></i>&nbsp;' + title + '</span>';
56             return dlgopen('', '', "modal-md", 0, '', alertTitle, {
57                 buttons: [
58                     {text: 'Yes', close: true, id: 'confirmYes', style: 'primary'},
59                     {text: '<i class="fa fa-thumbs-down mr-1"></i>No', close: true, id: 'confirmNo', style: 'primary'},
60                     {text: 'Nevermind', close: true, style: 'secondary'}
61                 ],
62                 type: 'Confirm',
63                 resolvePromiseOn: 'confirm',
64                 sizeHeight: 'auto',
65                 html: '<p class="text-center">' + data + '</p>'
66             });
67         }
69         /* popUp
70         * Borrowed from a CKEditor Source plugin and modified to suit my purpose.
71         * Licensed under the GPL 2 or greater.
72         * @license Copyright (c) 2003-2021, CKSource - Frederico Knabben. All rights reserved.
73         * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
74         */
75         function popUp( url, data, name, width, height) {
76             width = width || '80%'; height = height || '85%';
78             if ( typeof width == 'string' && width.length > 1 && width.substr( width.length - 1, 1 ) === '%') {
79                 width = parseInt(window.screen.width * parseInt(width, 10) / 100, 10);
80             }
81             if ( typeof height == 'string' && height.length > 1 && height.substr( height.length - 1, 1 ) === '%') {
82                 height = parseInt(window.screen.height * parseInt(height, 10) / 100, 10);
83             }
84             if ( width < 640 ) {
85                 width = 640;
86             }
87             if ( height < 420 ) {
88                 height = 420;
89             }
90             let top = parseInt(( window.screen.height - height ) / 2, 10);
91             let left = parseInt(( window.screen.width - width ) / 2, 10);
93             let options = ('location=no,menubar=no,toolbar=no,dependent=yes,minimizable=no,modal=yes,alwaysRaised=yes,resizable=yes,scrollbars=yes') +
94                 ',width=' + width +
95                 ',height=' + height +
96                 ',top=' + top +
97                 ',left=' + left;
99             let modalWindow = window.open('', name, options, true);
100             if ( !modalWindow ) {
101                 return false;
102             }
103             try {
104                 modalWindow.focus();
105                 if (data) {
106                     modalWindow.document.body.innerHTML = data;
107                 } else {
108                     modalWindow.location.href = url;
109                 }
110             } catch ( e ) {
111                 window.open(url, null, options, true);
112             }
114             return true;
115         }
117         function closeAjax() {
118             dlgCloseAjax();
119         }
121         function close() {
122             dlgclose();
123         }
124     });
126     if (typeof includeScript !== 'function') {
127         // Obviously utility.js has not been included for an unknown reason!
128         // Will include below.
129         function includeScript(srcUrl, type) {
130             return new Promise(function (resolve, reject) {
131                 if (type == 'script') {
132                     let newScriptElement = document.createElement('script');
133                     newScriptElement.src = srcUrl;
134                     newScriptElement.onload = () => resolve(newScriptElement);
135                     newScriptElement.onerror = () => reject(new Error(`Script load error for ${srcUrl}`));
137                     document.head.append(newScriptElement);
138                     console.log('Needed to load:[' + srcUrl + '] For: [' + location + ']');
139                 }
140                 if (type === "link") {
141                     let newScriptElement = document.createElement("link")
142                     newScriptElement.type = "text/css";
143                     newScriptElement.rel = "stylesheet";
144                     newScriptElement.href = srcUrl;
145                     newScriptElement.onload = () => resolve(newScriptElement);
146                     newScriptElement.onerror = () => reject(new Error(`Link load error for ${srcUrl}`));
148                     document.head.append(newScriptElement);
149                     console.log('Needed to load:[' + srcUrl + '] For: [' + location + ']');
150                 }
151             });
152         }
153     }
154     if (typeof window.xl !== 'function') {
155         (async (utilfn) => {
156             await includeScript(utilfn, 'script');
157         })(top.webroot_url + '/library/js/utility.js')
158     }
159 }(typeof define == 'function' && define.amd ?
160     define :
161     function (args, mName) {
162         this.dialog = typeof module != 'undefined' && module.exports ?
163             mName(require(args[0], {}), module.exports) :
164             mName(window.$);
165     }));
168 // open a new cascaded window
169 function cascwin(url, winname, width, height, options) {
170     var mywin = window.parent ? window.parent : window;
171     var newx = 25, newy = 25;
172     if (!isNaN(mywin.screenX)) {
173         newx += mywin.screenX;
174         newy += mywin.screenY;
175     } else if (!isNaN(mywin.screenLeft)) {
176         newx += mywin.screenLeft;
177         newy += mywin.screenTop;
178     }
179     if ((newx + width) > screen.width || (newy + height) > screen.height) {
180         newx = 0;
181         newy = 0;
182     }
183     if (typeof top.restoreSession === 'function') {
184         top.restoreSession();
185     }
187     // MS IE version detection taken from
188     // http://msdn2.microsoft.com/en-us/library/ms537509.aspx
189     // to adjust the height of this box for IE only -- JRM
190     if (navigator.appName == 'Microsoft Internet Explorer') {
191         var ua = navigator.userAgent;
192         var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
193         if (re.exec(ua) != null)
194             rv = parseFloat(RegExp.$1); // this holds the version number
195         height = height + 28;
196     }
198     retval = window.open(url, winname, options +
199         ",width=" + width + ",height=" + height +
200         ",left=" + newx + ",top=" + newy +
201         ",screenX=" + newx + ",screenY=" + newy);
203     return retval;
206 // recursive window focus-event grabber
207 function grabfocus(w) {
208     for (var i = 0; i < w.frames.length; ++i) grabfocus(w.frames[i]);
209     w.onfocus = top.imfocused;
212 // Call this when a "modal" windowed dialog is desired.
213 // Note that the below function is free standing for either
214 // ui's.Use dlgopen() for responsive b.s modal dialogs.
215 // Can now use anywhere to cascade natives...12/1/17 sjp
217 function dlgOpenWindow(url, winname, width, height) {
218     if (top.modaldialog && !top.modaldialog.closed) {
219         if (window.focus) top.modaldialog.focus();
220         if (top.modaldialog.confirm(top.oemr_dialog_close_msg)) {
221             top.modaldialog.close();
222             top.modaldialog = null;
223         } else {
224             return false;
225         }
226     }
227     top.modaldialog = cascwin(url, winname, width, height,
228         "resizable=1,scrollbars=1,location=0,toolbar=0");
230     return false;
233 // This is called from del_related() which in turn is invoked by find_code_dynamic.php.
234 // Deletes the specified codetype:code from the indicated input text element.
235 function my_del_related(s, elem, usetitle) {
236     if (!s) {
237         // Deleting everything.
238         elem.value = '';
239         if (usetitle) {
240             elem.title = '';
241         }
242         return;
243     }
244     // Convert the codes and their descriptions to arrays for easy manipulation.
245     var acodes = elem.value.split(';');
246     var i = acodes.indexOf(s);
247     if (i < 0) {
248         return; // not found, should not happen
249     }
250     // Delete the indicated code and description and convert back to strings.
251     acodes.splice(i, 1);
252     elem.value = acodes.join(';');
253     if (usetitle) {
254         var atitles = elem.title.split(';');
255         atitles.splice(i, 1);
256         elem.title = atitles.join(';');
257     }
260 function dialogID() {
261     function s4() {
262         return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
263     }
265     return s4() + s4() + s4() + s4() + s4() + +s4() + s4() + s4();
268 // test for and/or remove dependency.
269 function inDom(dependency, type, remove) {
270     let el = type;
271     let attr = type === 'script' ? 'src' : type === 'link' ? 'href' : 'none';
272     let all = document.getElementsByTagName(el);
273     for (let i = all.length; i > -1; i--) {
274         if (all[i] && all[i].getAttribute(attr) !== null && all[i].getAttribute(attr).indexOf(dependency) !== -1) {
275             if (remove) {
276                 all[i].parentNode.removeChild(all[i]);
277                 console.log("Removed from DOM: " + dependency);
278                 return true;
279             } else {
280                 return true;
281             }
282         }
283     }
284     return false;
287 // test to see if bootstrap theming is loaded (via standard or custom bootstrap library)
288 //  Will check for the badge-secondary class
289 //   - if exist, then assume bootstrap loaded
290 //   - if not exist, then assume bootstrap not loaded
291 function isBootstrapCss() {
292     for (let i = 0; i < document.styleSheets.length; i++) {
293         let rules = document.styleSheets[i].rules || document.styleSheets[i].cssRules;
294         for (let x in rules) {
295             if (rules[x].selectorText == '.badge-secondary') {
296                 return true;
297             }
298         }
299     }
300     return false;
303 // These functions may be called from scripts that may be out of scope with top so...
304 // if opener is tab then we need to be in tabs UI scope and while we're at it, let's bring webroot along...
306 if (typeof top.webroot_url === "undefined" && opener) {
307     if (typeof opener.top.webroot_url !== "undefined") {
308         top.webroot_url = opener.top.webroot_url;
309     }
311 // We'll need these if out of scope
313 if (typeof top.set_opener !== "function") {
314     var opener_list = [];
316     function set_opener(window, opener) {
317         top.opener_list[window] = opener;
318     }
320     function get_opener(window) {
321         return top.opener_list[window];
322     }
325 // universal alert popup message
326 if (typeof alertMsg !== "function") {
327     function alertMsg(message, timer = 5000, type = 'danger', size = '', persist = '') {
328         // this xl() is just so cool.
329         let gotIt = xl("Got It");
330         let title = xl("Alert");
331         let dismiss = xl("Dismiss");
332         $('#alert_box').remove();
333         let oHidden = '';
334         oHidden = !persist ? "hidden" : '';
335         let oSize = (size == 'lg') ? 'left:10%;width:80%;' : 'left:25%;width:50%;';
336         let style = "position:fixed;top:25%;" + oSize + " bottom:0;z-index:9999;";
337         $("body").prepend("<div class='container text-center' id='alert_box' style='" + style + "'></div>");
338         let mHtml = '<div id="alertmsg" class="alert alert-' + type + ' alert-dismissable">' +
339             '<button type="button" class="btn btn-link ' + oHidden + '" id="dontShowAgain" data-dismiss="alert">' +
340             gotIt + '&nbsp;<i class="fa fa-thumbs-up"></i></button>' +
341             '<h4 class="alert-heading text-center">' + title + '!</h4><hr>' + '<p style="color:#000;">' + message + '</p>' +
342             '<button type="button" class="pull-right btn btn-link" data-dismiss="alert">' + dismiss + '</button><br /></div>';
343         $('#alert_box').append(mHtml);
344         $('#alertmsg').on('closed.bs.alert', function () {
345             clearTimeout(AlertMsg);
346             $('#alert_box').remove();
347             return false;
348         });
349         $('#dontShowAgain').on('click', function (e) {
350             persistUserOption(persist, 1);
351         });
352         let AlertMsg = setTimeout(function () {
353             $('#alertmsg').fadeOut(800, function () {
354                 $('#alert_box').remove();
355             });
356         }, timer);
357     }
359     const persistUserOption = function (option, value) {
360         return $.ajax({
361             url: top.webroot_url + "/library/ajax/user_settings.php",
362             type: 'post',
363             contentType: 'application/x-www-form-urlencoded',
364             data: {
365                 csrf_token_form: top.csrf_token_js,
366                 target: option,
367                 setting: value
368             },
369             beforeSend: function () {
370                 if (typeof top.restoreSession === 'function') {
371                     top.restoreSession();
372                 }
373             },
374             error: function (jqxhr, status, errorThrown) {
375                 console.log(errorThrown);
376             }
377         });
378     };
382 // Test if supporting dialog callbacks and close dependencies are in scope.
383 // This is useful when opening and closing the dialog is in the same scope. Still use include_opener.js
384 // in script that will close a dialog that is not in the same scope dlgopen was used
385 // or use parent.dlgclose() if known decedent.
386 // dlgopen() will always have a name whether assigned by dev or created by function.
387 // Callback, onClosed and button clicks are still available either way.
388 // For a callback on close use: dlgclose(functionName, farg1, farg2 ...) which becomes: functionName(farg1,farg2, etc)
390 if (typeof dlgclose !== "function") {
391     if (!opener) {
392         opener = window;
393     }
395     function dlgclose(call, args) {
396         var frameName = window.name;
397         var wframe = top;
398         if (frameName === '') {
399             // try to find dialog. dialogModal is embedded dialog class
400             // It has to be here somewhere.
401             frameName = $(".dialogModal").attr('id');
402             if (!frameName) {
403                 frameName = parent.$(".dialogModal").attr('id');
404                 if (!frameName) {
405                     console.log("Unable to find dialog.");
406                     return false;
407                 }
408             }
409         }
410         var dialogModal = top.$('div#' + frameName);
412         var removeFrame = dialogModal.find("iframe[name='" + frameName + "']");
413         if (removeFrame.length > 0) {
414             removeFrame.remove();
415         }
417         if (dialogModal.length > 0) {
418             if (call) {
419                 wframe.setCallBack(call, args); // sets/creates callback function in dialogs scope.
420             }
421             dialogModal.modal('hide');
422         } else {
423             // no opener not iframe must be in here
424             $(this.document).find(".dialogModal").modal('hide');
425         }
426     }
430 * function dlgopen(url, winname, width, height, forceNewWindow, title, opts)
432 * @summary Stackable, resizable and draggable responsive ajax/iframe dialog modal.
434 * @param {url} string Content location.
435 * @param {String} winname If set becomes modal id and/or iframes name. Or, one is created/assigned(iframes).
436 * @param {Number| String} width|modalSize(modal-xl) For sizing: an number will be converted to a percentage of view port width.
437 * @param {Number} height Initial minimum height. For iframe auto resize starts at this height.
438 * @param {boolean} forceNewWindow Force using a native window.
439 * @param {String} title If exist then header with title is created otherwise no header and content only.
440 * @param {Object} opts Dialogs options.
441 * @returns {Object} dialog object reference.
442 * */
443 function dlgopen(url, winname, width, height, forceNewWindow, title, opts) {
444     // First things first...
445     if (typeof top.restoreSession === 'function') {
446         top.restoreSession();
447     }
449     // A matter of Legacy
450     if (forceNewWindow) {
451         return dlgOpenWindow(url, winname, width, height);
452     }
454     // wait for DOM then check dependencies needed to run this feature.
455     // dependency duration is while 'this' is in scope, temporary...
456     // seldom will this get used as more of U.I is moved to Bootstrap
457     // but better to continue than stop because of a dependency...
458     //
459     let jqurl = top.webroot_url + '/public/assets/jquery/dist/jquery.min.js';
460     if (typeof jQuery === 'undefined') {
461         (async (utilfn) => {
462             await includeScript(utilfn, 'script');
463         })(jqurl);
464     }
465     jQuery(function () {
466         // Check for dependencies we will need.
467         // webroot_url is a global defined in main_screen.php or main.php.
468         let bscss = top.webroot_url + '/public/assets/bootstrap/dist/css/bootstrap.min.css';
469         let bscssRtl = top.webroot_url + '/public/assets/bootstrap-v4-rtl/dist/css/bootstrap-rtl.min.css';
470         let bsurl = top.webroot_url + '/public/assets/bootstrap/dist/js/bootstrap.bundle.min.js';
472         let version = jQuery.fn.jquery.split(' ')[0].split('.');
473         if ((version[0] < 2 && version[1] < 9) || (version[0] === 1 && version[1] === 9 && version[2] < 1)) {
474             inDom('jquery-min', 'script', true);
475             (async (utilfn) => {
476                 await includeScript(utilfn, 'script');
477             })(jqurl).then(() => {
478                 console.log('Replacing jQuery version:[ ' + version + ' ]');
479             });
480         }
481         if (!isBootstrapCss()) {
482             (async (utilfn) => {
483                 await includeScript(utilfn, 'link');
484             })(bscss);
485             if (top.jsLanguageDirection == 'rtl') {
486                 (async (utilfn) => {
487                     await includeScript(utilfn, 'link');
488                 })(bscssRtl);
489             }
490         }
491         if (typeof jQuery.fn.modal === 'undefined') {
492             if (!inDom('bootstrap.bundle.min.js', 'script', false)) {
493                 (async (utilfn) => {
494                     await includeScript(utilfn, 'script');
495                 })(bsurl);
496             }
497         }
498     });
500     // onward
501     var opts_defaults = {
502         type: 'iframe', // POST, GET (ajax) or iframe
503         async: true,
504         frameContent: "", // for iframe embedded content
505         html: "", // content for alerts, comfirm etc ajax
506         allowDrag: false,
507         allowResize: true,
508         sizeHeight: 'auto', // 'full' will use as much height as allowed
509         // use is onClosed: fnName ... args not supported however, onClosed: 'reload' is auto defined and requires no function to be created.
510         onClosed: false,
511         allowExternal: false, // allow a dialog window to a URL that is external to the current url
512         callBack: false, // use {call: 'functionName, args: args, args} if known or use dlgclose.
513         resolvePromiseOn: '' // this may be useful. values are init, shown, show, confirm, alert and close which coincide with dialog events.
514     };
516     if (!opts) {
517         opts = {};
518     }
519     opts = jQuery.extend({}, opts_defaults, opts);
520     opts.type = opts.type ? opts.type.toLowerCase() : '';
521     opts.resolvePromiseOn = opts.resolvePromiseOn ?? 'init';
522     var mHeight, mWidth, mSize, msSize, dlgContainer, fullURL, where; // a growing list...
524     where = (opts.type === 'iframe') ? top : window;
526     // get url straight...
527     fullURL = "";
528     if (opts.url) {
529         url = opts.url;
530     }
531     if (url) {
532         if (url[0] === "/") {
533             fullURL = url
534         } else if (opts.allowExternal === true) {
535             var checkUrl = new URL(url);
536             // we only allow http & https protocols to be launched
537             if (checkUrl.protocol === "http:" || checkUrl.protocol == "https:") {
538                 fullURL = url;
539             }
540         } else {
541             fullURL = window.location.href.substr(0, window.location.href.lastIndexOf("/") + 1) + url;
542         }
543     }
545     // what's a window without a name. important for stacking and opener.
546     winname = (winname === "_blank" || !winname) ? dialogID() : winname;
548     // for small screens or request width is larger than viewport.
549     if (where.innerWidth <= 1080) {
550         width = "modal-full";
551     }
552     // Convert dialog size to percentages and/or css class.
553     var sizeChoices = ['modal-sm', 'modal-md', 'modal-mlg', 'modal-lg', 'modal-xl', 'modal-full'];
554     if (Math.abs(width) > 0) {
555         width = Math.abs(width);
556         mWidth = (width / where.innerWidth * 100).toFixed(1) + '%';
557         msSize = '<style>.modal-custom-' + winname + ' {max-width:' + mWidth + ' !important;}</style>';
558         mSize = 'modal-custom' + winname;
559     } else if (jQuery.inArray(width, sizeChoices) !== -1) {
560         mSize = width; // is a modal class
561     } else {
562         msSize = '<style>.modal-custom-' + winname + ' {max-width:35% !important;}</style>'; // standard B.S. modal default (modal-md)
563     }
564     // leave below for legacy
565     if (mSize === 'modal-sm') {
566         msSize = '<style>.modal-custom-' + winname + ' {max-width:25% !important;}</style>';
567     } else if (mSize === 'modal-md') {
568         msSize = '<style>.modal-custom-' + winname + ' {max-width:40% !important;}</style>';
569     } else if (mSize === 'modal-mlg') {
570         msSize = '<style>.modal-custom-' + winname + ' {max-width:55% !important;}</style>';
571     } else if (mSize === 'modal-lg') {
572         msSize = '<style>.modal-custom-' + winname + ' {max-width:75% !important;}</style>';
573     } else if (mSize === 'modal-xl') {
574         msSize = '<style>.modal-custom-' + winname + ' {max-width:92% !important;}</style>';
575     } else if (mSize === 'modal-full') {
576         msSize = '<style>.modal-custom-' + winname + ' {max-width:97% !important;}</style>';
577     }
578     mSize = 'modal-custom-' + winname;
580     // Initial responsive height.
581     let vpht = where.innerHeight;
582     if (height <= 300 && opts.type === 'iframe') {
583         height = 300;
584     }
585     mHeight = height > 0 ? (height / vpht * 100).toFixed(1) + 'vh' : '';
587     // Build modal template. For now !title = !header and modal full height.
588     var mTitle = title > "" ? '<h5 class=modal-title>' + title + '</h5>' : '';
590     var waitHtml =
591         '<div class="loadProgress text-center">' +
592         '<span class="fa fa-circle-notch fa-spin fa-3x text-primary"></span>' +
593         '</div>';
595     var headerhtml =
596         ('<div class="modal-header">%title%<button type="button" class="close" data-dismiss="modal">' +
597             '&times;</button></div>').replace('%title%', mTitle);
599     var frameHtml =
600         ('<iframe id="modalframe" class="modalIframe w-100 h-100 border-0" name="%winname%" %url%></iframe>').replace('%winname%', winname).replace('%url%', fullURL ? 'src=' + fullURL : '');
602     var contentStyles = ('style="height:%initHeight%; max-height: 94vh"').replace('%initHeight%', opts.sizeHeight !== 'full' ? mHeight : '90vh');
604     var altClose = '<div class="closeDlgIframe" data-dismiss="modal" ></div>';
606     var mhtml =
607         ('<div id="%id%" class="modal fade dialogModal" tabindex="-1" role="dialog">%sizeStyle%' +
608             '<style>.drag-resize {touch-action:none;user-select:none;}</style>' +
609             '<div %dialogId% class="modal-dialog %drag-action% %sizeClass%" role="dialog">' +
610             '<div class="modal-content %resize-action%" %contentStyles%>' + '%head%' + '%altclose%' + '%wait%' +
611             '<div class="modal-body px-1 h-100">' + '%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('%contentStyles%', contentStyles).replace('%body%', opts.type === 'iframe' ? frameHtml : '');
613     // Write modal template.
614     dlgContainer = where.jQuery(mhtml);
615     dlgContainer.attr("name", winname);
617     // No url and just iframe content
618     if (opts.frameContent && opts.type === 'iframe') {
619         var ipath = 'data:text/html,' + encodeURIComponent(opts.frameContent);
620         dlgContainer.find("iframe[name='" + winname + "']").attr("src", ipath);
621     }
623     if (opts.buttons) {
624         dlgContainer.find('.modal-content').append(buildFooter());
625     }
626     // Ajax setup
627     if (opts.type === 'alert') {
628         dlgContainer.find('.modal-body').html(opts.html);
629     }
630     if (opts.type === 'confirm') {
631         dlgContainer.find('.modal-body').html(opts.html);
632     }
633     if (opts.type !== 'iframe' && opts.type !== 'alert' && opts.type !== 'confirm') {
634         var params = {
635             async: opts.async,
636             method: opts.type || '', // if empty and has data object, then post else get.
637             content: opts.data || opts.html, // ajax loads fetched content.
638             url: opts.url || fullURL,
639             dataType: opts.dataType || '' // xml/json/text etc.
640         };
642         dialogAjax(params, dlgContainer, opts);
643     }
645     // let opener array know about us.
646     top.set_opener(winname, window);
648     // Write the completed template to calling document or 'where' window.
649     where.jQuery("body").append(dlgContainer);
651     // We promised
652     return new Promise((resolve, reject) => {
653         jQuery(function () {
654             // DOM Ready. Handle events and cleanup.
655             if (opts.type === 'iframe') {
656                 var modalwin = where.jQuery('body').find("[name='" + winname + "']");
657                 jQuery('div.modal-dialog', modalwin).css({'margin': "0.75rem auto auto"});
658                 modalwin.on('load', function (e) {
659                     setTimeout(function () {
660                         if (opts.sizeHeight === 'auto' && opts.type === 'iframe') {
661                             SizeModaliFrame(e, height);
662                         } else if (opts.sizeHeight === 'fixed') {
663                             sizing(e, height);
664                         } else {
665                             sizing(e, height); // must be full height of container
666                         }
667                     }, 800);
668                 });
669             } else {
670                 var modalwin = where.jQuery('body').find("[name='" + winname + "']");
671                 jQuery('div.modal-dialog', modalwin).css({'margin': '15px auto auto'});
672                 modalwin.on('show.bs.modal', function (e) {
673                     setTimeout(function () {
674                         sizing(e, height);
675                     }, 800);
676                 });
677             }
678             if (opts.resolvePromiseOn === 'confirm') {
679                 jQuery("#confirmYes").on('click', function (e) {
680                     resolve(true);
681                 });
682                 jQuery("#confirmNo").on('click', function (e) {
683                     resolve(false);
684                 });
685             }
686             // events chain.
687             dlgContainer.on('show.bs.modal', function () {
688                 if (opts.allowResize || opts.allowDrag) {
689                     initDragResize(where.document, where.document);
690                 }
692                 if (opts.resolvePromiseOn === 'show') {
693                     resolve(dlgContainer);
694                 }
695             }).on('shown.bs.modal', function () {
696                 // Remove waitHtml spinner/loader etc.
697                 jQuery(this).parent().find('div.loadProgress').fadeOut(function () {
698                     jQuery(this).remove();
699                 });
700                 dlgContainer.modal('handleUpdate'); // allow for scroll bar
702                 if (opts.resolvePromiseOn === 'shown') {
703                     resolve(dlgContainer);
704                 }
705             }).on('hidden.bs.modal', function (e) {
706                 // clear cursor
707                 e.target.style.cursor = "pointer";
708                 // remove our dialog
709                 jQuery(this).remove();
710                 // now we can run functions in our window.
711                 if (opts.onClosed) {
712                     console.log('Doing onClosed:[' + opts.onClosed + ']');
713                     if (opts.onClosed === 'reload') {
714                         window.location.reload();
715                     } else {
716                         window[opts.onClosed]();
717                     }
718                 }
719                 if (opts.callBack.call) {
720                     console.log('Doing callBack:[' + opts.callBack.call + '|' + opts.callBack.args + ']');
721                     if (opts.callBack.call === 'reload') {
722                         window.location.reload();
723                     } else if (typeof opts.callBack.call == 'string') {
724                         window[opts.callBack.call](opts.callBack.args);
725                     } else {
726                         opts.callBack.call(opts.callBack.args);
727                     }
728                 }
730                 if (opts.resolvePromiseOn == 'close') {
731                     resolve(dlgContainer);
732                 }
733             });
735             // define local dialog close() function. openers scope
736             window.dlgCloseAjax = function (calling, args) {
737                 if (calling) {
738                     opts.callBack = {call: calling, args: args};
739                 }
740                 dlgContainer.modal('hide'); // important to clean up in only one place, hide event....
741                 return false;
742             };
744             // define local callback function. Set with opener or from opener, will exe on hide.
745             window.dlgSetCallBack = function (calling, args) {
746                 opts.callBack = {call: calling, args: args};
747                 return false;
748             };
750             // in residents dialog scope
751             where.setCallBack = function (calling, args) {
752                 opts.callBack = {call: calling, args: args};
753                 return true;
754             };
756             where.getOpener = function () {
757                 return where;
758             };
759             // dialog is completely built and events set
760             // this is default returning our dialog container reference.
761             if (opts.resolvePromiseOn == 'init') {
762                 resolve(dlgContainer);
763             }
764             // Finally Show Dialog after DOM settles
765             dlgContainer.modal({backdrop: 'static', keyboard: true}, 'show');
766         }); // end events
767     }); /* Returning Promise */
769     // Ajax call with promise via dialog
770     function dialogAjax(data, $dialog, opts) {
771         var params = {
772             async: data.async,
773             method: data.method || '',
774             data: data.content,
775             url: data.url,
776             dataType: data.dataType || 'html'
777         };
779         if (data.url) {
780             jQuery.extend(params, data);
781         }
783         jQuery.ajax(params).done(aOkay).fail(oops);
785         return true;
787         function aOkay(html) {
788             opts.ajax = true;
789             $dialog.find('.modal-body').html(data.success ? data.success(html) : html);
791             return true;
792         }
794         function oops(r, s) {
795             var msg = data.error ?
796                 data.error(r, s, params) :
797                 '<div class="alert alert-danger">' +
798                 '<strong>XHR Failed:</strong> [ ' + params.url + '].' + '</div>';
800             $dialog.find('.modal-body').html(msg);
802             return false;
803         }
804     }
806     function buildFooter() {
807         if (opts.buttons === false) {
808             return '';
809         }
810         var oFoot = jQuery('<div>').addClass('modal-footer').prop('id', 'oefooter');
811         if (opts.buttons) {
812             for (var i = 0, k = opts.buttons.length; i < k; i++) {
813                 var btnOp = opts.buttons[i];
814                 if (typeof btnOp.class !== 'undefined') {
815                     btnOp.class = btnOp.class.replace(/default/gi, 'secondary');
816                     var btn = jQuery('<button>').addClass('btn ' + (btnOp.class || 'btn-primary'));
817                 } else { // legacy
818                     btnOp.style = btnOp.style.replace(/default/gi, 'secondary');
819                     var btn = jQuery('<button>').addClass('btn btn-' + (btnOp.style || 'primary'));
820                     btnOp.style = "";
821                 }
822                 for (var index in btnOp) {
823                     if (btnOp.hasOwnProperty(index)) {
824                         switch (index) {
825                             case 'close':
826                                 //add close event
827                                 if (btnOp[index]) {
828                                     btn.attr('data-dismiss', 'modal');
829                                 }
830                                 break;
831                             case 'click':
832                                 //binds button to click event of fn defined in calling document/form
833                                 var fn = btnOp.click.bind(dlgContainer.find('.modal-content'));
834                                 btn.click(fn);
835                                 break;
836                             case 'text':
837                                 btn.html(btnOp[index]);
838                                 break;
839                             case 'class':
840                                 break;
841                             default:
842                                 //all other possible HTML attributes to button element
843                                 // name, id etc
844                                 btn.attr(index, btnOp[index]);
845                         }
846                     }
847                 }
849                 oFoot.append(btn);
850             }
851         }
852         return oFoot; // jquery object of modal footer.
853     }
855     // dynamic sizing - special case for full height
856     function sizing(e, height) {
857         let viewPortHt = 0;
858         if (opts.sizeHeight === 'auto') {
859             dlgContainer.find('div.modal-body').css({'overflow-y': 'auto'});
860             // let BS determine height for alerts etc
861             return;
862         }
863         let $idoc = jQuery(e.currentTarget);
864         viewPortHt = Math.max(window.document.documentElement.clientHeight, window.innerHeight || 0);
865         let frameContentHt = opts.sizeHeight === 'full' ? viewPortHt : height;
866         frameContentHt = frameContentHt >= viewPortHt ? viewPortHt : frameContentHt;
867         size = (frameContentHt / viewPortHt * 100).toFixed(2);
868         size = size + 'vh';
869         dlgContainer.find('div.modal-content').css({'height': size});
870         if (opts.type === 'iframe') {
871             dlgContainer.find('div.modal-body').css({'overflow-y': 'hidden'});
872         } else {
873             dlgContainer.find('div.modal-body').css({'overflow-y': 'auto'});
874         }
877         return size;
878     }
880     // sizing for modals with iframes
881     function SizeModaliFrame(e, minSize) {
882         let viewPortHt = where.window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
883         let frameContentHt = 0;
884         let idoc = null;
885         try {
886             idoc = e.currentTarget.contentDocument ? e.currentTarget.contentDocument : e.currentTarget.contentWindow.document;
887             jQuery(e.currentTarget).parents('div.modal-content').css({'height': 0});
888             frameContentHt = Math.max(jQuery(idoc).height(), idoc.body.offsetHeight) + 60;
889         } catch (err) {
890             frameContentHt = minSize + 60;
891         }
892         frameContentHt = frameContentHt <= minSize ? minSize : frameContentHt;
893         frameContentHt = frameContentHt >= viewPortHt ? viewPortHt : frameContentHt;
894         size = (frameContentHt / viewPortHt * 100).toFixed(1);
895         size = size + 'vh';
896         jQuery(e.currentTarget).parents('div.modal-content').css({'height': size});
898         return size;
899     }