Merge pull request #1416 from bradymiller/date-time-format_1
[openemr.git] / library / dialog.js
blob81c1e1af87120dd509c1e6f4911a6e38c482ff08
1 // Copyright (C) 2005 Rod Roark <rod@sunsetsystems.com>
2 // Copyright (C) 2018 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 // open a new cascaded window
10 function cascwin(url, winname, width, height, options) {
11     var mywin = window.parent ? window.parent : window;
12     var newx = 25, newy = 25;
13     if (!isNaN(mywin.screenX)) {
14         newx += mywin.screenX;
15         newy += mywin.screenY;
16     } else if (!isNaN(mywin.screenLeft)) {
17         newx += mywin.screenLeft;
18         newy += mywin.screenTop;
19     }
20     if ((newx + width) > screen.width || (newy + height) > screen.height) {
21         newx = 0;
22         newy = 0;
23     }
24     top.restoreSession();
26     // MS IE version detection taken from
27     // http://msdn2.microsoft.com/en-us/library/ms537509.aspx
28     // to adjust the height of this box for IE only -- JRM
29     if (navigator.appName == 'Microsoft Internet Explorer') {
30         var ua = navigator.userAgent;
31         var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
32         if (re.exec(ua) != null)
33             rv = parseFloat(RegExp.$1); // this holds the version number
34         height = height + 28;
35     }
37     retval = window.open(url, winname, options +
38         ",width=" + width + ",height=" + height +
39         ",left=" + newx + ",top=" + newy +
40         ",screenX=" + newx + ",screenY=" + newy);
42     return retval;
45 // recursive window focus-event grabber
46 function grabfocus(w) {
47     for (var i = 0; i < w.frames.length; ++i) grabfocus(w.frames[i]);
48     w.onfocus = top.imfocused;
51 // Call this when a "modal" windowed dialog is desired.
52 // Note that the below function is free standing for either
53 // ui's.Use dlgopen() for responsive b.s modal dialogs.
54 // Can now use anywhere to cascade natives...12/1/17 sjp
56 function dlgOpenWindow(url, winname, width, height) {
57     if (top.modaldialog && !top.modaldialog.closed) {
58         if (window.focus) top.modaldialog.focus();
59         if (top.modaldialog.confirm(top.oemr_dialog_close_msg)) {
60             top.modaldialog.close();
61             top.modaldialog = null;
62         } else {
63             return false;
64         }
65     }
66     top.modaldialog = cascwin(url, winname, width, height,
67         "resizable=1,scrollbars=1,location=0,toolbar=0");
68     grabfocus(top);
69     return false;
72 // This is called from del_related() which in turn is invoked by find_code_dynamic.php.
73 // Deletes the specified codetype:code from the indicated input text element.
74 function my_del_related(s, elem, usetitle) {
75     if (!s) {
76         // Deleting everything.
77         elem.value = '';
78         if (usetitle) {
79             elem.title = '';
80         }
81         return;
82     }
83     // Convert the codes and their descriptions to arrays for easy manipulation.
84     var acodes = elem.value.split(';');
85     var i = acodes.indexOf(s);
86     if (i < 0) {
87         return; // not found, should not happen
88     }
89     // Delete the indicated code and description and convert back to strings.
90     acodes.splice(i, 1);
91     elem.value = acodes.join(';');
92     if (usetitle) {
93         var atitles = elem.title.split(';');
94         atitles.splice(i, 1);
95         elem.title = atitles.join(';');
96     }
99 function dialogID() {
100     function s4() {
101         return Math.floor((1 + Math.random()) * 0x10000)
102             .toString(16)
103             .substring(1);
104     }
106     return s4() + s4() + s4() + s4() + s4() + +s4() + s4() + s4();
110 * function includeScript(url, async)
112 * @summary Dynamically include JS Scripts or Css.
114 * @param {string} url file location.
115 * @param {boolean} async true/false load asynchronous/synchronous.
116 * @param {string} 'script' | 'link'.
118 * */
119 function includeScript(url, async, type) {
121     try {
122         let rqit = new XMLHttpRequest();
123         if (type === "link") {
124             let headElement = document.getElementsByTagName("head")[0];
125             let newScriptElement = document.createElement("link")
126             newScriptElement.type = "text/css";
127             newScriptElement.rel = "stylesheet";
128             newScriptElement.href = url;
129             headElement.appendChild(newScriptElement);
130             console.log('Needed to load:[ ' + url + ' ] For: [ ' + location + ' ]');
131             return false;
132         }
134         rqit.open("GET", url, async); // false = synchronous.
135         rqit.send(null);
137         if (rqit.status === 200) {
138             if (type === "script") {
139                 let headElement = document.getElementsByTagName("head")[0];
140                 let newScriptElement = document.createElement("script");
141                 newScriptElement.type = "text/javascript";
142                 newScriptElement.text = rqit.responseText;
143                 headElement.appendChild(newScriptElement);
144                 console.log('Needed to load:[ ' + url + ' ] For: [ ' + location + ' ]');
145                 return false; // in case req comes from a submit form.
146             }
147         }
149         throw new Error('<?php echo xlt("Failed to get URL:") ?>' + url);
151     }
152     catch (e) {
153         throw e;
154     }
158 // test for and/or remove dependency.
159 function inDom(dependency, type, remove) {
160     let el = type;
161     let attr = type === 'script' ? 'src' : type === 'link' ? 'href' : 'none';
162     let all = document.getElementsByTagName(el)
163     for (let i = all.length; i > -1; i--) {
164         if (all[i] && all[i].getAttribute(attr) != null && all[i].getAttribute(attr).indexOf(dependency) != -1) {
165             if (remove) {
166                 all[i].parentNode.removeChild(all[i]);
167                 console.log("Removed from DOM: " + dependency)
168                 return true
169             } else {
170                 return true;
171             }
172         }
173     }
174     return false;
178 * function dlgopen(url, winname, width, height, forceNewWindow, title, opts)
180 * @summary Stackable, resizable and draggable responsive ajax/iframe dialog modal.
182 * @param {url} string Content location.
183 * @param {String} winname If set becomes modal id and/or iframes name. Or, one is created/assigned(iframes).
184 * @param {Number| String} width|modalSize(modal-xlg) For sizing: an number will be converted to a percentage of view port width.
185 * @param {Number} height Initial height. For iframe auto resize starts here.
186 * @param {boolean} forceNewWindow Force using a native window.
187 * @param {String} title If exist then header with title is created otherwise no header and content only.
188 * @param {Object} opts Dialogs options.
189 * @returns {Object} dialog object reference.
190 * */
191 function dlgopen(url, winname, width, height, forceNewWindow, title, opts) {
192     // First things first...
193     top.restoreSession();
194     // A matter of Legacy
195     if (forceNewWindow) {
196         return dlgOpenWindow(url, winname, width, height);
197     }
199     // wait for DOM then check dependencies needed to run this feature.
200     // dependency duration is while 'this' is in scope, temporary...
201     // seldom will this get used as more of U.I is moved to Bootstrap
202     // but better to continue than stop because of a dependency...
203     //
204     let jqurl = top.webroot_url + '/public/assets/jquery-min-1-9-1/index.js';
205     if (typeof jQuery.fn.jquery === 'undefined') {
206         includeScript(jqurl, false, 'script'); // true is async
207     }
208     jQuery(function () {
209         // Check for dependencies we will need.
210         // webroot_url is a global defined in main_screen.php or main.php.
212         let bscss = top.webroot_url + '/public/assets/bootstrap-3-3-4/dist/css/bootstrap.min.css';
213         let bsurl = top.webroot_url + '/public/assets/bootstrap-3-3-4/dist/js/bootstrap.min.js';
214         let jqui = top.webroot_url + '/public/assets/jquery-ui-1-12-1/jquery-ui.min.js';
216         let version = jQuery.fn.jquery.split(' ')[0].split('.');
217         if ((version[0] < 2 && version[1] < 9) || (version[0] == 1 && version[1] == 9 && version[2] < 1)) {
218             inDom('jquery-min', 'script', true);
219             includeScript(jqurl, false, 'script');
220             console.log('Replacing jQuery version:[ ' + version + ' ]');
221         }
222         if (!inDom('bootstrap.min.css', 'link', false)) {
223             includeScript(bscss, false, 'link');
224         }
225         if (typeof jQuery.fn.modal === 'undefined') {
226             if (!inDom('bootstrap.min.js', 'script', false))
227                 includeScript(bsurl, false, 'script');
228         }
229         if (typeof jQuery.ui === 'undefined') {
230             includeScript(jqui, false, 'script');
231         }
232     });
234     // onward
235     var opts_defaults = {
236         type: 'iframe',
237         allowDrag: true,
238         allowResize: true,
239         sizeHeight: 'auto', // fixed in works...
240         onClosed: false,
241         callBack: false
242     };
244     if (!opts) var opts = {};
246     opts = jQuery.extend({}, opts_defaults, opts);
248     var mHeight, mWidth, mSize, msSize, dlgContainer, fullURL, where; // a growing list...
250     if (top.tab_mode) {
251         where = opts.type === 'iframe' ? top : window;
252     } else { // if frames u.i, this will search for the first body node so we have a landing place for stackable's
253         let wframe = window;
254         if (wframe.name !== 'left_nav') {
255             for (let i = 0; wframe.name !== 'RTop' && wframe.name !== 'RBot' && i < 6; wframe = wframe.parent) {
256                 if (i === 5) {
257                     wframe = window;
258                 }
259                 i++;
260             }
261         } else {
262             wframe = top.window['RTop'];
263         }
264         for (let i = 0; wframe.document.body.localName !== 'body' && i < 6; wframe = wframe[i++]) {
265             if (i === 5) {
266                 alert('<?php echo xlt("Unable to find window to build") ?>');
267                 return false;
268             }
269         }
271         where = wframe; // A moving target for Frames UI.
272     }
274     // get url straight...
275     if (opts.url) {
276         url = opts.url;
277     }
278     if (url[0] === "/") {
279         fullURL = url
280     }
281     else {
282         fullURL = window.location.href.substr(0, window.location.href.lastIndexOf("/") + 1) + url;
283     }
284     // what's a window without a name. important for stacking and opener.
285     winname = (winname === "_blank" || !winname) ? dialogID() : winname;
287     // Convert dialog size to percentages and/or css class.
288     var sizeChoices = ['modal-sm', 'modal-md', 'modal-mlg', 'modal-lg', 'modal-xl'];
289     if (Math.abs(width) > 0) {
290         width = Math.abs(width);
291         mWidth = (width / where.innerWidth * 100).toFixed(4) + '%';
292         msSize = '<style>.modal-custom' + winname + ' {width:' + mWidth + ';}</style>';
293         mSize = 'modal-custom' + winname;
294     } else if (jQuery.inArray(width, sizeChoices) !== -1) {
295         mSize = width; // is a modal class
296     } else {
297         msSize = 'default'; // standard B.S. modal default (modal-md)
298     }
300     if (mSize === 'modal-sm') {
301         msSize = '<style>.modal-sm {width:25%;}</style>';
302     } else if (mSize === 'modal-md') {
303         msSize = '<style>.modal-md {width:40%;}</style>';
304     } else if (mSize === 'modal-mlg') {
305         msSize = '<style>.modal-mlg {width:55%;}</style>';
306     } else if (mSize === 'modal-lg') {
307         msSize = '<style>.modal-lg {width:75%;}</style>';
308     } else if (mSize === 'modal-xl') {
309         msSize = '<style>.modal-xl {width:96%;}</style>';
310     }
312     // Initial responsive height.
313     var vpht = where.innerHeight;
314     mHeight = height > 0 ? (height / vpht * 100).toFixed(4) + 'vh' : '';
316     // Build modal template. For now !title = !header and modal full height.
317     var mTitle = title > "" ? '<h4 class=modal-title>' + title + '</h4>' : '';
319     var waitHtml =
320         '<div class="loadProgress text-center">' +
321         '<span class="fa fa-circle-o-notch fa-spin fa-3x text-primary"></span>' +
322         '</div>';
324     var headerhtml =
325         ('<div class=modal-header><span type=button class="x close" data-dismiss=modal>' +
326             '<span aria-hidden=true>&times;</span>' +
327             '</span><h5 class=modal-title>%title%</h5></div>')
328             .replace('%title%', mTitle);
330     var frameHead =
331         ('<div><span class="close data-dismiss=modal aria-hidden="true">&times;</span></div>');
333     var frameHtml =
334         ('<iframe id="modalframe" class="embed-responsive-item modalIframe" name="%winname%" frameborder=0 src="%url%">' +
335             '</iframe>')
336             .replace('%winname%', winname)
337             .replace('%url%', fullURL);
339     var embedded = 'embed-responsive embed-responsive-16by9';
341     var bodyStyles = (' style="margin:2px;padding:2px;height:%initHeight%;max-height:94vh;overflow-y:auto;"')
342         .replace('%initHeight%', opts.sizeHeight !== 'full' ? mHeight : '94vh');
344     var altClose = '<div class="closeDlgIframe" data-dismiss="modal" ></div>';
346     var mhtml =
347         ('<div id="%id%" class="modal fade dialogModal" tabindex="-1" role="dialog">%sStyle%' +
348             '<style>.modal-backdrop{opacity:0; transition:opacity 1s;}.modal-backdrop.in{opacity:0.2;}</style>' +
349             '<div %dialogId% class="modal-dialog %szClass%" role="document">' +
350             '<div class="modal-content">' +
351             '%head%' + '%altclose%' + '%wait%' +
352             '<div class="modal-body %embedded%" %bodyStyles%>' +
353             '%body%' + '</div></div></div></div>')
354             .replace('%id%', winname)
355             .replace('%sStyle%', msSize !== "default" ? msSize : '')
356             .replace('%dialogId%', opts.dialogId ? ('id="' + opts.dialogId + '"') : '')
357             .replace('%szClass%', mSize ? mSize : '')
358             .replace('%head%', mTitle !== '' ? headerhtml : '')
359             .replace('%altclose%', mTitle === '' ? altClose : '')
360             .replace('%wait%', '') // maybe option later
361             .replace('%bodyStyles%', bodyStyles)
362             .replace('%embedded%', opts.type === 'iframe' ? embedded : '')
363             .replace('%body%', opts.type === 'iframe' ? frameHtml : '');
365     // Write modal template.
366     //
367     dlgContainer = where.jQuery(mhtml);
368     dlgContainer.attr("name", winname);
370     if (opts.buttons) {
371         dlgContainer.find('.modal-content').append(buildFooter());
372     }
373     if (opts.type !== 'iframe') {
374         var params = {
375             type: opts.type || '', // if empty and has data object, then post else get.
376             data: opts.data || opts.html || '', // ajax loads fetched content or supplied html. think alerts.
377             url: opts.url || fullURL,
378             dataType: opts.dataType || '' // xml/json/text etc.
379         };
381         dialogAjax(params, dlgContainer);
382     }
384     // let opener array know about us.
385     top.set_opener(winname, window);
387     // Write the completed template to calling document or 'where' window.
388     where.jQuery("body").append(dlgContainer);
390     jQuery(function () {
391         // DOM Ready. Handle events and cleanup.
392         if (opts.type === 'iframe') {
393             var modalwin = where.jQuery('body').find("[name='" + winname + "']");
394             jQuery('div.modal-dialog', modalwin).css({'margin': '15px auto'});
395             modalwin.on('load', function (e) {
396                 setTimeout(function () {
397                     if (opts.sizeHeight === 'auto') {
398                         SizeModaliFrame(e, height);
399                     } else {
400                         sizing(e, height);
401                     }
402                 }, 500);
403             });
404         }
406         dlgContainer.on('show.bs.modal', function () {
407             if (opts.allowResize) {
408                 jQuery('.modal-content', this).resizable({
409                     grid: [5, 5],
410                     animate: true,
411                     animateEasing: "swing",
412                     animateDuration: "fast",
413                     alsoResize: jQuery('div.modal-body', this)
414                 })
415             }
416             if (opts.allowDrag) {
417                 jQuery('.modal-dialog', this).draggable({
418                     iframeFix: true,
419                     cursor: false
420                 });
421             }
422         }).on('shown.bs.modal', function () {
423             // Remove waitHtml spinner/loader etc.
424             jQuery(this).parent().find('div.loadProgress')
425                 .fadeOut(function () {
426                     jQuery(this).remove();
427                 });
428             dlgContainer.modal('handleUpdate'); // allow for scroll bar
429         }).on('hidden.bs.modal', function (e) {
430             // remove our dialog
431             jQuery(this).remove();
432             console.log('Modal hidden then removed!');
434             // now we can run functions in our window.
435             if (opts.onClosed) {
436                 console.log('Doing onClosed:[' + opts.onClosed + ']');
437                 if (opts.onClosed === 'reload') {
438                     window.location.reload();
439                 } else {
440                     window[opts.onClosed]();
441                 }
442             }
443             if (opts.callBack.call) {
444                 console.log('Doing callBack:[' + opts.callBack.call + '|' + opts.callBack.args + ']');
445                 if (opts.callBack.call === 'reload') {
446                     window.location.reload();
447                 } else {
448                     window[opts.callBack.call](opts.callBack.args);
449                 }
450             }
452         }).modal({backdrop: 'static', keyboard: true}, 'show');// Show Modal
454         // define local dialog close() function. openers scope
455         window.dlgCloseAjax = function (calling, args) {
456             if (calling) {
457                 opts.callBack = {call: calling, args: args};
458             }
459             dlgContainer.modal('hide'); // important to clean up in only one place, hide event....
460             return false;
461         };
463         // define local callback function. Set with opener or from opener, will exe on hide.
464         window.dlgSetCallBack = function (calling, args) {
465             opts.callBack = {call: calling, args: args};
466             return false;
467         };
469         // in residents dialog scope
470         where.setCallBack = function (calling, args) {
471             opts.callBack = {call: calling, args: args};
472             return true;
473         };
475         where.getOpener = function () {
476             return where;
477         };
479         // Return the dialog ref. looking towards deferring...
480         return dlgContainer;
482     }); // end events
484     function dialogAjax(data, $dialog) {
485         var params = {
486             async: true,
487             url: data.url || data,
488             dataType: data.dataType || 'text'
489         };
491         if (data.url) {
492             jQuery.extend(params, data);
493         }
495         jQuery.ajax(params)
496             .done(aOkay)
497             .fail(oops);
499         return true;
501         function aOkay(html) {
502             $dialog.find('.modal-body').html(data.success ? data.success(html) : html);
504             return true;
505         }
507         function oops(r, s) {
508             var msg = data.error ?
509                 data.error(r, s, params) :
510                 '<div class="alert alert-danger">' +
511                 '<strong><?php echo xlt("XHR Failed:") ?> </strong> [ ' + params.url + '].' + '</div>';
513             $dialog.find('.modal-body').html(msg);
515             return false;
516         }
517     }
519     function buildFooter() {
520         if (opts.buttons === false) {
521             return '';
522         }
523         var oFoot = jQuery('<div>').addClass('modal-footer').prop('id', 'oefooter');
524         if (opts.buttons) {
525             for (var i = 0, k = opts.buttons.length; i < k; i++) {
526                 var btnOp = opts.buttons[i];
527                 var btn = jQuery('<button>').addClass('btn btn-' + (btnOp.style || 'primary'));
529                 for (var index in btnOp) {
530                     if (btnOp.hasOwnProperty(index)) {
531                         switch (index) {
532                             case 'close':
533                                 //add close event
534                                 if (btnOp[index]) {
535                                     btn.attr('data-dismiss', 'modal');
536                                 }
537                                 break;
538                             case 'click':
539                                 //binds button to click event of fn defined in calling document/form
540                                 var fn = btnOp.click.bind(dlgContainer.find('.modal-content'));
541                                 btn.click(fn);
542                                 break;
543                             case 'text':
544                                 btn.html(btnOp[index]);
545                                 break;
546                             default:
547                                 //all other possible HTML attributes to button element
548                                 btn.attr(index, btnOp[index]);
549                         }
550                     }
551                 }
553                 oFoot.append(btn);
554             }
555         } else {
556             //if no buttons defined by user, add a standard close button.
557             oFoot.append('<button class="closeBtn btn btn-default" data-dismiss=modal type=button><?php echo xlt("Close") ?></button>');
558         }
560         return oFoot; // jquery object of modal footer.
561     }
563     // dynamic sizing - special case for full height - @todo use for fixed wt and ht
564     function sizing(e, height) {
565         var $idoc = jQuery(e.currentTarget);
566         if (top.tab_mode) {
567             var viewPortHt = Math.max(top.window.document.documentElement.clientHeight, top.window.innerHeight || 0);
568             var viewPortWt = Math.max(top.window.document.documentElement.clientWidth, top.window.innerWidth || 0);
569         } else {
570             var viewPortHt = window.innerHeight || 0;
571             var viewPortWt = window.innerWidth || 0;
572         }
573         var frameContentHt = opts.sizeHeight === 'full' ? viewPortHt : height;
574         frameContentHt = frameContentHt > viewPortHt ? viewPortHt : frameContentHt;
575         var hasHeader = $idoc.parents('div.modal-content').find('div.modal-header').height() || 0;
576         var hasFooter = $idoc.parents('div.modal-content').find('div.modal-footer').height() || 0;
577         frameContentHt = frameContentHt - hasHeader - hasFooter;
578         size = (frameContentHt / viewPortHt * 100).toFixed(4);
579         size = size + 'vh';
580         $idoc.parents('div.modal-body').css({'height': size, 'max-height': '91.5vh', 'max-width': '96vw'});
581         console.log('Modal loaded and sized! Content:' + frameContentHt + ' Viewport:' + viewPortHt + ' Modal height:' +
582             size + ' Type:' + opts.sizeHeight + ' Width:' + hasHeader + ' isFooter:' + hasFooter);
584         return size;
585     }
587     // sizing for modals with iframes
588     function SizeModaliFrame(e, minSize) {
589         var idoc = e.currentTarget.contentDocument ? e.currentTarget.contentDocument : e.currentTarget.contentWindow.document;
590         jQuery(e.currentTarget).parents('div.modal-content').height('');
591         jQuery(e.currentTarget).parent('div.modal-body').css({'height': 0});
592         if (top.tab_mode) {
593             var viewPortHt = top.window.innerHeight || 0;
594         } else {
595             var viewPortHt = where.window.innerHeight || 0;
596         }
597         //minSize = 100;
598         var frameContentHt = Math.max(jQuery(idoc).height(), idoc.body.offsetHeight || 0) + 30;
599         frameContentHt = frameContentHt < minSize ? minSize : frameContentHt;
600         frameContentHt = frameContentHt > viewPortHt ? viewPortHt : frameContentHt;
601         var hasHeader = jQuery(e.currentTarget).parents('div.modal-content').find('div.modal-header').length;
602         var hasFooter = jQuery(e.currentTarget).parents('div.modal-content').find('div.modal-footer').length;
603         size = (frameContentHt / viewPortHt * 100).toFixed(4);
604         var maxsize = hasHeader ? 90 : hasFooter ? 87.5 : 96;
605         maxsize = hasHeader && hasFooter ? 84 : maxsize;
606         maxsize = maxsize + 'vh';
607         size = size + 'vh'; // will start the dialog as responsive. Any resize by user turns dialog to absolute positioning.
609         jQuery(e.currentTarget).parent('div.modal-body').css({'height': size, 'max-height': maxsize}); // Set final size. Width was previously set.
610         //jQuery(e.currentTarget).parent('div.modal-body').height(size)
611         console.log('Modal loaded and sized! Content:' + frameContentHt + ' Viewport:' + viewPortHt + ' Modal height:' +
612             size + ' Max height:' + maxsize + ' isHeader:' + (hasHeader > 0 ? 'True ' : 'False ') + ' isFooter:' + (hasFooter > 0 ? 'True' : 'False'));
614         return size;
615     }