1 // Copyright (C) 2005 Rod Roark <rod@sunsetsystems.com>
2 // Copyright (C) 2018 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.
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;
20 if ((newx + width) > screen.width || (newy + height) > screen.height) {
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
37 retval = window.open(url, winname, options +
38 ",width=" + width + ",height=" + height +
39 ",left=" + newx + ",top=" + newy +
40 ",screenX=" + newx + ",screenY=" + newy);
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;
66 top.modaldialog = cascwin(url, winname, width, height,
67 "resizable=1,scrollbars=1,location=0,toolbar=0");
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) {
76 // Deleting everything.
83 // Convert the codes and their descriptions to arrays for easy manipulation.
84 var acodes = elem.value.split(';');
85 var i = acodes.indexOf(s);
87 return; // not found, should not happen
89 // Delete the indicated code and description and convert back to strings.
91 elem.value = acodes.join(';');
93 var atitles = elem.title.split(';');
95 elem.title = atitles.join(';');
101 return Math.floor((1 + Math.random()) * 0x10000)
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'.
119 function includeScript(url, async, type) {
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 + ' ]');
134 rqit.open("GET", url, async); // false = synchronous.
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.
149 throw new Error('<?php echo xlt("Failed to get URL:") ?>' + url);
158 // test for and/or remove dependency.
159 function inDom(dependency, type, remove) {
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) {
166 all[i].parentNode.removeChild(all[i]);
167 console.log("Removed from DOM: " + dependency)
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.
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);
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...
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
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 bscssRtl = top.webroot_url + '/public/assets/bootstrap-rtl-3-3-4/dist/css/bootstrap-rtl.min.css';
214 let bsurl = top.webroot_url + '/public/assets/bootstrap-3-3-4/dist/js/bootstrap.min.js';
215 let jqui = top.webroot_url + '/public/assets/jquery-ui-1-12-1/jquery-ui.min.js';
217 let version = jQuery.fn.jquery.split(' ')[0].split('.');
218 if ((version[0] < 2 && version[1] < 9) || (version[0] == 1 && version[1] == 9 && version[2] < 1)) {
219 inDom('jquery-min', 'script', true);
220 includeScript(jqurl, false, 'script');
221 console.log('Replacing jQuery version:[ ' + version + ' ]');
223 if (!inDom('bootstrap.min.css', 'link', false)) {
224 includeScript(bscss, false, 'link');
225 if (top.jsLanguageDirection === 'rtl') {
226 includeScript(bscssRtl, false, 'link');
229 if (typeof jQuery.fn.modal === 'undefined') {
230 if (!inDom('bootstrap.min.js', 'script', false))
231 includeScript(bsurl, false, 'script');
233 if (typeof jQuery.ui === 'undefined') {
234 includeScript(jqui, false, 'script');
239 var opts_defaults = {
243 sizeHeight: 'auto', // fixed in works...
248 if (!opts) var opts = {};
250 opts = jQuery.extend({}, opts_defaults, opts);
252 var mHeight, mWidth, mSize, msSize, dlgContainer, fullURL, where; // a growing list...
255 where = opts.type === 'iframe' ? top : window;
256 } else { // if frames u.i, this will search for the first body node so we have a landing place for stackable's
258 if (wframe.name !== 'left_nav') {
259 for (let i = 0; wframe.name !== 'RTop' && wframe.name !== 'RBot' && i < 6; wframe = wframe.parent) {
266 wframe = top.window['RTop'];
268 for (let i = 0; wframe.document.body.localName !== 'body' && i < 6; wframe = wframe[i++]) {
270 alert('<?php echo xlt("Unable to find window to build") ?>');
275 where = wframe; // A moving target for Frames UI.
278 // get url straight...
282 if (url[0] === "/") {
286 fullURL = window.location.href.substr(0, window.location.href.lastIndexOf("/") + 1) + url;
288 // what's a window without a name. important for stacking and opener.
289 winname = (winname === "_blank" || !winname) ? dialogID() : winname;
291 // Convert dialog size to percentages and/or css class.
292 var sizeChoices = ['modal-sm', 'modal-md', 'modal-mlg', 'modal-lg', 'modal-xl'];
293 if (Math.abs(width) > 0) {
294 width = Math.abs(width);
295 mWidth = (width / where.innerWidth * 100).toFixed(4) + '%';
296 msSize = '<style>.modal-custom' + winname + ' {width:' + mWidth + ';}</style>';
297 mSize = 'modal-custom' + winname;
298 } else if (jQuery.inArray(width, sizeChoices) !== -1) {
299 mSize = width; // is a modal class
301 msSize = 'default'; // standard B.S. modal default (modal-md)
304 if (mSize === 'modal-sm') {
305 msSize = '<style>.modal-sm {width:25%;}</style>';
306 } else if (mSize === 'modal-md') {
307 msSize = '<style>.modal-md {width:40%;}</style>';
308 } else if (mSize === 'modal-mlg') {
309 msSize = '<style>.modal-mlg {width:55%;}</style>';
310 } else if (mSize === 'modal-lg') {
311 msSize = '<style>.modal-lg {width:75%;}</style>';
312 } else if (mSize === 'modal-xl') {
313 msSize = '<style>.modal-xl {width:96%;}</style>';
316 // Initial responsive height.
317 var vpht = where.innerHeight;
318 mHeight = height > 0 ? (height / vpht * 100).toFixed(4) + 'vh' : '';
320 // Build modal template. For now !title = !header and modal full height.
321 var mTitle = title > "" ? '<h4 class=modal-title>' + title + '</h4>' : '';
324 '<div class="loadProgress text-center">' +
325 '<span class="fa fa-circle-o-notch fa-spin fa-3x text-primary"></span>' +
329 ('<div class=modal-header><span type=button class="x close" data-dismiss=modal>' +
330 '<span aria-hidden=true>×</span>' +
331 '</span><h5 class=modal-title>%title%</h5></div>')
332 .replace('%title%', mTitle);
335 ('<div><span class="close data-dismiss=modal aria-hidden="true">×</span></div>');
338 ('<iframe id="modalframe" class="embed-responsive-item modalIframe" name="%winname%" frameborder=0 src="%url%">' +
340 .replace('%winname%', winname)
341 .replace('%url%', fullURL);
343 var embedded = 'embed-responsive embed-responsive-16by9';
345 var bodyStyles = (' style="margin:2px;padding:2px;height:%initHeight%;max-height:94vh;overflow-y:auto;"')
346 .replace('%initHeight%', opts.sizeHeight !== 'full' ? mHeight : '94vh');
348 var altClose = '<div class="closeDlgIframe" data-dismiss="modal" ></div>';
351 ('<div id="%id%" class="modal fade dialogModal" tabindex="-1" role="dialog">%sStyle%' +
352 '<style>.modal-backdrop{opacity:0; transition:opacity 1s;}.modal-backdrop.in{opacity:0.2;}</style>' +
353 '<div %dialogId% class="modal-dialog %szClass%" role="document">' +
354 '<div class="modal-content">' +
355 '%head%' + '%altclose%' + '%wait%' +
356 '<div class="modal-body %embedded%" %bodyStyles%>' +
357 '%body%' + '</div></div></div></div>')
358 .replace('%id%', winname)
359 .replace('%sStyle%', msSize !== "default" ? msSize : '')
360 .replace('%dialogId%', opts.dialogId ? ('id="' + opts.dialogId + '"') : '')
361 .replace('%szClass%', mSize ? mSize : '')
362 .replace('%head%', mTitle !== '' ? headerhtml : '')
363 .replace('%altclose%', mTitle === '' ? altClose : '')
364 .replace('%wait%', '') // maybe option later
365 .replace('%bodyStyles%', bodyStyles)
366 .replace('%embedded%', opts.type === 'iframe' ? embedded : '')
367 .replace('%body%', opts.type === 'iframe' ? frameHtml : '');
369 // Write modal template.
371 dlgContainer = where.jQuery(mhtml);
372 dlgContainer.attr("name", winname);
375 dlgContainer.find('.modal-content').append(buildFooter());
377 if (opts.type !== 'iframe') {
379 type: opts.type || '', // if empty and has data object, then post else get.
380 data: opts.data || opts.html || '', // ajax loads fetched content or supplied html. think alerts.
381 url: opts.url || fullURL,
382 dataType: opts.dataType || '' // xml/json/text etc.
385 dialogAjax(params, dlgContainer);
388 // let opener array know about us.
389 top.set_opener(winname, window);
391 // Write the completed template to calling document or 'where' window.
392 where.jQuery("body").append(dlgContainer);
395 // DOM Ready. Handle events and cleanup.
396 if (opts.type === 'iframe') {
397 var modalwin = where.jQuery('body').find("[name='" + winname + "']");
398 jQuery('div.modal-dialog', modalwin).css({'margin': '15px auto'});
399 modalwin.on('load', function (e) {
400 setTimeout(function () {
401 if (opts.sizeHeight === 'auto') {
402 SizeModaliFrame(e, height);
403 } else if (opts.sizeHeight === 'fixed') {
406 sizing(e, height); // must be full height of container
412 dlgContainer.on('show.bs.modal', function () {
413 if (opts.allowResize) {
414 jQuery('.modal-content', this).resizable({
417 animateEasing: "swing",
418 animateDuration: "fast",
419 alsoResize: jQuery('div.modal-body', this)
422 if (opts.allowDrag) {
423 jQuery('.modal-dialog', this).draggable({
428 }).on('shown.bs.modal', function () {
429 // Remove waitHtml spinner/loader etc.
430 jQuery(this).parent().find('div.loadProgress')
431 .fadeOut(function () {
432 jQuery(this).remove();
434 dlgContainer.modal('handleUpdate'); // allow for scroll bar
435 }).on('hidden.bs.modal', function (e) {
437 jQuery(this).remove();
438 console.log('Modal hidden then removed!');
440 // now we can run functions in our window.
442 console.log('Doing onClosed:[' + opts.onClosed + ']');
443 if (opts.onClosed === 'reload') {
444 window.location.reload();
446 window[opts.onClosed]();
449 if (opts.callBack.call) {
450 console.log('Doing callBack:[' + opts.callBack.call + '|' + opts.callBack.args + ']');
451 if (opts.callBack.call === 'reload') {
452 window.location.reload();
454 window[opts.callBack.call](opts.callBack.args);
458 }).modal({backdrop: 'static', keyboard: true}, 'show');// Show Modal
460 // define local dialog close() function. openers scope
461 window.dlgCloseAjax = function (calling, args) {
463 opts.callBack = {call: calling, args: args};
465 dlgContainer.modal('hide'); // important to clean up in only one place, hide event....
469 // define local callback function. Set with opener or from opener, will exe on hide.
470 window.dlgSetCallBack = function (calling, args) {
471 opts.callBack = {call: calling, args: args};
475 // in residents dialog scope
476 where.setCallBack = function (calling, args) {
477 opts.callBack = {call: calling, args: args};
481 where.getOpener = function () {
485 // Return the dialog ref. looking towards deferring...
490 function dialogAjax(data, $dialog) {
493 url: data.url || data,
494 dataType: data.dataType || 'text'
498 jQuery.extend(params, data);
507 function aOkay(html) {
508 $dialog.find('.modal-body').html(data.success ? data.success(html) : html);
513 function oops(r, s) {
514 var msg = data.error ?
515 data.error(r, s, params) :
516 '<div class="alert alert-danger">' +
517 '<strong><?php echo xlt("XHR Failed:") ?> </strong> [ ' + params.url + '].' + '</div>';
519 $dialog.find('.modal-body').html(msg);
525 function buildFooter() {
526 if (opts.buttons === false) {
529 var oFoot = jQuery('<div>').addClass('modal-footer').prop('id', 'oefooter');
531 for (var i = 0, k = opts.buttons.length; i < k; i++) {
532 var btnOp = opts.buttons[i];
533 var btn = jQuery('<button>').addClass('btn btn-' + (btnOp.style || 'primary'));
535 for (var index in btnOp) {
536 if (btnOp.hasOwnProperty(index)) {
541 btn.attr('data-dismiss', 'modal');
545 //binds button to click event of fn defined in calling document/form
546 var fn = btnOp.click.bind(dlgContainer.find('.modal-content'));
550 btn.html(btnOp[index]);
553 //all other possible HTML attributes to button element
554 btn.attr(index, btnOp[index]);
562 //if no buttons defined by user, add a standard close button.
563 oFoot.append('<button class="closeBtn btn btn-default" data-dismiss=modal type=button><?php echo xlt("Close") ?></button>');
566 return oFoot; // jquery object of modal footer.
569 // dynamic sizing - special case for full height - @todo use for fixed wt and ht
570 function sizing(e, height) {
572 let $idoc = jQuery(e.currentTarget);
574 viewPortHt = Math.max(top.window.document.documentElement.clientHeight, top.window.innerHeight || 0);
575 viewPortWt = Math.max(top.window.document.documentElement.clientWidth, top.window.innerWidth || 0);
577 viewPortHt = window.innerHeight || 0;
578 viewPortWt = window.innerWidth || 0;
580 let frameContentHt = opts.sizeHeight === 'full' ? viewPortHt : height;
581 frameContentHt = frameContentHt > viewPortHt ? viewPortHt : frameContentHt;
582 let hasHeader = $idoc.parents('div.modal-content').find('div.modal-header').height() || 0;
583 let hasFooter = $idoc.parents('div.modal-content').find('div.modal-footer').height() || 0;
584 frameContentHt = frameContentHt - hasHeader - hasFooter;
585 size = (frameContentHt / viewPortHt * 100).toFixed(4);
586 let maxsize = hasHeader ? 90 : hasFooter ? 87.5 : 96;
587 maxsize = hasHeader && hasFooter ? 80 : maxsize;
588 maxsize = maxsize + 'vh';
590 $idoc.parents('div.modal-body').css({'height': size, 'max-height': maxsize, 'max-width': '96vw'});
591 console.log('Modal loaded and sized! Content:' + frameContentHt + ' Viewport:' + viewPortHt + ' Modal height:' +
592 size + ' Type:' + opts.sizeHeight + ' Width:' + hasHeader + ' isFooter:' + hasFooter);
597 // sizing for modals with iframes
598 function SizeModaliFrame(e, minSize) {
600 let idoc = e.currentTarget.contentDocument ? e.currentTarget.contentDocument : e.currentTarget.contentWindow.document;
601 jQuery(e.currentTarget).parents('div.modal-content').height('');
602 jQuery(e.currentTarget).parent('div.modal-body').css({'height': 0});
604 viewPortHt = top.window.innerHeight || 0;
606 viewPortHt = where.window.innerHeight || 0;
609 let frameContentHt = Math.max(jQuery(idoc).height(), idoc.body.offsetHeight || 0) + 30;
610 frameContentHt = frameContentHt < minSize ? minSize : frameContentHt;
611 frameContentHt = frameContentHt > viewPortHt ? viewPortHt : frameContentHt;
612 let hasHeader = jQuery(e.currentTarget).parents('div.modal-content').find('div.modal-header').length;
613 let hasFooter = jQuery(e.currentTarget).parents('div.modal-content').find('div.modal-footer').length;
614 size = (frameContentHt / viewPortHt * 100).toFixed(4);
615 let maxsize = hasHeader ? 90 : hasFooter ? 87.5 : 96;
616 maxsize = hasHeader && hasFooter ? 80 : maxsize;
617 maxsize = maxsize + 'vh';
618 size = size + 'vh'; // will start the dialog as responsive. Any resize by user turns dialog to absolute positioning.
620 jQuery(e.currentTarget).parent('div.modal-body').css({'height': size, 'max-height': maxsize}); // Set final size. Width was previously set.
621 //jQuery(e.currentTarget).parent('div.modal-body').height(size)
622 console.log('Modal loaded and sized! Content:' + frameContentHt + ' Viewport:' + viewPortHt + ' Modal height:' +
623 size + ' Max height:' + maxsize + ' isHeader:' + (hasHeader > 0 ? 'True ' : 'False ') + ' isFooter:' + (hasFooter > 0 ? 'True' : 'False'));