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