1 // Copyright (C) 2005 Rod Roark <rod@sunsetsystems.com>
2 // Copyright (C) 2018-2020 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.closeAjax = closeAjax;
21 buttons: data.buttons,
22 allowDrag: data.allowDrag,
23 allowResize: data.allowResize,
24 sizeHeight: data.sizeHeight,
28 dataType: data.dataType // xml/json/text etc.
31 let title = data.title;
33 return dlgopen('', '', data.size, 300, '', title, opts);
36 function alert(data, title) {
37 title = title ? title : 'Alert';
38 let alertTitle = '<i class="fa fa-warning alert-danger"></i> <span>' + title + '</span>';
39 return dlgopen('', '', 675, 250, '', alertTitle, {
41 {text: '<i class="fa fa-thumbs-up"> OK</i>', close: true, style: 'default'}
44 html: '<blockquote class="blockquote">' + data + '</blockquote>'
48 function closeAjax() {
53 if (typeof window.xl !== 'function') {
55 await includeScript(utilfn, 'script');
56 })(top.webroot_url + '/library/js/utility.js').then(() => {
57 console.log('Utilities Unavailable! loading:[ ' + utilfn + ' ] For: [ ' + location + ' ]');
60 }(typeof define == 'function' && define.amd ?
62 function (args, mName) {
63 this.dialog = typeof module != 'undefined' && module.exports ?
64 mName(require(args[0], {}), module.exports) :
69 // open a new cascaded window
70 function cascwin(url, winname, width, height, options) {
71 var mywin = window.parent ? window.parent : window;
72 var newx = 25, newy = 25;
73 if (!isNaN(mywin.screenX)) {
74 newx += mywin.screenX;
75 newy += mywin.screenY;
76 } else if (!isNaN(mywin.screenLeft)) {
77 newx += mywin.screenLeft;
78 newy += mywin.screenTop;
80 if ((newx + width) > screen.width || (newy + height) > screen.height) {
86 // MS IE version detection taken from
87 // http://msdn2.microsoft.com/en-us/library/ms537509.aspx
88 // to adjust the height of this box for IE only -- JRM
89 if (navigator.appName == 'Microsoft Internet Explorer') {
90 var ua = navigator.userAgent;
91 var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
92 if (re.exec(ua) != null)
93 rv = parseFloat(RegExp.$1); // this holds the version number
97 retval = window.open(url, winname, options +
98 ",width=" + width + ",height=" + height +
99 ",left=" + newx + ",top=" + newy +
100 ",screenX=" + newx + ",screenY=" + newy);
105 // recursive window focus-event grabber
106 function grabfocus(w) {
107 for (var i = 0; i < w.frames.length; ++i) grabfocus(w.frames[i]);
108 w.onfocus = top.imfocused;
111 // Call this when a "modal" windowed dialog is desired.
112 // Note that the below function is free standing for either
113 // ui's.Use dlgopen() for responsive b.s modal dialogs.
114 // Can now use anywhere to cascade natives...12/1/17 sjp
116 function dlgOpenWindow(url, winname, width, height) {
117 if (top.modaldialog && !top.modaldialog.closed) {
118 if (window.focus) top.modaldialog.focus();
119 if (top.modaldialog.confirm(top.oemr_dialog_close_msg)) {
120 top.modaldialog.close();
121 top.modaldialog = null;
126 top.modaldialog = cascwin(url, winname, width, height,
127 "resizable=1,scrollbars=1,location=0,toolbar=0");
132 // This is called from del_related() which in turn is invoked by find_code_dynamic.php.
133 // Deletes the specified codetype:code from the indicated input text element.
134 function my_del_related(s, elem, usetitle) {
136 // Deleting everything.
143 // Convert the codes and their descriptions to arrays for easy manipulation.
144 var acodes = elem.value.split(';');
145 var i = acodes.indexOf(s);
147 return; // not found, should not happen
149 // Delete the indicated code and description and convert back to strings.
151 elem.value = acodes.join(';');
153 var atitles = elem.title.split(';');
154 atitles.splice(i, 1);
155 elem.title = atitles.join(';');
159 function dialogID() {
161 return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
164 return s4() + s4() + s4() + s4() + s4() + +s4() + s4() + s4();
167 // test for and/or remove dependency.
168 function inDom(dependency, type, remove) {
170 let attr = type === 'script' ? 'src' : type === 'link' ? 'href' : 'none';
171 let all = document.getElementsByTagName(el);
172 for (let i = all.length; i > -1; i--) {
173 if (all[i] && all[i].getAttribute(attr) !== null && all[i].getAttribute(attr).indexOf(dependency) !== -1) {
175 all[i].parentNode.removeChild(all[i]);
176 console.log("Removed from DOM: " + dependency);
186 // test to see if bootstrap theming is loaded (via standard or custom bootstrap library)
187 // Will check for the badge-secondary class
188 // - if exist, then assume bootstrap loaded
189 // - if not exist, then assume bootstrap not loaded
190 function isBootstrapCss() {
191 for (let i = 0; i < document.styleSheets.length; i++) {
192 let rules = document.styleSheets[i].rules || document.styleSheets[i].cssRules;
193 for (let x in rules) {
194 if (rules[x].selectorText == '.badge-secondary') {
202 // These functions may be called from scripts that may be out of scope with top so...
203 // if opener is tab then we need to be in tabs UI scope and while we're at it, let's bring webroot along...
205 if (typeof top.webroot_url === "undefined" && opener) {
206 if (typeof opener.top.webroot_url !== "undefined") {
207 top.webroot_url = opener.top.webroot_url;
210 // We'll need these if out of scope
212 if (typeof top.set_opener !== "function") {
213 var opener_list = [];
215 function set_opener(window, opener) {
216 top.opener_list[window] = opener;
219 function get_opener(window) {
220 return top.opener_list[window];
224 // universal alert popup message
225 if (typeof alertMsg !== "function") {
226 function alertMsg(message, timer = 5000, type = 'danger', size = '', persist = '') {
227 // this xl() is just so cool.
228 let gotIt = xl("Got It");
229 let title = xl("Alert");
230 let dismiss = xl("Dismiss");
231 $('#alert_box').remove();
233 oHidden = !persist ? "hidden" : '';
234 let oSize = (size == 'lg') ? 'left:10%;width:80%;' : 'left:25%;width:50%;';
235 let style = "position:fixed;top:25%;" + oSize + " bottom:0;z-index:9999;";
236 $("body").prepend("<div class='container text-center' id='alert_box' style='" + style + "'></div>");
237 let mHtml = '<div id="alertmsg" class="alert alert-' + type + ' alert-dismissable">' +
238 '<button type="button" class="btn btn-link ' + oHidden + '" id="dontShowAgain" data-dismiss="alert">' +
239 gotIt + ' <i class="fa fa-thumbs-up"></i></button>' +
240 '<h4 class="alert-heading text-center">' + title + '!</h4><hr>' + '<p style="color:#000;">' + message + '</p>' +
241 '<button type="button" class="pull-right btn btn-link" data-dismiss="alert">' + dismiss + '</button><br /></div>';
242 $('#alert_box').append(mHtml);
243 $('#alertmsg').on('closed.bs.alert', function () {
244 clearTimeout(AlertMsg);
245 $('#alert_box').remove();
248 $('#dontShowAgain').on('click', function (e) {
249 persistUserOption(persist, 1);
251 let AlertMsg = setTimeout(function () {
252 $('#alertmsg').fadeOut(800, function () {
253 $('#alert_box').remove();
258 const persistUserOption = function (option, value) {
260 url: top.webroot_url + "/library/ajax/user_settings.php",
262 contentType: 'application/x-www-form-urlencoded',
264 csrf_token_form: top.csrf_token_js,
268 beforeSend: function () {
269 top.restoreSession();
271 error: function (jqxhr, status, errorThrown) {
272 console.log(errorThrown);
279 // Test if supporting dialog callbacks and close dependencies are in scope.
280 // This is useful when opening and closing the dialog is in the same scope. Still use include_opener.js
281 // in script that will close a dialog that is not in the same scope dlgopen was used
282 // or use parent.dlgclose() if known decedent.
283 // dlgopen() will always have a name whether assigned by dev or created by function.
284 // Callback, onClosed and button clicks are still available either way.
285 // For a callback on close use: dlgclose(functionName, farg1, farg2 ...) which becomes: functionName(farg1,farg2, etc)
287 if (typeof dlgclose !== "function") {
292 function dlgclose(call, args) {
293 var frameName = window.name;
295 if (frameName === '') {
296 // try to find dialog. dialogModal is embedded dialog class
297 // It has to be here somewhere.
298 frameName = $(".dialogModal").attr('id');
300 frameName = parent.$(".dialogModal").attr('id');
302 console.log("Unable to find dialog.");
307 var dialogModal = top.$('div#' + frameName);
309 var removeFrame = dialogModal.find("iframe[name='" + frameName + "']");
310 if (removeFrame.length > 0) {
311 removeFrame.remove();
314 if (dialogModal.length > 0) {
316 wframe.setCallBack(call, args); // sets/creates callback function in dialogs scope.
318 dialogModal.modal('hide');
324 * function dlgopen(url, winname, width, height, forceNewWindow, title, opts)
326 * @summary Stackable, resizable and draggable responsive ajax/iframe dialog modal.
328 * @param {url} string Content location.
329 * @param {String} winname If set becomes modal id and/or iframes name. Or, one is created/assigned(iframes).
330 * @param {Number| String} width|modalSize(modal-xl) For sizing: an number will be converted to a percentage of view port width.
331 * @param {Number} height Initial minimum height. For iframe auto resize starts at this height.
332 * @param {boolean} forceNewWindow Force using a native window.
333 * @param {String} title If exist then header with title is created otherwise no header and content only.
334 * @param {Object} opts Dialogs options.
335 * @returns {Object} dialog object reference.
337 function dlgopen(url, winname, width, height, forceNewWindow, title, opts) {
338 // First things first...
339 top.restoreSession();
340 // A matter of Legacy
341 if (forceNewWindow) {
342 return dlgOpenWindow(url, winname, width, height);
345 // wait for DOM then check dependencies needed to run this feature.
346 // dependency duration is while 'this' is in scope, temporary...
347 // seldom will this get used as more of U.I is moved to Bootstrap
348 // but better to continue than stop because of a dependency...
350 let jqurl = top.webroot_url + '/public/assets/jquery/dist/jquery.min.js';
351 if (typeof jQuery === 'undefined') {
353 await includeScript(utilfn, 'script');
357 // Check for dependencies we will need.
358 // webroot_url is a global defined in main_screen.php or main.php.
359 let bscss = top.webroot_url + '/public/assets/bootstrap/dist/css/bootstrap.min.css';
360 let bscssRtl = top.webroot_url + '/public/assets/bootstrap-v4-rtl/dist/css/bootstrap-rtl.min.css';
361 let bsurl = top.webroot_url + '/public/assets/bootstrap/dist/js/bootstrap.bundle.min.js';
363 let version = jQuery.fn.jquery.split(' ')[0].split('.');
364 if ((version[0] < 2 && version[1] < 9) || (version[0] === 1 && version[1] === 9 && version[2] < 1)) {
365 inDom('jquery-min', 'script', true);
367 await includeScript(utilfn, 'script');
368 })(jqurl).then(() => {
369 console.log('Replacing jQuery version:[ ' + version + ' ]');
372 if (!isBootstrapCss()) {
374 await includeScript(utilfn, 'link');
376 if (top.jsLanguageDirection == 'rtl') {
378 await includeScript(utilfn, 'link');
382 if (typeof jQuery.fn.modal === 'undefined') {
383 if (!inDom('bootstrap.bundle.min.js', 'script', false)) {
385 await includeScript(utilfn, 'script');
392 var opts_defaults = {
393 type: 'iframe', // POST, GET (ajax) or iframe
395 frameContent: "", // for iframe embedded content
396 html: "", // content for alerts, comfirm etc ajax
399 sizeHeight: 'auto', // 'full' will use as much height as allowed
400 // use is onClosed: fnName ... args not supported however, onClosed: 'reload' is auto defined and requires no function to be created.
402 callBack: false, // use {call: 'functionName, args: args, args} if known or use dlgclose.
403 resolvePromiseOn: 'init' // this may be useful values are init, shown, show and closed which coincide with dialog events.
409 opts = jQuery.extend({}, opts_defaults, opts);
410 opts.type = opts.type ? opts.type.toLowerCase() : '';
412 var mHeight, mWidth, mSize, msSize, dlgContainer, fullURL, where; // a growing list...
414 where = (opts.type === 'iframe') ? top : window;
416 // get url straight...
422 if (url[0] === "/") {
425 fullURL = window.location.href.substr(0, window.location.href.lastIndexOf("/") + 1) + url;
429 // what's a window without a name. important for stacking and opener.
430 winname = (winname === "_blank" || !winname) ? dialogID() : winname;
432 // for small screens or request width is larger than viewport.
433 if (where.innerWidth <= 768) {
436 // Convert dialog size to percentages and/or css class.
437 var sizeChoices = ['modal-sm', 'modal-md', 'modal-mlg', 'modal-lg', 'modal-xl'];
438 if (Math.abs(width) > 0) {
439 width = Math.abs(width);
440 mWidth = (width / where.innerWidth * 100).toFixed(1) + '%';
441 msSize = '<style>.modal-custom-' + winname + ' {max-width:' + mWidth + ' !important;}</style>';
442 mSize = 'modal-custom' + winname;
443 } else if (jQuery.inArray(width, sizeChoices) !== -1) {
444 mSize = width; // is a modal class
446 msSize = '<style>.modal-custom-' + winname + ' {max-width:35% !important;}</style>'; // standard B.S. modal default (modal-md)
448 // leave below for legacy
449 if (mSize === 'modal-sm') {
450 msSize = '<style>.modal-custom-' + winname + ' {max-width:25% !important;}</style>';
451 } else if (mSize === 'modal-md') {
452 msSize = '<style>.modal-custom-' + winname + ' {max-width:40% !important;}</style>';
453 } else if (mSize === 'modal-mlg') {
454 msSize = '<style>.modal-custom-' + winname + ' {max-width:55% !important;}</style>';
455 } else if (mSize === 'modal-lg') {
456 msSize = '<style>.modal-custom-' + winname + ' {max-width:75% !important;}</style>';
457 } else if (mSize === 'modal-xl') {
458 msSize = '<style>.modal-custom-' + winname + ' {max-width:92% !important;}</style>';
460 mSize = 'modal-custom-' + winname;
462 // Initial responsive height.
463 var vpht = where.innerHeight;
464 mHeight = height > 0 ? (height / vpht * 100).toFixed(1) + 'vh' : '';
466 // Build modal template. For now !title = !header and modal full height.
467 var mTitle = title > "" ? '<h5 class=modal-title>' + title + '</h5>' : '';
470 '<div class="loadProgress text-center">' +
471 '<span class="fa fa-circle-o-notch fa-spin fa-3x text-primary"></span>' +
475 ('<div class="modal-header">%title%<button type="button" class="close" data-dismiss="modal">' +
476 '×</button></div>').replace('%title%', mTitle);
479 ('<iframe id="modalframe" class="w-100 h-100 modalIframe" name="%winname%" %url% frameborder=0></iframe>').replace('%winname%', winname).replace('%url%', fullURL ? 'src=' + fullURL : '');
481 var bodyStyles = ('style="height:%initHeight%;"').replace('%initHeight%', opts.sizeHeight !== 'full' ? mHeight : '80vh');
483 var altClose = '<div class="closeDlgIframe" data-dismiss="modal" ></div>';
486 ('<div id="%id%" class="modal fade dialogModal" tabindex="-1" role="dialog">%sizeStyle%' +
487 '<style>.drag-resize {touch-action:none;user-select:none;}</style>' +
488 '<div %dialogId% class="modal-dialog %drag-action% %sizeClass%" role="document">' +
489 '<div class="modal-content %resize-action%" style="max-height: 92vh">' + '%head%' + '%altclose%' + '%wait%' +
490 '<div class="modal-body overflow-auto px-1" %bodyStyles%>' + '%body%' + '</div></div></div></div>').replace('%id%', winname).replace('%sizeStyle%', msSize ? msSize : '').replace('%dialogId%', opts.dialogId ? ('id=' + opts.dialogId + '"') : '').replace('%sizeClass%', mSize ? mSize : '').replace('%head%', mTitle !== '' ? headerhtml : '').replace('%altclose%', mTitle === '' ? altClose : '').replace('%drag-action%', (opts.allowDrag) ? 'drag-action' : '').replace('%resize-action%', (opts.allowResize) ? 'resize-action' : '').replace('%wait%', '').replace('%bodyStyles%', bodyStyles).replace('%body%', opts.type === 'iframe' ? frameHtml : '');
492 // Write modal template.
493 dlgContainer = where.jQuery(mhtml);
494 dlgContainer.attr("name", winname);
496 // No url and just iframe content
497 if (opts.frameContent && opts.type === 'iframe') {
498 var ipath = 'data:text/html,' + encodeURIComponent(opts.frameContent);
499 dlgContainer.find("iframe[name='" + winname + "']").attr("src", ipath);
503 dlgContainer.find('.modal-content').append(buildFooter());
506 if (opts.type === 'alert') {
507 dlgContainer.find('.modal-body').html(opts.html);
509 if (opts.type !== 'iframe' && opts.type !== 'alert') {
512 method: opts.type || '', // if empty and has data object, then post else get.
513 content: opts.data || opts.html, // ajax loads fetched content.
514 url: opts.url || fullURL,
515 dataType: opts.dataType || '' // xml/json/text etc.
518 dialogAjax(params, dlgContainer, opts);
521 // let opener array know about us.
522 top.set_opener(winname, window);
524 // Write the completed template to calling document or 'where' window.
525 where.jQuery("body").append(dlgContainer);
528 return new Promise((resolve, reject) => {
530 // DOM Ready. Handle events and cleanup.
531 if (opts.type === 'iframe') {
532 var modalwin = where.jQuery('body').find("[name='" + winname + "']");
533 jQuery('div.modal-dialog', modalwin).css({'margin': '15px auto auto'});
534 modalwin.on('load', function (e) {
535 setTimeout(function () {
536 if (opts.sizeHeight === 'auto') {
537 SizeModaliFrame(e, height);
538 } else if (opts.sizeHeight === 'fixed') {
541 sizing(e, height); // must be full height of container
546 var modalwin = where.jQuery('body').find("[name='" + winname + "']");
547 jQuery('div.modal-dialog', modalwin).css({'margin': '15px auto auto'});
548 modalwin.on('show.bs.modal', function (e) {
549 setTimeout(function () {
556 dlgContainer.on('show.bs.modal', function () {
557 if (opts.allowResize || opts.allowDrag) {
558 initDragResize(where.document, where.document);
561 if (opts.resolvePromiseOn == 'show') {
562 resolve(dlgContainer);
564 }).on('shown.bs.modal', function () {
565 // Remove waitHtml spinner/loader etc.
566 jQuery(this).parent().find('div.loadProgress').fadeOut(function () {
567 jQuery(this).remove();
569 dlgContainer.modal('handleUpdate'); // allow for scroll bar
571 if (opts.resolvePromiseOn == 'shown') {
572 resolve(dlgContainer);
574 }).on('hidden.bs.modal', function (e) {
576 jQuery(this).remove();
577 // now we can run functions in our window.
579 console.log('Doing onClosed:[' + opts.onClosed + ']');
580 if (opts.onClosed === 'reload') {
581 window.location.reload();
583 window[opts.onClosed]();
586 if (opts.callBack.call) {
587 console.log('Doing callBack:[' + opts.callBack.call + '|' + opts.callBack.args + ']');
588 if (opts.callBack.call === 'reload') {
589 window.location.reload();
591 window[opts.callBack.call](opts.callBack.args);
595 if (opts.resolvePromiseOn == 'close') {
596 resolve(dlgContainer);
600 // define local dialog close() function. openers scope
601 window.dlgCloseAjax = function (calling, args) {
603 opts.callBack = {call: calling, args: args};
605 dlgContainer.modal('hide'); // important to clean up in only one place, hide event....
609 // define local callback function. Set with opener or from opener, will exe on hide.
610 window.dlgSetCallBack = function (calling, args) {
611 opts.callBack = {call: calling, args: args};
615 // in residents dialog scope
616 where.setCallBack = function (calling, args) {
617 opts.callBack = {call: calling, args: args};
621 where.getOpener = function () {
624 // dialog is completely built and events set
625 // this is default returning our dialog container reference.
626 if (opts.resolvePromiseOn == 'init') {
627 resolve(dlgContainer);
629 // Finally Show Dialog after DOM settles
630 dlgContainer.modal({backdrop: 'static', keyboard: true}, 'show');
632 }); /* Returning Promise */
634 // Ajax call with promise via dialog
635 function dialogAjax(data, $dialog, opts) {
638 method: data.method || '',
641 dataType: data.dataType || 'html'
645 jQuery.extend(params, data);
648 jQuery.ajax(params).done(aOkay).fail(oops);
652 function aOkay(html) {
654 $dialog.find('.modal-body').html(data.success ? data.success(html) : html);
659 function oops(r, s) {
660 var msg = data.error ?
661 data.error(r, s, params) :
662 '<div class="alert alert-danger">' +
663 '<strong>XHR Failed:</strong> [ ' + params.url + '].' + '</div>';
665 $dialog.find('.modal-body').html(msg);
671 function buildFooter() {
672 if (opts.buttons === false) {
675 var oFoot = jQuery('<div>').addClass('modal-footer').prop('id', 'oefooter');
677 for (var i = 0, k = opts.buttons.length; i < k; i++) {
678 var btnOp = opts.buttons[i];
679 if (typeof btnOp.class !== 'undefined') {
680 btnOp.class = btnOp.class.replace(/default/gi, 'secondary');
681 var btn = jQuery('<button>').addClass('btn ' + (btnOp.class || 'btn-primary'));
683 btnOp.style = btnOp.style.replace(/default/gi, 'secondary');
684 var btn = jQuery('<button>').addClass('btn btn-' + (btnOp.style || 'primary'));
687 for (var index in btnOp) {
688 if (btnOp.hasOwnProperty(index)) {
693 btn.attr('data-dismiss', 'modal');
697 //binds button to click event of fn defined in calling document/form
698 var fn = btnOp.click.bind(dlgContainer.find('.modal-content'));
702 btn.html(btnOp[index]);
707 //all other possible HTML attributes to button element
709 btn.attr(index, btnOp[index]);
717 return oFoot; // jquery object of modal footer.
720 // dynamic sizing - special case for full height
721 function sizing(e, height) {
723 let $idoc = jQuery(e.currentTarget);
724 viewPortHt = Math.max(window.document.documentElement.clientHeight, window.innerHeight || 0);
725 let frameContentHt = opts.sizeHeight === 'full' ? viewPortHt : height;
726 frameContentHt = frameContentHt >= viewPortHt ? viewPortHt : frameContentHt;
727 size = (frameContentHt / viewPortHt * 100).toFixed(2);
729 $idoc.find('div.modal-content').css({'height': size});
734 // sizing for modals with iframes
735 function SizeModaliFrame(e, minSize) {
737 let idoc = e.currentTarget.contentDocument ? e.currentTarget.contentDocument : e.currentTarget.contentWindow.document;
738 jQuery(e.currentTarget).parents('div.modal-body').css({'height': 0});
739 viewPortHt = top.window.innerHeight;
740 let frameContentHt = Math.max(jQuery(idoc).height(), idoc.body.offsetHeight) + 40;
741 frameContentHt = frameContentHt < minSize ? minSize : frameContentHt;
742 frameContentHt = frameContentHt >= viewPortHt ? viewPortHt : frameContentHt;
743 size = (frameContentHt / viewPortHt * 100).toFixed(1);
744 size = size + 'vh'; // will start the dialog as responsive. Any resize by user turns dialog to absolute positioning.
745 jQuery(e.currentTarget).parents('div.modal-body').css({'height': size});