1 /*
  2     Copyright 2008-2021
  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                 node_jsx, newNode, parent,
232                 id_label, id_description;
233 
234             if (typeof doc !== 'object') {
235                 return;
236             }
237 
238             node_jsx = doc.getElementById(container);
239             parent = node_jsx.parentNode;
240 
241             id_label = container + '_ARIAlabel';
242             id_description = container + '_ARIAdescription';
243 
244             newNode = doc.createElement('div');
245             newNode.innerHTML = attr.title;
246             newNode.setAttribute('id', id_label);
247             newNode.style.display = 'none';
248             parent.insertBefore(newNode, node_jsx);
249 
250             newNode = doc.createElement('div');
251             newNode.innerHTML = attr.description;
252             newNode.setAttribute('id', id_description);
253             newNode.style.display = 'none';
254             parent.insertBefore(newNode, node_jsx);
255 
256             node_jsx.setAttribute('aria-labelledby', id_label);
257             node_jsx.setAttribute('aria-describedby', id_description);
258         },
259 
260         /**
261          * Remove the two corresponding ARIA divs when freeing a board
262          *
263          * @param {JXG.Board} board
264          *
265          * @private
266          */
267         _removeARIANodes: function(board) {
268             var node, id, doc;
269 
270             doc = board.document || document;
271             if (typeof doc !== 'object') {
272                 return;
273             }
274 
275             id = board.containerObj.getAttribute('aria-labelledby');
276             node = document.getElementById(id);
277             if (node && node.parentNode) {
278                 node.parentNode.removeChild(node);
279             }
280             id = board.containerObj.getAttribute('aria-describedby');
281             node = document.getElementById(id);
282             if (node && node.parentNode) {
283                 node.parentNode.removeChild(node);
284             }
285         },
286 
287         /**
288          * Initialise a new board.
289          * @param {String} box HTML-ID to the HTML-element in which the board is painted.
290          * @param {Object} attributes An object that sets some of the board properties. Most of these properties can be set via JXG.Options.
291          * @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
292          * @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.
293          * @param {Boolean} [attributes.showCopyright=false] Show the copyright string in the top left corner.
294          * @param {Boolean} [attributes.showNavigation=false] Show the navigation buttons in the bottom right corner.
295          * @param {Object} [attributes.zoom] Allow the user to zoom with the mouse wheel or the two-fingers-zoom gesture.
296          * @param {Object} [attributes.pan] Allow the user to pan with shift+drag mouse or two-fingers-pan gesture.
297          * @param {Object} [attributes.drag] Allow the user to drag objects with a pointer device.
298          * @param {Object} [attributes.keyboard] Allow the user to drag objects with arrow keys on keyboard.
299          * @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.
300          * @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.
301          * @param {Boolean} [attributes.registerEvents=true] Register mouse / touch events.
302          * @returns {JXG.Board} Reference to the created board.
303          */
304         initBoard: function (box, attributes) {
305             var originX, originY, unitX, unitY,
306                 renderer,
307                 w, h, dimensions,
308                 bbox, attr, axattr, axattr_x, axattr_y,
309                 board;
310 
311             attributes = attributes || {};
312             attr = this._setAttributes(attributes);
313 
314             dimensions = Env.getDimensions(box, attr.document);
315 
316             if (attr.unitx || attr.unity) {
317                 originX = Type.def(attr.originx, 150);
318                 originY = Type.def(attr.originy, 150);
319                 unitX = Type.def(attr.unitx, 50);
320                 unitY = Type.def(attr.unity, 50);
321             } else {
322                 bbox = attr.boundingbox;
323                 if (bbox[0] < attr.maxboundingbox[0]) { bbox[0] = attr.maxboundingbox[0]; }
324                 if (bbox[1] > attr.maxboundingbox[1]) { bbox[1] = attr.maxboundingbox[1]; }
325                 if (bbox[2] > attr.maxboundingbox[2]) { bbox[2] = attr.maxboundingbox[2]; }
326                 if (bbox[3] < attr.maxboundingbox[3]) { bbox[3] = attr.maxboundingbox[3]; }
327 
328                 w = parseInt(dimensions.width, 10);
329                 h = parseInt(dimensions.height, 10);
330 
331                 if (Type.exists(bbox) && attr.keepaspectratio) {
332                     /*
333                      * If the boundingbox attribute is given and the ratio of height and width of the
334                      * sides defined by the bounding box and the ratio of the dimensions of the div tag
335                      * which contains the board do not coincide, then the smaller side is chosen.
336                      */
337                     unitX = w / (bbox[2] - bbox[0]);
338                     unitY = h / (bbox[1] - bbox[3]);
339 
340                     if (Math.abs(unitX) < Math.abs(unitY)) {
341                         unitY = Math.abs(unitX) * unitY / Math.abs(unitY);
342                     } else {
343                         unitX = Math.abs(unitY) * unitX / Math.abs(unitX);
344                     }
345                 } else {
346                     unitX = w / (bbox[2] - bbox[0]);
347                     unitY = h / (bbox[1] - bbox[3]);
348                 }
349                 originX = -unitX * bbox[0];
350                 originY = unitY * bbox[1];
351             }
352 
353             renderer = this.initRenderer(box, dimensions, attr.document, attr.renderer);
354             this._setARIA(box, attr);
355 
356             // create the board
357             board = new Board(box, renderer, attr.id, [originX, originY],
358                         attr.zoomfactor * attr.zoomx,
359                         attr.zoomfactor * attr.zoomy,
360                         unitX, unitY,
361                         dimensions.width, dimensions.height,
362                         attr);
363 
364             board.keepaspectratio = attr.keepaspectratio;
365 
366             this._fillBoard(board, attr, dimensions);
367 
368             // create elements like axes, grid, navigation, ...
369             board.suspendUpdate();
370             if (attr.axis) {
371                 axattr = typeof attr.axis === 'object' ? attr.axis : {};
372 
373                 // The defaultAxes attributes are overwritten by user supplied axis object.
374                 axattr_x = Type.deepCopy(Options.board.defaultAxes.x, axattr);
375                 axattr_y = Type.deepCopy(Options.board.defaultAxes.y, axattr);
376                 // The user supplied defaultAxes attributes are merged in.
377                 if (attr.defaultaxes.x) {
378                     axattr_x = Type.deepCopy(axattr_x, attr.defaultaxes.x);
379                 }
380                 if (attr.defaultaxes.y) {
381                     axattr_y = Type.deepCopy(axattr_y, attr.defaultaxes.y);
382                 }
383 
384                 board.defaultAxes = {};
385                 board.defaultAxes.x = board.create('axis', [[0, 0], [1, 0]], axattr_x);
386                 board.defaultAxes.y = board.create('axis', [[0, 0], [0, 1]], axattr_y);
387             }
388             if (attr.grid) {
389                 board.create('grid', [], (typeof attr.grid === 'object' ? attr.grid : {}));
390             }
391             board.unsuspendUpdate();
392 
393             return board;
394         },
395 
396         /**
397          * Load a board from a file containing a construction made with either GEONExT,
398          * Intergeo, Geogebra, or Cinderella.
399          * @param {String} box HTML-ID to the HTML-element in which the board is painted.
400          * @param {String} file base64 encoded string.
401          * @param {String} format containing the file format: 'Geonext' or 'Intergeo'.
402          * @param {Object} attributes Attributes for the board and 'encoding'.
403          *  Compressed files need encoding 'iso-8859-1'. Otherwise it probably is 'utf-8'.
404          * @param {Function} callback
405          * @returns {JXG.Board} Reference to the created board.
406          * @see JXG.FileReader
407          * @see JXG.GeonextReader
408          * @see JXG.GeogebraReader
409          * @see JXG.IntergeoReader
410          * @see JXG.CinderellaReader
411          *
412          * @example
413          * // Uncompressed file
414          * var board = JXG.JSXGraph.loadBoardFromFile('jxgbox', 'filename', 'geonext',
415          *      {encoding: 'utf-8'},
416          *      function (board) { console.log("Done loading"); }
417          * );
418          * // Compressed file
419          * var board = JXG.JSXGraph.loadBoardFromFile('jxgbox', 'filename', 'geonext',
420          *      {encoding: 'iso-8859-1'},
421          *      function (board) { console.log("Done loading"); }
422          * );
423          *
424          * @example
425          * // From <input type="file" id="localfile" />
426          * var file = document.getElementById('localfile').files[0];
427          * JXG.JSXGraph.loadBoardFromFile('jxgbox', file, 'geonext',
428          *      {encoding: 'utf-8'},
429          *      function (board) { console.log("Done loading"); }
430          * );
431          */
432         loadBoardFromFile: function (box, file, format, attributes, callback) {
433             var attr, renderer, board, dimensions, encoding;
434 
435             attributes = attributes || {};
436             attr = this._setAttributes(attributes);
437 
438             dimensions = Env.getDimensions(box, attr.document);
439             renderer = this.initRenderer(box, dimensions, attr.document, attr.renderer);
440             this._setARIA(box, attr);
441 
442             /* User default parameters, in parse* the values in the gxt files are submitted to board */
443             board = new Board(box, renderer, '', [150, 150], 1, 1, 50, 50, dimensions.width, dimensions.height, attr);
444             this._fillBoard(board, attr, dimensions);
445             encoding = attr.encoding || 'iso-8859-1';
446             FileReader.parseFileContent(file, board, format, true, encoding, callback);
447 
448             return board;
449         },
450 
451         /**
452          * Load a board from a base64 encoded string containing a construction made with either GEONExT,
453          * Intergeo, Geogebra, or Cinderella.
454          * @param {String} box HTML-ID to the HTML-element in which the board is painted.
455          * @param {String} string base64 encoded string.
456          * @param {String} format containing the file format: 'Geonext', 'Intergeo', 'Geogebra'.
457          * @param {Object} attributes Attributes for the board and 'encoding'.
458          *  Compressed files need encoding 'iso-8859-1'. Otherwise it probably is 'utf-8'.
459          * @param {Function} callback
460          * @returns {JXG.Board} Reference to the created board.
461          * @see JXG.FileReader
462          * @see JXG.GeonextReader
463          * @see JXG.GeogebraReader
464          * @see JXG.IntergeoReader
465          * @see JXG.CinderellaReader
466          */
467         loadBoardFromString: function (box, string, format, attributes, callback) {
468             var attr, renderer, board, dimensions;
469 
470             attributes = attributes || {};
471             attr = this._setAttributes(attributes);
472 
473             dimensions = Env.getDimensions(box, attr.document);
474             renderer = this.initRenderer(box, dimensions, attr.document);
475             this._setARIA(box, attr);
476 
477             /* User default parameters, in parse* the values in the gxt files are submitted to board */
478             board = new Board(box, renderer, '', [150, 150], 1.0, 1.0, 50, 50, dimensions.width, dimensions.height, attr);
479             this._fillBoard(board, attr, dimensions);
480             FileReader.parseString(string, board, format, true, callback);
481 
482             return board;
483         },
484 
485         /**
486          * Delete a board and all its contents.
487          * @param {JXG.Board,String} board HTML-ID to the DOM-element in which the board is drawn.
488          */
489         freeBoard: function (board) {
490             var el;
491 
492             if (typeof board === 'string') {
493                 board = JXG.boards[board];
494             }
495 
496             this._removeARIANodes(board);
497             board.removeEventHandlers();
498             board.suspendUpdate();
499 
500             // Remove all objects from the board.
501             for (el in board.objects) {
502                 if (board.objects.hasOwnProperty(el)) {
503                     board.objects[el].remove();
504                 }
505             }
506 
507             // Remove all the other things, left on the board, XHTML save
508             while (board.containerObj.firstChild) {
509                 board.containerObj.removeChild(board.containerObj.firstChild);
510             }
511 
512             // Tell the browser the objects aren't needed anymore
513             for (el in board.objects) {
514                 if (board.objects.hasOwnProperty(el)) {
515                     delete board.objects[el];
516                 }
517             }
518 
519             // Free the renderer and the algebra object
520             delete board.renderer;
521 
522             // clear the creator cache
523             board.jc.creator.clearCache();
524             delete board.jc;
525 
526             // Finally remove the board itself from the boards array
527             delete JXG.boards[board.id];
528         },
529 
530         /**
531          * @deprecated Use JXG#registerElement
532          * @param element
533          * @param creator
534          */
535         registerElement: function (element, creator) {
536             JXG.deprecated('JXG.JSXGraph.registerElement()', 'JXG.registerElement()');
537             JXG.registerElement(element, creator);
538         }
539     };
540 
541     // JessieScript/JessieCode startup: Search for script tags of type text/jessiescript and interprete them.
542     if (Env.isBrowser && typeof window === 'object' && typeof document === 'object') {
543         Env.addEvent(window, 'load', function () {
544             var type, i, j, div,
545                 id, board, txt,
546                 width, height, maxWidth, aspectRatio, cssClasses,
547                 bbox, axis, grid, code,
548                 src, request, postpone = false,
549                 scripts = document.getElementsByTagName('script'),
550                 init = function (code, type, bbox) {
551                     var board = JXG.JSXGraph.initBoard(id, {boundingbox: bbox, keepaspectratio: true, grid: grid, axis: axis, showReload: true});
552 
553                     if (type.toLowerCase().indexOf('script') > -1) {
554                         board.construct(code);
555                     } else {
556                         try {
557                             board.jc.parse(code);
558                         } catch (e2) {
559                             JXG.debug(e2);
560                         }
561                     }
562 
563                     return board;
564                 },
565                 makeReload = function (board, code, type, bbox) {
566                     return function () {
567                         var newBoard;
568 
569                         JXG.JSXGraph.freeBoard(board);
570                         newBoard = init(code, type, bbox);
571                         newBoard.reload = makeReload(newBoard, code, type, bbox);
572                     };
573                 };
574 
575             for (i = 0; i < scripts.length; i++) {
576                 type = scripts[i].getAttribute('type', false);
577 
578                 if (Type.exists(type) &&
579                     (type.toLowerCase() === 'text/jessiescript' || type.toLowerCase() === 'jessiescript' ||
580                      type.toLowerCase() === 'text/jessiecode' || type.toLowerCase() === 'jessiecode')) {
581                     cssClasses = scripts[i].getAttribute('class', false) || '';
582                     width = scripts[i].getAttribute('width', false) || '';
583                     height = scripts[i].getAttribute('height', false) || '';
584                     maxWidth = scripts[i].getAttribute('maxwidth', false) || '100%';
585                     aspectRatio = scripts[i].getAttribute('aspectratio', false) || '1/1';
586                     bbox = scripts[i].getAttribute('boundingbox', false) || '-5, 5, 5, -5';
587                     id = scripts[i].getAttribute('container', false);
588                     src = scripts[i].getAttribute('src', false);
589 
590                     bbox = bbox.split(',');
591                     if (bbox.length !== 4) {
592                         bbox = [-5, 5, 5, -5];
593                     } else {
594                         for (j = 0; j < bbox.length; j++) {
595                             bbox[j] = parseFloat(bbox[j]);
596                         }
597                     }
598                     axis = Type.str2Bool(scripts[i].getAttribute('axis', false) || 'false');
599                     grid = Type.str2Bool(scripts[i].getAttribute('grid', false) || 'false');
600 
601                     if (!Type.exists(id)) {
602                         id = 'jessiescript_autgen_jxg_' + i;
603                         div = document.createElement('div');
604                         div.setAttribute('id', id);
605 
606                         txt = (width !== '') ? ('width:' + width + ';') : '';
607                         txt += (height !== '') ? ('height:' + height + ';') : '';
608                         txt += (maxWidth !== '') ? ('max-width:' + maxWidth + ';') : '';
609                         txt += (aspectRatio !== '') ? ('aspect-ratio:' + aspectRatio + ';') : '';
610 
611                         div.setAttribute('style', txt);
612                         div.setAttribute('class', 'jxgbox ' + cssClasses);
613                         try {
614                             document.body.insertBefore(div, scripts[i]);
615                         } catch (e) {
616                             // there's probably jquery involved...
617                             if (typeof jQuery === 'object') {
618                                 jQuery(div).insertBefore(scripts[i]);
619                             }
620                         }
621                     } else {
622                         div = document.getElementById(id);
623                     }
624 
625                     code = '';
626 
627                     if (Type.exists(src)) {
628                         postpone = true;
629                         request = new XMLHttpRequest();
630                         request.open("GET", src);
631                         request.overrideMimeType("text/plain; charset=x-user-defined");
632                         /* jshint ignore:start */
633                         request.addEventListener("load", function() {
634                             if (this.status < 400) {
635                                 code = this.responseText + '\n' + code;
636                                 board = init(code, type, bbox);
637                                 board.reload = makeReload(board, code, type, bbox);
638                             } else {
639                                 throw new Error("\nJSXGraph: failed to load file", src, ":", this.responseText);
640                             }
641                         });
642                         request.addEventListener("error", function(e) {
643                             throw new Error("\nJSXGraph: failed to load file", src, ":", e);
644                         });
645                         /* jshint ignore:end */
646                         request.send();
647                     } else {
648                         postpone = false;
649                     }
650 
651                     if (document.getElementById(id)) {
652                         code = scripts[i].innerHTML;
653                         code = code.replace(/<!\[CDATA\[/g, '').replace(/\]\]>/g, '');
654                         scripts[i].innerHTML = code;
655 
656                         if (!postpone) {
657                             // Do no wait for data from "src" attribute
658                             board = init(code, type, bbox);
659                             board.reload = makeReload(board, code, type, bbox);
660                         }
661                     } else {
662                         JXG.debug('JSXGraph: Apparently the div injection failed. Can\'t create a board, sorry.');
663                     }
664                 }
665             }
666         }, window);
667     }
668 
669     return JXG.JSXGraph;
670 });
671