1 // Copyright (C) 2005 Rod Roark <rod@sunsetsystems.com>
2 // Copyright (C) 2018-2021 Jerry Padgett <sjpadgett@gmail.com>
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.
10 define(['jquery'], function ($, root) {
11 let opts_default = {};
15 root.confirm = confirm;
16 root.closeAjax = closeAjax;
23 buttons: data.buttons,
24 allowDrag: data.allowDrag,
25 allowResize: data.allowResize,
26 sizeHeight: data.sizeHeight,
28 resolvePromiseOn: data.resolvePromiseOn,
31 dataType: data.dataType // xml/json/text etc.
34 let title = data.title;
36 return dlgopen('', '', data.size, 0, '', title, opts);
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> ' + title + '</span>';
42 return dlgopen('', '', 675, 0, '', alertTitle, {
44 {text: 'OK', close: true, style: 'primary'}
48 resolvePromiseOn: 'close',
49 html: '<p class="text-center">' + data + '</p>'
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> ' + title + '</span>';
56 return dlgopen('', '', "modal-md", 0, '', alertTitle, {
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'}
63 resolvePromiseOn: 'confirm',
65 html: '<p class="text-center">' + data + '</p>'
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
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);
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);
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') +
99 let modalWindow = window.open('', name, options, true);
100 if ( !modalWindow ) {
106 modalWindow.document.body.innerHTML = data;
108 modalWindow.location.href = url;
111 window.open(url, null, options, true);
117 function closeAjax() {
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 + ']');
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 + ']');
154 if (typeof window.xl !== 'function') {
156 await includeScript(utilfn, 'script');
157 })(top.webroot_url + '/library/js/utility.js')
159 }(typeof define == 'function' && define.amd ?
161 function (args, mName) {
162 this.dialog = typeof module != 'undefined' && module.exports ?
163 mName(require(args[0], {}), module.exports) :
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;
179 if ((newx + width) > screen.width || (newy + height) > screen.height) {
183 if (typeof top.restoreSession === 'function') {
184 top.restoreSession();
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;
198 retval = window.open(url, winname, options +
199 ",width=" + width + ",height=" + height +
200 ",left=" + newx + ",top=" + newy +
201 ",screenX=" + newx + ",screenY=" + newy);
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;
227 top.modaldialog = cascwin(url, winname, width, height,
228 "resizable=1,scrollbars=1,location=0,toolbar=0");
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) {
237 // Deleting everything.
244 // Convert the codes and their descriptions to arrays for easy manipulation.
245 var acodes = elem.value.split(';');
246 var i = acodes.indexOf(s);
248 return; // not found, should not happen
250 // Delete the indicated code and description and convert back to strings.
252 elem.value = acodes.join(';');
254 var atitles = elem.title.split(';');
255 atitles.splice(i, 1);
256 elem.title = atitles.join(';');
260 function dialogID() {
262 return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
265 return s4() + s4() + s4() + s4() + s4() + +s4() + s4() + s4();
268 // test for and/or remove dependency.
269 function inDom(dependency, type, remove) {
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) {
276 all[i].parentNode.removeChild(all[i]);
277 console.log("Removed from DOM: " + dependency);
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') {
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;
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;
320 function get_opener(window) {
321 return top.opener_list[window];
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();
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 + ' <i class="fa fa-thumbs-up"></i></button>' +
341 '<h4 class="alert-heading text-center">' + title + '!</h4><hr>' + '<p class="bg-light text-dark">' + message + '</p>' +
342 '<button type="button" id="alertDismissButton" 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();
349 $('#dontShowAgain').on('click', function (e) {
350 clearTimeout(AlertMsg);
351 $('#alert_box').remove();
352 persistUserOption(persist, 1);
354 $('#alertDismissButton').on('click', function (e) {
355 clearTimeout(AlertMsg);
356 $('#alert_box').remove();
358 let AlertMsg = setTimeout(function () {
359 $('#alertmsg').fadeOut(800, function () {
360 $('#alert_box').remove();
365 const persistUserOption = function (option, value) {
367 url: top.webroot_url + "/library/ajax/user_settings.php",
369 contentType: 'application/x-www-form-urlencoded',
371 csrf_token_form: top.csrf_token_js,
375 beforeSend: function () {
376 if (typeof top.restoreSession === 'function') {
377 top.restoreSession();
380 error: function (jqxhr, status, errorThrown) {
381 console.log(errorThrown);
388 // Test if supporting dialog callbacks and close dependencies are in scope.
389 // This is useful when opening and closing the dialog is in the same scope. Still use include_opener.js
390 // in script that will close a dialog that is not in the same scope dlgopen was used
391 // or use parent.dlgclose() if known decedent.
392 // dlgopen() will always have a name whether assigned by dev or created by function.
393 // Callback, onClosed and button clicks are still available either way.
394 // For a callback on close use: dlgclose(functionName, farg1, farg2 ...) which becomes: functionName(farg1,farg2, etc)
396 if (typeof dlgclose !== "function") {
401 function dlgclose(call, args) {
402 var frameName = window.name;
404 if (frameName === '') {
405 // try to find dialog. dialogModal is embedded dialog class
406 // It has to be here somewhere.
407 frameName = $(".dialogModal").attr('id');
409 frameName = parent.$(".dialogModal").attr('id');
411 console.log("Unable to find dialog.");
416 var dialogModal = top.$('div#' + frameName);
418 var removeFrame = dialogModal.find("iframe[name='" + frameName + "']");
419 if (removeFrame.length > 0) {
420 removeFrame.remove();
423 if (dialogModal.length > 0) {
425 wframe.setCallBack(call, args); // sets/creates callback function in dialogs scope.
427 dialogModal.modal('hide');
429 // no opener not iframe must be in here
430 $(this.document).find(".dialogModal").modal('hide');
436 * function dlgopen(url, winname, width, height, forceNewWindow, title, opts)
438 * @summary Stackable, resizable and draggable responsive ajax/iframe dialog modal.
440 * @param {url} string Content location.
441 * @param {String} winname If set becomes modal id and/or iframes name. Or, one is created/assigned(iframes).
442 * @param {Number| String} width|modalSize(modal-xl) For sizing: an number will be converted to a percentage of view port width.
443 * @param {Number} height Initial minimum height. For iframe auto resize starts at this height.
444 * @param {boolean} forceNewWindow Force using a native window.
445 * @param {String} title If exist then header with title is created otherwise no header and content only.
446 * @param {Object} opts Dialogs options.
447 * @returns {Object} dialog object reference.
449 function dlgopen(url, winname, width, height, forceNewWindow, title, opts) {
450 // First things first...
451 if (typeof top.restoreSession === 'function') {
452 top.restoreSession();
455 // A matter of Legacy
456 if (forceNewWindow) {
457 return dlgOpenWindow(url, winname, width, height);
460 // wait for DOM then check dependencies needed to run this feature.
461 // dependency duration is while 'this' is in scope, temporary...
462 // seldom will this get used as more of U.I is moved to Bootstrap
463 // but better to continue than stop because of a dependency...
465 let jqurl = top.webroot_url + '/public/assets/jquery/dist/jquery.min.js';
466 if (typeof jQuery === 'undefined') {
468 await includeScript(utilfn, 'script');
472 // Check for dependencies we will need.
473 // webroot_url is a global defined in main_screen.php or main.php.
474 let bscss = top.webroot_url + '/public/assets/bootstrap/dist/css/bootstrap.min.css';
475 let bscssRtl = top.webroot_url + '/public/assets/bootstrap-v4-rtl/dist/css/bootstrap-rtl.min.css';
476 let bsurl = top.webroot_url + '/public/assets/bootstrap/dist/js/bootstrap.bundle.min.js';
478 let version = jQuery.fn.jquery.split(' ')[0].split('.');
479 if ((version[0] < 2 && version[1] < 9) || (version[0] === 1 && version[1] === 9 && version[2] < 1)) {
480 inDom('jquery-min', 'script', true);
482 await includeScript(utilfn, 'script');
483 })(jqurl).then(() => {
484 console.log('Replacing jQuery version:[ ' + version + ' ]');
487 if (!isBootstrapCss()) {
489 await includeScript(utilfn, 'link');
491 if (top.jsLanguageDirection == 'rtl') {
493 await includeScript(utilfn, 'link');
497 if (typeof jQuery.fn.modal === 'undefined') {
498 if (!inDom('bootstrap.bundle.min.js', 'script', false)) {
500 await includeScript(utilfn, 'script');
507 var opts_defaults = {
508 type: 'iframe', // POST, GET (ajax) or iframe
510 frameContent: "", // for iframe embedded content
511 html: "", // content for alerts, comfirm etc ajax
514 sizeHeight: 'auto', // 'full' will use as much height as allowed
515 // use is onClosed: fnName ... args not supported however, onClosed: 'reload' is auto defined and requires no function to be created.
517 allowExternal: false, // allow a dialog window to a URL that is external to the current url
518 callBack: false, // use {call: 'functionName, args: args, args} if known or use dlgclose.
519 resolvePromiseOn: '' // this may be useful. values are init, shown, show, confirm, alert and close which coincide with dialog events.
525 opts = jQuery.extend({}, opts_defaults, opts);
526 opts.type = opts.type ? opts.type.toLowerCase() : '';
527 opts.resolvePromiseOn = opts.resolvePromiseOn ?? 'init';
528 var mHeight, mWidth, mSize, msSize, dlgContainer, fullURL, where; // a growing list...
530 where = (opts.type === 'iframe') ? top : window;
532 // get url straight...
538 if (url[0] === "/") {
540 } else if (opts.allowExternal === true) {
541 var checkUrl = new URL(url);
542 // we only allow http & https protocols to be launched
543 if (checkUrl.protocol === "http:" || checkUrl.protocol == "https:") {
547 fullURL = window.location.href.substr(0, window.location.href.lastIndexOf("/") + 1) + url;
551 // what's a window without a name. important for stacking and opener.
552 winname = (winname === "_blank" || !winname) ? dialogID() : winname;
554 // for small screens or request width is larger than viewport.
555 if (where.innerWidth <= 1080) {
556 width = "modal-full";
558 // Convert dialog size to percentages and/or css class.
559 var sizeChoices = ['modal-sm', 'modal-md', 'modal-mlg', 'modal-lg', 'modal-xl', 'modal-full'];
560 if (Math.abs(width) > 0) {
561 width = Math.abs(width);
562 mWidth = (width / where.innerWidth * 100).toFixed(1) + '%';
563 msSize = '<style>.modal-custom-' + winname + ' {max-width:' + mWidth + ' !important;}</style>';
564 mSize = 'modal-custom' + winname;
565 } else if (jQuery.inArray(width, sizeChoices) !== -1) {
566 mSize = width; // is a modal class
568 msSize = '<style>.modal-custom-' + winname + ' {max-width:35% !important;}</style>'; // standard B.S. modal default (modal-md)
570 // leave below for legacy
571 if (mSize === 'modal-sm') {
572 msSize = '<style>.modal-custom-' + winname + ' {max-width:25% !important;}</style>';
573 } else if (mSize === 'modal-md') {
574 msSize = '<style>.modal-custom-' + winname + ' {max-width:40% !important;}</style>';
575 } else if (mSize === 'modal-mlg') {
576 msSize = '<style>.modal-custom-' + winname + ' {max-width:55% !important;}</style>';
577 } else if (mSize === 'modal-lg') {
578 msSize = '<style>.modal-custom-' + winname + ' {max-width:75% !important;}</style>';
579 } else if (mSize === 'modal-xl') {
580 msSize = '<style>.modal-custom-' + winname + ' {max-width:92% !important;}</style>';
581 } else if (mSize === 'modal-full') {
582 msSize = '<style>.modal-custom-' + winname + ' {max-width:97% !important;}</style>';
584 mSize = 'modal-custom-' + winname;
586 // Initial responsive height.
587 let vpht = where.innerHeight;
588 if (height <= 300 && opts.type === 'iframe') {
591 mHeight = height > 0 ? (height / vpht * 100).toFixed(1) + 'vh' : '';
593 // Build modal template. For now !title = !header and modal full height.
594 var mTitle = title > "" ? '<h5 class=modal-title>' + title + '</h5>' : '';
597 '<div class="loadProgress text-center">' +
598 '<span class="fa fa-circle-notch fa-spin fa-3x text-primary"></span>' +
602 ('<div class="modal-header">%title%<button type="button" class="close" data-dismiss="modal">' +
603 '×</button></div>').replace('%title%', mTitle);
606 ('<iframe id="modalframe" class="modalIframe w-100 h-100 border-0" name="%winname%" %url%></iframe>').replace('%winname%', winname).replace('%url%', fullURL ? 'src=' + fullURL : '');
608 var contentStyles = ('style="height:%initHeight%; max-height: 94vh"').replace('%initHeight%', opts.sizeHeight !== 'full' ? mHeight : '90vh');
610 var altClose = '<div class="closeDlgIframe" data-dismiss="modal" ></div>';
613 ('<div id="%id%" class="modal fade dialogModal" tabindex="-1" role="dialog">%sizeStyle%' +
614 '<style>.drag-resize {touch-action:none;user-select:none;}</style>' +
615 '<div %dialogId% class="modal-dialog %drag-action% %sizeClass%" role="dialog">' +
616 '<div class="modal-content %resize-action%" %contentStyles%>' + '%head%' + '%altclose%' + '%wait%' +
617 '<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 : '');
619 // Write modal template.
620 dlgContainer = where.jQuery(mhtml);
621 dlgContainer.attr("name", winname);
623 // No url and just iframe content
624 if (opts.frameContent && opts.type === 'iframe') {
625 var ipath = 'data:text/html,' + encodeURIComponent(opts.frameContent);
626 dlgContainer.find("iframe[name='" + winname + "']").attr("src", ipath);
630 dlgContainer.find('.modal-content').append(buildFooter());
633 if (opts.type === 'alert') {
634 dlgContainer.find('.modal-body').html(opts.html);
636 if (opts.type === 'confirm') {
637 dlgContainer.find('.modal-body').html(opts.html);
639 if (opts.type !== 'iframe' && opts.type !== 'alert' && opts.type !== 'confirm') {
642 method: opts.type || '', // if empty and has data object, then post else get.
643 content: opts.data || opts.html, // ajax loads fetched content.
644 url: opts.url || fullURL,
645 dataType: opts.dataType || '' // xml/json/text etc.
648 dialogAjax(params, dlgContainer, opts);
651 // let opener array know about us.
652 top.set_opener(winname, window);
654 // Write the completed template to calling document or 'where' window.
655 where.jQuery("body").append(dlgContainer);
658 return new Promise((resolve, reject) => {
660 // DOM Ready. Handle events and cleanup.
661 if (opts.type === 'iframe') {
662 var modalwin = where.jQuery('body').find("[name='" + winname + "']");
663 jQuery('div.modal-dialog', modalwin).css({'margin': "0.75rem auto auto"});
664 modalwin.on('load', function (e) {
665 setTimeout(function () {
666 if (opts.sizeHeight === 'auto' && opts.type === 'iframe') {
667 SizeModaliFrame(e, height);
668 } else if (opts.sizeHeight === 'fixed') {
671 sizing(e, height); // must be full height of container
676 var modalwin = where.jQuery('body').find("[name='" + winname + "']");
677 jQuery('div.modal-dialog', modalwin).css({'margin': '15px auto auto'});
678 modalwin.on('show.bs.modal', function (e) {
679 setTimeout(function () {
684 if (opts.resolvePromiseOn === 'confirm') {
685 jQuery("#confirmYes").on('click', function (e) {
688 jQuery("#confirmNo").on('click', function (e) {
693 dlgContainer.on('show.bs.modal', function () {
694 if (opts.allowResize || opts.allowDrag) {
695 initDragResize(where.document, where.document);
698 if (opts.resolvePromiseOn === 'show') {
699 resolve(dlgContainer);
701 }).on('shown.bs.modal', function () {
702 // Remove waitHtml spinner/loader etc.
703 jQuery(this).parent().find('div.loadProgress').fadeOut(function () {
704 jQuery(this).remove();
706 dlgContainer.modal('handleUpdate'); // allow for scroll bar
708 if (opts.resolvePromiseOn === 'shown') {
709 resolve(dlgContainer);
711 }).on('hidden.bs.modal', function (e) {
713 e.target.style.cursor = "pointer";
715 jQuery(this).remove();
716 // now we can run functions in our window.
718 console.log('Doing onClosed:[' + opts.onClosed + ']');
719 if (opts.onClosed === 'reload') {
720 window.location.reload();
722 window[opts.onClosed]();
725 if (opts.callBack.call) {
726 console.log('Doing callBack:[' + opts.callBack.call + '|' + opts.callBack.args + ']');
727 if (opts.callBack.call === 'reload') {
728 window.location.reload();
729 } else if (typeof opts.callBack.call == 'string') {
730 window[opts.callBack.call](opts.callBack.args);
732 opts.callBack.call(opts.callBack.args);
736 if (opts.resolvePromiseOn == 'close') {
737 resolve(dlgContainer);
741 // define local dialog close() function. openers scope
742 window.dlgCloseAjax = function (calling, args) {
744 opts.callBack = {call: calling, args: args};
746 dlgContainer.modal('hide'); // important to clean up in only one place, hide event....
750 // define local callback function. Set with opener or from opener, will exe on hide.
751 window.dlgSetCallBack = function (calling, args) {
752 opts.callBack = {call: calling, args: args};
756 // in residents dialog scope
757 where.setCallBack = function (calling, args) {
758 opts.callBack = {call: calling, args: args};
762 where.getOpener = function () {
765 // dialog is completely built and events set
766 // this is default returning our dialog container reference.
767 if (opts.resolvePromiseOn == 'init') {
768 resolve(dlgContainer);
770 // Finally Show Dialog after DOM settles
771 dlgContainer.modal({backdrop: 'static', keyboard: true}, 'show');
773 }); /* Returning Promise */
775 // Ajax call with promise via dialog
776 function dialogAjax(data, $dialog, opts) {
779 method: data.method || '',
782 dataType: data.dataType || 'html'
786 jQuery.extend(params, data);
789 jQuery.ajax(params).done(aOkay).fail(oops);
793 function aOkay(html) {
795 $dialog.find('.modal-body').html(data.success ? data.success(html) : html);
800 function oops(r, s) {
801 var msg = data.error ?
802 data.error(r, s, params) :
803 '<div class="alert alert-danger">' +
804 '<strong>XHR Failed:</strong> [ ' + params.url + '].' + '</div>';
806 $dialog.find('.modal-body').html(msg);
812 function buildFooter() {
813 if (opts.buttons === false) {
816 var oFoot = jQuery('<div>').addClass('modal-footer').prop('id', 'oefooter');
818 for (var i = 0, k = opts.buttons.length; i < k; i++) {
819 var btnOp = opts.buttons[i];
820 if (typeof btnOp.class !== 'undefined') {
821 btnOp.class = btnOp.class.replace(/default/gi, 'secondary');
822 var btn = jQuery('<button>').addClass('btn ' + (btnOp.class || 'btn-primary'));
824 btnOp.style = btnOp.style.replace(/default/gi, 'secondary');
825 var btn = jQuery('<button>').addClass('btn btn-' + (btnOp.style || 'primary'));
828 for (var index in btnOp) {
829 if (btnOp.hasOwnProperty(index)) {
834 btn.attr('data-dismiss', 'modal');
838 //binds button to click event of fn defined in calling document/form
839 var fn = btnOp.click.bind(dlgContainer.find('.modal-content'));
843 btn.html(btnOp[index]);
848 //all other possible HTML attributes to button element
850 btn.attr(index, btnOp[index]);
858 return oFoot; // jquery object of modal footer.
861 // dynamic sizing - special case for full height
862 function sizing(e, height) {
864 if (opts.sizeHeight === 'auto') {
865 dlgContainer.find('div.modal-body').css({'overflow-y': 'auto'});
866 // let BS determine height for alerts etc
869 let $idoc = jQuery(e.currentTarget);
870 viewPortHt = Math.max(window.document.documentElement.clientHeight, window.innerHeight || 0);
871 let frameContentHt = opts.sizeHeight === 'full' ? viewPortHt : height;
872 frameContentHt = frameContentHt >= viewPortHt ? viewPortHt : frameContentHt;
873 size = (frameContentHt / viewPortHt * 100).toFixed(2);
875 dlgContainer.find('div.modal-content').css({'height': size});
876 if (opts.type === 'iframe') {
877 dlgContainer.find('div.modal-body').css({'overflow-y': 'hidden'});
879 dlgContainer.find('div.modal-body').css({'overflow-y': 'auto'});
886 // sizing for modals with iframes
887 function SizeModaliFrame(e, minSize) {
888 let viewPortHt = where.window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
889 let frameContentHt = 0;
892 idoc = e.currentTarget.contentDocument ? e.currentTarget.contentDocument : e.currentTarget.contentWindow.document;
893 jQuery(e.currentTarget).parents('div.modal-content').css({'height': 0});
894 frameContentHt = Math.max(jQuery(idoc).height(), idoc.body.offsetHeight) + 60;
896 frameContentHt = minSize + 60;
898 frameContentHt = frameContentHt <= minSize ? minSize : frameContentHt;
899 frameContentHt = frameContentHt >= viewPortHt ? viewPortHt : frameContentHt;
900 size = (frameContentHt / viewPortHt * 100).toFixed(1);
902 jQuery(e.currentTarget).parents('div.modal-content').css({'height': size});