1 /*
  2     Copyright 2008-2022
  3         Matthias Ehmann,
  4         Michael Gerhaeuser,
  5         Carsten Miller,
  6         Bianca Valentin,
  7         Alfred Wassermann,
  8         Peter Wilfahrt
  9 
 10     This file is part of JSXGraph.
 11 
 12     JSXGraph is free software dual licensed under the GNU LGPL or MIT License.
 13 
 14     You can redistribute it and/or modify it under the terms of the
 15 
 16       * GNU Lesser General Public License as published by
 17         the Free Software Foundation, either version 3 of the License, or
 18         (at your option) any later version
 19       OR
 20       * MIT License: https://github.com/jsxgraph/jsxgraph/blob/master/LICENSE.MIT
 21 
 22     JSXGraph is distributed in the hope that it will be useful,
 23     but WITHOUT ANY WARRANTY; without even the implied warranty of
 24     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 25     GNU Lesser General Public License for more details.
 26 
 27     You should have received a copy of the GNU Lesser General Public License and
 28     the MIT License along with JSXGraph. If not, see <http://www.gnu.org/licenses/>
 29     and <http://opensource.org/licenses/MIT/>.
 30  */
 31 
 32 
 33 /*global JXG: true, document:true, jQuery:true, define: true, window: true*/
 34 /*jslint nomen: true, plusplus: true*/
 35 
 36 /* depends:
 37  jxg
 38  utils/env
 39  utils/type
 40  base/board
 41  reader/file
 42  options
 43  renderer/svg
 44  renderer/vml
 45  renderer/canvas
 46  renderer/no
 47  */
 48 
 49 /**
 50  * @fileoverview The JSXGraph object is defined in this file. JXG.JSXGraph controls all boards.
 51  * It has methods to create, save, load and free boards. Additionally some helper functions are
 52  * defined in this file directly in the JXG namespace.
 53  * @version 0.99
 54  */
 55 
 56 define([
 57     'jxg', 'utils/env', 'utils/type', 'base/board', 'reader/file', 'options',
 58     'renderer/svg', 'renderer/vml', 'renderer/canvas', 'renderer/no'
 59 ], function (JXG, Env, Type, Board, FileReader, Options, SVGRenderer, VMLRenderer, CanvasRenderer, NoRenderer) {
 60 
 61     "use strict";
 62 
 63     /**
 64      * Constructs a new JSXGraph singleton object.
 65      * @class The JXG.JSXGraph singleton stores all properties required
 66      * to load, save, create and free a board.
 67      */
 68     JXG.JSXGraph = {
 69         /**
 70          * Stores the renderer that is used to draw the boards.
 71          * @type String
 72          */
 73         rendererType: (function () {
 74             Options.board.renderer = 'no';
 75 
 76             if (Env.supportsVML()) {
 77                 Options.board.renderer = 'vml';
 78                 // Ok, this is some real magic going on here. IE/VML always was so
 79                 // terribly slow, except in one place: Examples placed in a moodle course
 80                 // was almost as fast as in other browsers. So i grabbed all the css and
 81                 // lib scripts from our moodle, added them to a jsxgraph example and it
 82                 // worked. next step was to strip all the css/lib code which didn't affect
 83                 // the VML update speed. The following five lines are what was left after
 84                 // the last step and yes - it basically does nothing but reads two
 85                 // properties of document.body on every mouse move. why? we don't know. if
 86                 // you know, please let us know.
 87                 //
 88                 // If we want to use the strict mode we have to refactor this a little bit. Let's
 89                 // hope the magic isn't gone now. Anywho... it's only useful in old versions of IE
 90                 // which should not be used anymore.
 91                 document.onmousemove = function () {
 92                     var t;
 93 
 94                     if (document.body) {
 95                         t = document.body.scrollLeft;
 96                         t += document.body.scrollTop;
 97                     }
 98 
 99                     return t;
100                 };
101             }
102 
103             if (Env.supportsCanvas()) {
104                 Options.board.renderer = 'canvas';
105             }
106 
107             if (Env.supportsSVG()) {
108                 Options.board.renderer = 'svg';
109             }
110 
111             // we are inside node
112             if (Env.isNode() && Env.supportsCanvas()) {
113                 Options.board.renderer = 'canvas';
114             }
115 
116             if (Env.isNode() || Options.renderer === 'no') {
117                 Options.text.display = 'internal';
118                 Options.infobox.display = 'internal';
119             }
120 
121             return Options.board.renderer;
122         }()),
123 
124         /**
125          * Initialize the rendering engine
126          *
127          * @param  {String} box        HTML id of the div-element which hosts the JSXGraph construction
128          * @param  {Object} dim        The dimensions of the board
129          * @param  {Object} doc        Usually, this is document object of the browser window.  If false or null, this defaults
130          * to the document object of the browser.
131          * @param  {Object} attrRenderer Attribute 'renderer', speficies the rendering engine. Possible values are 'auto', 'svg',
132          *  'canvas', 'no', and 'vml'.
133          * @returns {Object}           Reference to the rendering engine object.
134          * @private
135          */
136         initRenderer: function (box, dim, doc, attrRenderer) {
137             var boxid, renderer;
138 
139             // Former version:
140             // doc = doc || document
141             if ((!Type.exists(doc) || doc === false) && typeof document === 'object') {
142                 doc = document;
143             }
144 
145             if (typeof doc === 'object' && box !== null) {
146                 boxid = doc.getElementById(box);
147 
148                 // Remove everything from the container before initializing the renderer and the board
149                 while (boxid.firstChild) {
150                     boxid.removeChild(boxid.firstChild);
151                 }
152             } else {
153                 boxid = box;
154             }
155 
156             // If attrRenderer is not supplied take the first available renderer
157             if (attrRenderer === undefined || attrRenderer === 'auto') {
158                 attrRenderer = this.rendererType;
159             }
160             // create the renderer
161             if (attrRenderer === 'svg') {
162                 renderer = new SVGRenderer(boxid, dim);
163             } else if (attrRenderer === 'vml') {
164                 renderer = new VMLRenderer(boxid);
165             } else if (attrRenderer === 'canvas') {
166                 renderer = new CanvasRenderer(boxid, dim);
167             } else {
168                 renderer = new NoRenderer();
169             }
170 
171             return renderer;
172         },
173 
174         /**
175          * Merge the user supplied attributes with the attributes in options.js
176          *
177          * @param {Object} attributes User supplied attributes
178          * @returns {Object} Merged attributes for the board
179          *
180          * @private
181          */
182         _setAttributes: function(attributes) {
183             // merge attributes
184             var attr = Type.copyAttributes(attributes, Options, 'board');
185 
186             // The attributes which are objects have to be copied separately
187             attr.zoom = Type.copyAttributes(attr, Options, 'board', 'zoom');
188             attr.pan = Type.copyAttributes(attr, Options, 'board', 'pan');
189             attr.drag = Type.copyAttributes(attr, Options, 'board', 'drag');
190             attr.keyboard = Type.copyAttributes(attr, Options, 'board', 'keyboard');
191             attr.selection = Type.copyAttributes(attr, Options, 'board', 'selection');
192             attr.navbar = Type.copyAttributes(attr.navbar, Options, 'navbar');
193             attr.screenshot = Type.copyAttributes(attr, Options, 'board', 'screenshot');
194             attr.resize = Type.copyAttributes(attr, Options, 'board', 'resize');
195             attr.fullscreen = Type.copyAttributes(attr, Options, 'board', 'fullscreen');
196 
197             // Treat moveTarget separately, because deepCopy will not work here.
198             // Reason: moveTarget will be an HTML node and it is prevented that Type.deepCopy will copy it.
199             attr.movetarget = attributes.moveTarget || attributes.movetarget || Options.board.moveTarget;
200 
201             return attr;
202         },
203 
204         /**
205          * Further initialization of the board. Set some properties from attribute values.
206          *
207          * @param {JXG.Board} board
208          * @param {Object} attr attributes object
209          * @param {Object} dimensions Object containing dimensions of the canvas
210          *
211          * @private
212          */
213         _fillBoard: function(board, attr, dimensions) {
214             board.initInfobox();
215             board.maxboundingbox = attr.maxboundingbox;
216             board.resizeContainer(dimensions.width, dimensions.height, true, true);
217             board._createSelectionPolygon(attr);
218             board.renderer.drawZoomBar(board, attr.navbar);
219             JXG.boards[board.id] = board;
220         },
221 
222         /**
223          *
224          * @param {String} container HTML-ID to the HTML-element in which the board is painted.
225          * @param {*} attr An object that sets some of the board properties.
226          *
227          * @private
228          */
229         _setARIA: function(container, attr) {
230             var doc = attr.document || document,
231                 doc_glob,
232                 node_jsx, newNode, parent,
233                 id_label, id_description;
234 
235             if (typeof doc !== 'object') {
236                 return;
237             }
238 
239             node_jsx = doc.getElementById(container);
240             doc_glob = node_jsx.ownerDocument;   // This is the window.document element, needed below.
241             parent = node_jsx.parentNode;
242 
243             id_label = container + '_ARIAlabel';
244             id_description = container + '_ARIAdescription';
245 
246             newNode = doc_glob.createElement('div');
247             newNode.innerHTML = attr.title;
248             newNode.setAttribute('id', id_label);
249             newNode.style.display = 'none';
250             parent.insertBefore(newNode, node_jsx);
251 
252             newNode = doc_glob.createElement('div');
253             newNode.innerHTML = attr.description;
254             newNode.setAttribute('id', id_description);
255             newNode.style.display = 'none';
256             parent.insertBefore(newNode, node_jsx);
257 
258             node_jsx.setAttribute('aria-labelledby', id_label);
259             node_jsx.setAttribute('aria-describedby', id_description);
260         },
261 
262         /**
263          * Remove the two corresponding ARIA divs when freeing a board
264          *
265          * @param {JXG.Board} board
266          *
267          * @private
268          */
269         _removeARIANodes: function(board) {
270             var node, id, doc;
271 
272             doc = board.document || document;
273             if (typeof doc !== 'object') {
274                 return;
275             }
276 
277             id = board.containerObj.getAttribute('aria-labelledby');
278             node = doc.getElementById(id);
279             if (node && node.parentNode) {
280                 node.parentNode.removeChild(node);
281             }
282             id = board.containerObj.getAttribute('aria-describedby');
283             node = doc.getElementById(id);
284             if (node && node.parentNode) {
285                 node.parentNode.removeChild(node);
286             }
287         },
288 
289         /**
290          * Initialise a new board.
291          * @param {String} box HTML-ID to the HTML-element in which the board is painted.
292          * @param {Object} attributes An object that sets some of the board properties. Most of these properties can be set via JXG.Options.
293          * @param {Array} [attributes.boundingbox=[-5, 5, 5, -5]] An array containing four numbers describing the left, top, right and bottom boundary of the board in user coordinates
294          * @param {Boolean} [attributes.keepaspectratio=false] If <tt>true</tt>, the bounding box is adjusted to the same aspect ratio as the aspect ratio of the div containing the board.
295          * @param {Boolean} [attributes.showCopyright=false] Show the copyright string in the top left corner.
296          * @param {Boolean} [attributes.showNavigation=false] Show the navigation buttons in the bottom right corner.
297          * @param {Object} [attributes.zoom] Allow the user to zoom with the mouse wheel or the two-fingers-zoom gesture.
298          * @param {Object} [attributes.pan] Allow the user to pan with shift+drag mouse or two-fingers-pan gesture.
299          * @param {Object} [attributes.drag] Allow the user to drag objects with a pointer device.
300          * @param {Object} [attributes.keyboard] Allow the user to drag objects with arrow keys on keyboard.
301          * @param {Boolean} [attributes.axis=false] If set to true, show the axis. Can also be set to an object that is given to both axes as an attribute object.
302          * @param {Boolean|Object} [attributes.grid] If set to true, shows the grid. Can also be set to an object that is given to the grid as its attribute object.
303          * @param {Boolean} [attributes.registerEvents=true] Register mouse / touch events.
304          * @returns {JXG.Board} Reference to the created board.
305          */
306         initBoard: function (box, attributes) {
307             var originX, originY, unitX, unitY,
308                 renderer,
309                 offX = 0,
310                 offY = 0,
311                 w, h, dimensions,
312                 bbox, attr, axattr, axattr_x, axattr_y,
313                 board;
314 
315             attributes = attributes || {};
316             attr = this._setAttributes(attributes);
317 
318             dimensions = Env.getDimensions(box, attr.document);
319 
320             if (attr.unitx || attr.unity) {
321                 originX = Type.def(attr.originx, 150);
322                 originY = Type.def(attr.originy, 150);
323                 unitX = Type.def(attr.unitx, 50);
324                 unitY = Type.def(attr.unity, 50);
325             } else {
326                 bbox = attr.boundingbox;
327                 if (bbox[0] < attr.maxboundingbox[0]) { bbox[0] = attr.maxboundingbox[0]; }
328                 if (bbox[1] > attr.maxboundingbox[1]) { bbox[1] = attr.maxboundingbox[1]; }
329                 if (bbox[2] > attr.maxboundingbox[2]) { bbox[2] = attr.maxboundingbox[2]; }
330                 if (bbox[3] < attr.maxboundingbox[3]) { bbox[3] = attr.maxboundingbox[3]; }
331 
332                 w = parseInt(dimensions.width, 10);
333                 h = parseInt(dimensions.height, 10);
334 
335                 if (Type.exists(bbox) && attr.keepaspectratio) {
336                     /*
337                      * If the boundingbox attribute is given and the ratio of height and width of the
338                      * sides defined by the bounding box and the ratio of the dimensions of the div tag
339                      * which contains the board do not coincide, then the smaller side is chosen.
340                      */
341                     unitX = w / (bbox[2] - bbox[0]);
342                     unitY = h / (bbox[1] - bbox[3]);
343 
344                     if (Math.abs(unitX) < Math.abs(unitY)) {
345                         unitY = Math.abs(unitX) * unitY / Math.abs(unitY);
346                         // Add the additional units in equal portions above and below
347                         offY = (h / unitY - (bbox[1] - bbox[3])) * 0.5;
348                     } else {
349                         unitX = Math.abs(unitY) * unitX / Math.abs(unitX);
350                         // Add the additional units in equal portions left and right
351                         offX = (w / unitX - (bbox[2] - bbox[0])) * 0.5;
352                     }
353                 } else {
354                     unitX = w / (bbox[2] - bbox[0]);
355                     unitY = h / (bbox[1] - bbox[3]);
356                 }
357                 originX = -unitX * (bbox[0] - offX);
358                 originY = unitY * (bbox[1] + offY);
359             }
360 
361             renderer = this.initRenderer(box, dimensions, attr.document, attr.renderer);
362             this._setARIA(box, attr);
363 
364             // create the board
365             board = new Board(box, renderer, attr.id, [originX, originY],
366                         attr.zoomfactor * attr.zoomx,
367                         attr.zoomfactor * attr.zoomy,
368                         unitX, unitY,
369                         dimensions.width, dimensions.height,
370                         attr);
371 
372             board.keepaspectratio = attr.keepaspectratio;
373 
374             this._fillBoard(board, attr, dimensions);
375 
376             // create elements like axes, grid, navigation, ...
377             board.suspendUpdate();
378             if (attr.axis) {
379                 axattr = typeof attr.axis === 'object' ? attr.axis : {};
380 
381                 // The defaultAxes attributes are overwritten by user supplied axis object.
382                 axattr_x = Type.deepCopy(Options.board.defaultAxes.x, axattr);
383                 axattr_y = Type.deepCopy(Options.board.defaultAxes.y, axattr);
384                 // The user supplied defaultAxes attributes are merged in.
385                 if (attr.defaultaxes.x) {
386                     axattr_x = Type.deepCopy(axattr_x, attr.defaultaxes.x);
387                 }
388                 if (attr.defaultaxes.y) {
389                     axattr_y = Type.deepCopy(axattr_y, attr.defaultaxes.y);
390                 }
391 
392                 board.defaultAxes = {};
393                 board.defaultAxes.x = board.create('axis', [[0, 0], [1, 0]], axattr_x);
394                 board.defaultAxes.y = board.create('axis', [[0, 0], [0, 1]], axattr_y);
395             }
396             if (attr.grid) {
397                 board.create('grid', [], (typeof attr.grid === 'object' ? attr.grid : {}));
398             }
399             board.unsuspendUpdate();
400 
401             return board;
402         },
403 
404         /**
405          * Load a board from a file containing a construction made with either GEONExT,
406          * Intergeo, Geogebra, or Cinderella.
407          * @param {String} box HTML-ID to the HTML-element in which the board is painted.
408          * @param {String} file base64 encoded string.
409          * @param {String} format containing the file format: 'Geonext' or 'Intergeo'.
410          * @param {Object} attributes Attributes for the board and 'encoding'.
411          *  Compressed files need encoding 'iso-8859-1'. Otherwise it probably is 'utf-8'.
412          * @param {Function} callback
413          * @returns {JXG.Board} Reference to the created board.
414          * @see JXG.FileReader
415          * @see JXG.GeonextReader
416          * @see JXG.GeogebraReader
417          * @see JXG.IntergeoReader
418          * @see JXG.CinderellaReader
419          *
420          * @example
421          * // Uncompressed file
422          * var board = JXG.JSXGraph.loadBoardFromFile('jxgbox', 'filename', 'geonext',
423          *      {encoding: 'utf-8'},
424          *      function (board) { console.log("Done loading"); }
425          * );
426          * // Compressed file
427          * var board = JXG.JSXGraph.loadBoardFromFile('jxgbox', 'filename', 'geonext',
428          *      {encoding: 'iso-8859-1'},
429          *      function (board) { console.log("Done loading"); }
430          * );
431          *
432          * @example
433          * // From <input type="file" id="localfile" />
434          * var file = document.getElementById('localfile').files[0];
435          * JXG.JSXGraph.loadBoardFromFile('jxgbox', file, 'geonext',
436          *      {encoding: 'utf-8'},
437          *      function (board) { console.log("Done loading"); }
438          * );
439          */
440         loadBoardFromFile: function (box, file, format, attributes, callback) {
441             var attr, renderer, board, dimensions, encoding;
442 
443             attributes = attributes || {};
444             attr = this._setAttributes(attributes);
445 
446             dimensions = Env.getDimensions(box, attr.document);
447             renderer = this.initRenderer(box, dimensions, attr.document, attr.renderer);
448             this._setARIA(box, attr);
449 
450             /* User default parameters, in parse* the values in the gxt files are submitted to board */
451             board = new Board(box, renderer, '', [150, 150], 1, 1, 50, 50, dimensions.width, dimensions.height, attr);
452             this._fillBoard(board, attr, dimensions);
453             encoding = attr.encoding || 'iso-8859-1';
454             FileReader.parseFileContent(file, board, format, true, encoding, callback);
455 
456             return board;
457         },
458 
459         /**
460          * Load a board from a base64 encoded string containing a construction made with either GEONExT,
461          * Intergeo, Geogebra, or Cinderella.
462          * @param {String} box HTML-ID to the HTML-element in which the board is painted.
463          * @param {String} string base64 encoded string.
464          * @param {String} format containing the file format: 'Geonext', 'Intergeo', 'Geogebra'.
465          * @param {Object} attributes Attributes for the board and 'encoding'.
466          *  Compressed files need encoding 'iso-8859-1'. Otherwise it probably is 'utf-8'.
467          * @param {Function} callback
468          * @returns {JXG.Board} Reference to the created board.
469          * @see JXG.FileReader
470          * @see JXG.GeonextReader
471          * @see JXG.GeogebraReader
472          * @see JXG.IntergeoReader
473          * @see JXG.CinderellaReader
474          */
475         loadBoardFromString: function (box, string, format, attributes, callback) {
476             var attr, renderer, board, dimensions;
477 
478             attributes = attributes || {};
479             attr = this._setAttributes(attributes);
480 
481             dimensions = Env.getDimensions(box, attr.document);
482             renderer = this.initRenderer(box, dimensions, attr.document);
483             this._setARIA(box, attr);
484 
485             /* User default parameters, in parse* the values in the gxt files are submitted to board */
486             board = new Board(box, renderer, '', [150, 150], 1.0, 1.0, 50, 50, dimensions.width, dimensions.height, attr);
487             this._fillBoard(board, attr, dimensions);
488             FileReader.parseString(string, board, format, true, callback);
489 
490             return board;
491         },
492 
493         /**
494          * Delete a board and all its contents.
495          * @param {JXG.Board,String} board HTML-ID to the DOM-element in which the board is drawn.
496          */
497         freeBoard: function (board) {
498             var el;
499 
500             if (typeof board === 'string') {
501                 board = JXG.boards[board];
502             }
503 
504             this._removeARIANodes(board);
505             board.removeEventHandlers();
506             board.suspendUpdate();
507 
508             // Remove all objects from the board.
509             for (el in board.objects) {
510                 if (board.objects.hasOwnProperty(el)) {
511                     board.objects[el].remove();
512                 }
513             }
514 
515             // Remove all the other things, left on the board, XHTML save
516             while (board.containerObj.firstChild) {
517                 board.containerObj.removeChild(board.containerObj.firstChild);
518             }
519 
520             // Tell the browser the objects aren't needed anymore
521             for (el in board.objects) {
522                 if (board.objects.hasOwnProperty(el)) {
523                     delete board.objects[el];
524                 }
525             }
526 
527             // Free the renderer and the algebra object
528             delete board.renderer;
529 
530             // clear the creator cache
531             board.jc.creator.clearCache();
532             delete board.jc;
533 
534             // Finally remove the board itself from the boards array
535             delete JXG.boards[board.id];
536         },
537 
538         /**
539          * @deprecated Use JXG#registerElement
540          * @param element
541          * @param creator
542          */
543         registerElement: function (element, creator) {
544             JXG.deprecated('JXG.JSXGraph.registerElement()', 'JXG.registerElement()');
545             JXG.registerElement(element, creator);
546         }
547     };
548 
549     // JessieScript/JessieCode startup: 
550     // Search for script tags of type text/jessiescript and interprete them.
551     if (Env.isBrowser && typeof window === 'object' && typeof document === 'object') {
552         Env.addEvent(window, 'load', function () {
553             var type, i, j, div,
554                 id, board, txt,
555                 width, height, maxWidth, aspectRatio, cssClasses,
556                 bbox, axis, grid, code,
557                 src, request, postpone = false,
558                 scripts = document.getElementsByTagName('script'),
559                 init = function (code, type, bbox) {
560                     var board = JXG.JSXGraph.initBoard(id, {boundingbox: bbox, keepaspectratio: true, grid: grid, axis: axis, showReload: true});
561 
562                     if (type.toLowerCase().indexOf('script') > -1) {
563                         board.construct(code);
564                     } else {
565                         try {
566                             board.jc.parse(code);
567                         } catch (e2) {
568                             JXG.debug(e2);
569                         }
570                     }
571 
572                     return board;
573                 },
574                 makeReload = function (board, code, type, bbox) {
575                     return function () {
576                         var newBoard;
577 
578                         JXG.JSXGraph.freeBoard(board);
579                         newBoard = init(code, type, bbox);
580                         newBoard.reload = makeReload(newBoard, code, type, bbox);
581                     };
582                 };
583 
584             for (i = 0; i < scripts.length; i++) {
585                 type = scripts[i].getAttribute('type', false);
586 
587                 if (Type.exists(type) &&
588                     (type.toLowerCase() === 'text/jessiescript' || type.toLowerCase() === 'jessiescript' ||
589                      type.toLowerCase() === 'text/jessiecode' || type.toLowerCase() === 'jessiecode')) {
590                     cssClasses = scripts[i].getAttribute('class', false) || '';
591                     width = scripts[i].getAttribute('width', false) || '';
592                     height = scripts[i].getAttribute('height', false) || '';
593                     maxWidth = scripts[i].getAttribute('maxwidth', false) || '100%';
594                     aspectRatio = scripts[i].getAttribute('aspectratio', false) || '1/1';
595                     bbox = scripts[i].getAttribute('boundingbox', false) || '-5, 5, 5, -5';
596                     id = scripts[i].getAttribute('container', false);
597                     src = scripts[i].getAttribute('src', false);
598 
599                     bbox = bbox.split(',');
600                     if (bbox.length !== 4) {
601                         bbox = [-5, 5, 5, -5];
602                     } else {
603                         for (j = 0; j < bbox.length; j++) {
604                             bbox[j] = parseFloat(bbox[j]);
605                         }
606                     }
607                     axis = Type.str2Bool(scripts[i].getAttribute('axis', false) || 'false');
608                     grid = Type.str2Bool(scripts[i].getAttribute('grid', false) || 'false');
609 
610                     if (!Type.exists(id)) {
611                         id = 'jessiescript_autgen_jxg_' + i;
612                         div = document.createElement('div');
613                         div.setAttribute('id', id);
614 
615                         txt = (width !== '') ? ('width:' + width + ';') : '';
616                         txt += (height !== '') ? ('height:' + height + ';') : '';
617                         txt += (maxWidth !== '') ? ('max-width:' + maxWidth + ';') : '';
618                         txt += (aspectRatio !== '') ? ('aspect-ratio:' + aspectRatio + ';') : '';
619 
620                         div.setAttribute('style', txt);
621                         div.setAttribute('class', 'jxgbox ' + cssClasses);
622                         try {
623                             document.body.insertBefore(div, scripts[i]);
624                         } catch (e) {
625                             // there's probably jquery involved...
626                             if (typeof jQuery === 'object') {
627                                 jQuery(div).insertBefore(scripts[i]);
628                             }
629                         }
630                     } else {
631                         div = document.getElementById(id);
632                     }
633 
634                     code = '';
635 
636                     if (Type.exists(src)) {
637                         postpone = true;
638                         request = new XMLHttpRequest();
639                         request.open("GET", src);
640                         request.overrideMimeType("text/plain; charset=x-user-defined");
641                         /* jshint ignore:start */
642                         request.addEventListener("load", function() {
643                             if (this.status < 400) {
644                                 code = this.responseText + '\n' + code;
645                                 board = init(code, type, bbox);
646                                 board.reload = makeReload(board, code, type, bbox);
647                             } else {
648                                 throw new Error("\nJSXGraph: failed to load file", src, ":", this.responseText);
649                             }
650                         });
651                         request.addEventListener("error", function(e) {
652                             throw new Error("\nJSXGraph: failed to load file", src, ":", e);
653                         });
654                         /* jshint ignore:end */
655                         request.send();
656                     } else {
657                         postpone = false;
658                     }
659 
660                     if (document.getElementById(id)) {
661                         code = scripts[i].innerHTML;
662                         code = code.replace(/<!\[CDATA\[/g, '').replace(/\]\]>/g, '');
663                         scripts[i].innerHTML = code;
664 
665                         if (!postpone) {
666                             // Do no wait for data from "src" attribute
667                             board = init(code, type, bbox);
668                             board.reload = makeReload(board, code, type, bbox);
669                         }
670                     } else {
671                         JXG.debug('JSXGraph: Apparently the div injection failed. Can\'t create a board, sorry.');
672                     }
673                 }
674             }
675         }, window);
676     }
677 
678     return JXG.JSXGraph;
679 });
680