-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
2217 lines (1979 loc) · 683 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops">
<head>
<meta charset="utf-8" />
<title>Photosynthesis Lab</title>
<link rel="stylesheet" type="text/css" href="ejss.css" />
<script src="common_script.js"></script>
<script src="textresizedetector.js"></script>
<script type="text/javascript"><!--//--><![CDATA[//><!--
var EJSS_HARDWARE = EJSS_HARDWARE || {};
EJSS_HARDWARE.orientationTools = function () {
var self = {};
var mIOSkind = (getMobileOperatingSystem()!=="Android");
var mOrientation = 0;
self.getOrientation = function() { return mOrientation; }
function readOrientation() {
var orientation;
if (mIOSkind) { // Android does it otherwise
if (window.orientation=="90") orientation = 90;
else if (window.orientation=="0") orientation = 0;
else if (window.orientation=="-90") orientation = -90;
else orientation = 180;
}
else { // iOS behaviour
if (window.orientation=="90") orientation = -90;
else if (window.orientation=="0") orientation = 180;
else if (window.orientation=="-90") orientation = 90;
else orientation = 0;
}
return orientation;
}
function getMobileOperatingSystem() {
var userAgent = navigator.userAgent || navigator.vendor || window.opera;
if( userAgent.match( /iPad/i ) || userAgent.match( /iPhone/i ) ||
userAgent.match( /iPod/i ) ) return 'iOS';
if( userAgent.match( /Android/i ) ) return 'Android';
return 'unknown';
};
window.addEventListener("orientationchange", function() {
mOrientation = readOrientation();
}, false);
mOrientation = readOrientation();
//alert ("is IOSKind = "+mIOSkind+"\n orientation = "+mOrientation);
return self;
};
EJSS_HARDWARE.accelerometer = function () {
var self = {};
var mListeners = [];
var mOrientationTools = EJSS_HARDWARE.orientationTools();
var mAverageTime = 0;
var mIsRunning = false;
var mData = { x : 0, y:0, z:0, interval:0 , alpha: 0, beta: 0, gamma: 0};
var mHistory = []; // Stores data taken, most recent data goes to [0]
function copyData(acceleration,rotation,data) {
data.x = acceleration.x;
data.y = acceleration.y;
data.z = acceleration.z;
data.alpha = rotation.alpha;
data.beta = rotation.beta;
data.gamma = rotation.gamma;
data.millisAgo = 0;
return data;
};
function deviceMotionHandler(eventData) {
// Grab the acceleration from the results
//var acceleration = eventData.acceleration;
var acceleration = eventData.accelerationIncludingGravity;
var rotation = eventData.rotationRate;
var interval = eventData.interval;
if (mAverageTime>0) {
for (var j=0, numData=mHistory.length; j<numData; j++) {
var data = mHistory[j];
data.millisAgo += interval;
if (data.millisAgo>mAverageTime) {
mHistory.length = j;
break;
}
}
mHistory.unshift(copyData(acceleration,rotation,{}));
}
copyData(acceleration,rotation,mData);
for (var i=0, n=mListeners.length; i<n; i++) {
mListeners[i](mData);
}
};
self.isPresent = function() { return (typeof window.DeviceMotionEvent != "undefined"); };
self.start = function() {
if (self.isPresent()) {
window.addEventListener('devicemotion', deviceMotionHandler, false);
mIsRunning = true;
}
};
self.stop = function() {
if (self.isPresent()) window.removeEventListener('devicemotion', deviceMotionHandler);
mHistory = [];
mData = { x : 0, y:0, z:0, interval:0 , alpha: 0, beta: 0, gamma: 0};
mIsRunning = false;
};
self.isRunning = function() { return mIsRunning; };
self.setAverageInterval = function (seconds) {
mAverageTime = seconds;
if (mAverageTime<=0) mHistory = [];
};
function averageData() {
var data = { x : 0, y:0, z:0, interval:0 , alpha: 0, beta: 0, gamma: 0};
data.alpha = mData.alpha;
data.beta = mData.beta;
data.gamma = mData.gamma;
var n = mHistory.length;
for (var i=0; i<n; i++) {
var historicalData = mHistory[i];
data.x += historicalData.x;
data.y += historicalData.y;
data.z += historicalData.z;
}
data.x /= n;
data.y /= n;
data.z /= n;
return data;
};
self.getDeviceData = function() { return (mAverageTime>0) ? averageData() : mData; };
self.getViewData = function () {
var data = (mAverageTime>0) ? averageData() : mData;
switch (mOrientationTools.getOrientation()) {
case 0 : return { x: data.x, y: data.y, z: data.z, alpha: data.alpha, beta: data.beta, gamma: data.gamma }; break;
case 90 : return { x:-data.y, y: data.x, z: data.z, alpha: data.alpha, beta: data.beta, gamma: data.gamma }; break;
case -90 : return { x: data.y, y:-data.x, z: data.z, alpha: data.alpha, beta: data.beta, gamma: data.gamma }; break;
default : return { x:-data.x, y:-data.y, z: data.z, alpha: data.alpha, beta: data.beta, gamma: data.gamma }; break;
}
};
self.addListener = function(listener) { mListeners.push(listener); };
self.removeListener = function(listener) {
var index = mListeners.indexOf(listener);
if (index>-1) mListeners = mListeners.splice(index,1);
};
return self;
};
EJSS_HARDWARE.SensorTag = {
ACCELEROMETER : 0,
GYROSCOPE : 1,
AMBIENT_TEMPERATURE : 2,
INFRARED_TEMPERATURE : 3,
HUMIDITY : 4,
BAROMETER : 5,
MAGNETOMETER : 6
};
EJSS_HARDWARE.sensorTag = function () {
var SensorTag = EJSS_HARDWARE.SensorTag;
var self = {};
self.isSupported = function() {
return window.sensors && window.sensors.isSupportedSensorTag();
};
self.start = function(accelerometerPeriod, magnetometerPeriod) {
if (typeof accelerometerPeriod === "undefined") accelerometerPeriod = 20;
if (typeof magnetometerPeriod === "undefined") magnetometerPeriod = 20;
window.sensors.runSensorTag(""+accelerometerPeriod,""+magnetometerPeriod);
};
self.stop = function() {
window.sensors.stopSensorTag();
};
self.readData = function(sensor) {
if (typeof sensor === "undefined") sensor = SensorTag.ACCELEROMETER;
switch (sensor) {
default :
case SensorTag.ACCELEROMETER : return window.sensors.getSensorTagAccelerometer(); break;
case SensorTag.GYROSCOPE : return window.sensors.getSensorTagGyroscope(); break;
case SensorTag.AMBIENT_TEMPERATURE : return window.sensors.getSensorTagTempAmb(); break;
case SensorTag.INFRARED_TEMPERATURE : return window.sensors.getSensorTagTempIR(); break;
case SensorTag.HUMIDITY : return window.sensors.getSensorTagHumidity();break;
case SensorTag.BAROMETER : return window.sensors.getSensorTagPressure();break;
case SensorTag.MAGNETOMETER : return window.sensors.getSensorTagMagnetometer();break;
}
};
return self;
};
EJSS_HARDWARE.linearAccelerometer = function () {
var self = {};
self.isPresent = function() {
return window.sensors && window.sensors.isLinearAcceleration();
};
self.start = function() {
if (self.isPresent()) window.sensors.runLinearAcceleration();
};
self.stop = function() {
if (self.isPresent()) window.sensors.stopLinearAcceleration();
};
self.readData = function() {
if (self.isPresent()) return eval(window.sensors.getLinearAcceleration());
else return {x:0, y:0, z:0};
};
return self;
};
EJSS_HARDWARE.gyroscope = function () {
var self = {};
self.isPresent = function() {
return window.sensors && window.sensors.isGyroscope();
};
self.start = function() {
if (self.isPresent()) window.sensors.runGyroscope();
};
self.stop = function() {
if (self.isPresent()) window.sensors.stopGyroscope();
};
self.readData = function() {
if (self.isPresent()) return eval(window.sensors.getGyroscope());
else return {x:0, y:0, z:0};
};
return self;
};
//--><!]]></script>
<script type="text/javascript"><!--//--><![CDATA[//><!--
var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.AnalyticCurve={copyTo:function(source,dest){EJSS_DRAWING2D.Element.copyTo(source,dest);dest.setNumPoints(source.getNumPoints());dest.setMinimun(source.getMinimun());dest.setMaximun(source.getMaximun());dest.setVariable(source.getVariable());dest.setFunctionX(source.getFunctionX());dest.setFunctionY(source.getFunctionY())},registerProperties:function(element,controller){EJSS_DRAWING2D.Element.registerProperties(element,controller);controller.registerProperty("NumPoints",element.setNumPoints,element.getNumPoints);controller.registerProperty("Minimum",element.setMinimun,element.getMinimun);controller.registerProperty("Maximum",element.setMaximun,element.getMaximun);controller.registerProperty("Variable",element.setVariable,element.getVariable);controller.registerProperty("FunctionX",element.setFunctionX,element.getFunctionX);controller.registerProperty("FunctionY",element.setFunctionY,element.getFunctionY);controller.registerAction("OnError")}};EJSS_DRAWING2D.analyticCurve=function(name){var self=EJSS_DRAWING2D.element(name);var mMinimun;var mMaximun;var mVariable="t";var mFunctionX="t";var mFunctionY="0";var mParameters={};var mNumPoints=screen.width*5;self._23=function(){return"ElementAnalyticCurve"};self.setParameters=function(parameters){for(var param in parameters){mParameters[param]=parameters[param]}self.setChanged(true)};self.getParameters=function(){return mParameters};self.getBounds=function(element){var x=self.getX(),y=self.getY();var sx=self.getSizeX(),sy=self.getSizeY();var mx=sx/2,my=sy/2;var d=self.getRelativePositionOffset(sx,sy);var parser=EJSS_DRAWING2D.functionsParser();var exprfx;var exprfy;var mustReturn=false;try{exprfx=parser.parse(mFunctionX)}catch(errorfx){console.log("Analytic curve error parsing FunctionX: "+mFunctionX);mustReturn=true}if(!mustReturn){try{exprfy=parser.parse(mFunctionY)}catch(errorfy){console.log("Analytic curve error parsing FunctionY: "+mFunctionY);mustReturn=true}}if(mustReturn){self.getController().invokeAction("OnError");return{left:x+d[0]-mx-sx,right:x+d[0]-mx+sx,top:y+d[1]-my+sy,bottom:y+d[1]-my-sy}}var min=typeof mMinimun=="undefined"||mMinimun===null?self.getPanel().getRealWorldXMin():mMinimun;var max=typeof mMaximun=="undefined"||mMaximun===null?self.getPanel().getRealWorldXMax():mMaximun;var step=(max-min)/mNumPoints;var points=[];var vblevalue={};for(var param in mParameters){vblevalue[param]=mParameters[param]}try{for(var j=0,i=min;i<max;i+=step){vblevalue[mVariable]=i;var fxvalue=exprfx.evaluate(vblevalue);var fyvalue=exprfy.evaluate(vblevalue);if(!isNaN(fxvalue)&&!isNaN(fyvalue)){points[j]=[];points[j][0]=fxvalue;points[j++][1]=fyvalue}}}catch(errorEvaluate){self.getController().invokeAction("OnError");return{left:x+d[0]-mx-sx,right:x+d[0]-mx+sx,top:y+d[1]-my+sy,bottom:y+d[1]-my-sy}}var maxfx=0;var maxfy=0;var minfx=0;var minfy=0;if(points.length>0){maxfx=points[0][0],minfx=points[0][0];maxfy=points[0][1],minfy=points[0][1];for(var k=0;k<points.length;k++){if(points[k][0]>maxfx)maxfx=points[k][0];if(points[k][0]<minfx)minfx=points[k][0];if(points[k][1]>maxfy)maxfy=points[k][1];if(points[k][1]<minfy)minfy=points[k][1]}}return{left:x+d[0]-mx+minfx*sx,right:x+d[0]-mx+maxfx*sx,top:y+d[1]-my+maxfy*sy,bottom:y+d[1]-my+minfy*sy}};self.setNumPoints=function(numpoints){if(mNumPoints!=numpoints){mNumPoints=numpoints;self.setChanged(true)}};self.getNumPoints=function(){return mNumPoints};self.setMinimun=function(minimun){if(mMinimun!=minimun){mMinimun=minimun;self.setChanged(true)}};self.getMinimun=function(){return mMinimun};self.setMaximun=function(maximun){if(mMaximun!=maximun){mMaximun=maximun;self.setChanged(true)}};self.getMaximun=function(){return mMaximun};self.setVariable=function(variable){if(mVariable!=variable){mVariable=variable;self.setChanged(true)}};self.getVariable=function(){return mVariable};self.setFunctionX=function(functionx){if(mFunctionX!=functionx){mFunctionX=functionx;self.setChanged(true)}};self.getFunctionX=function(){return mFunctionX};self.setFunctionY=function(functiony){if(mFunctionY!=functiony){mFunctionY=functiony;self.setChanged(true)}};self.getFunctionY=function(){return mFunctionY};self.registerProperties=function(controller){EJSS_DRAWING2D.AnalyticCurve.registerProperties(self,controller)};self.setSize([1,1]);self.setRelativePosition("SOUTH_WEST");return self};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.Arrow={};EJSS_DRAWING2D.arrow=function(name){};EJSS_DRAWING2D.ArrowSet={};EJSS_DRAWING2D.arrowSet=function(mName){};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.Axis={AXIS_VERTICAL:0,AXIS_HORIZONTAL:1,TICKS_UP:2,TICKS_DOWN:3,SCALE_NUM:0,SCALE_LOG:1,registerProperties:function(element,controller){EJSS_DRAWING2D.Element.registerProperties(element,controller);controller.registerProperty("Step",element.setStep,element.getStep);controller.registerProperty("TickStep",element.setTickStep,element.getTickStep);controller.registerProperty("Ticks",element.setTicks,element.getTicks);controller.registerProperty("AutoTicks",element.setAutoTicks,element.getAutoTicks);controller.registerProperty("FixedTick",element.setFixedTick,element.getFixedTick);controller.registerProperty("Orient",element.setOrient,element.getOrient);controller.registerProperty("Scale",element.setScale,element.getScale);controller.registerProperty("TicksMode",element.setTicksMode,element.getTicksMode);controller.registerProperty("TicksSize",element.setTicksSize,element.getTicksSize);controller.registerProperty("AutoStepMin",element.setAutoStepMin,element.getAutoStepMin);controller.registerProperty("AutoTicksRange",element.setAutoTicksRange,element.getAutoTicksRange);controller.registerProperty("TextPosition",element.setTextPosition,element.getTextPosition);controller.registerProperty("ScalePrecision",element.setScalePrecision,element.getScalePrecision);controller.registerProperty("Font",element.getFont().setFont);controller.registerProperty("FontFamily",element.getFont().setFontFamily);controller.registerProperty("FontSize",element.getFont().setFontSize);controller.registerProperty("LetterSpacing",element.getFont().setLetterSpacing);controller.registerProperty("FontOutlineColor",element.getFont().setOutlineColor);controller.registerProperty("FontWeight",element.getFont().setFontWeight);controller.registerProperty("FontFillColor",element.getFont().setFillColor);controller.registerProperty("Show",element.setShow,element.getShow)}};EJSS_DRAWING2D.axis=function(mName){var self=EJSS_DRAWING2D.segment(mName);var mAutoTicks=true;var mTicks=0;var mStep=20;var mTickStep=0;var mFixedTick=Number.NaN;var mOrient=EJSS_DRAWING2D.Axis.AXIS_VERTICAL;var mScale=[-1,1];var mInvertedScaleY=false;var mTicksMode=EJSS_DRAWING2D.Axis.SCALE_NUM;var mTextPosition=EJSS_DRAWING2D.Axis.TICKS_UP;var mTicksSize=10;var mScalePrecision=1;var mFont=EJSS_DRAWING2D.font(mName);var mAutoStepMin=40;var mAutoTicksRange=[5,10,20];var mShow=true;self._23=function(){return"ElementAxis"};self.setShow=function(show){if(mShow!=show){mShow=show;self.setChanged(true)}};self.getShow=function(){return mShow};self.getFont=function(){return mFont};self.setAutoTicksRange=function(range){if(mAutoTicksRange!=range){mAutoTicksRange=range;self.setChanged(true)}};self.getAutoTicksRange=function(){return mAutoTicksRange};self.setAutoStepMin=function(min){if(mAutoStepMin!=min){mAutoStepMin=min;self.setChanged(true)}};self.getAutoStepMin=function(){return mAutoStepMin};self.setFixedTick=function(fixed){if(mFixedTick!=fixed){mFixedTick=fixed;self.setChanged(true)}};self.getFixedTick=function(){return mFixedTick};self.setAutoTicks=function(auto){if(mAutoTicks!=auto){mAutoTicks=auto;self.setChanged(true)}};self.getAutoTicks=function(){return mAutoTicks};self.setStep=function(step){if(mStep!=step){mStep=step;self.setChanged(true)}};self.getStep=function(){return mStep};self.setTickStep=function(TickStep){if(mTickStep!=TickStep){mTickStep=TickStep;self.setChanged(true)}};self.getTickStep=function(){return mTickStep};self.setTicks=function(ticks){if(mTicks!=ticks){mTicks=ticks;self.setChanged(true)}};self.getTicks=function(){return mTicks};self.setTicksMode=function(ticksMode){if(typeof ticksMode=="string")ticksMode=EJSS_DRAWING2D.Grid[ticksMode.toUpperCase()];if(mTicksMode!=ticksMode){mTicksMode=ticksMode;self.setChanged(true)}};self.getTicksMode=function(){return mTicksMode};self.setTextPosition=function(textPosition){if(typeof textPosition=="string")textPosition=EJSS_DRAWING2D.Axis[textPosition.toUpperCase()];if(mTextPosition!=textPosition){mTextPosition=textPosition;self.setChanged(true)}};self.getTextPosition=function(){return mTextPosition};self.setOrient=function(orient){if(typeof orient=="string")orient=EJSS_DRAWING2D.Axis[orient.toUpperCase()];if(mOrient!=orient){mOrient=orient;self.setChanged(true)}};self.getOrient=function(){return mOrient};self.setScale=function(scale){if(mScale!=scale){mScale=scale;self.setChanged(true)}};self.getScale=function(){return mScale};self.setScalePrecision=function(scalePrecision){if(mScalePrecision!=scalePrecision){mScalePrecision=scalePrecision;self.setChanged(true)}};self.getScalePrecision=function(){return mScalePrecision};self.setTicksSize=function(ticksSize){if(mTicksSize!=ticksSize){mTicksSize=ticksSize;self.setChanged(true)}};self.getTicksSize=function(){return mTicksSize};self.setInvertedScaleY=function(invertedscale){if(mInvertedScaleY!=invertedscale){mInvertedScaleY=invertedscale;self.setChanged(true)}};self.getInvertedScaleY=function(){return mInvertedScaleY};self.registerProperties=function(controller){EJSS_DRAWING2D.Axis.registerProperties(self,controller)};mFont.setChangeListener(function(change){self.setChanged(true)});return self};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.ByteRaster={};EJSS_DRAWING2D.byteRaster=function(name){};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.Canvas={copyTo:function(source,dest){EJSS_DRAWING2D.Element.copyTo(source,dest);dest.setDimensions(source.getDimensions())},registerProperties:function(element,controller){EJSS_DRAWING2D.Element.registerProperties(element,controller);controller.registerProperty("Dimensions",element.setDimensions,element.getDimensions)}};EJSS_DRAWING2D.canvas=function(name){var self=EJSS_DRAWING2D.element(name);var mDrawables=[];var mxMin=-10;var mxMax=10;var myMin=-10;var myMax=10;self._23=function(){return"ElementCanvas"};self.setDimensions=function(dimensions){xMin=dimensions[0];xMax=dimensions[1];yMin=dimensions[2];yMax=dimensions[3];self.setChanged(true)};self.getDimensions=function(){return[xMin,xMax,yMin,yMax]};self.addDrawable=function(drawable){mDrawables.push(drawable);self.setChanged(true)};self.addImageField=function(data,xMin,xMax,xPoints,yMin,yMax,yPoints,autoscale,zMin,zMax){var imgField=function(){var shape={};shape.imageField=true;shape.data=data||undefined;shape.xMin=xMin===undefined?-5:xMin;shape.xMax=xMax===undefined?5:xMax;shape.nx=xPoints||128;shape.yMin=yMin===undefined?-5:yMin;shape.yMax=yMax===undefined?5:yMax;shape.ny=yPoints||128;shape.autoscale=autoscale||true;shape.lower=zMin===undefined?-1:zMin;shape.upper=zMax===undefined?1:zMax;shape.center=(shape.lower+shape.upper)/2;shape.maskRadius=0;function arrayCoordinates(min,max,points){var coordinates=[];var step=(max-min)/(points-1);var val=min;for(var i=0;i<points;i++){coordinates.push(val);val+=step}return coordinates}shape.xPos=arrayCoordinates(shape.xMin,shape.xMax,shape.nx);shape.yPos=arrayCoordinates(shape.yMin,shape.yMax,shape.ny);shape.updateData=function(newData){shape.data=newData||shape.data;shape.xPos=arrayCoordinates(shape.xMin,shape.xMax,shape.nx);shape.yPos=arrayCoordinates(shape.yMin,shape.yMax,shape.ny);self.setChanged(true)};shape.setThreshold=function(lower,upper){shape.lower=lower===undefined?shape.lower:lower;shape.upper=upper===undefined?shape.upper:upper;self.setChanged(true)};shape.setCircularMask=function(radius){shape.maskRadius=radius;self.setChanged(true)};return shape}();self.addDrawable(imgField);return imgField};self.getDrawables=function(){return mDrawables};this.clearObjects=function(){mDrawables=[];self.setChanged(true)};self.registerProperties=function(controller){EJSS_DRAWING2D.Canvas.registerProperties(self,controller)};self.copyTo=function(element){EJSS_DRAWING2D.Canvas.copyTo(self,element)};return self};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.CellLattice={};EJSS_DRAWING2D.cellLattice=function(name){};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.Cursor={};EJSS_DRAWING2D.cursor=function(name){};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.Custom={};EJSS_DRAWING2D.custom=function(name){};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.DrawingPanel={MOUSE_ENTERED:0,MOUSE_EXITED:1,MOUSE_PRESSED:2,MOUSE_DRAGGED:3,MOUSE_RELEASED:4,GRAPHICS2D_SVG:0,GRAPHICS2D_CANVAS:1,SCALE_NUM:0,SCALE_LOG:1,ENABLED_NONE:0,ENABLED_ANY:1,ENABLED_X:2,ENABLED_Y:3,ENABLED_NO_MOVE:4,registerProperties:function(element,controller){element.setController(controller);controller.registerProperty("AutoScale",element.setAutoScale,element.getAutoScale);controller.registerProperty("AutoScaleX",element.setAutoScaleX,element.getAutoScaleX);controller.registerProperty("AutoScaleY",element.setAutoScaleY,element.getAutoScaleY);controller.registerProperty("InvertedScaleY",element.setInvertedScaleY,element.getInvertedScaleY);controller.registerProperty("MinimumX",element.setWorldXMin,element.getWorldXMin);controller.registerProperty("MaximumX",element.setWorldXMax,element.getWorldXMax);controller.registerProperty("MinimumY",element.setWorldYMin,element.getWorldYMin);controller.registerProperty("MaximumY",element.setWorldYMax,element.getWorldYMax);controller.registerProperty("Bounds",element.setWorldCoordinates,element.getWorldCoordinates);controller.registerProperty("ScaleXType",function(v){element.setTypeScaleX(v);element.scale()},element.getTypeScaleX);controller.registerProperty("ScaleYType",function(v){element.setTypeScaleY(v);element.scale()},element.getTypeScaleY);controller.registerProperty("MarginX",element.setMarginX,element.getMarginX);controller.registerProperty("MarginY",element.setMarginY,element.getMarginY);controller.registerProperty("Parent",element.getGraphics().setParent,element.getGraphics().getParent);controller.registerProperty("ClassName",element.getGraphics().setClassName);controller.registerProperty("Width",function(v){if(element.getGraphics().setWidth(v))element.scale()},element.getGraphics().getBox().width);controller.registerProperty("Height",function(v){if(element.getGraphics().setHeight(v))element.scale()},element.getGraphics().getBox().height);controller.registerProperty("SquareAspect",element.setSquareAspect);controller.registerProperty("GraphicsMode",element.setGraphicsMode);controller.registerProperty("Enabled",element.getPanelInteraction().setEnabled);controller.registerProperty("StopMoveEvents",element.getPanelInteraction().setStopMoveEvents);controller.registerProperty("StopEventPropagation",element.getPanelInteraction().setStopGestures);controller.registerProperty("Gutters",element._25);controller.registerProperty("GuttersLineColor",element.getGuttersStyle().setLineColor);controller.registerProperty("GuttersLineWidth",element.getGuttersStyle().setLineWidth);controller.registerProperty("GuttersDrawLines",element.getGuttersStyle().setDrawLines);controller.registerProperty("GuttersColor",element.getGuttersStyle().setFillColor);controller.registerProperty("GuttersFill",element.getGuttersStyle().setDrawFill);controller.registerProperty("GuttersRendering",element.getStyle().setShapeRendering);controller.registerProperty("Background",element.getStyle().setFillColor);controller.registerProperty("Foreground",element.getStyle().setLineColor);controller.registerProperty("LineColor",element.getStyle().setLineColor);controller.registerProperty("LineWidth",element.getStyle().setLineWidth);controller.registerProperty("DrawLines",element.getStyle().setDrawLines);controller.registerProperty("FillColor",element.getStyle().setFillColor);controller.registerProperty("DrawFill",element.getStyle().setDrawFill);controller.registerProperty("ShapeRendering",element.getStyle().setShapeRendering);controller.registerProperty("Visibility",element.getGraphics().getStyle().setVisibility);controller.registerProperty("Display",element.getGraphics().getStyle().setDisplay);controller.registerProperty("CSS",element.getGraphics().getStyle().setCSS);controller.registerProperty("TRMessage",element.getMessageDecoration("TR").setText);controller.registerProperty("TLMessage",element.getMessageDecoration("TL").setText);controller.registerProperty("BRMessage",element.getMessageDecoration("BR").setText);controller.registerProperty("BLMessage",element.getMessageDecoration("BL").setText);controller.registerProperty("CoordinatesFormat",element.getCoordinates().setFormat);controller.registerProperty("ShowCoordinates",element.setShowCoordinates);controller.registerProperty("ShowAreaRectangle",element.setShowAreaRectangle);controller.registerProperty("EnabledZooming",element.setEnabledZooming);controller.registerProperty("EnabledDragging",element.setEnabledDragging);controller.registerProperty("CursorTypeForMove",element.getInteraction().setCursorTypeForMove);controller.registerAction("OnDoubleClick",element.getInteraction().getInteractionPoint);controller.registerAction("OnMove",element.getInteraction().getInteractionPoint,element.getOnMoveHandler);controller.registerAction("OnPress",element.getInteraction().getInteractionPoint,element.getOnPressHandler);controller.registerAction("OnDrag",element.getInteraction().getInteractionPoint,element.getOnDragHandler);controller.registerAction("OnRelease",element.getInteraction().getInteractionBounds,element.getOnReleaseHandler);controller.registerAction("OnResize",element.getInteraction().getInteractionBounds,element.scale);controller.registerAction("OnOrientationChange",element.getInteraction().getOrientation,element.scale);controller.registerAction("OnZoom",element.getInteraction().getPinchDistance,element.getOnZoomHandler)}};EJSS_DRAWING2D.drawingPanel=function(mName,mGraphicsMode){var self={};var mGraphics;var mStyle=EJSS_DRAWING2D.style(mName);var mBottomDecorations=[];var mElements=[];var mElementsChanged=false;var mAutoScaleX=false;var mAutoScaleY=false;var mInvertedScaleY=false;var mTypeScaleX=0;var mTypeScaleY=0;var mTopDecorations=[];var mShowCoordinates=true;var mShowAreaRectangle=true;var mEnabledDragging=false;var mEnabledZooming=false;var mZoomRate=1.1;var mZoomLimits=[.1,1e3];var mCollectersList=[];var xmindef=-1,xmaxdef=+1,ymindef=-1,ymaxdef=+1;var mWorld={xminPreferred:NaN,xmaxPreferred:NaN,yminPreferred:NaN,ymaxPreferred:NaN,xminMeasured:NaN,xmaxMeasured:NaN,yminMeasured:NaN,ymaxMeasured:NaN,xmargin:0,ymargin:0,xmin:-1,xmax:+1,ymin:-1,ymax:+1,squareAspect:false,xorigin:0,yorigin:0,xscale:1,yscale:1};var mGutters={left:0,right:0,top:0,bottom:0,visible:false};var mGuttersStyle=EJSS_DRAWING2D.style(mName+" gutters");var mPanelChanged=true;var mMustScale=true;var mEnabledRedering=true;var mController={propertiesChanged:function(){},invokeAction:function(){}};self.getName=function(){return mName};self.getGraphics=function(){return mGraphics};self.importGraphics=function(callback){if(mGraphics.importSVG)return mGraphics.importSVG(callback);return null};self.getStyle=function(){return mStyle};self.getGraphicsMode=function(){return mGraphicsMode};self.getGraphicsModeName=function(){switch(mGraphicsMode){case EJSS_DRAWING2D.DrawingPanel.GRAPHICS2D_CANVAS:return"CANVAS";default:case EJSS_DRAWING2D.DrawingPanel.GRAPHICS2D_SVG:return"SVG"}};self.setGraphicsMode=function(mode){if(typeof mode==="string"){if(mode.indexOf("GRAPHICS2D_")!=0)mode="GRAPHICS2D_"+mode;mode=EJSS_DRAWING2D.DrawingPanel[mode.toUpperCase()]|EJSS_DRAWING2D.DrawingPanel.GRAPHICS2D_SVG}else if(typeof mode==="undefined"){mode=EJSS_DRAWING2D.DrawingPanel.GRAPHICS2D_SVG}if(mode==mGraphicsMode)return;mGraphicsMode=mode;var exists=typeof mGraphics!=="undefined";if(exists){var parent=mGraphics.getParent();var width=mGraphics.getWidth();var height=mGraphics.getHeight();var style=mGraphics.getEventContext().getAttribute("style");var ele=document.getElementById(mName);ele.parentNode.removeChild(ele)}if(mode==EJSS_DRAWING2D.DrawingPanel.GRAPHICS2D_SVG){mGraphics=EJSS_GRAPHICS.svgGraphics(mName)}else if(mode==EJSS_DRAWING2D.DrawingPanel.GRAPHICS2D_CANVAS){mGraphics=EJSS_GRAPHICS.canvasGraphics(mName)}else{console.log("WARNING: setGraphics() - Graphics not supported")}if(exists){mGraphics.setParent(parent);mGraphics.setWidth(width);mGraphics.setHeight(height);mGraphics.getEventContext().setAttribute("style",style);mElementsChanged=true;mInteraction.reload()}};self.getAutoScale=function(){return mAutoScaleX||mAutoScaleY};self.setAutoScale=function(autoscale){self.setAutoScaleX(autoscale);self.setAutoScaleY(autoscale)};self.setAutoScaleX=function(autoscale){mAutoScaleX=autoscale};self.getAutoScaleX=function(){return mAutoScaleX};self.setAutoScaleY=function(autoscale){mAutoScaleY=autoscale};self.getAutoScaleY=function(){return mAutoScaleY};self.setInvertedScaleY=function(invertedscale){if(mInvertedScaleY!=invertedscale){mInvertedScaleY=invertedscale;if(mInvertedScaleY)mTypeScaleY=EJSS_DRAWING2D.DrawingPanel.SCALE_NUM;var changed=self.reportDecorations("bounds");if(changed)mPanelChanged=true}};self.getInvertedScaleY=function(){return mInvertedScaleY};self.setTypeScaleX=function(typescale){if(typeof typescale=="string")typescale=EJSS_DRAWING2D.DrawingPanel[typescale.toUpperCase()];mTypeScaleX=typescale};self.getTypeScaleX=function(){return mTypeScaleX};self.setTypeScaleY=function(typescale){if(typeof typescale=="string")typescale=EJSS_DRAWING2D.DrawingPanel[typescale.toUpperCase()];mTypeScaleY=typescale;if(mTypeScaleY==EJSS_DRAWING2D.DrawingPanel.SCALE_LOG)mInvertedScaleY=false};self.getTypeScaleY=function(){return mTypeScaleY};self.setWorldXMin=function(xmin){if(xmin!==mWorld.xminPreferred){mWorld.xminPreferred=xmin}};self.getWorldXMin=function(){return mWorld.xminPreferred};self.setWorldXMax=function(xmax){if(xmax!==mWorld.xmaxPreferred){mWorld.xmaxPreferred=xmax}};self.getWorldXMax=function(){return mWorld.xmaxPreferred};self.setWorldYMin=function(ymin){if(ymin!==mWorld.yminPreferred){mWorld.yminPreferred=ymin}};self.getWorldYMin=function(){return mWorld.yminPreferred};self.setWorldYMax=function(ymax){if(ymax!==mWorld.ymaxPreferred){mWorld.ymaxPreferred=ymax}};self.getWorldYMax=function(){return mWorld.ymaxPreferred};self.setWorldCoordinates=function(bounds){self.setWorldXMin(bounds[0]);self.setWorldXMax(bounds[1]);self.setWorldYMin(bounds[2]);self.setWorldYMax(bounds[3])};self.getWorldCoordinates=function(){return[self.getWorldXMin(),self.getWorldXMax(),self.getWorldYMin(),self.getWorldYMax()]};self.getMeasuredCoordinates=function(){return[mWorld.xminMeasured,mWorld.xmaxMeasured,mWorld.yminMeasured,mWorld.ymaxMeasured]};self.getRealWorldCoordinates=function(){return[mWorld.xmin,mWorld.xmax,mWorld.ymin,mWorld.ymax]};self.getRealWorldXMin=function(){return mWorld.xmin};self.getRealWorldXMax=function(){return mWorld.xmax};self.getRealWorldYMin=function(){return mWorld.ymin};self.getRealWorldYMax=function(){return mWorld.ymax};self.setSquareAspect=function(square){if(square!==mWorld.squareAspect){mWorld.squareAspect=square;mMustScale=true}};self.setMarginX=function(margin){if(mWorld.xmargin!=margin){mWorld.xmargin=margin;mMustScale=true}};self.getMarginX=function(){return mWorld.xmargin};self.setMarginY=function(margin){if(mWorld.ymargin!=margin){mWorld.ymargin=margin;mMustScale=true}};self.getMarginY=function(){return mWorld.ymargin};self.setEnabledDragging=function(motion){if(typeof motion=="string"){value=EJSS_DRAWING2D.DrawingPanel[motion.toUpperCase()];mEnabledDragging=typeof value==="undefined"?EJSS_DRAWING2D.DrawingPanel.ENABLED_NONE:value}else mEnabledDragging=motion};self.getEnabledDragging=function(){return mEnabledDragging};self.setEnabledZooming=function(allowed){mEnabledZooming=allowed};self.getEnabledZooming=function(){return mEnabledZooming};self.setZoomRate=function(rate){mZoomRate=rate};self.getZoomRate=function(){return mZoomRate};self.setZoomLimits=function(limits){mZoomLimits=limits};self.getZoomLimits=function(){return mZoomLimits};self.setShowCoordinates=function(show){mShowCoordinates=show};self.getShowCoordinates=function(){return mShowCoordinates};self.setShowAreaRectangle=function(show){mShowAreaRectangle=show};self.getShowAreaRectangle=function(){return mShowAreaRectangle};self.addDecoration=function(drawable,position,istop){if(istop)EJSS_TOOLS.addToArray(mTopDecorations,drawable,position);else EJSS_TOOLS.addToArray(mBottomDecorations,drawable,position);if(drawable.setPanel)drawable.setPanel(self);return self};self.removeDecoration=function(drawable){EJSS_TOOLS.removeFromArray(mBottomDecorations,drawable);EJSS_TOOLS.removeFromArray(mTopDecorations,drawable);if(drawable.setPanel)drawable.setPanel(null);return self};self.addElement=function(element,sibling){if(typeof sibling==="undefined"){EJSS_TOOLS.addToArray(mElements,element)}else if(typeof sibling==="object"){var index=EJSS_TOOLS.arrayObjectIndexOf(mElements,sibling);EJSS_TOOLS.addToArray(mElements,element,index)}else{EJSS_TOOLS.addToArray(mElements,element,sibling)}element.setPanel(self);if(element.dataCollected)mCollectersList.push(element);mElementsChanged=true};self.removeElement=function(element){EJSS_TOOLS.removeFromArray(mElements,element);mInteraction.clearInteractionElement(element);element.setPanel(null);if(element.dataCollected)EJSS_TOOLS.removeFromArray(mCollectersList,element);mElementsChanged=true};self.getElements=function(){return mElements};self.indexOfElement=function(element){return mElements.indexOf(element)};self._25=function(rect){var left=rect[0],top=rect[1],right=rect[2],bottom=rect[3];var changed=false;if(left!==mGutters.left){mGutters.left=left;changed=true}if(top!==mGutters.top){mGutters.top=top;changed=true}if(right!==mGutters.right){mGutters.right=right;changed=true}if(bottom!==mGutters.bottom){mGutters.bottom=bottom;changed=true}if(changed){mGutters.visible=mGutters.left>0||mGutters.top>0||mGutters.right>0||mGutters.bottom>0;mPanelChanged=true;mMustScale=true}};self.getGutters=function(){return mGutters};self.getGuttersStyle=function(){return mGuttersStyle};self.toPixelAxisY=function(y){return mWorld.yorigin-y-mWorld.yscale*mWorld.ymin};self.toPixelAxisX=function(x){return mWorld.xorigin+x-mWorld.xscale*mWorld.xmin};self._26=function(point,scale){var scaleX=typeof scale!="undefined"?scale:mTypeScaleX;var scaleY=typeof scale!="undefined"?scale:mTypeScaleY;var pos=[];if(scaleX==EJSS_DRAWING2D.DrawingPanel.SCALE_LOG)pos[0]=self.toPixelLogScale(point[0],mWorld.xorigin,mWorld.xmin,mWorld.xmax,mWorld.xscale);else pos[0]=mWorld.xorigin+mWorld.xscale*(point[0]-mWorld.xmin);if(scaleY==EJSS_DRAWING2D.DrawingPanel.SCALE_LOG)pos[1]=self.toPixelLogScale(point[1],mWorld.yorigin,mWorld.ymin,mWorld.ymax,mWorld.yscale);else{if(!mInvertedScaleY)pos[1]=mWorld.yorigin+mWorld.yscale*(point[1]-mWorld.ymin);else pos[1]=mGutters.top+mWorld.yscale*(mWorld.ymin-point[1])}return pos};self.toPixelMod=function(mod){var pmod=[];pmod[0]=mod[0]*mWorld.xscale;pmod[1]=mod[1]*mWorld.yscale;return pmod};self.toPanelPosition=function(point,scale){var scaleX=typeof scale!="undefined"?scale:mTypeScaleX;var scaleY=typeof scale!="undefined"?scale:mTypeScaleY;var pos=[];if(scaleX==EJSS_DRAWING2D.DrawingPanel.SCALE_LOG)pos[0]=self.toPanelLogScale(point[0],mWorld.xorigin,mWorld.xmin,mWorld.xmax,mWorld.xscale);else pos[0]=mWorld.xmin+(point[0]-mWorld.xorigin)/mWorld.xscale;if(scaleY==EJSS_DRAWING2D.DrawingPanel.SCALE_LOG)pos[1]=self.toPanelLogScale(point[1],mWorld.yorigin,mWorld.ymin,mWorld.ymax,mWorld.yscale);else{if(!mInvertedScaleY)pos[1]=mWorld.ymin+(point[1]-mWorld.yorigin)/mWorld.yscale;else pos[1]=mWorld.ymin-(point[1]-mGutters.top)/mWorld.yscale}return pos};self.toPanelMod=function(mod){var pmod=[];pmod[0]=mWorld.xscale==0?0:mod[0]/mWorld.xscale;pmod[1]=mWorld.yscale==0?0:mod[1]/mWorld.yscale;return pmod};self.toPixelLogScale=function(value,origin,min,max,pixratio){var minscale=min<=0?1:Math.log(min)/Math.log(10);var maxscale=max<=0?1:Math.log(max)/Math.log(10);var segsize=(max-min)*pixratio;var scalesize=maxscale-minscale;var sizeratio=segsize/scalesize;var step=value<=0?0:Math.log(value)/Math.log(10);return origin+sizeratio*(step-minscale)};self.toPanelLogScale=function(value,origin,min,max,pixratio){var minscale=min<0?0:Math.log(min)/Math.log(10);var maxscale=max<0?0:Math.log(max)/Math.log(10);var segsize=(max-min)*pixratio;var scalesize=maxscale-minscale;var sizeratio=segsize/scalesize;return Math.pow(10,minscale+(value-origin)/sizeratio)};self.getPixelPositionWorldOrigin=function(){return[mWorld.xorigin,mWorld.yorigin]};self.getInnerRect=function(){var bounds=self.getRealWorldCoordinates();if(!self.getInvertedScaleY())var pos=self._26([bounds[0],bounds[3]]);else var pos=self._26([bounds[0],bounds[2]]);var size=self.toPixelMod([bounds[1]-bounds[0],bounds[3]-bounds[2]]);return{x:pos[0],width:Math.abs(size[0]),y:pos[1],height:Math.abs(size[1])}},self.scale=function(){mMustScale=true;mElementsChanged=true};self.touch=function(){mMustScale=true;mElementsChanged=true;for(var i=0,n=mElements.length;i<n;i++)mElements[i].setChanged(true)};self._27=function(){var newWorld=false;var rangeX=(mWorld.xmaxMeasured-mWorld.xminMeasured)/2;var rangeY=(mWorld.ymaxMeasured-mWorld.yminMeasured)/2;var xmin=mWorld.xminMeasured-Math.abs(rangeX*mWorld.xmargin/100);var xmax=mWorld.xmaxMeasured+Math.abs(rangeX*mWorld.xmargin/100);var ymin=mWorld.yminMeasured-Math.abs(rangeY*mWorld.ymargin/100);var ymax=mWorld.ymaxMeasured+Math.abs(rangeY*mWorld.ymargin/100);var box=mGraphics.getBox();var width=box.width-(mGutters.left+mGutters.right);var height=box.height-(mGutters.bottom+mGutters.top);var xPixPerUnit=width/(xmax-xmin);var yPixPerUnit=height/(ymax-ymin);var stretch,diff;if(mWorld.squareAspect){stretch=Math.abs(xPixPerUnit/yPixPerUnit);if(stretch>=1){stretch=Math.min(stretch,width);diff=(xmax-xmin)*(stretch-1)/2;xmin-=diff;xmax+=diff;xPixPerUnit=width/(xmax-xmin)}else{stretch=Math.max(stretch,1/height);diff=(ymax-ymin)*(1/stretch-1)/2;ymin-=diff;ymax+=diff;yPixPerUnit=height/(ymax-ymin)}}newWorld=mWorld.xscale!=xPixPerUnit||mWorld.yscale!=-yPixPerUnit;mWorld.xscale=xPixPerUnit;mWorld.yscale=-yPixPerUnit;mWorld.xorigin=mGutters.left+.5;mWorld.yorigin=height+mGutters.top+.5;mMustScale=false;if(mWorld.xmin!==xmin||mWorld.xmax!==xmax||mWorld.ymin!==ymin||mWorld.ymax!==ymax){mWorld.xmin=xmin;mWorld.xmax=xmax;mWorld.ymin=ymin;mWorld.ymax=ymax;var changed=self.reportDecorations("bounds");if(changed)mPanelChanged=true;newWorld=true}if(newWorld){for(var i=0,n=mElements.length;i<n;i++)mElements[i].setMustProject(true)}};self.reportDecorations=function(event){var changed=false,i,n;for(i=0,n=mBottomDecorations.length;i<n;i++){changed|=mBottomDecorations[i].panelChangeListener&&mBottomDecorations[i].panelChangeListener("bounds")}for(i=0,n=mTopDecorations.length;i<n;i++){if(mTopDecorations[i].panelChangeListener)mTopDecorations[i].panelChangeListener("bounds")}return changed};self._28=function(){var xminMeasured=Number.MAX_VALUE;var xmaxMeasured=-Number.MAX_VALUE;var yminMeasured=Number.MAX_VALUE;var ymaxMeasured=-Number.MAX_VALUE;if(self.getAutoScaleY()||self.getAutoScaleX()){for(var i=0,n=mElements.length;i<n;i++){if(mElements[i].isMeasured()&&!mElements[i].isGroup()&&(mElements[i].getGroup()==null||mElements[i].getGroup().isMeasured())){if(mElements[i].isPixelSize()){var pos=mElements[i].getPosition();xminMeasured=Math.min(xminMeasured,pos[0]);xmaxMeasured=Math.max(xmaxMeasured,pos[0]);yminMeasured=Math.min(yminMeasured,pos[1]);ymaxMeasured=Math.max(ymaxMeasured,pos[1])}else{var bounds=mElements[i].getAbsoluteBounds();xminMeasured=Math.min(xminMeasured,bounds.left);xmaxMeasured=Math.max(xmaxMeasured,bounds.right);yminMeasured=Math.min(yminMeasured,bounds.bottom);ymaxMeasured=Math.max(ymaxMeasured,bounds.top)}}}}var updatedX=false;if(self.getAutoScaleX()){if(!isNaN(mWorld.xminPreferred))xminMeasured=Math.min(xminMeasured,mWorld.xminPreferred);if(!isNaN(mWorld.xmaxPreferred))xmaxMeasured=Math.max(xmaxMeasured,mWorld.xmaxPreferred);if(xmaxMeasured<=xminMeasured){updatedX=mWorld.xminMeasured!=xmindef||mWorld.xmaxMeasured!=xmaxdef;mWorld.xminMeasured=xmindef;mWorld.xmaxMeasured=xmaxdef}else{updatedX=mWorld.xminMeasured!=xminMeasured||mWorld.xmaxMeasured!=xmaxMeasured;mWorld.xminMeasured=xminMeasured;mWorld.xmaxMeasured=xmaxMeasured}}else if(!isNaN(mWorld.xminPreferred)&&!isNaN(mWorld.xmaxPreferred)){updatedX=mWorld.xminMeasured!=mWorld.xminPreferred||mWorld.xmaxMeasured!=mWorld.xmaxPreferred;mWorld.xminMeasured=mWorld.xminPreferred;mWorld.xmaxMeasured=mWorld.xmaxPreferred}else{updatedX=mWorld.xminMeasured!=xmindef||mWorld.xmaxMeasured!=xmaxdef;mWorld.xminMeasured=xmindef;mWorld.xmaxMeasured=xmaxdef}var updatedY=false;if(self.getAutoScaleY()){if(!isNaN(mWorld.yminPreferred))yminMeasured=Math.min(yminMeasured,mWorld.yminPreferred);if(!isNaN(mWorld.ymaxPreferred))ymaxMeasured=Math.max(ymaxMeasured,mWorld.ymaxPreferred);if(ymaxMeasured<=yminMeasured){updatedY=mWorld.yminMeasured!=ymindef||mWorld.ymaxMeasured!=ymaxdef;mWorld.yminMeasured=ymindef;mWorld.ymaxMeasured=ymaxdef}else{updatedY=mWorld.yminMeasured!=yminMeasured||mWorld.ymaxMeasured!=ymaxMeasured;mWorld.yminMeasured=yminMeasured;mWorld.ymaxMeasured=ymaxMeasured}}else if(!isNaN(mWorld.yminPreferred)&&!isNaN(mWorld.ymaxPreferred)){updatedY=mWorld.yminMeasured!=mWorld.yminPreferred||mWorld.ymaxMeasured!=mWorld.ymaxPreferred;mWorld.yminMeasured=mWorld.yminPreferred;mWorld.ymaxMeasured=mWorld.ymaxPreferred}else{updatedY=mWorld.yminMeasured!=ymindef||mWorld.ymaxMeasured!=ymaxdef;mWorld.yminMeasured=ymindef;mWorld.ymaxMeasured=ymaxdef}return updatedX||updatedY};self.reset=function(){mGraphics.reset()};self.disable=function(){mEnabledRedering=false};self.enable=function(){mEnabledRedering=true};self.render=function(){if(mEnabledRedering){var reseted=false;if(mGraphics.setImageData||mElementsChanged){mGraphics.reset();reseted=true;mElementsChanged=false}for(var i=0,n=mCollectersList.length;i<n;i++)mCollectersList[i].dataCollected();var measuredWorld=self._28();if(mMustScale||measuredWorld)self._27();if(mPanelChanged||reseted){mGraphics.drawPanel(self)}mGraphics.draw(mBottomDecorations);mGraphics.draw(mElements,reseted);if(mPanelChanged||reseted){mGraphics._24(self)}mGraphics.draw(mTopDecorations);mPanelChanged=false;for(var i=0,n=mElements.length;i<n;i++)mElements[i].setChanged(false)}};self.getPanelInteraction=function(){return mInteraction};self.getController=function(){return mController};self.setController=function(controller){mController=controller};self.getOnMoveHandler=null;self.getOnZoomHandler=function(){if(mEnabledZooming){var delta=mInteraction.getInteractionZoomDelta();var bounds=self.getWorldCoordinates();if(isNaN(bounds[0])||isNaN(bounds[1])||isNaN(bounds[2])||isNaN(bounds[3]))bounds=self.getMeasuredCoordinates();var incw=+((1-mZoomRate)*(bounds[1]-bounds[0])*delta/2);var inch=+((1-mZoomRate)*(bounds[3]-bounds[2])*delta/2);var neww=Math.abs(bounds[0]-bounds[1])-2*incw;if(neww>mZoomLimits[0]&&neww<mZoomLimits[1]){self.setWorldCoordinates([bounds[0]+incw,bounds[1]-incw,bounds[2]+inch,bounds[3]-inch])}}};self.getOnPressHandler=function(){if(mShowCoordinates){var point=mInteraction.getInteractionPoint();var bounds=self.getRealWorldCoordinates();if(bounds[0]<point[0]&&bounds[1]>point[0]&&bounds[3]>point[1]&&bounds[2]<point[1]){mCoorDecoration.setText(point);mCoorDecoration.setVisible(true);mCoorDecoration.getController().propertiesChanged("Visible","Text")}}};self.getOnDragHandler=function(){if(mShowCoordinates){var point=mInteraction.getInteractionPoint();var bounds=self.getRealWorldCoordinates();if(bounds[0]<point[0]&&bounds[1]>point[0]&&bounds[3]>point[1]&&bounds[2]<point[1]){mCoorDecoration.setText(point);mCoorDecoration.setVisible(true);mCoorDecoration.getController().propertiesChanged("Visible","Text")}}if(mShowAreaRectangle){var boundsInter=mInteraction.getInteractionBounds();if(boundsInter.length>0&&mTypeScaleX==EJSS_DRAWING2D.DrawingPanel.SCALE_NUM&&mTypeScaleY==EJSS_DRAWING2D.DrawingPanel.SCALE_NUM){mDragDecoration.setBounds(boundsInter);mDragDecoration.setVisible(true);mDragDecoration.getController().propertiesChanged("Position","X","Y","Size","SizeX","SizeY","Visible")}else{mDragDecoration.setVisible(false);mDragDecoration.getController().propertiesChanged("Visible")}}if(mEnabledDragging!=0&&mEnabledDragging!=4){var distance=mInteraction.getInteractionDistance();if(distance.length>0&&mTypeScaleX==EJSS_DRAWING2D.DrawingPanel.SCALE_NUM&&mTypeScaleY==EJSS_DRAWING2D.DrawingPanel.SCALE_NUM){var bounds=self.getWorldCoordinates();if(isNaN(bounds[0])||isNaN(bounds[1])||isNaN(bounds[2])||isNaN(bounds[3]))bounds=self.getMeasuredCoordinates();if(mEnabledDragging==1){self.setWorldCoordinates([bounds[0]+distance[0],bounds[1]+distance[0],bounds[2]+distance[1],bounds[3]+distance[1]])}else if(mEnabledDragging==2){self.setWorldCoordinates([bounds[0]+distance[0],bounds[1]+distance[0],bounds[2],bounds[3]])}else{self.setWorldCoordinates([bounds[0],bounds[1],bounds[2]+distance[1],bounds[3]+distance[1]])}}}};self.getOnReleaseHandler=function(){if(mShowCoordinates){mCoorDecoration.setVisible(false);mCoorDecoration.getController().propertiesChanged("Visible")}if(mShowAreaRectangle){mDragDecoration.setVisible(false);mDragDecoration.getController().propertiesChanged("Visible")}};self.getMessageDecoration=function(whichOne){switch(whichOne){case"TL":return mTLMessageDecoration;case"BR":return mBRMessageDecoration;case"BL":return mBLMessageDecoration}return mTRMessageDecoration};self.getCoordinates=function(){return mCoorDecoration};self.getInteraction=function(){return mInteraction};self.registerProperties=function(controller){EJSS_DRAWING2D.DrawingPanel.registerProperties(self,controller)};self.serialize=function(){return{mStyle:mStyle.serialize(),mTopDecorations:mTopDecorations,mBottomDecorations:mBottomDecorations,mElements:mElements,mCollectersList:mCollectersList,mAutoScaleX:mAutoScaleX,mAutoScaleY:mAutoScaleY,mInvertedScaleY:mInvertedScaleY,mTypeScaleX:mTypeScaleX,mTypeScaleY:mTypeScaleY,mShowCoordinates:mShowCoordinates,xmindef:xmindef,xmaxdef:xmaxdef,ymindef:ymindef,ymaxdef:ymaxdef,mWorld:mWorld,mGutters:mGutters,mGuttersStyle:mGuttersStyle.serialize()}};self.unserialize=function(json){mStyle.unserialize(json.mStyle),mAutoScaleX=json.mAutoScaleX,mAutoScaleY=json.mAutoScaleY,mInvertedScaleY=json.mInvertedScaleY,mTypeScaleX=json.mTypeScaleX,mTypeScaleY=json.mTypeScaleY,mShowCoordinates=json.mShowCoordinates,xmindef=json.xmindef,xmaxdef=json.xmaxdef,ymindef=json.ymindef,ymaxdef=json.ymaxdef,mWorld=json.mWorld,mGutters=json.mGutters,mGuttersStyle.unserialize(json.mGuttersStyle),mPanelChanged=true};self.setGraphicsMode(mGraphicsMode);mStyle.setLineColor("black");mStyle.setFillColor("rgb(239,239,255)");mStyle.setChangeListener(function(change){mPanelChanged=true});mGuttersStyle.setChangeListener(function(reporter){mPanelChanged=true});var mDragDecoration=EJSS_DRAWING2D.shape(mName+"__cursorBox__");mDragDecoration.setShapeType(EJSS_DRAWING2D.Shape.RECTANGLE);mDragDecoration.getStyle().setDrawFill(false);mDragDecoration.getStyle().setLineColor("black");mDragDecoration.setRelativePosition("CENTER");mDragDecoration.setVisible(false);self.addDecoration(mDragDecoration,0,true);var mTLMessageDecoration=EJSS_DRAWING2D.text(mName+"__tlmessage__");mTLMessageDecoration.setRelativePosition("NORTH_WEST");mTLMessageDecoration.getStyle().setDrawLines(true);mTLMessageDecoration.getStyle().setDrawFill(true);mTLMessageDecoration.getStyle().setFillColor("yellow");mTLMessageDecoration.getStyle().setLineColor("black");mTLMessageDecoration.getFont().setFontSize(12);mTLMessageDecoration.setPosition([mWorld.xmin,mWorld.ymax]);mTLMessageDecoration.setFramed(true);mTLMessageDecoration.panelChangeListener=function(event){if(event=="bounds"){if(self.getInvertedScaleY())mTLMessageDecoration.setPosition([mWorld.xmin,mWorld.ymin]);else mTLMessageDecoration.setPosition([mWorld.xmin,mWorld.ymax])}};self.addDecoration(mTLMessageDecoration,0,true);var mBLMessageDecoration=EJSS_DRAWING2D.text(mName+"__blmessage__");mBLMessageDecoration.setRelativePosition("SOUTH_WEST");mBLMessageDecoration.getStyle().setDrawLines(true);mBLMessageDecoration.getStyle().setDrawFill(true);mBLMessageDecoration.getStyle().setFillColor("yellow");mBLMessageDecoration.getStyle().setLineColor("black");mBLMessageDecoration.getFont().setFontSize(12);mBLMessageDecoration.setPosition([mWorld.xmin,mWorld.ymin]);mBLMessageDecoration.setFramed(true);mBLMessageDecoration.panelChangeListener=function(event){if(event=="bounds")if(self.getInvertedScaleY())mBLMessageDecoration.setPosition([mWorld.xmin,mWorld.ymax]);else mBLMessageDecoration.setPosition([mWorld.xmin,mWorld.ymin])};self.addDecoration(mBLMessageDecoration,0,true);var mBRMessageDecoration=EJSS_DRAWING2D.text(mName+"__brmessage__");mBRMessageDecoration.setRelativePosition("SOUTH_EAST");mBRMessageDecoration.getStyle().setDrawLines(true);mBRMessageDecoration.getStyle().setDrawFill(true);mBRMessageDecoration.getStyle().setFillColor("yellow");mBRMessageDecoration.getStyle().setLineColor("black");mBRMessageDecoration.getFont().setFontSize(12);mBRMessageDecoration.setPosition([mWorld.xmax,mWorld.ymin]);mBRMessageDecoration.setFramed(true);mBRMessageDecoration.panelChangeListener=function(event){if(event=="bounds")if(self.getInvertedScaleY())mBRMessageDecoration.setPosition([mWorld.xmax,mWorld.ymax]);else mBRMessageDecoration.setPosition([mWorld.xmax,mWorld.ymin])};self.addDecoration(mBRMessageDecoration,0,true);var mTRMessageDecoration=EJSS_DRAWING2D.text(mName+"__trmessage__");mTRMessageDecoration.setRelativePosition("NORTH_EAST");mTRMessageDecoration.getStyle().setDrawLines(true);mTRMessageDecoration.getStyle().setDrawFill(true);mTRMessageDecoration.getStyle().setFillColor("yellow");mTRMessageDecoration.getStyle().setLineColor("black");mTRMessageDecoration.getFont().setFontSize(12);mTRMessageDecoration.setPosition([mWorld.xmax,mWorld.ymax]);mTRMessageDecoration.setFramed(true);mTRMessageDecoration.panelChangeListener=function(event){if(event=="bounds")if(self.getInvertedScaleY())mTRMessageDecoration.setPosition([mWorld.xmax,mWorld.ymin]);else mTRMessageDecoration.setPosition([mWorld.xmax,mWorld.ymax])};self.addDecoration(mTRMessageDecoration,0,true);var mCoorDecoration=EJSS_DRAWING2D.infoText(mName+"__coor__");mCoorDecoration.setRelativePosition("SOUTH_WEST");mCoorDecoration.getFont().setFontSize(12);mCoorDecoration.getStyle().setFillColor("yellow");mCoorDecoration.setPosition([mWorld.xmin,mWorld.ymin]);mCoorDecoration.setFormat("x:0.##,y:0.##");mCoorDecoration.setFramed(true);mCoorDecoration.setVisible(false);mCoorDecoration.panelChangeListener=function(event){if(event=="bounds")if(self.getInvertedScaleY())mCoorDecoration.setPosition([mWorld.xmin,mWorld.ymax]);else mCoorDecoration.setPosition([mWorld.xmin,mWorld.ymin])};self.addDecoration(mCoorDecoration,0,true);self.getGuttersStyle().setLineColor("black");self.getGuttersStyle().setFillColor("rgb(239,239,255)");self.getGuttersStyle().setShapeRendering("RENDER_CRISPEDGES");var mInteraction=EJSS_DRAWING2D.panelInteraction(self);mGraphics.getEventContext().addEventListener("dblclick",function(event){event.preventDefault();event.stopPropagation();return false},true);return self};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.Element={CENTER:0,NORTH:1,SOUTH:2,EAST:3,WEST:4,NORTH_EAST:5,NORTH_WEST:6,SOUTH_EAST:7,SOUTH_WEST:8,registerProperties:function(element,controller){var TARGET_POSITION=EJSS_DRAWING2D.PanelInteraction.TARGET_POSITION;var TARGET_SIZE=EJSS_DRAWING2D.PanelInteraction.TARGET_SIZE;var style=element.getStyle();element.setController(controller);controller.registerProperty("Parent",element.setParent,element.getParent);controller.registerProperty("X",element.setX,element.getX);controller.registerProperty("Y",element.setY,element.getY);controller.registerProperty("Position",element.setPosition,element.getPosition);controller.registerProperty("PixelPosition",element.setPixelPosition,element.getPixelPosition)
;controller.registerProperty("Diameter",function(diameter){element.setSize([diameter,diameter])});controller.registerProperty("Radius",function(radius){element.setSize([radius*2,radius*2])});controller.registerProperty("SizeX",element.setSizeX,element.getSizeX);controller.registerProperty("SizeY",element.setSizeY,element.getSizeY);controller.registerProperty("Size",element.setSize,element.getSize);controller.registerProperty("PixelSize",element.setPixelSize,element.getPixelSize);controller.registerProperty("Bounds",element.setBounds,element.getBounds);controller.registerProperty("RelativePosition",element.setRelativePosition,element.getRelativePosition);controller.registerProperty("Visibility",element.setVisible,element.isVisible);controller.registerProperty("Measured",element.setMeasured,element.isMeasured);controller.registerProperty("Transformation",element.setTransformation);controller.registerProperty("Rotate",element.setRotate);controller.registerProperty("ScaleX",element.setScaleX);controller.registerProperty("ScaleY",element.setScaleY);controller.registerProperty("SkewX",element.setSkewX);controller.registerProperty("SkewY",element.setSkewY);controller.registerProperty("LineColor",style.setLineColor,style.getLineColor);controller.registerProperty("LineWidth",style.setLineWidth,style.getLineWidth);controller.registerProperty("DrawLines",style.setDrawLines,style.getDrawLines);controller.registerProperty("FillColor",style.setFillColor,style.getFillColor);controller.registerProperty("DrawFill",style.setDrawFill,style.getDrawFill);controller.registerProperty("ShapeRendering",style.setShapeRendering,style.getShapeRendering);controller.registerProperty("Attributes",style.setAttributes,style.getAttributes);controller.registerProperty("EnabledPosition",function(enabled){element.getInteractionTarget(TARGET_POSITION).setMotionEnabled(enabled)});controller.registerProperty("MovesGroup",function(affects){element.getInteractionTarget(TARGET_POSITION).setAffectsGroup(affects)});controller.registerProperty("EnabledSize",function(enabled){element.getInteractionTarget(TARGET_SIZE).setMotionEnabled(enabled)});controller.registerProperty("ResizesGroup",function(affects){element.getInteractionTarget(TARGET_SIZE).setAffectsGroup(affects)});controller.registerProperty("Sensitivity",function(sense){element.getInteractionTarget(TARGET_POSITION).setSensitivity(sense);element.getInteractionTarget(TARGET_SIZE).setSensitivity(sense)});controller.registerAction("OnDoubleClick",element.getOnDoubleClickInformation);controller.registerAction("OnEnter",element.getOnEnterInformation);controller.registerAction("OnExit",element.getOnExitInformation);controller.registerAction("OnPress",element.getOnPressInformation);controller.registerAction("OnDrag",element.getOnDragInformation);controller.registerAction("OnRelease",element.getOnReleaseInformation)},copyTo:function(source,dest){var InteractionTarget=EJSS_DRAWING2D.InteractionTarget;var TARGET_POSITION=EJSS_DRAWING2D.PanelInteraction.TARGET_POSITION;var TARGET_SIZE=EJSS_DRAWING2D.PanelInteraction.TARGET_SIZE;EJSS_DRAWING2D.Style.copyTo(source.getStyle(),dest.getStyle());dest.setVisible(source.isVisible());dest.setMeasured(source.isMeasured());dest.setPosition(source.getPosition());dest.setPixelPosition(source.isPixelPosition());dest.setSize(source.getSize());dest.setPixelSize(source.isPixelSize());dest.setTransformation(source.getTransformation());dest.setRotate(source.getRotate());dest.setRelativePosition(source.getRelativePosition());InteractionTarget.copyTo(source.getInteractionTarget(TARGET_POSITION),dest.getInteractionTarget(TARGET_POSITION));InteractionTarget.copyTo(source.getInteractionTarget(TARGET_SIZE),dest.getInteractionTarget(TARGET_SIZE));dest.setParent(source.getParent(),source)},getRelativePositionOffset:function(position,sx,sy,invertedy){var dx=0;var dy=0;switch(position){default:case EJSS_DRAWING2D.Element.CENTER:dx=0;dy=0;break;case EJSS_DRAWING2D.Element.NORTH:dx=0;dy=-(sy/2);break;case EJSS_DRAWING2D.Element.SOUTH:dx=0;dy=sy/2;break;case EJSS_DRAWING2D.Element.EAST:dx=-(sx/2);dy=0;break;case EJSS_DRAWING2D.Element.WEST:dx=sx/2;dy=0;break;case EJSS_DRAWING2D.Element.NORTH_EAST:dx=-(sx/2);dy=-(sy/2);break;case EJSS_DRAWING2D.Element.NORTH_WEST:dx=sx/2;dy=-(sy/2);break;case EJSS_DRAWING2D.Element.SOUTH_EAST:dx=-(sx/2);dy=sy/2;break;case EJSS_DRAWING2D.Element.SOUTH_WEST:dx=sx/2;dy=sy/2;break}if(typeof invertedy!="undefined"&&invertedy)dy=-dy;return[dx,dy]},getSWRelativePositionOffset:function(position,sx,sy,invertedy){var dx=0;var dy=0;switch(position){default:case EJSS_DRAWING2D.Element.CENTER:dx=-(sx/2);dy=sy/2;break;case EJSS_DRAWING2D.Element.NORTH:dx=-(sx/2);dy=sy;break;case EJSS_DRAWING2D.Element.SOUTH:dx=-(sx/2);dy=0;break;case EJSS_DRAWING2D.Element.EAST:dx=-sx;dy=sy/2;break;case EJSS_DRAWING2D.Element.WEST:dx=0;dy=sy/2;break;case EJSS_DRAWING2D.Element.NORTH_EAST:dx=-sx;dy=sy;break;case EJSS_DRAWING2D.Element.NORTH_WEST:dx=0;dy=sy;break;case EJSS_DRAWING2D.Element.SOUTH_EAST:dx=-sx;dy=0;break;case EJSS_DRAWING2D.Element.SOUTH_WEST:dx=0;dy=0;break}if(typeof invertedy!="undefined"&&invertedy)dy=-dy;return[dx,dy]}};EJSS_DRAWING2D.element=function(mName){var self={};var Element=EJSS_DRAWING2D.Element;var PanelInteraction=EJSS_DRAWING2D.PanelInteraction;var mStyle=EJSS_DRAWING2D.style(mName);var mVisible=true;var mMeasured=true;var mRelativePosition=Element.CENTER;var mX=0;var mY=0;var mPixelPosition=false;var mSizeX=1;var mSizeY=1;var mPixelSize=false;var mTransformation=[];var mRotate=0;var mInteraction={positionTarget:EJSS_DRAWING2D.interactionTarget(self,PanelInteraction.TARGET_POSITION,Element.CENTER),sizeTarget:EJSS_DRAWING2D.interactionTarget(self,PanelInteraction.TARGET_SIZE,Element.NORTH_EAST)};var mPanel=null;var mGroup=null;var mSet=null;var mIndexInSet=-1;var mProjectedPosition=[];var mProjectedSize=[];var mMustProject=true;var mElementChanged=true;var mController={propertiesChanged:function(){},invokeAction:function(){}};var mCustomObject=null;self.getName=function(){return mName};self.setParent=function(parent,sibling){if(parent.render){self.setGroup(null);parent.addElement(self);self.setPanel(parent)}else if(parent._23()=="ElementGroup"){self.setGroup(parent);self.getGroupPanel().addElement(self,sibling);self.setPanel(self.getGroupPanel())}else{console.log("WARNING: setParent() - Parent not valid : "+parent.getName())}};self.getParent=function(){var parent;if(mGroup!==null)parent=self.getGroup();else parent=self.getPanel();return parent};self.isGroup=function(){return false};self.getStyle=function(){return mStyle};self.setCustomObject=function(object){mCustomObject=object};self.getCustomObject=function(){return mCustomObject};self.setX=function(x,dummy){if(mX!=x){mX=x;mElementChanged=true}};self.getX=function(){return mX};self.setY=function(y){if(mY!=y){mY=y;mElementChanged=true}};self.getY=function(){return mY};self.setPosition=function(position){self.setX(position[0]);self.setY(position[1])};self.getPosition=function(){return[mX,mY]};self.setPixelPosition=function(pixel){if(mPixelPosition!=pixel){mPixelPosition=pixel;mElementChanged=true}};self.isPixelPosition=function(){return mPixelPosition};self.setSizeX=function(sizeX){if(mSizeX!=sizeX){mSizeX=sizeX;mElementChanged=true}};self.getSizeX=function(){return mSizeX};self.setSizeY=function(sizeY){if(mSizeY!=sizeY){mSizeY=sizeY;mElementChanged=true}};self.getSizeY=function(){return mSizeY};self.setSize=function(size){self.setSizeX(size[0]);self.setSizeY(size[1])};self.getSize=function(){return[self.getSizeX(),self.getSizeY()]};self.setPixelSize=function(pixel){if(mPixelSize!=pixel){mPixelSize=pixel;mElementChanged=true}};self.isPixelSize=function(){return mPixelSize};self.setBounds=function(bounds){var left,right,top,bottom;if(bounds.left){left=bounds.left;right=bounds.right;top=bounds.top;bottom=bounds.bottom}else{left=bounds[0];right=bounds[1];top=bounds[2];bottom=bounds[3]}var sx=right-left;var sy=bottom-top;var d=self.getRelativePositionOffset(sx,sy);var mx=sx/2,my=sy/2;var x=left+mx-d[0];var y=top+my-d[1];self.setX(x);self.setY(y);self.setSizeX(sx);self.setSizeY(sy)};self.getBounds=function(){var size=mPixelSize?mPanel.toPanelMod([mSizeX,-mSizeY]):[mSizeX,mSizeY];var mx=size[0]/2,my=size[1]/2;var d=self.getRelativePositionOffset(size[0],size[1]);return{left:mX+d[0]-mx,right:mX+d[0]+mx,top:mY+d[1]+my,bottom:mY+d[1]-my}};self.getAbsoluteBounds=function(withTransf){var bounds=self.getBounds();var p1=self.toGroupSpace([bounds.left,bounds.top],withTransf);var p2=self.toGroupSpace([bounds.right,bounds.bottom],withTransf);return{left:p1[0],top:p1[1],right:p2[0],bottom:p2[1]}};self.setRelativePosition=function(position){if(typeof position=="string")position=Element[position.toUpperCase()];if(mRelativePosition!=position){mRelativePosition=position;mElementChanged=true}};self.getRelativePosition=function(){return mRelativePosition};self.getRelativePositionOffset=function(s1,s2){var sx,sy;if(Array.isArray(s1)){sx=s1[0];sy=s1[1]}else{sx=s1;sy=s2}var invertedScale=mPanel.getInvertedScaleY?mPanel.getInvertedScaleY():false;return Element.getRelativePositionOffset(mRelativePosition,sx,sy,invertedScale)};self.setVisible=function(visible){if(visible!=mVisible){mVisible=visible;mElementChanged=true}};self.isVisible=function(){return mVisible};self.isGroupVisible=function(){var el=mGroup;while(typeof el!="undefined"&&el!==null){if(!el.isVisible())return false;el=el.getGroup()}return mVisible};self.setMeasured=function(measured){mMeasured=measured};self.isMeasured=function(){return mMeasured};self.setTransformation=function(trans){if(typeof trans=="undefined"||trans===null){mTransformation=[]}else if(Array.isArray(trans)&&trans.length>5){if(!EJSS_TOOLS.compareArrays(mTransformation,trans)){mTransformation=trans.slice();mElementChanged=true}}else if(mRotate!=trans){mRotate=trans;mElementChanged=true}};self.getTransformation=function(){return mTransformation};self.setRotate=function(angle){if(mRotate!=angle){mRotate=angle;mElementChanged=true}};self.getRotate=function(){return mRotate};self.setScaleX=function(rate){if(mTransformation.length==0)mTransformation=[1,0,0,1,0,0];if(mTransformation[0]!=rate){mTransformation[0]=rate;mElementChanged=true}};self.getScaleX=function(){if(mTransformation.length==0)return 1;else return mTransformation[0]};self.setScaleY=function(rate){if(mTransformation.length==0)mTransformation=[1,0,0,1,0,0];if(mTransformation[3]!=rate){mTransformation[3]=rate;mElementChanged=true}};self.getScaleY=function(){if(mTransformation.length==0)return 1;else return mTransformation[3]};self.setSkewX=function(angle){if(mTransformation.length==0)mTransformation=[1,0,0,1,0,0];if(mTransformation[2]!=angle){mTransformation[2]=angle;mElementChanged=true}};self.getSkewX=function(){if(mTransformation.length==0)return 0;else return mTransformation[2]};self.setSkewY=function(angle){if(mTransformation.length==0)mTransformation=[1,0,0,1,0,0];if(mTransformation[1]!=angle){mTransformation[1]=angle;mElementChanged=true}};self.getSkewY=function(){if(mTransformation.length==0)return 0;else return mTransformation[1]};self.getInfo=function(){var info="x="+mX.toFixed(2)+" y="+mY.toFixed(2);return info};self.setPanel=function(panel){mPanel=panel;mMustProject=true};self.getPanel=function(){return mPanel};self.getGroupPanel=function(){var el=self;while(el.getGroup())el=el.getGroup();return el.getPanel()};self.setGroup=function(group){mGroup=group;mElementChanged=true};self.getGroup=function(){return mGroup};self.setSet=function(set,index){mSet=set;mIndexInSet=index};self.getSet=function(){return mSet};self.getSetIndex=function(){return mIndexInSet};self.isChanged=function(){return mElementChanged};self.setChanged=function(changed){mElementChanged=changed};self.isGroupChanged=function(){var el=self.getGroup();while(typeof el!="undefined"&&el!==null){if(el.isChanged())return true;el=el.getGroup()}return false};self.setMustProject=function(needsIt){mMustProject=needsIt};self.isMustProject=function(){return mMustProject};self.getPixelPosition=function(withTransf){if(self.isChanged()||self.isGroupChanged()||self.isMustProject()||withTransf){mProjectedPosition=self.getPixelPositionOf(mX,mY,withTransf);mProjectedSize=self.getPixelSizeOf(mSizeX,mSizeY);self.setMustProject(withTransf)}return mProjectedPosition};self.getPixelSizes=function(withTransf){if(self.isChanged()||self.isGroupChanged()||self.isMustProject()){mProjectedPosition=self.getPixelPositionOf(mX,mY,withTransf);mProjectedSize=self.getPixelSizeOf(mSizeX,mSizeY);self.setMustProject(withTransf)}return mProjectedSize};self.getAbsoluteSize=function(){var size=mPixelSize?mPanel.toPanelMod([mSizeX,-mSizeY]):[mSizeX,mSizeY];return self.toGroupSpaceMod(size)};self.getAbsolutePosition=function(withTransf){var pos;if(mPixelPosition){if(mGroup===null)pos=mPanel.toPanelPosition([mX,mY]);else pos=mPanel.toPanelPosition([mX,mY],EJSS_DRAWING2D.DrawingPanel.SCALE_NUM)}else{pos=[mX,mY]}return self.toGroupSpace(pos,withTransf)};self.setAbsolutePosition=function(position){if(mPixelPosition){console.log("setAbsolutePosition not supported!")}else{self.setPosition(self.toElementSpace(position))}};self.setAbsoluteX=function(x){if(mPixelPosition){console.log("setAbsoluteX not supported!")}else{self.setX(self.toElementSpace([x,0])[0])}};self.setAbsoluteY=function(y){if(mPixelPosition){console.log("setAbsoluteY not supported!")}else{self.setY(self.toElementSpace([0,y])[1])}};self.getPixelSizeOf=function(sx,sy){if(mPixelSize)return[sx,-sy];else return self.getGroupPanel().toPixelMod(self.toGroupSpaceMod([sx,sy]))};self.getPixelPositionOf=function(x,y,withTransf){if(mPixelPosition){if(mGroup){var groupPos=mGroup.getPixelPosition();return[groupPos[0]+x,groupPos[1]-y]}return[self.getGroupPanel().toPixelAxisX(x),self.getGroupPanel().toPixelAxisY(y)]}else{if(mGroup===null)return self.getGroupPanel()._26(self.toGroupSpace([x,y]));return self.getGroupPanel()._26(self.toGroupSpace([x,y],withTransf),EJSS_DRAWING2D.DrawingPanel.SCALE_NUM)}};self.toGroupSpaceMod=function(mod){var el=mGroup;while(typeof el!="undefined"&&el!==null){mod[0]*=el.getSizeX();mod[1]*=el.getSizeY();el=el.getGroup()}return mod};self.toGroupSpace=function(point,withTransf){var el=mGroup;while(typeof el!="undefined"&&el!==null){point[0]*=el.getSizeX();point[1]*=el.getSizeY();point[0]+=el.getX();point[1]+=el.getY();el=el.getGroup()}if(withTransf){el=mGroup;while(typeof el!="undefined"&&el!==null){var trans=el.getTransformation();if(Array.isArray(trans)){point[0]=trans.a*point[0]+trans.c*point[1]+trans.e;point[1]=trans.b*point[0]+trans.d*point[1]+trans.f}else if(typeof trans==="number"){var pos=el.getAbsolutePosition();point=EJSS_TOOLS.Mathematics.rotate(pos,point,-trans)}el=el.getGroup()}}return point};self.toElementSpace=function(point){var list=[];var el=mGroup;while(typeof el!="undefined"&&el!==null){list.push(el);el=el.getGroup()}list=list.reverse();var listLength=list.length;for(var i=0;i<listLength;i++){var el=list[i];point[0]-=el.getX();point[1]-=el.getY();if(el.getSizeX()==0)point[0]=0;else point[0]/=el.getSizeX();if(el.getSizeY()==0)point[1]=0;else point[1]/=el.getSizeY()}return point};self.getController=function(){return mController};self.setController=function(controller){mController=controller};self.getInteractionTarget=function(target){switch(target){case PanelInteraction.TARGET_POSITION:return mInteraction.positionTarget;case PanelInteraction.TARGET_SIZE:return mInteraction.sizeTarget}return null};self.getInteractionTargets=function(){return[mInteraction.positionTarget,mInteraction.sizeTarget]};self.getInteractionInformation=function(){return{info:self.getPosition(),element:self,point:self.getGroupPanel().getPanelInteraction().getInteractionPoint()}};self.getOnDoubleClickInformation=function(){var info=self.getInteractionInformation();info.action="OnDoubleClick";return info};self.getOnEnterInformation=function(){var info=self.getInteractionInformation();info.action="OnEnter";return info};self.getOnExitInformation=function(){var info=self.getInteractionInformation();info.action="OnExit";return info};self.getOnPressInformation=function(){var info=self.getInteractionInformation();info.action="OnPress";return info};self.getOnDragInformation=function(){var info=self.getInteractionInformation();info.action="OnDrag";return info};self.getOnReleaseInformation=function(){var info=self.getInteractionInformation();info.action="OnRelease";return info};self.registerProperties=function(controller){EJSS_DRAWING2D.Element.registerProperties(self,controller)};self.copyTo=function(element){EJSS_DRAWING2D.Element.copyTo(self,element)};self.serialize=function(){return{mStyle:mStyle.serialize(),mVisible:mVisible,mMeasured:mMeasured,mRelativePosition:mRelativePosition,mX:mX,mY:mY,mPixelPosition:mPixelPosition,mSizeX:mSizeX,mSizeY:mSizeY,mPixelSize:mPixelSize,mTransformation:mTransformation,mInteraction:{},mPanel:mPanel?mPanel.getName():mPanel,mGroup:mGroup?mGroup.getName():mGroup,mSet:mSet?mSet.getName():mSet,mIndexInSet:mIndexInSet,mProjectedPosition:mProjectedPosition,mProjectedSize:mProjectedSize}};self.unserialize=function(json){mStyle.unserialize(json.mStyle),mVisible=json.mVisible,mMeasured=json.mMeasured,mRelativePosition=json.mRelativePosition,mX=json.mX,mY=json.mY,mPixelPosition=json.mPixelPosition,mSizeX=json.mSizeX,mSizeY=json.mSizeY,mPixelSize=json.mPixelSize,mTransformation=json.mTransformation,mIndexInSet=json.mIndexInSet,mProjectedPosition=json.mProjectedPosition,mProjectedSize=json.mProjectedSize,mElementChanged=true};mStyle.setChangeListener(function(change){mElementChanged=true});return self};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.ElementSet={registerProperties:function(set,controller){var TARGET_POSITION=EJSS_DRAWING2D.PanelInteraction.TARGET_POSITION;var TARGET_SIZE=EJSS_DRAWING2D.PanelInteraction.TARGET_SIZE;set.setController(controller);set.setToEach(function(element,value){element.setController(value)},controller);controller.registerProperty("Parent",function(panel){set.setParent(panel);set.setToEach(function(element,value){element.setParent(value)},set)});controller.registerProperty("NumberOfElements",set.setNumberOfElements);controller.registerProperty("ElementInteracted",set.setElementInteracted,set.getElementInteracted);controller.registerProperty("X",function(v){set.setToEach(function(element,value){element.setX(value)},v)},function(){return set.getFromEach(function(element){return element.getX()})});controller.registerProperty("Y",function(v){set.setToEach(function(element,value){element.setY(value)},v)},function(){return set.getFromEach(function(element){return element.getY()})});controller.registerProperty("Position",function(v){set.setToEach(function(element,value){element.setPosition(value)},v)},function(){return set.getFromEach(function(element){return element.getPosition()})});controller.registerProperty("PixelPosition",function(v){set.setToEach(function(element,value){element.setPixelPosition(value)},v)});controller.registerProperty("Diameter",function(v){set.setToEach(function(element,value){element.setSize([value,value])},v)});controller.registerProperty("Radius",function(v){set.setToEach(function(element,value){element.setSize([value*2,value*2])},v)});controller.registerProperty("SizeX",function(v){set.setToEach(function(element,value){element.setSizeX(value)},v)},function(){return set.getFromEach(function(element){return element.getSizeX()})});controller.registerProperty("SizeY",function(v){set.setToEach(function(element,value){element.setSizeY(value)},v)},function(){return set.getFromEach(function(element){return element.getSizeY()})});controller.registerProperty("Size",function(v){set.setToEach(function(element,value){element.setSize(value)},v)},function(){return set.getFromEach(function(element){return element.getSize()})});controller.registerProperty("PixelSize",function(v){set.setToEach(function(element,value){element.setPixelSize(value)},v)});controller.registerProperty("Bounds",function(bounds){var setBounds=function(element,bound){element.setX(bound[0]);element.setY(bound[2]);element.setSizeX(bound[1]-bound[0]);element.setSizeY(bound[3]-bound[2])};set.setToEach(setBounds,bounds)},function(){var getBounds=function(element){return[element.getX(),element.getX()+element.getSizeX(),element.getY(),element.getY()+element.getSizeY()]};return set.getFromEach(getBounds)});controller.registerProperty("Visibility",function(v){set.setToEach(function(element,value){element.setVisible(value)},v)});controller.registerProperty("Measured",function(v){set.setToEach(function(element,value){element.setMeasured(value)},v)});controller.registerProperty("Transformation",function(v){set.setToEach(function(element,value){element.setTransformation(value)},v)});controller.registerProperty("Rotate",function(v){set.setToEach(function(element,value){element.setRotate(value)},v)});controller.registerProperty("ScaleX",function(v){set.setToEach(function(element,value){element.setScaleX(value)},v)});controller.registerProperty("ScaleY",function(v){set.setToEach(function(element,value){element.setScaleY(value)},v)});controller.registerProperty("SkewX",function(v){set.setToEach(function(element,value){element.setSkewX(value)},v)});controller.registerProperty("SkewY",function(v){set.setToEach(function(element,value){element.setSkewY(value)},v)});controller.registerProperty("RelativePosition",function(v){set.setToEach(function(element,value){element.setRelativePosition(value)},v)});controller.registerProperty("LineColor",function(v){set.setToEach(function(element,value){element.getStyle().setLineColor(value)},v)});controller.registerProperty("LineWidth",function(v){set.setToEach(function(element,value){element.getStyle().setLineWidth(value)},v)});controller.registerProperty("DrawLines",function(v){set.setToEach(function(element,value){element.getStyle().setDrawLines(value)},v)});controller.registerProperty("FillColor",function(v){set.setToEach(function(element,value){element.getStyle().setFillColor(value)},v)});controller.registerProperty("DrawFill",function(v){set.setToEach(function(element,value){element.getStyle().setDrawFill(value)},v)});controller.registerProperty("Attributes",function(v){set.setToEach(function(element,value){element.getStyle().setAttributes(value)},v)});controller.registerProperty("ShapeRendering",function(v){set.setToEach(function(element,value){element.getStyle().setShapeRendering(value)},v)});controller.registerProperty("EnabledPosition",function(v){set.setToEach(function(element,value){element.getInteractionTarget(TARGET_POSITION).setMotionEnabled(value)},v)});controller.registerProperty("MovesGroup",function(v){set.setToEach(function(element,value){element.getInteractionTarget(TARGET_POSITION).setAffectsGroup(value)},v)});controller.registerProperty("EnabledSize",function(v){set.setToEach(function(element,value){element.getInteractionTarget(TARGET_SIZE).setMotionEnabled(value)},v)});controller.registerProperty("ResizesGroup",function(v){set.setToEach(function(element,value){element.getInteractionTarget(TARGET_SIZE).setAffectsGroup(value)},v)});controller.registerProperty("Sensitivity",function(v){set.setToEach(function(element,value){element.getInteractionTarget(TARGET_POSITION).setSensitivity(value);element.getInteractionTarget(TARGET_SIZE).setSensitivity(value)},v)});var dataFunction=function(){var panel=set.getGroupPanel();var index=panel.getPanelInteraction().getIndexElement();var element=panel.getElements()[index];var elementIndex=element.getSetIndex();set.setElementInteracted(elementIndex);controller.propertiesChanged("ElementInteracted");return{index:elementIndex,position:element.getPosition()}};controller.registerAction("OnDoubleClick",dataFunction);controller.registerAction("OnEnter",dataFunction);controller.registerAction("OnExit",dataFunction);controller.registerAction("OnPress",dataFunction);controller.registerAction("OnDrag",dataFunction);controller.registerAction("OnRelease",dataFunction)}};EJSS_DRAWING2D.elementSet=function(mConstructor,mName){var self=EJSS_DRAWING2D.group(mName);var ElementSet=EJSS_DRAWING2D.ElementSet;var mElementList=[];var mNumberOfElementsSet=false;var mElementInteracted=-1;var mLastElementList=[];self.setNumberOfElements=function(numberOfElements){mNumberOfElementsSet=true;adjustNumberOfElements(numberOfElements)};function adjustNumberOfElements(numberOfElements){var name=self.getName?self.getName():"unnamed";numberOfElements=Math.max(1,numberOfElements);var diff=mElementList.length-numberOfElements;if(diff>0){mLastElementList=mElementList.splice(numberOfElements,diff);for(var j=0;j<mLastElementList.length;j++){var panel=mLastElementList[j].getPanel();if(panel)panel.removeElement(mLastElementList[j])}}else if(diff<0){mLastElementList=[];var controller=self.getController();var oldElement=mElementList[mElementList.length-1];for(var i=mElementList.length;i<numberOfElements;i++){var element=mConstructor(name+"["+i+"]");element.setSet(self,i);oldElement.copyTo(element);element.setController(controller);mElementList.push(element)}}}self.getElements=function(){return mElementList};self.getElement=function(index){return mElementList[index]};self.getLastElements=function(){var ret=mLastElementList.slice();mLastElementList=[];return ret};self.setElementInteracted=function(index){mElementInteracted=index};self.getElementInteracted=function(){return mElementInteracted};var super_setPanel=self.setPanel;self.setPanel=function(panel){super_setPanel(panel);for(var i=0,n=mElementList.length;i<n;i++)mElementList[i].setPanel(panel)};self.setToEach=function(f,v){if(Array.isArray(v)){if(!mNumberOfElementsSet){if(mElementList.length<v.length)adjustNumberOfElements(v.length)}for(var i=0,n=Math.min(mElementList.length,v.length);i<n;i++)f(mElementList[i],v[i])}else{for(var i=0,n=mElementList.length;i<n;i++)f(mElementList[i],v)}};self.getFromEach=function(f){var value=[];for(var i=0,n=mElementList.length;i<n;i++)value[i]=f(mElementList[i]);return value};self.registerProperties=function(controller){ElementSet.registerProperties(self,controller)};var element=mConstructor(mName+"[0]");element.setController(self.getController());element.setSet(self,0);mElementList.push(element);return self};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.Grid={SCALE_NUM:0,SCALE_LOG:1,registerProperties:function(element,controller){EJSS_DRAWING2D.Element.registerProperties(element,controller);controller.registerProperty("StepX",element.setStepX,element.getStepX);controller.registerProperty("StepY",element.setStepY,element.getStepY);controller.registerProperty("TicksX",element.setTicksX,element.getTicksX);controller.registerProperty("TicksY",element.setTicksY,element.getTicksY);controller.registerProperty("TickStepX",element.setTickStepX,element.getTickStepX);controller.registerProperty("TickStepY",element.setTickStepY,element.getTickStepY);controller.registerProperty("TicksXMode",element.setTicksXMode,element.getTicksXMode);controller.registerProperty("TicksYMode",element.setTicksYMode,element.getTicksYMode);controller.registerProperty("ShowX",element.setShowX,element.getShowX);controller.registerProperty("ShowY",element.setShowY,element.getShowY);controller.registerProperty("FixedTickX",element.setFixedTickX,element.getFixedTickX);controller.registerProperty("FixedTickY",element.setFixedTickY,element.getFixedTickY);controller.registerProperty("ScaleX",element.setScaleX,element.getScaleX);controller.registerProperty("ScaleY",element.setScaleY,element.getScaleY);controller.registerProperty("ScalePrecisionX",element.setScalePrecisionX,element.getScalePrecisionX);controller.registerProperty("ScalePrecisionY",element.setScalePrecisionY,element.getScalePrecisionY);controller.registerProperty("AutoTicksX",element.setAutoTicksX,element.getAutoTicksX);controller.registerProperty("AutoTicksY",element.setAutoTicksY,element.getAutoTicksY);controller.registerProperty("AutoStepXMin",element.setAutoStepXMin,element.getAutoStepXMin);controller.registerProperty("AutoStepYMin",element.setAutoStepYMin,element.getAutoStepYMin);controller.registerProperty("AutoTicksXRange",element.setAutoTicksXRange,element.getAutoTicksXRange);controller.registerProperty("AutoTicksYRange",element.setAutoTicksYRange,element.getAutoTicksYRange);controller.registerProperty("LineColorX",element.setLineColorX,element.getLineColorX);controller.registerProperty("LineWidthX",element.setLineWidthX,element.getLineWidthX);controller.registerProperty("ShapeRenderingX",element.setShapeRenderingX,element.getShapeRenderingX);controller.registerProperty("LineColorY",element.setLineColorY,element.getLineColorY);controller.registerProperty("LineWidthY",element.setLineWidthY,element.getLineWidthY);controller.registerProperty("ShapeRenderingY",element.setShapeRenderingY,element.getShapeRenderingY)}};EJSS_DRAWING2D.grid=function(name){var self=EJSS_DRAWING2D.element(name);var mAutoTicksX=true;var mAutoTicksY=true;var mTicksX=0;var mTicksY=0;var mStepX=0;var mStepY=0;var mTickStepX=0;var mTickStepY=0;var mShowX=true;var mShowY=true;var mFixedTickX=Number.NaN;var mFixedTickY=Number.NaN;var mScaleX=[-1,1];var mScaleY=[-1,1];var mScalePrecisionX=1;var mScalePrecisionY=1;var mTicksXMode=EJSS_DRAWING2D.Grid.SCALE_NUM;var mTicksYMode=EJSS_DRAWING2D.Grid.SCALE_NUM;var mAutoStepXMin=40;var mAutoStepYMin=40;var mAutoTicksXRange=[5,10,20];var mAutoTicksYRange=[5,10,20];var mLineColorX="black";var mLineWidthX=.5;var mShapeRenderingX=EJSS_DRAWING2D.Style.RENDER_AUTO;var mLineColorY="black";var mLineWidthY=.5;var mShapeRenderingY=EJSS_DRAWING2D.Style.RENDER_AUTO;self._23=function(){return"ElementGrid"};self.setAutoTicksRangeY=function(range){if(mAutoTicksYRange!=range){mAutoTicksYRange=range;self.setChanged(true)}};self.getAutoTicksRangeY=function(){return mAutoTicksYRange};self.setAutoTicksRangeX=function(range){if(mAutoTicksXRange!=range){mAutoTicksXRange=range;self.setChanged(true)}};self.getAutoTicksRangeX=function(){return mAutoTicksXRange};self.setAutoStepYMin=function(min){if(mAutoStepYMin!=min){mAutoStepYMin=min;self.setChanged(true)}};self.getAutoStepYMin=function(){return mAutoStepYMin};self.setAutoStepXMin=function(min){if(mAutoStepXMin!=min){mAutoStepXMin=min;self.setChanged(true)}};self.getAutoStepXMin=function(){return mAutoStepXMin};self.setScaleY=function(scale){if(mScaleY!=scale){mScaleY=scale;self.setChanged(true)}};self.getScaleY=function(){return mScaleY};self.setScaleX=function(scale){if(mScaleX!=scale){mScaleX=scale;self.setChanged(true)}};self.getScaleX=function(){return mScaleX};self.setScalePrecisionX=function(scalePrecisionX){if(mScalePrecisionX!=scalePrecisionX){mScalePrecisionX=scalePrecisionX;self.setChanged(true)}};self.getScalePrecisionX=function(){return mScalePrecisionX};self.setScalePrecisionY=function(scalePrecisionY){if(mScalePrecisionY!=scalePrecisionY){mScalePrecisionY=scalePrecisionY;self.setChanged(true)}};self.getScalePrecisionY=function(){return mScalePrecisionY};self.setFixedTickX=function(fixed){if(mFixedTickX!=fixed){mFixedTickX=fixed;self.setChanged(true)}};self.getFixedTickX=function(){return mFixedTickX};self.setFixedTickY=function(fixed){if(mFixedTickY!=fixed){mFixedTickY=fixed;self.setChanged(true)}};self.getFixedTickY=function(){return mFixedTickY};self.setAutoTicksX=function(auto){if(mAutoTicksX!=auto){mAutoTicksX=auto;self.setChanged(true)}};self.getAutoTicksX=function(){return mAutoTicksX};self.setAutoTicksY=function(auto){if(mAutoTicksY!=auto){mAutoTicksY=auto;self.setChanged(true)}};self.getAutoTicksY=function(){return mAutoTicksY};self.setStepX=function(stepX){if(mStepX!=stepX){mStepX=stepX;self.setChanged(true)}};self.getStepX=function(){return mStepX};self.setStepY=function(stepY){if(mStepY!=stepY){mStepY=stepY;self.setChanged(true)}};self.getStepY=function(){return mStepY};self.setTickStepX=function(TickStepX){if(mTickStepX!=TickStepX){mTickStepX=TickStepX;self.setChanged(true)}};self.getTickStepX=function(){return mTickStepX}
;self.setTickStepY=function(TickStepY){if(mTickStepY!=TickStepY){mTickStepY=TickStepY;self.setChanged(true)}};self.getTickStepY=function(){return mTickStepY};self.setTicksX=function(ticksX){if(mTicksX!=ticksX){mTicksX=ticksX;self.setChanged(true)}};self.getTicksX=function(){return mTicksX};self.setTicksY=function(ticksY){if(mTicksY!=ticksY){mTicksY=ticksY;self.setChanged(true)}};self.getTicksY=function(){return mTicksY};self.setTicksXMode=function(ticksXMode){if(typeof ticksXMode=="string")ticksXMode=EJSS_DRAWING2D.Grid[ticksXMode.toUpperCase()];if(mTicksXMode!=ticksXMode){mTicksXMode=ticksXMode;self.setChanged(true)}};self.getTicksXMode=function(){return mTicksXMode};self.setTicksYMode=function(ticksYMode){if(typeof ticksYMode=="string")ticksXMode=EJSS_DRAWING2D.Grid[ticksYMode.toUpperCase()];if(mTicksYMode!=ticksYMode){mTicksYMode=ticksYMode;self.setChanged(true)}};self.setShowX=function(show){if(mShowX!=show){mShowX=show;self.setChanged(true)}};self.getShowX=function(){return mShowX};self.setShowY=function(show){if(mShowY!=show){mShowY=show;self.setChanged(true)}};self.getShowY=function(){return mShowY};self.getTicksYMode=function(){return mTicksYMode};self.setLineColorX=function(color){if(typeof color!=="string")color=EJSS_TOOLS.DisplayColors.getLineColor(color);if(color!=mLineColorX){mLineColorX=color;self.setChanged(true)}return self};self.getLineColorX=function(){return mLineColorX};self.setLineWidthX=function(width){if(width!=mLineWidthX){mLineWidthX=width;self.setChanged(true)}};self.getLineWidthX=function(){return mLineWidthX};self.setShapeRenderingX=function(rendering){if(rendering.substring(0,6)=="RENDER")rendering=EJSS_DRAWING2D.Style[rendering.toUpperCase()];if(mShapeRenderingX!=rendering){mShapeRenderingX=rendering;self.setChanged(true)}};self.getShapeRenderingX=function(){return mShapeRenderingX};self.setLineColorY=function(color){if(typeof color!=="string")color=EJSS_TOOLS.DisplayColors.getLineColor(color);if(color!=mLineColorY){mLineColorY=color;self.setChanged(true)}return self};self.getLineColorY=function(){return mLineColorY};self.setLineWidthY=function(width){if(width!=mLineWidthY){mLineWidthY=width;self.setChanged(true)}};self.getLineWidthY=function(){return mLineWidthY};self.setShapeRenderingY=function(rendering){if(rendering.substring(0,6)=="RENDER")rendering=EJSS_DRAWING2D.Style[rendering.toUpperCase()];if(mShapeRenderingY!=rendering){mShapeRenderingY=rendering;self.setChanged(true)}};self.getShapeRenderingY=function(){return mShapeRenderingY};self.registerProperties=function(controller){EJSS_DRAWING2D.Grid.registerProperties(self,controller)};return self};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.Group={};EJSS_DRAWING2D.group=function(name){var self=EJSS_DRAWING2D.element(name);self._23=function(){return"ElementGroup"};self.isGroup=function(){return true};return self};EJSS_DRAWING2D.GroupSet={};EJSS_DRAWING2D.groupSet=function(mName){};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.Histogram={};EJSS_DRAWING2D.histogram=function(mName){};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.Image={copyTo:function(source,dest){EJSS_DRAWING2D.Element.copyTo(source,dest);dest.setImageUrl(source.getImageUrl())},registerProperties:function(element,controller){EJSS_DRAWING2D.Element.registerProperties(element,controller);controller.registerProperty("ImageUrl",element.setImageUrl);controller.registerProperty("Encode",element.setEncode)}};EJSS_DRAWING2D.image=function(name){var self=EJSS_DRAWING2D.element(name);var mUrl="";var mCode="";var mChangedImage=false;self._23=function(){return"ElementImage"};self.setImageUrl=function(url){var set=self.getSet();var resPathFunction=set!=null?set.getResourcePath:self.getResourcePath;if(resPathFunction!=null){url=resPathFunction(url)}else console.log("No getResourcePath function for "+self.getName()+". Texture="+url);if(mUrl!=url){mUrl=url;self.setChanged(true);self.setChangedImage(true)}};self.getImageUrl=function(){return mUrl};self.forceImageUrl=function(url){console.log("Setting image to "+url);mUrl=window.URL.createObjectURL(url);self.setChanged(true);self.setChangedImage(true)};self.setChangedImage=function(changed){mChangedImage=changed};self.getChangedImage=function(){return mChangedImage};self.setEncode=function(code){if(mCode.length!=code.length){mCode=code;self.setChanged(true);self.setChangedImage(true)}};self.getEncode=function(){return mCode};self.getImageData=function(callback){var size=self.getPixelSizes();var img=new Image;img.src=mUrl;var canvas=document.createElement("canvas");var context=canvas.getContext("2d");canvas.width=Math.abs(size[0])+1;canvas.height=Math.abs(size[1])+1;if(callback){img.onload=function(){context.drawImage(img,0,0,img.width,img.height,0,0,canvas.width,canvas.height);callback(context.getImageData(0,0,canvas.width,canvas.height))}}else{context.drawImage(img,0,0,img.width,img.height,0,0,canvas.width,canvas.height);return context.getImageData(0,0,canvas.width,canvas.height)}};self.registerProperties=function(controller){EJSS_DRAWING2D.Image.registerProperties(self,controller)};self.copyTo=function(element){EJSS_DRAWING2D.Image.copyTo(self,element)};return self};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.ImageSet={};EJSS_DRAWING2D.imageSet=function(mName){};var EJSS_CANVASGRAPHICS=EJSS_CANVASGRAPHICS||{};EJSS_CANVASGRAPHICS.analyticCurve=function(mContext,mElement){function drawAnalyticCurve(points,x,y,sx,sy){mContext.beginPath();for(var i=0;i<points.length;i++){var point=points[i];var xx=x+point[0]*sx;var yy=y+point[1]*sy;var type=point[2];if(i==0||type==0)mContext.moveTo(xx,yy);else mContext.lineTo(xx,yy)}}var pos=mElement.getPixelPosition();var size=mElement.getPixelSizes();var offset=mElement.getRelativePositionOffset(size);var x=pos[0]+offset[0];var y=pos[1]+offset[1];var mx=size[0]/2;var my=size[1]/2;var numPoints=mElement.getNumPoints();var mMinimun=mElement.getMinimun();var mMaximun=mElement.getMaximun();var min=typeof mMinimun=="undefined"||mMinimun===null?mElement.getPanel().getRealWorldXMin():mMinimun;var max=typeof mMaximun=="undefined"||mMaximun===null?mElement.getPanel().getRealWorldXMax():mMaximun;var vble=mElement.getVariable();var fx=mElement.getFunctionX();var fy=mElement.getFunctionY();var parser=EJSS_DRAWING2D.functionsParser();var exprfx;var exprfy;var mustReturn=false;try{exprfx=parser.parse(fx)}catch(errorfx){console.log("Analytic curve error parsing FunctionX: "+fx);mustReturn=true}if(!mustReturn){try{exprfy=parser.parse(fy)}catch(errorfy){console.log("Analytic curve error parsing FunctionY: "+fy);mustReturn=true}}if(mustReturn){mElement.getController().invokeAction("OnError");return}var step=(max-min)/(numPoints-1);var points=[];var vblevalue={};var parameters=mElement.getParameters();for(var param in parameters){vblevalue[param]=parameters[param]}try{for(var j=0,i=min;i<=max;i+=step){vblevalue[vble]=i;var fxvalue=exprfx.evaluate(vblevalue);var fyvalue=exprfy.evaluate(vblevalue);if(!isNaN(fxvalue)&&!isNaN(fyvalue)){points[j]=[];points[j][0]=fxvalue;points[j++][1]=fyvalue}}}catch(error){mElement.getController().invokeAction("OnError")}drawAnalyticCurve(points,x-mx,y-my,size[0],size[1]);var style=mElement.getStyle();if(style.getDrawFill()&&style.getFillColor()!="none"){mContext.fillStyle=style.getFillColor();mContext.fill()}if(style.getDrawLines()){mContext.lineWidth=style.getLineWidth();mContext.strokeStyle=style.getLineColor();mContext.stroke()}};var EJSS_CANVASGRAPHICS=EJSS_CANVASGRAPHICS||{};EJSS_CANVASGRAPHICS.arrow=function(mContext,mElement){var Arrow=EJSS_DRAWING2D.Arrow;function createMarkDef(px,py,mark,width,height,stroke,color,sizex,sizey){mContext.save();width/=2;height/=2;var angle=sizex==0?Math.PI/2:Math.atan(sizey/sizex);angle+=sizex<0?-Math.PI/2:Math.PI/2;switch(mark){case Arrow.TRIANGLE:mContext.beginPath();mContext.translate(px,py);mContext.rotate(angle);mContext.moveTo(0,height/2);mContext.lineTo(width,height/2);mContext.lineTo(0,-height/2);mContext.lineTo(-width,height/2);mContext.closePath();break;case Arrow.ANGLE:mContext.beginPath();mContext.translate(px,py);mContext.rotate(angle);mContext.moveTo(width,height);mContext.lineTo(0,0);mContext.lineTo(-width,height);break;case Arrow.LINE:mContext.beginPath();mContext.translate(px,py);mContext.rotate(angle);mContext.moveTo(width,0);mContext.lineTo(-width,0);break;case Arrow.RECTANGLE:mContext.beginPath();mContext.translate(px,py);mContext.rotate(angle);mContext.moveTo(0,-height);mContext.lineTo(width,-height);mContext.lineTo(width,height);mContext.lineTo(-width,height);mContext.lineTo(-width,-height);mContext.closePath();break;case Arrow.POINTED:mContext.beginPath();mContext.translate(px,py);mContext.rotate(angle);mContext.moveTo(0,height/4);mContext.lineTo(width,height);mContext.lineTo(0,-height/4);mContext.lineTo(-width,height);mContext.closePath();break;case Arrow.CIRCLE:var size=width<height?width:height;mContext.beginPath();mContext.translate(px,py);mContext.arc(0,0,size,0,2*Math.PI,false);break;case Arrow.DIAMOND:mContext.beginPath();mContext.translate(px,py);mContext.rotate(angle);mContext.moveTo(0,-height);mContext.lineTo(width,0);mContext.lineTo(0,height);mContext.lineTo(-width,0);mContext.closePath();break;case Arrow.INVTRIANGLE:mContext.beginPath();mContext.translate(px,py);mContext.rotate(angle);mContext.moveTo(0,-height/2);mContext.lineTo(-width,-height/2);mContext.lineTo(0,height/2);mContext.lineTo(width,-height/2);mContext.closePath();break;case Arrow.INVANGLE:mContext.beginPath();mContext.translate(px,py);mContext.rotate(angle);mContext.moveTo(-width,-height);mContext.lineTo(0,0);mContext.lineTo(width,-height);break;case Arrow.WEDGE:case Arrow.CURVE:console.log("Type of Arrow: not supported");break}if(color!="none"){if(mark!=Arrow.ANGLE&&mark!=Arrow.INVANGLE){mContext.fillStyle=color;mContext.fill()}if(mark!=Arrow.POINTED){mContext.lineWidth=stroke;mContext.strokeStyle=color;mContext.stroke()}}mContext.restore()}var pos=mElement.getPixelPosition();var size=mElement.getPixelSizes();var offset=mElement.getRelativePositionOffset(size);var x=pos[0]+offset[0];var y=pos[1]+offset[1];var mx=size[0]/2;var my=size[1]/2;if(size[0]!=0||size[1]!=0){mContext.beginPath();mContext.moveTo(x-mx,y-my);mContext.lineTo(x+mx,y+my);var style=mElement.getStyle();if(style.getDrawFill()&&style.getFillColor()!="none"){mContext.fillStyle=style.getFillColor();mContext.fill()}if(style.getDrawLines()){mContext.lineWidth=style.getLineWidth();mContext.strokeStyle=style.getLineColor();mContext.stroke()}if(mElement.getMarkEnd()!=Arrow.NONE){var endMax=mElement.getMarkProportion()*EJSS_TOOLS.Mathematics.norm([size[0],size[1]]);var endW=endMax!=0&&endMax<mElement.getMarkEndWidth()?endMax:mElement.getMarkEndWidth();var endH=endMax!=0&&endMax<mElement.getMarkEndHeight()?endMax:mElement.getMarkEndHeight();var color=mElement.getMarkEndColor()=="none"?mElement.getStyle().getLineColor():mElement.getMarkEndColor();var stroke=mElement.getMarkEndStroke()<0?mElement.getStyle().getLineWidth():mElement.getMarkEndStroke();createMarkDef(x+mx,y+my,mElement.getMarkEnd(),endW,endH,stroke,color,mx,my)}if(mElement.getMarkMiddle()!=Arrow.NONE){var midMax=mElement.getMarkProportion()*EJSS_TOOLS.Mathematics.norm([size[0],size[1]]);var midW=midMax!=0&&midMax<mElement.getMarkMiddleWidth()?midMax:mElement.getMarkMiddleWidth();var midH=midMax!=0&&midMax<mElement.getMarkMiddleHeight()?midMax:mElement.getMarkMiddleHeight();var color=mElement.getMarkMiddleColor()=="none"?mElement.getStyle().getLineColor():mElement.getMarkMiddleColor();var stroke=mElement.getMarkMiddleStroke()<0?mElement.getStyle().getLineWidth():mElement.getMarkMiddleStroke();createMarkDef(x,y,mElement.getMarkMiddle(),midW,midH,stroke,color,mx,my)}if(mElement.getMarkStart()!=Arrow.NONE){var stMax=mElement.getMarkProportion()*EJSS_TOOLS.Mathematics.norm([size[0],size[1]]);var stW=stMax!=0&&stMax<mElement.getMarkStartWidth()?stMax:mElement.getMarkStartWidth();var stH=stMax!=0&&stMax<mElement.getMarkStartHeight()?stMax:mElement.getMarkStartHeight();var color=mElement.getMarkStartColor()=="none"?mElement.getStyle().getLineColor():mElement.getMarkStartColor();var stroke=mElement.getMarkStartStroke()<0?mElement.getStyle().getLineWidth():mElement.getMarkStartStroke();createMarkDef(x-mx,y-my,mElement.getMarkStart(),stW,stH,stroke,color,mx,my)}}};var EJSS_CANVASGRAPHICS=EJSS_CANVASGRAPHICS||{};EJSS_CANVASGRAPHICS.axis=function(mContext,mElement){function drawLine(x,y,mx,my,orient,inverted){if(orient==EJSS_DRAWING2D.Axis.AXIS_VERTICAL){if(inverted){my=-my;y=-y}mContext.moveTo(x,y-my);mContext.lineTo(x,y+my)}else{mContext.moveTo(x-mx,y);mContext.lineTo(x+mx,y)}}function drawTick(x,y,ticksize,orient){if(orient==EJSS_DRAWING2D.Axis.AXIS_VERTICAL){mContext.moveTo(x-ticksize/2,y);mContext.lineTo(x+ticksize/2,y)}else{mContext.moveTo(x,y-ticksize/2);mContext.lineTo(x,y+ticksize/2)}}function tickText(x,y,text,font,horizontal){mContext.save();var font=mElement.getFont();var fondtxt="";fondtxt+=font.getFontStyle()!="none"?font.getFontStyle()+" ":"";fondtxt+=font.getFontWeight()!="none"?font.getFontWeight()+" ":"";fondtxt+=font.getFontSizeString()+"px ";fondtxt+=font.getFontFamily();mContext.font=fondtxt;mContext.fillStyle=font.getFillColor();if(horizontal){x-=mContext.measureText(text).width/2+.5}else{y+=font.getFontSize()/2}mContext.fillText(text,x,y);mContext.restore()}if(mElement.getShow()){var pos=mElement.getPixelPosition();var size=mElement.getPixelSizes();var offset=mElement.getRelativePositionOffset(size);var x=pos[0]+offset[0];var y=pos[1]+offset[1];var mx=size[0]/2;var my=size[1]/2;var style=mElement.getStyle();var orient=mElement.getOrient();var inverted=mElement.getInvertedScaleY();mContext.beginPath();drawLine(x,y,mx,my,orient,inverted);var segsize=orient==EJSS_DRAWING2D.Axis.AXIS_VERTICAL?Math.abs(size[1]):Math.abs(size[0]);var ticksmode=mElement.getTicksMode();if(ticksmode==EJSS_DRAWING2D.Axis.SCALE_LOG){var scale=mElement.getScale();if(scale[0]>0&&scale[1]>0){var ticks=mElement.getTicks();var scalePrecision=mElement.getScalePrecision();var ticksize=mElement.getTicksSize();EJSS_GRAPHICS.GraphicsUtils.drawLogTicks(x,y,mx,my,segsize,ticksize,scale,ticks,orient,drawTick);var font=mElement.getFont();var textPosition=mElement.getTextPosition();EJSS_GRAPHICS.GraphicsUtils.drawLogTicksText(x,y,mx,my,ticks,ticksize,scale,scalePrecision,font,textPosition,orient,tickText)}}else if(ticksmode==EJSS_DRAWING2D.Axis.SCALE_NUM){var step=0;var tickstep=0;if(!mElement.getAutoTicks()){var ticks=mElement.getTicks();if(ticks!=0){step=segsize/ticks}else{step=mElement.getStep();tickstep=mElement.getTickStep()}}else{var stepmin=mElement.getAutoStepMin();var ticksrange=mElement.getAutoTicksRange();for(var i=ticksrange.length-1;i>=0;i--){step=Math.abs(segsize/ticksrange[i]);if(step*1.001>=stepmin)break}}var scalePrecision=mElement.getScalePrecision();var scale=mElement.getScale();if(tickstep==0){var scalestep=Math.abs((scale[1]-scale[0])*step/segsize)}else{var scalestep=tickstep;step=Math.abs(scalestep*segsize/(scale[1]-scale[0]))}var decimals=Math.pow(10,scalePrecision);var scalestepTmp=Math.round(scalestep*decimals)/decimals;if(scalestepTmp>0){scalestep=scalestepTmp;step=Math.abs(scalestepTmp*segsize/(scale[1]-scale[0]))}var fixedTicks=mElement.getFixedTick();var tickfixed=scale[1];if(!isNaN(fixedTicks)){if(fixedTicks<scale[0])tickfixed=fixedTicks+(Math.floor((scale[0]-fixedTicks)/scalestep)+1)*scalestep;else if(fixedTicks>scale[1])tickfixed=fixedTicks-(Math.floor((fixedTicks-scale[1])/scalestep)+1)*scalestep;else tickfixed=fixedTicks}var scaleshift=Math.abs((scale[0]-tickfixed)%scalestep);var dist=Math.abs(scaleshift-scalestep);if(scaleshift<.001||dist<.001)scaleshift=0;var shift=segsize*scaleshift/Math.abs(scale[1]-scale[0]);var ticksize=mElement.getTicksSize();EJSS_GRAPHICS.GraphicsUtils.drawDecTicks(x,y,mx,my,ticksize,step,shift,orient,inverted,drawTick);var font=mElement.getFont();var textPosition=mElement.getTextPosition();EJSS_GRAPHICS.GraphicsUtils.drawDecTicksText(x,y,mx,my,ticksize,step,shift,scale,scalePrecision,scalestep,scaleshift,font,textPosition,orient,inverted,tickText)}var style=mElement.getStyle();if(style.getDrawFill()&&style.getFillColor()!="none"){mContext.fillStyle=style.getFillColor();mContext.fill()}if(style.getDrawLines()){mContext.lineWidth=style.getLineWidth();mContext.strokeStyle=style.getLineColor();mContext.stroke()}}};var EJSS_CANVASGRAPHICS=EJSS_CANVASGRAPHICS||{};EJSS_CANVASGRAPHICS.byteRaster=function(mContext,mElement){if(mElement.getDataChanged()){var data=mElement.getData();var colors=mElement.getColorMapper().getColors();var xlen=data.length;var ylen=data[0].length;var num=mElement.getColorMapper().getNumberOfColors();var pos=mElement.getPixelPosition();var size=mElement.getPixelSizes();var offset=mElement.getRelativePositionOffset(size);var x=pos[0]+offset[0];var y=pos[1]+offset[1];var mx=Math.abs(size[0]/2);var my=Math.abs(size[1]/2);var idcanvas=mContext.canvas.id;EJSS_SVGGRAPHICS.Utils.ImageDataCanvas(xlen,ylen,num,data,colors,function(img){var canvas=document.getElementById(idcanvas);mContext=canvas.getContext("2d");mContext.putImageData(img,x-mx,y-my)});mElement.setDataChanged(false)}};var EJSS_CANVASGRAPHICS=EJSS_CANVASGRAPHICS||{};EJSS_CANVASGRAPHICS.canvas=function(mContext,mElement){var pos=mElement.getPixelPosition();var size=mElement.getPixelSizes();var offset=mElement.getRelativePositionOffset(size);var x=pos[0]+offset[0];var y=pos[1]+offset[1];var dim=mElement.getDimensions();var deltaX=dim[1]-dim[0];var deltaY=dim[3]-dim[2];var pixWth=Math.abs(size[0]);var pixHgt=Math.abs(size[1]);var pxPerUnitX=pixWth/deltaX;var pxPerUnitY=pixHgt/deltaY;var pxTopLeftX=x-pixWth/2;var pxTopLeftY=y+pixHgt/2;var drawables=mElement.getDrawables();for(var i=0;i<drawables.length;i++){if(typeof drawables[i].imageField!="undefined")EJSS_GRAPHICS.GraphicsUtils.drawImageField(mContext,pxTopLeftX,pxTopLeftY,xMin,yMin,pixWth,pixHgt,pxPerUnitX,pxPerUnitY,drawables[i]);else if(typeof drawables[i].run!="undefined")drawables[i].draw(mContext,pxTopLeftX,pxTopLeftY,xMin,yMin,pixWth,pixHgt,pxPerUnitX,pxPerUnitY)}};var EJSS_CANVASGRAPHICS=EJSS_CANVASGRAPHICS||{};EJSS_CANVASGRAPHICS.cellLattice=function(mContext,mElement){function drawGrid(left,top,right,bottom,stepx,stepy){mContext.beginPath();if(stepx==0)stepx=Math.abs(right-left);for(var i=left;i<=right;i=i+stepx){mContext.moveTo(i,top);mContext.lineTo(i,bottom)}if(stepy==0)stepy=Math.abs(top-bottom);for(var i=bottom;i>=top;i=i-stepy){mContext.moveTo(left,i);mContext.lineTo(right,i)}}function rectCell(x,y,sx,sy,fill){mContext.beginPath();var mx=sx/2,my=sy/2;mContext.moveTo(x-mx,y+my);mContext.lineTo(x+mx,y+my);mContext.lineTo(x+mx,y-my);mContext.lineTo(x-mx,y-my);mContext.lineTo(x-mx,y+my);mContext.fillStyle=fill;mContext.fill();mContext.lineWidth=1;mContext.strokeStyle=fill;mContext.stroke()}function gridCell(x,y,sx,sy,stepx,stepy,style){var mx=sx/2,my=sy/2;var left=x-mx,right=x+mx,top=y+my,bottom=y-my;drawGrid(left,top,right,bottom,stepx,stepy);if(style.getDrawFill()&&style.getFillColor()!="none"){mContext.fillStyle=style.getFillColor();mContext.fill()}if(style.getDrawLines()){mContext.lineWidth=style.getLineWidth();mContext.strokeStyle=style.getLineColor();mContext.stroke()}}var pos=mElement.getPixelPosition();var size=mElement.getPixelSizes();var offset=mElement.getRelativePositionOffset(size);var x=pos[0]+offset[0];var y=pos[1]+offset[1];var mx=size[0]/2;var my=size[1]/2;var style=mElement.getStyle();var data=mElement.getData();var colors=mElement.getColorMapper().getColors();var xlen=data.length;var ylen=data[0].length;var stepx=Math.abs(size[0]/xlen);var stepy=Math.abs(size[1]/ylen);var left=x-mx+stepx/2,bottom=y-my-stepy/2;for(var i=0;i<ylen;i++){for(var j=0;j<xlen;j++){rectCell(left+stepx*j,bottom-stepy*i,stepx,stepy,colors[data[j][i]])}}var showGrid=mElement.getShowGrid();if(showGrid)gridCell(x,y,size[0],size[1],stepx,stepy,style)};var EJSS_CANVASGRAPHICS=EJSS_CANVASGRAPHICS||{};EJSS_CANVASGRAPHICS.cursor=function(mContext,mElement){var pos=mElement.getPixelPosition();var cursorType=mElement.getCursorType();var panel=mElement.getGroupPanel();var bounds=panel.getRealWorldCoordinates();var bottomLeft=panel._26([bounds[0],bounds[2]]);var topRight=panel._26([bounds[1],bounds[3]]);mContext.beginPath();if(cursorType!=EJSS_DRAWING2D.Cursor.VERTICAL){var x1=bottomLeft[0],x2=topRight[0];var y=pos[1];if(y>bottomLeft[1])y=bottomLeft[1];else if(y<topRight[1])y=topRight[1];mContext.moveTo(x1,y);mContext.lineTo(x2,y)}if(cursorType!=EJSS_DRAWING2D.Cursor.HORIZONTAL){var x=pos[0];var y1=bottomLeft[1],y2=topRight[1];if(x<bottomLeft[0])x=bottomLeft[0];else if(x>topRight[0])x=topRight[0];mContext.moveTo(x,y1);mContext.lineTo(x,y2)}var style=mElement.getStyle();if(style.getDrawFill()&&style.getFillColor()!="none"){mContext.fillStyle=style.getFillColor();mContext.fill()}if(style.getDrawLines()){mContext.lineWidth=style.getLineWidth();mContext.strokeStyle=style.getLineColor();mContext.stroke()}};var EJSS_CANVASGRAPHICS=EJSS_CANVASGRAPHICS||{};EJSS_CANVASGRAPHICS.ellipse=function(mContext,mElement){var pos=mElement.getPixelPosition();var size=mElement.getPixelSizes();var offset=mElement.getRelativePositionOffset(size);var xm=pos[0]+offset[0];var ym=pos[1]+offset[1];var w=Math.abs(size[0]);var h=Math.abs(size[1]);var kappa=.5522848,x=xm-w/2,y=ym-h/2;ox=w/2*kappa,oy=h/2*kappa,xe=x+w,ye=y+h,mContext.beginPath();mContext.moveTo(x,ym);mContext.bezierCurveTo(x,ym-oy,xm-ox,y,xm,y);mContext.bezierCurveTo(xm+ox,y,xe,ym-oy,xe,ym);mContext.bezierCurveTo(xe,ym+oy,xm+ox,ye,xm,ye);mContext.bezierCurveTo(xm-ox,ye,x,ym+oy,x,ym);var style=mElement.getStyle();if(style.getDrawFill()&&style.getFillColor()!="none"){mContext.fillStyle=style.getFillColor();mContext.fill()}if(style.getDrawLines()){mContext.lineWidth=style.getLineWidth();mContext.strokeStyle=style.getLineColor();mContext.stroke()}};var EJSS_CANVASGRAPHICS=EJSS_CANVASGRAPHICS||{};EJSS_CANVASGRAPHICS.grid=function(mContext,mElement){var pos=mElement.getPixelPosition();var size=mElement.getPixelSizes();var offset=mElement.getRelativePositionOffset(size);var x=pos[0]+offset[0];var y=pos[1]+offset[1];var mx=size[0]/2;var my=size[1]/2;var showx=mElement.getShowX();var showy=mElement.getShowY();if(showx){mContext.beginPath();var ticksXmode=mElement.getTicksXMode();if(ticksXmode==EJSS_DRAWING2D.Grid.SCALE_LOG){var scaleX=mElement.getScaleX();if(scaleX[0]>0&&scaleX[1]>0){var ticksX=mElement.getTicksX();var left=x-mx,right=x+mx,top=y+my,bottom=y-my;EJSS_GRAPHICS.GraphicsUtils.drawLogGrid(left,top,right,bottom,ticksX,scaleX,1,function(xx,yy){mContext.moveTo(xx,yy)},function(xx,yy){mContext.lineTo(xx,yy)})}}else if(ticksXmode==EJSS_DRAWING2D.Grid.SCALE_NUM){var stepx=0;var tickstepx=0;if(!mElement.getAutoTicksX()){var ticksX=mElement.getTicksX();if(ticksX!=0){stepx=Math.abs(size[0]/ticksX)}else{stepx=mElement.getStepX();tickstepx=mElement.getTickStepX()}}else{var stepxmin=mElement.getAutoStepXMin();var ticksxrange=mElement.getAutoTicksRangeX();for(var i=ticksxrange.length-1;i>=0;i--){stepx=Math.abs(size[0]/ticksxrange[i]);if(stepx>=stepxmin)break}}var scalePrecisionX=mElement.getScalePrecisionX();var scaleX=mElement.getScaleX();if(tickstepx==0){var scalestepX=Math.abs((scaleX[1]-scaleX[0])*stepx/size[0])}else{var scalestepX=tickstepx;stepx=Math.abs(scalestepX*size[0]/(scaleX[1]-scaleX[0]))}var decimalsX=Math.pow(10,scalePrecisionX);var scalestepXTmp=Math.round(scalestepX*decimalsX)/decimalsX;if(scalestepXTmp>0){scalestepX=scalestepXTmp;stepx=Math.abs(scalestepXTmp*size[0]/(scaleX[1]-scaleX[0]))}var fixedTicks=mElement.getFixedTickX();var tickfixed=scaleX[1];if(!isNaN(fixedTicks)){if(fixedTicks<scaleX[0])tickfixed=fixedTicks+(Math.floor((scaleX[0]-fixedTicks)/scalestepX)+1)*scalestepX;else if(fixedTicks>scaleX[1])tickfixed=fixedTicks-(Math.floor((fixedTicks-scaleX[1])/scalestepX)+1)*scalestepX;else tickfixed=fixedTicks}var scaleshift=Math.abs((scaleX[0]-tickfixed)%scalestepX);var dist=Math.abs(scaleshift-scalestepX);if(scaleshift<.001||dist<.001)scaleshift=0;var shiftx=Math.abs(size[0]*scaleshift/(scaleX[1]-scaleX[0]));var left=x-mx,right=x+mx,top=y+my,bottom=y-my;EJSS_GRAPHICS.GraphicsUtils.drawDecGrid(left,top,right,bottom,shiftx,stepx,1,function(xx,yy){mContext.moveTo(xx,yy)},function(xx,yy){mContext.lineTo(xx,yy)})}mContext.lineWidth=mElement.getLineWidthX();mContext.strokeStyle=mElement.getLineColorX();mContext.stroke()}if(showy){mContext.beginPath();var ticksYmode=mElement.getTicksYMode();if(ticksYmode==EJSS_DRAWING2D.Grid.SCALE_LOG){var scaleY=mElement.getScaleY();if(scaleY[0]>0&&scaleY[1]>0){var ticksY=mElement.getTicksY();var left=x-mx,right=x+mx,top=y+my,bottom=y-my;EJSS_GRAPHICS.GraphicsUtils.drawLogGrid(left,top,right,bottom,ticksY,scaleY,-1,function(xx,yy){mContext.moveTo(xx,yy)},function(xx,yy){mContext.lineTo(xx,yy)})}}else if(ticksYmode==EJSS_DRAWING2D.Grid.SCALE_NUM){var stepy=0;var tickstepy=0;if(!mElement.getAutoTicksY()){var ticksY=mElement.getTicksY();if(ticksY!=0){stepy=Math.abs(size[1]/ticksY)}else{stepy=mElement.getStepY();tickstepy=mElement.getTickStepY()}}else{var stepymin=mElement.getAutoStepYMin();var ticksyrange=mElement.getAutoTicksRangeY();for(var i=ticksyrange.length-1;i>=0;i--){stepy=Math.abs(size[1]/ticksyrange[i]);if(stepy>=stepymin)break}}var scalePrecisionY=mElement.getScalePrecisionY();var scaleY=mElement.getScaleY();if(tickstepy==0){var scalestepY=Math.abs((scaleY[1]-scaleY[0])*stepy/size[1])}else{var scalestepY=tickstepy;stepy=Math.abs(scalestepY*size[1]/(scaleY[1]-scaleY[0]))}var decimalsY=Math.pow(10,scalePrecisionY);var scalestepYTmp=Math.round(scalestepY*decimalsY)/decimalsY;if(scalestepYTmp>0){scalestepY=scalestepYTmp;stepy=Math.abs(scalestepYTmp*size[1]/(scaleY[1]-scaleY[0]))}var fixedTicks=mElement.getFixedTickY();var tickfixed=scaleY[1];if(!isNaN(fixedTicks)){if(fixedTicks<scaleY[0])tickfixed=fixedTicks+(Math.floor((scaleY[0]-fixedTicks)/scalestepY)+1)*scalestepY;else if(fixedTicks>scaleY[1])tickfixed=fixedTicks-(Math.floor((fixedTicks-scaleY[1])/scalestepY)+1)*scalestepY;else tickfixed=fixedTicks}var scaleshift=Math.abs((scaleY[0]-tickfixed)%scalestepY);var dist=Math.abs(scaleshift-scalestepY);if(scaleshift<.001||dist<.001)scaleshift=0
;var shifty=Math.abs(size[1]*scaleshift/(scaleY[1]-scaleY[0]));var left=x-mx,right=x+mx,top=y+my,bottom=y-my;EJSS_GRAPHICS.GraphicsUtils.drawDecGrid(left,top,right,bottom,shifty,stepy,-1,function(xx,yy){mContext.moveTo(xx,yy)},function(xx,yy){mContext.lineTo(xx,yy)})}mContext.lineWidth=mElement.getLineWidthY();mContext.strokeStyle=mElement.getLineColorY();mContext.stroke()}};var EJSS_CANVASGRAPHICS=EJSS_CANVASGRAPHICS||{};EJSS_CANVASGRAPHICS.histogram=function(mContext,mElement){function areaBar(barx1,barx2,bary,axis,barstyle){mContext.beginPath();mContext.moveTo(barx1,axis);mContext.lineTo(barx1,bary);mContext.lineTo(barx2,bary);mContext.lineTo(barx2,axis);if(barstyle.getDrawFill()&&barstyle.getFillColor()!="none"){mContext.fillStyle=barstyle.getFillColor();mContext.fill()}if(barstyle.getDrawLines()){mContext.lineWidth=barstyle.getLineWidth();mContext.strokeStyle=barstyle.getLineColor();mContext.stroke()}}var pos=mElement.getPixelPosition();var size=mElement.getPixelSizes();var offset=mElement.getRelativePositionOffset(size);var x=pos[0]+offset[0];var y=pos[1]+offset[1];var mx=size[0]/2;var my=size[1]/2;var style=mElement.getStyle();var discrete=mElement.getDiscrete();var halfBin=mElement.getBinWidth()/2;var bars=mElement.getBars();var axisx=mElement.getGroupPanel().getPixelPositionWorldOrigin()[1];for(var j=0;j<bars.length;j++){var barx1,barx2;var cbin=bars[j][0];if(discrete){barx1=barx2=x-mx+cbin*size[0]}else{barx1=x-mx+(cbin-halfBin)*size[0];barx2=x-mx+(cbin+halfBin)*size[0]}var bary=y-my+bars[j][1]*size[1];areaBar(barx1,barx2,bary,axisx,style)}};var EJSS_CANVASGRAPHICS=EJSS_CANVASGRAPHICS||{};EJSS_CANVASGRAPHICS.image=function(mContext,mElement,transformCallBack){var pos=mElement.getPixelPosition();var size=mElement.getPixelSizes();var offset=mElement.getRelativePositionOffset(size);var x=pos[0]+offset[0];var y=pos[1]+offset[1];var mx=Math.abs(size[0]/2);var my=Math.abs(size[1]/2);var img;if(!mElement.getChangedImage())img=mElement.getCustomObject();if(img){mContext.save();transformCallBack(mElement);mContext.drawImage(img,x-mx,y-my,Math.abs(size[0]),Math.abs(size[1]));mContext.restore()}else{img=new Image;mElement.setCustomObject(img);img.onload=function(){mContext.save();transformCallBack(mElement);mContext.drawImage(img,x-mx,y-my,Math.abs(size[0]),Math.abs(size[1]));mContext.restore()};var code=mElement.getEncode();if(code.length>0){img.src="data:png;base64,"+code}else{img.src=mElement.getImageUrl()}}mElement.setChangedImage(false)};var EJSS_CANVASGRAPHICS=EJSS_CANVASGRAPHICS||{};EJSS_CANVASGRAPHICS.mesh=function(mContext,mElement){var mA;var mB;var mCells;var mBoundary;function fillCell(xs,ys,numpoints,color,levelIndex){mContext.beginPath();for(var i=0;i<numpoints;i++){if(i==0)mContext.moveTo(xs[0],ys[0]);else mContext.lineTo(xs[i],ys[i])}mContext.lineTo(xs[0],ys[0]);var fill=color.indexToColor(levelIndex);mContext.fillStyle=fill;mContext.fill();mContext.lineWidth=1.25;mContext.strokeStyle=fill;mContext.stroke()}function drawCell(xs,ys,fill,style){mContext.beginPath();var numpoints=xs.length;for(var i=0;i<numpoints;i++){if(i==0)mContext.moveTo(xs[0],ys[0]);else mContext.lineTo(xs[i],ys[i])}mContext.lineTo(xs[0],ys[0]);if(fill&&style.getDrawFill()&&style.getFillColor()!="none"){mContext.fillStyle=style.getFillColor();mContext.fill()}if(style.getDrawLines()){mContext.lineWidth=style.getLineWidth();mContext.strokeStyle=style.getLineColor();mContext.stroke()}}function drawSegment(xs,ys,color,lineWidth){mContext.beginPath();var numpoints=xs.length;for(var i=0;i<numpoints;i++){if(i==0)mContext.moveTo(xs[0],ys[0]);else mContext.lineTo(xs[i],ys[i])}mContext.lineTo(xs[0],ys[0]);mContext.lineWidth=lineWidth+.5;mContext.strokeStyle=color;mContext.stroke()}function drawVectors(cellA,cellB,field,lenVector){for(var i=0;i<cellA.length;i++){var a=cellA[i];var b=cellB[i];var a1=field[i][0];var b1=field[i][1];var len=EJSS_TOOLS.Mathematics.norm([a1,b1]);var sa=a1*lenVector/len;var sb=b1*lenVector/len;if(sa!=0||sb!=0){var stMax=.3*EJSS_TOOLS.Mathematics.norm([sa,sb]);var stW=stMax!=0&&stMax<12?stMax:12;var angle=Math.atan2(sa,sb);mContext.beginPath();mContext.moveTo(a,b);mContext.lineTo(a+sa-stW*Math.cos(angle),b+sb-stW*Math.sin(angle));mContext.lineTo(a+sa-stW*Math.cos(angle-Math.PI/6),b+sb-stW*Math.sin(angle-Math.PI/6));mContext.lineTo(a+sa,y+my);mContext.lineTo(a+sa-stW*Math.cos(angle+Math.PI/6),b+sb-stW*Math.sin(angle+Math.PI/6));mContext.lineTo(a+sa-stW*Math.cos(angle),b+sb-stW*Math.sin(angle));mContext.lineWidth=1;mContext.strokeStyle="black";mContext.stroke()}}}var pos=mElement.getPixelPosition();var size=mElement.getPixelSizes();var offset=mElement.getRelativePositionOffset(size);var x=pos[0]+offset[0];var y=pos[1]+offset[1];var mx=size[0]/2;var my=size[1]/2;var mPoints=mElement.getPoints();if(mPoints==null)return;var nPoints=mPoints.length;mA=new Array(nPoints);mB=new Array(nPoints);for(var i=0;i<nPoints;i++){mA[i]=x-mx+mPoints[i][0]*size[0];mB[i]=y-my+mPoints[i][1]*size[1]}var cells=mElement.getCells();var field=mElement.getFieldAtPoints();if(field){mCells=EJSS_GRAPHICS.GraphicsUtils.buildCells(mA,mB,cells,field,false)}else{field=mElement.getFieldAtCells();mCells=EJSS_GRAPHICS.GraphicsUtils.buildCells(mA,mB,cells,field,true)}if(cells!=null){var style=mElement.getStyle();if(field!=null){var color=mElement.getColorCoded();EJSS_GRAPHICS.GraphicsUtils.drawPolygons(mCells,color,function(xs,ys){drawCell(xs,ys,false,style)},function(xs,ys,numpoints,color,levelIndex){fillCell(xs,ys,numpoints,color,levelIndex)})}else{EJSS_GRAPHICS.GraphicsUtils.drawPolygons(mCells,color,function(xs,ys){drawCell(xs,ys,true,style)},function(xs,ys,numpoints,color,levelIndex){})}}var boundary=mElement.getBoundary();if(mElement.getDrawBoundary()&&boundary!=null){var labels=mElement.getBoundaryLabels();var colors=mElement.getBoundaryColors();var lineWidth=mElement.getBoundaryLineWidth();mBoundary=EJSS_GRAPHICS.GraphicsUtils.buildBoundary(mA,mB,boundary);EJSS_GRAPHICS.GraphicsUtils.drawBoundary(mBoundary,labels,colors,function(xs,ys,color){drawSegment(xs,ys,color,lineWidth)})}if(mElement.getDataType()>=4&&field!=null){var lenVector=mElement.getVectorLength()*size[0];for(var i=0,n=cells.length;i<n;i++){drawVectors(mCellA[i],mCellB[i],field[i],lenVector)}}};var EJSS_CANVASGRAPHICS=EJSS_CANVASGRAPHICS||{};EJSS_CANVASGRAPHICS.pipe=function(mContext,mElement){var points=mElement.getPoints();if(!points||points.length<=0)return;var pos=mElement.getPixelPosition();var size=mElement.getPixelSizes();var offset=mElement.getRelativePositionOffset(size);var x=pos[0]+offset[0];var y=pos[1]+offset[1];var sx=Math.abs(size[0]);var sy=Math.abs(size[1]);var xmin=x-sx/2;var ymin=y+sy/2;var style=mElement.getStyle();mContext.beginPath();mContext.moveTo(xmin,ymin);var x=xmin;var y=ymin;for(var i=0,n=points.length;i<n;i++){var point=points[i];x+=Math.round(point[0]*sx);y+=Math.round(-point[1]*sy);mContext.lineTo(x,y)}if(style.getDrawLines()){mContext.lineWidth=2*style.getLineWidth()+mElement.getPipeWidth();mContext.strokeStyle=style.getLineColor();mContext.stroke()}mContext.beginPath();mContext.moveTo(xmin,ymin);var x=xmin;var y=ymin;for(var i=0,n=points.length;i<n;i++){var point=points[i];x+=Math.round(point[0]*sx);y+=Math.round(-point[1]*sy);mContext.lineTo(x,y)}if(style.getDrawLines()){mContext.lineWidth=mElement.getPipeWidth();mContext.strokeStyle=style.getFillColor();mContext.stroke()}};var EJSS_CANVASGRAPHICS=EJSS_CANVASGRAPHICS||{};EJSS_CANVASGRAPHICS.point=function(mContext,mElement){var pos=mElement.getPixelPosition();var size=mElement.getPixelSizes();var offset=mElement.getRelativePositionOffset(size);var xm=pos[0]+offset[0];var ym=pos[1]+offset[1];mContext.beginPath();mContext.arc(xm,ym,2,0,2*Math.PI);var style=mElement.getStyle();mContext.fillStyle=style.getFillColor();mContext.fill()};var EJSS_CANVASGRAPHICS=EJSS_CANVASGRAPHICS||{};EJSS_CANVASGRAPHICS.polygon=function(mContext,mElement){var pos=mElement.getPixelPosition();var size=mElement.getPixelSizes();var offset=mElement.getRelativePositionOffset(size);var x=pos[0]+offset[0];var y=pos[1]+offset[1];var mx=size[0]/2;var my=size[1]/2;mContext.beginPath();var points=mElement.getPoints();for(var i=0;i<points.length;i++){var point=points[i];var xx=x-mx+point[0]*size[0];var yy=y-my+point[1]*size[1];var type=point[2];if(i==0||type==0)mContext.moveTo(xx,yy);else mContext.lineTo(xx,yy)}var style=mElement.getStyle();if(style.getDrawFill()&&style.getFillColor()!="none"){mContext.fillStyle=style.getFillColor();mContext.fill()}if(style.getDrawLines()){mContext.lineWidth=style.getLineWidth();mContext.strokeStyle=style.getLineColor();mContext.stroke()}};var EJSS_CANVASGRAPHICS=EJSS_CANVASGRAPHICS||{};EJSS_CANVASGRAPHICS.rectangle=function(mContext,mElement){var pos=mElement.getPixelPosition();var size=mElement.getPixelSizes();var offset=mElement.getRelativePositionOffset(size);var x=pos[0]+offset[0];var y=pos[1]+offset[1];var mx=size[0]/2;var my=size[1]/2;mContext.beginPath();mContext.moveTo(x-mx,y+my);mContext.lineTo(x+mx,y+my);mContext.lineTo(x+mx,y-my);mContext.lineTo(x-mx,y-my);mContext.lineTo(x-mx,y+my);var style=mElement.getStyle();if(style.getDrawFill()&&style.getFillColor()!="none"){mContext.fillStyle=style.getFillColor();mContext.fill()}if(style.getDrawLines()){mContext.lineWidth=style.getLineWidth();mContext.strokeStyle=style.getLineColor();mContext.stroke()}};var EJSS_CANVASGRAPHICS=EJSS_CANVASGRAPHICS||{};EJSS_CANVASGRAPHICS.roundRectangle=function(mContext,mElement){var pos=mElement.getPixelPosition();var size=mElement.getPixelSizes();var offset=mElement.getRelativePositionOffset(size);var mx=pos[0]+offset[0];var my=pos[1]+offset[1];var width=Math.abs(size[0]);var height=Math.abs(size[1]);var x=mx-width/2;var y=my-height/2;var radius=Math.abs(mElement.getCornerRadius());mContext.beginPath();mContext.moveTo(x+radius,y);mContext.lineTo(x+width-radius,y);mContext.quadraticCurveTo(x+width,y,x+width,y+radius);mContext.lineTo(x+width,y+height-radius);mContext.quadraticCurveTo(x+width,y+height,x+width-radius,y+height);mContext.lineTo(x+radius,y+height);mContext.quadraticCurveTo(x,y+height,x,y+height-radius);mContext.lineTo(x,y+radius);mContext.quadraticCurveTo(x,y,x+radius,y);mContext.closePath();var style=mElement.getStyle();if(style.getDrawFill()&&style.getFillColor()!="none"){mContext.fillStyle=style.getFillColor();mContext.fill()}if(style.getDrawLines()){mContext.lineWidth=style.getLineWidth();mContext.strokeStyle=style.getLineColor();mContext.stroke()}};var EJSS_CANVASGRAPHICS=EJSS_CANVASGRAPHICS||{};EJSS_CANVASGRAPHICS.canvas=function(mContext,mElement){var pos=mElement.getPixelPosition();var size=mElement.getPixelSizes();var offset=mElement.getRelativePositionOffset(size);var x=pos[0]+offset[0];var y=pos[1]+offset[1];var deltaX=mElement.getMaximumX()-mElement.getMinimumX();var deltaY=mElement.getMaximumY()-mElement.getMinimumY();var pixWth=Math.abs(size[0]);var pixHgt=Math.abs(size[1]);var pxPerUnitX=pixWth/deltaX;var pxPerUnitY=pixHgt/deltaY;var pxTopLeftX=x-pixWth/2;var pxTopLeftY=y+pixHgt/2;EJSS_GRAPHICS.GraphicsUtils.drawImageField(context,pxTopLeftX,pxTopLeftY,mElement.getMinimumX(),mElement.getMinimumY(),pixWth,pixHgt,pxPerUnitX,pxPerUnitY,{data:mElement.getData()})};var EJSS_CANVASGRAPHICS=EJSS_CANVASGRAPHICS||{};EJSS_CANVASGRAPHICS.segment=function(mContext,mElement){var pos=mElement.getPixelPosition();var size=mElement.getPixelSizes();var offset=mElement.getRelativePositionOffset(size);var x=pos[0]+offset[0];var y=pos[1]+offset[1];var mx=size[0]/2;var my=size[1]/2;mContext.beginPath();mContext.moveTo(x-mx,y-my);mContext.lineTo(x+mx,y+my);var style=mElement.getStyle();if(style.getDrawFill()&&style.getFillColor()!="none"){mContext.fillStyle=style.getFillColor();mContext.fill()}if(style.getDrawLines()){mContext.lineWidth=style.getLineWidth();mContext.strokeStyle=style.getLineColor();mContext.stroke()}};var EJSS_CANVASGRAPHICS=EJSS_CANVASGRAPHICS||{};EJSS_CANVASGRAPHICS.spring=function(mContext,mElement){var pos=mElement.getPixelPosition();var size=mElement.getPixelSizes();var offset=mElement.getRelativePositionOffset(size);var x=pos[0]+offset[0];var y=pos[1]+offset[1];var mx=size[0]/2;var my=size[1]/2;var radius=mElement.getGroupPanel().toPixelMod([mElement.getRadius(),0])[0];mContext.beginPath();EJSS_GRAPHICS.GraphicsUtils.drawSpring(mElement.getLoops(),mElement.getPointsPerLoop(),radius,mElement.getSolenoid(),mElement.getThinExtremes(),x-mx,y-my,size[0],size[1],function(xx,yy){mContext.moveTo(xx,yy)},function(xx,yy){mContext.lineTo(xx,yy)});var style=mElement.getStyle();if(style.getDrawFill()&&style.getFillColor()!="none"){mContext.fillStyle=style.getFillColor();mContext.fill()}if(style.getDrawLines()){mContext.lineWidth=style.getLineWidth();mContext.strokeStyle=style.getLineColor();mContext.stroke()}};var EJSS_CANVASGRAPHICS=EJSS_CANVASGRAPHICS||{};EJSS_CANVASGRAPHICS.tank=function(mContext,mElement){var pos=mElement.getPixelPosition();var size=mElement.getPixelSizes();var offset=mElement.getRelativePositionOffset(size);var x=pos[0]+offset[0];var y=pos[1]+offset[1];var mx=Math.abs(size[0]/2);var my=Math.abs(size[1]/2);var level=mElement.getPixelSizeOf(0,mElement.getLevel());var xmin=x-mx,xmax=x+mx;var ymin=y+my,ymax=y-my;var ylevel=ymin+level[1];var style=mElement.getStyle();mContext.beginPath();mContext.moveTo(xmin+level[0],ylevel);mContext.lineTo(xmin,ymin);mContext.lineTo(xmax,ymin);mContext.lineTo(xmax+level[0],ylevel);mContext.fillStyle=mElement.getLevelColor();mContext.fill();mContext.beginPath();mContext.moveTo(xmin,ymax);mContext.lineTo(xmin,ymin);mContext.lineTo(xmax,ymin);mContext.lineTo(xmax,ymax);if(style.getDrawFill()&&style.getFillColor()!="none"){mContext.fillStyle=style.getFillColor();mContext.fill()}mContext.lineWidth=style.getLineWidth();mContext.strokeStyle=style.getLineColor();mContext.stroke()};var EJSS_CANVASGRAPHICS=EJSS_CANVASGRAPHICS||{};EJSS_CANVASGRAPHICS.text=function(mContext,mElement){var font=mElement.getFont();var fondtxt="";fondtxt+=font.getFontStyle()!="none"?font.getFontStyle()+" ":"";fondtxt+=font.getFontWeight()!="none"?font.getFontWeight()+" ":"";fondtxt+=font.getFontSizeString()+(font.getFontSizeString().toString().indexOf("px")>-1?" ":"px ");fondtxt+=font.getFontFamily();mContext.font=fondtxt;var txt=mElement.getText();var pos=mElement.getPixelPosition();var marginFrame=mElement.getFramed()?4:0;var size=[mContext.measureText(txt).width+marginFrame*2,font.getFontSize()+marginFrame*2];var offset=EJSS_DRAWING2D.Element.getSWRelativePositionOffset(mElement.getRelativePosition(),size[0],size[1]);var xmargin=mElement.getMarginX();var ymargin=mElement.getMarginY();var x=pos[0]+offset[0]+xmargin+marginFrame;var y=pos[1]+offset[1]+ymargin-marginFrame;if(mElement.getFramed()){var tbmargin=marginFrame;var rlmargin=marginFrame;var wlen=size[0]-marginFrame*2;var hlen=size[1]-marginFrame*2;if(wlen>0){var bottom=y+tbmargin,top=y-hlen-tbmargin;var left=x-rlmargin,rigth=x+wlen+tbmargin;mContext.save();mContext.beginPath();mContext.moveTo(left,bottom);mContext.lineTo(rigth,bottom);mContext.lineTo(rigth,top);mContext.lineTo(left,top);mContext.lineTo(left,bottom);var style=mElement.getStyle();if(style.getDrawFill()&&style.getFillColor()!="none"){mContext.fillStyle=style.getFillColor();mContext.fill()}if(style.getDrawLines()){mContext.lineWidth=style.getLineWidth();mContext.strokeStyle=style.getLineColor();mContext.stroke()}mContext.restore()}}var angletext=0;switch(mElement.getWritingMode()){case EJSS_DRAWING2D.Text.MODE_TOPDOWN:angletext=Math.PI/2;break;case EJSS_DRAWING2D.Text.MODE_RIGTHLEFT:angletext=Math.PI;break;case EJSS_DRAWING2D.Text.MODE_DOWNTOP:angletext=3*Math.PI/2;break;case EJSS_DRAWING2D.Text.MODE_LEFTRIGHT:angletext=0;break}mContext.translate(pos[0]+xmargin,pos[1]+ymargin);mContext.rotate(angletext);mContext.translate(-(pos[0]+xmargin),-(pos[1]+ymargin));mContext.fillStyle=font.getFillColor();mContext.fillText(mElement.getText(),x,y)};var EJSS_CANVASGRAPHICS=EJSS_CANVASGRAPHICS||{};EJSS_CANVASGRAPHICS.trace=function(mContext,mElement){function drawTrail(points,x,y,sx,sy){mContext.beginPath();for(var i=0;i<points.length;i++){var point=points[i];var xx=x+point[0]*sx;var yy=y+point[1]*sy;var type=point[2];if(i==0||type==0)mContext.moveTo(xx,yy);else mContext.lineTo(xx,yy)}}function ellipseMark(markx,marky,size,markstyle){var xm=markx;var ym=marky;var w=Math.abs(size[0]);var h=Math.abs(size[1]);var kappa=.5522848,x=xm-w/2,y=ym-h/2;ox=w/2*kappa,oy=h/2*kappa,xe=x+w,ye=y+h,mContext.beginPath();mContext.moveTo(x,ym);mContext.bezierCurveTo(x,ym-oy,xm-ox,y,xm,y);mContext.bezierCurveTo(xm+ox,y,xe,ym-oy,xe,ym);mContext.bezierCurveTo(xe,ym+oy,xm+ox,ye,xm,ye);mContext.bezierCurveTo(xm-ox,ye,x,ym+oy,x,ym);if(markstyle.getDrawFill()&&markstyle.getFillColor()!="none"){mContext.fillStyle=markstyle.getFillColor();mContext.fill()}if(markstyle.getDrawLines()){mContext.lineWidth=markstyle.getLineWidth();mContext.strokeStyle=markstyle.getLineColor();mContext.stroke()}}function rectangleMark(markx,marky,size,markstyle){var x=markx;var y=marky;var sx=Math.abs(size[0]);var sy=Math.abs(size[1]);mContext.beginPath();mContext.rect(x-sx/2,y-sy/2,sx,sy);if(markstyle.getDrawFill()&&markstyle.getFillColor()!="none"){mContext.fillStyle=markstyle.getFillColor();mContext.fill()}if(markstyle.getDrawLines()){mContext.lineWidth=markstyle.getLineWidth();mContext.strokeStyle=markstyle.getLineColor();mContext.stroke()}}function areaMark(lastmarkx,lastmarky,markx,marky,axis,markstyle){mContext.beginPath();mContext.moveTo(lastmarkx,axis);mContext.lineTo(lastmarkx,lastmarky);mContext.lineTo(markx,marky);mContext.lineTo(markx,axis);if(markstyle.getDrawFill()&&markstyle.getFillColor()!="none"){mContext.fillStyle=markstyle.getFillColor();mContext.fill()}if(markstyle.getDrawLines()){mContext.lineWidth=markstyle.getLineWidth();mContext.strokeStyle=markstyle.getLineColor();mContext.stroke()}}var pos=mElement.getPixelPosition();var size=mElement.getPixelSizes();var offset=mElement.getRelativePositionOffset(size);var x=pos[0]+offset[0];var y=pos[1]+offset[1];var mx=size[0]/2;var my=size[1]/2;drawTrail(mElement.getPoints(),x-mx,y-my,size[0],size[1]);var style=mElement.getStyle();if(style.getDrawFill()&&style.getFillColor()!="none"){mContext.fillStyle=style.getFillColor();mContext.fill()}if(style.getDrawLines()){mContext.lineWidth=style.getLineWidth();mContext.strokeStyle=style.getLineColor();mContext.stroke()}var points=mElement.getPoints();var lastpointX,lastpointY;for(var i=0;i<points.length;i++){var point=points[i];var markx=x-mx+point[0]*size[0];var marky=y-my+point[1]*size[1];var markType=point[3];var markstyle=point[4];var marksize=[point[5],point[6]];if(markType==EJSS_DRAWING2D.Trace.ELLIPSE){ellipseMark(markx,marky,marksize,markstyle)}else if(markType==EJSS_DRAWING2D.Trace.RECTANGLE){rectangleMark(markx,marky,marksize,markstyle)}else if(markType==EJSS_DRAWING2D.Trace.BAR){var axisx=mElement.getGroupPanel()._26([0,0])[1];marksize[1]=axisx-marky;marky=marky+marksize[1]/2;rectangleMark(markx,marky,marksize,markstyle)}else if(markType==EJSS_DRAWING2D.Trace.AREA){if(i!=0){var axisx=mElement.getGroupPanel()._26([0,0])[1];var lastmarkx=x-mx+lastpointX*size[0];var lastmarky=y-my+lastpointY*size[1];areaMark(mMark,lastmarkx,lastmarky,markx,marky,axisx,markstyle)}lastpointX=point[0];lastpointY=point[1]}}};var EJSS_CANVASGRAPHICS=EJSS_CANVASGRAPHICS||{};EJSS_CANVASGRAPHICS.trail=function(mContext,mElement){function addSegment(points,num,style,pX,pY,sX,sY){if(num<=0)return;mContext.beginPath();for(var i=0;i<num;i++){var point=points[i];var xx=pX+point[0]*sX;var yy=pY+point[1]*sY;var type=point[2];if(i==0||type==0)mContext.moveTo(xx,yy);else mContext.lineTo(xx,yy)}if(style.getDrawLines()){mContext.lineWidth=style.getLineWidth();mContext.strokeStyle=style.getLineColor();mContext.stroke()}}var pos=mElement.getPixelPosition();var size=mElement.getPixelSizes();var offset=mElement.getRelativePositionOffset(size);var x=pos[0]+offset[0];var y=pos[1]+offset[1];var mx=size[0]/2;var my=size[1]/2;var pX=x-mx;var pY=y-my;var sX=size[0];var sY=size[1];var segmentCount=mElement.getSegmentsCount();if(segmentCount>0){for(var i=0;i<segmentCount;i++){var num=mElement.getSegmentPoints(i).length;addSegment(mElement.getSegmentPoints(i),num,mElement.getSegmentStyle(i),pX,pY,sX,sY)}}var num=mElement.getCurrentPoints().length;addSegment(mElement.getCurrentPoints(),num,mElement.getStyle(),pX,pY,sX,sY)};var EJSS_CANVASGRAPHICS=EJSS_CANVASGRAPHICS||{};EJSS_CANVASGRAPHICS.wheel=function(mContext,mElement){var pos=mElement.getPixelPosition();var size=mElement.getPixelSizes();var offset=mElement.getRelativePositionOffset(size);var xm=pos[0]+offset[0];var ym=pos[1]+offset[1];var w=Math.abs(size[0]);var h=Math.abs(size[1]);var mx=size[0]/2;var my=size[1]/2;var kappa=.5522848,x=xm-w/2,y=ym-h/2;ox=w/2*kappa,oy=h/2*kappa,xe=x+w,ye=y+h,mContext.beginPath();mContext.moveTo(x,ym);mContext.bezierCurveTo(x,ym-oy,xm-ox,y,xm,y);mContext.bezierCurveTo(xm+ox,y,xe,ym-oy,xe,ym);mContext.bezierCurveTo(xe,ym+oy,xm+ox,ye,xm,ye);mContext.bezierCurveTo(xm-ox,ye,x,ym+oy,x,ym);mContext.moveTo(xm-mx,ym);mContext.lineTo(xm+mx,ym);mContext.moveTo(xm,ym-my);mContext.lineTo(xm,ym+my);var style=mElement.getStyle();if(style.getDrawFill()&&style.getFillColor()!="none"){mContext.fillStyle=style.getFillColor();mContext.fill()}if(style.getDrawLines()){mContext.lineWidth=style.getLineWidth();mContext.strokeStyle=style.getLineColor();mContext.stroke()}};var EJSS_GRAPHICS=EJSS_GRAPHICS||{};EJSS_GRAPHICS.CanvasGraphics={getOffsetRect:function(graphics){return EJSS_GRAPHICS.GraphicsUtils.getOffsetRect(graphics)}};EJSS_GRAPHICS.canvasGraphics=function(mName){var self=EJSS_INTERFACE.canvas(mName);var mInterfaceGraphics=self.getDOMElement();var mContext=self.getContext();self.getEventContext=function(){return mInterfaceGraphics};self.getBox=function(){var box=EJSS_GRAPHICS.CanvasGraphics.getOffsetRect(self);box.width-=1;box.height-=1;return box};self.reset=function(){var rect=EJSS_GRAPHICS.CanvasGraphics.getOffsetRect(self);mContext.clearRect(0,0,rect.width,rect.height)};self.draw=function(elements,force){for(var i=0,n=elements.length;i<n;i++){var element=elements[i];if(element.isGroupVisible()){self.drawElement(element,self.transformElement)}}};self.drawElement=function(element,transformCallBack){var Shape=EJSS_DRAWING2D.Shape;var cl=element._23();if(cl==="ElementImage"){EJSS_CANVASGRAPHICS.image(mContext,element,transformCallBack)}else{mContext.save();transformCallBack(element);switch(cl){case"ElementCustom":{var customFunction=element.getFunction();if(customFunction)customFunction(mContext,element)}break;case"ElementShape":switch(element.getShapeType()){default:case Shape.ELLIPSE:EJSS_CANVASGRAPHICS.ellipse(mContext,element);break;case Shape.RECTANGLE:EJSS_CANVASGRAPHICS.rectangle(mContext,element);break;case Shape.ROUND_RECTANGLE:EJSS_CANVASGRAPHICS.roundRectangle(mContext,element);break;case Shape.WHEEL:EJSS_CANVASGRAPHICS.wheel(mContext,element);break;case Shape.NONE:case Shape.POINT:EJSS_CANVASGRAPHICS.point(mContext,element);break}break;case"ElementSegment":EJSS_CANVASGRAPHICS.segment(mContext,element);break;case"ElementArrow":EJSS_CANVASGRAPHICS.arrow(mContext,element);break;case"ElementText":EJSS_CANVASGRAPHICS.text(mContext,element);break;case"ElementSpring":EJSS_CANVASGRAPHICS.spring(mContext,element);break;case"ElementTrail":EJSS_CANVASGRAPHICS.trail(mContext,element);break;case"ElementTrace":EJSS_CANVASGRAPHICS.trace(mContext,element);break;case"ElementGrid":EJSS_CANVASGRAPHICS.grid(mContext,element);break;case"ElementAxis":EJSS_CANVASGRAPHICS.axis(mContext,element);break;case"ElementCursor":EJSS_CANVASGRAPHICS.cursor(mContext,element);break;case"ElementPolygon":EJSS_CANVASGRAPHICS.polygon(mContext,element);break;case"ElementAnalyticCurve":EJSS_CANVASGRAPHICS.analyticCurve(mContext,element);break;case"ElementCellLattice":EJSS_CANVASGRAPHICS.cellLattice(mContext,element);break;case"ElementByteRaster":EJSS_CANVASGRAPHICS.byteRaster(mContext,element);break;case"ElementMesh":EJSS_CANVASGRAPHICS.mesh(mContext,element);break;case"ElementTank":EJSS_CANVASGRAPHICS.tank(mContext,element);break;case"ElementPipe":EJSS_CANVASGRAPHICS.pipe(mContext,element);break;case"ElementHistogram":EJSS_CANVASGRAPHICS.histogram(mContext,element);break;case"ElementScalarField":EJSS_CANVASGRAPHICS.scalarField(mContext,element);break;case"ElementCanvas":EJSS_CANVASGRAPHICS.canvas(mContext,element);break;case"ElementVideo":Console.log("Not supported ElementVideo in Canvas!");break}mContext.restore()}};self.transformElement=function(element){if(element.getGroup()!=null)self.transformElement(element.getGroup());var trans=element.getTransformation();if(Array.isArray(trans)){console.log("Array transformations are not supported in Canvas!")}else if(typeof trans==="string"){console.log("SVG-based transformations are not supported in Canvas!")}else if(typeof trans==="number"){var pos=element.getPixelPosition();mContext.translate(pos[0],pos[1]);mContext.rotate(-trans);mContext.translate(-pos[0],-pos[1])}};self._24=function(panel){var gutters=panel.getGutters();if(gutters.visible){var inner=panel.getInnerRect();var x=.5,y=.5;var box=self.getBox();var sx=box.width,sy=box.height;var guttersStyle=panel.getGuttersStyle();var panelStyle=panel.getStyle();if(guttersStyle.getDrawFill()){mContext.beginPath();mContext.moveTo(x,y);mContext.lineTo(x,y+sy);mContext.lineTo(x+sx,y+sy);mContext.lineTo(x+sx,y);mContext.lineTo(x,y);mContext.moveTo(inner.x,inner.y);mContext.lineTo(inner.x+inner.width,inner.y);mContext.lineTo(inner.x+inner.width,inner.y+inner.height);mContext.lineTo(inner.x,inner.y+inner.height);mContext.lineTo(inner.x,inner.y);mContext.moveTo(x,y);mContext.closePath();mContext.fillStyle=guttersStyle.getFillColor();mContext.fill()}if(guttersStyle.getDrawLines()){mContext.beginPath();mContext.moveTo(x,y);mContext.lineTo(x,y+sy);mContext.lineTo(x+sx,y+sy);mContext.lineTo(x+sx,y);mContext.lineTo(x,y);mContext.closePath();mContext.lineWidth=guttersStyle.getLineWidth();mContext.strokeStyle=guttersStyle.getLineColor();mContext.stroke()}if(guttersStyle.getDrawLines()){mContext.beginPath();mContext.moveTo(inner.x,inner.y);mContext.lineTo(inner.x+inner.width,inner.y);mContext.lineTo(inner.x+inner.width,inner.y+inner.height);mContext.lineTo(inner.x,inner.y+inner.height);mContext.lineTo(inner.x,inner.y);mContext.closePath();mContext.lineWidth=panelStyle.getLineWidth();mContext.strokeStyle=panelStyle.getLineColor();mContext.stroke()}}};self.drawPanel=function(panel){var x=.5,y=.5;var box=self.getBox();mContext.beginPath();mContext.rect(x,y,box.width,box.height);var style=panel.getStyle();mContext.fillStyle=style.getFillColor();mContext.fill();if(style.getDrawLines()){mContext.lineWidth=style.getLineWidth();mContext.strokeStyle=style.getLineColor();mContext.stroke()}};return self};var EJSS_GRAPHICS=EJSS_GRAPHICS||{};EJSS_GRAPHICS.GraphicsUtils={getOffsetRect:function(graphics){var width,height,top,left;var element=graphics.getDOMElement();var strw=graphics.getWidth();var strh=graphics.getHeight();width=parseFloat(strw);var isWidthNumber=!isNaN(width)&&isFinite(strw);height=parseFloat(strh);var isHeightNumber=!isNaN(height)&&isFinite(strh);if(element.getBoundingClientRect){var mypanel=element.getElementById?element.getElementById(".myPanel"):null;if(mypanel&&mypanel.childElementCount>0){var box=mypanel.getBoundingClientRect()}else{var box=element.getBoundingClientRect()}top=box.top;left=box.left;if(!isWidthNumber)width=box.width;if(!isHeightNumber)height=box.height}else if(element.offsetTop!==undefined){top=element.offsetTop;left=element.offsetLeft;if(!isWidthNumber)width=element.offsetWidth;if(!isHeightNumber)height=element.offsetHeight}else{var parent=element.parentNode||document.getElementById(element.id).parentNode;while(parent&&!parent.offsetTop&&(parent&&!parent.previousElementSibling&&!parent.nextElementSibling)){parent=parent.parentNode}top=parent.offsetTop;left=parent.offsetLeft;if(!isWidthNumber)width=parent.offsetWidth;if(!isHeightNumber)height=parent.offsetHeight}var body=document.body;var docElem=document.documentElement;var clientTop=docElem.clientTop||body.clientTop||0;var clientLeft=docElem.clientLeft||body.clientLeft||0;top=top-clientTop;left=left-clientLeft;return{top:top,left:left,width:width,height:height,bottom:top+height,right:left+width}},drawSpring:function(loops,pointsPerLoop,radius,solenoid,thinExtremes,x,y,sx,sy,moveTo,lineTo){var segments=loops*pointsPerLoop;var delta=2*Math.PI/pointsPerLoop;if(radius<0)delta*=-1;var pre=pointsPerLoop/2;var size=[sx,sy,0];var u1=EJSS_TOOLS.Mathematics.normalTo(size);var u2=EJSS_TOOLS.Mathematics.normalize(EJSS_TOOLS.Mathematics.crossProduct(size,u1));for(var i=0;i<=segments;i++){var k;if(thinExtremes){if(i<pre)k=0;else if(i<pointsPerLoop)k=i-pre;else if(i>segments-pre)k=0;else if(i>segments-pointsPerLoop)k=segments-i-pre;else k=pre}else k=pre;var angle=Math.PI/2+i*delta;var cos=Math.cos(angle),sin=Math.sin(angle);var xx=x+i*sx/segments+k*radius*(cos*u1[0]+sin*u2[0])/pre;var yy=y+i*sy/segments+k*radius*(cos*u1[1]+sin*u2[1])/pre;if(solenoid!=0){var cte=k*Math.cos(i*2*Math.PI/pointsPerLoop)/pre;xx+=solenoid*cte*sx;yy+=solenoid*cte*sy}if(i==0)moveTo(xx,yy);else lineTo(xx,yy)}},drawDecTicks:function(x,y,mx,my,ticksize,step,shift,orient,inverted,drawTick){var UTILS=EJSS_SVGGRAPHICS.Utils;var left=x-mx,right=x+mx,top=y+my,bottom=y-my;var cright=UTILS.crispValue(right);var cbottom=UTILS.crispValue(bottom);if(orient==EJSS_DRAWING2D.Axis.AXIS_VERTICAL){for(var i=cbottom-shift;i>=top-.5;i-=step){drawTick(x,i,ticksize,orient)}}else{for(var i=left+shift;i<=cright+.5;i+=step){drawTick(i,y,ticksize,orient)}}},drawDecTicksText:function(x,y,mx,my,ticksize,step,shift,scale,scalePrecision,scalestep,scaleshift,font,textPosition,orient,inverted,tickText){var UTILS=EJSS_SVGGRAPHICS.Utils;var left=x-mx,right=x+mx,top=y+my,bottom=y-my;var cright=UTILS.crispValue(right);var cbottom=UTILS.crispValue(bottom);if(orient==EJSS_DRAWING2D.Axis.AXIS_VERTICAL){for(var j=0,i=cbottom-shift;i>=top-.5;i-=step,j++){if(inverted)var number=scale[1]-scaleshift-scalestep*j;else var number=scale[0]+scaleshift+scalestep*j;var text=parseFloat(number.toFixed(scalePrecision)).toFixed(scalePrecision);if(textPosition==EJSS_DRAWING2D.Axis.TICKS_DOWN){var dx=ticksize/2;tickText(mGroup,x+dx,i,text,font,false)}else{var dx=text.length*Math.floor(font.getFontSize()/2);dx+=text.length*font.getNumberLetterSpacing();dx+=Math.floor(ticksize/2);tickText(x-dx,i,text,font,false)}}}else{for(var j=0,i=left+shift;i<=cright+.5;i+=step,j++){var number=scale[0]+scaleshift+scalestep*j;var text=parseFloat(number.toFixed(scalePrecision)).toFixed(scalePrecision);if(textPosition==EJSS_DRAWING2D.Axis.TICKS_DOWN){var dy=Math.floor(ticksize/2)+2;tickText(i,y-ticksize,text,font,true)}else{var dy=font.getFontSize()+Math.floor(ticksize/2);tickText(i,y+dy,text,font,true)}}}},drawLogTicks:function(x,y,mx,my,segsize,ticksize,scale,numticks,orient,drawTick){var UTILS=EJSS_SVGGRAPHICS.Utils;var left=x-mx,bottom=y-my;var cbottom=UTILS.crispValue(bottom);if(orient==EJSS_DRAWING2D.Axis.AXIS_VERTICAL){var minscale=Math.log(scale[0])/Math.log(10);var maxscale=Math.log(scale[1])/Math.log(10);var scalesize=maxscale-minscale;var numbands=Math.ceil(scalesize);var sizeratio=segsize/scalesize;for(var i=0;i<=numbands;i++){var bandmin=Math.pow(10,i+minscale);var bandmax=Math.pow(10,i+minscale+1);var bandshift=bandmax/numticks;for(var j=0;j<numticks-1;j++){var number=bandmin+j*bandshift;if(number!=0&&number>=scale[0]&&number<=scale[1]){var step=Math.log(number)/Math.log(10);var pos=cbottom-(step-minscale)*sizeratio;drawTick(x,pos,ticksize,orient)}}}}else{var minscale=Math.log(scale[0])/Math.log(10);var maxscale=Math.log(scale[1])/Math.log(10);var scalesize=maxscale-minscale;var numbands=Math.ceil(scalesize);var sizeratio=segsize/scalesize;for(var i=0;i<=numbands;i++){var bandmin=Math.pow(10,i+minscale);var bandmax=Math.pow(10,i+minscale+1);var bandshift=bandmax/numticks
;for(var j=0;j<numticks-1;j++){var number=bandmin+j*bandshift;if(number!=0&&number>=scale[0]&&number<=scale[1]){var step=Math.log(number)/Math.log(10);var pos=left+(step-minscale)*sizeratio;drawTick(pos,y,ticksize,orient)}}}}},drawLogTicksText:function(x,y,mx,my,numticks,ticksize,scale,scalePrecision,font,textPosition,orient,tickText){var UTILS=EJSS_SVGGRAPHICS.Utils;var left=x-mx,bottom=y-my;var cbottom=UTILS.crispValue(bottom);if(orient==EJSS_DRAWING2D.Axis.AXIS_VERTICAL){var minscale=Math.log(scale[0])/Math.log(10);var maxscale=Math.log(scale[1])/Math.log(10);var scalesize=maxscale-minscale;var numbands=Math.ceil(scalesize);var sizeratio=segsize/scalesize;for(var i=0;i<=numbands;i++){var bandmin=Math.pow(10,i+minscale);var bandmax=Math.pow(10,i+minscale+1);var bandshift=bandmax/numticks;for(var j=0;j<numticks-1;j++){var number=bandmin+j*bandshift;if(number!=0&&number>=scale[0]&&number<=scale[1]){var step=Math.log(number)/Math.log(10);var pos=cbottom-(step-minscale)*sizeratio;if(j==0){var text=number.toExponential(scalePrecision)}else{var text=parseFloat((number/bandmin).toFixed(scalePrecision)).toFixed(scalePrecision)}if(textPosition==EJSS_DRAWING2D.Axis.TICKS_DOWN){var dx=ticksize/2;tickText(x+dx,pos,text,font,false)}else{var dx=text.length*Math.floor(font.getFontSize()/2);dx+=text.length*font.getNumberLetterSpacing();dx+=Math.floor(ticksize/2);tickText(x-dx,pos,text,font,false)}}}}}else{var minscale=Math.log(scale[0])/Math.log(10);var maxscale=Math.log(scale[1])/Math.log(10);var scalesize=maxscale-minscale;var numbands=Math.ceil(scalesize);var sizeratio=segsize/scalesize;for(var i=0;i<=numbands;i++){var bandmin=Math.pow(10,i+minscale);var bandmax=Math.pow(10,i+minscale+1);var bandshift=bandmax/numticks;for(var j=0;j<numticks-1;j++){var number=bandmin+j*bandshift;if(number!=0&&number>=scale[0]&&number<=scale[1]){var step=Math.log(number)/Math.log(10);var pos=left+(step-minscale)*sizeratio;if(j==0){var text=number.toExponential(scalePrecision)}else{var text=parseFloat((number/bandmin).toFixed(scalePrecision)).toFixed(scalePrecision)}if(textPosition==EJSS_DRAWING2D.Axis.TICKS_DOWN){var dy=Math.floor(ticksize/2)+2;tickText(pos,y-ticksize,text,font,true)}else{var dy=font.getFontSize()+Math.floor(ticksize/2);tickText(pos,y+dy,text,font,true)}}}}}},drawDecGrid:function(left,top,right,bottom,sh,step,orientation,moveTo,lineTo){var UTILS=EJSS_SVGGRAPHICS.Utils;var cleft=UTILS.crispValue(left),cright=UTILS.crispValue(right);var ctop=UTILS.crispValue(top),cbottom=UTILS.crispValue(bottom);if(orientation==-1){if(step==0)step=Math.abs(ctop-cbottom);for(var i=cbottom-sh;i>=top-.5;i-=step){moveTo(left,i);lineTo(right,i)}}else{if(step==0)step=Math.abs(cright-cleft);for(var i=left+sh;i<=cright+.5;i+=step){moveTo(i,top);lineTo(i,bottom)}}},drawLogGrid:function(left,top,right,bottom,numTicks,scale,orientation,moveTo,lineTo){var UTILS=EJSS_SVGGRAPHICS.Utils;var cleft=UTILS.crispValue(left),cright=UTILS.crispValue(right);var ctop=UTILS.crispValue(top),cbottom=UTILS.crispValue(bottom);var path="";var minscale=Math.log(scale[0])/Math.log(10);var maxscale=Math.log(scale[1])/Math.log(10);var scalesize=maxscale-minscale;var numbands=Math.ceil(scalesize);if(orientation==-1)var sizeratio=(cbottom-ctop)/scalesize;else var sizeratio=(cright-cleft)/scalesize;for(var i=0;i<=numbands;i++){var bandmin=Math.pow(10,i+minscale);var bandmax=Math.pow(10,i+minscale+1);var bandshift=bandmax/numTicks;for(var j=0;j<numTicks-1;j++){var number=bandmin+j*bandshift;if(number!=0&&number>=scale[0]&&number<=scale[1]){var step=Math.log(number)/Math.log(10);if(orientation==-1){var pos=cbottom-(step-minscale)*sizeratio;moveTo(cleft,pos);lineTo(cright,pos)}else{var pos=cleft+(step-minscale)*sizeratio;moveTo(pos,ctop);lineTo(pos,cbottom)}}}}return path},buildCells:function(a,b,cells,field,fieldGivenPerCell){var cellA;var cellB;var cellZ;var cellVector;if(cells!=null&&cells.length>0){var nCells=cells.length;cellA=new Array(nCells);cellB=new Array(nCells);cellZ=new Array(nCells);cellVector=new Array(nCells);var dimension=1;if(field!=null){if(fieldGivenPerCell)dimension=field[0][0].length;else dimension=field[0].length}for(var i=0;i<nCells;i++){var cell=cells[i];var nCellPoints=cell.length;cellA[i]=new Array(nCellPoints);cellB[i]=new Array(nCellPoints);for(var j=0;j<nCellPoints;j++){var p=cell[j];cellA[i][j]=a[p];cellB[i][j]=b[p]}if(field!=null){cellZ[i]=new Array(nCellPoints);cellVector[i]=new Array(nCellPoints);if(!fieldGivenPerCell){for(var j=0;j<nCellPoints;j++){var p=cell[j];cellZ[i][j]=dimension<=1?field[p][0]:EJSS_TOOLS.Mathematics.norm(field[p]);cellVector[i][j]=new Array(dimension);for(var k=0;k<dimension;k++){cellVector[i][j][k]=field[p][k]}}}else{var cellField=field[i];for(var j=0;j<nCellPoints;j++){cellZ[i][j]=dimension<=1?cellField[j][0]:EJSS_TOOLS.Mathematics.norm(cellField[j]);cellVector[i][j]=new Array(dimension);for(var k=0;k<dimension;k++){cellVector[i][j][k]=cellField[j][k]}}}}}}return{cellA:cellA,cellB:cellB,cellZ:cellZ,cellVector:cellVector}},drawPolygons:function(cells,color,drawCell,fillCell){var cellA=cells.cellA;var cellB=cells.cellB;var cellZ=cells.cellZ;for(var i=0,n=cellA.length;i<n;i++){var a=cellA[i];var b=cellB[i];var values=cellZ[i];if(typeof values!="undefined"){var nVertex=a.length;var vertexIndex=new Array(nVertex);var minIndex=Number.MAX_VALUE,maxIndex=Number.MIN_VALUE;for(var j=0;j<nVertex;j++){var valueIndex=color.doubleToIndex(values[j]);minIndex=Math.min(valueIndex,minIndex);maxIndex=Math.max(valueIndex,maxIndex);vertexIndex[j]=valueIndex}var mThresholds=color.getColorThresholds();var newCornersX=new Array(2*nVertex);var newCornersY=new Array(2*nVertex);for(var levelIndex=minIndex;levelIndex<=maxIndex;levelIndex++){var pointsAdded=0;for(var point=0;point<nVertex;point++){var nextPoint=(point+1)%nVertex;if(vertexIndex[point]<=levelIndex&&vertexIndex[nextPoint]>=levelIndex){if(vertexIndex[point]==levelIndex){newCornersX[pointsAdded]=a[point];newCornersY[pointsAdded]=b[point];pointsAdded++}else{var lambda=(mThresholds[levelIndex]-values[point])/(values[nextPoint]-values[point]);newCornersX[pointsAdded]=Math.round(a[point]+lambda*(a[nextPoint]-a[point]));newCornersY[pointsAdded]=Math.round(b[point]+lambda*(b[nextPoint]-b[point]));pointsAdded++}if(vertexIndex[nextPoint]>levelIndex){var lambda=(mThresholds[levelIndex+1]-values[point])/(values[nextPoint]-values[point]);newCornersX[pointsAdded]=Math.round(a[point]+lambda*(a[nextPoint]-a[point]));newCornersY[pointsAdded]=Math.round(b[point]+lambda*(b[nextPoint]-b[point]));pointsAdded++}}else if(vertexIndex[point]>=levelIndex&&vertexIndex[nextPoint]<=levelIndex){if(vertexIndex[point]==levelIndex){newCornersX[pointsAdded]=a[point];newCornersY[pointsAdded]=b[point];pointsAdded++}else{var lambda=(mThresholds[levelIndex+1]-values[point])/(values[nextPoint]-values[point]);newCornersX[pointsAdded]=Math.round(a[point]+lambda*(a[nextPoint]-a[point]));newCornersY[pointsAdded]=Math.round(b[point]+lambda*(b[nextPoint]-b[point]));pointsAdded++}if(vertexIndex[nextPoint]<levelIndex){var lambda=(mThresholds[levelIndex]-values[point])/(values[nextPoint]-values[point]);newCornersX[pointsAdded]=Math.round(a[point]+lambda*(a[nextPoint]-a[point]));newCornersY[pointsAdded]=Math.round(b[point]+lambda*(b[nextPoint]-b[point]));pointsAdded++}}}if(pointsAdded>0){fillCell(newCornersX,newCornersY,pointsAdded,color,levelIndex)}}}drawCell(a,b)}},buildBoundary:function(a,b,boundary){var boundaryA;var boundaryB;if(boundary!=null&&boundary.length>0){var num=boundary.length;boundaryA=new Array(num);boundaryB=new Array(num);for(var i=0;i<num;i++){var segment=boundary[i];var len=segment.length;boundaryA[i]=new Array(len);boundaryB[i]=new Array(len);for(var j=0;j<len;j++){var p=segment[j];boundaryA[i][j]=a[p];boundaryB[i][j]=b[p]}}}return{boundaryA:boundaryA,boundaryB:boundaryB}},drawBoundary:function(boundary,labels,colors,drawSegment){var boundaryA=boundary.boundaryA;var boundaryB=boundary.boundaryB;var segmentColor="black";for(var i=0,n=boundaryA.length;i<n;i++){if(labels!=null){var colorIndex=labels[i];if(colors!=null&&colorIndex<colors.length)segmentColor=colors[colorIndex]}drawSegment(boundaryA[i],boundaryB[i],segmentColor)}},drawImageField:function(ctx,pxTopLeftX,pxTopLeftY,xMin,yMin,pixWth,pixHgt,pxPerUnitX,pxPerUnitY,shape){function xToPix(x){return pxTopLeftX+(x-xMin)*pxPerUnitX}function yToPix(y){return pxTopLeftY-(y-yMin)*pxPerUnitY}var left=Math.round(xToPix(shape.xMin));var top=Math.round(yToPix(shape.yMax));var width=Math.round(pixWth);var height=Math.round(pixHgt);var imageData=ctx.getImageData(left,top,width,height);var maskpx=this.maskRadius*pxPerUnitX;var r=0;var g=0;var b=0;for(var i=0;i<width;i++){var ii=Math.floor(i*shape.nx/width);for(var j=0;j<height;j++){var jj=Math.floor(j*shape.ny/height);g=0;if(shape.data[ii][jj]<shape.lower){b=255;r=0}else if(shape.data[ii][jj]<shape.center){b=255*(shape.center-shape.data[ii][jj])/(shape.center-shape.lower);r=0}else if(shape.data[ii][jj]<shape.upper){b=0;r=255*(shape.data[ii][jj]-shape.center)/(shape.upper-shape.center)}else{b=0;r=255}if(shape.maskRadius>0){if(Math.sqrt((i-width/2)*(i-width/2)+(j-height/2)*(j-height/2))>maskpx){r=g=224;b=255}}var index=4*i+4*width*j;imageData.data[index+0]=r;imageData.data[index+1]=g;imageData.data[index+2]=b}}ctx.putImageData(imageData,left,top)}};var EJSS_SVGGRAPHICS=EJSS_SVGGRAPHICS||{};EJSS_SVGGRAPHICS.analyticCurve=function(mGraphics,mElement){function pathForanalyticCurve(points,x,y,sx,sy){var path="";for(var i=0;i<points.length;i++){var point=points[i];var xx=x+point[0]*sx;var yy=y+point[1]*sy;var type=point[2];if(i==0||type==0)path+=" M "+xx+" "+yy;else path+=" L "+xx+" "+yy}return path}var group,elementGroup=mElement.getGroup();if(elementGroup!==null)group=mGraphics.getElementById(elementGroup.getName());else group=mGraphics;var mShape=mGraphics.getElementById(mElement.getName());if(mShape===null){mShape=document.createElementNS("http://www.w3.org/2000/svg","path");mShape.setAttribute("id",mElement.getName());group.appendChild(mShape)}var pos=mElement.getPixelPosition();var size=mElement.getPixelSizes();var offset=mElement.getRelativePositionOffset(size);var x=pos[0]+offset[0];var y=pos[1]+offset[1];var mx=size[0]/2;var my=size[1]/2;var numPoints=mElement.getNumPoints();var mMinimun=mElement.getMinimun();var mMaximun=mElement.getMaximun();var min=typeof mMinimun=="undefined"||mMinimun===null?mElement.getPanel().getRealWorldXMin():mMinimun;var max=typeof mMaximun=="undefined"||mMaximun===null?mElement.getPanel().getRealWorldXMax():mMaximun;var vble=mElement.getVariable();var fx=mElement.getFunctionX();var fy=mElement.getFunctionY();var parser=EJSS_DRAWING2D.functionsParser();var exprfx;var exprfy;var mustReturn=false;try{exprfx=parser.parse(fx)}catch(errorfx){console.log("Analytic curve error parsing FunctionX: "+fx);mustReturn=true}if(!mustReturn){try{exprfy=parser.parse(fy)}catch(errorfy){console.log("Analytic curve error parsing FunctionY: "+fy);mustReturn=true}}if(mustReturn){mElement.getController().invokeAction("OnError");return}var step=(max-min)/(numPoints-1);var points=[];var vblevalue={};var parameters=mElement.getParameters();for(var param in parameters){vblevalue[param]=parameters[param]}try{for(var j=0,i=min;i<=max;i+=step){vblevalue[vble]=i;var fxvalue=exprfx.evaluate(vblevalue);var fyvalue=exprfy.evaluate(vblevalue);if(!isNaN(fxvalue)&&!isNaN(fyvalue)){points[j]=[];points[j][0]=fxvalue;points[j++][1]=fyvalue}}}catch(error){mElement.getController().invokeAction("OnError")}var analyticCurvepath=pathForanalyticCurve(points,x-mx,y-my,size[0],size[1]);if(analyticCurvepath!==""){mShape.setAttribute("d",analyticCurvepath);var style=mElement.getStyle();if(style.getDrawFill())mShape.setAttribute("fill",style.getFillColor());else mShape.setAttribute("fill","none");if(style.getDrawLines()){mShape.setAttribute("stroke",style.getLineColor());mShape.setAttribute("stroke-width",style.getLineWidth())}else{mShape.setAttribute("stroke","none");mShape.setAttribute("stroke-width",0)}mShape.setAttribute("shapeRendering",style.getShapeRendering());var attributes=style.getAttributes();for(var attr in attributes){mShape.setAttribute(attr,attributes[attr])}}return mShape};var EJSS_SVGGRAPHICS=EJSS_SVGGRAPHICS||{};EJSS_SVGGRAPHICS.arrow=function(mGraphics,mElement){};var EJSS_SVGGRAPHICS=EJSS_SVGGRAPHICS||{};EJSS_SVGGRAPHICS.axis=function(mGraphics,mElement){var UTILS=EJSS_SVGGRAPHICS.Utils;function drawLine(group,x,y,mx,my,style,orient,inverted){var mLine=document.createElementNS("http://www.w3.org/2000/svg","path");group.appendChild(mLine);if(orient==EJSS_DRAWING2D.Axis.AXIS_VERTICAL){if(inverted){my=-my;y=-y}if(style.getShapeRendering()=="crispEdges"){mLine.setAttribute("d","M "+UTILS.crispValue(x)+" "+UTILS.crispValue(y-.5-my)+" L "+UTILS.crispValue(x)+" "+UTILS.crispValue(y-.5+my))}else{mLine.setAttribute("d","M "+x+" "+(y-my)+" L "+x+" "+(y+my))}}else{if(style.getShapeRendering()=="crispEdges"){mLine.setAttribute("d","M "+UTILS.crispValue(x+.5-mx)+" "+UTILS.crispValue(y)+" L "+UTILS.crispValue(x+.5+mx)+" "+UTILS.crispValue(y))}else{mLine.setAttribute("d","M "+(x-mx)+" "+y+" L "+(x+mx)+" "+y)}}}function drawTick(group,x,y,ticksize,style,orient){if(orient==EJSS_DRAWING2D.Axis.AXIS_VERTICAL){var mTick=document.createElementNS("http://www.w3.org/2000/svg","path");group.appendChild(mTick);if(style.getShapeRendering()=="crispEdges"){mTick.setAttribute("d","M "+UTILS.crispValue(x-ticksize/2)+" "+UTILS.crispValue(y)+" L "+UTILS.crispValue(x+ticksize/2)+" "+UTILS.crispValue(y))}else{mTick.setAttribute("d","M "+(x-ticksize/2)+" "+y+" L "+(x+ticksize/2)+" "+y)}}else{var mTick=document.createElementNS("http://www.w3.org/2000/svg","path");group.appendChild(mTick);if(style.getShapeRendering()=="crispEdges"){mTick.setAttribute("d","M "+UTILS.crispValue(x)+" "+UTILS.crispValue(y-ticksize/2)+" L "+UTILS.crispValue(x)+" "+UTILS.crispValue(y+ticksize/2))}else{mTick.setAttribute("d","M "+x+" "+(y-ticksize/2)+" L "+x+" "+(y+ticksize/2))}}}function tickText(group,x,y,text,font,horizontal){var mTxtGroup=document.createElementNS("http://www.w3.org/2000/svg","g");group.appendChild(mTxtGroup);var mText=document.createElementNS("http://www.w3.org/2000/svg","text");mTxtGroup.appendChild(mText);mText.setAttribute("font-family",font.getFontFamily());mText.setAttribute("font-size",font.getFontSizeString());mText.setAttribute("fill",font.getFillColor());mText.setAttribute("stroke",font.getOutlineColor());mText.setAttribute("stroke-width",font.getFontWeight());mText.setAttribute("letterSpacing",font.getLetterSpacing());mText.textContent=text;if(horizontal){x-=mText.getComputedTextLength()/2+.5}else{y+=font.getFontSize()/2}mText.setAttribute("x",x);mText.setAttribute("y",y)}var group,elementGroup=mElement.getGroup();if(elementGroup!==null)group=mGraphics.getElementById(elementGroup.getName());else group=mGraphics;var mGroup=mGraphics.getElementById(mElement.getName());if(mGroup!==null)group.removeChild(mGroup);if(mElement.getShow()){mGroup=document.createElementNS("http://www.w3.org/2000/svg","g");mGroup.setAttribute("id",mElement.getName());group.appendChild(mGroup);var pos=mElement.getPixelPosition();var size=mElement.getPixelSizes();var offset=mElement.getRelativePositionOffset(size);var x=pos[0]+offset[0];var y=pos[1]+offset[1];var mx=size[0]/2;var my=size[1]/2;var style=mElement.getStyle();var orient=mElement.getOrient();var inverted=mElement.getInvertedScaleY();drawLine(mGroup,x,y,mx,my,style,orient,inverted);var segsize=orient==EJSS_DRAWING2D.Axis.AXIS_VERTICAL?Math.abs(size[1]):Math.abs(size[0]);var ticksmode=mElement.getTicksMode();if(ticksmode==EJSS_DRAWING2D.Axis.SCALE_LOG){var scale=mElement.getScale();if(scale[0]>0&&scale[1]>0){var ticks=mElement.getTicks();var scalePrecision=mElement.getScalePrecision();var ticksize=mElement.getTicksSize();EJSS_GRAPHICS.GraphicsUtils.drawLogTicks(x,y,mx,my,segsize,ticksize,scale,ticks,orient,function(x,y,ticksize,orient){drawTick(mGroup,x,y,ticksize,style,orient)});var font=mElement.getFont();var textPosition=mElement.getTextPosition();EJSS_GRAPHICS.GraphicsUtils.drawLogTicksText(x,y,mx,my,ticks,ticksize,scale,scalePrecision,font,textPosition,orient,function(x,y,text,font,horizontal){tickText(mGroup,x,y,text,font,horizontal)})}}else if(ticksmode==EJSS_DRAWING2D.Axis.SCALE_NUM){var step=0;var tickstep=0;if(!mElement.getAutoTicks()){var ticks=mElement.getTicks();if(ticks!=0){step=segsize/ticks}else{step=mElement.getStep();tickstep=mElement.getTickStep()}}else{var stepmin=mElement.getAutoStepMin();var ticksrange=mElement.getAutoTicksRange();for(var i=ticksrange.length-1;i>=0;i--){step=Math.abs(segsize/ticksrange[i]);if(step*1.001>=stepmin)break}}var scalePrecision=mElement.getScalePrecision();var scale=mElement.getScale();if(tickstep==0){var scalestep=Math.abs((scale[1]-scale[0])*step/segsize)}else{var scalestep=tickstep;step=Math.abs(scalestep*segsize/(scale[1]-scale[0]))}var decimals=Math.pow(10,scalePrecision);var scalestepTmp=Math.round(scalestep*decimals)/decimals;if(scalestepTmp>0){scalestep=scalestepTmp;step=Math.abs(scalestepTmp*segsize/(scale[1]-scale[0]))}var fixedTicks=mElement.getFixedTick();var tickfixed=scale[1];if(!isNaN(fixedTicks)){if(fixedTicks<scale[0])tickfixed=fixedTicks+(Math.floor((scale[0]-fixedTicks)/scalestep)+1)*scalestep;else if(fixedTicks>scale[1])tickfixed=fixedTicks-(Math.floor((fixedTicks-scale[1])/scalestep)+1)*scalestep;else tickfixed=fixedTicks}var scaleshift=Math.abs((scale[0]-tickfixed)%scalestep);var dist=Math.abs(scaleshift-scalestep);if(scaleshift<.001||dist<.001)scaleshift=0;var shift=segsize*scaleshift/Math.abs(scale[1]-scale[0]);var ticksize=mElement.getTicksSize();EJSS_GRAPHICS.GraphicsUtils.drawDecTicks(x,y,mx,my,ticksize,step,shift,orient,inverted,function(x,y,ticksize,orient){drawTick(mGroup,x,y,ticksize,style,orient)});var font=mElement.getFont();var textPosition=mElement.getTextPosition();EJSS_GRAPHICS.GraphicsUtils.drawDecTicksText(x,y,mx,my,ticksize,step,shift,scale,scalePrecision,scalestep,scaleshift,font,textPosition,orient,inverted,function(x,y,text,font,horizontal){tickText(mGroup,x,y,text,font,horizontal)})}if(style.getDrawFill())mGroup.setAttribute("fill",style.getFillColor());else mGroup.setAttribute("fill","none");if(style.getDrawLines()){mGroup.setAttribute("stroke",style.getLineColor());mGroup.setAttribute("stroke-width",style.getLineWidth())}else{mGroup.setAttribute("stroke","none");mGroup.setAttribute("stroke-width",0)}mGroup.setAttribute("shapeRendering",style.getShapeRendering());var attributes=style.getAttributes();for(var attr in attributes){mGroup.setAttribute(attr,attributes[attr])}}return mGroup};var EJSS_SVGGRAPHICS=EJSS_SVGGRAPHICS||{};EJSS_SVGGRAPHICS.byteRaster=function(mGraphics,mElement){};var EJSS_SVGGRAPHICS=EJSS_SVGGRAPHICS||{};EJSS_SVGGRAPHICS.canvas=function(mGraphics,mElement){var group,elementGroup=mElement.getGroup();if(elementGroup!==null)group=mGraphics.getElementById(elementGroup.getName());else group=mGraphics;var mShape=mGraphics.getElementById(mElement.getName());var myCanvasSrc;if(mShape===null){mShape=document.createElementNS("http://www.w3.org/2000/svg","foreignObject");mShape.setAttribute("id",mElement.getName());group.appendChild(mShape);myCanvasSrc=document.createElement("canvas");myCanvasSrc.setAttribute("id",mElement.getName()+".canvas");mShape.appendChild(myCanvasSrc)}else{myCanvasSrc=document.getElementById(mElement.getName()+".canvas")}var pos=mElement.getPixelPosition();var size=mElement.getPixelSizes();var offset=mElement.getRelativePositionOffset(size);var x=pos[0]+offset[0];var y=pos[1]+offset[1];myCanvasSrc.width=Math.abs(size[0]);myCanvasSrc.height=Math.abs(size[1]);mShape.width=Math.abs(size[0]);mShape.height=Math.abs(size[1]);var mx=Math.abs(size[0]/2);var my=Math.abs(size[1]/2);mShape.setAttribute("x",x-mx);mShape.setAttribute("y",y-my);var dim=mElement.getDimensions();var deltaX=dim[1]-dim[0];var deltaY=dim[3]-dim[2];var pixWth=Math.abs(size[0]);var pixHgt=Math.abs(size[1]);var pxPerUnitX=pixWth/deltaX;var pxPerUnitY=pixHgt/deltaY;var pxTopLeftX=x-pixWth/2;var pxTopLeftY=y+pixHgt/2;var drawables=mElement.getDrawables();var context=myCanvasSrc.getContext("2d");context.fillRect(0,0,myCanvasSrc.width-.5,myCanvasSrc.height-.5);for(var i=0;i<drawables.length;i++){if(typeof drawables[i].imageField!="undefined")EJSS_GRAPHICS.GraphicsUtils.drawImageField(context,pxTopLeftX,pxTopLeftY,xMin,yMin,pixWth,pixHgt,pxPerUnitX,pxPerUnitY,drawables[i]);else if(typeof drawables[i].run!="undefined")drawables[i].draw(context,pxTopLeftX,pxTopLeftY,xMin,yMin,pixWth,pixHgt,pxPerUnitX,pxPerUnitY)}var attributes=mElement.getStyle().getAttributes();for(var attr in attributes){mShape.setAttribute(attr,attributes[attr])}return mShape};var EJSS_SVGGRAPHICS=EJSS_SVGGRAPHICS||{};EJSS_SVGGRAPHICS.cellLattice=function(mGraphics,mElement){};var EJSS_SVGGRAPHICS=EJSS_SVGGRAPHICS||{};EJSS_SVGGRAPHICS.cursor=function(mGraphics,mElement){};var EJSS_SVGGRAPHICS=EJSS_SVGGRAPHICS||{};EJSS_SVGGRAPHICS.ellipse=function(mGraphics,mElement){var group,elementGroup=mElement.getGroup();if(elementGroup!==null)group=mGraphics.getElementById(elementGroup.getName());else group=mGraphics;var mShape=mGraphics.getElementById(mElement.getName());if(mShape===null){mShape=document.createElementNS("http://www.w3.org/2000/svg","ellipse");mShape.setAttribute("id",mElement.getName());group.appendChild(mShape)}var pos=mElement.getPixelPosition();var size=mElement.getPixelSizes();var offset=mElement.getRelativePositionOffset(size);var x=pos[0]+offset[0];var y=pos[1]+offset[1];var mx=Math.abs(size[0]/2);var my=Math.abs(size[1]/2);mShape.setAttribute("cx",x);mShape.setAttribute("cy",y);mShape.setAttribute("rx",mx);mShape.setAttribute("ry",my);var style=mElement.getStyle();if(style.getDrawFill())mShape.setAttribute("fill",style.getFillColor());else mShape.setAttribute("fill","none");if(style.getDrawLines()){mShape.setAttribute("stroke",style.getLineColor());mShape.setAttribute("stroke-width",style.getLineWidth())}else{mShape.setAttribute("stroke","none");mShape.setAttribute("stroke-width",0)}mShape.setAttribute("shapeRendering",style.getShapeRendering());var attributes=style.getAttributes();for(var attr in attributes){mShape.setAttribute(attr,attributes[attr])}return mShape};var EJSS_SVGGRAPHICS=EJSS_SVGGRAPHICS||{};EJSS_SVGGRAPHICS.grid=function(mGraphics,mElement){var group,elementGroup=mElement.getGroup();if(elementGroup!==null)group=mGraphics.getElementById(elementGroup.getName());else group=mGraphics;var mGroup=mGraphics.getElementById(mElement.getName());if(mGroup!==null)group.removeChild(mGroup);mGroup=document.createElementNS("http://www.w3.org/2000/svg","g");mGroup.setAttribute("id",mElement.getName());group.appendChild(mGroup);var mShapeX=document.createElementNS("http://www.w3.org/2000/svg","path");mShapeX.setAttribute("id",mElement.getName()+"X");mGroup.appendChild(mShapeX);var mShapeY=document.createElementNS("http://www.w3.org/2000/svg","path");mShapeY.setAttribute("id",mElement.getName()+"Y");mGroup.appendChild(mShapeY);var pos=mElement.getPixelPosition();var size=mElement.getPixelSizes();var offset=mElement.getRelativePositionOffset(size);var x=pos[0]+offset[0];var y=pos[1]+offset[1];var mx=size[0]/2;var my=size[1]/2;var showx=mElement.getShowX();var showy=mElement.getShowY();var pathX="";var pathY="";if(showx){var ticksXmode=mElement.getTicksXMode();if(ticksXmode==EJSS_DRAWING2D.Grid.SCALE_LOG){var scaleX=mElement.getScaleX();if(scaleX[0]>0&&scaleX[1]>0){var ticksX=mElement.getTicksX();var left=x-mx,right=x+mx,top=y+my,bottom=y-my;EJSS_GRAPHICS.GraphicsUtils.drawLogGrid(left,top,right,bottom,ticksX,scaleX,1,function(xx,yy){pathX+=" M "+xx+" "+yy},function(xx,yy){pathX+=" L "+xx+" "+yy})}}else if(ticksXmode==EJSS_DRAWING2D.Grid.SCALE_NUM){var stepx=0;var tickstepx=0;if(!mElement.getAutoTicksX()){var ticksX=mElement.getTicksX();if(ticksX!=0){stepx=Math.abs(size[0]/ticksX)}else{stepx=mElement.getStepX();tickstepx=mElement.getTickStepX()}}else{var stepxmin=mElement.getAutoStepXMin();var ticksxrange=mElement.getAutoTicksRangeX();for(var i=ticksxrange.length-1;i>=0;i--){stepx=Math.abs(size[0]/ticksxrange[i]);if(stepx>=stepxmin)break}}var scalePrecisionX=mElement.getScalePrecisionX();var scaleX=mElement.getScaleX();if(tickstepx==0){var scalestepX=Math.abs((scaleX[1]-scaleX[0])*stepx/size[0])}else{var scalestepX=tickstepx;stepx=Math.abs(scalestepX*size[0]/(scaleX[1]-scaleX[0]))}var decimalsX=Math.pow(10,scalePrecisionX);var scalestepXTmp=Math.round(scalestepX*decimalsX)/decimalsX;if(scalestepXTmp>0){scalestepX=scalestepXTmp;stepx=Math.abs(scalestepXTmp*size[0]/(scaleX[1]-scaleX[0]))}var fixedTicks=mElement.getFixedTickX();var tickfixed=scaleX[1];if(!isNaN(fixedTicks)){if(fixedTicks<scaleX[0])tickfixed=fixedTicks+(Math.floor((scaleX[0]-fixedTicks)/scalestepX)+1)*scalestepX;else if(fixedTicks>scaleX[1])tickfixed=fixedTicks-(Math.floor((fixedTicks-scaleX[1])/scalestepX)+1)*scalestepX;else tickfixed=fixedTicks}var scaleshift=Math.abs((scaleX[0]-tickfixed)%scalestepX);var dist=Math.abs(scaleshift-scalestepX);if(scaleshift<.001||dist<.001)scaleshift=0;var shiftx=Math.abs(size[0]*scaleshift/(scaleX[1]-scaleX[0]));var left=x-mx,right=x+mx,top=y+my,bottom=y-my;EJSS_GRAPHICS.GraphicsUtils.drawDecGrid(left,top,right,bottom,shiftx,stepx,1,function(xx,yy){pathX+=" M "+xx+" "+yy},function(xx,yy){pathX+=" L "+xx+" "+yy})}}if(showy){var ticksYmode=mElement.getTicksYMode();if(ticksYmode==EJSS_DRAWING2D.Grid.SCALE_LOG){var scaleY=mElement.getScaleY();if(scaleY[0]>0&&scaleY[1]>0){var ticksY=mElement.getTicksY();var left=x-mx,right=x+mx,top=y+my,bottom=y-my;EJSS_GRAPHICS.GraphicsUtils.drawLogGrid(left,top,right,bottom,ticksY,scaleY,-1,function(xx,yy){pathY+=" M "+xx+" "+yy},function(xx,yy){pathY+=" L "+xx+" "+yy})}}else if(ticksYmode==EJSS_DRAWING2D.Grid.SCALE_NUM){var stepy=0;var tickstepy=0;if(!mElement.getAutoTicksY()){var ticksY=mElement.getTicksY();if(ticksY!=0){stepy=Math.abs(size[1]/ticksY)}else{stepy=mElement.getStepY();tickstepy=mElement.getTickStepY()}}else{var stepymin=mElement.getAutoStepYMin();var ticksyrange=mElement.getAutoTicksRangeY();for(var i=ticksyrange.length-1;i>=0;i--){stepy=Math.abs(size[1]/ticksyrange[i]);if(stepy>=stepymin)break}}var scalePrecisionY=mElement.getScalePrecisionY();var scaleY=mElement.getScaleY();if(tickstepy==0){var scalestepY=Math.abs((scaleY[1]-scaleY[0])*stepy/size[1])}else{var scalestepY=tickstepy;stepy=Math.abs(scalestepY*size[1]/(scaleY[1]-scaleY[0]))}var decimalsY=Math.pow(10,scalePrecisionY);var scalestepYTmp=Math.round(scalestepY*decimalsY)/decimalsY;if(scalestepYTmp>0){scalestepY=scalestepYTmp;stepy=Math.abs(scalestepYTmp*size[1]/(scaleY[1]-scaleY[0]))}var fixedTicks=mElement.getFixedTickY();var tickfixed=scaleY[1];if(!isNaN(fixedTicks)){if(fixedTicks<scaleY[0])tickfixed=fixedTicks+(Math.floor((scaleY[0]-fixedTicks)/scalestepY)+1)*scalestepY;else if(fixedTicks>scaleY[1])tickfixed=fixedTicks-(Math.floor((fixedTicks-scaleY[1])/scalestepY)+1)*scalestepY;else tickfixed=fixedTicks}var scaleshift=Math.abs((scaleY[0]-tickfixed)%scalestepY);var dist=Math.abs(scaleshift-scalestepY);if(scaleshift<.001||dist<.001)scaleshift=0;var shifty=Math.abs(size[1]*scaleshift/(scaleY[1]-scaleY[0]));var left=x-mx,right=x+mx,top=y+my,bottom=y-my;EJSS_GRAPHICS.GraphicsUtils.drawDecGrid(left,top,right,bottom,shifty,stepy,-1,function(xx,yy){pathY+=" M "+xx+" "+yy},function(xx,yy){pathY+=" L "+xx+" "+yy})}}if(pathX.length>0){mShapeX.setAttribute("d",pathX);mShapeX.setAttribute("shapeRendering",mElement.getShapeRenderingX());mShapeX.setAttribute("stroke",mElement.getLineColorX());mShapeX.setAttribute("stroke-width",mElement.getLineWidthX())}if(pathY.length>0){mShapeY.setAttribute("d",pathY);mShapeY.setAttribute("shapeRendering",mElement.getShapeRenderingY());mShapeY.setAttribute("stroke",mElement.getLineColorY());mShapeY.setAttribute("stroke-width",mElement.getLineWidthY())}var attributes=mElement.getStyle().getAttributes();for(var attr in attributes){mShapeX.setAttribute(attr,attributes[attr]);mShapeY.setAttribute(attr,attributes[attr])}return mGroup};var EJSS_SVGGRAPHICS=EJSS_SVGGRAPHICS||{};EJSS_SVGGRAPHICS.group=function(mGraphics,mElement){var group,elementGroup=mElement.getGroup();if(elementGroup!==null)group=mGraphics.getElementById(elementGroup.getName());else group=mGraphics;var mShape=mGraphics.getElementById(mElement.getName());if(mShape===null){mShape=document.createElementNS("http://www.w3.org/2000/svg","g");mShape.setAttribute("id",mElement.getName());group.appendChild(mShape)}return mShape};var EJSS_SVGGRAPHICS=EJSS_SVGGRAPHICS||{};EJSS_SVGGRAPHICS.histogram=function(mGraphics,mElement){};var EJSS_SVGGRAPHICS=EJSS_SVGGRAPHICS||{};EJSS_SVGGRAPHICS.image=function(mGraphics,mElement){var group,elementGroup=mElement.getGroup();if(elementGroup!==null)group=mGraphics.getElementById(elementGroup.getName());else group=mGraphics;var mShape=mGraphics.getElementById(mElement.getName());if(mShape===null){mShape=document.createElementNS("http://www.w3.org/2000/svg","image");mShape.setAttribute("id",mElement.getName());group.appendChild(mShape)}var pos=mElement.getPixelPosition();var size=mElement.getPixelSizes();var offset=mElement.getRelativePositionOffset(size);var x=pos[0]+offset[0];var y=pos[1]+offset[1];var mx=Math.abs(size[0]/2);var my=Math.abs(size[1]/2);var current=mShape.getAttributeNS("http://www.w3.org/1999/xlink","href");if(!current||mElement.getChangedImage()){var code=mElement.getEncode();if(code.length>0){mShape.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href","data:png;base64,"+code)}else{mShape.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",mElement.getImageUrl())}mElement.setChangedImage(false)}mShape.setAttribute("preserveAspectRatio","none");mShape.setAttribute("x",x-mx);mShape.setAttribute("y",y-my);mShape.setAttribute("width",Math.abs(size[0]));mShape.setAttribute("height",Math.abs(size[1]));var style=mElement.getStyle();if(style.getDrawFill())mShape.setAttribute("fill",style.getFillColor());else mShape.setAttribute("fill","none");if(style.getDrawLines()){mShape.setAttribute("stroke",style.getLineColor());mShape.setAttribute("stroke-width",style.getLineWidth())}else{mShape.setAttribute("stroke","none");mShape.setAttribute("stroke-width",0)}mShape.setAttribute("shapeRendering",style.getShapeRendering());var attributes=style.getAttributes();for(var attr in attributes){mShape.setAttribute(attr,attributes[attr])}return mShape};var EJSS_SVGGRAPHICS=EJSS_SVGGRAPHICS||{};EJSS_SVGGRAPHICS.mesh=function(mGraphics,mElement){};var EJSS_SVGGRAPHICS=EJSS_SVGGRAPHICS||{};EJSS_SVGGRAPHICS.pipe=function(mGraphics,mElement){};var EJSS_SVGGRAPHICS=EJSS_SVGGRAPHICS||{};EJSS_SVGGRAPHICS.point=function(mGraphics,mElement){var group,elementGroup=mElement.getGroup();if(elementGroup!==null)group=mGraphics.getElementById(elementGroup.getName());else group=mGraphics;var mShape=mGraphics.getElementById(mElement.getName());if(mShape===null){mShape=document.createElementNS("http://www.w3.org/2000/svg","ellipse");mShape.setAttribute("id",mElement.getName());group.appendChild(mShape)}var pos=mElement.getPixelPosition();var size=mElement.getPixelSizes();var offset=mElement.getRelativePositionOffset(size);var x=pos[0]+offset[0];var y=pos[1]+offset[1];mShape.setAttribute("cx",x);mShape.setAttribute("cy",y);mShape.setAttribute("rx",2);mShape.setAttribute("ry",2);var style=mElement.getStyle();mShape.setAttribute("fill",style.getFillColor());var attributes=style.getAttributes();for(var attr in attributes){mShape.setAttribute(attr,attributes[attr])}return mShape};var EJSS_SVGGRAPHICS=EJSS_SVGGRAPHICS||{};EJSS_SVGGRAPHICS.polygon=function(mGraphics,mElement){var group,elementGroup=mElement.getGroup();if(elementGroup!==null)group=mGraphics.getElementById(elementGroup.getName());else group=mGraphics;var mShape=mGraphics.getElementById(mElement.getName());if(mShape===null){mShape=document.createElementNS("http://www.w3.org/2000/svg","path");mShape.setAttribute("id",mElement.getName());group.appendChild(mShape)}var pos=mElement.getPixelPosition();var size=mElement.getPixelSizes();var offset=mElement.getRelativePositionOffset(size);var x=pos[0]+offset[0];var y=pos[1]+offset[1];var mx=size[0]/2;var my=size[1]/2;var points=mElement.getPoints();var polpath="";for(var i=0;i<points.length;i++){var point=points[i];var xx=x-mx+point[0]*size[0];var yy=y-my+point[1]*size[1];var type=point[2];if(i==0||type==0)polpath+=" M "+xx+" "+yy;else polpath+=" L "+xx+" "+yy}if(polpath!==""){mShape.setAttribute("d",polpath);var style=mElement.getStyle();if(style.getDrawFill())mShape.setAttribute("fill",style.getFillColor());else mShape.setAttribute("fill","none");if(style.getDrawLines()){mShape.setAttribute("stroke",style.getLineColor());mShape.setAttribute("stroke-width",style.getLineWidth())}else{mShape.setAttribute("stroke","none");mShape.setAttribute("stroke-width",0)}mShape.setAttribute("shapeRendering",style.getShapeRendering());var attributes=style.getAttributes();for(var attr in attributes){mShape.setAttribute(attr,attributes[attr])}}return mShape};var EJSS_SVGGRAPHICS=EJSS_SVGGRAPHICS||{};EJSS_SVGGRAPHICS.rectangle=function(mGraphics,mElement){var UTILS=EJSS_SVGGRAPHICS.Utils;var group,elementGroup=mElement.getGroup();if(elementGroup!==null)group=mGraphics.getElementById(elementGroup.getName());else group=mGraphics;var mShape=mGraphics.getElementById(mElement.getName());if(mShape===null){mShape=document.createElementNS("http://www.w3.org/2000/svg","path");mShape.setAttribute("id",mElement.getName());group.appendChild(mShape)}var pos=mElement.getPixelPosition();var size=mElement.getPixelSizes();var offset=mElement.getRelativePositionOffset(size);var x=pos[0]+offset[0];var y=pos[1]+offset[1];var mx=size[0]/2;var my=size[1]/2;var style=mElement.getStyle();if(style.getShapeRendering()=="crispEdges"){mShape.setAttribute("d","M "+UTILS.crispValue(x-mx)+" "+UTILS.crispValue(y+my)+" L "+UTILS.crispValue(x+mx)+" "+UTILS.crispValue(y+my)+" L "+UTILS.crispValue(x+mx)+" "+UTILS.crispValue(y-my)+" L "+UTILS.crispValue(x-mx)+" "+UTILS.crispValue(y-my)+" z")}else{mShape.setAttribute("d","M "+(x-mx)+" "+(y+my)+" L "+(x+mx)+" "+(y+my)+" L "+(x+mx)+" "+(y-my)+" L "+(x-mx)+" "+(y-my)+" z")}if(style.getDrawFill())mShape.setAttribute("fill",style.getFillColor());else mShape.setAttribute("fill","none");if(style.getDrawLines()){mShape.setAttribute("stroke",style.getLineColor());mShape.setAttribute("stroke-width",style.getLineWidth())}else{mShape.setAttribute("stroke","none");mShape.setAttribute("stroke-width",0)}mShape.setAttribute("shapeRendering",style.getShapeRendering());var attributes=style.getAttributes();for(var attr in attributes){mShape.setAttribute(attr,attributes[attr])}return mShape};var EJSS_SVGGRAPHICS=EJSS_SVGGRAPHICS||{};EJSS_SVGGRAPHICS.roundRectangle=function(mGraphics,mElement){var group,elementGroup=mElement.getGroup();if(elementGroup!==null)group=mGraphics.getElementById(elementGroup.getName());else group=mGraphics;var mShape=mGraphics.getElementById(mElement.getName());if(mShape===null){mShape=document.createElementNS("http://www.w3.org/2000/svg","rect");mShape.setAttribute("id",mElement.getName());group.appendChild(mShape)}var pos=mElement.getPixelPosition();var size=mElement.getPixelSizes();var offset=mElement.getRelativePositionOffset(size);var x=pos[0]+offset[0];var y=pos[1]+offset[1];var mx=Math.abs(size[0]/2);var my=Math.abs(size[1]/2);var radius=Math.abs(mElement.getCornerRadius());mShape.setAttribute("x",x-mx);mShape.setAttribute("y",y-my);mShape.setAttribute("width",Math.abs(size[0]));mShape.setAttribute("height",Math.abs(size[1]));mShape.setAttribute("rx",radius);mShape.setAttribute("ry",radius);var style=mElement.getStyle();if(style.getDrawFill())mShape.setAttribute("fill",style.getFillColor());else mShape.setAttribute("fill","none");if(style.getDrawLines()){mShape.setAttribute("stroke",style.getLineColor());mShape.setAttribute("stroke-width",style.getLineWidth())}else{mShape.setAttribute("stroke","none");mShape.setAttribute("stroke-width",0)}mShape.setAttribute("shapeRendering",style.getShapeRendering());var attributes=style.getAttributes();for(var attr in attributes){mShape.setAttribute(attr,attributes[attr])}return mShape};var EJSS_SVGGRAPHICS=EJSS_SVGGRAPHICS||{};EJSS_SVGGRAPHICS.scalarField=function(mGraphics,mElement){var group,elementGroup=mElement.getGroup();if(elementGroup!==null)group=mGraphics.getElementById(elementGroup.getName());else group=mGraphics;var mShape=mGraphics.getElementById(mElement.getName());var myScalarFieldSrc;if(mShape===null){mShape=document.createElementNS("http://www.w3.org/2000/svg","foreignObject");mShape.setAttribute("id",mElement.getName());group.appendChild(mShape);myScalarFieldSrc=document.createElement("scalarField");myScalarFieldSrc.setAttribute("id",mElement.getName()+".scalarField");mShape.appendChild(myScalarFieldSrc)}else{myScalarFieldSrc=document.getElementById(mElement.getName()+".scalarField")}var pos=mElement.getPixelPosition();var size=mElement.getPixelSizes();var offset=mElement.getRelativePositionOffset(size);var x=pos[0]+offset[0];var y=pos[1]+offset[1];myScalarFieldSrc.width=Math.abs(size[0]);myScalarFieldSrc.height=Math.abs(size[1]);mShape.width=Math.abs(size[0]);mShape.height=Math.abs(size[1]);var mx=Math.abs(size[0]/2);var my=Math.abs(size[1]/2);mShape.setAttribute("x",x-mx);mShape.setAttribute("y",y-my);var deltaX=mElement.getMaximumX()-mElement.getMinimumX();var deltaY=mElement.getMaximumY()-mElement.getMinimumY();var pixWth=Math.abs(size[0]);var pixHgt=Math.abs(size[1])
;var pxPerUnitX=pixWth/deltaX;var pxPerUnitY=pixHgt/deltaY;var pxTopLeftX=x-pixWth/2;var pxTopLeftY=y+pixHgt/2;var context=myScalarFieldSrc.getContext("2d");context.fillRect(0,0,myScalarFieldSrc.width-.5,myScalarFieldSrc.height-.5);EJSS_GRAPHICS.GraphicsUtils.drawImageField(context,pxTopLeftX,pxTopLeftY,mElement.getMinimumX(),mElement.getMinimumY(),pixWth,pixHgt,pxPerUnitX,pxPerUnitY,{data:mElement.getData()});var attributes=mElement.getStyle().getAttributes();for(var attr in attributes){mShape.setAttribute(attr,attributes[attr])}return mShape};var EJSS_SVGGRAPHICS=EJSS_SVGGRAPHICS||{};EJSS_SVGGRAPHICS.segment=function(mGraphics,mElement){var UTILS=EJSS_SVGGRAPHICS.Utils;var group,elementGroup=mElement.getGroup();if(elementGroup!==null)group=mGraphics.getElementById(elementGroup.getName());else group=mGraphics;var mShape=mGraphics.getElementById(mElement.getName());if(mShape===null){mShape=document.createElementNS("http://www.w3.org/2000/svg","path");mShape.setAttribute("id",mElement.getName());group.appendChild(mShape)}var pos=mElement.getPixelPosition();var size=mElement.getPixelSizes();var offset=mElement.getRelativePositionOffset(size);var x=pos[0]+offset[0];var y=pos[1]+offset[1];var mx=size[0]/2;var my=size[1]/2;var style=mElement.getStyle();if(style.getShapeRendering()=="crispEdges"){mShape.setAttribute("d","M "+UTILS.crispValue(x-mx)+" "+UTILS.crispValue(y-my)+" L "+UTILS.crispValue(x+mx)+" "+UTILS.crispValue(y+my))}else{mShape.setAttribute("d","M "+(x-mx)+" "+(y-my)+" L "+(x+mx)+" "+(y+my))}if(style.getDrawFill())mShape.setAttribute("fill",style.getFillColor());else mShape.setAttribute("fill","none");if(style.getDrawLines()){mShape.setAttribute("stroke",style.getLineColor());mShape.setAttribute("stroke-width",style.getLineWidth())}else{mShape.setAttribute("stroke","none");mShape.setAttribute("stroke-width",0)}mShape.setAttribute("shapeRendering",style.getShapeRendering());var attributes=style.getAttributes();for(var attr in attributes){mShape.setAttribute(attr,attributes[attr])}return mShape};var EJSS_SVGGRAPHICS=EJSS_SVGGRAPHICS||{};EJSS_SVGGRAPHICS.spring=function(mGraphics,mElement){};var EJSS_SVGGRAPHICS=EJSS_SVGGRAPHICS||{};EJSS_SVGGRAPHICS.tank=function(mGraphics,mElement){};var EJSS_SVGGRAPHICS=EJSS_SVGGRAPHICS||{};EJSS_SVGGRAPHICS.text=function(mGraphics,mElement){var group,elementGroup=mElement.getGroup();if(elementGroup!==null)group=mGraphics.getElementById(elementGroup.getName());else group=mGraphics;var mGroup=mGraphics.getElementById(mElement.getName());var mInnerGroup,mText,mBox;if(mGroup===null){mGroup=document.createElementNS("http://www.w3.org/2000/svg","g");mGroup.setAttribute("id",mElement.getName());group.appendChild(mGroup);mInnerGroup=document.createElementNS("http://www.w3.org/2000/svg","g");mInnerGroup.setAttribute("id",mElement.getName()+".inner");mGroup.appendChild(mInnerGroup);mBox=document.createElementNS("http://www.w3.org/2000/svg","path");mBox.setAttribute("id",mElement.getName()+".box");mInnerGroup.appendChild(mBox);mText=document.createElementNS("http://www.w3.org/2000/svg","text");mText.setAttribute("id",mElement.getName()+".text");mInnerGroup.appendChild(mText)}else{mInnerGroup=mGraphics.getElementById(mElement.getName()+".inner");mText=mGraphics.getElementById(mElement.getName()+".text");mBox=mGraphics.getElementById(mElement.getName()+".box")}while(mText.firstChild){mText.removeChild(mText.firstChild)}var font=mElement.getFont();mText.setAttribute("font-style",font.getFontStyle());mText.setAttribute("font-weight",font.getFontWeight());mText.setAttribute("font-size",font.getFontSizeString());mText.setAttribute("font-family",font.getFontFamily());mText.setAttribute("fill",font.getFillColor());mText.setAttribute("stroke",font.getOutlineColor());mText.setAttribute("stroke-width",font.getOutlineWidth());mText.setAttribute("letterSpacing",font.getLetterSpacing());var text=mElement.getText();var arr=text.split("\n");var maxLength;var maxHeight;var drawingSize=mElement.getDrawingSize();if(drawingSize[0]==-1){if(typeof text=="undefined"||text==null)text="";maxLength=0;maxHeight=font.getFontSize();mText.textContent="";mText.setAttribute("visibility","hidden");for(i=0;i<arr.length;i++){mText.textContent=arr[i];var len=mText.getComputedTextLength();if(len>maxLength)maxLength=len;if(i>0)maxHeight+=1.8*font.getFontSize()}mText.setAttribute("visibility","inherit");mText.textContent="";mElement.setDrawingSize([maxLength,maxHeight])}else{maxLength=drawingSize[0];maxHeight=drawingSize[1]}var pos=mElement.getPixelPosition();var marginFrame=mElement.getFramed()?4:0;var size=[maxLength+marginFrame*2,maxHeight/1.5+marginFrame*2];var offset=EJSS_DRAWING2D.Element.getSWRelativePositionOffset(mElement.getRelativePosition(),size[0],size[1]);var xmargin=mElement.getMarginX();var ymargin=mElement.getMarginY();var x=pos[0]+offset[0]+xmargin+marginFrame;var y=pos[1]+offset[1]+ymargin-marginFrame;mText.setAttribute("x",x);mText.setAttribute("y",y);for(i=arr.length-1;i>=0;i--){var ts=document.createElementNS("http://www.w3.org/2000/svg","tspan");if(i==arr.length-1)ts.setAttribute("y",y);else ts.setAttribute("dy","-1.2em");ts.setAttribute("x",x);ts.textContent=arr[i];mText.appendChild(ts)}if(mElement.getFramed()){var tbmargin=marginFrame;var rlmargin=marginFrame;var wlen=size[0]-marginFrame*2;var hlen=size[1]-marginFrame*2;if(wlen>0){var bottom=y+tbmargin,top=y-hlen-tbmargin;var left=x-rlmargin,rigth=x+wlen+tbmargin;mBox.setAttribute("d","M "+left+" "+bottom+" L "+rigth+" "+bottom+" L "+rigth+" "+top+" L "+left+" "+top+" z");var style=mElement.getStyle();if(style.getDrawFill())mBox.setAttribute("fill",style.getFillColor());else mBox.setAttribute("fill","none");if(style.getDrawLines()){mBox.setAttribute("stroke",style.getLineColor());mBox.setAttribute("stroke-width",style.getLineWidth())}else{mBox.setAttribute("stroke","none");mBox.setAttribute("stroke-width",0)}var attributes=style.getAttributes();for(var attr in attributes){mShape.setAttribute(attr,attributes[attr])}}else{mBox.setAttribute("stroke","none");mBox.setAttribute("fill","none")}}var angletext=0;switch(mElement.getWritingMode()){case EJSS_DRAWING2D.Text.MODE_TOPDOWN:angletext=90;break;case EJSS_DRAWING2D.Text.MODE_RIGTHLEFT:angletext=180;break;case EJSS_DRAWING2D.Text.MODE_DOWNTOP:angletext=270;break;case EJSS_DRAWING2D.Text.MODE_LEFTRIGHT:angletext=0;break}mInnerGroup.setAttribute("transform","rotate("+angletext+" "+(pos[0]+xmargin)+" "+(pos[1]+ymargin)+")");return mGroup};var EJSS_SVGGRAPHICS=EJSS_SVGGRAPHICS||{};EJSS_SVGGRAPHICS.trace=function(mGraphics,mElement){};var EJSS_SVGGRAPHICS=EJSS_SVGGRAPHICS||{};EJSS_SVGGRAPHICS.trail=function(mGraphics,mElement){};var EJSS_SVGGRAPHICS=EJSS_SVGGRAPHICS||{};EJSS_SVGGRAPHICS.Utils={};EJSS_SVGGRAPHICS.Utils.crispValue=function(value){return Math.round(+value.toFixed(4)+.5)-.5};EJSS_SVGGRAPHICS.Utils.crispTop=function(value){return Math.round(+value.toFixed(4)+.5)-.5};EJSS_SVGGRAPHICS.Utils.round=function(value){return+value.toFixed(4)};EJSS_SVGGRAPHICS.Utils.hsl2rgb=function(hsl){var H=hsl[0],S=hsl[1],L=hsl[2];var C=(1-Math.abs(2*L-1))*S;var H_=H/60;var X=C*(1-Math.abs(H_%2-1));var R1,G1,B1;if(H===undefined||isNaN(H)||H===null){R1=G1=B1=0}else{if(H_>=0&&H_<1){R1=C;G1=X;B1=0}else if(H_>=1&&H_<2){R1=X;G1=C;B1=0}else if(H_>=2&&H_<3){R1=0;G1=C;B1=X}else if(H_>=3&&H_<4){R1=0;G1=X;B1=C}else if(H_>=4&&H_<5){R1=X;G1=0;B1=C}else if(H_>=5&&H_<6){R1=C;G1=0;B1=X}}var m=L-C/2;var R,G,B;R=(R1+m)*255;G=(G1+m)*255;B=(B1+m)*255;R=Math.round(R);G=Math.round(G);B=Math.round(B);return{r:R,g:G,b:B}};EJSS_SVGGRAPHICS.Utils.PNGCanvasWorker=function(params){var imageData=params.data.params.imageData;var width=params.data.params.width;var height=params.data.params.height;var depth=params.data.params.depth;var data=params.data.params.data;var colors=params.data.params.colors;var index=params.data.id;function Rgb(rgb){var rgb=rgb.substring(4,rgb.length-1).replace(/ /g,"").split(",");return{r:rgb[0],g:rgb[1],b:rgb[2]}}function Hsl(hsl){var hsl=hsl.substring(4,hsl.length-1).replace(/ /g,"").replace(/%/g,"").split(",");return{h:hsl[0],s:hsl[1]/100,l:hsl[2]/100}}function setPixel(imageData,x,y,r,g,b,a){index=(x+y*imageData.width)*4;imageData.data[index+0]=r;imageData.data[index+1]=g;imageData.data[index+2]=b;imageData.data[index+3]=a}var cinf=colors[0];var csup=colors[colors.length-1];for(var i=0;i<width;i++){for(var j=0;j<height;j++){var index=data[i][height-j-1];var color=index<0?cinf:index<colors.length?colors[index]:csup;if(typeof color=="undefined")color=cinf;if(color.substring(0,3)=="rgb"){rgb=Rgb(color)}else if(color.substring(0,3)=="hsl"){rgb=EJSS_SVGGRAPHICS.Utils.hsl2rgb(Hsl(color))}setPixel(imageData,i,j,rgb.r,rgb.g,rgb.b,255)}}self.postMessage({result:imageData,id:index})};EJSS_SVGGRAPHICS.Utils.PNGCanvasNoWorker=function(imageData,width,height,depth,data,colors){function Rgb(rgb){var rgb=rgb.substring(4,rgb.length-1).replace(/ /g,"").split(",");return{r:rgb[0],g:rgb[1],b:rgb[2]}}function Hsl(hsl){var hsl=hsl.substring(4,hsl.length-1).replace(/ /g,"").replace(/%/g,"").split(",");return{h:hsl[0],s:hsl[1]/100,l:hsl[2]/100}}function setPixel(imageData,x,y,r,g,b,a){index=(x+y*imageData.width)*4;imageData.data[index+0]=r;imageData.data[index+1]=g;imageData.data[index+2]=b;imageData.data[index+3]=a}var cinf=colors[0];var csup=colors[colors.length-1];for(var i=0;i<width;i++){for(var j=0;j<height;j++){var index=data[i][height-j-1];var color=index<0?cinf:index<colors.length?colors[index]:csup;if(typeof color=="undefined")color=cinf;if(color.substring(0,3)=="rgb"){rgb=Rgb(color)}else if(color.substring(0,3)=="hsl"){rgb=EJSS_SVGGRAPHICS.Utils.hsl2rgb(Hsl(color))}setPixel(imageData,i,j,rgb.r,rgb.g,rgb.b,255)}}};EJSS_SVGGRAPHICS.Utils.PNGCanvas=function(width,height,depth,data,colors,callback){var element=document.createElement("canvas");element.setAttribute("width",width);element.setAttribute("height",height);var c=element.getContext("2d");var imageData=c.createImageData(width,height);if(EJSS_TOOLS.Worker.runFunction){EJSS_TOOLS.Worker.runFunction("PNGCanvasWorker",EJSS_SVGGRAPHICS.Utils.PNGCanvasWorker,{imageData:imageData,width:width,height:height,depth:depth,data:data,colors:colors},function(result){c.putImageData(result.result,0,0);callback(element.toDataURL())})}else{EJSS_SVGGRAPHICS.Utils.PNGCanvasNoWorker(imageData,width,height,depth,data,colors);c.putImageData(imageData,0,0);callback(element.toDataURL())}};EJSS_SVGGRAPHICS.Utils.ImageDataCanvas=function(width,height,depth,data,colors,callback){var element=document.createElement("canvas");element.setAttribute("width",width);element.setAttribute("height",height);var c=element.getContext("2d");var imageData=c.createImageData(width,height);EJSS_TOOLS.Worker.runFunction("PNGCanvasWorker",EJSS_SVGGRAPHICS.Utils.PNGCanvasWorker,{imageData:imageData,width:width,height:height,depth:depth,data:data,colors:colors},function(result){callback(result)})};var EJSS_SVGGRAPHICS=EJSS_SVGGRAPHICS||{};EJSS_SVGGRAPHICS.video=function(mGraphics,mElement){};var EJSS_SVGGRAPHICS=EJSS_SVGGRAPHICS||{};EJSS_SVGGRAPHICS.wheel=function(mGraphics,mElement){var group,elementGroup=mElement.getGroup();if(elementGroup!==null)group=mGraphics.getElementById(elementGroup.getName());else group=mGraphics;var mGroup=mGraphics.getElementById(mElement.getName());var mCircle,mCross;if(mGroup===null){mGroup=document.createElementNS("http://www.w3.org/2000/svg","g");mGroup.setAttribute("id",mElement.getName());group.appendChild(mGroup);mCircle=document.createElementNS("http://www.w3.org/2000/svg","ellipse");mCircle.setAttribute("id",mElement.getName()+".circle");mGroup.appendChild(mCircle);mCross=document.createElementNS("http://www.w3.org/2000/svg","path");mCross.setAttribute("id",mElement.getName()+".cross");mGroup.appendChild(mCross)}else{mCircle=mGraphics.getElementById(mElement.getName()+".circle");mCross=mGraphics.getElementById(mElement.getName()+".cross")}var pos=mElement.getPixelPosition();var size=mElement.getPixelSizes();var offset=mElement.getRelativePositionOffset(size);var x=pos[0]+offset[0];var y=pos[1]+offset[1];var mx=size[0]/2;var my=size[1]/2;mCircle.setAttribute("cx",x);mCircle.setAttribute("cy",y);mCircle.setAttribute("rx",Math.abs(mx));mCircle.setAttribute("ry",Math.abs(my));mCross.setAttribute("d","M "+(x-mx)+" "+y+" L "+(x+mx)+" "+y+" M "+x+" "+(y-my)+" L "+x+" "+(y+my));var style=mElement.getStyle();if(style.getDrawFill())mGroup.setAttribute("fill",style.getFillColor());else mGroup.setAttribute("fill","none");if(style.getDrawLines()){mGroup.setAttribute("stroke",style.getLineColor());mGroup.setAttribute("stroke-width",style.getLineWidth())}else{mGroup.setAttribute("stroke","none");mGroup.setAttribute("stroke-width",0)}mGroup.setAttribute("shapeRendering",style.getShapeRendering());var attributes=style.getAttributes();for(var attr in attributes){mGroup.setAttribute(attr,attributes[attr])}return mGroup};var EJSS_GRAPHICS=EJSS_GRAPHICS||{};EJSS_GRAPHICS.SvgGraphics={getOffsetRect:function(graphics){return EJSS_GRAPHICS.GraphicsUtils.getOffsetRect(graphics)}};EJSS_GRAPHICS.svgGraphics=function(mName){var self=EJSS_INTERFACE.svgGraphics(mName);var mInterfaceGraphics=self.getDOMElement();var mDefs=document.createElementNS("http://www.w3.org/2000/svg","defs");mInterfaceGraphics.appendChild(mDefs);self.getEventContext=function(){return mInterfaceGraphics};self.getBox=function(){var box=EJSS_GRAPHICS.CanvasGraphics.getOffsetRect(self);box.width-=1;box.height-=1;return box};self.remove=function(name){var myElement=mInterfaceGraphics.getElementById(name);if(myElement!==null){mInterfaceGraphics.removeChild(myElement);return true}return false};self.reset=function(){while(mInterfaceGraphics.firstChild){mInterfaceGraphics.removeChild(mInterfaceGraphics.firstChild)}mInterfaceGraphics.appendChild(mDefs)};self.getDefs=function(){return mDefs};self.draw=function(elements,force){for(var i=0,n=elements.length;i<n;i++){var element=elements[i];if(element.getElements){var lasts=element.getLastElements();for(var j=0,m=lasts.length;j<m;j++){var mShape=mInterfaceGraphics.getElementById(lasts[j].getName());if(mShape)mShape.parentNode.removeChild(mShape)}}if(force||element.isChanged()||element.isGroupChanged()||element.isMustProject()){var build=self.drawElement(element);if(typeof build!="undefined"&&build!=null)self.transformElement(element,build)}}};self.drawElement=function(element){var Shape=EJSS_DRAWING2D.Shape;var build=null;switch(element._23()){case"ElementCustom":{var customFunction=element.getFunction();if(customFunction)build=customFunction(mInterfaceGraphics,element)}break;case"ElementGroup":build=EJSS_SVGGRAPHICS.group(mInterfaceGraphics,element);break;case"ElementShape":switch(element.getShapeType()){default:case Shape.ELLIPSE:build=EJSS_SVGGRAPHICS.ellipse(mInterfaceGraphics,element);break;case Shape.RECTANGLE:build=EJSS_SVGGRAPHICS.rectangle(mInterfaceGraphics,element);break;case Shape.ROUND_RECTANGLE:build=EJSS_SVGGRAPHICS.roundRectangle(mInterfaceGraphics,element);break;case Shape.WHEEL:build=EJSS_SVGGRAPHICS.wheel(mInterfaceGraphics,element);break;case Shape.NONE:case Shape.POINT:build=EJSS_SVGGRAPHICS.point(mInterfaceGraphics,element);break}break;case"ElementSegment":build=EJSS_SVGGRAPHICS.segment(mInterfaceGraphics,element);break;case"ElementImage":build=EJSS_SVGGRAPHICS.image(mInterfaceGraphics,element);break;case"ElementVideo":build=EJSS_SVGGRAPHICS.video(mInterfaceGraphics,element);break;case"ElementArrow":build=EJSS_SVGGRAPHICS.arrow(mInterfaceGraphics,element);break;case"ElementText":build=EJSS_SVGGRAPHICS.text(mInterfaceGraphics,element);break;case"ElementSpring":build=EJSS_SVGGRAPHICS.spring(mInterfaceGraphics,element);break;case"ElementTrail":build=EJSS_SVGGRAPHICS.trail(mInterfaceGraphics,element);break;case"ElementTrace":build=EJSS_SVGGRAPHICS.trace(mInterfaceGraphics,element);break;case"ElementGrid":build=EJSS_SVGGRAPHICS.grid(mInterfaceGraphics,element);break;case"ElementAxis":build=EJSS_SVGGRAPHICS.axis(mInterfaceGraphics,element);break;case"ElementCursor":build=EJSS_SVGGRAPHICS.cursor(mInterfaceGraphics,element);break;case"ElementPolygon":build=EJSS_SVGGRAPHICS.polygon(mInterfaceGraphics,element);break;case"ElementAnalyticCurve":build=EJSS_SVGGRAPHICS.analyticCurve(mInterfaceGraphics,element);break;case"ElementCellLattice":build=EJSS_SVGGRAPHICS.cellLattice(mInterfaceGraphics,element);break;case"ElementByteRaster":build=EJSS_SVGGRAPHICS.byteRaster(mInterfaceGraphics,element);break;case"ElementMesh":build=EJSS_SVGGRAPHICS.mesh(mInterfaceGraphics,element);break;case"ElementTank":build=EJSS_SVGGRAPHICS.tank(mInterfaceGraphics,element);break;case"ElementPipe":build=EJSS_SVGGRAPHICS.pipe(mInterfaceGraphics,element);break;case"ElementHistogram":build=EJSS_SVGGRAPHICS.histogram(mInterfaceGraphics,element);break;case"ElementScalarField":build=EJSS_SVGGRAPHICS.scalarField(mInterfaceGraphics,element);break;case"ElementCanvas":build=EJSS_SVGGRAPHICS.canvas(mInterfaceGraphics,element);break}if(build){if(!element.isGroupVisible())build.setAttribute("visibility","hidden");else build.setAttribute("visibility","visible")}return build};self.transformElement=function(element,build){var trstr="";var trans=element.getTransformation();var rot=element.getRotate();if(trans.length>0){trstr="matrix("+trans[0]+" "+trans[1]+" "+trans[2]+" "+trans[3]+" "+trans[4]+" "+trans[5]+")"}if(rot>0){var angle=EJSS_TOOLS.Mathematics.degrees(-rot);trstr+=" rotate("+angle+")"}if(trstr.length>0){var pos=element.getPixelPosition();build.setAttribute("transform",trstr);build.setAttribute("transform-origin",pos[0]+"px "+pos[1]+"px")}};self._24=function(panel){var gutters=panel.getGutters();if(gutters.visible){var UTILS=EJSS_SVGGRAPHICS.Utils;var mShape=mInterfaceGraphics.getElementById(".myGutters");var mOuterBorder=mInterfaceGraphics.getElementById(".myOuterBorder");var mInnerBorder=mInterfaceGraphics.getElementById(".myInnerBorder");if(mShape===null){mShape=document.createElementNS("http://www.w3.org/2000/svg","path");mShape.setAttribute("id",".myGutters");mShape.setAttribute("stroke","none");mShape.setAttribute("stroke-width",0);mInterfaceGraphics.appendChild(mShape)
;mOuterBorder=document.createElementNS("http://www.w3.org/2000/svg","path");mOuterBorder.setAttribute("id",".myOuterBorder");mOuterBorder.setAttribute("fill","none");mInterfaceGraphics.appendChild(mOuterBorder);mInnerBorder=document.createElementNS("http://www.w3.org/2000/svg","path");mInnerBorder.setAttribute("id",".myInnerBorder");mInnerBorder.setAttribute("fill","none");mInterfaceGraphics.appendChild(mInnerBorder)}var inner=panel.getInnerRect();var x=.5,y=.5;var box=self.getBox();var sx=box.width,sy=box.height;var guttersStyle=panel.getGuttersStyle();var panelStyle=panel.getStyle();if(panelStyle.getShapeRendering()=="crispEdges"){mShape.setAttribute("d","M "+UTILS.crispValue(x)+" "+UTILS.crispValue(y)+" L "+UTILS.crispValue(x)+" "+UTILS.crispValue(y+sy)+" L "+UTILS.crispValue(x+sx)+" "+UTILS.crispValue(y+sy)+" L "+UTILS.crispValue(x+sx)+" "+UTILS.crispValue(y)+" L "+UTILS.crispValue(x)+" "+UTILS.crispValue(y)+" M "+UTILS.crispValue(inner.x)+" "+UTILS.crispValue(inner.y)+" L "+UTILS.crispValue(inner.x+inner.width)+" "+UTILS.crispValue(inner.y)+" L "+UTILS.crispValue(inner.x+inner.width)+" "+UTILS.crispValue(inner.y+inner.height)+" L "+UTILS.crispValue(inner.x)+" "+UTILS.crispValue(inner.y+inner.height)+" L "+UTILS.crispValue(inner.x)+" "+UTILS.crispValue(inner.y)+" z");mOuterBorder.setAttribute("d","M "+UTILS.crispValue(x)+" "+UTILS.crispValue(y)+" L "+UTILS.crispValue(x)+" "+UTILS.crispValue(y+sy)+" L "+UTILS.crispValue(x+sx)+" "+UTILS.crispValue(y+sy)+" L "+UTILS.crispValue(x+sx)+" "+UTILS.crispValue(y)+" L "+UTILS.crispValue(x)+" "+UTILS.crispValue(y)+" z");mInnerBorder.setAttribute("d","M "+UTILS.crispValue(inner.x)+" "+UTILS.crispValue(inner.y)+" L "+UTILS.crispValue(inner.x+inner.width)+" "+UTILS.crispValue(inner.y)+" L "+UTILS.crispValue(inner.x+inner.width)+" "+UTILS.crispValue(inner.y+inner.height)+" L "+UTILS.crispValue(inner.x)+" "+UTILS.crispValue(inner.y+inner.height)+" L "+UTILS.crispValue(inner.x)+" "+UTILS.crispValue(inner.y)+" z")}else{mShape.setAttribute("d","M "+x+" "+y+" L "+x+" "+(y+sy)+" L "+(x+sx)+" "+(y+sy)+" L "+(x+sx)+" "+y+" L "+x+" "+y+" M "+inner.x+" "+inner.y+" L "+(inner.x+inner.width)+" "+inner.y+" L "+(inner.x+inner.width)+" "+(inner.y+inner.height)+" L "+inner.x+" "+(inner.y+inner.height)+" L "+inner.x+" "+inner.y+" z");mOuterBorder.setAttribute("d","M "+x+" "+y+" L "+x+" "+(y+sy)+" L "+(x+sx)+" "+(y+sy)+" L "+(x+sx)+" "+y+" L "+x+" "+y+" z");mInnerBorder.setAttribute("d","M "+inner.x+" "+inner.y+" L "+(inner.x+inner.width)+" "+inner.y+" L "+(inner.x+inner.width)+" "+(inner.y+inner.height)+" L "+inner.x+" "+(inner.y+inner.height)+" L "+inner.x+" "+inner.y+" z")}if(guttersStyle.getDrawFill())mShape.setAttribute("fill",guttersStyle.getFillColor());else mShape.setAttribute("fill","none");if(guttersStyle.getDrawLines()){mOuterBorder.setAttribute("stroke",guttersStyle.getLineColor());mOuterBorder.setAttribute("stroke-width",guttersStyle.getLineWidth())}else{mOuterBorder.setAttribute("stroke","none");mOuterBorder.setAttribute("stroke-width",0)}if(panelStyle.getDrawLines()){mInnerBorder.setAttribute("stroke",panelStyle.getLineColor());mInnerBorder.setAttribute("stroke-width",panelStyle.getLineWidth())}else{mInnerBorder.setAttribute("stroke","none");mInnerBorder.setAttribute("stroke-width",0)}mShape.setAttribute("shapeRendering",panelStyle.getShapeRendering());mOuterBorder.setAttribute("shapeRendering",guttersStyle.getShapeRendering());mInnerBorder.setAttribute("shapeRendering",panelStyle.getShapeRendering())}};self.drawPanel=function(panel){var UTILS=EJSS_SVGGRAPHICS.Utils;var mShape=mInterfaceGraphics.getElementById(".myPanel");if(mShape===null){mShape=document.createElementNS("http://www.w3.org/2000/svg","path");mShape.setAttribute("id",".myPanel");mInterfaceGraphics.appendChild(mShape)}var x=.5,y=.5;var box=self.getBox();var sx=box.width,sy=box.height;var style=panel.getStyle();if(style.getShapeRendering()=="crispEdges"){mShape.setAttribute("d","M "+UTILS.crispValue(x)+" "+UTILS.crispValue(y)+" L "+UTILS.crispValue(x)+" "+UTILS.crispValue(y+sy)+" L "+UTILS.crispValue(x+sx)+" "+UTILS.crispValue(y+sy)+" L "+UTILS.crispValue(x+sx)+" "+UTILS.crispValue(y)+" z")}else{mShape.setAttribute("d","M "+x+" "+y+" L "+x+" "+(y+sy)+" L "+(x+sx)+" "+(y+sy)+" L "+(x+sx)+" "+y+" z")}if(style.getDrawFill())mShape.setAttribute("fill",style.getFillColor());else mShape.setAttribute("fill","none");if(style.getDrawLines()){mShape.setAttribute("stroke",style.getLineColor());mShape.setAttribute("stroke-width",style.getLineWidth())}else{mShape.setAttribute("stroke","none");mShape.setAttribute("stroke-width",0)}mShape.setAttribute("shapeRendering",style.getShapeRendering())};self.importSVG=function(callback){var box=self.getBox();var canvas=document.createElement("canvas");canvas.width=box.width+1;canvas.height=box.height+1;var ctx=canvas.getContext("2d");var dom=self.getDOMElement();dom.setAttribute("width",canvas.width);dom.setAttribute("height",canvas.height);var svg_xml=(new XMLSerializer).serializeToString(dom);var img=new Image;img.src="data:image/svg+xml;utf8,"+svg_xml;img.onload=function(){console.log("tam "+canvas.width+" "+canvas.height);ctx.drawImage(img,0,0);if(callback)callback(canvas.toDataURL("image/png"))};return img.src};return self};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.InfoText={registerProperties:function(element,controller){EJSS_DRAWING2D.Text.registerProperties(element,controller);controller.registerProperty("Info",element.setInfo);controller.registerProperty("Format",element.setFormat)}};EJSS_DRAWING2D.infoText=function(name){var self=EJSS_DRAWING2D.text(name);var super_getText=self.getText;var mInfo;var mFormat;self.setInfo=function(info){mInfo=info};self.getText=function(){if(typeof mInfo!="undefined"){if(mInfo.getInfo)return mInfo.getInfo();else if(typeof mInfo=="function")return mInfo()}else{var text=super_getText();return fillString(mFormat,text)}};self.setFormat=function(format){mFormat=format};self.isChanged=function(){return true};self.registerProperties=function(controller){EJSS_DRAWING2D.InfoText.registerProperties(self,controller)};function fillString(format,text){if(!Array.isArray(text)||typeof mFormat=="undefined")return text;var t="";var txt=format;var numbers=format.match(/[0-9]*\.(\^|#)+/g);for(var i=0;i<numbers.length;i++){var precision=numbers[i].split("#").length-1;if(isNaN(text[i]))t=text[i];else t=text[i].toFixed(precision);txt=txt.replace(numbers[i],t)}return txt}return self};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.Knob={};EJSS_DRAWING2D.knob=function(mName){};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.KnobOld={registerProperties:function(element,controller){EJSS_DRAWING2D.Element.registerProperties(element,controller);controller.registerProperty("Value",element.setValue,element.getValue);controller.registerProperty("Minimum",element.setMinimum,element.getMinimum);controller.registerProperty("Maximum",element.setMaximum,element.getMaximum);controller.registerAction("OnPress",element.getValue);controller.registerAction("OnRelease",element.getValue);controller.registerAction("OnChange",element.getValue);controller.registerProperty("Size",element.setSize)}};EJSS_DRAWING2D.knobOld=function(mName){var self=EJSS_DRAWING2D.group(mName);var mValue=0;var mMaximum=1;var mMinimum=-1;var mNumberOfMarks=21;var mBigMark=4;var mMediumMark=2;var mDigits=0;var mMinimumAngle=Math.PI/2+1.5*Math.PI/2;var mMaximumAngle=Math.PI/2-1.5*Math.PI/2;var mMinAngle=-Math.PI*.7;var mMaxAngle=Math.PI*.7;var mThreshold=Math.PI/5;var mKnobExterior,mKnobMiddle,mKnobInterior;var mSegments,mTexts,mBrand,mUnits;var mDummyContainer;var mSVGDefs="<svg xmlns='http://www.w3.org/2000/svg' version='1.1'>"+" <defs>"+" <linearGradient id='KnobExteriorGradient' x1='0%' y1='0%' x2='100%' y2='100%'>"+" <stop offset='0%' stop-color='rgb(250,250,250)' />"+" <stop offset='100%' stop-color='rgb(100,100,100)' />"+" </linearGradient>"+" <linearGradient id='KnobMiddleGradient' x1='0%' y1='0%' x2='100%' y2='100%'>"+" <stop offset='0%' stop-color='rgb(200,200,200)' />"+" <stop offset='100%' stop-color='rgb(150,150,150)' />"+" </linearGradient>"+" <linearGradient id='KnobInteriorGradient' x1='0%' y1='0%' x2='100%' y2='100%'>"+" <stop offset='0%' stop-color='rgb(127,127,127)' />"+" <stop offset='100%' stop-color='rgb(250,250,250)' />"+" </linearGradient>"+" <filter id='KnobFilter' x='0' y='0' width='200%' height='200%'>"+" <feOffset result='offOut' in='SourceGraphic' dx='1' dy='1' />"+" <feGaussianBlur result='blurOut' in='offOut' stdDeviation='2' />"+" <feBlend in='SourceGraphic' in2='blurOut' mode='normal' />"+" </filter>"+" </defs>"+"</svg>";self.setValue=function(value){if(mValue!=value){mValue=value;adjustPosition()}};self.getValue=function(){return mValue};self.setMinimum=function(value){if(mMinimum!=value){mMinimum=value;adjustPosition()}};self.getMinimum=function(){return mMinimum};self.setMaximum=function(value){if(mMaximum!=value){mMaximum=value;adjustPosition()}};self.getMaximum=function(){return mMaximum};self.setSize=function(value){self.setSizeX(value);self.setSizeY(value)};self.registerProperties=function(controller){createKnob();EJSS_DRAWING2D.Knob.registerProperties(self,controller)};self.superSetParent=self.setParent;self.setParent=function(parent,sibling){self.superSetParent(parent,sibling);mKnobExterior.setParent(self);mKnobMiddle.setParent(self);mKnobInterior.setParent(self)};function createKnob(){mDummyContainer=document.createElement("div");document.body.appendChild(mDummyContainer);mDummyContainer.innerHTML=mSVGDefs;mKnobExterior=EJSS_DRAWING2D.shape(mName+".exterior_shape");mKnobExterior.setSize([1,1]);mKnobExterior.getStyle().setDrawLines(false);mKnobExterior.getStyle().setAttributes({fill:"url(#KnobExteriorGradient)",filter:"url(#KnobFilter)"});mKnobMiddle=EJSS_DRAWING2D.shape(mName+".middle_shape");mKnobMiddle.setSize([.9,.9]);mKnobMiddle.getStyle().setDrawLines(false);mKnobMiddle.getStyle().setAttributes({fill:"url(#KnobMiddleGradient)"});mKnobInterior=EJSS_CORE.promoteToControlElement(EJSS_DRAWING2D.shape(mName+".inner_shape"),self.getView(),mName+".inner_shape");mKnobInterior.setY(.3);mKnobInterior.setSize([.2,.2]);mKnobInterior.getStyle().setDrawLines(false);mKnobInterior.getStyle().setAttributes({fill:"url(#KnobInteriorGradient)"});mKnobInterior.setProperty("EnabledPosition","ENABLED_NO_MOVE");mKnobInterior.setProperty("Sensitivity",10);mKnobInterior.setProperty("OnDrag",dragged);mKnobInterior.setProperty("OnPress",pressed);mKnobInterior.setProperty("OnRelease",released)}function adjustPosition(){mValue=Math.max(Math.min(mMaximum,mValue),mMinimum);var angle=mMaxAngle-(mValue-mMinimum)/(mMaximum-mMinimum)*(mMaxAngle-mMinAngle)+Math.PI/2;mKnobInterior.setPosition([.3*Math.cos(angle),.3*Math.sin(angle)])}function pressed(point,info){var controller=self.getController();if(controller)controller.invokeImmediateAction("OnPress")}function released(point,info){var controller=self.getController();if(controller)controller.invokeImmediateAction("OnRelease")}function dragged(point,info){var point=info.point;var element=info.element;var group_pos=self.getAbsolutePosition(true);point[0]-=group_pos[0];point[1]-=group_pos[1];var angle=mMaxAngle-(mValue-mMinimum)/(mMaximum-mMinimum)*(mMaxAngle-mMinAngle);var rotation=Math.atan2(-point[0],point[1]);if(Math.abs(rotation-angle)>mThreshold)return;rotation=Math.min(Math.max(rotation,mMinAngle),mMaxAngle);mValue=mMaximum-(rotation-mMinAngle)/(mMaxAngle-mMinAngle)*(mMaximum-mMinimum);var angle=rotation+Math.PI/2;element.setPosition([.3*Math.cos(angle),.3*Math.sin(angle)]);var controller=self.getController();if(controller){controller.immediatePropertyChanged("Value");controller.invokeImmediateAction("OnChange")}}return self};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.Mesh={};EJSS_DRAWING2D.mesh=function(name){};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.Meter={};EJSS_DRAWING2D.meter=function(mName){}
;var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.Pipe={};EJSS_DRAWING2D.pipe=function(name){};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.PlottingPanel={registerProperties:function(element,controller){EJSS_DRAWING2D.DrawingPanel.registerProperties(element,controller);controller.registerProperty("Title",element.getTitle().setText);controller.registerProperty("TitleFont",element.getTitle().getFont().setFont);controller.registerProperty("TitleColor",element.getTitle().getFont().setFillColor);controller.registerProperty("TitleMargin",element.getTitle().setMarginY);controller.registerProperty("TitleX",element.getTitleX().setText);controller.registerProperty("TitleXFont",element.getTitleX().getFont().setFont);controller.registerProperty("TitleXColor",element.getTitleX().getFont().setFillColor);controller.registerProperty("TitleXMargin",element.getTitleX().setMarginY);controller.registerProperty("TitleY",element.getTitleY().setText);controller.registerProperty("TitleYFont",element.getTitleY().getFont().setFont);controller.registerProperty("TitleYColor",element.getTitleY().getFont().setFillColor);controller.registerProperty("TitleYMargin",element.getTitleY().setMarginX);controller.registerProperty("GridXShow",element.getGrid().setShowX,element.getGrid().getShowX);controller.registerProperty("GridXTicks",element.getGrid().setTicksX,element.getGrid().getTicksX);controller.registerProperty("GridXStep",element.getGrid().setStepX,element.getGrid().getStepX);controller.registerProperty("GridXAutoStepMin",element.getGrid().setAutoStepXMin,element.getGrid().getAutoStepXMin);controller.registerProperty("GridXAutoTicksRange",element.getGrid().setAutoTicksXRange,element.getGrid().getAutoTicksXRange);controller.registerProperty("GridXScale",element.getGrid().setScaleX,element.getGrid().getScaleX);controller.registerProperty("GridXScalePrecision",element.getGrid().setScalePrecisionX,element.getGrid().getScalePrecisionX);controller.registerProperty("GridXFixedTick",element.getGrid().setFixedTickX,element.getGrid().getFixedTickX);controller.registerProperty("GridXAutoTicks",element.getGrid().setAutoTicksX,element.getGrid().getAutoTicksX);controller.registerProperty("GridXLineColor",element.getGrid().setLineColorX);controller.registerProperty("GridXLineWidth",element.getGrid().setLineWidthX);controller.registerProperty("GridXShapeRendering",element.getGrid().setShapeRenderingX);controller.registerProperty("GridYShow",element.getGrid().setShowY,element.getGrid().getShowY);controller.registerProperty("GridYTicks",element.getGrid().setTicksY,element.getGrid().getTicksY);controller.registerProperty("GridYStep",element.getGrid().setStepY,element.getGrid().getStepY);controller.registerProperty("GridYAutoStepMin",element.getGrid().setAutoStepYMin,element.getGrid().getAutoStepYMin);controller.registerProperty("GridYAutoTicksRange",element.getGrid().setAutoTicksYRange,element.getGrid().getAutoTicksYRange);controller.registerProperty("GridYScale",element.getGrid().setScaleY,element.getGrid().getScaleY);controller.registerProperty("GridYScalePrecision",element.getGrid().setScalePrecisionY,element.getGrid().getScalePrecisionY);controller.registerProperty("GridYFixedTick",element.getGrid().setFixedTickY,element.getGrid().getFixedTickY);controller.registerProperty("GridYAutoTicks",element.getGrid().setAutoTicksY,element.getGrid().getAutoTicksY);controller.registerProperty("GridYLineColor",element.getGrid().setLineColorY);controller.registerProperty("GridYLineWidth",element.getGrid().setLineWidthY);controller.registerProperty("GridYShapeRendering",element.getGrid().setShapeRenderingY);controller.registerProperty("AxisXShow",element.getAxisX().setShow);controller.registerProperty("AxisXLineColor",element.getAxisX().getStyle().setLineColor);controller.registerProperty("AxisXLineWidth",element.getAxisX().getStyle().setLineWidth);controller.registerProperty("AxisXShapeRendering",element.getAxisX().getStyle().setShapeRendering);controller.registerProperty("AxisXFixedTick",element.getAxisX().setFixedTick,element.getAxisX().getFixedTick);controller.registerProperty("AxisXAutoTicks",element.getAxisX().setAutoTicks,element.getAxisX().getAutoTicks);controller.registerProperty("AxisXTicks",element.getAxisX().setTicks,element.getAxisX().getTicks);controller.registerProperty("AxisXStep",element.getAxisX().setStep,element.getAxisX().getStep);controller.registerProperty("AxisXTickStep",element.getAxisX().setTickStep,element.getAxisX().getTickStep);controller.registerProperty("AxisXAutoStepMin",element.getAxisX().setAutoStepMin,element.getAxisX().getAutoStepMin);controller.registerProperty("AxisXAutoTicksRange",element.getAxisX().setAutoTicksRange,element.getAxisX().getAutoTicksRange);controller.registerProperty("AxisXScale",element.getAxisX().setScale,element.getAxisX().getScale);controller.registerProperty("AxisXScalePrecision",element.getAxisX().setScalePrecision,element.getAxisX().getScalePrecision);controller.registerProperty("AxisXFont",element.getAxisX().getFont().setFont);controller.registerProperty("AxisXFontColor",element.getAxisX().getFont().setFillColor);controller.registerProperty("AxisYShow",element.getAxisY().setShow);controller.registerProperty("AxisYLineColor",element.getAxisY().getStyle().setLineColor);controller.registerProperty("AxisYLineWidth",element.getAxisY().getStyle().setLineWidth);controller.registerProperty("AxisYShapeRendering",element.getAxisY().getStyle().setShapeRendering);controller.registerProperty("AxisYFixedTick",element.getAxisY().setFixedTick,element.getAxisY().getFixedTick);controller.registerProperty("AxisYAutoTicks",element.getAxisY().setAutoTicks,element.getAxisY().getAutoTicks);controller.registerProperty("AxisYTicks",element.getAxisY().setTicks,element.getAxisY().getTicks);controller.registerProperty("AxisYStep",element.getAxisY().setStep,element.getAxisY().getStep);controller.registerProperty("AxisYTickStep",element.getAxisY().setTickStep,element.getAxisY().getTickStep);controller.registerProperty("AxisYAutoStepMin",element.getAxisY().setAutoStepMin,element.getAxisY().getAutoStepMin);controller.registerProperty("AxisYAutoTicksRange",element.getAxisY().setAutoTicksRange,element.getAxisY().getAutoTicksRange);controller.registerProperty("AxisYScale",element.getAxisY().setScale,element.getAxisY().getScale);controller.registerProperty("AxisYScalePrecision",element.getAxisY().setScalePrecision,element.getAxisY().getScalePrecision);controller.registerProperty("AxisYFont",element.getAxisY().getFont().setFont);controller.registerProperty("AxisYFontColor",element.getAxisY().getFont().setFillColor);controller.registerProperty("XFixedTick",function(v){element.getAxisX().setFixedTick(v);element.getGrid().setFixedTickX(v)});controller.registerProperty("YFixedTick",function(v){element.getAxisY().setFixedTick(v);element.getGrid().setFixedTickY(v)});controller.registerProperty("XTicks",function(v){element.getAxisX().setTicks(v);element.getGrid().setTicksX(v)});controller.registerProperty("YTicks",function(v){element.getAxisY().setTicks(v);element.getGrid().setTicksY(v)});controller.registerProperty("XStep",function(v){element.getAxisX().setStep(v);element.getGrid().setStepX(v)});controller.registerProperty("YStep",function(v){element.getAxisY().setStep(v);element.getGrid().setStepY(v)});controller.registerProperty("XTickStep",function(v){element.getAxisX().setTickStep(v);element.getGrid().setTickStepX(v)});controller.registerProperty("YTickStep",function(v){element.getAxisY().setTickStep(v);element.getGrid().setTickStepY(v)});controller.registerProperty("XAutoStepMin",function(v){element.getAxisX().setAutoStepMin(v);element.getGrid().setAutoStepXMin(v)});controller.registerProperty("YAutoStepMin",function(v){element.getAxisY().setAutoStepMin(v);element.getGrid().setAutoStepYMin(v)});controller.registerProperty("XAutoTicksRange",function(v){element.getAxisX().setAutoTicksRange(v);element.getGrid().setAutoTicksXRange(v)});controller.registerProperty("YAutoTicksRange",function(v){element.getAxisY().setAutoTicksRange(v);element.getGrid().setAutoTicksyRange(v)});controller.registerProperty("XScale",function(v){element.getAxisX().setScale(v);element.getGrid().setScaleX(v)});controller.registerProperty("YScale",function(v){element.getAxisY().setScale(v);element.getGrid().setScaleY(v)});controller.registerProperty("XScalePrecision",function(v){element.getAxisX().setScalePrecision(v);element.getGrid().setScalePrecisionX(v)});controller.registerProperty("YScalePrecision",function(v){element.getAxisY().setScalePrecision(v);element.getGrid().setScalePrecisionY(v)});controller.registerProperty("XAutoTicks",function(v){element.getAxisX().setAutoTicks(v);element.getGrid().setAutoTicksX(v)});controller.registerProperty("YAutoTicks",function(v){element.getAxisY().setAutoTicks(v);element.getGrid().setAutoTicksY(v)})}};EJSS_DRAWING2D.plottingPanel=function(mName,mGraphicsMode){var self=EJSS_DRAWING2D.drawingPanel(mName,mGraphicsMode);self.getGrid=function(){return mGrid};self.getAxisX=function(){return mAxisX};self.getAxisY=function(){return mAxisY};self.getTitleX=function(){return mTitleX};self.getTitleY=function(){return mTitleY};self.getTitle=function(){return mTitle};self.getFixedTickX=function(){return getGrid().getFixedTickX()};self.getFixedTickY=function(){return getGrid().getFixedTickY()};self.registerProperties=function(controller){EJSS_DRAWING2D.PlottingPanel.registerProperties(self,controller)};var mBottomGroup=EJSS_DRAWING2D.group(mName+".bottomgroup");mBottomGroup.setRelativePosition("SOUTH_WEST");mBottomGroup.panelChangeListener=function(event){if(event=="bounds"){var xmin=self.getRealWorldXMin();var xmax=self.getRealWorldXMax();var ymin=self.getRealWorldYMin();var ymax=self.getRealWorldYMax();var sx=Math.abs(xmax-xmin);var sy=Math.abs(ymax-ymin);mBottomGroup.setSize([sx,sy]);mBottomGroup.setPosition([xmin,ymin]);return true}};mBottomGroup.panelChangeListener("bounds");var mGrid=EJSS_DRAWING2D.grid(mName+".grid");mGrid.setGroup(mBottomGroup);mGrid.setRelativePosition("SOUTH_WEST");mGrid.setLineColorX("lightgray");mGrid.setShapeRenderingX("RENDER_CRISPEDGES");mGrid.setLineColorY("lightgray");mGrid.setShapeRenderingY("RENDER_CRISPEDGES");mGrid.setSize([1,1]);mGrid.setPosition([0,0]);mGrid.panelChangeListener=function(event){if(event=="bounds"){var xmin=self.getRealWorldXMin();var xmax=self.getRealWorldXMax();mGrid.setScaleX([xmin,xmax]);mGrid.setTicksXMode(self.getTypeScaleX());var ymin=self.getRealWorldYMin();var ymax=self.getRealWorldYMax();mGrid.setScaleY([ymin,ymax]);mGrid.setTicksYMode(self.getTypeScaleY());return true}};var mTopGroup=EJSS_DRAWING2D.group(mName+".topgroup");mTopGroup.setRelativePosition("SOUTH_WEST");mTopGroup.panelChangeListener=function(event){if(event=="bounds"){var xmin=self.getRealWorldXMin();var xmax=self.getRealWorldXMax();var ymin=self.getRealWorldYMin();var ymax=self.getRealWorldYMax();var sx=Math.abs(xmax-xmin);var sy=Math.abs(ymax-ymin);mTopGroup.setSize([sx,sy]);mTopGroup.setPosition([xmin,ymin]);return true}};mTopGroup.panelChangeListener("bounds");var mAxisX=EJSS_DRAWING2D.axis(mName+".axisX");mAxisX.setGroup(mTopGroup);mAxisX.setRelativePosition("WEST");mAxisX.getStyle().setLineColor("black");mAxisX.getStyle().setShapeRendering("RENDER_CRISPEDGES");mAxisX.getFont().setFontSize(10);mAxisX.setSize([1,1]);mAxisX.setPosition([0,0]);mAxisX.setOrient("AXIS_HORIZONTAL");mAxisX.panelChangeListener=function(event){if(event=="bounds"){var xmin=self.getRealWorldXMin();var xmax=self.getRealWorldXMax();mAxisX.setScale([xmin,xmax]);mAxisX.setTicksMode(self.getTypeScaleX());if(self.getInvertedScaleY()){mAxisX.setTextPosition("TICKS_DOWN");mTitleX.setMarginY(-30);mTitle.setMarginY(20)}else{mAxisX.setTextPosition("TICKS_UP");mTitleX.setMarginY(30);mTitle.setMarginY(-20)}return true}};mAxisX.setTicksMode(self.getTypeScaleX());var mAxisY=EJSS_DRAWING2D.axis(mName+".axisY");mAxisY.setGroup(mTopGroup);mAxisY.setRelativePosition("SOUTH");mAxisY.getStyle().setLineColor("black");mAxisY.getStyle().setShapeRendering("RENDER_CRISPEDGES");mAxisY.getFont().setFontSize(10);mAxisY.setSize([1,1]);mAxisY.setPosition([0,0]);mAxisY.setOrient("AXIS_VERTICAL");mAxisY.panelChangeListener=function(event){if(event=="bounds"){var ymin=self.getRealWorldYMin();var ymax=self.getRealWorldYMax();mAxisY.setScale([ymin,ymax]);mAxisY.setTicksMode(self.getTypeScaleY());mAxisY.setInvertedScaleY(self.getInvertedScaleY());return true}};mAxisY.setTicksMode(self.getTypeScaleY());var mTitleX=EJSS_DRAWING2D.text(mName+".titleX");mTitleX.setGroup(mTopGroup);mTitleX.setRelativePosition("CENTER");mTitleX.getFont().setFontSize(12);mTitleX.setPosition([.5,0]);mTitleX.setMarginY(30);mTitleX.setText("x");var mTitleY=EJSS_DRAWING2D.text(mName+".titleY");mTitleY.setGroup(mTopGroup);mTitleY.setRelativePosition("CENTER");mTitleY.getFont().setFontSize(12);mTitleY.setWritingMode("MODE_DOWNTOP");mTitleY.setPosition([0,.5]);mTitleY.setMarginX(-40);mTitleY.setText("y");var mTitle=EJSS_DRAWING2D.text(mName+".title");mTitle.setGroup(mTopGroup);mTitle.setRelativePosition("CENTER");mTitle.getFont().setFontSize(12);mTitle.setPosition([.5,1]);mTitle.setMarginY(-20);mTitle.setText("Plot");self.getStyle().setLineColor("black");self.getStyle().setFillColor("white");self.getStyle().setShapeRendering("RENDER_CRISPEDGES");self._25([50,50,50,50]);self.getGuttersStyle().setLineColor("black");self.getGuttersStyle().setFillColor("rgb(211,216,255)");self.getGuttersStyle().setShapeRendering("RENDER_CRISPEDGES");self.addDecoration(mBottomGroup);self.addDecoration(mGrid);self.addDecoration(mTopGroup,-1,true);self.addDecoration(mAxisX,-1,true);self.addDecoration(mAxisY,-1,true);self.addDecoration(mTitleX,-1,true);self.addDecoration(mTitleY,-1,true);self.addDecoration(mTitle,-1,true);return self};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.Polygon={NO_CONNECTION:0,LINE_CONNECTION:1,copyTo:function(source,dest){EJSS_DRAWING2D.Element.copyTo(source,dest);dest.setPoints(source.getPoints())},registerProperties:function(element,controller){EJSS_DRAWING2D.Element.registerProperties(element,controller);controller.registerProperty("Points",element.setPoints,element.getPoints);controller.registerProperty("PointsX",element.setPointsX);controller.registerProperty("PointsY",element.setPointsY);controller.registerProperty("LastPoint",element.addPoint,element.getLastPoint)}};EJSS_DRAWING2D.polygon=function(name){var self=EJSS_DRAWING2D.element(name);var mPointList=[];var mTempX=null;var mTempY=null;self._23=function(){return"ElementPolygon"};self.addPoint=function(x,y,style){if(x instanceof Array)addPoint(x[0],x[1],x[2]);else addPoint(x,y,style);self.setChanged(true)};self.addPoints=function(x,y){if(x==undefined||x==null||x[0]==undefined)return;if(x[0]instanceof Array){for(var i=0,n=x.length;i<n;i++)addPoint(x[i][0],x[i][1],x[i][2])}else{var n=Math.min(x.length,y.length);for(var i=0;i<n;i++)addPoint(x[i],y[i])}self.setChanged(true)};self.setPoints=function(x,y){self.clear();self.addPoints(x,y);self.setChanged(true)};self.setPointsX=function(x){if(mTempY==null)mTempX=x;else{self.setPoints(x,mTempY);mTempY=null}};self.setPointsY=function(y){if(mTempX==null)mTempY=y;else{self.setPoints(mTempX,y);mTempX=null}};self.getPoints=function(){return mPointList};self.getLastPoint=function(){if(mPointList.length>0)return mPointList[mPointList.length-1];else return[]};self.clear=function(){mPointList=[];self.setChanged(true)};self.getBounds=function(element){var xmin,xmax,ymin,ymax;var points=self.getPoints();var len=points.length;if(len==0){xmin=xmax=ymin=ymax=0}else{xmax=xmin=points[0][0];ymax=ymin=points[0][1];for(var j=1;j<len;j++){var x=points[j][0],y=points[j][1];if(x>xmax)xmax=x;if(y>ymax)ymax=y;if(x<xmin)xmin=x;if(y<ymin)ymin=y}}var x=self.getX(),y=self.getY();var sx=self.getSizeX(),sy=self.getSizeY();var mx=sy/2,my=sy/2;var d=self.getRelativePositionOffset(sx,sy);return{left:x+d[0]-mx+xmin*sx,right:x+d[0]-mx+xmax*sx,top:y+d[1]-my+ymax*sy,bottom:y+d[1]-my+ymin*sy}};function addPoint(_x,_y,_style){if(isNaN(_x)||isNaN(_y)){return}mPointList[mPointList.length]=[_x,_y,_style]}self.registerProperties=function(controller){EJSS_DRAWING2D.Polygon.registerProperties(self,controller)};self.copyTo=function(element){EJSS_DRAWING2D.Polygon.copyTo(self,element)};self.setSize([1,1]);self.setRelativePosition("SOUTH_WEST");return self};EJSS_DRAWING2D.PolygonSet={};EJSS_DRAWING2D.polygonSet=function(mName){};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.Ruler={};EJSS_DRAWING2D.ruler=function(mName){};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.ScalarField={registerProperties:function(element,controller){EJSS_DRAWING2D.Element.registerProperties(element,controller);controller.registerProperty("Data",element.setData,element.getData);controller.registerProperty("MinimumX",element.setMinimumX,element.getMinimumX);controller.registerProperty("MaximumX",element.setMaximumX,element.getMaximumX);controller.registerProperty("MinimumY",element.setMinimumY,element.getMinimumY);controller.registerProperty("MaximumY",element.setMaximumY,element.getMaximumY);controller.registerProperty("MinimumZ",element.setMinimumZ,element.getMinimumZ);controller.registerProperty("MaximumZ",element.setMaximumZ,element.getMaximumZ);controller.registerProperty("Radius",element.setRadius,element.getRadius)}};EJSS_DRAWING2D.scalarField=function(name){var self=EJSS_DRAWING2D.element(name);var mData=[];var mxMin=-1;var mxMax=1;var myMin=-1;var myMax=1;var mzMin=-1;var mzMax=1;var mRadius=0;self._23=function(){return"ElementScalarField"};self.getMinimumX=function(){return mxMin};self.setMinimumX=function(min){if(mxMin!=min){mxMin=min;self.setChanged(true)}};self.getMaximumX=function(){return mxMax};self.setMaximumX=function(max){if(mxMax!=max){mxMax=max;self.setChanged(true)}};self.getMinimumY=function(){return myMin};self.setMinimumY=function(min){if(myMin!=min){myMin=min;self.setChanged(true)}};self.getMaximumY=function(){return myMax};self.setMaximumY=function(max){if(myMax!=max){myMax=max;self.setChanged(true)}};self.getMinimumZ=function(){return mzMin};self.setMinimumZ=function(min){if(mzMin!=min){mzMin=min;self.setChanged(true)}};self.getMaximumZ=function(){return mzMax};self.setMaximumZ=function(max){if(mzMax!=max){mzMax=max;self.setChanged(true)}};self.getRadius=function(){return mRadius};self.setRadius=function(radius){if(mRadius!=radius){mRadius=radius;self.setChanged(true)}};self.getData=function(){return mData};self.setData=function(data){mData=data||mData;self.setChanged(true)};self.registerProperties=function(controller){EJSS_DRAWING2D.ScalarField.registerProperties(self,controller)};return self};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.Segment={registerProperties:function(element,controller){EJSS_DRAWING2D.Element.registerProperties(element,controller);controller.registerProperty("Offset",element.setRelativePosition,element.getRelativePosition)}};EJSS_DRAWING2D.segment=function(name){var self=EJSS_DRAWING2D.element(name);self._23=function(){return"ElementSegment"};self.registerProperties=function(controller){EJSS_DRAWING2D.Segment.registerProperties(self,controller)};self.setSize([.1,.1]);self.setRelativePosition("SOUTH_WEST");return self};EJSS_DRAWING2D.SegmentSet={};EJSS_DRAWING2D.segmentSet=function(mName){};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.SetSquare={};EJSS_DRAWING2D.setSquare=function(mName){};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.Shape={NONE:0,ELLIPSE:1,RECTANGLE:2,ROUND_RECTANGLE:3,WHEEL:4,POINT:5,registerProperties:function(element,controller){EJSS_DRAWING2D.Element.registerProperties(element,controller);controller.registerProperty("ShapeType",element.setShapeType);controller.registerProperty("CornerRadius",element.setCornerRadius)},copyTo:function(source,dest){EJSS_DRAWING2D.Element.copyTo(source,dest);dest.setShapeType(source.getShapeType());dest.setCornerRadius(source.getCornerRadius())}};EJSS_DRAWING2D.shape=function(name){var self=EJSS_DRAWING2D.element(name);var mCornerRadius=10;var mShapeType=EJSS_DRAWING2D.Shape.ELLIPSE;self.setShapeType=function(shapeType){if(typeof shapeType==="string")mShapeType=EJSS_DRAWING2D.Shape[shapeType.toUpperCase()];else mShapeType=shapeType};self.getShapeType=function(){return mShapeType};self.setCornerRadius=function(radius){if(mCornerRadius!=radius){mCornerRadius=radius;self.setChanged(true)}};self.getCornerRadius=function(){return mCornerRadius};self._23=function(){return"ElementShape"};self.registerProperties=function(controller){EJSS_DRAWING2D.Shape.registerProperties(self,controller)};self.copyTo=function(element){EJSS_DRAWING2D.Shape.copyTo(self,element)};self.setSize([.1,.1]);self.setRelativePosition("CENTER");self.getStyle().setFillColor("Blue");self.getStyle().setLineColor("Black");return self};EJSS_DRAWING2D.ShapeSet={registerProperties:function(set,controller){var ElementSet=EJSS_DRAWING2D.ElementSet;ElementSet.registerProperties(set,controller);controller.registerProperty("ShapeType",function(v){set.setToEach(function(element,value){element.setShapeType(value)},v)});controller.registerProperty("CornerRadius",function(v){set.setToEach(function(element,value){element.setCornerRadius(value)},v)})}};EJSS_DRAWING2D.shapeSet=function(mName){var self=EJSS_DRAWING2D.elementSet(EJSS_DRAWING2D.shape,mName);var ShapeSet=EJSS_DRAWING2D.ShapeSet;self.registerProperties=function(controller){ShapeSet.registerProperties(self,controller)};return self};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.SimplePanel={GRAPHICS2D_SVG:"SVG",GRAPHICS2D_CANVAS:"Canvas",registerProperties:function(element,controller){controller.registerProperty("MinimumX",element.setWorldXMin,element.getWorldXMin);controller.registerProperty("MaximumX",element.setWorldXMax,element.getWorldXMax);controller.registerProperty("MinimumY",element.setWorldYMin,element.getWorldYMin);controller.registerProperty("MaximumY",element.setWorldYMax,element.getWorldYMax);controller.registerProperty("Bounds",element.setWorldCoordinates,element.getWorldCoordinates);controller.registerProperty("MarginX",element.setMarginX,element.getMarginX);controller.registerProperty("MarginY",element.setMarginY,element.getMarginY);controller.registerProperty("Parent",element.getGraphics().setParent,element.getGraphics().getParent);controller.registerProperty("Width",element.getGraphics().setWidth,element.getGraphics().getWidth);controller.registerProperty("Height",element.getGraphics().setHeight,element.getGraphics().getHeight);controller.registerProperty("Graphics",element.setGraphics);controller.registerProperty("Background",element.getStyle().setFillColor);controller.registerProperty("Foreground",element.getStyle().setLineColor);controller.registerProperty("LineColor",element.getStyle().setLineColor);controller.registerProperty("LineWidth",element.getStyle().setLineWidth);controller.registerProperty("DrawLines",element.getStyle().setDrawLines);controller.registerProperty("FillColor",element.getStyle().setFillColor);controller.registerProperty("DrawFill",element.getStyle().setDrawFill);controller.registerProperty("ShapeRendering",element.getStyle().setShapeRendering);controller.registerProperty("Visibility",element.getGraphics().getStyle().setVisibility);controller.registerProperty("Display",element.getGraphics().getStyle().setDisplay);controller.registerProperty("CSS",element.getGraphics().getStyle().setCSS)}};EJSS_DRAWING2D.simplePanel=function(mName){var self={};var mGraphics=EJSS_GRAPHICS.svgGraphics(mName);var mStyle=EJSS_DRAWING2D.style(mName);var mElements=[];var mElementsChanged=false;var mCollectersList=[];var mWorld={xminPreferred:-1,xmaxPreferred:1,yminPreferred:-1,ymaxPreferred:1,xorigin:0,yorigin:0,xscale:1,yscale:1};var mPanelChanged=true;var mMustScale=true;self.getName=function(){return mName};self.getGraphics=function(){return mGraphics};self.importGraphics=function(callback){return mGraphics.importSVG(callback)};self.getStyle=function(){return mStyle};self.setGraphics=function(type){if(type==EJSS_DRAWING2D.SimplePanel.GRAPHICS2D_SVG){mGraphics=EJSS_GRAPHICS.svgGraphics(mName)}else if(type==EJSS_DRAWING2D.SimplePanel.GRAPHICS2D_CANVAS){console.log("WARNING: setGraphics() - Canvas not supported")}else{console.log("WARNING: setGraphics() - Graphics not supported")}};self.setWorldXMin=function(xmin){if(xmin!==mWorld.xminPreferred){mWorld.xminPreferred=xmin;mMustScale=true}};self.getWorldXMin=function(){return mWorld.xminPreferred};self.setWorldXMax=function(xmax){if(xmax!==mWorld.xmaxPreferred){mWorld.xmaxPreferred=xmax;mMustScale=true}};self.getWorldXMax=function(){return mWorld.xmaxPreferred};self.setWorldYMin=function(ymin){if(ymin!==mWorld.yminPreferred){mWorld.yminPreferred=ymin;mMustScale=true}};self.getWorldYMin=function(){return mWorld.yminPreferred};self.setWorldYMax=function(ymax){if(ymax!==mWorld.ymaxPreferred){mWorld.ymaxPreferred=ymax;mMustScale=true}};self.getWorldYMax=function(){return mWorld.ymaxPreferred};self.setWorldCoordinates=function(bounds){self.setWorldXMin(bounds[0]);self.setWorldXMax(bounds[1]);self.setWorldYMin(bounds[2]);self.setWorldYMax(bounds[3])};self.getWorldCoordinates=function(){return[self.getWorldXMin(),self.getWorldXMax(),self.getWorldYMin(),self.getWorldYMax()]};self.addElement=function(element,position){EJSS_TOOLS.addToArray(mElements,element,position);element.setPanel(self);if(element.dataCollected)mCollectersList.push(element);mElementsChanged=true};self.removeElement=function(element){EJSS_TOOLS.removeFromArray(mElements,element);element.setPanel(null);if(element.dataCollected)EJSS_TOOLS.removeFromArray(mCollectersList,element);mElementsChanged=true};self.getElements=function(){return mElements};self.indexOfElement=function(element){return mElements.indexOf(element)};self.toPixelAxisY=function(y){return mWorld.yorigin-y-mWorld.yscale*mWorld.yminPreferred};self.toPixelAxisX=function(x){return mWorld.xorigin+x-mWorld.xscale*mWorld.xminPreferred};self._26=function(point){var pos=[];pos[0]=mWorld.xorigin+mWorld.xscale*(point[0]-mWorld.xminPreferred);pos[1]=mWorld.yorigin+mWorld.yscale*(point[1]-mWorld.yminPreferred);return pos};self.toPixelMod=function(mod){var pmod=[];pmod[0]=mod[0]*mWorld.xscale;pmod[1]=mod[1]*mWorld.yscale;return pmod};self.toPanelPosition=function(point){var pos=[];pos[0]=mWorld.xminPreferred+(point[0]-mWorld.xorigin)/mWorld.xscale;pos[1]=mWorld.yminPreferred+(point[1]-mWorld.yorigin)/mWorld.yscale;return pos};self.toPanelMod=function(mod){var pmod=[];pmod[0]=mWorld.xscale==0?0:mod[0]/mWorld.xscale;pmod[1]=mWorld.yscale==0?0:mod[1]/mWorld.yscale;return pmod};self.getPixelPositionWorldOrigin=function(){return[mWorld.xorigin,mWorld.yorigin]};self._27=function(){var width=mGraphics.getWidth();var height=mGraphics.getHeight();var xPixPerUnit=width/(mWorld.xmaxPreferred-mWorld.xminPreferred);var yPixPerUnit=height/(mWorld.ymaxPreferred-mWorld.yminPreferred);mWorld.xscale=xPixPerUnit;mWorld.yscale=-yPixPerUnit;mWorld.xorigin=.5;mWorld.yorigin=height+.5;mMustScale=false};self.reset=function(){mGraphics.reset()};self.render=function(){var reseted=false;if(mElementsChanged){mGraphics.reset();reseted=true;mElementsChanged=false}for(var i=0,n=mCollectersList.length;i<n;i++)mCollectersList[i].dataCollected();if(mMustScale)self._27();if(mPanelChanged||reseted){mGraphics.drawPanel(self)}mGraphics.draw(mElements,reseted);mPanelChanged=false;for(var i=0,n=mElements.length;i<n;i++)mElements[i].setChanged(false)};self.registerProperties=function(controller){EJSS_DRAWING2D.SimplePanel.registerProperties(self,controller)};mStyle.setLineColor("black");mStyle.setFillColor("rgb(239,239,255)");mStyle.setChangeListener(function(change){mPanelChanged=true});return self};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.Spring={};EJSS_DRAWING2D.spring=function(name){};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.SpringSet={};EJSS_DRAWING2D.springSet=function(mName){};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.Tank={};EJSS_DRAWING2D.tank=function(name){};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.Text={MODE_TOPDOWN:0,MODE_RIGTHLEFT:1,MODE_DOWNTOP:2,MODE_LEFTRIGHT:3,copyTo:function(source,dest){EJSS_DRAWING2D.Element.copyTo(source,dest);EJSS_DRAWING2D.Font.copyTo(source.getFont(),dest.getFont());dest.setText(source.getText());dest.setWritingMode(source.getWritingMode())},registerProperties:function(element,controller){EJSS_DRAWING2D.Element.registerProperties(element,controller);controller.registerProperty("Text",element.setText);controller.registerProperty("Framed",element.setFramed);controller.registerProperty("WritingMode",element.setWritingMode);controller.registerProperty("Font",element.getFont().setFont);controller.registerProperty("FontFamily",element.getFont().setFontFamily);controller.registerProperty("FontSize",element.getFont().setFontSize);controller.registerProperty("LetterSpacing",element.getFont().setLetterSpacing);controller.registerProperty("OutlineColor",element.getFont().setOutlineColor);controller.registerProperty("FontWeight",element.getFont().setFontWeight);controller.registerProperty("FillColor",element.getFont().setFillColor);controller.registerProperty("FontStyle",element.getFont().setFontStyle);controller.registerProperty("MarginX",element.getMarginX().setMarginX);controller.registerProperty("MarginY",element.getMarginY().setMarginY)}};EJSS_DRAWING2D.text=function(mName){var self=EJSS_DRAWING2D.element(mName);var mText="";var mWritingMode=EJSS_DRAWING2D.Text.MODE_LEFTRIGHT;var mFont=EJSS_DRAWING2D.font(mName);var mFramed=false;var mMarginX=0;var mMarginY=0;var mDrawingSize=[-1,-1];self._23=function(){return"ElementText"};self.setText=function(text){text=text+"";if(mText!=text){mText=text;self.setChanged(true);mDrawingSize=[-1,-1]}};self.getText=function(){return mText};self.setDrawingSize=function(drawingSize){mDrawingSize=drawingSize};self.getDrawingSize=function(){return mDrawingSize};self.getSizeX=function(){return mDrawingSize[0]};self.getSizeY=function(){return mDrawingSize[1]};self.setMarginX=function(margin){if(mMarginX!=margin){mMarginX=margin;self.setChanged(true)}};self.getMarginX=function(){return mMarginX};self.setMarginY=function(margin){if(mMarginY!=margin){mMarginY=margin;self.setChanged(true)}};self.getMarginY=function(){return mMarginY};self.getFont=function(){return mFont};self.setFramed=function(framed){if(mFramed!=framed){mFramed=framed;self.setChanged(true)}};self.getFramed=function(){return mFramed};self.setWritingMode=function(writemode){if(typeof writemode=="string")writemode=EJSS_DRAWING2D.Text[writemode.toUpperCase()];if(mWritingMode!=writemode){mWritingMode=writemode;self.setChanged(true)}};self.getWritingMode=function(){return mWritingMode};self.registerProperties=function(controller){EJSS_DRAWING2D.Text.registerProperties(self,controller)};self.copyTo=function(element){EJSS_DRAWING2D.Text.copyTo(self,element)};mFont.setChangeListener(function(change){self.setChanged(true)});self.setPixelSize(true);return self};EJSS_DRAWING2D.TextSet={};EJSS_DRAWING2D.textSet=function(mName){};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.Trace={};EJSS_DRAWING2D.trace=function(mName){};EJSS_DRAWING2D.TraceSet={};EJSS_DRAWING2D.traceSet=function(mName){};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.Trail={};EJSS_DRAWING2D.trail=function(name){};EJSS_DRAWING2D.TrailSet={};EJSS_DRAWING2D.trailSet=function(mName){};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.colorCoded=function(mNumColors,mPalette){var self=EJSS_DRAWING2D.colorMapper(mNumColors,mPalette);var mSymmetricZ=false;self.setSymmetricZ=function(symmetric){mSymmetricZ=symmetric};self.isSymmetricZ=function(){return mSymmetricZ};self.setAutoscale=function(values){var min=Number.MAX_VALUE;var max=Number.MIN_VALUE;for(var i=0,n=values.length;i<n;i++){var value=values[i];max=Math.max(max,value);min=Math.min(min,value)}var ceil=max;var floor=min;if(mSymmetricZ){ceil=Math.max(Math.abs(min),Math.abs(max));floor=-ceil}self.setScale(floor,ceil)};self.setAutoscaleArray2=function(values){var min=Number.MAX_VALUE;var max=Number.MIN_VALUE;for(var i=0,n=values.length;i<n;i++){for(var j=0,m=values[i].length;j<m;j++){var value=values[i][j];max=Math.max(max,value);min=Math.min(min,value)}}var ceil=max;var floor=min;if(mSymmetricZ){ceil=Math.max(Math.abs(min),Math.abs(max));floor=-ceil}self.setScale(floor,ceil)};self.setAutoscaleArray3=function(values){var min=Number.MAX_VALUE;var max=Number.MIN_VALUE;for(var i=0,n=values.length;i<n;i++){for(var j=0,m=values[i].length;j<m;j++){for(var k=0,p=values[i][j].length;k<p;k++){var value=values[i][j][k];max=Math.max(max,value);min=Math.min(min,value)}}}var ceil=max;var floor=min;if(mSymmetricZ){ceil=Math.max(Math.abs(min),Math.abs(max));floor=-ceil}self.setScale(floor,ceil)};return self};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.ColorMapper={CUSTOM:-1,SPECTRUM:0,GRAYSCALE:1,DUALSHADE:2,RED:3,GREEN:4,BLUE:5,BLACK:6,WIREFRAME:7,NORENDER:8,REDBLUE_SHADE:9,getColorPalette:function(numColors,paletteType){function HSB2RGB(h,s,b){var hsb={h:Math.round(360*h),s:s,b:b};var rgb={r:0,g:0,b:0};if(hsb.s===0){rgb.r=rgb.g=rgb.b=hsb.h;return rgb}else{var Hi=Math.floor(hsb.h/60),f=hsb.h/60-Hi,p=hsb.b*(1-hsb.s),q=hsb.b*(1-f*hsb.s),t=hsb.b*(1-(1-f)*hsb.s);switch(Hi){case 0:rgb.r=hsb.b;rgb.g=t;rgb.b=p;break;case 1:rgb.r=q;rgb.g=hsb.b;rgb.b=p;break;case 2:rgb.r=p;rgb.g=hsb.b;rgb.b=t;break;case 3:rgb.r=p;rgb.g=q;rgb.b=hsb.b;break;case 4:rgb.r=t;rgb.g=p;rgb.b=hsb.b;break;case 5:rgb.r=hsb.b;rgb.g=p;rgb.b=q;break}rgb.r=Math.round(rgb.r*255);rgb.g=Math.round(rgb.g*255);rgb.b=Math.round(rgb.b*255);return rgb}}var ColorMapper=EJSS_DRAWING2D.ColorMapper;var colors=[];if(numColors<2)numColors=2;for(var i=0;i<numColors;i++){var level=i/(numColors-1)*.8;var porc1=1,porc2=1;var r=0,g=0,b=0;switch(paletteType){case ColorMapper.REDBLUE_SHADE:r=Math.floor(Math.max(0,-numColors-1+i*2)*255/(numColors-1));b=Math.floor(Math.max(0,numColors-1-i*2)*255/(numColors-1));colors[i]="rgb("+r+","+g+","+b+")";break;case ColorMapper.SPECTRUM:level=.8-level;var rgb=HSB2RGB(level,porc1,porc2);colors[i]="rgb("+rgb.r+","+rgb.g+","+rgb.b+")";break;case ColorMapper.GRAYSCALE:case ColorMapper.BLACK:r=g=b=Math.floor(i*255/(numColors-1));colors[i]="rgb("+r+","+g+","+b+")";break;case ColorMapper.RED:r=Math.floor(i*255/(numColors-1));colors[i]="rgb("+r+","+g+","+b+")";break;case ColorMapper.GREEN:g=Math.floor(i*255/(numColors-1));colors[i]="rgb("+r+","+g+","+b+")";break;case ColorMapper.BLUE:b=Math.floor(i*255/(numColors-1));colors[i]="rgb("+r+","+g+","+b+")";break;case ColorMapper.DUALSHADE:default:var tmp=i/(numColors-1);level=.8*(1-tmp);porc2=.2+1.6*Math.abs(.5-tmp);var rgb=HSB2RGB(level,porc1,porc2);colors[i]="rgb("+rgb.r+","+rgb.g+","+rgb.b+")";break}}return colors}};EJSS_DRAWING2D.colorMapper=function(mNumColors,mPalette){var ColorMapper=EJSS_DRAWING2D.ColorMapper;var self={};var mColors=[];var mFloorColor="darkgray";var mCeilColor="lightgray";var mFloor=-1;var mCeil=1;var mChangeListener;var mPaletteType;var mThresholds;self.setChangeListener=function(listener){mChangeListener=listener};self.setPaletteType=function(_paletteType){if(typeof _paletteType=="string")_paletteType=EJSS_DRAWING2D.ColorMapper[_paletteType.toUpperCase()];mPaletteType=_paletteType;mFloorColor="darkgray";mCeilColor="lightgray";if(mPaletteType==EJSS_DRAWING2D.ColorMapper.GRAYSCALE||mPaletteType==EJSS_DRAWING2D.ColorMapper.BLACK){mFloorColor="rgb(64,64,128)";mCeilColor="rgb(255,191,191)"}mNumColors=Math.max(2,mNumColors);mColors=ColorMapper.getColorPalette(mNumColors,mPaletteType);if(mChangeListener)mChangeListener("palette")};self.getColors=function(){return mColors};self.getFloorColor=function(){return mFloorColor};self.getCeilColor=function(){return mCeilColor};self.getNumColors=function(){return mNumColors};self.setFloorCeilColor=function(_floorColor,_ceilColor){mFloorColor=_floorColor;mCeilColor=_ceilColor};self.setScale=function(_floor,_ceil){mFloor=_floor;mCeil=_ceil;mThresholds=new Array(mColors.length+1);var delta=(mCeil-mFloor)/mColors.length;for(var i=0,n=mColors.length;i<n;i++)mThresholds[i]=mFloor+i*delta;mThresholds[mColors.length]=mCeil};self.getPaletteType=function(){return mPaletteType};self.setColorPalette=function(_colors){mFloorColor="darkgray";mCeilColor="lightgray";mColors=_colors;mNumColors=_colors.length;mPaletteType=EJSS_DRAWING2D.ColorMapper.CUSTOM;if(mChangeListener)mChangeListener("colors")};self.setNumberOfColors=function(_numColors){if(_numColors==mNumColors){return}mNumColors=_numColors;if(mPaletteType==EJSS_DRAWING2D.ColorMapper.CUSTOM){var newColors=[];for(var i=0,n=Math.min(colors.length,mNumColors);i<n;i++){newColors[i]=colors[i]}for(var i=colors.length;i<numColors;i++){newColors[i]=colors[colors.length-1]}colors=newColors}else{self.setPaletteType(mPaletteType)}if(mChangeListener)mChangeListener("numColors")};self.getNumberOfColors=function(){return mNumColors};self.doubleToIndex=function(value){if(mFloor-value>Number.MIN_VALUE){return-1}else if(value-mCeil>Number.MIN_VALUE){return mColors.length}var index=0;if(mCeil!=mFloor)index=Math.floor(mColors.length*(value-mFloor)/(mCeil-mFloor));index=Math.max(0,index);return Math.min(index,mColors.length-1)};self.indexToColor=function(index){if(index<0)return mFloorColor;if(index>=mColors.length)return mCeilColor;return mColors[index]};self.doubleToColor=function(value){return self.indexToColor(self.doubleToIndex())};self.getColorThresholds=function(){return mThresholds};self.setPaletteType(mPalette);self.setScale(-1,1);return self};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.Font={FONTSTYLES:["normal","italic","oblique","initial"],FONTWEIGHTS:["normal","lighter","bold","bolder","initial","100","200","300","400","500","600","700","800","900"],copyTo:function(source,dest){dest.setFontFamily(source.getFontFamily());dest.setFontSize(source.getFontSizeString());dest.setLetterSpacing(source.getLetterSpacing());dest.setOutlineColor(source.getOutlineColor());dest.setOutlineWidth(source.getOutlineWidth());dest.setFontWeight(source.getFontWeight());dest.setFillColor(source.getFillColor())}};EJSS_DRAWING2D.font=function(mName){var self={};var mFontFamily="Arial";var mFontSize="20";var mLetterSpacing="normal";var mLineColor="none";var mLineWidth="1";var mFontWeight="normal";var mFillColor="black";var mFontStyle="none";var mChangeListener;self.setChangeListener=function(listener){mChangeListener=listener};self.setFontFamily=function(fontFamily){if(mFontFamily!=fontFamily){mFontFamily=fontFamily;if(mChangeListener)mChangeListener("fontFamily")}};self.getFontFamily=function(){return mFontFamily};self.setFontSize=function(fontSize){if(mFontSize!=fontSize){mFontSize=fontSize;if(mChangeListener)mChangeListener("fontSize")}};self.getFontSize=function(){var size;if(!isNaN(mFontSize)){size=+mFontSize}else if(mFontSize.indexOf("em")!=-1){size=+mFontSize.substr(0,mFontSize.indexOf("em"))*10}else if(mFontSize.indexOf("px")!=-1){size=+mFontSize.substr(0,mFontSize.indexOf("px"))}else{size=0}return size};self.getFontSizeString=function(){return mFontSize};self.setLetterSpacing=function(letterSpacing){if(mLetterSpacing!=letterSpacing){mLetterSpacing=letterSpacing;if(mChangeListener)mChangeListener("letterSpacing")}};self.getLetterSpacing=function(){return mLetterSpacing};self.getNumberLetterSpacing=function(){var spacing;if(!isNaN(mLetterSpacing)){spacing=+mLetterSpacing}else if(mLetterSpacing.indexOf("px")!=-1){spacing=+mLetterSpacing.substr(0,mLetterSpacing.indexOf("px"))}else{spacing=1}return spacing};self.setOutlineColor=function(lineColor){if(mLineColor!=lineColor){mLineColor=lineColor;if(mChangeListener)mChangeListener("lineColor")}};self.getOutlineColor=function(){return mLineColor};self.setOutlineWidth=function(lineWidth){if(mLineWidth!=lineWidth){mLineWidth=lineWidth;if(mChangeListener)mChangeListener("lineWidth")}};self.getOutlineWidth=function(){return mLineWidth};self.setFontWeight=function(fontWeight){if(mFontWeight!=fontWeight&&EJSS_DRAWING2D.Font.FONTWEIGHTS.indexOf(fontWeight)>-1){mFontWeight=fontWeight;if(mChangeListener)mChangeListener("fontWeight")}};self.getFontWeight=function(){return mFontWeight};self.setFillColor=function(fillColor){if(mFillColor!=fillColor){mFillColor=fillColor;if(mChangeListener)mChangeListener("fillColor")}};self.getFillColor=function(){return mFillColor};self.setFontStyle=function(fontstyle){if(mFontStyle!=fontstyle&&EJSS_DRAWING2D.Font.FONTSTYLES.indexOf(fontstyle)>-1){mFontStyle=fontstyle;if(mChangeListener)mChangeListener("fontstyle")}};self.getFontStyle=function(){return mFontStyle};self.getFont=function(){return mFontStyle+" "+mLineWidth+" "+mFontSize+" "+mFontFamily};self.setFont=function(recap){if(typeof recap!=="string"||recap.length<=0)return;var params=recap.split(" ");mFontStyle=params[0];mFontWeight=params[1];var sizes=params[2].split("/");mFontSize=sizes[0];if(params[3])mFontFamily=recap.substring(recap.indexOf(params[3]))};return self};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.functionsParser=function(){var self={};function object(o){function F(){}F.prototype=o;return new F}var TNUMBER=0;var TOP1=1;var TOP2=2;var TVAR=3;var TFUNCALL=4;function Token(type_,index_,prio_,number_){this.type_=type_;this.index_=index_||0;this.prio_=prio_||0;this.number_=number_!==undefined&&number_!==null?number_:0;this.toString=function(){switch(this.type_){case TNUMBER:return this.number_;case TOP1:case TOP2:case TVAR:return this.index_;case TFUNCALL:return"CALL";default:return"Invalid Token"}}}function Expression(tokens,ops1,ops2,functions){this.tokens=tokens;this.ops1=ops1;this.ops2=ops2;this.functions=functions}var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\'\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,meta={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r","'":"\\'","\\":"\\\\"};function escapeValue(v){if(typeof v==="string"){escapable.lastIndex=0;return escapable.test(v)?"'"+v.replace(escapable,function(a){var c=meta[a];return typeof c==="string"?c:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+"'":"'"+v+"'"}return v}Expression.prototype={simplify:function(values){values=values||{};var nstack=[];var newexpression=[];var n1;var n2;var f;var L=this.tokens.length;var item;var i=0;for(i=0;i<L;i++){item=this.tokens[i];var type_=item.type_;if(type_===TNUMBER){nstack.push(item)}else if(type_===TVAR&&item.index_ in values){item=new Token(TNUMBER,0,0,values[item.index_]);nstack.push(item)}else if(type_===TOP2&&nstack.length>1){n2=nstack.pop();n1=nstack.pop();f=this.ops2[item.index_];item=new Token(TNUMBER,0,0,f(n1.number_,n2.number_));nstack.push(item)}else if(type_===TOP1&&nstack.length>0){n1=nstack.pop();f=this.ops1[item.index_];item=new Token(TNUMBER,0,0,f(n1.number_));nstack.push(item)}else{while(nstack.length>0){newexpression.push(nstack.shift())}newexpression.push(item)}}while(nstack.length>0){newexpression.push(nstack.shift())}return new Expression(newexpression,object(this.ops1),object(this.ops2),object(this.functions))},substitute:function(variable,expr){if(!(expr instanceof Expression)){expr=(new Parser).parse(String(expr))}var newexpression=[];var L=this.tokens.length;var item;var i=0;for(i=0;i<L;i++){item=this.tokens[i];var type_=item.type_;if(type_===TVAR&&item.index_===variable){for(var j=0;j<expr.tokens.length;j++){var expritem=expr.tokens[j];var replitem=new Token(expritem.type_,expritem.index_,expritem.prio_,expritem.number_);newexpression.push(replitem)}}else{newexpression.push(item)}}var ret=new Expression(newexpression,object(this.ops1),object(this.ops2),object(this.functions));return ret},evaluate:function(values){values=values||{};var nstack=[];var n1;var n2;var f;var L=this.tokens.length;var item;var i=0;for(i=0;i<L;i++){item=this.tokens[i];var type_=item.type_;if(type_===TNUMBER){nstack.push(item.number_)}else if(type_===TOP2){n2=nstack.pop();n1=nstack.pop();f=this.ops2[item.index_];nstack.push(f(n1,n2))}else if(type_===TVAR){if(item.index_ in values){nstack.push(values[item.index_])}else if(item.index_ in this.functions){nstack.push(this.functions[item.index_])}else{throw new Error("undefined variable: "+item.index_)}}else if(type_===TOP1){n1=nstack.pop();f=this.ops1[item.index_];nstack.push(f(n1))}else if(type_===TFUNCALL){n1=nstack.pop();f=nstack.pop();if(f.apply&&f.call){if(Object.prototype.toString.call(n1)=="[object Array]"){nstack.push(f.apply(undefined,n1))}else{nstack.push(f.call(undefined,n1))}}else{throw new Error(f+" is not a function")}}else{throw new Error("invalid Expression")}}if(nstack.length>1){throw new Error("invalid Expression (parity)")}return nstack[0]},toString:function(toJS){var nstack=[];var n1;var n2;var f;var L=this.tokens.length;var item;var i=0;for(i=0;i<L;i++){item=this.tokens[i];var type_=item.type_;if(type_===TNUMBER){nstack.push(escapeValue(item.number_))}else if(type_===TOP2){n2=nstack.pop();n1=nstack.pop();f=item.index_;if(toJS&&f=="^"){nstack.push("Math.pow("+n1+","+n2+")")}else{nstack.push("("+n1+f+n2+")")}}else if(type_===TVAR){nstack.push(item.index_)}else if(type_===TOP1){n1=nstack.pop();f=item.index_;if(f==="-"){nstack.push("("+f+n1+")")}else{nstack.push(f+"("+n1+")")}}else if(type_===TFUNCALL){n1=nstack.pop();f=nstack.pop();nstack.push(f+"("+n1+")")}else{throw new Error("invalid Expression")}}if(nstack.length>1){throw new Error("invalid Expression (parity)")}return nstack[0]},variables:function(){var L=this.tokens.length;var vars=[];for(var i=0;i<L;i++){var item=this.tokens[i];if(item.type_===TVAR&&vars.indexOf(item.index_)==-1){vars.push(item.index_)}}return vars},toJSFunction:function(param,variables){var f=new Function(param,"with(Parser.values) { return "+this.simplify(variables).toString(true)+"; }");return f}};function add(a,b){return Number(a)+Number(b)}function sub(a,b){return a-b}function mul(a,b){return a*b}function div(a,b){return a/b}function mod(a,b){return a%b}function concat(a,b){return""+a+b}function neg(a){return-a}function random(a){return Math.random()*(a||1)}function fac(a){a=Math.floor(a);var b=a;while(a>1){b=b*--a}return b}function pyt(a,b){return Math.sqrt(a*a+b*b)}function ifelse(a,b,c){if(a)return b;else return c}function step(a){if(a<0)return 0;return 1}function append(a,b){if(Object.prototype.toString.call(a)!="[object Array]"){return[a,b]}a=a.slice();a.push(b);return a}function greaterthan(a,b){return a>b?1:0}function lessthan(a,b){return a<b?1:0}function equalto(a,b){return a==b?1:0}function notequalto(a,b){return a!=b?1:0}function Parser(){this.success=false;this.errormsg="";this.expression="";this.pos=0;this.tokennumber=0;this.tokenprio=0;this.tokenindex=0;this.tmpprio=0;this.ops1={sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,sqrt:Math.sqrt,log:Math.log,abs:Math.abs,ceil:Math.ceil,floor:Math.floor,round:Math.round,"-":neg,neg:neg,exp:Math.exp};this.ops2={"+":add,"-":sub,"*":mul,"/":div,"%":mod,"^":Math.pow,",":append,"||":concat,">":greaterthan,"<":lessthan,"==":equalto,"!=":notequalto};this.functions={random:random,fac:fac,min:Math.min,max:Math.max,pyt:pyt,step:step,pow:Math.pow,atan2:Math.atan2,if:ifelse};this.consts={E:Math.E,pi:Math.PI,PI:Math.PI}}self.parse=function(expr){return(new Parser).parse(expr)};self.evaluate=function(expr,variables){return Parser.parse(expr).evaluate(variables)};Parser.Expression=Expression;Parser.values={sign:Math.sign,sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,sqrt:Math.sqrt,log:Math.log,abs:Math.abs,ceil:Math.ceil,floor:Math.floor,round:Math.round,random:random,fac:fac,exp:Math.exp,min:Math.min,max:Math.max,pyt:pyt,ifelse:ifelse,step:step,pow:Math.pow,atan2:Math.atan2,E:Math.E,pi:Math.PI,PI:Math.PI};var PRIMARY=1<<0;var OPERATOR=1<<1;var FUNCTION=1<<2;var LPAREN=1<<3;var RPAREN=1<<4;var COMMA=1<<5
;var SIGN=1<<6;var CALL=1<<7;var NULLARY_CALL=1<<8;Parser.prototype={parse:function(expr){this.errormsg="";this.success=true;var operstack=[];var tokenstack=[];this.tmpprio=0;var expected=PRIMARY|LPAREN|FUNCTION|SIGN;var noperators=0;this.expression=expr;this.pos=0;while(this.pos<this.expression.length){if(this.isOperator()){if(this.isSign()&&expected&SIGN){if(this.isNegativeSign()){this.tokenprio=2;this.tokenindex="-";noperators++;this.addfunc(tokenstack,operstack,TOP1)}expected=PRIMARY|LPAREN|FUNCTION|SIGN}else if(this.isComment()){}else{if((expected&OPERATOR)===0){this.error_parsing(this.pos,"unexpected operator")}noperators+=2;this.addfunc(tokenstack,operstack,TOP2);expected=PRIMARY|LPAREN|FUNCTION|SIGN}}else if(this.isNumber()){if((expected&PRIMARY)===0){this.error_parsing(this.pos,"unexpected number")}var token=new Token(TNUMBER,0,0,this.tokennumber);tokenstack.push(token);expected=OPERATOR|RPAREN|COMMA}else if(this.isString()){if((expected&PRIMARY)===0){this.error_parsing(this.pos,"unexpected string")}var token=new Token(TNUMBER,0,0,this.tokennumber);tokenstack.push(token);expected=OPERATOR|RPAREN|COMMA}else if(this.isLeftParenth()){if((expected&LPAREN)===0){this.error_parsing(this.pos,'unexpected "("')}if(expected&CALL){noperators+=2;this.tokenprio=-2;this.tokenindex=-1;this.addfunc(tokenstack,operstack,TFUNCALL)}expected=PRIMARY|LPAREN|FUNCTION|SIGN|NULLARY_CALL}else if(this.isRightParenth()){if(expected&NULLARY_CALL){var token=new Token(TNUMBER,0,0,[]);tokenstack.push(token)}else if((expected&RPAREN)===0){this.error_parsing(this.pos,'unexpected ")"')}expected=OPERATOR|RPAREN|COMMA|LPAREN|CALL}else if(this.isComma()){if((expected&COMMA)===0){this.error_parsing(this.pos,'unexpected ","')}this.addfunc(tokenstack,operstack,TOP2);noperators+=2;expected=PRIMARY|LPAREN|FUNCTION|SIGN}else if(this.isConst()){if((expected&PRIMARY)===0){this.error_parsing(this.pos,"unexpected constant")}var consttoken=new Token(TNUMBER,0,0,this.tokennumber);tokenstack.push(consttoken);expected=OPERATOR|RPAREN|COMMA}else if(this.isOp2()){if((expected&FUNCTION)===0){this.error_parsing(this.pos,"unexpected function")}this.addfunc(tokenstack,operstack,TOP2);noperators+=2;expected=LPAREN}else if(this.isOp1()){if((expected&FUNCTION)===0){this.error_parsing(this.pos,"unexpected function")}this.addfunc(tokenstack,operstack,TOP1);noperators++;expected=LPAREN}else if(this.isVar()){if((expected&PRIMARY)===0){this.error_parsing(this.pos,"unexpected variable")}var vartoken=new Token(TVAR,this.tokenindex,0,0);tokenstack.push(vartoken);expected=OPERATOR|RPAREN|COMMA|LPAREN|CALL}else if(this.isWhite()){}else{if(this.errormsg===""){this.error_parsing(this.pos,"unknown character")}else{this.error_parsing(this.pos,this.errormsg)}}}if(this.tmpprio<0||this.tmpprio>=10){this.error_parsing(this.pos,'unmatched "()"')}while(operstack.length>0){var tmp=operstack.pop();tokenstack.push(tmp)}if(noperators+1!==tokenstack.length){this.error_parsing(this.pos,"parity")}return new Expression(tokenstack,object(this.ops1),object(this.ops2),object(this.functions))},evaluate:function(expr,variables){return this.parse(expr).evaluate(variables)},error_parsing:function(column,msg){this.success=false;this.errormsg="parse error [column "+column+"]: "+msg;throw new Error(this.errormsg)},addfunc:function(tokenstack,operstack,type_){var operator=new Token(type_,this.tokenindex,this.tokenprio+this.tmpprio,0);while(operstack.length>0){if(operator.prio_<=operstack[operstack.length-1].prio_){tokenstack.push(operstack.pop())}else{break}}operstack.push(operator)},isNumber:function(){var r=false;var str="";while(this.pos<this.expression.length){var code=this.expression.charCodeAt(this.pos);if(code>=48&&code<=57||code===46){str+=this.expression.charAt(this.pos);this.pos++;this.tokennumber=parseFloat(str);r=true}else{break}}return r},unescape:function(v,pos){var buffer=[];var escaping=false;for(var i=0;i<v.length;i++){var c=v.charAt(i);if(escaping){switch(c){case"'":buffer.push("'");break;case"\\":buffer.push("\\");break;case"/":buffer.push("/");break;case"b":buffer.push("\b");break;case"f":buffer.push("\f");break;case"n":buffer.push("\n");break;case"r":buffer.push("\r");break;case"t":buffer.push("\t");break;case"u":var codePoint=parseInt(v.substring(i+1,i+5),16);buffer.push(String.fromCharCode(codePoint));i+=4;break;default:throw this.error_parsing(pos+i,"Illegal escape sequence: '\\"+c+"'")}escaping=false}else{if(c=="\\"){escaping=true}else{buffer.push(c)}}}return buffer.join("")},isString:function(){var r=false;var str="";var startpos=this.pos;if(this.pos<this.expression.length&&this.expression.charAt(this.pos)=="'"){this.pos++;while(this.pos<this.expression.length){var code=this.expression.charAt(this.pos);if(code!="'"||str.slice(-1)=="\\"){str+=this.expression.charAt(this.pos);this.pos++}else{this.pos++;this.tokennumber=this.unescape(str,startpos);r=true;break}}}return r},isConst:function(){var str;for(var i in this.consts){var L=i.length;str=this.expression.substr(this.pos,L);if(i===str){this.tokennumber=this.consts[i];this.pos+=L;return true}}return false},isOperator:function(){var code=this.expression.charCodeAt(this.pos);if(code===43){this.tokenprio=0;this.tokenindex="+"}else if(code===45){this.tokenprio=0;this.tokenindex="-"}else if(code===124){if(this.expression.charCodeAt(this.pos+1)===124){this.pos++;this.tokenprio=0;this.tokenindex="||"}else{return false}}else if(code===61){if(this.expression.charCodeAt(this.pos+1)===61){this.pos++;this.tokenprio=0;this.tokenindex="=="}else{return false}}else if(code===33){if(this.expression.charCodeAt(this.pos+1)===61){this.pos++;this.tokenprio=0;this.tokenindex="!="}else{return false}}else if(code===42){this.tokenprio=1;this.tokenindex="*"}else if(code===47){this.tokenprio=2;this.tokenindex="/"}else if(code===37){this.tokenprio=2;this.tokenindex="%"}else if(code===94){this.tokenprio=3;this.tokenindex="^"}else if(code===60){this.tokenprio=2;this.tokenindex="<"}else if(code===62){this.tokenprio=2;this.tokenindex=">"}else{return false}this.pos++;return true},isSign:function(){var code=this.expression.charCodeAt(this.pos-1);if(code===45||code===43){return true}return false},isPositiveSign:function(){var code=this.expression.charCodeAt(this.pos-1);if(code===43){return true}return false},isNegativeSign:function(){var code=this.expression.charCodeAt(this.pos-1);if(code===45){return true}return false},isLeftParenth:function(){var code=this.expression.charCodeAt(this.pos);if(code===40){this.pos++;this.tmpprio+=10;return true}return false},isRightParenth:function(){var code=this.expression.charCodeAt(this.pos);if(code===41){this.pos++;this.tmpprio-=10;return true}return false},isComma:function(){var code=this.expression.charCodeAt(this.pos);if(code===44){this.pos++;this.tokenprio=-1;this.tokenindex=",";return true}return false},isWhite:function(){var code=this.expression.charCodeAt(this.pos);if(code===32||code===9||code===10||code===13){this.pos++;return true}return false},isOp1:function(){var str="";for(var i=this.pos;i<this.expression.length;i++){var c=this.expression.charAt(i);if(c.toUpperCase()===c.toLowerCase()){if(i===this.pos||c!="_"&&(c<"0"||c>"9")){break}}str+=c}if(str.length>0&&str in this.ops1){this.tokenindex=str;this.tokenprio=5;this.pos+=str.length;return true}return false},isOp2:function(){var str="";for(var i=this.pos;i<this.expression.length;i++){var c=this.expression.charAt(i);if(c.toUpperCase()===c.toLowerCase()){if(i===this.pos||c!="_"&&(c<"0"||c>"9")){break}}str+=c}if(str.length>0&&str in this.ops2){this.tokenindex=str;this.tokenprio=5;this.pos+=str.length;return true}return false},isVar:function(){var str="";for(var i=this.pos;i<this.expression.length;i++){var c=this.expression.charAt(i);if(c.toUpperCase()===c.toLowerCase()){if(i===this.pos||c!="_"&&(c<"0"||c>"9")){break}}str+=c}if(str.length>0){this.tokenindex=str;this.tokenprio=4;this.pos+=str.length;return true}return false},isComment:function(){var code=this.expression.charCodeAt(this.pos-1);if(code===47&&this.expression.charCodeAt(this.pos)===42){this.pos=this.expression.indexOf("*/",this.pos)+2;if(this.pos===1){this.pos=this.expression.length}return true}return false}};return self};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.InteractionTarget={ENABLED_FIXED:0,ENABLED_NONE:0,ENABLED_ANY:1,ENABLED_X:2,ENABLED_Y:3,ENABLED_NO_MOVE:4,SENSITIVITY_BOTH:0,SENSITIVITY_HORIZONTAL:1,SENSITIVITY_VERTICAL:2,SENSITIVITY_ANY:3,copyTo:function(source,dest){dest.setMotionEnabled(source.getMotionEnabled());dest.setAffectsGroup(source.getAffectsGroup());dest.setActionCommand(source.getActionCommand());dest.setDataObject(source.getDataObject());dest.setSensitivity(source.getSensitivity())}};EJSS_DRAWING2D.interactionTarget=function(mElement,mType,mPosition){var InteractionTarget=EJSS_DRAWING2D.InteractionTarget;var self={};var Element=EJSS_DRAWING2D.Element;var mMotionEnabled=InteractionTarget.ENABLED_NONE;var mAffectsGroup=false;var mCommand=null;var mDataObject=null;var mSensitivity=20;var mSensitivityType=InteractionTarget.SENSITIVITY_BOTH;self.getElement=function(){return mElement};self.getType=function(){return mType};self.setMotionEnabled=function(motion){if(typeof motion=="string"){value=InteractionTarget[motion.toUpperCase()];mMotionEnabled=typeof value==="undefined"?InteractionTarget.ENABLED_NONE:value}else mMotionEnabled=motion};self.getMotionEnabled=function(){return mMotionEnabled};self.setSensitivityType=function(sensitivityType){if(typeof sensitivityType=="string")mSensitivityType=InteractionTarget[sensitivityType.toUpperCase()];else mSensitivityType=sensitivityType};self.getSensitivityType=function(){return mSensitivityType};self.isEnabled=function(){return mMotionEnabled!=InteractionTarget.ENABLED_NONE};self.setPositionOffset=function(position){mPosition=position};self.getPositionOffset=function(){return mPosition};self.getPixelPosition=function(){var pos=mElement.getPixelPosition(true);var size=mElement.getPixelSizes(true);var offset=mElement.getRelativePositionOffset(size);var x=pos[0]+offset[0];var y=pos[1]+offset[1];var inverted=mElement.getPanel().getInvertedScaleY();var d=Element.getRelativePositionOffset(mPosition,size[0],size[1],inverted);return[x-d[0],y-d[1]]};self.getPosition=function(){var pos=mElement.getAbsolutePosition(true);var size=mElement.getAbsoluteSize();var inverted=mElement.getPanel().getInvertedScaleY();var d=Element.getRelativePositionOffset(mPosition,size[0],size[1],inverted);var offset=mElement.getRelativePositionOffset(size);var x=pos[0]+offset[0]-d[0];var y=pos[1]+offset[1]-d[1];return[x,y]};self.setAffectsGroup=function(value){mAffectsGroup=value};self.getAffectsGroup=function(){return mAffectsGroup};self.setSensitivity=function(sense){mSensitivity=sense};self.getSensitivity=function(){return mSensitivity};self.setActionCommand=function(command){mCommand=command};self.getActionCommand=function(){return mCommand};self.setDataObject=function(object){mDataObject=object};self.getDataObject=function(){return mDataObject};return self};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.PanelInteraction={TARGET_POSITION:0,TARGET_SIZE:1};EJSS_DRAWING2D.panelInteraction=function(mPanel){var self={};var PanelInteraction=EJSS_DRAWING2D.PanelInteraction;var mEnabled=false;var mStopGestures=false;var mStopMoveEvents=false;var mLastPoint=[];var mFirstPoint=[];var mPreviousPoint=[];var mOnlyTarget=null;var mIsPanelOnlyTarget=false;var mMouseIsDown=false;var mLastTime=0;var mPinching=0;var mPinchInitDistance=[0,0];var mPinchRelDistance=[0,0];var mZoomDelta=0;var mCursorTypeForMove="move";var mElementInteracted=0;self.reload=function(){mLastPoint=[];mFirstPoint=[];mPreviousPoint=[];mOnlyTarget=null;mMouseIsDown=false;mLastTime=0;mPinching=0;mPinchInitDistance=[0,0];mPinchRelDistance=[0,0];mZoomDelta=0;mElementInteracted=0;mEnabled=!mEnabled;self.setEnabled(!mEnabled);mStopGestures=!mStopGestures;self.setStopGestures(!mStopGestures)};self.getPanel=function(){return mPanel};self.getEnabled=function(){return mEnabled};self.setStopMoveEvents=function(stop){if(mStopMoveEvents!=stop){mStopMoveEvents=stop;if(mStopMoveEvents){self.setHandler("move",function(){return true})}else{self.setHandler("move",self.handleMouseMoveEvent)}}};self.setStopGestures=function(stop){if(mStopGestures!=stop){mStopGestures=stop;if(mStopGestures){self.setHandler("gesturestart",function(e){e.preventDefault();e.stopPropagation();return false});self.setHandler("gesturechange",function(e){e.preventDefault();e.stopPropagation();return false});self.setHandler("gestureend",function(e){e.preventDefault();e.stopPropagation();return false})}else{self.setHandler("gesturestart",function(){return true});self.setHandler("gesturechange",function(){return true});self.setHandler("gestureend",function(){return true})}}};self.setEnabled=function(enabled){if(mEnabled!=enabled){mEnabled=enabled;if(mEnabled){if(!mStopMoveEvents){self.setHandler("move",self.handleMouseMoveEvent)}self.setHandler("down",self.handleMouseDownEvent);self.setHandler("up",self.handleMouseUpEvent);self.setHandler("mousewheel",self.handleMouseWheelEvent)}else{self.setHandler("move",function(){return true});self.setHandler("down",function(){return true});self.setHandler("up",function(){return true});self.setHandler("mousewheel",function(){return true})}}};self.setCursorTypeForMove=function(type){mCursorTypeForMove=type};self.getInteractionPoint=function(){return mPanel.toPanelPosition(mLastPoint)};self.getInteractionDistance=function(){if(mPreviousPoint.length==0||mLastPoint.length==0)return[];var p=mPanel.toPanelPosition(mPreviousPoint);var l=mPanel.toPanelPosition(mLastPoint);return[p[0]-l[0],p[1]-l[1]]};self.getInteractionBounds=function(){if(mFirstPoint.length==0||mLastPoint.length==0)return[];var f=mPanel.toPanelPosition(mFirstPoint);var l=mPanel.toPanelPosition(mLastPoint);return[f[0],l[0],f[1],l[1]]};self.getInteractionZoomDelta=function(){if(mZoomDelta==0&&mPinchRelDistance[0]==0)return 0;if(mZoomDelta>0||mPinchRelDistance[0]>0)return 1;return-1};self.getInteractionElement=function(){return mOnlyTarget};self.clearInteractionElement=function(element){if(mOnlyTarget&&element===mOnlyTarget.getElement())mOnlyTarget=null};self.getOrientation=function(){return window.orientation};self.handleMouseMoveEvent=function(event){if(mStopGestures){event.preventDefault();event.stopPropagation()}var nFingers=typeof event.touches!="undefined"?event.touches.length:1;if(nFingers==2){var e0=event.touches[0];var e1=event.touches[1];var e0x=e0.clientX||e0.x;var e0y=e0.clientY||e0.y;var e1x=e1.clientX||e1.x;var e1y=e1.clientY||e1.y;if(mPinching!=0){var newDistance=[Math.abs(e0x-e1x),Math.abs(e0y-e1y)];var delta=[newDistance[0]-mPinchInitDistance[0],newDistance[1]-mPinchInitDistance[1]];if(delta[0]<8&&delta[0]>-8&&delta[1]<8&&delta[1]>-8){mPinchRelDistance=[0,0]}else{mPinchRelDistance=delta;mPinchInitDistance=newDistance}}else{mPinching=1;mPinchInitDistance=[Math.abs(e0x-e1x),Math.abs(e0y-e1y)];mPinchRelDistance=[0,0]}}else{mPinching=0;mPinchInitDistance=[0,0]}var locations=getEventLocations(event);mPreviousPoint=mLastPoint;mLastPoint=locations[locations.length-1];if(mMouseIsDown){if(mOnlyTarget!=null){var element=mOnlyTarget.getAffectsGroup()?mOnlyTarget.getElement().getGroup():mOnlyTarget.getElement();var point=mPanel.toPanelPosition(mLastPoint);var refpoint=mPanel.toPanelPosition(mPreviousPoint);propertiesChanged(element,mOnlyTarget,point,refpoint);element.getController().invokeAction("OnDrag");if(mEnabled)mPanel.getController().invokeAction("OnMove")}else if(mIsPanelOnlyTarget){if(mEnabled){mPanel.getController().invokeAction("OnDrag")}}else{var targetHitList=[];for(var i=0;i<locations.length;i++){var targetHit=self.findInteractionTarget(mPanel.getElements(),locations[i]);if(targetHit!=null){targetHitList.push(targetHit);var element=targetHit.getAffectsGroup()?targetHit.getElement().getGroup():targetHit.getElement();var point=mPanel.toPanelPosition(locations[i]);propertiesChanged(element,targetHit,point,targetHit.getPosition());element.getController().invokeAction("OnDrag");if(mEnabled)mPanel.getController().invokeAction("OnMove")}}if(mEnabled){if(mPinching==0)mPanel.getController().invokeAction("OnDrag");else if(mPinching==1&&targetHitList.length==0)mPanel.getController().invokeAction("OnZoom")}}}else{var targetHit=self.findInteractionTarget(mPanel.getElements(),locations[0]);if(targetHit===null){if(mOnlyTarget!=null)mOnlyTarget.getElement().getController().invokeAction("OnExit");if(mEnabled)mPanel.getController().invokeAction("OnMove");event.target.style.cursor="default"}else{if(mOnlyTarget!=targetHit){if(mOnlyTarget!=null)mOnlyTarget.getElement().getController().invokeAction("OnExit");targetHit.getElement().getController().invokeAction("OnEnter")}if(targetHit.isEnabled())event.target.style.cursor=mCursorTypeForMove;else event.target.style.cursor="default"}mOnlyTarget=targetHit}mPanel.getController().reportInteractions();return false};self.handleMouseDownEvent=function(event){mMouseIsDown=true;if(mStopMoveEvents){self.setHandler("move",self.handleMouseMoveEvent)}if(mStopGestures){event.preventDefault();event.stopPropagation()}var nFingers=typeof event.touches!="undefined"?event.touches.length:1;if(nFingers!=2){mPinching=0}var locations=getEventLocations(event);mFirstPoint=locations[0];mPreviousPoint=mFirstPoint;mLastPoint=locations[locations.length-1];var isPanelHit=false;var targetHit=null;for(var i=0;i<locations.length;i++){targetHit=self.findInteractionTarget(mPanel.getElements(),locations[i]);if(targetHit!==null){targetHit.getElement().getController().invokeAction("OnPress");event.target.style.cursor=mCursorTypeForMove}else if(mEnabled){mPanel.getController().invokeAction("OnPress");isPanelHit=true}}if(locations.length==1&&nFingers==1){mOnlyTarget=targetHit;mIsPanelOnlyTarget=isPanelHit}else{mOnlyTarget=null;mIsPanelOnlyTarget=false}mPanel.getController().reportInteractions();return false};self.handleMouseUpEvent=function(event){mMouseIsDown=false;if(mStopMoveEvents){self.setHandler("move",function(){return true})}if(mStopGestures){event.preventDefault();event.stopPropagation()}if(mPinching!=0){mPinching=0;mPinchRelDistance=[0,0];mPinchInitDistance=[0,0]}var locations=getEventLocations(event);mPreviousPoint=mLastPoint;mLastPoint=locations[locations.length-1];var dblclick=event.timeStamp-mLastTime<500;if(mOnlyTarget!=null){mOnlyTarget.getElement().getController().invokeAction("OnRelease");if(dblclick)mOnlyTarget.getElement().getController().invokeAction("OnDoubleClick")}else{for(var i=0;i<locations.length;i++){var targetHit=self.findInteractionTarget(mPanel.getElements(),locations[i]);if(targetHit!==null){targetHit.getElement().getController().invokeAction("OnRelease");if(dblclick)targetHit.getElement().getController().invokeAction("OnDoubleClick")}else if(mEnabled){mPanel.getController().invokeAction("OnRelease");if(dblclick)mPanel.getController().invokeAction("OnDoubleClick")}}}mLastTime=event.timeStamp;event.target.style.cursor="default";mPanel.getController().reportInteractions();return false};self.handleMouseWheelEvent=function(event){var nFingers=typeof event.touches!="undefined"?event.touches.length:0;if(nFingers==0){if(mStopGestures){event.preventDefault();event.stopPropagation()}mZoomDelta=Math.max(-1,Math.min(1,event.wheelDelta||-event.detail));mPanel.getController().invokeAction("OnZoom");mPanel.getController().reportInteractions()}};self.findInteractionTarget=function(elements,location){var InteractionTarget=EJSS_DRAWING2D.InteractionTarget;var target=null;for(var i=elements.length-1;i>=0;i--){var element=elements[i];if(element.isGroupVisible()){if(element.getElements){target=self.findInteractionTarget(element.getElements(),location);if(target!==null)return target}else{var targets=element.getInteractionTargets();for(var j=0;j<targets.length;j++){if(targets[j].isEnabled()){var sensitivity=targets[j].getSensitivity();if(sensitivity>0){var projectedPosition=targets[j].getPixelPosition();var selected=false;switch(targets[j].getSensitivityType()){case InteractionTarget.SENSITIVITY_HORIZONTAL:selected=Math.abs(projectedPosition[1]-location[1])<sensitivity;break;case InteractionTarget.SENSITIVITY_VERTICAL:selected=Math.abs(projectedPosition[0]-location[0])<sensitivity;break;case InteractionTarget.SENSITIVITY_ANY:selected=Math.abs(projectedPosition[0]-location[0])<sensitivity||Math.abs(projectedPosition[1]-location[1])<sensitivity;break;default:selected=Math.abs(projectedPosition[0]-location[0])<sensitivity&&Math.abs(projectedPosition[1]-location[1])<sensitivity;break}if(selected){mElementInteracted=i;return targets[j]}}}}if(mPinching!=0){target=element.getInteractionTarget(PanelInteraction.TARGET_SIZE);if(target.isEnabled()&&!target.getSensitivity()){var rect=element.getAbsoluteBounds();var pos=mPanel.toPanelPosition(location);if(rect.left<pos[0]&&rect.right>pos[0]&&rect.bottom<pos[1]&&rect.top>pos[1]){mElementInteracted=i;mPinching=2;return target}}}target=element.getInteractionTarget(PanelInteraction.TARGET_POSITION);if(target.isEnabled()&&!target.getSensitivity()){var rect=element.getAbsoluteBounds();var pos=mPanel.toPanelPosition(location);if(rect.left<pos[0]&&rect.right>pos[0]&&rect.bottom<pos[1]&&rect.top>pos[1]){mElementInteracted=i;return target}}}}}return null};self.getIndexElement=function(){return mElementInteracted};function propertiesChanged(element,target,point,targetPosition){var InteractionTarget=EJSS_DRAWING2D.InteractionTarget;var PanelInteraction=EJSS_DRAWING2D.PanelInteraction;if(target.getType()===PanelInteraction.TARGET_POSITION){var dx=point[0]-targetPosition[0];var dy=point[1]-targetPosition[1];switch(target.getMotionEnabled()){case InteractionTarget.ENABLED_ANY:element.setX(element.getX()+dx);element.setY(element.getY()+dy);element.getController().propertiesChanged("Position","X","Y");target.getElement().setChanged(true);element.setChanged(true);break;case InteractionTarget.ENABLED_X:element.setX(element.getX()+dx);element.getController().propertiesChanged("Position","X");target.getElement().setChanged(true);element.setChanged(true);break;case InteractionTarget.ENABLED_Y:element.setY(element.getY()+dy);element.getController().propertiesChanged("Position","Y");target.getElement().setChanged(true);element.setChanged(true);break}}else if(target.getType()===PanelInteraction.TARGET_SIZE){if(mPinching==2){var diff=mPanel.toPanelMod(mPinchRelDistance);var dx=diff[0];var dy=-diff[1]}else{var dx=point[0]-targetPosition[0];var dy=point[1]-targetPosition[1]}var targetElement=target.getElement();var absSize=targetElement.getAbsoluteSize();if(absSize[0]===0)absSize[0]=1e-5;if(absSize[1]===0)absSize[1]=1e-5;var rsizes=[dx/absSize[0],dy/absSize[1]];var size=element.getSize();if(size[0]===0&&rsizes[0]!==0)size[0]=1e-5;if(size[1]===0&&rsizes[0]!==0)size[1]=1e-5;switch(target.getMotionEnabled()){case InteractionTarget.ENABLED_ANY:element.setSizeX(size[0]+size[0]*rsizes[0]);element.setSizeY(size[1]+size[1]*rsizes[1]);element.getController().propertiesChanged("Size","SizeX","SizeY");target.getElement().setChanged(true);element.setChanged(true);break;case InteractionTarget.ENABLED_X:element.setSizeX(size[0]+size[0]*rsizes[0]);element.getController().propertiesChanged("Size","SizeX");target.getElement().setChanged(true);element.setChanged(true);break;case InteractionTarget.ENABLED_Y:element.setSizeY(size[1]+size[1]*rsizes[1]);element.getController().propertiesChanged("Size","SizeY");target.getElement().setChanged(true);element.setChanged(true);break}}}function getEventLocations(e){var box=mPanel.getGraphics().getBox();var oleft=box.left;var otop=box.top;var locations=[];if(typeof e.changedTouches!="undefined"){for(var i=0;i<e.changedTouches.length;i++){locations[i]=[];locations[i][0]=e.changedTouches[i].pageX-oleft;locations[i][1]=e.changedTouches[i].pageY-otop}}else{locations[0]=[];locations[0][0]=(e.clientX||e.x)-oleft;locations[0][1]=(e.clientY||e.y)-otop}return locations}self.setHandler=function(type,handler){var graphics=mPanel.getGraphics();var context=graphics.getEventContext();switch(type){case"move":context.addEventListener("mousemove",handler,false);context.addEventListener("touchmove",handler,false);break;case"down":context.addEventListener("mousedown",handler,false);context.addEventListener("touchstart",handler,false);break;case"up":context.addEventListener("mouseup",handler,false);context.addEventListener("touchend",handler,false);break;case"mousewheel":context.addEventListener("mousewheel",handler,false);break;case"gesturestart":context.addEventListener("gesturestart",handler,false);break;case"gesturechange":context.addEventListener("gesturechange",handler,false);break;case"gestureend":context.addEventListener("gestureend",handler,false);break;default:}return false};var _super_onorientationchange=window.onorientationchange;window.onorientationchange=function(){if(_super_onorientationchange)_super_onorientationchange();mPanel.getController().invokeAction("OnOrientationChange");mPanel.getController().reportInteractions()};var _super_onresize=window.onresize;window.onresize=function(){if(_super_onresize)_super_onresize();mPanel.getController().invokeAction("OnResize");mPanel.getController().reportInteractions()};self.setStopGestures(true);return self};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.Style={RENDER_AUTO:"auto",RENDER_OPTSPEED:"optimizeSpeed",RENDER_CRISPEDGES:"crispEdges",RENDER_GEOPRECISION:"geometricPrecision",copyTo:function(source,dest){dest.setDrawLines(source.getDrawLines());dest.setLineColor(source.getLineColor());dest.setLineWidth(source.getLineWidth());dest.setDrawFill(source.getDrawFill());dest.setFillColor(source.getFillColor());dest.setAttributes(source.getAttributes());dest.setShapeRendering(source.getShapeRendering())}};EJSS_DRAWING2D.style=function(mName){var Style=EJSS_DRAWING2D.Style;var self={};var mDrawLines=true;var mLineColor="black";var mLineWidth=.5;var mDrawFill=true;var mFillColor="none";var mShapeRendering=Style.RENDER_AUTO;var mChangeListener;var mAttributes={};self.setChangeListener=function(listener){mChangeListener=listener};self.setDrawLines=function(draw){if(draw!=mDrawLines){mDrawLines=draw;if(mChangeListener)mChangeListener("drawlines")}};self.getDrawLines=function(){return mDrawLines};self.setLineColor=function(color){if(typeof color!=="string")color=EJSS_TOOLS.DisplayColors.getLineColor(color);if(color!=mLineColor){mLineColor=color;if(mChangeListener)mChangeListener("linecolor")}return self};self.getLineColor=function(){return mLineColor};self.setLineWidth=function(width){if(width!=mLineWidth){mLineWidth=width;if(mChangeListener)mChangeListener("linewidth")}};self.getLineWidth=function(){return mLineWidth};self.setDrawFill=function(draw){if(draw!=mDrawFill){mDrawFill=draw;if(mChangeListener)mChangeListener("drawfill")}};self.getDrawFill=function(){return mDrawFill};self.setFillColor=function(color){if(typeof color!=="string")color=EJSS_TOOLS.DisplayColors.getLineColor(color);if(color!=mFillColor){mFillColor=color;if(mChangeListener)mChangeListener("fillcolor")}};self.getFillColor=function(){return mFillColor};self.setShapeRendering=function(rendering){if(rendering.substring(0,6)=="RENDER")rendering=Style[rendering.toUpperCase()];if(mShapeRendering!=rendering){mShapeRendering=rendering;if(mChangeListener)mChangeListener("shaperendering")}};self.getShapeRendering=function(){return mShapeRendering};self.setAttributes=function(attr){if(attr!=mAttributes){mAttributes=attr;if(mChangeListener)mChangeListener("attributes")}};self.getAttributes=function(){return mAttributes};self.serialize=function(){return{mDrawLines:mDrawLines,mLineColor:mLineColor,mLineWidth:mLineWidth,mDrawFill:mDrawFill,mFillColor:mFillColor,mShapeRendering:mShapeRendering,mAttributes:mAttributes}};self.unserialize=function(json){mDrawLines=json.mDrawLines,mLineColor=json.mLineColor,mLineWidth=json.mLineWidth,mDrawFill=json.mDrawFill,mFillColor=json.mFillColor,mShapeRendering=json.mShapeRendering,mAttributes=json.mAttributes};return self};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.Transformation={compare:function(mtr1,mtr2){return mtr1.radians==mtr2.radians&&mtr1.a==mtr2.a&&mtr1.b==mtr2.b&&mtr1.c==mtr2.c&&mtr1.d==mtr2.d&&mtr1.e==mtr2.e&&mtr1.f==mtr2.f}};EJSS_DRAWING2D.transformation=function(transform){transform=transform||{a:1,b:0,c:0,d:1,e:0,f:0};var self={a:transform.a,c:transform.c,e:transform.e,b:transform.b,d:transform.d,f:transform.f,radians:0};self.toString=function(){return"a="+self.a+", c="+self.c+", e="+self.e+"\n"+"b="+self.b+", d="+self.d+", f="+self.f};self.setToIdentity=function(){self.a=1;self.c=0;self.e=0;self.b=0;self.d=1;self.f=0;radians=0};self.setTransform=function(tr){if(Array.isArray(tr)&&tr.length>5){self.a=tr[0];self.c=tr[2];self.e=tr[4];self.b=tr[1];self.d=tr[3];self.f=tr[5]}else{self.a=tr.a;self.c=tr.c;self.e=tr.e;self.b=tr.b;self.d=tr.d;self.f=tr.f;self.radians=tr.radians}};self.setToTranslation=function(x,y){self.a=1;self.c=0;self.e=x;self.b=0;self.d=1;self.f=y};self.setToRotation=function(radians){var cos=Math.cos(radians),sin=Math.sin(radians);self.a=cos;self.c=-sin;self.e=0;self.b=sin;self.d=cos;self.f=0;self.radians=radians};self.getRotation=function(){return self.radians};self.translate=function(dx,dy){self.e+=dx;self.f+=dy};self.scale=function(sx,sy){self.a*=sx;self.b*=sx;self.c*=sy;self.d*=sy};self.concatenate=function(tr){var a=self.a,b=self.b,c=self.c,d=self.d,e=self.e,f=self.f;self.a=a*tr.a+c*tr.b;self.b=b*tr.a+d*tr.b;self.c=a*tr.c+c*tr.d;self.d=b*tr.c+d*tr.d;self.e=a*tr.e+c*tr.f+e,self.f=b*tr.e+d*tr.f+f;self.radians+=tr.radians};self.transform=function(point){var x=point[0],y=point[1];point[0]=self.a*x+self.c*y+self.e;point[1]=self.b*x+self.d*y+self.f;return point};self.transformVector=function(vector){var x=vector[0],y=vector[1];vector[0]=self.a*x+self.c*y;vector[1]=self.b*x+self.d*y;return vector};self.inverseTransform=function(point){var a=self.a,b=self.b,c=self.c,d=self.d,e=self.e,f=self.f;var den=a*d-b*c;if(den===0)return null;var x=point[0],y=point[1];point[0]=(d*x-c*y+(c*f-d*e))/den;point[1]=(-b*x+a*y+(b*e-a*f))/den;return point};return self};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.Video={};EJSS_DRAWING2D.video=function(name){};var EJSS_DRAWING2D=EJSS_DRAWING2D||{};EJSS_DRAWING2D.WebCamImage={};EJSS_DRAWING2D.webCamImage=function(mName){};var EJSS_DRAWING3D=EJSS_DRAWING3D||{};EJSS_DRAWING3D.AnalyticCurve={};EJSS_DRAWING3D.analyticCurve=function(name){};var EJSS_DRAWING3D=EJSS_DRAWING3D||{};EJSS_DRAWING3D.AnalyticSurface={};EJSS_DRAWING3D.analyticSurface=function(name){};var EJSS_DRAWING3D=EJSS_DRAWING3D||{};EJSS_DRAWING3D.Arrow={};EJSS_DRAWING3D.arrow=function(name){};EJSS_DRAWING3D.ArrowSet={};EJSS_DRAWING3D.arrowSet=function(mName){};var EJSS_DRAWING3D=EJSS_DRAWING3D||{};EJSS_DRAWING3D.Basic={};EJSS_DRAWING3D.basic=function(name){};EJSS_DRAWING3D.BasicSet={};EJSS_DRAWING3D.basicSet=function(mName){};var EJSS_DRAWING3D=EJSS_DRAWING3D||{};EJSS_DRAWING3D.Box={};EJSS_DRAWING3D.box=function(name){};EJSS_DRAWING3D.BoxSet={};EJSS_DRAWING3D.boxSet=function(mName){};var EJSS_DRAWING3D=EJSS_DRAWING3D||{};EJSS_DRAWING3D.Cone={};EJSS_DRAWING3D.cone=function(name){};EJSS_DRAWING3D.ConeSet={};EJSS_DRAWING3D.coneSet=function(mName){};var EJSS_DRAWING3D=EJSS_DRAWING3D||{};EJSS_DRAWING3D.Cylinder={};EJSS_DRAWING3D.cylinder=function(name){};EJSS_DRAWING3D.CylinderSet={};EJSS_DRAWING3D.cylinderSet=function(mName){};var EJSS_DRAWING3D=EJSS_DRAWING3D||{};EJSS_DRAWING3D.Disk={};EJSS_DRAWING3D.disk=function(name){};var EJSS_DRAWING3D=EJSS_DRAWING3D||{};EJSS_DRAWING3D.DrawingPanel={};EJSS_DRAWING3D.drawingPanel=function(mName){};var EJSS_DRAWING3D=EJSS_DRAWING3D||{};EJSS_DRAWING3D.Element={};EJSS_DRAWING3D.element=function(mName){};var EJSS_DRAWING3D=EJSS_DRAWING3D||{};EJSS_DRAWING3D.ElementSet={};EJSS_DRAWING3D.elementSet=function(mConstructor,mName){};var EJSS_DRAWING3D=EJSS_DRAWING3D||{};EJSS_DRAWING3D.Ellipsoid={};EJSS_DRAWING3D.ellipsoid=function(name){};EJSS_DRAWING3D.EllipsoidSet={};EJSS_DRAWING3D.ellipsoidSet=function(mName){};var EJSS_DRAWING3D=EJSS_DRAWING3D||{};EJSS_DRAWING3D.Group={};EJSS_DRAWING3D.group=function(name){};var EJSS_DRAWING3D=EJSS_DRAWING3D||{};EJSS_DRAWING3D.panelInteraction=function(mPanel){var self={};var mEnabled=false;var mLastLocation=[0,0];var mDeltaX=0;var mDeltaY=0;var mMouseIsDown=false;var mUpLastTime=0;var mZoomLastTime=0;var mZoomDelta=0;var mLastZoom=0;var mPinching=false;var mPinchInitDistance=[0,0];self.getPanel=function(){return mPanel};self.getEnabled=function(){return mEnabled};self.setEnabled=function(enabled){if(mEnabled!=enabled){mEnabled=enabled;if(mEnabled){self.setHandler("move",self.handleMouseMoveEvent);self.setHandler("down",self.handleMouseDownEvent);self.setHandler("up",self.handleMouseUpEvent);self.setHandler("mousewheel",self.handleMouseWheelEvent)}else{self.setHandler("move",function(){});self.setHandler("down",function(){});self.setHandler("up",function(){});self.setHandler("mousewheel",function(){})}}};self.getInteractionPoint=function(){return mLastLocation};self.getInteractionDeltas=function(){return[mDeltaX,mDeltaY]};self.getInteractionZoomDelta=function(){return mZoomDelta};self.handleMouseWheelEvent=function(event){var nFingers=typeof event.touches!="undefined"?event.touches.length:0;if(nFingers==0){event.preventDefault();mZoomDelta=Math.max(-1,Math.min(1,event.wheelDelta||-event.detail));mPanel.getController().invokeAction("OnZoom");mPanel.getController().reportInteractions()}};self.handlePinchGesture=function(event){if(event.timeStamp-mZoomLastTime>100){event.preventDefault();if(event.scale<mLastZoom){mZoomDelta=1}else if(event.scale>=mLastZoom){mZoomDelta=-1}mLastZoom=event.scale;mPanel.getController().invokeAction("OnZoom");mPanel.getController().reportInteractions();mZoomLastTime=event.timeStamp}};self.handleMouseMoveEvent=function(event){var nFingers=typeof event.touches!="undefined"?event.touches.length:1;if(nFingers==1){var currentX=mLastLocation[0];var currentY=mLastLocation[1];mLastLocation=getEventLocation(event);mDeltaX=mLastLocation[0]-currentX;mDeltaY=mLastLocation[1]-currentY;if(mMouseIsDown){mPanel.getController().invokeAction("OnDrag");event.target.style.cursor="move"}else{event.target.style.cursor="default"}}if(nFingers==2){if(event.timeStamp-mZoomLastTime>25){event.preventDefault();var e0=event.touches[0];var e1=event.touches[1];var e0x=e0.clientX||e0.x;var e0y=e0.clientY||e0.y;var e1x=e1.clientX||e1.x;var e1y=e1.clientY||e1.y;if(mPinching){var newDistance=[Math.abs(e0x-e1x),Math.abs(e0y-e1y)];var delta=newDistance[0]-mPinchInitDistance[0];if(delta<3&&delta>-3){mZoomDelta=0}else{mZoomDelta=delta;mPinchInitDistance=newDistance}mPanel.getController().invokeAction("OnZoom")}else{mPinching=true;mPinchInitDistance=[Math.abs(e0x-e1x),Math.abs(e0y-e1y)];mZoomDelta=0}mZoomLastTime=event.timeStamp}}else{mPinching=false;mPinchInitDistance=[0,0]}mPanel.getController().reportInteractions()};self.handleMouseDownEvent=function(event){var nFingers=typeof event.touches!="undefined"?event.touches.length:1;if(nFingers==1){mMouseIsDown=true;mLastLocation=getEventLocation(event);mPanel.getController().invokeAction("OnPress");self.pick(mLastLocation[0],mLastLocation[1]);event.preventDefault();mPanel.getController().reportInteractions()}mPinching=false};self.handleMouseUpEvent=function(event){var nFingers=typeof event.touches!="undefined"?event.touches.length:1;if(nFingers==1){mMouseIsDown=false;mLastLocation=getEventLocation(event);mPanel.getController().invokeAction("OnRelease");event.target.style.cursor="default";if(event.timeStamp-mUpLastTime<500){mPanel.getController().invokeAction("OnDoubleClick")}mUpLastTime=event.timeStamp;mPanel.getController().reportInteractions()}mPinching=false};function getEventLocation(e){var x,y;var box=mPanel.getGraphics().getBox();var oleft=box.left;var otop=box.top;if(typeof e.changedTouches!="undefined"&&e.changedTouches.length===1){x=e.changedTouches[0].pageX;y=e.changedTouches[0].pageY}else{x=e.x||e.clientX;y=e.y||e.clientY}return[x-oleft,y-otop]}self.setHandler=function(type,handler){var graphics=mPanel.getGraphics();var context=graphics.getEventContext();switch(type){case"move":context.addEventListener("mousemove",handler,false);context.addEventListener("touchmove",handler,false);break;default:case"down":context.addEventListener("mousedown",handler,false);context.addEventListener("touchstart",handler,false);break;case"up":context.addEventListener("mouseup",handler,false);context.addEventListener("touchend",handler,false);break;case"mousewheel":context.addEventListener("mousewheel",handler,false);break;case"pinch":context.addEventListener("gesturestart",function(event){mLastZoom=1},false);context.addEventListener("gesturechange",handler,false);break}return false};self.pick=function(mousex,mousey){var x=mousex-1;var y=mousey-1;var w=1;var h=1;var gl=mPanel.getGraphics().getContext();if(!gl)return;var data=new Uint8Array(w*h*4);gl.readPixels(x,y,w,h,gl.RGBA,gl.UNSIGNED_BYTE,data);if(data.data)data=data.data};return self};var EJSS_DRAWING3D=EJSS_DRAWING3D||{};EJSS_DRAWING3D.Style={copyTo:function(source,dest){dest.setClosedTop(source.getClosedTop());dest.setClosedBottom(source.getClosedBottom());dest.setClosedLeft(source.getClosedLeft());dest.setClosedRight(source.getClosedRight());dest.setDrawLines(source.getDrawLines());dest.setLineColor(source.getLineColor());dest.setLineWidth(source.getLineWidth());dest.setDrawFill(source.getDrawFill());dest.setTransparency(source.getTransparency());dest.setAmbientColor(source.getAmbientColor());dest.setFillColor(source.getFillColor());dest.setSpecularColor(source.getSpecularColor());dest.setAmbientReflection(source.getAmbientReflection());dest.setColorReflection(source.getColorReflection());dest.setSpecularReflection(source.getSpecularReflection());dest.setShininessVal(source.getShininessVal());dest.setPaletteFloor(source.getPaletteFloor());dest.setPaletteCeil(source.getPaletteCeil());dest.setPaletteFloorColor(source.getPaletteFloorColor());dest.setPaletteCeilColor(source.getPaletteCeilColor())}};EJSS_DRAWING3D.style=function(mName){var self={};var mClosedTop=true;var mClosedBottom=true;var mClosedLeft=true;var mClosedRight=true;var mLineColor=[0,0,0];var mLineWidth=.5;var mAmbientColor=[0,0,0];var mFillColor=[0,0,0];var mSpecularColor=[1,1,1];var mAmbientReflection=1;var mColorReflection=1;var mSpecularReflection=1;var mShininessVal=10;var mPaletteFloor;var mPaletteCeil;var mPaletteFloorColor=[1,0,-1];var mPaletteCeilColor=[-1,0,1];var mDrawLines=false;var mDrawFill=true;var mTransparency=0;var mProjChangeListener;var mMeshChangeListener;self.setProjChangeListener=function(listener){mProjChangeListener=listener};self.setMeshChangeListener=function(listener){mMeshChangeListener=listener};self.setClosedTop=function(closed){if(closed!=mClosedTop){mClosedTop=closed;if(mMeshChangeListener)mMeshChangeListener("closedtop")}};self.getClosedTop=function(){return mClosedTop};self.setClosedBottom=function(closed){if(closed!=mClosedBottom){mClosedBottom=closed;if(mMeshChangeListener)mMeshChangeListener("closedbottom")}};self.getClosedBottom=function(){return mClosedBottom};self.setClosedLeft=function(closed){if(closed!=mClosedLeft){mClosedLeft=closed;if(mMeshChangeListener)mMeshChangeListener("closedleft")}};self.getClosedLeft=function(){return mClosedLeft};self.setClosedRight=function(closed){if(closed!=mClosedRight){mClosedRight=closed;if(mMeshChangeListener)mMeshChangeListener("closedright")}};self.getClosedRight=function(){return mClosedRight};self.setDrawLines=function(draw){if(draw!=mDrawLines){mDrawLines=draw;if(mProjChangeListener)mProjChangeListener("drawlines")}};self.getDrawLines=function(){return mDrawLines};self.setLineColor=function(color){if(typeof color==="string")color=EJSS_TOOLS.DisplayColors.getArrayColor(color);if(!EJSS_TOOLS.compareArrays(color,mLineColor)){mLineColor=color.slice();if(mProjChangeListener)mProjChangeListener("linecolor")}return self};self.getLineColor=function(){return mLineColor};self.setLineWidth=function(width){if(width!=mLineWidth){mLineWidth=width;if(mProjChangeListener)mProjChangeListener("linewidth")}};self.getLineWidth=function(){return mLineWidth};self.setDrawFill=function(draw){if(draw!=mDrawFill){mDrawFill=draw;if(mProjChangeListener)mProjChangeListener("drawfill")}};self.getDrawFill=function(){return mDrawFill};self.setFillColor=function(color){if(typeof color==="string")color=EJSS_TOOLS.DisplayColors.getArrayColor(color);if(!EJSS_TOOLS.compareArrays(color,mFillColor)){mFillColor=color.slice();if(mProjChangeListener)mProjChangeListener("fillcolor")}};self.getFillColor=function(){return mFillColor};self.setAmbientColor=function(color){if(typeof color==="string")color=EJSS_TOOLS.DisplayColors.getArrayColor(color);if(!EJSS_TOOLS.compareArrays(color,mAmbientColor)){mAmbientColor=color.slice();if(mProjChangeListener)mProjChangeListener("ambientcolor")}};self.getAmbientColor=function(){return mAmbientColor};self.setSpecularColor=function(color){if(typeof color==="string")color=EJSS_TOOLS.DisplayColors.getArrayColor(color);if(!EJSS_TOOLS.compareArrays(color,mSpecularColor)){mSpecularColor=color.slice();if(mProjChangeListener)mProjChangeListener("specularcolor")}};self.getSpecularColor=function(){return mSpecularColor};self.setAmbientReflection=function(k){if(mAmbientReflection!=k){mAmbientReflection=k;if(mProjChangeListener)mProjChangeListener("ambientreflection")}};self.getAmbientReflection=function(){return mAmbientReflection};self.setColorReflection=function(k){if(mColorReflection!=k){mColorReflection=k;if(mProjChangeListener)mProjChangeListener("colorreflection")}};self.getColorReflection=function(){return mColorReflection};self.setSpecularReflection=function(k){if(mSpecularReflection!=k){mSpecularReflection=k;if(mProjChangeListener)mProjChangeListener("specularreflection")}};self.getSpecularReflection=function(){return mSpecularReflection};self.setShininessVal=function(shininess){if(mShininessVal!=shininess){mShininessVal=shininess;if(mProjChangeListener)mProjChangeListener("shininess")}};self.getShininessVal=function(){return mShininessVal};self.setTransparency=function(transparency){if(transparency!=mTransparency){mTransparency=transparency;if(mProjChangeListener)mProjChangeListener("transparency")}};self.getTransparency=function(){return mTransparency};self.setPaletteFloor=function(floor){if(floor&&!EJSS_TOOLS.compareArrays(floor,mPaletteFloor)){mPaletteFloor=floor.slice();if(mProjChangeListener)mProjChangeListener("palettefloor")}};self.getPaletteFloor=function(){return mPaletteFloor};self.setPaletteCeil=function(ceil){if(ceil&&!EJSS_TOOLS.compareArrays(ceil,mPaletteCeil)){mPaletteCeil=ceil.slice();if(mProjChangeListener)mProjChangeListener("paletteceil")}};self.getPaletteCeil=function(){return mPaletteCeil};self.setPaletteFloorColor=function(color){if(!EJSS_TOOLS.compareArrays(color,mPaletteFloorColor)){mPaletteFloorColor=color.slice();if(mProjChangeListener)mProjChangeListener("palettefloorcolor")}};self.getPaletteFloorColor=function(){return mPaletteFloorColor};self.setPaletteCeilColor=function(color){if(!EJSS_TOOLS.compareArrays(color,mPaletteCeilColor)){mPaletteCeilColor=color.slice();if(mProjChangeListener)mProjChangeListener("paletteceilcolor")}};self.getPaletteCeilColor=function(){return mPaletteCeilColor};return self};var EJSS_DRAWING3D=EJSS_DRAWING3D||{};EJSS_DRAWING3D.Transformation={registerProperties:function(element,controller){element.setController(controller);controller.registerProperty("Parent",element.setParent,element.getParent);controller.registerProperty("Axis",element.setAxis,element.getAxis);controller.registerProperty("Angle",element.setAngle,element.getAngle);controller.registerProperty("Origin",element.setOrigin,element.getOrigin)}};EJSS_DRAWING3D.rotationX=function(mName){var self=EJSS_DRAWING3D.transformation();self.setAxis([1,0,0]);return self};EJSS_DRAWING3D.rotationY=function(mName){var self=EJSS_DRAWING3D.transformation();self.setAxis([0,1,0]);return self};EJSS_DRAWING3D.rotationZ=function(mName){var self=EJSS_DRAWING3D.transformation();self.setAxis([0,0,1]);return self};EJSS_DRAWING3D.transformation=function(mName){var self={};var mParent=null;var mArray=[0,0,0,1,0,0,0];var mController={propertiesChanged:function(){},invokeAction:function(){}};self.getArray=function(){return mArray};self.setChanged=function(changed){if(changed)mParent.setProjChanged(true)};self.setParent=function(parent){if(mParent){mParent.removeExtraTransformation(self)}mParent=parent;if(mParent){mParent.addExtraTransformation(self)}};self.getParent=function(){return mParent};self.setAngle=function(angle){mArray[0]=angle};self.getAngle=function(){return mArray[0]};self.setAxis=function(axis){mArray[1]=axis[0];mArray[2]=axis[1];mArray[3]=axis[2]};self.getAxis=function(){return mArray.slice(1,4)};self.setOrigin=function(origin){mArray[4]=origin[0];mArray[5]=origin[1];mArray[6]=origin[2]};self.getOrigin=function(){return mArray.slice(5)};self.getController=function(){return mController};self.setController=function(controller){mController=controller};self.registerProperties=function(controller){EJSS_DRAWING3D.Transformation.registerProperties(self,controller)};return self};var EJSS_WEBGLGRAPHICS=EJSS_WEBGLGRAPHICS||{};EJSS_WEBGLGRAPHICS.analyticCurve=function(mGL,mElement){};var EJSS_WEBGLGRAPHICS=EJSS_WEBGLGRAPHICS||{};EJSS_WEBGLGRAPHICS.analyticSurface=function(mGL,mElement){};var EJSS_WEBGLGRAPHICS=EJSS_WEBGLGRAPHICS||{};EJSS_WEBGLGRAPHICS.arrow=function(mGL,mElement){};var EJSS_WEBGLGRAPHICS=EJSS_WEBGLGRAPHICS||{};EJSS_WEBGLGRAPHICS.basic=function(mGL,mElement){};var EJSS_WEBGLGRAPHICS=EJSS_WEBGLGRAPHICS||{};EJSS_WEBGLGRAPHICS.box=function(mGL,mElement){};var EJSS_WEBGLGRAPHICS=EJSS_WEBGLGRAPHICS||{};EJSS_WEBGLGRAPHICS.cylinder=function(mGL,mElement){};var EJSS_WEBGLGRAPHICS=EJSS_WEBGLGRAPHICS||{};EJSS_WEBGLGRAPHICS.ellipsoid=function(mGL,mElement){};var hasFloat32Array=typeof Float32Array!="undefined";function Matrix(){var m=Array.prototype.concat.apply([],arguments);if(!m.length){m=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}this.m=hasFloat32Array?new Float32Array(m):m}Matrix.prototype={inverse:function(){return Matrix.inverse(this,new Matrix)},transpose:function(){return Matrix.transpose(this,new Matrix)},multiply:function(matrix){return Matrix.multiply(this,matrix,new Matrix)},transformPoint:function(v){var m=this.m;return new Vector(m[0]*v.x+m[1]*v.y+m[2]*v.z+m[3],m[4]*v.x+m[5]*v.y+m[6]*v.z+m[7],m[8]*v.x+m[9]*v.y+m[10]*v.z+m[11]).divide(m[12]*v.x+m[13]*v.y+m[14]*v.z+m[15])},transformVector:function(v){var m=this.m;return new Vector(m[0]*v.x+m[1]*v.y+m[2]*v.z,m[4]*v.x+m[5]*v.y+m[6]*v.z,m[8]*v.x+m[9]*v.y+m[10]*v.z)}};Matrix.inverse=function(matrix,result){result=result||new Matrix;var m=matrix.m,r=result.m;r[0]=m[5]*m[10]*m[15]-m[5]*m[14]*m[11]-m[6]*m[9]*m[15]+m[6]*m[13]*m[11]+m[7]*m[9]*m[14]-m[7]*m[13]*m[10];r[1]=-m[1]*m[10]*m[15]+m[1]*m[14]*m[11]+m[2]*m[9]*m[15]-m[2]*m[13]*m[11]-m[3]*m[9]*m[14]+m[3]*m[13]*m[10];r[2]=m[1]*m[6]*m[15]-m[1]*m[14]*m[7]-m[2]*m[5]*m[15]+m[2]*m[13]*m[7]+m[3]*m[5]*m[14]-m[3]*m[13]*m[6];r[3]=-m[1]*m[6]*m[11]+m[1]*m[10]*m[7]+m[2]*m[5]*m[11]-m[2]*m[9]*m[7]-m[3]*m[5]*m[10]+m[3]*m[9]*m[6];r[4]=-m[4]*m[10]*m[15]+m[4]*m[14]*m[11]+m[6]*m[8]*m[15]-m[6]*m[12]*m[11]-m[7]*m[8]*m[14]+m[7]*m[12]*m[10];r[5]=m[0]*m[10]*m[15]-m[0]*m[14]*m[11]-m[2]*m[8]*m[15]+m[2]*m[12]*m[11]+m[3]*m[8]*m[14]-m[3]*m[12]*m[10];r[6]=-m[0]*m[6]*m[15]+m[0]*m[14]*m[7]+m[2]*m[4]*m[15]-m[2]*m[12]*m[7]-m[3]*m[4]*m[14]+m[3]*m[12]*m[6];r[7]=m[0]*m[6]*m[11]-m[0]*m[10]*m[7]-m[2]*m[4]*m[11]+m[2]*m[8]*m[7]+m[3]*m[4]*m[10]-m[3]*m[8]*m[6];r[8]=m[4]*m[9]*m[15]-m[4]*m[13]*m[11]-m[5]*m[8]*m[15]+m[5]*m[12]*m[11]+m[7]*m[8]*m[13]-m[7]*m[12]*m[9];r[9]=-m[0]*m[9]*m[15]+m[0]*m[13]*m[11]+m[1]*m[8]*m[15]-m[1]*m[12]*m[11]-m[3]*m[8]*m[13]+m[3]*m[12]*m[9];r[10]=m[0]*m[5]*m[15]-m[0]*m[13]*m[7]-m[1]*m[4]*m[15]+m[1]*m[12]*m[7]+m[3]*m[4]*m[13]-m[3]*m[12]*m[5];r[11]=-m[0]*m[5]*m[11]+m[0]*m[9]*m[7]+m[1]*m[4]*m[11]-m[1]*m[8]*m[7]-m[3]*m[4]*m[9]+m[3]*m[8]*m[5];r[12]=-m[4]*m[9]*m[14]+m[4]*m[13]*m[10]+m[5]*m[8]*m[14]-m[5]*m[12]*m[10]-m[6]*m[8]*m[13]+m[6]*m[12]*m[9];r[13]=m[0]*m[9]*m[14]-m[0]*m[13]*m[10]-m[1]*m[8]*m[14]+m[1]*m[12]*m[10]+m[2]*m[8]*m[13]-m[2]*m[12]*m[9];r[14]=-m[0]*m[5]*m[14]+m[0]*m[13]*m[6]+m[1]*m[4]*m[14]-m[1]*m[12]*m[6]-m[2]*m[4]*m[13]+m[2]*m[12]*m[5];r[15]=m[0]*m[5]*m[10]-m[0]*m[9]*m[6]-m[1]*m[4]*m[10]+m[1]*m[8]*m[6]+m[2]*m[4]*m[9]-m[2]*m[8]*m[5];var det=m[0]*r[0]+m[1]*r[4]+m[2]*r[8]+m[3]*r[12];for(var i=0;i<16;i++)r[i]/=det;return result};Matrix.transpose=function(matrix,result){result=result||new Matrix;var m=matrix.m,r=result.m;r[0]=m[0];r[1]=m[4];r[2]=m[8];r[3]=m[12];r[4]=m[1];r[5]=m[5];r[6]=m[9];r[7]=m[13];r[8]=m[2];r[9]=m[6];r[10]=m[10];r[11]=m[14];r[12]=m[3];r[13]=m[7];r[14]=m[11];r[15]=m[15];return result};Matrix.multiply=function(left,right,result){result=result||new Matrix;var a=left.m,b=right.m,r=result.m;r[0]=a[0]*b[0]+a[1]*b[4]+a[2]*b[8]+a[3]*b[12];r[1]=a[0]*b[1]+a[1]*b[5]+a[2]*b[9]+a[3]*b[13];r[2]=a[0]*b[2]+a[1]*b[6]+a[2]*b[10]+a[3]*b[14];r[3]=a[0]*b[3]+a[1]*b[7]+a[2]*b[11]+a[3]*b[15];r[4]=a[4]*b[0]+a[5]*b[4]+a[6]*b[8]+a[7]*b[12];r[5]=a[4]*b[1]+a[5]*b[5]+a[6]*b[9]+a[7]*b[13];r[6]=a[4]*b[2]+a[5]*b[6]+a[6]*b[10]+a[7]*b[14];r[7]=a[4]*b[3]+a[5]*b[7]+a[6]*b[11]+a[7]*b[15];r[8]=a[8]*b[0]+a[9]*b[4]+a[10]*b[8]+a[11]*b[12];r[9]=a[8]*b[1]+a[9]*b[5]+a[10]*b[9]+a[11]*b[13];r[10]=a[8]*b[2]+a[9]*b[6]+a[10]*b[10]+a[11]*b[14];r[11]=a[8]*b[3]+a[9]*b[7]+a[10]*b[11]+a[11]*b[15];r[12]=a[12]*b[0]+a[13]*b[4]+a[14]*b[8]+a[15]*b[12];r[13]=a[12]*b[1]+a[13]*b[5]+a[14]*b[9]+a[15]*b[13];r[14]=a[12]*b[2]+a[13]*b[6]+a[14]*b[10]+a[15]*b[14];r[15]=a[12]*b[3]+a[13]*b[7]+a[14]*b[11]+a[15]*b[15];return result};Matrix.identity=function(result){result=result||new Matrix;var m=result.m;m[0]=m[5]=m[10]=m[15]=1;m[1]=m[2]=m[3]=m[4]=m[6]=m[7]=m[8]=m[9]=m[11]=m[12]=m[13]=m[14]=0;return result};Matrix.perspective=function(fov,aspect,near,far,result){
var y=Math.tan(fov*Math.PI/360)*near;var x=y*aspect;return Matrix.frustum(-x,x,-y,y,near,far,result)};Matrix.frustum=function(l,r,b,t,n,f,result){result=result||new Matrix;var m=result.m;m[0]=2*n/(r-l);m[1]=0;m[2]=(r+l)/(r-l);m[3]=0;m[4]=0;m[5]=2*n/(t-b);m[6]=(t+b)/(t-b);m[7]=0;m[8]=0;m[9]=0;m[10]=-(f+n)/(f-n);m[11]=-2*f*n/(f-n);m[12]=0;m[13]=0;m[14]=-1;m[15]=0;return result};Matrix.ortho=function(l,r,b,t,n,f,result){result=result||new Matrix;var m=result.m;m[0]=2/(r-l);m[1]=0;m[2]=0;m[3]=-(r+l)/(r-l);m[4]=0;m[5]=2/(t-b);m[6]=0;m[7]=-(t+b)/(t-b);m[8]=0;m[9]=0;m[10]=-2/(f-n);m[11]=-(f+n)/(f-n);m[12]=0;m[13]=0;m[14]=0;m[15]=1;return result};Matrix.scale=function(x,y,z,result){result=result||new Matrix;var m=result.m;m[0]=x;m[1]=0;m[2]=0;m[3]=0;m[4]=0;m[5]=y;m[6]=0;m[7]=0;m[8]=0;m[9]=0;m[10]=z;m[11]=0;m[12]=0;m[13]=0;m[14]=0;m[15]=1;return result};Matrix.translate=function(x,y,z,result){result=result||new Matrix;var m=result.m;m[0]=1;m[1]=0;m[2]=0;m[3]=x;m[4]=0;m[5]=1;m[6]=0;m[7]=y;m[8]=0;m[9]=0;m[10]=1;m[11]=z;m[12]=0;m[13]=0;m[14]=0;m[15]=1;return result};Matrix.rotate=function(a,x,y,z,cx,cy,cz,result){if(!a||!x&&!y&&!z){return Matrix.identity(result)}result=result||new Matrix;var m=result.m;var d=Math.sqrt(x*x+y*y+z*z);x/=d;y/=d;z/=d;var c=Math.cos(a),s=Math.sin(a),t=1-c;m[0]=x*x*t+c;m[1]=x*y*t-z*s;m[2]=x*z*t+y*s;m[3]=cx-m[0]*cx-m[1]*cy-m[2]*cz;m[4]=y*x*t+z*s;m[5]=y*y*t+c;m[6]=y*z*t-x*s;m[7]=cy-m[4]*cx-m[5]*cy-m[6]*cz;m[8]=z*x*t-y*s;m[9]=z*y*t+x*s;m[10]=z*z*t+c;m[11]=cz-m[8]*cx-m[9]*cy-m[10]*cz;m[12]=0;m[13]=0;m[14]=0;m[15]=1;return result};Matrix.lookAt=function(ex,ey,ez,cx,cy,cz,ux,uy,uz,result){result=result||new Matrix;var m=result.m;var e=new Vector(ex,ey,ez);var c=new Vector(cx,cy,cz);var u=new Vector(ux,uy,uz);var f=e.subtract(c).unit();var s=u.cross(f).unit();var t=f.cross(s).unit();m[0]=s.x;m[1]=s.y;m[2]=s.z;m[3]=-s.dot(e);m[4]=t.x;m[5]=t.y;m[6]=t.z;m[7]=-t.dot(e);m[8]=f.x;m[9]=f.y;m[10]=f.z;m[11]=-f.dot(e);m[12]=0;m[13]=0;m[14]=0;m[15]=1;return result};var EJSS_WEBGLGRAPHICS=EJSS_WEBGLGRAPHICS||{};EJSS_WEBGLGRAPHICS.mesh=function(mGL,id,options){};EJSS_WEBGLGRAPHICS.indexer=function(){var self={};var unique=[];var map={};self.getUnique=function(){return unique};self.add=function(obj){var key=JSON.stringify(obj);if(!(key in map)){map[key]=unique.length;unique.push(obj)}return map[key]};return self};EJSS_WEBGLGRAPHICS.buffer=function(mGL,target,type){var self={};var buffer=null;var target=target;var type=type;var mName="";var mData=[];self.setData=function(b){mData=b};self._0=function(name){mName=name};self.getBuffer=function(){return buffer};self.getName=function(){return mName};self.compile=function(tp){var data=[];for(var i=0,chunk=1e4;i<mData.length;i+=chunk){data=Array.prototype.concat.apply(data,mData.slice(i,i+chunk))}var spacing=mData.length?data.length/mData.length:0;if(spacing!=Math.round(spacing))throw"buffer elements not of consistent size, average size is "+spacing;buffer=buffer||mGL.createBuffer();buffer.length=data.length;buffer.spacing=spacing;mGL.bindBuffer(target,buffer);mGL.bufferData(target,new type(data),tp||mGL.STATIC_DRAW)};return self};var EJSS_WEBGLGRAPHICS=EJSS_WEBGLGRAPHICS||{};EJSS_WEBGLGRAPHICS.plane=function(mGL,mElement){};var EJSS_WEBGLGRAPHICS=EJSS_WEBGLGRAPHICS||{};EJSS_WEBGLGRAPHICS.segment=function(mGL,mElement){};var EJSS_WEBGLGRAPHICS=EJSS_WEBGLGRAPHICS||{};EJSS_WEBGLGRAPHICS.Shader={};EJSS_WEBGLGRAPHICS.shader=function(mGL,mName,vertexSource,fragmentSource){};var EJSS_WEBGLGRAPHICS=EJSS_WEBGLGRAPHICS||{};EJSS_WEBGLGRAPHICS.spring=function(mGL,mElement){};var EJSS_WEBGLGRAPHICS=EJSS_WEBGLGRAPHICS||{};EJSS_WEBGLGRAPHICS.surface=function(mGL,mElement){};var EJSS_WEBGLGRAPHICS=EJSS_WEBGLGRAPHICS||{};EJSS_WEBGLGRAPHICS.text=function(mGL,mElement){};var EJSS_WEBGLGRAPHICS=EJSS_WEBGLGRAPHICS||{};EJSS_WEBGLGRAPHICS.Texture={};EJSS_WEBGLGRAPHICS.texture=function(mGL,width,height,options){};var EJSS_WEBGLGRAPHICS=EJSS_WEBGLGRAPHICS||{};EJSS_WEBGLGRAPHICS.trail=function(mGL,mElement){};var EJSS_WEBGLGRAPHICS=EJSS_WEBGLGRAPHICS||{};EJSS_WEBGLGRAPHICS.Utils={};EJSS_WEBGLGRAPHICS.Utils.regexMap=function(regex,text,callback){while((result=regex.exec(text))!=null){callback(result)}};EJSS_WEBGLGRAPHICS.Utils.isArray=function(obj){var str=Object.prototype.toString.call(obj);return str=="[object Array]"||str=="[object Float32Array]"};EJSS_WEBGLGRAPHICS.Utils.isNumber=function(obj){var str=Object.prototype.toString.call(obj);return str=="[object Number]"||str=="[object Boolean]"};function Vector(x,y,z){if(typeof x=="object"){this.x=x[0]||0;this.y=x[1]||0;this.z=x[2]||0}else{this.x=x||0;this.y=y||0;this.z=z||0}}Vector.prototype={setx:function(x){this.x=x},sety:function(y){this.y=y},setz:function(z){this.z=z},getx:function(){return this.x},gety:function(){return this.y},getz:function(){return this.z},negative:function(){return new Vector(-this.x,-this.y,-this.z)},add:function(v){if(v instanceof Vector)return new Vector(this.x+v.x,this.y+v.y,this.z+v.z);else return new Vector(this.x+v,this.y+v,this.z+v)},subtract:function(v){if(v instanceof Vector)return new Vector(this.x-v.x,this.y-v.y,this.z-v.z);else return new Vector(this.x-v,this.y-v,this.z-v)},multiply:function(v){if(v instanceof Vector)return new Vector(this.x*v.x,this.y*v.y,this.z*v.z);else return new Vector(this.x*v,this.y*v,this.z*v)},divide:function(v){if(v instanceof Vector)return new Vector(this.x/v.x,this.y/v.y,this.z/v.z);else return new Vector(this.x/v,this.y/v,this.z/v)},equals:function(v){return this.x==v.x&&this.y==v.y&&this.z==v.z},dot:function(v){return this.x*v.x+this.y*v.y+this.z*v.z},cross:function(v){return new Vector(this.y*v.z-this.z*v.y,this.z*v.x-this.x*v.z,this.x*v.y-this.y*v.x)},length:function(){return Math.sqrt(this.dot(this))},unit:function(){return this.divide(this.length())},min:function(){return Math.min(Math.min(this.x,this.y),this.z)},max:function(){return Math.max(Math.max(this.x,this.y),this.z)},angle:function(v){return Math.acos(this.dot(v)/(this.length()*v.length()))},toAngles:function(){return{theta:Math.atan2(this.z,this.x),phi:Math.asin(this.y/this.length())}},toArray:function(n){return[this.x,this.y,this.z].slice(0,n||3)},clone:function(){return new Vector(this.x,this.y,this.z)},init:function(x,y,z){this.x=x;this.y=y;this.z=z;return this}};Vector.negative=function(a,b){b.x=-a.x;b.y=-a.y;b.z=-a.z;return b};Vector.add=function(a,b,c){if(b instanceof Vector){c.x=a.x+b.x;c.y=a.y+b.y;c.z=a.z+b.z}else{c.x=a.x+b;c.y=a.y+b;c.z=a.z+b}return c};Vector.subtract=function(a,b,c){if(b instanceof Vector){c.x=a.x-b.x;c.y=a.y-b.y;c.z=a.z-b.z}else{c.x=a.x-b;c.y=a.y-b;c.z=a.z-b}return c};Vector.multiply=function(a,b,c){if(b instanceof Vector){c.x=a.x*b.x;c.y=a.y*b.y;c.z=a.z*b.z}else{c.x=a.x*b;c.y=a.y*b;c.z=a.z*b}return c};Vector.divide=function(a,b,c){if(b instanceof Vector){c.x=a.x/b.x;c.y=a.y/b.y;c.z=a.z/b.z}else{c.x=a.x/b;c.y=a.y/b;c.z=a.z/b}return c};Vector.cross=function(a,b,c){c.x=a.y*b.z-a.z*b.y;c.y=a.z*b.x-a.x*b.z;c.z=a.x*b.y-a.y*b.x;return c};Vector.unit=function(a,b){var length=a.length();b.x=a.x/length;b.y=a.y/length;b.z=a.z/length;return b};Vector.fromAngles=function(theta,phi){return new Vector(Math.cos(theta)*Math.cos(phi),Math.sin(phi),Math.sin(theta)*Math.cos(phi))};Vector.randomDirection=function(){return Vector.fromAngles(Math.random()*Math.PI*2,Math.asin(Math.random()*2-1))};Vector.min=function(a,b){return new Vector(Math.min(a.x,b.x),Math.min(a.y,b.y),Math.min(a.z,b.z))};Vector.max=function(a,b){return new Vector(Math.max(a.x,b.x),Math.max(a.y,b.y),Math.max(a.z,b.z))};Vector.lerp=function(a,b,fraction){return b.subtract(a).multiply(fraction).add(a)};Vector.fromArray=function(a){return new Vector(a[0],a[1],a[2])};var EJSS_GRAPHICS=EJSS_GRAPHICS||{};EJSS_GRAPHICS.WebGLGraphics={};EJSS_GRAPHICS.webGLGraphics=function(mName){};var EJSS_DRAWING3D=EJSS_DRAWING3D||{};EJSS_DRAWING3D.Plane={};EJSS_DRAWING3D.plane=function(name){};EJSS_DRAWING3D.PlaneSet={};EJSS_DRAWING3D.planeSet=function(mName){};var EJSS_DRAWING3D=EJSS_DRAWING3D||{};EJSS_DRAWING3D.Segment={};EJSS_DRAWING3D.segment=function(name){};EJSS_DRAWING3D.SegmentSet={};EJSS_DRAWING3D.segmentSet=function(mName){};var EJSS_DRAWING3D=EJSS_DRAWING3D||{};EJSS_DRAWING3D.Sphere={};EJSS_DRAWING3D.sphere=function(name){};EJSS_DRAWING3D.SphereSet={};EJSS_DRAWING3D.sphereSet=function(mName){};var EJSS_DRAWING3D=EJSS_DRAWING3D||{};EJSS_DRAWING3D.Spring={};EJSS_DRAWING3D.spring=function(name){};EJSS_DRAWING3D.SpringSet={};EJSS_DRAWING3D.springSet=function(mName){};var EJSS_DRAWING3D=EJSS_DRAWING3D||{};EJSS_DRAWING3D.Surface={};EJSS_DRAWING3D.surface=function(name){};EJSS_DRAWING3D.SurfaceSet={};EJSS_DRAWING3D.surfaceSet=function(mName){};var EJSS_DRAWING3D=EJSS_DRAWING3D||{};EJSS_DRAWING3D.Tetrahedron={};EJSS_DRAWING3D.tetrahedron=function(name){};EJSS_DRAWING3D.TetrahedronSet={};EJSS_DRAWING3D.tetrahedronSet=function(mName){};var EJSS_DRAWING3D=EJSS_DRAWING3D||{};EJSS_DRAWING3D.Text={};EJSS_DRAWING3D.text=function(name){};EJSS_DRAWING3D.TextSet={};EJSS_DRAWING3D.textSet=function(mName){};var EJSS_DRAWING3D=EJSS_DRAWING3D||{};EJSS_DRAWING3D.Trail={};EJSS_DRAWING3D.trail=function(name){};EJSS_DRAWING3D.TrailSet={};EJSS_DRAWING3D.trailSet=function(mName){};var EJSS_INTERFACE=EJSS_INTERFACE||{};EJSS_INTERFACE.ArrayPanel={};EJSS_INTERFACE.arrayPanel=function(mName){};var EJSS_INTERFACE=EJSS_INTERFACE||{};EJSS_INTERFACE.Audio={};EJSS_INTERFACE.audio=function(mName){};var EJSS_INTERFACE=EJSS_INTERFACE||{};EJSS_INTERFACE.BoxPanel={registerProperties:function(element,controller){EJSS_INTERFACE.Panel.registerProperties(element,controller);controller.registerProperty("Draggable",element.setDraggable)},showOkDialog:function(message,okfunction,width){var mypanel=document.getElementById(".myBoxPanelOk")||EJSS_INTERFACE.boxPanel(".myBoxPanelOk").getDOMElement();var mybackpanel=document.getElementById(".myBoxPanelOk.back");var myMsg=document.getElementById(".myBoxPanelOk.msg");myMsg.style.visibility="visible";myMsg.innerHTML=message+"<br/>";var myOkButton=document.getElementById(".myBoxPanelOk.okbt");myOkButton.onclick=okfunction;myOkButton.style.display="inline";mypanel.style.width=width||"200px";if(mypanel.style.position=="fixed")mypanel.style.marginLeft=parseFloat(mypanel.style.width)/-2+"px";mypanel.style.visibility="visible";mybackpanel.style.visibility="visible"},showOkCancelDialog:function(message,okfunction,cancelfunction,width){var mypanel=document.getElementById(".myBoxPanelCancelOk")||EJSS_INTERFACE.boxPanel(".myBoxPanelCancelOk").getDOMElement();var mybackpanel=document.getElementById(".myBoxPanelCancelOk.back");var myMsg=document.getElementById(".myBoxPanelCancelOk.msg");myMsg.style.visibility="visible";myMsg.innerHTML=message+"<br/>";var myOkButton=document.getElementById(".myBoxPanelCancelOk.okbt");myOkButton.onclick=okfunction;myOkButton.style.display="inline";var myCancelButton=document.getElementById(".myBoxPanelCancelOk.cancelbt");myCancelButton.onclick=cancelfunction;myCancelButton.style.display="inline";mypanel.style.width=width||"200px";if(mypanel.style.position=="fixed")mypanel.style.marginLeft=parseFloat(mypanel.style.width)/-2+"px";mypanel.style.visibility="visible";mybackpanel.style.visibility="visible"},showInputDialog:function(message,okfunction,cancelfunction,width){var mypanel=document.getElementById(".BoxPanelInput")||EJSS_INTERFACE.boxPanel(".BoxPanelInput").getDOMElement();var mybackpanel=document.getElementById(".BoxPanelInput.back");var myMsg=document.getElementById(".BoxPanelInput.msg");myMsg.style.visibility="visible";myMsg.innerHTML=message;var myIn=document.getElementById(".BoxPanelInput.input");myIn.style.display="inline";var myOkButton=document.getElementById(".BoxPanelInput.okbt");myOkButton.onclick=function(){okfunction(myIn.value)};myOkButton.style.display="inline";var myCancelButton=document.getElementById(".BoxPanelInput.cancelbt");myCancelButton.onclick=cancelfunction;myCancelButton.style.display="inline";mypanel.style.width=width||"200px";if(mypanel.style.position=="fixed")mypanel.style.marginLeft=parseFloat(mypanel.style.width)/-2+"px";mypanel.style.visibility="visible";mybackpanel.style.visibility="visible"},showSelectDialog:function(message,options,okfunction,cancelfunction,size,width){var mypanel=document.getElementById(".BoxPanelSelect")||EJSS_INTERFACE.boxPanel(".BoxPanelSelect").getDOMElement();var mybackpanel=document.getElementById(".BoxPanelSelect.back");var myMsg=document.getElementById(".BoxPanelSelect.msg");myMsg.style.visibility="visible";myMsg.innerHTML=message;var mySelect=document.getElementById(".BoxPanelSelect.select");mySelect.innerHTML="";for(var i=0;i<options.text.length;i++){var option=document.createElement("option");if(option.value&&option.value[i])option.setAttribute("value",options.value[i]);option.innerHTML=options.text[i];mySelect.appendChild(option)}if(size)mySelect.size=size;mySelect.style.display="block";mySelect.style.margin="0 auto";var myOkButton=document.getElementById(".BoxPanelSelect.okbt");myOkButton.onclick=function(){okfunction(options.value[mySelect.selectedIndex])};myOkButton.style.display="inline";var myCancelButton=document.getElementById(".BoxPanelSelect.cancelbt");myCancelButton.onclick=cancelfunction;myCancelButton.style.display="inline";mypanel.style.width=width||"200px";if(mypanel.style.position=="fixed")mypanel.style.marginLeft=parseFloat(mypanel.style.width)/-2+"px";mypanel.style.visibility="visible";mybackpanel.style.visibility="visible"}};EJSS_INTERFACE.boxPanel=function(mName){var self=EJSS_INTERFACE.panel(mName);var offset={x:0,y:0};self.setVisibility=function(visible){mElement.style.visibility=visible;self.getStyle().setVisibility(visible)};self.setDraggable=function(draggable){if(draggable){self.getDOMElement().addEventListener("mousedown",mouseDown,false);self.getDOMElement().addEventListener("touchstart",mouseDown,false);window.addEventListener("mouseup",mouseUp,false);window.addEventListener("touchend",mouseUp,false)}else{self.getDOMElement().removeEventListener("mousedown",mouseDown,false);self.getDOMElement().removeEventListener("touchstart",mouseDown,false);window.removeEventListener("mouseup",mouseUp,false);window.removeEventListener("touchend",mouseUp,false)}};function mouseUp(){window.removeEventListener("mousemove",popupMove,true);window.removeEventListener("touchmove",popupMove,true)}function mouseDown(e){var box=self.getDOMElement().getBoundingClientRect();offset.x=e.clientX-box.left;offset.y=e.clientY-box.top;window.addEventListener("mousemove",popupMove,true)}function popupMove(e){self.getDOMElement().style.position="absolute";self.getDOMElement().style.margin="0px";var top=e.clientY-offset.y;var left=e.clientX-offset.x;self.getDOMElement().style.top=top+"px";self.getDOMElement().style.left=left+"px"}self.registerProperties=function(controller){EJSS_INTERFACE.BoxPanel.registerProperties(self,controller)};var mBackElement=document.createElement("div");document.body.appendChild(mBackElement);mBackElement.className="myBoxPanelBackground";mBackElement.id=mName+".back";mBackElement.style.backgroundColor="rgba(255, 255, 255, 0.3)";mBackElement.style.position="fixed";mBackElement.style.top="1%";mBackElement.style.left="1%";mBackElement.style.width="98%";mBackElement.style.height="98%";mBackElement.style.zIndex="99998";mBackElement.style.visibility="hidden";var mMsgElement=document.createElement("span");mMsgElement.id=mName+".msg";mMsgElement.style.visibility="hidden";self.getDOMElement().appendChild(mMsgElement);var mInputElement=document.createElement("input");mInputElement.id=mName+".input";mInputElement.type="text";mInputElement.style.display="none";mInputElement.size="20";self.getDOMElement().appendChild(mInputElement);var mSelectElement=document.createElement("select");mSelectElement.id=mName+".select";mSelectElement.style.display="none";mSelectElement.size="4";self.getDOMElement().appendChild(mSelectElement);var mOkBtElement=document.createElement("button");mOkBtElement.id=mName+".okbt";mOkBtElement.innerHTML="Ok";mOkBtElement.style.verticalAlign="middle";mOkBtElement.style.display="none";mOkBtElement.addEventListener("click",function(){document.getElementById(mName).style.visibility="hidden";document.getElementById(mName+".back").style.visibility="hidden";document.getElementById(mName+".msg").style.visibility="hidden";document.getElementById(mName+".input").style.display="none";document.getElementById(mName+".okbt").style.display="none";document.getElementById(mName+".cancelbt").style.display="none"});self.getDOMElement().appendChild(mOkBtElement);var mCancelBtElement=document.createElement("button");mCancelBtElement.id=mName+".cancelbt";mCancelBtElement.innerHTML="Cancel";mCancelBtElement.style.verticalAlign="middle";mCancelBtElement.style.display="none";mCancelBtElement.addEventListener("click",function(){document.getElementById(mName).style.visibility="hidden";document.getElementById(mName+".back").style.visibility="hidden";document.getElementById(mName+".msg").style.visibility="hidden";document.getElementById(mName+".input").style.display="none";document.getElementById(mName+".okbt").style.display="none";document.getElementById(mName+".cancelbt").style.display="none"});self.getDOMElement().appendChild(mCancelBtElement);self.getDOMElement().className="BoxPanel";self.getStyle().setCSS({position:"fixed",top:"25%",left:"50%"});self.getStyle().setCSS({zIndex:"99999",visibility:"hidden"});self.getStyle().setCSS({marginLeft:"-250px",width:"500px"});self.getStyle().setCSS({background:"lightgray"});self.getStyle().setCSS({borderWidth:"1px"});self.getStyle().setCSS({borderStyle:"solid"});self.getStyle().setCSS({borderColor:"red"});self.getStyle().setCSS({overflow:"hidden",wordWrap:"break-word"});self.setDraggable(true);return self};var EJSS_INTERFACE=EJSS_INTERFACE||{};EJSS_INTERFACE.Button={registerProperties:function(element,controller){EJSS_INTERFACE.Element.registerProperties(element,controller);controller.registerProperty("Text",element.setText);controller.registerProperty("Disabled",element.setDisabled);controller.registerProperty("ImageUrl",element.setImageUrl);controller.registerAction("OnClick");controller.registerAction("OnPress");controller.registerAction("OnRelease")}};EJSS_INTERFACE.button=function(mName){var self=EJSS_INTERFACE.element(mName);var mUrl="";var mText="";self.setDisabled=function(disabled){self.getDOMElement().disabled=disabled};self.getDisabled=function(){return self.getDOMElement().disabled};self.setText=function(text){if(mText==text)return;mText=text;applyChange()};self.getText=function(){return mText};self.setImageUrl=function(url){var newUrl=self.getResourcePath(url);if(newUrl==mUrl)return;mUrl=newUrl;applyChange()};function applyChange(){self.getDOMElement().innerHTML="";if(mUrl.length>0)self.getDOMElement().innerHTML='<img style="vertical-align:inherit;-webkit-touch-callout:none;user-select:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;" src="'+mUrl+'"/>';if(mText.length>0)self.getDOMElement().innerHTML+='<span style="white-space:pre;-webkit-touch-callout:none;user-select:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;vertical-align:inherit;">'+mText.toString()+"</span>"}self.getImageUrl=function(){return mUrl};self.registerProperties=function(controller){EJSS_INTERFACE.Button.registerProperties(self,controller)};var mElement=document.createElement("button");mElement.id=mName;mElement.style.verticalAlign="middle";mElement.style.webkitTouchCallout="none";document.body.appendChild(mElement);self.setDOMElement(mElement);self.getDOMElement().oncontextmenu=function(e){e.preventDefault();e.stopPropagation();return false};self.getDOMElement().onmousedown=function(e){var controller=self.getController();if(controller)controller.invokeAction("OnPress").reportInteractions();e.preventDefault();e.stopPropagation();return false};self.getDOMElement().addEventListener("touchstart",function(e){var controller=self.getController();if(controller)controller.invokeAction("OnPress").reportInteractions();e.preventDefault();e.stopPropagation();return false});self.getDOMElement().onmouseup=function(e){var controller=self.getController();if(controller){controller.invokeAction("OnRelease");controller.invokeAction("OnClick").reportInteractions()}e.preventDefault();e.stopPropagation();return false};self.getDOMElement().addEventListener("touchend",function(e){var controller=self.getController();if(controller){controller.invokeAction("OnRelease");controller.invokeAction("OnClick").reportInteractions()}e.preventDefault();e.stopPropagation();return false});return self};var EJSS_INTERFACE=EJSS_INTERFACE||{};EJSS_INTERFACE.Canvas={registerProperties:function(element,controller){EJSS_INTERFACE.Element.registerProperties(element,controller);controller.registerProperty("Height",element.setHeight);controller.registerProperty("Width",element.setWidth);controller.registerProperty("ImageData",element.setImageData);controller.registerProperty("Enabled",element.setEnabled,element.isEnabled);controller.registerAction("OnPress",element.getInteractionPoint);controller.registerAction("OnDrag",element.getInteractionPoint);controller.registerAction("OnRelease",element.getInteractionPoint);controller.registerAction("OnEnter",element.getInteractionPoint);controller.registerAction("OnExit",element.getInteractionPoint);controller.registerAction("OnMove",element.getInteractionPoint)}};EJSS_INTERFACE.canvas=function(mName){var self=EJSS_INTERFACE.element(mName);var mHeight=0;var mWidth=0;var mLastPoint=[0,0];var mImageData;var mDragging=false;var mEnabled;self.render=function(){if(mImageData)mContext.putImageData(mImageData,0,0)};self.setImageData=function(data){if(!mImageData)mImageData=mContext.createImageData(mWidth,mHeight);if(data.data)data=data.data;for(var i=0;i<data.length;i++)mImageData.data[i]=data[i]};self.clear=function(){mContext.clearRect(0,0,mWidth,mHeight)};self.setWidth=function(width){var element=self.getDOMElement();if(mWidth!=width){mWidth=width;if(typeof width==="string"&&width.indexOf("%")!=-1&&element.parentNode&&element.parentNode.offsetWidth){width=element.parentNode.offsetWidth*parseFloat(width)/100}else if(typeof width==="string"){width=parseFloat(width)}if(typeof width==="number"){element.setAttribute("width",width)}return true}return false};self.getWidth=function(){var element=self.getDOMElement();if(typeof mWidth==="string"&&mWidth.indexOf("%")!=-1&&element.parentNode&&element.parentNode.offsetWidth){var value=element.parentNode.offsetWidth*parseFloat(mWidth)/100;if(typeof value==="number"){var orig=element.getAttribute("width");if(value!=orig)element.setAttribute("width",value)}}return mWidth};self.setHeight=function(height){var element=self.getDOMElement();if(mHeight!=height){mHeight=height;if(typeof height==="string"&&height.indexOf("%")!=-1&&element.parentNode&&element.parentNode.offsetHeight){height=element.parentNode.offsetHeight*parseFloat(height)/100}self.getDOMElement().setAttribute("height",height);return true}return false};self.getHeight=function(){var element=self.getDOMElement();if(typeof mHeight==="string"&&mHeight.indexOf("%")!=-1&&element.parentNode&&element.parentNode.offsetHeight){value=element.parentNode.offsetHeight*parseFloat(mHeight)/100;if(typeof value==="number"){var orig=element.getAttribute("height");if(value!=orig)element.setAttribute("height",value)}}return mHeight};self.getContext=function(){return mContext};self.registerProperties=function(controller){EJSS_INTERFACE.Canvas.registerProperties(self,controller)};self.setEnabled=function(enabled){mEnabled=enabled;var element=self.getDOMElement();if(mEnabled){element.onmousedown=handlerOnPress;element.onmouseup=handlerOnRelease;element.onmouseover=handlerOnEnter;element.onmouseout=handlerOnExit;element.onmousemove=handlerOnMove;element.addEventListener("touchstart",handlerOnPress,false);element.addEventListener("touchend",handlerOnRelease,false);element.addEventListener("touchmove",handlerOnMove,false)}else{element.onmousedown=undefined;element.onmouseup=undefined;element.onmouseover=undefined;element.onmouseout=undefined;element.onmousemove=undefined;element.removeEventListener("touchstart",handlerOnPress);element.removeEventListener("touchend",handlerOnRelease);element.removeEventListener("touchmove",handlerOnMove)}};self.isEnabled=function(){return mEnabled};self.getInteractionPoint=self.getMousePosition=function(){return mLastPoint};function getLastEventLocation(e){var pos=EJSS_GRAPHICS.CanvasGraphics.getOffsetRect(self);var locations=[];if(typeof e.changedTouches!="undefined"){for(var i=0;i<e.changedTouches.length;i++){locations[i]=[];locations[i][0]=e.changedTouches[i].pageX-window.pageXOffset-pos.left;locations[i][1]=e.changedTouches[i].pageY-window.pageYOffset-pos.top}}else{locations[0]=[];locations[0][0]=(e.clientX||e.x)-pos.left;locations[0][1]=(e.clientY||e.y)-pos.top}return locations[0]}function handlerOnPress(e){e.preventDefault();var controller=self.getController();if(controller){mLastPoint=getLastEventLocation(e);controller.invokeAction("OnPress").reportInteractions()}mDragging=true;return false}function handlerOnRelease(e){e.preventDefault();var controller=self.getController();if(mDragging&&controller){mLastPoint=getLastEventLocation(e);controller.invokeAction("OnRelease").reportInteractions()}mDragging=false;return false}function handlerOnEnter(e){e.preventDefault();var controller=self.getController();mDragging=false;if(controller){mLastPoint=getLastEventLocation(e);controller.invokeAction("OnEnter").reportInteractions()}return false}function handlerOnExit(e){e.preventDefault();var controller=self.getController();mDragging=false;if(controller){mLastPoint=getLastEventLocation(e);controller.invokeAction("OnExit").reportInteractions()}return false}function handlerOnMove(e){e.preventDefault();var controller=self.getController();if(controller){mLastPoint=getLastEventLocation(e);if(mDragging)controller.invokeAction("OnDrag").reportInteractions();else controller.invokeAction("OnMove").reportInteractions()}return false}var mElement=document.createElement("canvas");mElement.setAttribute("id",mName);mElement.style.overflow="hidden";var mContext=mElement.getContext("2d");document.body.appendChild(mElement);self.setDOMElement(mElement);self.setEnabled(true);self.setWidth(500);self.setHeight(500);return self};var EJSS_INTERFACE=EJSS_INTERFACE||{};EJSS_INTERFACE.CheckBox={OFF:false,ON:true,registerProperties:function(element,controller){EJSS_INTERFACE.Element.registerProperties(element,controller);controller.registerProperty("Text",element.setText);controller.registerProperty("ImageUrl",element.setImageUrl);controller.registerProperty("TextOn",element.setTextOn);controller.registerProperty("ImageOnUrl",element.setImageOnUrl);controller.registerProperty("TextOff",element.setTextOff);controller.registerProperty("ImageOffUrl",element.setImageOffUrl);controller.registerProperty("Checked",element.setChecked,element.getChecked);controller.registerProperty("Value",element.setValue,element.getValue);controller.registerAction("OnChange",element.getChecked);controller.registerAction("OnCheckOn");controller.registerAction("OnCheckOff")}};EJSS_INTERFACE.checkBox=function(mName){var self=EJSS_INTERFACE.element(mName);var mUrl=new Image;var mUrlOn=new Image;var mUrlOff=new Image;var mText="";var mTextOn="";var mTextOff="";self.setText=function(text){mText=text;applyChange()};self.setImageUrl=function(url){mUrl.src=self.getResourcePath(url);applyChange()};self.setTextOff=function(text){mTextOff=text;applyChange()};self.getTextOff=function(){return mTextOff};self.setImageOffUrl=function(url){mUrlOff.src=self.getResourcePath(url);applyChange()};self.getImageUrlOff=function(){return mUrlOff.src};self.setTextOn=function(text){mTextOn=text;applyChange()};self.getTextOn=function(){return mTextOn};self.setImageOnUrl=function(url){mUrlOn.src=self.getResourcePath(url);applyChange()};self.getImageUrlOn=function(){return mUrlOn.src};self.setChecked=function(state){if(mCBElement.checked!=state){mCBElement.checked=state;applyChange()}};self.getChecked=function(){return mCBElement.checked};self.setValue=function(value){mCBElement.value=value};self.getValue=function(){return mCBElement.value};function applyChange(){mLBElement.innerHTML="";if(mCBElement.checked){if(mUrlOn.src.length>0)mLBElement.appendChild(mUrlOn);else if(mTextOn.length>0)mLBElement.innerHTML=mTextOn.toString();else if(mUrl.src.length>0)mLBElement.appendChild(mUrl);else if(mText.length>0)mLBElement.innerHTML=mText.toString()}else{if(mUrlOff.src.length>0)mLBElement.appendChild(mUrlOff);else if(mTextOff.length>0)mLBElement.innerHTML=mTextOff.toString();else if(mUrl.src.length>0)mLBElement.appendChild(mUrl);else if(mText.length>0)mLBElement.innerHTML=mText.toString()}}self.registerProperties=function(controller){EJSS_INTERFACE.CheckBox.registerProperties(self,controller)};var mElement=document.createElement("fieldset");mElement.id=mName;mElement.style.border=0;mElement.style.display="inline-block";document.body.appendChild(mElement);self.setDOMElement(mElement);var mCBElement=document.createElement("input");mCBElement.id=mName+".checkbox";mCBElement.type="checkbox"
;mElement.appendChild(mCBElement);mCBElement.onchange=function(){applyChange();var controller=self.getController();if(controller){controller.propertiesChanged("Checked");controller.invokeAction("OnChange");if(mCBElement.checked)controller.invokeAction("OnCheckOn");else controller.invokeAction("OnCheckOff");controller.reportInteractions()}};mCBElement.ontouchend=function(e){e.stopPropagation()};mCBElement.onmouseup=function(e){e.stopPropagation()};var mLBElement=document.createElement("label");mLBElement.id=mName+".label";mLBElement.style.display="inline-block";mElement.appendChild(mLBElement);return self};var EJSS_INTERFACE=EJSS_INTERFACE||{};EJSS_INTERFACE.ComboBox={registerProperties:function(element,controller){EJSS_INTERFACE.Element.registerProperties(element,controller);controller.registerProperty("Options",element.setOptions,element.getOptions);controller.registerProperty("SelectedOptions",element.setSelectedOptions,element.getSelectedOptions);controller.registerProperty("Multiple",element.setMultiple);controller.registerProperty("Size",element.setSize);controller.registerAction("OnChange");controller.registerAction("OnFocus")}};EJSS_INTERFACE.comboBox=function(mName){var self=EJSS_INTERFACE.element(mName);var mOptions=[];self.registerProperties=function(controller){EJSS_INTERFACE.ComboBox.registerProperties(self,controller)};self.setSize=function(size){self.getDOMElement().size=size};self.getSize=function(){return self.getDOMElement().size};self.setMultiple=function(multiple){self.getDOMElement().multiple=multiple};self.getMultiple=function(){return self.getDOMElement().multiple};self.setSelectedOptions=function(options){var dom=self.getDOMElement();for(var i=0;i<dom.options.length;i++){dom.options[i].selected=false;for(var j=0;j<options.length;j++){if(dom.options[i].value==options[j]){dom.options[i].selected=true;break}}}};self.getSelectedOptions=function(){var mSelectedOptions=[];var dom=self.getDOMElement();for(var j=0,i=0;i<dom.options.length;i++){if(dom.options[i].selected)mSelectedOptions[j++]=dom.options[i].value}return mSelectedOptions};self.getSelectedOptionsIndexes=function(){var mSelectedOptionsIs=[];var dom=self.getDOMElement();for(var j=0,i=0;i<dom.options.length;i++){if(dom.options[i].selected)mSelectedOptionsIs[j++]=i}return mSelectedOptionsIs};self.setOptions=function(values){if(EJSS_TOOLS.compareArrays(mOptions,values))return;mOptions=[];var selected=self.getSelectedOptions();var dom=self.getDOMElement();dom.innerHTML="";for(var i=0;i<values.length;i++){var option=document.createElement("option");option.setAttribute("value",values[i]);option.innerHTML=values[i];dom.appendChild(option);mOptions[i]=values[i]}self.setSelectedOptions(selected)};self.getOptions=function(){var copyOptions=[];var dom=self.getDOMElement();for(var i=0;i<dom.options.length;i++){copyOptions[i]=dom.options[i].value}return copyOptions};self.setEditable=function(editable){self.getDOMElement().readOnly=!editable};self.getEditable=function(){return!self.getDOMElement().readOnly};var mElement=document.createElement("select");mElement.id=mName;document.body.appendChild(mElement);self.setDOMElement(mElement);self.getDOMElement().onfocus=function(){var controller=self.getController();self.getStyle().setBackgroundColor("white");if(controller){controller.propertiesChanged("Options");controller.invokeAction("OnFocus");controller.reportInteractions()}};self.getDOMElement().onchange=function(){var controller=self.getController();self.getStyle().setBackgroundColor("white");if(controller){controller.propertiesChanged("SelectedOptions");controller.invokeAction("OnChange");controller.reportInteractions()}};self.getDOMElement().onkeydown=function(){self.getStyle().setBackgroundColor("yellow")};self.getDOMElement().ontouchend=function(e){e.stopPropagation()};self.getDOMElement().onmouseup=function(e){e.stopPropagation()};return self};var EJSS_INTERFACE=EJSS_INTERFACE||{};EJSS_INTERFACE.DataTable={};EJSS_INTERFACE.dataTable=function(mName){};var EJSS_INTERFACE=EJSS_INTERFACE||{};EJSS_INTERFACE.Element={registerProperties:function(element,controller){element.setController(controller);controller.registerProperty("Tooltip",element.setTitle);controller.registerProperty("Foreground",element.getStyle().setColor);controller.registerProperty("Background",element.getStyle().setBackgroundColor);controller.registerProperty("BackgroundImage",element.getStyle().setBackgroundImage);controller.registerProperty("BorderWidth",element.getStyle().setBorderWidth);controller.registerProperty("BorderColor",element.getStyle().setBorderColor);controller.registerProperty("BorderStyle",element.getStyle().setBorderStyle);controller.registerProperty("Padding",element.getStyle().setPadding);controller.registerProperty("Width",element.getStyle().setWidth,element.getStyle().getWidth);controller.registerProperty("Height",element.getStyle().setHeight,element.getStyle().getHeight);controller.registerProperty("LineHeight",element.getStyle().setLineHeight,element.getStyle().getLineHeight);controller.registerProperty("TextAlign",element.getStyle().setTextAlign);controller.registerProperty("VerticalAlign",element.getStyle().setVerticalAlign);controller.registerProperty("Visibility",element.getStyle().setVisibility);controller.registerProperty("Display",element.getStyle().setDisplay);controller.registerProperty("Disabled",element.setDisabled);controller.registerProperty("Float",element.getStyle().setFloat);controller.registerProperty("Position",element.getStyle().setPosition);controller.registerProperty("Left",element.getStyle().setLeft);controller.registerProperty("Top",element.getStyle().setTop);controller.registerProperty("Bottom",element.getStyle().setBottom);controller.registerProperty("Overflow",element.getStyle().setOverflow);controller.registerProperty("BoxShadow",element.getStyle().setShadow);controller.registerProperty("Margin",element.getStyle().setMargin);controller.registerProperty("Parent",element.setParent);controller.registerProperty("ClassName",element.setClassName);controller.registerProperty("CSS",element.getStyle().setCSS);controller.registerProperty("Font",element.getStyle().setFont);controller.registerProperty("FontFamily",element.getStyle().setFontFamily);controller.registerProperty("FontSize",element.getStyle().setFontSize);controller.registerProperty("LetterSpacing",element.getStyle().setLetterSpacing);controller.registerProperty("OutlineColor",element.getStyle().setOutlineColor);controller.registerProperty("FontWeight",element.getStyle().setFontWeight);controller.registerProperty("FillColor",element.getStyle().setFillColor);controller.registerProperty("FontStyle",element.getStyle().setFontStyle);controller.registerProperty("Transform",element.getStyle().setTransform);controller.registerProperty("WhiteSpace",element.getStyle().setWhiteSpace)}};EJSS_INTERFACE.element=function(mName){var self={};var mDOMElement;var mParent;var mStyle=EJSS_INTERFACE.style(mName);var mController=null;self.getDOMElement=function(){return mDOMElement};self.setDOMElement=function(element){mDOMElement=element};self.setParent=function(parent){mParent=parent;if(typeof parent=="string"){var domObject=document.getElementById(parent);domObject.appendChild(self.getDOMElement())}else if(parent.getDOMElement){parent.appendChild(self)}else{parent.appendChild(self.getDOMElement())}};self.getParent=function(){return mParent};self.getName=function(){return mName};self.getResourcePath=function(filename){return filename};self.setClassName=function(name){self.getDOMElement().className=name};self._23Name=function(){return self.getDOMElement().className};self.setDisabled=function(disabled){self.getDOMElement().disabled=disabled};self.getDisabled=function(){return self.getDOMElement().disabled};self.setTitle=function(title){self.getDOMElement().title=title};self.getTitle=function(){return self.getDOMElement().title};self.getStyle=function(){return mStyle};self.getController=function(){return mController};self.setController=function(controller){mController=controller};self.registerProperties=function(controller){EJSS_INTERFACE.Element.registerProperties(self,controller)};return self};var EJSS_INTERFACE=EJSS_INTERFACE||{};EJSS_INTERFACE.FileUpload={registerProperties:function(element,controller){EJSS_INTERFACE.Element.registerProperties(element,controller);controller.registerProperty("Accept",element.setAccept,element.getAccpet);controller.registerProperty("Multiple",element.setMultiple,element.getMultiple);controller.registerAction("OnChange")}};EJSS_INTERFACE.fileUpload=function(mName){var self=EJSS_INTERFACE.element(mName);var mTarget={};self.getValue=function(){return self.getDOMElement().value};self.getTarget=function(){return mTarget};self.getAccept=function(){return self.getDOMElement().accept};self.setAccept=function(accept){self.getDOMElement().accept=accept};self.getMultiple=function(){return self.getDOMElement().multiple};self.setMultiple=function(multiple){self.getDOMElement().multiple=multiple};self.registerProperties=function(controller){EJSS_INTERFACE.FileUpload.registerProperties(self,controller)};var mElement=document.createElement("input");mElement.id=mName;mElement.type="file";document.body.appendChild(mElement);self.setDOMElement(mElement);mElement.onchange=function(event){mTarget=event.target;var controller=self.getController();if(controller){controller.invokeAction("OnChange");controller.reportInteractions()}};return self};var EJSS_INTERFACE=EJSS_INTERFACE||{};EJSS_INTERFACE.FunctionField={registerProperties:function(element,controller){EJSS_INTERFACE.TextField.registerProperties(element,controller);controller.registerAction("OnError")}};EJSS_INTERFACE.functionField=function(mName){var self=EJSS_INTERFACE.textField(mName);var mParser=EJSS_DRAWING2D.functionsParser();var mExpression=mParser.parse("0");var mSuperSetValue=self.setValue;var mCurrentValue;var mParameters={};var mBackground=self.getStyle().getBackgroundColor();self.registerProperties=function(controller){EJSS_INTERFACE.FunctionField.registerProperties(self,controller)};self.setParameters=function(parameters){for(var param in parameters){mParameters[param]=parameters[param]}};self.parseValue=function(value){if(value){if(value!=mCurrentValue){try{mExpression=mParser.parse(value);self.getStyle().setBackgroundColor(mBackground)}catch(error){self.getController().invokeAction("OnError");console.log('FunctionField: Error parsing function "'+value+'" : '+error.message+"\n");self.getStyle().setBackgroundColor("red")}mCurrentValue=value}}else{mCurrentValue="0";mExpression=mParser.parse("0");self.getStyle().setBackgroundColor(mBackground)}};self.setValue=function(value){mSuperSetValue(value);self.parseValue(value)};self.evaluate=function(variablesValues){var vblevalue={};for(var param in mParameters){vblevalue[param]=mParameters[param]}for(var values in variablesValues){vblevalue[values]=variablesValues[values]}try{return mExpression.evaluate(vblevalue)}catch(error){self.getController().invokeAction("OnError");return NaN}};return self};var EJSS_INTERFACE=EJSS_INTERFACE||{};EJSS_INTERFACE.Html={};EJSS_INTERFACE.html=function(mName){};var EJSS_INTERFACE=EJSS_INTERFACE||{};EJSS_INTERFACE.Image={};EJSS_INTERFACE.image=function(mName){};var EJSS_INTERFACE=EJSS_INTERFACE||{};EJSS_INTERFACE.ImageAndTextButton={registerProperties:function(element,controller){EJSS_INTERFACE.Element.registerProperties(element,controller);controller.registerProperty("Text",element.setText);controller.registerProperty("ImageUrl",element.setImageUrl);controller.registerAction("OnClick")}};EJSS_INTERFACE.imageAndTextButton=function(mName){var self=EJSS_INTERFACE.element(mName);var mText="";var mUrl="";self.setText=function(text){mText=text.toString();self.getDOMElement().innerHTML=mUrl+mText};self.getText=function(){return mText};self.setImageUrl=function(url){mUrl='<img src="'+self.getResourcePath(url)+'"/>';self.getDOMElement().innerHTML=mUrl+mText};self.getImageUrl=function(){return mUrl};self.registerProperties=function(controller){EJSS_INTERFACE.ImageAndTextButton.registerProperties(self,controller)};var mElement=document.createElement("button");mElement.id=mName;mElement.style.borderStyle="none";mElement.style.background="inherit";mElement.style.cursor="inherit";mElement.style.webkitBoxShadow="inset 0 0px 0 rgba(255,255,255,0),0 0px 0px rgba(0,0,0,0)";document.body.appendChild(mElement);self.setDOMElement(mElement);self.getDOMElement().onclick=function(e){var controller=self.getController();if(controller)controller.invokeAction("OnClick").reportInteractions();e.preventDefault();e.stopPropagation();return false};return self};var EJSS_INTERFACE=EJSS_INTERFACE||{};EJSS_INTERFACE.Label={};EJSS_INTERFACE.label=function(mName){};var EJSS_INTERFACE=EJSS_INTERFACE||{};EJSS_INTERFACE.MathML={};EJSS_INTERFACE.mathML=function(mName){};var EJSS_INTERFACE=EJSS_INTERFACE||{};EJSS_INTERFACE.Media={};EJSS_INTERFACE.media=function(mName){};var EJSS_INTERFACE=EJSS_INTERFACE||{};EJSS_INTERFACE.MotionJPEG={};EJSS_INTERFACE.motionJPEG=function(mName){};var EJSS_INTERFACE=EJSS_INTERFACE||{};EJSS_INTERFACE.NumberField={};EJSS_INTERFACE.numberField=function(mName){};var EJSS_INTERFACE=EJSS_INTERFACE||{};EJSS_INTERFACE.Panel={registerProperties:function(element,controller){EJSS_INTERFACE.Element.registerProperties(element,controller);controller.registerProperty("Html",element.setHtml,element.getHtml);controller.registerAction("OnClick");controller.registerAction("OnPress");controller.registerAction("OnRelease");controller.registerAction("OnMove")}};EJSS_INTERFACE.panel=function(mName){var self=EJSS_INTERFACE.element(mName);self.appendChild=function(element){var child=element.getDOMElement();self.getDOMElement().appendChild(child)};self.removeChild=function(element){var child=element.getDOMElement();self.getDOMElement().removeChild(child)};self.insertBefore=function(newele,refele){var newchild=newele.getDOMElement();var refchild=refele.getDOMElement();self.getDOMElement().insertBefore(newchild,refchild)};self.setHtml=function(value){self.getDOMElement().innerHTML=value};self.getHtml=function(){return self.getDOMElement().innerHTML};self.registerProperties=function(controller){EJSS_INTERFACE.Panel.registerProperties(self,controller)};var mElement=document.createElement("div");mElement.id=mName;mElement.contenteditable=true;document.body.appendChild(mElement);self.setDOMElement(mElement);self.getStyle().setPadding("0px");self.getStyle().setMargin("0px");self.getStyle().setTextAlign("TEXTA_CENTER");self.getStyle().setCSS({display:"block","margin-left":"auto","margin-right":"auto"});self.getDOMElement().addEventListener("touchstart",function(event){var ips=document.getElementsByTagName("input");for(var i=0;ips.length>i;i++){ips[i].disabled=false}});self.getDOMElement().addEventListener("mousedown",function(e){var controller=self.getController();if(controller)controller.invokeAction("OnPress").reportInteractions()});self.getDOMElement().addEventListener("touchstart",function(e){var controller=self.getController();if(controller)controller.invokeAction("OnPress").reportInteractions()});self.getDOMElement().addEventListener("mouseup",function(e){var controller=self.getController();if(controller){controller.invokeAction("OnRelease");controller.invokeAction("OnClick").reportInteractions()}});self.getDOMElement().addEventListener("touchend",function(e){var controller=self.getController();if(controller){controller.invokeAction("OnRelease");controller.invokeAction("OnClick").reportInteractions()}});self.getDOMElement().addEventListener("mousemove",function(e){var controller=self.getController();if(controller){controller.invokeAction("OnMove").reportInteractions()}});self.getDOMElement().addEventListener("touchmove",function(e){var controller=self.getController();if(controller){controller.invokeAction("OnMove").reportInteractions()}});return self};var EJSS_INTERFACE=EJSS_INTERFACE||{};EJSS_INTERFACE.PasswordField={};EJSS_INTERFACE.passwordField=function(mName){};var EJSS_INTERFACE=EJSS_INTERFACE||{};EJSS_INTERFACE.RadioButton={};EJSS_INTERFACE.radioButton=function(mName){};var EJSS_INTERFACE=EJSS_INTERFACE||{};EJSS_INTERFACE.Separator={};EJSS_INTERFACE.separator=function(mName){};var EJSS_INTERFACE=EJSS_INTERFACE||{};EJSS_INTERFACE.Slider={PRECISION:1e5,registerProperties:function(element,controller){EJSS_INTERFACE.Element.registerProperties(element,controller);controller.registerProperty("Value",element.setValue,element.getValue);controller.registerProperty("Minimum",element.setMin);controller.registerProperty("Maximum",element.setMax);controller.registerProperty("Step",element.setStep);controller.registerProperty("TextWidth",element.setTextWidth);controller.registerProperty("ShowText",element.setShowText);controller.registerProperty("Format",element.setFormat);controller.registerProperty("Disabled",element.setDisabled);controller.registerProperty("LabelCSS",element.setLabelCSS);controller.registerProperty("RangeCSS",element.setRangeCSS);controller.registerAction("OnChange",element.getValue);controller.registerAction("OnRelease",element.getValue)}};EJSS_INTERFACE.slider=function(mName){var self=EJSS_INTERFACE.element(mName);var mShowText=false;var mDigits=3;var mStepSetByUser=false;self.registerProperties=function(controller){EJSS_INTERFACE.Slider.registerProperties(self,controller)};self.setValue=function(value){if(typeof value=="undefined")mSLElement.value="value undefined";else{if(!isNaN(parseFloat(value))&&isFinite(value)){mSLElement.value=parseFloat(value);if(mShowText)mLBElement.innerHTML=parseFloat(value).toFixed(mDigits)}}};self.getValue=function(){var value=mSLElement.value;if(!isNaN(parseFloat(value))&&isFinite(value)){return parseFloat(value)}return value};self.setFormat=function(format){var index=format.indexOf(".");var digits=0;if(index>=0)digits=Number(format.length-index-1);if(mDigits!=digits){mDigits=digits;self.setValue(self.getValue())}};self.setStep=function(value){if(isNaN(value)){mStepSetByUser=false;mSLElement.step=(mSLElement.max-mSLElement.min)/EJSS_INTERFACE.Slider.PRECISION}else{mStepSetByUser=true;mSLElement.step=value}};self.getStep=function(){return mSLElement.step};self.setMax=function(value){mSLElement.max=value;if(!mStepSetByUser)mSLElement.step=(mSLElement.max-mSLElement.min)/EJSS_INTERFACE.Slider.PRECISION};self.getMax=function(){return mSLElement.max};self.setMin=function(value){mSLElement.min=value;if(!mStepSetByUser)mSLElement.step=(mSLElement.max-mSLElement.min)/EJSS_INTERFACE.Slider.PRECISION};self.getMin=function(){return mSLElement.min};self.setShowText=function(value){mShowText=value;if(mShowText)mLBElement.innerHTML=""};self.getShowText=function(){return mShowText};self.setTextWidth=function(value){mLBElement.style.width=value};self.getTextWidth=function(value){return mLBElement.style.width};self.setDisabled=function(disabled){mSLElement.disabled=disabled};self.getDisabled=function(){return mSLElement.disabled};self.setLabelCSS=function(css){EJSS_INTERFACE.Style.setCSS(mLBElement,css)};self.setRangeCSS=function(css){EJSS_INTERFACE.Style.setCSS(mSLElement,css)};var mElement=document.createElement("div");mElement.id=mName;mElement.style.display="inline-block";mElement.style.overflow="hidden";mElement.style.textAlign="left";mElement.style.verticalAlign="middle";mElement.style.webkitTouchCallout="none";mElement.style.webkitUserSelect="none";mElement.style.userSelect="none";document.body.appendChild(mElement);self.setDOMElement(mElement);var mLBElement=document.createElement("label");mLBElement.id=mName+".label";mLBElement.style.float="left";mElement.appendChild(mLBElement);var mDIElement=document.createElement("div");mDIElement.id=mName+".div2";mDIElement.style.overflow="hidden";mElement.appendChild(mDIElement);var mSLElement=document.createElement("input");mSLElement.style.verticalAlign="middle";mSLElement.style.width="98%";mSLElement.style.height="98%";mSLElement.type="range";mSLElement.id=mName+".slider";mSLElement.value=0;mDIElement.appendChild(mSLElement);mSLElement.oninput=function(){var controller=self.getController();if(controller){controller.propertiesChanged("Value");controller.invokeAction("OnChange");controller.reportInteractions()}return false};mSLElement.onmouseup=function(e){var controller=self.getController();if(controller){controller.invokeAction("OnRelease");controller.reportInteractions()}e.stopPropagation()};mSLElement.ontouchend=function(e){var controller=self.getController();if(controller){controller.invokeAction("OnRelease");controller.reportInteractions()}e.stopPropagation()};return self};var EJSS_INTERFACE=EJSS_INTERFACE||{};EJSS_INTERFACE.Style={BORDER_SOLID:"solid",BORDER_DOTTED:"dotted",BORDER_DASHED:"dashed",TEXTA_LEFT:"left",TEXTA_RIGHT:"right",TEXTA_CENTER:"center",TEXTA_JUSTIFY:"justify",VISIB_VISIBLE:"visible",VISIB_HIDDEN:"hidden",FLOAT_LEFT:"left",FLOAT_RIGHT:"right",FLOAT_NONE:"none",FLOAT_CENTER:"none",POSITION_STATIC:"static",POSITION_ABSOLUTE:"absolute",POSITION_FIXED:"fixed",POSITION_RELATIVE:"relative",POSITION_INHERIT:"inherit",OVERFLOW_VISIBLE:"visible",OVERFLOW_HIDDEN:"hidden",OVERFLOW_SCROLL:"scroll",OVERFLOW_AUTO:"auto",setCSS:function(element,css){var rdashAlpha=/-([\da-z])/gi;var fcamelCase=function(all,letter){return(letter+"").toUpperCase()};var style=element.style;if(typeof css!=="object"){var cssvals=css.trim().split("{");if(cssvals[0]&&cssvals[0].length>0){var classname=cssvals[0].trim();var x,classes=document.styleSheets[0].rules||document.styleSheets[0].cssRules;for(x=0;x<classes.length;x++){if(classes[x].selectorText==classname)break}var classesCss=classes[x].cssText?classes[x].cssText:classes[x].style.cssText;classesCss=classesCss.match(/{.*}/g)[0];var css_rows=classesCss.slice(1,classesCss.length-2).split(";");for(elem in css_rows){var elem_parts=css_rows[elem].split(":");if(elem_parts.length==2){var property_name=elem_parts[0].trim();var property_value=elem_parts[1].trim();var camelCase=property_name.replace(rdashAlpha,fcamelCase);style[camelCase]=property_value}}}if(cssvals[1]){var addition=cssvals[1].trim();var css_rows=addition.slice(0,addition.length-2).split(";");for(elem in css_rows){var elem_parts=css_rows[elem].split(":");if(elem_parts.length==2){var property_name=elem_parts[0].trim();var property_value=elem_parts[1].trim();var camelCase=property_name.replace(rdashAlpha,fcamelCase);style[camelCase]=property_value}}}}else{for(var prop in css){var camelCase=prop.replace(rdashAlpha,fcamelCase);style[camelCase]=css[prop]}}}};EJSS_INTERFACE.style=function(mName){var Style=EJSS_INTERFACE.Style;var self={};var mBorderColor="white";var mBorderWidth=0;var mBorderStyle=Style.BORDER_SOLID;self.setCSS=function(css){Style.setCSS(document.getElementById(mName),css)};self.setVisibility=function(visible){document.getElementById(mName).style.visibility=visible?"visible":"hidden"};self.getVisibility=function(){return document.getElementById(mName).style.visibility=="visible"};self.setVerticalAlign=function(value){document.getElementById(mName).style.verticalAlign=value};self.getVerticalAlign=function(){return document.getElementById(mName).style.verticalAlign};self.setTextAlign=function(value){if(value.substring(0,6)=="TEXTA_")value=Style[value.toUpperCase()];document.getElementById(mName).style.textAlign=value};self.getTextAlign=function(){return document.getElementById(mName).style.textAlign};self.setLineHeight=function(value){if(typeof value!=="string")value=value+"px";document.getElementById(mName).style.lineHeight=value};self.getLineHeight=function(){return document.getElementById(mName).style.lineHeight};self.setHeight=function(value){if(typeof value!=="string")value=value+"px";document.getElementById(mName).style.height=value};self.getHeight=function(){return document.getElementById(mName).style.height};self.setWidth=function(value){if(typeof value!=="string")value=value+"px";document.getElementById(mName).style.width=value};self.getWidth=function(){return document.getElementById(mName).style.width};self.setOverflow=function(overflow){if(overflow.substring(0,6)=="OVERFL")overflow=Style[overflow.toUpperCase()];document.getElementById(mName).style.overflow=overflow};self.getOverflow=function(){return document.getElementById(mName).style.overflow};self.setPosition=function(position){if(position.substring(0,6)=="POSITI")position=Style[position.toUpperCase()];document.getElementById(mName).style.position=position};self.getPosition=function(){return document.getElementById(mName).style.position};self.setFloat=function(floatstyle){if(floatstyle.substring(0,6)=="FLOAT_")floatstyle=Style[floatstyle.toUpperCase()];document.getElementById(mName).style.float=floatstyle};self.getFloat=function(){return document.getElementById(mName).style.float};self.setDisplay=function(displayStyle){document.getElementById(mName).style.display=displayStyle};self.getDisplay=function(){return document.getElementById(mName).style.display};self.setTop=function(top){document.getElementById(mName).style.top=top};self.getTop=function(){return document.getElementById(mName).style.top};self.setBottom=function(bottom){document.getElementById(mName).style.bottom=bottom};self.getBottom=function(){return document.getElementById(mName).style.bottom};self.setLeft=function(left){document.getElementById(mName).style.left=left};self.getLeft=function(){return document.getElementById(mName).style.left};self.setBorderStyle=function(style){if(style.substring(0,6)=="BORDER")style=Style[style.toUpperCase()];mBorderStyle=style;document.getElementById(mName).style.border=mBorderWidth+"px "+mBorderStyle+" "+mBorderColor};self.getBorderStyle=function(){return mBorderStyle};self.setBorderWidth=function(width){mBorderWidth=width;document.getElementById(mName).style.border=mBorderWidth+"px "+mBorderStyle+" "+mBorderColor};self.getBorderWidth=function(){return mBorderWidth};self.setBorderColor=function(color){if(typeof color!=="string")color=EJSS_TOOLS.DisplayColors.getLineColor(color);mBorderColor=color;document.getElementById(mName).style.border=mBorderWidth+"px "+mBorderStyle+" "+mBorderColor};self.getBorderColor=function(){return mBorderColor};self.setPadding=function(padding){document.getElementById(mName).style.padding=padding};self.getPadding=function(){return document.getElementById(mName).style.padding};self.setShadow=function(shadow){if(shadow)document.getElementById(mName).style.boxShadow=shadow;else document.getElementById(mName).style.boxShadow=""};self.getShadow=function(){return document.getElementById(mName).style.boxShadow!=""};self.setMargin=function(margin){document.getElementById(mName).style.margin=margin};self.getMargin=function(){return document.getElementById(mName).style.margin};self.setBackgroundImage=function(url){document.getElementById(mName).style.backgroundImage="url("+url+")";document.getElementById(mName).style.backgroundSize="100% 100%"};self.getBackgroundImage=function(){return document.getElementById(mName).style.backgroundImage};self.setBackgroundColor=function(color){if(typeof color!=="string")color=EJSS_TOOLS.DisplayColors.getLineColor(color);document.getElementById(mName).style.backgroundColor=color};self.getBackgroundColor=function(){return document.getElementById(mName).style.backgroundColor};self.setColor=function(color){if(typeof color!=="string")color=EJSS_TOOLS.DisplayColors.getLineColor(color);document.getElementById(mName).style.color=color};self.getColor=function(){return document.getElementById(mName).style.color};self.getFont=function(){return document.getElementById(mName).style.font};self.setFont=function(recap){if(typeof recap!=="string"||recap.length<=0)return;var style=document.getElementById(mName).style;var params=recap.split(" ");style.fontStyle=params[0];style.fontWeight=params[1];var sizes=params[2].split("/");style.fontSize=sizes[0];if(sizes[1])style.lineHeight=sizes[1];if(params[3])style.fontFamily=recap.substring(recap.indexOf(params[3]))};self.setFontStyle=function(fontStyle){document.getElementById(mName).style.fontStyle=fontStyle};self.getFontStyle=function(){return document.getElementById(mName).style.fontStyle};self.setFontFamily=function(fontFamily){document.getElementById(mName).style.fontFamily=fontFamily};self.getFontFamily=function(){return document.getElementById(mName).style.fontFamily};self.setFontSize=function(fontSize){document.getElementById(mName).style.fontSize=fontSize};self.getFontSize=function(){return document.getElementById(mName).style.fontSize};self.setLetterSpacing=function(letterSpacing){document.getElementById(mName).style.letterSpacing=letterSpacing};self.getLetterSpacing=function(){return document.getElementById(mName).style.letterSpacing};self.setOutlineColor=function(lineColor){document.getElementById(mName).style.stroke=lineColor};self.getOutlineColor=function(){return document.getElementById(mName).style.stroke};self.setFontWeight=function(lineWidth){document.getElementById(mName).style.fontWeight=lineWidth};self.getFontWeight=function(){return document.getElementById(mName).style.fontWeight};self.setFillColor=function(fillColor){document.getElementById(mName).style.fill=fillColor};self.getFillColor=function(){return document.getElementById(mName).style.fill};self.setTransform=function(transform){document.getElementById(mName).style.transform=transform;document.getElementById(mName).style["-ms-transform"]=transform;document.getElementById(mName).style["-webkit-transform"]=transform};self.getTransform=function(){return document.getElementById(mName).style.transform};self.setWhiteSpace=function(whiteSpace){document.getElementById(mName).style.whiteSpace=whiteSpace};self.getWhiteSpace=function(){return document.getElementById(mName).style.whiteSpace};return self};var EJSS_INTERFACE=EJSS_INTERFACE||{};EJSS_INTERFACE.SvgGraphics={registerProperties:function(element,controller){EJSS_INTERFACE.Element.registerProperties(element,controller);controller.registerProperty("Height",element.setHeight);controller.registerProperty("Width",element.setWidth)}};EJSS_INTERFACE.svgGraphics=function(mName){var self=EJSS_INTERFACE.element(mName);var mHeight=0;var mWidth=0;self.setWidth=function(width){if(mWidth!=width){mWidth=width;var value=typeof mWidth==="string"&&mWidth.indexOf("%")!=-1?mWidth:parseFloat(mWidth);self.getDOMElement().setAttribute("width",value);return true}return false};self.getWidth=function(){return mWidth};self.setHeight=function(height){if(mHeight!=height){mHeight=height;self.getDOMElement().setAttribute("height",mHeight);return true}return false};self.getHeight=function(){return mHeight};self.registerProperties=function(controller){EJSS_INTERFACE.SvgGraphics.registerProperties(self,controller)};var mElement=document.createElementNS("http://www.w3.org/2000/svg","svg");mElement.setAttribute("id",mName);mElement.style.overflow="hidden";mElement.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:xlink","http://www.w3.org/1999/xlink");document.body.appendChild(mElement);self.setDOMElement(mElement);self.setWidth(500);self.setHeight(500);return self};var EJSS_INTERFACE=EJSS_INTERFACE||{};EJSS_INTERFACE.TabbedPanel={registerProperties:function(element,controller){EJSS_INTERFACE.Element.registerProperties(element,controller);controller.registerProperty("Titles",element.setTitles,element.getTitles);controller.registerProperty("Selected",element.setSelected,element.getSelected);controller.registerProperty("Font",element.setFont);controller.registerProperty("Foreground",element.setColor);controller.registerProperty("Background",element.setBackgroundColor);controller.registerProperty("FillColor",element.setFillColor)}};EJSS_INTERFACE.tabbedPanel=function(mName){var self=EJSS_INTERFACE.element(mName);var mTitles=[];var mSelected=0;var mBackground=null;self.appendChild=function(element){var child=element.getDOMElement();mDIVElement.appendChild(child);select()};self.removeChild=function(element){var child=element.getDOMElement();mDIVElement.removeChild(child);select()};self.insertBefore=function(newele,refele){var newchild=newele.getDOMElement();var refchild=refele.getDOMElement();mDIVElement.insertBefore(newchild,refchild);select()};self.getTitles=function(){return mTitles};self.setTitles=function(items){if(!EJSS_TOOLS.compareArrays(mTitles,items)){mTitles=items;updateTitles()}};self.getSelected=function(){return mSelected};self.setSelected=function(index){if(mSelected!=index){mSelected=index;select()}};self.registerProperties=function(controller){EJSS_INTERFACE.TabbedPanel.registerProperties(self,controller)};function updateTitles(){mTABElement.innerHTML="";for(var i=0;i<mTitles.length;i++){var title=mTitles[i];var mLIElement=document.createElement("li");mLIElement.className="_TabbedPanel.li";mLIElement.id=mName+".item";mTABElement.appendChild(mLIElement);mLIElement.style.background=mBackground?mBackground:self.getStyle().getBackgroundColor();mLIElement.onmouseover=function(){this.style.cursor="pointer"};mLIElement.onmouseout=function(){this.style.cursor="auto"};var mAElement=document.createElement("a");mAElement.className="_TabbedPanel.a";mAElement.id=mName+".item.a."+i;mAElement.innerHTML=title;mLIElement.appendChild(mAElement);mAElement.style.color=self.getStyle().getColor();mAElement.style.fontStyle=self.getStyle().getFontStyle();mAElement.style.fontWeight=self.getStyle().getFontWeight();mAElement.style.fontSize=self.getStyle().getFontSize();mAElement.style.fontFamily=self.getStyle().getFontFamily();mAElement.style.lineHeight=self.getStyle().getLineHeight();mAElement.onclick=function(){var parts=this.id.split(".");mSelected=parseInt(parts[parts.length-1]);select()};select()}}function select(){for(var j=0;j<mDIVElement.childNodes.length;j++){mDIVElement.childNodes[j].style.display="none"}if(mDIVElement.childNodes.length>mSelected)mDIVElement.childNodes[mSelected].style.display="block";for(var j=0;j<mTABElement.childNodes.length;j++){mTABElement.childNodes[j].firstChild.style.backgroundColor="transparent"}if(mTABElement.childNodes.length>mSelected)mTABElement.childNodes[mSelected].firstChild.style.backgroundColor=self.getStyle().getFillColor()}self.setFont=function(font){self.getStyle().setFont(font);updateTitles()};self.setFillColor=function(color){self.getStyle().setFillColor(color);select()};self.setBackgroundColor=function(color){mBackground=color;updateTitles()};self.setColor=function(color){self.getStyle().setColor(color);updateTitles()};var mElement=document.createElement("span");mElement.className="_TabbedPanel.span";mElement.id=mName;document.body.appendChild(mElement);self.setDOMElement(mElement);var mTABElement=document.createElement("ul");mTABElement.className="_TabbedPanel.ul";mTABElement.id=mName+".ul";mElement.appendChild(mTABElement);var mDIVElement=document.createElement("span");mDIVElement.id=mName+".divs";mElement.appendChild(mDIVElement);updateTitles();self.getStyle().setFillColor("#ccc");return self};var EJSS_INTERFACE=EJSS_INTERFACE||{};EJSS_INTERFACE.TextArea={};EJSS_INTERFACE.textArea=function(mName){};var EJSS_INTERFACE=EJSS_INTERFACE||{};EJSS_INTERFACE.TextField={registerProperties:function(element,controller){EJSS_INTERFACE.Element.registerProperties(element,controller);controller.registerProperty("Value",element.setValue,element.getValue);controller.registerProperty("Editable",element.setEditable);controller.registerProperty("Size",element.setSize);controller.registerAction("OnChange")}};EJSS_INTERFACE.textField=function(mName){var self=EJSS_INTERFACE.element(mName);var mEdition=false;var mTmp="";self.registerProperties=function(controller){EJSS_INTERFACE.TextField.registerProperties(self,controller)};self.enableEPub=function(){if(self.getDOMElement().disabled)self.getDOMElement().disabled=false};if(typeof _isEPub!=="undefined"&&_isEPub){self.render=function(){self.enableEPub()}}self.setValue=function(value){if(!mEdition){if(typeof value=="undefined")self.getDOMElement().value="value undefined";else{self.getDOMElement().value=value}}};self.getValue=function(){return self.getDOMElement().value};self.setEditable=function(editable){self.getDOMElement().readOnly=!editable;if(editable)self.getStyle().setBackgroundColor("white");else self.getStyle().setBackgroundColor("lightgrey")};self.getEditable=function(){return!self.getDOMElement().readOnly};self.setSize=function(value){self.getDOMElement().size=value};self.getSize=function(){return self.getDOMElement().size};function checkValue(){var value=self.getDOMElement().value;self.getStyle().setBackgroundColor("white");if(self.parseValue)self.parseValue(value);if(mTmp!=value){var controller=self.getController();if(controller){controller.propertiesChanged("Value");controller.invokeAction("OnChange");controller.reportInteractions()}}}var mElement=document.createElement("input");mElement.id=mName;mElement.type="text";document.body.appendChild(mElement);self.setDOMElement(mElement);self.getDOMElement().onkeydown=function(key){var dom=self.getDOMElement();if(!dom.readOnly){var ev=key||window.event;var charCode=ev.which?ev.which:ev.keyCode;if(charCode==13){mEdition=false;checkValue();mTmp=self.getDOMElement().value}else if(charCode==27){self.getDOMElement().value=mTmp}else{self.getStyle().setBackgroundColor("yellow");mEdition=true}}};self.getDOMElement().onfocus=function(dom){mTmp=self.getDOMElement().value};self.getDOMElement().onblur=function(dom){if(!dom.readOnly&&mEdition){checkValue();mEdition=false}};self.getDOMElement().ontouchend=function(e){e.stopPropagation()};self.getDOMElement().onmouseup=function(e){e.stopPropagation()};if(typeof _isEPub!=="undefined"&&_isEPub){self.getDOMElement().ontouchstart=function(event){if(self.getDOMElement().disabled)self.getDOMElement().disabled=false;self.getDOMElement().focus();event.stop()}}return self};var EJSS_INTERFACE=EJSS_INTERFACE||{};EJSS_INTERFACE.TwoStateButton={OFF:false,ON:true,registerProperties:function(element,controller){EJSS_INTERFACE.Element.registerProperties(element,controller);controller.registerProperty("TextOn",element.setTextOn);controller.registerProperty("ImageOnUrl",element.setImageUrlOn);controller.registerProperty("TextOff",element.setTextOff);controller.registerProperty("ImageOffUrl",element.setImageUrlOff);controller.registerProperty("State",element.setState,element.getState);controller.registerAction("OnClick");controller.registerAction("OffClick")}};EJSS_INTERFACE.twoStateButton=function(mName){var TSButton=EJSS_INTERFACE.TwoStateButton;var self=EJSS_INTERFACE.element(mName);var mUrlOn="";var mUrlOff="";var mTextOn="";var mTextOff="";var mState=-1;self.setTextOff=function(text){mTextOff=text;applyChange()};self.getTextOff=function(){return mTextOff};self.setImageUrlOff=function(url){var newUrl=self.getResourcePath(url);if(newUrl==mUrlOff)return;mUrlOff=newUrl;applyChange()};self.getImageUrlOff=function(){return mUrlOff};self.setTextOn=function(text){mTextOn=text;applyChange()};self.getTextOn=function(){return mTextOn};self.setImageUrlOn=function(url){var newUrl=self.getResourcePath(url);if(newUrl==mUrlOn)return;mUrlOn=newUrl;applyChange()};self.getImageUrlOn=function(){return mUrlOn};self.setState=function(state){if(typeof state=="string")state=TSButton[state.toUpperCase()];if(state!=mState){mState=state;applyChange()}};self.getState=function(){return mState};function applyChange(){self.getDOMElement().innerHTML="";if(mState){if(mUrlOn.length>0)self.getDOMElement().innerHTML='<img style="vertical-align:inherit;-webkit-touch-callout:none;user-select:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;" src="'+mUrlOn+'"/>';if(mTextOn.length>0)self.getDOMElement().innerHTML+='<span style="white-space:pre;vertical-align:inherit;-webkit-touch-callout:none;user-select:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;">'+mTextOn.toString()+"</span>"}else{if(mUrlOff.length>0)self.getDOMElement().innerHTML='<img style="vertical-align:inherit;-webkit-touch-callout:none;user-select:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;" src="'+mUrlOff+'"/>';if(mTextOff.length>0)self.getDOMElement().innerHTML+='<span style="white-space:pre;vertical-align:inherit;-webkit-touch-callout:none;user-select:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;">'+mTextOff.toString()+"</span>"}}self.registerProperties=function(controller){EJSS_INTERFACE.TwoStateButton.registerProperties(self,controller)};var mElement=document.createElement("button");mElement.id=mName;mElement.style.verticalAlign="middle";mElement.style.webkitTouchCallout="none";document.body.appendChild(mElement);self.setDOMElement(mElement);self.getDOMElement().oncontextmenu=function(e){e.preventDefault();e.stopPropagation();return false};function onClickListener(e){var state=self.getState();self.setState(!state);var controller=self.getController();if(controller){controller.propertiesChanged("State");if(state)controller.invokeAction("OnClick");else controller.invokeAction("OffClick");controller.reportInteractions()}e.stopPropagation();return false}self.getDOMElement().addEventListener("mouseup",onClickListener);self.getDOMElement().addEventListener("touchend",onClickListener);return self};var EJSS_INTERFACE=EJSS_INTERFACE||{};EJSS_INTERFACE.Video={};EJSS_INTERFACE.video=function(mName){};var EJSS_INTERFACE=EJSS_INTERFACE||{};EJSS_INTERFACE.WebGLCanvas={};EJSS_INTERFACE.webGLCanvas=function(mName){};var EJSS_INTERFACE=EJSS_INTERFACE||{};EJSS_INTERFACE.WrappedPanel={};EJSS_INTERFACE.wrappedPanel=function(mName){};var EJSS_CORE=EJSS_CORE||{};EJSS_CORE.Model={MODE_JAVA_STYLE:1,MODE_RESPECT_TIME:2,MODE_RESPECT_DELAY:3};EJSS_CORE.createAnimation=function(){var self={};var MINIMUM_DELAY=1;var SAVETEXT_Q="Choose a name for the file";var READFILE_Q="Select a file to read";var mDelay=MINIMUM_DELAY;var mStepsPerDisplay=1;var mAbortSPDLoop=false;var mShouldUpdateView=true;var mAutoplay=false;var mShouldBreak=false;var mLastTime=+new Date;var mIsPlaying=false;var mView=null;var mInitialRealTime=NaN;var mSleepTime=mDelay;var mExcededTime=0;var mMinimumDelay=10;var mCurrentTimeOut;var mRunTime;var mFocus=true;var mRunAlways=false;var mOnloadFunc;var mRunningMode=EJSS_CORE.Model.MODE_JAVA_STYLE;self.setView=function(view){mView=view;mView._12(function(){if(!mIsPlaying){if(mView._16(mRunCount,mRunTime,mIsPlaying)){self.automaticResetSolvers();self.update()}}})};self.getView=function(){return mView};self.serialize=function(){var encodedModel={};if(self._userSerialize)encodedModel=self._userSerialize();var encodedView=mView.serialize();var encoded={model:encodedModel,view:encodedView};return JSON.stringify(encoded,function(key,value){if(typeof value=="number"){if(isNaN(value))value="__NaN";else if(!isFinite(value))value="__Infinity"}return value})};self.unserialize=function(json){var encoded=JSON.parse(json,function(key,value){if(value=="__NaN")value=NaN;else if(value=="__Infinity")value=Infinity;return value});if(encoded.model){var encodedModel=encoded.model;if(self._userUnserialize)self._userUnserialize(encodedModel)}if(encoded.view){var encodedView=encoded.view;mView.unserialize(encodedView)}};var context_id;var user_id;var ejsapp_id;var moodle_upload_file;var moodle_send_file_list;self.sendCallback=function(){};self.setStatusParams=function(_context_id,_user_id,_ejsapp_id,_moodle_upload_file,_moodle_send_file_list,_moodle_callback){context_id=_context_id;user_id=_user_id;ejsapp_id=_ejsapp_id;moodle_upload_file=_moodle_upload_file;moodle_send_file_list=_moodle_send_file_list;if(_moodle_callback)self.sendCallback=_moodle_callback};self.sendSnapshot=function(svgpanel,user_file,callback_ok,callback_error){if(!moodle_upload_file)return;svgpanel.importGraphics(function(png){var http=new XMLHttpRequest;var params="user_file="+user_file+"&file="+encodeURIComponent(png)+"&type=png"+"&context_id="+context_id+"&user_id="+user_id+"&ejsapp_id="+ejsapp_id;http.open("POST",moodle_upload_file,true);http.setRequestHeader("Content-type","application/x-www-form-urlencoded");http.onreadystatechange=function(){if(http.readyState==4&&http.status==200){if(callback_ok)callback_ok()}else{if(callback_error)callback_error()}};http.send(params)})};self.sendState=function(user_file,callback_ok,callback_error){if(!moodle_upload_file)return;var json=self.serialize();var http=new XMLHttpRequest;var params="user_file="+user_file+"&file="+encodeURIComponent(json)+"&type=json"+"&context_id="+context_id+"&user_id="+user_id+"&ejsapp_id="+ejsapp_id;http.open("POST",moodle_upload_file,true);http.setRequestHeader("Content-type","application/x-www-form-urlencoded");http.onreadystatechange=function(){if(http.readyState==4&&http.status==200){if(callback_ok)callback_ok()}else{if(callback_error)callback_error()}};http.send(params)};self.sendText=function(user_file,content,type,callback_ok,callback_error){if(!moodle_upload_file)return;var http=new XMLHttpRequest;var params="user_file="+user_file+"&file="+encodeURIComponent(content)+"&type="+type+"&context_id="+context_id+"&user_id="+user_id+"&ejsapp_id="+ejsapp_id;http.open("POST",moodle_upload_file,true);http.setRequestHeader("Content-type","application/x-www-form-urlencoded");http.onreadystatechange=function(){if(http.readyState==4&&http.status==200){if(callback_ok)callback_ok()}else{if(callback_error)callback_error()}};http.send(params)};self.getState=function(url,callback_ok,callback_error){var http=new XMLHttpRequest;http.open("GET",url,true);http.setRequestHeader("Cache-Control","no-cache");http.onreadystatechange=function(){if(http.readyState==4&&http.status==200){self.unserialize(http.responseText);if(callback_ok)callback_ok()}else{if(callback_error)callback_error()}};http.send()};self.getText=function(url,callback_ok,callback_error){var http=new XMLHttpRequest;http.open("GET",url,true);http.setRequestHeader("Cache-Control","no-cache");http.onreadystatechange=function(){if(http.readyState==4&&http.status==200){if(callback_ok)callback_ok(http.responseText)}else{if(callback_error)callback_error()}};http.send()};self.getStateFiles=function(type,callback_ok,callback_error){if(!ejsapp_id)return;var http=new XMLHttpRequest;var get_url=moodle_send_file_list+"?ejsapp_id="+ejsapp_id+"&type="+type;http.open("GET",get_url,true);http.onreadystatechange=function(){if(http.readyState==4&&http.status==200){var list={};list["name"]=[];list["url"]=[];var data=JSON.parse(http.responseText);for(var i=0;i<data.file_names.length;i++){list["name"].push(data.file_names[i].file_name);list["url"].push(data.file_paths[i].file_path)}if(callback_ok)callback_ok(list)}else{if(callback_error)callback_error()}};http.send()};self.saveText=function(name,type,content){if(!content){var content=type;type=null}if(context_id)EJSS_INTERFACE.BoxPanel.showInputDialog(SAVETEXT_Q,function(name){self.sendText(name,content,type,function(){self.sendCallback()})});else self.sendText(name,content,type,function(){self.sendCallback()})};self.saveState=function(name){if(context_id)EJSS_INTERFACE.BoxPanel.showInputDialog(SAVETEXT_Q,function(name){self.sendState(name,function(){self.sendCallback()})});else self.sendState(name,function(){self.sendCallback()})};self.saveImage=function(name,panelname){if(context_id)EJSS_INTERFACE.BoxPanel.showInputDialog(SAVETEXT_Q,function(name){self.sendSnapshot(mView[panelname],name,function(){self.sendCallback()})});else self.sendSnapshot(mView[panelname],name,function(){self.sendCallback()})};self.readState=function(url,type){if(!url){var tp=typeof type!=="undefined"?type:".json";self.getStateFiles(tp,function(lf){var options={text:lf.name,value:lf.url};EJSS_INTERFACE.BoxPanel.showSelectDialog(READFILE_Q,options,function(url){self.getState(url)})})}else self.getState(url)};self.readText=function(url,type,varname_or_callback){if(!url){self.getStateFiles(type,function(lf){var options={text:lf.name,value:lf.url};EJSS_INTERFACE.BoxPanel.showSelectDialog(READFILE_Q,options,function(url){self.getText(url,function(text){if(typeof varname_or_callback==="function"){varname_or_callback(text)}else{var json={};json[varname_or_callback]=text;self._userUnserialize(json)}})})})}else self.getText(url,function(text){if(typeof varname_or_callback==="function"){varname_or_callback(text)}else{var json={};json[varname_or_callback]=text;self._userUnserialize(json)}})};var mUserEvents=[];var mRunCount=0;var mWebSocket;var mEventSource;var _stylesBak={};var _isPlayingCaptureStream=false;self.getEventInteractionsStream=function(event){var target=event.target||event.srcElement;var myevent={pageX:event.pageX,pageY:event.pageY,offsetLeft:target.offsetLeft,offsetTop:target.offsetTop,target:target.id,timeStamp:+new Date};myevent["runCount"]=mRunCount;myevent["runTime"]=mRunTime;myevent["type"]=event.type;myevent["event"]="touch";mWebSocket.send(JSON.stringify(myevent))};self.startCaptureStream=function(port,win,fail,open,close){var loc=window.location;var uri=loc.protocol==="https:"?"wss:":"ws:";uri+="//"+loc.host+":"+port;try{mWebSocket=new WebSocket(uri);if(typeof win!=="undefined")win();mWebSocket.onopen=function(){mRunCount=0;mRunTime=+new Date;mView.registerInteractions(mWebSocket);document.addEventListener("mousemove",self.getEventInteractionsStream);document.addEventListener("touchmove",self.getEventInteractionsStream);document.addEventListener("mousedown",self.getEventInteractionsStream);document.addEventListener("touchstart",self.getEventInteractionsStream)};mWebSocket.onclose=function(evt){self.stopCaptureStream();close(evt)};mWebSocket.onmessage=function(evt){console.log("Message is received: "+evt.data)}}catch(exception){if(typeof fail!=="undefined")fail(exception);return}};self.stopCaptureStream=function(){try{mWebSocket.close()}catch(exception){}mView.unregisterInteractions();document.removeEventListener("mousemove",self.getEventInteractionsStream);document.removeEventListener("touchmove",self.getEventInteractionsStream);document.removeEventListener("mousedown",self.getEventInteractionsStream);document.removeEventListener("touchstart",self.getEventInteractionsStream)};self.playCaptureStream=function(uri,win,fail,open,close){var FREC=10;if(_isPlayingCaptureStream)return;_isPlayingCaptureStream=true;var captured=[];try{mEventSource=new EventSource(uri);if(typeof win!=="undefined")win();mEventSource.onopen=open;mEventSource.onclose=function(evt){var s=document.getElementById("_my_mouse");if(s)document.body.removeChild(s);close(evt)};mEventSource.onmessage=function(evt){var alldata=JSON.parse(evt.data);console.log("Now: "+Date.now()+"-"+alldata.timeStamp);captured=captured.concat(alldata.interactions)}}catch(exception){if(typeof fail!=="undefined")fail(exception);return}setTimeout(function(){mRunCount=0;mRunTime=+new Date;_capturedInteractions=[];var lastTime=0;var ixCaptured=0;var crun=mRunCount;var ctime=0;var ltime=0;var diffLeft=0;var diffTop=0;var myTimer=setInterval(function(){var ix=ixCaptured;while(ix<captured.length){var data=captured[ix++];if(typeof data["isPlaying"]!=="undefined"&&data["isPlaying"]){_capturedInteractions.push(data);ixCaptured++}else if(data.runCount==crun&&ctime>=data.timeStamp-data.runTime&<ime<=data.timeStamp-data.runTime){ixCaptured++;ltime=data.timeStamp-data.runTime;for(var i in _stylesBak){var element=mView[i];element.getDOMElement().style.border=_stylesBak[i]}_stylesBak={};if(typeof data.event!=="undefined"){var x=data.pageX;var y=data.pageY;var target=data.target;if(typeof target!=="undefined"&&target.length>0){var element=document.getElementById(target);if(element!=null){diffLeft=data.offsetLeft-element.offsetLeft;diffTop=data.offsetTop-element.offsetTop}}x-=diffLeft;y+=diffTop;var s=document.getElementById("_my_mouse");if(!s){var s=document.createElement("div");s.id="_my_mouse";s.style.position="absolute";s.style.margin="0";s.style.border="3px solid red";document.body.appendChild(s)}s.style.left=x+"px";s.style.top=y+"px"}else if(typeof data.property!=="undefined"){var element=mView[data.element];element.propertyChanged(data.property,data.data).reportInteractions()}else if(typeof data.action!=="undefined"){var element=mView[data.element];element.invokeAction(data.action).reportInteractions();if(typeof _stylesBak[element.getName()]=="undefined")_stylesBak[element.getName()]=element.getDOMElement().style.border;element.getDOMElement().style.border="1px solid red"}}}if(crun!=mRunCount){crun=mRunCount;ctime=0;ltime=0}else{ctime+=FREC}if(!_isPlayingCaptureStream){clearInterval(myTimer)}},FREC)},1e3)};self.pauseCaptureStream=function(){try{mEventSource.close()}catch(exception){}_isPlayingCaptureStream=false};self.getEventInteractions=function(event){var target=event.target||event.srcElement;var myevent={pageX:event.pageX,pageY:event.pageY,offsetLeft:target.offsetLeft,offsetTop:target.offsetTop,target:target.id,timeStamp:+new Date};myevent["runCount"]=mRunCount;myevent["runTime"]=mRunTime;myevent["type"]=event.type;myevent["event"]="touch";mUserEvents.push(myevent)};self.startCapture=function(){mRunCount=0;mRunTime=+new Date;mView.registerInteractions();mUserEvents=[];document.addEventListener("mousemove",self.getEventInteractions);document.addEventListener("touchmove",self.getEventInteractions);document.addEventListener("mousedown",self.getEventInteractions);document.addEventListener("touchstart",self.getEventInteractions)};self.getCapture=function(){var interactions={interactions:mView.getRegInteractions(),events:mUserEvents};return interactions};self.stopCapture=function(){mView.unregisterInteractions();document.removeEventListener("mousemove",self.getEventInteractions);document.removeEventListener("touchmove",self.getEventInteractions);document.removeEventListener("mousedown",self.getEventInteractions);document.removeEventListener("touchstart",self.getEventInteractions);return self.getCapture()};self._readCapturedInteractions=function(){var n=_capturedInteractions.length;for(var i=0;i<n;i++){var inter=_capturedInteractions[i];if(inter["runCount"]==mRunCount&&inter["isPlaying"]){if(inter.property!=="undefined"){var element=mView[inter.element];element.propertyChanged(inter.property,inter.data).reportInteractions()}if(inter.action!=="undefined"){var element=mView[inter.element];element.invokeAction(inter.action).reportInteractions();if(typeof _stylesBak[element.getName()]=="undefined")_stylesBak[element.getName()]=element.getDOMElement().style.border;element.getDOMElement().style.border="1px solid red"}inter["runCount"]=-1}}};var _isPlayingCapture=false;var _resetPlayingCapture=false;var _stepPlayingCapture=1;var _isPlayingBeforePause=false;var _capturedInteractions=[];self.playCapture=function(captured,callback,step){var FREC=10;var actions=captured.interactions;var lactions=actions.length;var caction=0;var events=captured.events;var levents=events.length;var cevent=0;if(_isPlayingCapture)return;_isPlayingCapture=true;_resetPlayingCapture=false;self.reset();if(typeof step!=="undefined")_stepPlayingCapture=step;mDelay/=_stepPlayingCapture;mRunCount=0;mRunTime=+new Date;_capturedInteractions=actions;var crun=mRunCount;var ctime=0;var diffLeft=0;var diffTop=0;var myTimer=setInterval(function(){for(var i in _stylesBak){var element=mView[i];element.getDOMElement().style.border=_stylesBak[i]}_stylesBak={};if(_isPlayingCapture){while(caction<lactions&&actions[caction]["runCount"]<=crun&&ctime>=actions[caction].timeStamp-actions[caction].runTime){if(!actions[caction]["isPlaying"]){if(actions[caction].property!=="undefined"){var element=mView[actions[caction].element];element.propertyChanged(actions[caction].property,actions[caction].data).reportInteractions()}if(actions[caction].action!=="undefined"){var element=mView[actions[caction].element];element.invokeAction(actions[caction].action).reportInteractions();if(typeof _stylesBak[element.getName()]=="undefined")_stylesBak[element.getName()]=element.getDOMElement().style.border;element.getDOMElement().style.border="1px solid red"}}caction++}while(cevent<levents&&events[cevent]["runCount"]<=crun&&ctime>=events[cevent].timeStamp-events[cevent].runTime){var x=events[cevent].pageX;var y=events[cevent].pageY;var target=events[cevent].target;if(typeof target!=="undefined"&&target.length>0){var element=document.getElementById(target);if(element!=null){diffLeft=events[cevent].offsetLeft-element.offsetLeft;diffTop=events[cevent].offsetTop-element.offsetTop}}x-=diffLeft;y+=diffTop;var s=document.getElementById("_my_mouse");if(!s){var s=document.createElement("div");s.id="_my_mouse";s.style.position="absolute";s.style.margin="0";s.style.border="3px solid red";document.body.appendChild(s)}s.style.left=x+"px";s.style.top=y+"px";cevent++}if(crun!=mRunCount){crun=mRunCount;ctime=0}else{ctime+=FREC*_stepPlayingCapture}if(cevent>=levents&&caction>=lactions){var s=document.getElementById("_my_mouse");if(s)document.body.removeChild(s);clearInterval(myTimer);_isPlayingCapture=false;mDelay*=_stepPlayingCapture;_capturedInteractions=[];callback()}}if(_resetPlayingCapture){clearInterval(myTimer);_isPlayingCapture=false;mDelay*=_stepPlayingCapture;_capturedInteractions=[];callback()}},FREC)};self.pauseCapture=function(){_isPlayingBeforePause=mIsPlaying;self.pause();_isPlayingCapture=false};self.resumeCapture=function(){if(_isPlayingBeforePause)self.play();_isPlayingCapture=true};self.resetCapture=function(){_resetPlayingCapture=true};self.changeCaptureStep=function(step){mDelay*=_stepPlayingCapture;_stepPlayingCapture=step;mDelay/=_stepPlayingCapture};mModelCalls=[];mIsRegModelCalls=false;self.pushRegModelCalls=function(func){var mycall={function:func,timeStamp:+new Date};mycall["runCount"]=mRunCount;mycall["runTime"]=mRunTime;mModelCalls.push(mycall)};self.startRegister=function(events){if(!mIsRegModelCalls){mIsRegModelCalls=true;mRunCount=0;mRunTime=+new Date;mView.registerInteractions();mModelCalls=[];mUserEvents=[];if(events){document.addEventListener("mousemove",self.getEventInteractions);document.addEventListener("touchmove",self.getEventInteractions);document.addEventListener("mousedown",self.getEventInteractions);document.addEventListener("touchstart",self.getEventInteractions)}}};self.getRegister=function(empty){var interactions={interactions:mView.getRegInteractions(empty),model:mModelCalls,events:mUserEvents};if(empty){mModelCalls=[];mUserEvents=[]}return interactions};self.stopRegister=function(){mView.unregisterInteractions();mIsRegModelCalls=false;document.removeEventListener("mousemove",self.getEventInteractions);document.removeEventListener("touchmove",self.getEventInteractions);document.removeEventListener("mousedown",self.getEventInteractions);document.removeEventListener("touchstart",self.getEventInteractions);return self.getRegister()};self.sendRegister=function(empty,callback_ok,callback_error){if(!moodle_upload_file)return;var json=JSON.stringify(self.getRegister(empty),function(key,value){if(typeof value=="number"){if(isNaN(value))value="__NaN";else if(!isFinite(value))value="__Infinity"}return value});var http=new XMLHttpRequest;var params="file="+encodeURIComponent(json)+"&type=actions"+"&user_id="+user_id+"&ejsapp_id="+ejsapp_id;http.open("POST",moodle_upload_file,true);http.setRequestHeader("Content-type","application/x-www-form-urlencoded");http.onreadystatechange=function(){if(http.readyState==4&&http.status==200){if(callback_ok)callback_ok()}else{if(callback_error)callback_error()}};http.send(params)};self.setMode=function(mode){self.setRunningMode(mode)};self.setRunningMode=function(mode){if(typeof mode==="string")mRunningMode=EJSS_CORE.Model[mode.toUpperCase()];else mRunningMode=mode};self.getMode=function(){return mRunningMode};self.setRunAlways=function(always){mRunAlways=always};self.setPauseOnPageExit=function(pause){mRunAlways=!pause};self.setFPS=function(fps){mDelay=Math.max(1e3/fps,MINIMUM_DELAY)};self.getFPS=function(){return Math.floor(1e3/mDelay)};self.setDelay=function(delay){mDelay=Math.max(delay,0)};self.getDelay=function(delay){return mDelay};self.setMinimumDelay=function(delay){mMinimumDelay=Math.max(delay,0)};self.setStepsPerDisplay=function(steps){if(steps>=1)mStepsPerDisplay=steps};self.setUpdateView=function(mustDo){mShouldUpdateView=mustDo};self.setAutoplay=function(play){mAutoplay=play};self.isPlaying=function(){return mIsPlaying};self.isPaused=function(){return!mIsPlaying};self.resetRealTime=function(){var now=+Date();mInitialRealTime=1e3*self.getRealTime()-now};self.play=function(){if(mIsPlaying)return;if(mIsRegModelCalls)self.pushRegModelCalls("play");mLastTime=+new Date;mSleepTime=mDelay;mIsPlaying=true;mCurrentTimeOut=window.setTimeout(self.run,mMinimumDelay)};self.pause=function(){if(mIsRegModelCalls)self.pushRegModelCalls("pause");mIsPlaying=false;mAbortSPDLoop=true;if(mCurrentTimeOut!=0){window.clearTimeout(mCurrentTimeOut);mCurrentTimeOut=0}};self.run=function(){mRunCount++;mRunTime=+new Date;var timeout=1;var elapsed;if(!mIsPlaying)return;if(mFocus||mRunAlways){switch(mRunningMode){default:case EJSS_CORE.Model.MODE_JAVA_STYLE:self.step();mLastTime=+new Date;elapsed=mLastTime-mRunTime;timeout=Math.max(mMinimumDelay,mDelay-elapsed);break;case EJSS_CORE.Model.MODE_RESPECT_DELAY:self.step();timeout=mDelay;mLastTime=+new Date;break;case EJSS_CORE.Model.MODE_RESPECT_TIME:elapsed=mRunTime-mLastTime;if(elapsed>=mSleepTime-mExcededTime){var step=0
;if(mSleepTime){step=Math.floor((elapsed+mExcededTime)/mSleepTime);mExcededTime=elapsed+mExcededTime-step*mSleepTime}var stepModelTime=self.step(step);if(mSleepTime&&stepModelTime>elapsed&&step>100){alert("Imposible running with delay "+mSleepTime+" ms.");mIsPlaying=false;mExcededTime=0}mSleepTime=mDelay;mLastTime=mRunTime}break}var thisTimeOut=mCurrentTimeOut;self._readCapturedInteractions();if(mView._16(mRunCount,mRunTime,mIsPlaying)){self.automaticResetSolvers();self.update()}if(thisTimeOut!=mCurrentTimeOut)return}else{mLastTime=+new Date}mCurrentTimeOut=window.setTimeout(self.run,timeout)};self.onExit=function(){self.pause();mView._16(mRunCount,mRunTime,mIsPlaying);self.freeMemory()};self.reset=function(reuseview){if(mIsRegModelCalls)self.pushRegModelCalls("reset");if(!reuseview){self.pause();self.resetModel()}mView._14(false);mView._reset();if(!reuseview){mView._15();mView._initialize();self.initializeModel()}self.updateModel();if(mShouldUpdateView){mView._update();mView._render()}else mView._collectData();mView._14(true);if(mAutoplay)self.play();mView._resized(window.innerWidth,window.innerHeight)};self.initialize=function(){if(mIsRegModelCalls)self.pushRegModelCalls("initialize");mView._initialize();self.initializeModel();self.updateModel();if(mShouldUpdateView){mView._update();mView._render()}else mView._collectData()};self.update=function(){if(!(mFocus||mRunAlways))return;self.updateModel();if(mShouldUpdateView){mView._update();mView._render()}else mView._collectData()};self.step=function(forceStepsPerDisplay){var now=+new Date;if(!forceStepsPerDisplay)forceStepsPerDisplay=1;var steps=Math.max(forceStepsPerDisplay,mStepsPerDisplay);if(steps>1){mAbortSPDLoop=false;for(var i=1;i<steps;i++){if(mAbortSPDLoop){self.update();return}self.stepModel();self.updateModel();mView._collectData()}}self.stepModel();var stepModelTime=+new Date-now;self.update();return stepModelTime};self.setShouldBreak=function(shouldDo){mShouldBreak=shouldDo};self.getShouldBreak=function(){return mShouldBreak};self._autoSelectView=function(viewsInfo){var height=screen.height;var width=screen.width;var sel=[];var min=Number.MAX_VALUE;for(var i=0;i<viewsInfo.length;i++){var dis=width-viewsInfo[i]["width"];if(dis>=0){if(dis<min){min=dis;sel=[i]}else if(dis==min){sel.push(i)}}}var ret=-1;min=Number.MAX_VALUE;for(var i=0;i<sel.length;i++){var dis=Math.abs(height-viewsInfo[sel[i]]["height"]);if(dis<min){min=dis;ret=sel[i]}}return ret};self.addToOnload=function(onloadfunc){mOnloadFunc=onloadfunc};self.onload=function(){if(typeof mOnloadFunc=="function")mOnloadFunc()};self.parseInputParameters=function(inputParameters){if(typeof inputParameters==="string"||inputParameters instanceof String){try{inputParameters=EJSS_TOOLS.Decode.hex_to_ascii(inputParameters);inputParameters=EJSS_TOOLS.Decode.decode(inputParameters);if(inputParameters[0]=="'"&&inputParameters[inputParameters.length-1]=="'")inputParameters=inputParameters.substring(1,inputParameters.length-1);else if(inputParameters[0]=='"'&&inputParameters[inputParameters.length-1]=='"')inputParameters=inputParameters.substring(1,inputParameters.length-1);inputParameters=JSON.parse(inputParameters)}catch(exception){console.log("Error trying to parse input parameters: "+inputParameters);return null}}return inputParameters};var mResetList=[];var mInitializationList=[];var mEvolutionList=[];var mFixedRelationsList=[];self.getRealTime=function(){return NaN};self.automaticResetSolvers=function(){};self.freeMemory=function(){};self.addToReset=function(aFunction){mResetList.push(aFunction)};self.addToInitialization=function(aFunction){mInitializationList.push(aFunction)};self.addToEvolution=function(aFunction){mEvolutionList.push(aFunction)};self.addToFixedRelations=function(aFunction){mFixedRelationsList.push(aFunction)};self.resetModel=function(){processFunctionList(mResetList)};self.initializeModel=function(){processFunctionList(mInitializationList)};self.stepModel=function(){processFunctionList(mEvolutionList)};self.updateModel=function(){processFunctionList(mFixedRelationsList)};function processFunctionList(functionList){for(var i=0,n=functionList.length;i<n;i++){mShouldBreak=false;functionList[i]();if(mShouldBreak)return}}window.onblur=function(){mFocus=false;if(mView)mView._onBlur()};window.onfocus=function(){mFocus=true;if(mView)mView._onFocus()};return self};var EJSS_ODE_INTERPOLATION=EJSS_ODE_INTERPOLATION||{};EJSS_ODE_INTERPOLATION.Bootstrap2IntervalData={};EJSS_ODE_INTERPOLATION.bootstrap2IntervalData=function(aState,aRate,bState,bRate,ode){var self=EJSS_ODE_INTERPOLATION.bootstrapIntervalData(aState,aRate,bState,bRate,ode);var mBt2_c2;var mBt2_c3;var mBt2_c4;var mBt2_c5;self.interpolate=function(time,index){var deltaTime=self.getDeltaTime();var leftState=self.getLeftState();var leftRate=self.getLeftRate();var step=(time-self.getLeft())/deltaTime;return leftState[index]+step*(deltaTime*leftRate[index]+step*(mBt2_c2[index]+step*(mBt2_c3[index]+step*(mBt2_c4[index]+step*mBt2_c5[index]))))};self.interpolateState=function(time,state,beginIndex,length){self.bootstrap2((time-self.getLeft())/self.getDeltaTime(),state,beginIndex,length);return state};self.bootstrap2=function(step,state,beginIndex,length){var deltaTime=self.getDeltaTime();var leftState=self.getLeftState();var leftRate=self.getLeftRate();var index=beginIndex;for(var i=0;i<length;i++){state[i]=leftState[index]+step*(deltaTime*leftRate[index]+step*(mBt2_c2[index]+step*(mBt2_c3[index]+step*(mBt2_c4[index]+step*mBt2_c5[index]))));index++}};var BETA1=.7;var BETA2=.85;var bt2_den=2*BETA1*(BETA1-1)*BETA2*(BETA2-1)*(BETA2-BETA1)*(10*BETA1*BETA2-5*BETA2-5*BETA1+3);var bt2_cf11=BETA1*(-3*BETA1+2);var bt2_cf01=BETA1*(-3*BETA1+4)-1;var bt2_cys1=6*BETA1*(BETA1-1);var bt2_cf12=BETA2*(-3*BETA2+2);var bt2_cf02=BETA2*(-3*BETA2+4)-1;var bt2_cys2=6*BETA2*(BETA2-1);var bt2_m44=BETA1*(2+BETA1*(-6+4*BETA1));var bt2_m54=BETA2*(2+BETA2*(-6+4*BETA2));var bt2_m45=BETA1*(4+BETA1*(-9+5*BETA1*BETA1));var bt2_m55=BETA2*(4+BETA2*(-9+5*BETA2*BETA2));var dimension=aState.length;var timeIndex=dimension-1;var deltaTime=self.getDeltaTime();var state_bt2=new Array(dimension);var rate_bt21=new Array(dimension);var rate_bt22=new Array(dimension);mBt2_c2=new Array(dimension);mBt2_c3=new Array(dimension);mBt2_c4=new Array(dimension);mBt2_c5=new Array(dimension);self.bootstrap1(BETA1,state_bt2,0,timeIndex);state_bt2[timeIndex]=self.getLeft()+BETA1*deltaTime;ode.getRate(state_bt2,rate_bt21);self.bootstrap1(BETA2,state_bt2,0,timeIndex);state_bt2[timeIndex]=self.getLeft()+BETA2*deltaTime;ode.getRate(state_bt2,rate_bt22);for(var i=0;i<dimension;i++){var dif=bState[i]-aState[i];var f0=deltaTime*aRate[i];var f1=deltaTime*bRate[i];var e1=deltaTime*rate_bt21[i]+bt2_cf11*f1+bt2_cf01*f0+bt2_cys1*dif;var e2=deltaTime*rate_bt22[i]+bt2_cf12*f1+bt2_cf02*f0+bt2_cys2*dif;var c4=(bt2_m55*e1-bt2_m45*e2)/bt2_den;var c5=(bt2_m44*e2-bt2_m54*e1)/bt2_den;var c3=f1+f0-2*dif-2*c4-3*c5;mBt2_c5[i]=c5;mBt2_c4[i]=c4;mBt2_c3[i]=c3;mBt2_c2[i]=dif-f0-c3-c4-c5}return self};var EJSS_ODE_INTERPOLATION=EJSS_ODE_INTERPOLATION||{};EJSS_ODE_INTERPOLATION.BootstrapIntervalData={};EJSS_ODE_INTERPOLATION.bootstrapIntervalData=function(aState,aRate,bState,bRate,ode){var self=EJSS_ODE_INTERPOLATION.hermiteIntervalData(aState,aRate,bState,bRate);var mBt1_c2;var mBt1_c3;var mBt1_c4;self.interpolate=function(time,index){var deltaTime=self.getDeltaTime();var leftState=self.getLeftState();var leftRate=self.getLeftRate();var step=(time-self.getLeft())/deltaTime;return leftState[index]+step*(deltaTime*leftRate[index]+step*(mBt1_c2[index]+step*(mBt1_c3[index]+step*mBt1_c4[index])))};self.interpolateState=function(time,state,beginIndex,length){self.bootstrap1((time-self.getLeft())/self.getDeltaTime(),state,beginIndex,length);return state};self.bootstrap1=function(step,state,beginIndex,length){var deltaTime=self.getDeltaTime();var leftState=self.getLeftState();var leftRate=self.getLeftRate();var index=beginIndex;for(var i=0;i<length;i++){state[i]=leftState[index]+step*(deltaTime*leftRate[index]+step*(mBt1_c2[index]+step*(mBt1_c3[index]+step*mBt1_c4[index])));index++}};var ALPHA=.25;var bt1_den=ALPHA*(ALPHA-1)*(4*ALPHA-2);var bt1_cf1=ALPHA*(-3*ALPHA+2);var bt1_cf0=ALPHA*(-3*ALPHA+4)-1;var bt1_cys=6*ALPHA*(ALPHA-1);var dimension=aState.length;var deltaTime=self.getDeltaTime();var state_bt1=new Array(dimension);var rate_bt1=new Array(dimension);mBt1_c2=new Array(dimension);mBt1_c3=new Array(dimension);mBt1_c4=new Array(dimension);self.hermite(ALPHA,state_bt1,0,dimension-1);state_bt1[dimension-1]=self.getLeft()+ALPHA*deltaTime;ode.getRate(state_bt1,rate_bt1);for(var i=0;i<dimension;i++){var dif=bState[i]-aState[i];var f0=deltaTime*aRate[i];var f1=deltaTime*bRate[i];var c4=(deltaTime*rate_bt1[i]+bt1_cf1*f1+bt1_cf0*f0+bt1_cys*dif)/bt1_den;var c3=f1+f0-2*dif-2*c4;mBt1_c4[i]=c4;mBt1_c3[i]=c3;mBt1_c2[i]=dif-f0-c3-c4}return self};var EJSS_ODE_INTERPOLATION=EJSS_ODE_INTERPOLATION||{};EJSS_ODE_INTERPOLATION.ConstantConditionData={};EJSS_ODE_INTERPOLATION.constantConditionData=function(aState){var self=EJSS_ODE_INTERPOLATION.intervalData(Number.NaN,Number.NaN);var mState;self.interpolate=function(time,index){return mState[index]};self.interpolateState=function(time,state,beginIndex,length){var index=beginIndex;for(var i=0;i<length;i++){state[i]=mState[index];index++}return state};var dimension=aState.length;mState=new Array(dimension);for(var i=0;i<dimension;i++){mState[i]=aState[i]}return self};var EJSS_ODE_INTERPOLATION=EJSS_ODE_INTERPOLATION||{};EJSS_ODE_INTERPOLATION.Dopri5IntervalData={};EJSS_ODE_INTERPOLATION.dopri5IntervalData=function(aState,bState,coeffs){var self=EJSS_ODE_INTERPOLATION.extraStepsIntervalData(aState,bState,coeffs);self.interpolate=function(time,index){var theta=(time-self.getLeft())/self.getDeltaTime();var theta1=1-theta;var coeffs=self.getCoeffs();return coeffs[0][index]+theta*(coeffs[1][index]+theta1*(coeffs[2][index]+theta*(coeffs[3][index]+theta1*coeffs[4][index])))};self.interpolateState=function(time,state,beginIndex,length){var theta=(time-self.getLeft())/self.getDeltaTime();var theta1=1-theta;var coeffs=self.getCoeffs();var index=beginIndex;for(var i=0;i<length;i++){state[i]=coeffs[0][index]+theta*(coeffs[1][index]+theta1*(coeffs[2][index]+theta*(coeffs[3][index]+theta1*coeffs[4][index])));index++}return state};return self};var EJSS_ODE_INTERPOLATION=EJSS_ODE_INTERPOLATION||{};EJSS_ODE_INTERPOLATION.Dopri853IntervalData={};EJSS_ODE_INTERPOLATION.dopri853IntervalData=function(aState,bState,coeffs){var self=EJSS_ODE_INTERPOLATION.extraStepsIntervalData(aState,bState,coeffs);self.interpolate=function(time,index){var theta=(time-self.getLeft())/self.getDeltaTime();var theta1=1-theta;var coeffs=self.getCoeffs();return coeffs[0][index]+theta*(coeffs[1][index]+theta1*(coeffs[2][index]+theta*(coeffs[3][index]+theta1*(coeffs[4][index]+theta*(coeffs[5][index]+theta1*(coeffs[6][index]+theta*coeffs[7][index]))))))};self.interpolateState=function(time,state,beginIndex,length){var theta=(time-self.getLeft())/self.getDeltaTime();var theta1=1-theta;var coeffs=self.getCoeffs();var index=beginIndex;for(var i=0;i<length;i++){state[i]=coeffs[0][index]+theta*(coeffs[1][index]+theta1*(coeffs[2][index]+theta*(coeffs[3][index]+theta1*(coeffs[4][index]+theta*(coeffs[5][index]+theta1*(coeffs[6][index]+theta*coeffs[7][index]))))));index++}return state};return self};var EJSS_ODE_INTERPOLATION=EJSS_ODE_INTERPOLATION||{};EJSS_ODE_INTERPOLATION.EulerIntervalData={};EJSS_ODE_INTERPOLATION.eulerIntervalData=function(state,rate,right){var self=EJSS_ODE_INTERPOLATION.intervalData(state[state.length-1],right);var mLeftState;var mLeftRate;self.interpolate=function(time,index){var step=time-self.getLeft();return mLeftState[index]+step*mLeftRate[index]};self.interpolateState=function(time,state,beginIndex,length){var step=time-self.getLeft();var index=beginIndex;for(var i=0;i<length;i++){state[i]=mLeftState[index]+step*mLeftRate[index];index++}return state};var dimension=state.length;mLeftState=new Array(dimension);mLeftRate=new Array(dimension);for(var i=0;i<dimension;i++){mLeftState[i]=state[i];mLeftRate[i]=rate[i]}return self};var EJSS_ODE_INTERPOLATION=EJSS_ODE_INTERPOLATION||{};EJSS_ODE_INTERPOLATION.EulerRichardsonIntervalData={};EJSS_ODE_INTERPOLATION.eulerRichardsonIntervalData=function(state,rate,right,K2){var self=EJSS_ODE_INTERPOLATION.intervalData(state[state.length-1],right);var mTimeIndex;var mStepSize;var mLeftState;var mLeftRate;var mK2;self.interpolate=function(time,index){var theta=(time-self.getLeft())/mStepSize;var b2=theta*theta*mStepSize;var b1=mStepSize*theta-b2;return mLeftState[index]+b1*mLeftRate[index]+b2*mK2[index]};self.interpolateState=function(time,state,beginIndex,length){var theta=(time-self.getLeft())/mStepSize;var b2=theta*theta*mStepSize;var b1=mStepSize*theta-b2;var index=beginIndex;for(var i=0;i<length;i++){state[i]=mLeftState[index]+b1*mLeftRate[index]+b2*mK2[index];index++}return state};var dimension=state.length;mLeftState=new Array(dimension);mLeftRate=new Array(dimension);mK2=new Array(dimension);for(var i=0;i<dimension;i++){mLeftState[i]=state[i];mLeftRate[i]=rate[i];mK2[i]=K2[i]}mTimeIndex=dimension-1;mStepSize=right-state[mTimeIndex];return self};var EJSS_ODE_INTERPOLATION=EJSS_ODE_INTERPOLATION||{};EJSS_ODE_INTERPOLATION.ExtraStepsIntervalData={};EJSS_ODE_INTERPOLATION.extraStepsIntervalData=function(aState,bState,coeffs){var self=EJSS_ODE_INTERPOLATION.intervalData(aState[aState.length-1],bState[bState.length-1]);var mTimeIndex;var mDeltaTime;var mCoeffs;self.getTimeIndex=function(){return mTimeIndex};self.getDeltaTime=function(){return mDeltaTime};self.getCoeffs=function(){return mCoeffs};var dimension=aState.length;mTimeIndex=dimension-1;mDeltaTime=bState[mTimeIndex]-aState[mTimeIndex];var length=coeffs.length;mCoeffs=new Array(length);for(var i=0;i<length;i++){mCoeffs[i]=new Array(dimension);for(var j=0;j<dimension;j++){mCoeffs[i][j]=coeffs[i][j]}}return self};var EJSS_ODE_INTERPOLATION=EJSS_ODE_INTERPOLATION||{};EJSS_ODE_INTERPOLATION.HermiteIntervalData={};EJSS_ODE_INTERPOLATION.hermiteIntervalData=function(aState,aRate,bState,bRate){var self=EJSS_ODE_INTERPOLATION.intervalData(aState[aState.length-1],bState[bState.length-1]);var mTimeIndex;var mDeltaTime;var mLeftState;var mLeftRate;var mRightState;var mRightRate;self.getTimeIndex=function(){return mTimeIndex};self.getDeltaTime=function(){return mDeltaTime};self.getLeftState=function(){return mLeftState};self.getLeftRate=function(){return mLeftRate};self.interpolate=function(time,index){var theta=(time-self.getLeft())/mDeltaTime;var minus1=theta-1;var prod1=theta*minus1;var prod2=prod1*(1-2*theta);var coefX0=-minus1-prod2;var coefX1=theta+prod2;var coefF0=prod1*minus1*mDeltaTime;var coefF1=prod1*theta*mDeltaTime;return coefX0*mLeftState[index]+coefX1*mRightState[index]+coefF0*mLeftRate[index]+coefF1*mRightRate[index]};self.interpolateState=function(time,state,beginIndex,length){self.hermite((time-self.getLeft())/mDeltaTime,state,beginIndex,length);return state};self.hermite=function(theta,state,beginIndex,length){var minus1=theta-1;var prod1=theta*minus1;var prod2=prod1*(1-2*theta);var coefX0=-minus1-prod2;var coefX1=theta+prod2;var coefF0=prod1*minus1*mDeltaTime;var coefF1=prod1*theta*mDeltaTime;var index=beginIndex;for(var i=0;i<length;i++){state[i]=coefX0*mLeftState[index]+coefX1*mRightState[index]+coefF0*mLeftRate[index]+coefF1*mRightRate[index];index++}};var dimension=aState.length;mLeftState=new Array(dimension);mLeftRate=new Array(dimension);mRightState=new Array(dimension);mRightRate=new Array(dimension);for(var i=0;i<dimension;i++){mLeftState[i]=aState[i];mLeftRate[i]=aRate[i];mRightState[i]=bState[i];mRightRate[i]=bRate[i]}mTimeIndex=dimension-1;mDeltaTime=bState[mTimeIndex]-aState[mTimeIndex];return self};var EJSS_ODE_INTERPOLATION=EJSS_ODE_INTERPOLATION||{};EJSS_ODE_INTERPOLATION.InitialConditionData={};EJSS_ODE_INTERPOLATION.initialConditionData=function(mDDE){var self=EJSS_ODE_INTERPOLATION.intervalData(Number.NaN,Number.NaN);var mState;self.interpolate=function(time,index){mDDE.getInitialCondition(time,mState);return mState[index]};self.interpolateState=function(time,state,beginIndex,length){mDDE.getInitialCondition(time,mState);var index=beginIndex;for(var i=0;i<length;i++){state[i]=mState[index];index++}return state};var state=mDDE.getState();var dimension=state.length;mState=new Array(dimension);return self};var EJSS_ODE_INTERPOLATION=EJSS_ODE_INTERPOLATION||{};EJSS_ODE_INTERPOLATION.IntervalData={};EJSS_ODE_INTERPOLATION.intervalData=function(mLeft,mRight){var self={};self.getLeft=function(){return mLeft};self.getRight=function(){return mRight};self.setRight=function(rightSide){mRight=rightSide};self.interpolate=function(time,index){return Number.NaN};self.interpolateState=function(time,state,beginIndex,length){return state};return self};var EJSS_ODE_INTERPOLATION=EJSS_ODE_INTERPOLATION||{};EJSS_ODE_INTERPOLATION.Radau5IntervalData={};EJSS_ODE_INTERPOLATION.radau5IntervalData=function(aState,aRate,coeffs){var self=EJSS_ODE_INTERPOLATION.extraStepsIntervalData(aState,bState,coeffs);var mFinalTime=bState[bState.length-1];self.interpolate=function(time,index){var theta=(time-mFinalTime)/self.getDeltaTime();var coeffs=self.getCoeffs();var c1m1=EJSS_ODE_SOLVERS.Radau5.c1m1;var c2m1=EJSS_ODE_SOLVERS.Radau5.c2m1;return coeffs[0][index]+theta*(coeffs[1][index]+(theta-c2m1)*(coeffs[2][index]+(theta-c1m1)*coeffs[3][index]))};self.interpolateState=function(time,state,beginIndex,length){var theta=(time-mFinalTime)/mDeltaTime;var coeffs=self.getCoeffs();var c1m1=EJSS_ODE_SOLVERS.Radau5.c1m1;var c2m1=EJSS_ODE_SOLVERS.Radau5.c2m1;var index=beginIndex;for(var i=0;i<length;i++){state[i]=coeffs[0][index]+theta*(coeffs[1][index]+(theta-c2m1)*(coeffs[2][index]+(theta-c1m1)*coeffs[3][index]));index++}return state};return self};var EJSS_ODE_INTERPOLATION=EJSS_ODE_INTERPOLATION||{};EJSS_ODE_INTERPOLATION.StateHistory={};EJSS_ODE_INTERPOLATION.stateHistory=function(ode){var self={};var mIntervalList=[];var mForwards=true;var mLastResourceInterval;var mMinimumLength=0;var mUserLength=0;var mActualLength=0;self.setLength=function(length){mUserLength=Math.abs(length);mActualLength=Math.max(mMinimumLength,mUserLength)};self.setMinimumLength=function(length){mMinimumLength=Math.abs(length);mActualLength=Math.max(mMinimumLength,mUserLength)};self.addIntervalData=function(data){mForwards=data.getLeft()<=data.getRight();var length=mIntervalList.length;if(mIntervalList.length>0){var lastIndex=mIntervalList.length-1;var lastInterval=mIntervalList[lastIndex];var toRemove=0;if(mForwards){while(lastInterval!=null&&lastInterval.getLeft()>=data.getLeft()){toRemove++;lastIndex--;if(lastIndex<0)lastInterval=null;else lastInterval=mIntervalList[lastIndex]}if(lastInterval!=null&&data.getLeft()<lastInterval.getRight())lastInterval.setRight(data.getLeft())}else{while(lastInterval!=null&&lastInterval.getLeft()<=data.getLeft()){toRemove++;lastIndex--;if(lastIndex<0)lastInterval=null;else lastInterval=mIntervalList[lastIndex]}if(lastInterval!=null&&data.getLeft()>lastInterval.getRight())lastInterval.setRight(data.getLeft())}if(toRemove>0)mIntervalList.splice(lastIndex,toRemove)}mIntervalList.push(data)};self.toString=function(){var txt="History has now "+mIntervalList.length+" intervals: ";for(var i=0,n=mIntervalList.length;i<n;i++){var interval=mIntervalList[i];if(i>0)txt+=", ";txt+=" ["+interval.getLeft()+","+interval.getRight()+")"}return txt};self.clearAll=function(){mIntervalList=[]};self.clean=function(currentTime){if(!isFinite(mActualLength))return;if(mActualLength==0){clearAll();return}var toBeRemoved=0;var length=mIntervalList.length;if(mForwards){currentTime-=mActualLength;for(var i=0;i<length;i++){var interval=mIntervalList[i];if(interval.getRight()>currentTime)break;toBeRemoved++}}else{currentTime+=mActualLength;for(var i=0;i<length;i++){var interval=mIntervalList[i];if(interval.getRight()<currentTime)break;toBeRemoved++}}if(toBeRemoved>0)mIntervalList.splice(0,toBeRemoved)};self.findInterval=function(time){var length=mIntervalList.length;if(mForwards){for(var i=length-1;i>=0;i--){var interval=mIntervalList[i];if(interval.getLeft()<=time)return interval}}else{for(var i=length-1;i>=0;i--){var interval=mIntervalList[i];if(interval.getLeft()>=time)return interval}}return mLastResourceInterval};self.interpolate=function(time,index){var interval=self.findInterval(time);return interval.interpolate(time,index)};self.interpolateState=function(time,state,beginIndex,length){var interval=self.findInterval(time);if(!length)length=state.length;if(!beginIndex)beginIndex=0;return interval.interpolateState(time,state,beginIndex,length)};if(ode.getInitialCondition){mLastResourceInterval=EJSS_ODE_INTERPOLATION.initialConditionData(ode);ode.setStateHistory(self)}else{mLastResourceInterval=EJSS_ODE_INTERPOLATION.constantConditionData(ode.getState())}return self};var EJSS_ODE_SOLVERS=EJSS_ODE_SOLVERS||{};EJSS_ODE_SOLVERS.EVENT_TYPE={STATE_EVENT:0,POSITIVE_EVENT:1,CROSSING_EVENT:2};EJSS_ODE_SOLVERS.EVENT_METHOD={BISECTION:0,SECANT:1};EJSS_ODE_SOLVERS.ERROR={NO_ERROR:0,INTERNAL_SOLVER_ERROR:1,EVENT_NOT_FOUND:2,ILLEGAL_EVENT_STATE:3,ZENO_EFFECT:4,TOO_MANY_STEPS_ERROR:5,DISCONTINUITY_PRODUCED_ERROR:6,DID_NOT_CONVERGE:7};EJSS_ODE_SOLVERS.DISCONTINUITY_CODE={DISCONTINUITY_PRODUCED_ERROR:0,NO_DISCONTINUITY_ALONG_STEP:1,DISCONTINUITY_ALONG_STEP:2,DISCONTINUITY_JUST_PASSED:3,DISCONTINUITY_EXACTLY_ON_STEP:4};EJSS_ODE_SOLVERS.InterpolatorEventSolver={};EJSS_ODE_SOLVERS.interpolatorEventSolver=function(mSolverEngine,mODE){var self={};var mEnableExceptions=true;var mUseBestInterpolation=false;var mStepSize=.1;var mAbsoluteTolerance=Number.NaN;var mRelativeTolerance=Number.NaN;var mMaxEventStep=Number.POSITIVE_INFINITY;var mZenoMaximumAllowedTimes=500;var mProximityThreshold=2*Number.MIN_VALUE;var mCoalesceCloseEvents=true;var mMaxInternalSteps=1e4;var mRunsForwards=mStepSize>0;var mDimension;var mTimeIndex;var mErrorCode=EJSS_ODE_SOLVERS.ERROR.NO_ERROR;var mErrorMessage="No error";var mNumberOfAttempts=0;var mTest_ode_state;var mIntermediate_ode_state;var mEventList=[];var mHappened=[];var mTemp_list=[];var mLastEventDataTime=Number.NaN;var mLastEventData=null;var mZenoCounter=0;var mZenoList=[];var mCurrentEventData=null;var mHasEventsOrDiscontinuities=false;var mHasDiscontinuities=false;var mDiscontinuityAtEnd=null;var mDiscontinuityList=[];var mDDEdiscontinuity=null;var mDDEdiscontinuityMaxIterations=100;var mDDEdiscontinuityTolerance=1e-8;var sEPSILON=Number.NaN;self.getEPSILON=function(){if(isNaN(sEPSILON)){sEPSILON=1;while(sEPSILON+1!=1)sEPSILON/=2;sEPSILON*=2}return sEPSILON};self.setEnableExceptions=function(enable){mEnableExceptions=enable};self.setBestInterpolation=function(best){mUseBestInterpolation=best};self.setHistoryLength=function(length){mSolverEngine.getStateHistory().setLength(length)};self.setStepSize=function(stepSize){if(mStepSize==stepSize)return;mStepSize=stepSize;mRunsForwards=mStepSize>0;self.setInternalStepSize(mSolverEngine.getStepSize())};self.getStepSize=function(){return mStepSize};self.setEstimateFirstStep=function(estimate){mSolverEngine.setEstimateFirstStep(estimate)};self.setInternalStepSize=function(stepSize){mSolverEngine.setStepSize(mRunsForwards?Math.abs(stepSize):-Math.abs(stepSize))};self.setMaximumInternalStepSize=function(stepSize){mSolverEngine.setMaximumStepSize(stepSize)};self.setMaximumInternalSteps=function(steps){mMaxInternalSteps=steps};self.setTolerances=function(absTol,relTol){mSolverEngine.setTolerances(mAbsoluteTolerance=Math.abs(absTol),mRelativeTolerance=Math.abs(relTol))};self.setTolerance=function(tol){setTolerances(tol,0)};self.getTolerance=function(){return Math.max(mAbsoluteTolerance,mRelativeTolerance)};self.setDDETolerance=function(tol){mDDEdiscontinuityTolerance=tol};self.getDDETolerance=function(){return mDDEdiscontinuityTolerance};self.setDDEIterations=function(iterations){mDDEdiscontinuityMaxIterations=iterations};self.getDDEIterations=function(){return mDDEdiscontinuityMaxIterations};self.addEvent=function(event){mEventList.push(EJSS_ODE_SOLVERS.eventData(self,event,mODE.getState()));mHasEventsOrDiscontinuities=true};self.removeEvent=function(event){var index=-1;var length=mEventList.length;for(var i=0;i<length;i++){var data=mEventList[i];if(data.getEvent()==event){index=i;break}}if(index>=0){var foundData=mEventList[index];if(mLastEventData==foundData){mLastEventData=null;mZenoCounter=0}if(mCurrentEventData==foundData)mCurrentEventData=null;mEventList.splice(index,1)}mHasEventsOrDiscontinuities=mHasDiscontinuities||mEventList.length>0};self.addDiscontinuity=function(discontinuity){mDiscontinuityList.push(EJSS_ODE_SOLVERS.discontinuityData(self,discontinuity,mODE.getState()));mHasDiscontinuities=true;mHasEventsOrDiscontinuities=true};self.removeDiscontinuity=function(discontinuity){var index=-1;var length=mDiscontinuityList.length;for(var i=0;i<length;i++){var data=mDiscontinuityList[i];if(data.getDiscontinuity()==discontinuity){index=i;break}}if(index>=0){mDiscontinuityList.splice(index,1)}mHasDiscontinuities=mDiscontinuityList.length>0;mHasEventsOrDiscontinuities=mHasDiscontinuities||mEventList.length>0};self.removeAllEvents=function(){mEventList=[];mDiscontinuityList=[];mHasDiscontinuities=false;mHasEventsOrDiscontinuities=false;if(mDDEdiscontinuity!=null)self.addDiscontinuity(mDDEdiscontinuity)};self.setMaximumEventStep=function(step){mMaxEventStep=Math.abs(step)};self.getMaximumEventStep=function(){return mMaxEventStep};self.setCoalesceCloseEvents=function(coalesce){mCoalesceCloseEvents=coalesce};self.isCoalesceCloseEvents=function(){return mCoalesceCloseEvents};self.setEventProximityThreshold=function(threshold){mProximityThreshold=threshold};self.getEventProximityThreshold=function(){return mProximityThreshold};self.setZenoEffectDetection=function(times){mZenoMaximumAllowedTimes=times};self.getZenoEffectDetection=function(){return mZenoMaximumAllowedTimes};self.addZenoEffectListener=function(listener){mZenoList.push(listener)};self.removeZenoEffectListener=function(listener){var length=mZenoList.length;for(var i=0;i<length;i++){if(mZenoList[i]==listener){mZenoList.splice(i,1);return}}};self.setZeroZenoCounter=function(){mZenoCounter=0};self.getSolverEngine=function(){return mSolverEngine};self.getODE=function(){return mODE};self.getStateHistory=function(){return mSolverEngine.getStateHistory()};self.getErrorCode=function(){return mErrorCode};self.getErrorMessage=function(){return mErrorMessage};self.getCounter=function(){return mSolverEngine.getCounter()};self.getNumberOfAttempts=function(){return mNumberOfAttempts};self.getInternalStepSize=function(){return mSolverEngine.getInternalStepSize()};self.getIndependentVariableValue=function(){return mODE.getState()[mTimeIndex]};self.getCurrentTime=function(){return mODE.getState()[mTimeIndex]};self.getRunsForwards=function(){return mRunsForwards};self.getCurrentEventData=function(){return mCurrentEventData};self.getLastEventData=function(){return mLastEventData};self.getLastEventDataTime=function(){return mLastEventDataTime};self.initialize=function(stepSize){var i,length,state;mStepSize=stepSize;mRunsForwards=mStepSize>0;mSolverEngine.initialize(mStepSize);state=mODE.getState();mDimension=state.length;mTimeIndex=mDimension-1;mTest_ode_state=new Array(mDimension);mIntermediate_ode_state=new Array(mDimension);mErrorCode=EJSS_ODE_SOLVERS.ERROR.NO_ERROR;mErrorMessage="No error";mZenoCounter=0;mLastEventData=null;mCurrentEventData=null;if(mDDEdiscontinuity!==null){mDDEdiscontinuity.initialize(state);self.removeDiscontinuity(mDDEdiscontinuity);self.addDiscontinuity(mDDEdiscontinuity)}length=mEventList.length;for(i=0;i<length;i++)mEventList[i].reset(state);length=mDiscontinuityList.length;for(i=0;i<length;i++)mDiscontinuityList[i].reset(state)};self.step=function(){if(mHasEventsOrDiscontinuities)return stepWithEvents();return stepWithoutEvents()};self.maxStep=function(){if(mHasEventsOrDiscontinuities)return maxStepWithEvents();return maxStepWithoutEvents()};self.userReinitialize=function(){mCurrentEventData=null;self.reinitialize()};self.reinitialize=function(){var i,length;var state=mODE.getState();mSolverEngine.reinitialize(state);mErrorCode=EJSS_ODE_SOLVERS.ERROR.NO_ERROR;mErrorMessage="No error";if(mDDEdiscontinuity!=null)mDDEdiscontinuity.reset(state);length=mEventList.length;for(i=0;i<length;i++)mEventList[i].reset(state);length=mDiscontinuityList.length;for(i=0;i<length;i++)mDiscontinuityList[i].reset(state);mDiscontinuityAtEnd=null};self.resetDiscontinuities=function(state){if(mDDEdiscontinuity!==null){mDDEdiscontinuity.reset(state);var length=mDiscontinuityList.length;for(var i=0;i<length;i++)mDiscontinuityList[i].reset(state)}};self.checkDiscontinuity=function(state,isEndOfInterval){var length=mDiscontinuityList.length;var justHappened=null;for(var i=0;i<length;i++){var data=mDiscontinuityList[i];var h=data.getDiscontinuity().evaluate(state);data.setH(h);switch(data.getCurrentPosition()){default:case EJSS_ODE_SOLVERS.ProblemData.POSITIVE:if(h<=0){return EJSS_ODE_SOLVERS.DISCONTINUITY_CODE.DISCONTINUITY_ALONG_STEP}if(h<data.getDiscontinuity().getTolerance())justHappened=data;break;case EJSS_ODE_SOLVERS.ProblemData.SMALL_POSITIVE:if(h<=0&&data.hasPositiveFlag()){self.error(EJSS_ODE_SOLVERS.ERROR.ILLEGAL_EVENT_STATE,"The system started from an illegal state at "+state[mTimeIndex]+" for the discontinuity "+data.getDiscontinuity());return EJSS_ODE_SOLVERS.DISCONTINUITY_CODE.DISCONTINUITY_PRODUCED_ERROR}break;case EJSS_ODE_SOLVERS.ProblemData.ZERO:if(h<0&&data.hasPositiveFlag()){self.error(EJSS_ODE_SOLVERS.ERROR.ILLEGAL_EVENT_STATE,"The system started from an illegal state at "+state[mTimeIndex]+" for the discontinuity "+data.getDiscontinuity());return EJSS_ODE_SOLVERS.DISCONTINUITY_CODE.DISCONTINUITY_PRODUCED_ERROR}else if(h>0&&data.hasNegativeFlag()){self.error(EJSS_ODE_SOLVERS.ERROR.ILLEGAL_EVENT_STATE,"The system started from an illegal state at "+state[mTimeIndex]+" for the discontinuity "+data.getDiscontinuity());return EJSS_ODE_SOLVERS.DISCONTINUITY_CODE.DISCONTINUITY_PRODUCED_ERROR}break;case EJSS_ODE_SOLVERS.ProblemData.SMALL_NEGATIVE:if(data.hasNegativeFlag()&&h>=0){self.error(EJSS_ODE_SOLVERS.ERROR.ILLEGAL_EVENT_STATE,"The system started from an illegal state at "+state[mTimeIndex]+" for the discontinuity "+data.getDiscontinuity());return EJSS_ODE_SOLVERS.DISCONTINUITY_CODE.DISCONTINUITY_PRODUCED_ERROR}break;case EJSS_ODE_SOLVERS.ProblemData.NEGATIVE:if(h>0){return EJSS_ODE_SOLVERS.DISCONTINUITY_CODE.DISCONTINUITY_ALONG_STEP}if(h>-data.getDiscontinuity().getTolerance())justHappened=data;break}}if(justHappened!=null){if(isEndOfInterval){mDiscontinuityAtEnd=justHappened;mDiscontinuityAtEnd.setTime(state[mTimeIndex])}return EJSS_ODE_SOLVERS.DISCONTINUITY_CODE.DISCONTINUITY_EXACTLY_ON_STEP}return EJSS_ODE_SOLVERS.DISCONTINUITY_CODE.NO_DISCONTINUITY_ALONG_STEP};function doTheInterpolation(time,state){if(mUseBestInterpolation)mSolverEngine.bestInterpolate(time,state);else mSolverEngine.interpolate(time,state)}self.error=function(code,msg){mErrorCode=code;mErrorMessage=msg;if(mEnableExceptions)throw{name:"ODE Solver exception",solver:mSolverEngine,message:msg};return Number.NaN};function maxStepWithoutEvents(){var state=mODE.getState();var rate=mSolverEngine.getCurrentRate();var tBegin=state[mTimeIndex];if(tBegin+rate[mTimeIndex]==tBegin)return 0;var max_t=mSolverEngine.getMaximumTime(false);if(isNaN(max_t))return self.error(EJSS_ODE_SOLVERS.ERROR.INTERNAL_SOLVER_ERROR,"Error when stepping the solver at "+state[mTimeIndex]);if(tBegin==max_t){max_t=mSolverEngine.internalStep(false);if(isNaN(max_t))return self.error(EJSS_ODE_SOLVERS.ERROR.INTERNAL_SOLVER_ERROR,"Error when stepping the solver at max step at "+state[mTimeIndex])}doTheInterpolation(max_t,state);return max_t-tBegin}function stepWithoutEvents(){var state=mODE.getState();var rate=mSolverEngine.getCurrentRate()
;var tBegin=state[mTimeIndex];if(tBegin+rate[mTimeIndex]==tBegin)return 0;var tEnd=state[mTimeIndex]+mStepSize;var max_t=mSolverEngine.getMaximumTime(false);if(isNaN(max_t))return self.error(EJSS_ODE_SOLVERS.ERROR.INTERNAL_SOLVER_ERROR,"Error when stepping the solver at "+state[mTimeIndex]);var counter=0;if(mRunsForwards){while(max_t<tEnd){max_t=mSolverEngine.internalStep(false);if(isNaN(max_t))return self.error(EJSS_ODE_SOLVERS.ERROR.INTERNAL_SOLVER_ERROR,"Error when stepping the solver forwards at "+state[mTimeIndex]);if(++counter>mMaxInternalSteps){var initTime=state[mTimeIndex];var currentTime=mSolverEngine.bestInterpolate(tEnd,new Array(mDimension))[mTimeIndex];return self.error(EJSS_ODE_SOLVERS.ERROR.TOO_MANY_STEPS_ERROR,"The solver exceeded the maximum of "+mMaxInternalSteps+" internal steps\nat "+currentTime+", starting from "+initTime+" for an step of "+mStepSize)}}}else{while(max_t>tEnd){max_t=mSolverEngine.internalStep(false);if(isNaN(max_t))return self.error(EJSS_ODE_SOLVERS.ERROR.INTERNAL_SOLVER_ERROR,"Error when stepping the solver backwards at "+state[mTimeIndex]);if(++counter>mMaxInternalSteps)return self.error(EJSS_ODE_SOLVERS.ERROR.TOO_MANY_STEPS_ERROR,"The solver exceeded the number of internal steps at "+state[mTimeIndex])}}doTheInterpolation(tEnd,state);return mStepSize}function maxStepWithEvents(){var state=mODE.getState();if(mZenoMaximumAllowedTimes>0&&mZenoCounter>mZenoMaximumAllowedTimes){if(callZenoAction(state))return 0}var tBegin=state[mTimeIndex];var rate=mSolverEngine.getCurrentRate();if(tBegin+rate[mTimeIndex]==tBegin)return 0;var max_t=mSolverEngine.getMaximumTime(mHasDiscontinuities);if(isNaN(max_t))return self.error(EJSS_ODE_SOLVERS.ERROR.INTERNAL_SOLVER_ERROR,"Error when stepping the solver at "+state[mTimeIndex]);if(tBegin==max_t){max_t=mSolverEngine.internalStep(mHasDiscontinuities);if(isNaN(max_t))return self.error(EJSS_ODE_SOLVERS.ERROR.INTERNAL_SOLVER_ERROR,"Error when stepping the solver forwards at "+state[mTimeIndex])}if(mLastEventData!=null){if(!isNaN(mLastEventData.getMaxAdvance())){max_t=mRunsForwards?Math.min(max_t,mLastEventData.getMaxAdvance()):Math.max(max_t,mLastEventData.getMaxAdvance())}}var tTest=mRunsForwards?Math.min(tBegin+mMaxEventStep,max_t):Math.max(tBegin-mMaxEventStep,max_t);while(true){var problem=null;mCurrentEventData=null;doTheInterpolation(tTest,mTest_ode_state);problem=self.findFirstEvent(state,tTest,mTest_ode_state);if(problem==null&&mDiscontinuityAtEnd!=null&&mDiscontinuityAtEnd.getTime()<=tTest)problem=mDiscontinuityAtEnd;if(problem==null){if(tTest==max_t){for(var i=0;i<mDimension;i++)state[i]=mTest_ode_state[i];updateEventsAndDiscontinuities(state[mTimeIndex]);return max_t-tBegin}tTest=mRunsForwards?Math.min(tTest+mMaxEventStep,max_t):Math.max(tTest-mMaxEventStep,max_t);continue}mCurrentEventData=problem;if(mUseBestInterpolation)mSolverEngine.bestInterpolate(problem.getTime(),state);else for(var i=0;i<mDimension;i++)state[i]=mTest_ode_state[i];var timeBefore=state[mTimeIndex];problem.action();self.reinitialize();state=mODE.getState();if(timeBefore!=state[mTimeIndex]){mZenoCounter=0;mLastEventData=null;mCurrentEventData=null;problem.reset(state);return problem.getTime()-tBegin}if(mLastEventData!=null){if(Math.abs(mLastEventDataTime-problem.getTime())<mProximityThreshold){mZenoCounter++}else mZenoCounter=0}mLastEventData=problem;mLastEventDataTime=problem.getTime();return problem.getTime()-tBegin}}function stepWithEvents(){var state=mODE.getState();if(mZenoMaximumAllowedTimes>0&&mZenoCounter>mZenoMaximumAllowedTimes){if(callZenoAction(state))return 0}var tBegin=state[mTimeIndex];var rate=mSolverEngine.getCurrentRate();if(tBegin+rate[mTimeIndex]==tBegin)return 0;var tEnd=tBegin+mStepSize;var max_t=mSolverEngine.getMaximumTime(mHasDiscontinuities);if(isNaN(max_t))return self.error(EJSS_ODE_SOLVERS.ERROR.INTERNAL_SOLVER_ERROR,"Error when stepping the solver at "+state[mTimeIndex]);var tTest=mRunsForwards?Math.min(tBegin+mMaxEventStep,tEnd):Math.max(tBegin-mMaxEventStep,tEnd);var counter=0;while(true){var problem=null;mCurrentEventData=null;var notYetThere=mRunsForwards?max_t<tTest:max_t>tTest;if(notYetThere){mSolverEngine.bestInterpolate(max_t,mTest_ode_state);problem=self.findFirstEvent(state,max_t,mTest_ode_state);if(problem==null)problem=mDiscontinuityAtEnd;if(problem==null){for(var i=0;i<mDimension;i++)state[i]=mTest_ode_state[i];updateEventsAndDiscontinuities(state[mTimeIndex]);max_t=mSolverEngine.internalStep(mHasDiscontinuities);if(isNaN(max_t))return self.error(EJSS_ODE_SOLVERS.ERROR.INTERNAL_SOLVER_ERROR,"Error when stepping the solver looking for an event at "+state[mTimeIndex]);if(++counter>mMaxInternalSteps)return self.error(EJSS_ODE_SOLVERS.ERROR.TOO_MANY_STEPS_ERROR,"The solver exceeded the number of internal steps at "+state[mTimeIndex]);continue}}else{doTheInterpolation(tTest,mTest_ode_state);problem=self.findFirstEvent(state,tTest,mTest_ode_state);if(problem==null&&mDiscontinuityAtEnd!=null&&mDiscontinuityAtEnd.time<=tTest)problem=mDiscontinuityAtEnd;if(problem==null){if(tTest==tEnd){for(var i=0;i<mDimension;i++)state[i]=mTest_ode_state[i];updateEventsAndDiscontinuities(state[mTimeIndex]);return tEnd-tBegin}tTest=mRunsForwards?Math.min(tTest+mMaxEventStep,tEnd):Math.max(tTest-mMaxEventStep,tEnd);continue}}mCurrentEventData=problem;if(mUseBestInterpolation)mSolverEngine.bestInterpolate(problem.getTime(),state);else for(var i=0;i<mDimension;i++)state[i]=mTest_ode_state[i];var timeBefore=state[mTimeIndex];var wantsToQuit=problem.action();self.reinitialize();counter=0;state=mODE.getState();if(timeBefore!=state[mTimeIndex]){mZenoCounter=0;mLastEventData=null;mCurrentEventData=null;problem.reset(state);return problem.getTime()-tBegin}if(mLastEventData!=null){if(Math.abs(mLastEventDataTime-problem.getTime())<mProximityThreshold){mZenoCounter++;if(mCoalesceCloseEvents)wantsToQuit=false}else mZenoCounter=0}mLastEventData=problem;mLastEventDataTime=problem.getTime();if(wantsToQuit)return problem.getTime()-tBegin;if(mZenoMaximumAllowedTimes>0&&mZenoCounter>mZenoMaximumAllowedTimes){if(callZenoAction(state))return problem.getTime()-tBegin}mDiscontinuityAtEnd=null;max_t=mSolverEngine.getMaximumTime(mHasDiscontinuities);if(!isNaN(problem.getMaxAdvance())){max_t=mRunsForwards?Math.min(max_t,problem.getMaxAdvance()):Math.max(max_t,problem.getMaxAdvance())}if(isNaN(max_t))return self.error(EJSS_ODE_SOLVERS.ERROR.INTERNAL_SOLVER_ERROR,"Error when stepping the solver after an event at "+state[mTimeIndex])}}function updateEventsAndDiscontinuities(time){var i,length;length=mEventList.length;for(i=0;i<length;i++){var data=mEventList[i];data.findPosition(time,data.getH())}length=mDiscontinuityList.length;for(i=0;i<length;i++){var data=mDiscontinuityList[i];data.findPosition(time,data.getH())}}function callZenoAction(state){if(mZenoList.length<=0){self.error(EJSS_ODE_SOLVERS.ERROR.ZENO_EFFECT,"A Zeno-like effect has been detected.\nLast event was "+mLastEventData.getProblem()+" which took place at "+mLastEventDataTime);return true}var returnAtZeno=false;var i;var length=mZenoList.length;for(i=0;i<length;i++){var listener=mZenoList[i];if(listener.zenoEffectAction(mLastEventData.getProblem(),state))returnAtZeno=true}mZenoCounter=0;return returnAtZeno}self.findFirstEvent=function(current_state,tFinal,final_state){var i,length;mNumberOfAttempts=0;var happensAtT1=happensRightNow(current_state[mTimeIndex],final_state,mHappened,"at t1");if(happensAtT1!=null){happensAtT1.time=current_state[mTimeIndex];happensAtT1.maxAdvance=tFinal;for(i=0;i<mDimension;i++)final_state[i]=current_state[i];return happensAtT1}if(mHappened.length<=0)return null;var doItAgain=true;length=mEventList.length;for(i=0;i<length;i++){var eventData=mEventList[i];eventData.setHAfter(eventData.getH())}while(doItAgain){mNumberOfAttempts++;var tTest=nextPointToCheck(mHappened,current_state[mTimeIndex],tFinal);doTheInterpolation(tTest,mIntermediate_ode_state);var shortDurationEvent=happensRightNow(current_state[mTimeIndex],mIntermediate_ode_state,mTemp_list,"short");if(shortDurationEvent!=null){shortDurationEvent.time=current_state[mTimeIndex];shortDurationEvent.maxAdvance=tTest;for(i=0;i<mDimension;i++)final_state[i]=current_state[i];return shortDurationEvent}if(mTemp_list.length<=0){var happensInTtest=null;length=mHappened.length;for(i=0;i<length;i++){var eventData=mHappened[i];if(eventData.getCurrentPosition()==EJSS_ODE_SOLVERS.ProblemData.POSITIVE){if(eventData.getH()<eventData.getEvent().getTolerance()){happensInTtest=eventData;break}}else{if(eventData.getH()>-eventData.getEvent().getTolerance()){happensInTtest=eventData;break}}}if(happensInTtest!=null){happensInTtest.time=tTest;happensInTtest.maxAdvance=tFinal;for(i=0;i<mDimension;i++)final_state[i]=mIntermediate_ode_state[i];return happensInTtest}for(i=0;i<mDimension;i++)current_state[i]=mIntermediate_ode_state[i];length=mEventList.length;for(i=0;i<length;i++){var eventData=mEventList[i];eventData.findPosition(current_state[mTimeIndex],eventData.getH())}var happensNowInTtest=happensRightNow(current_state[mTimeIndex],final_state,mHappened,"at tTest");if(happensNowInTtest!=null){happensNowInTtest.time=current_state[mTimeIndex];happensNowInTtest.maxAdvance=tFinal;for(i=0;i<mDimension;i++)final_state[i]=current_state[i];return happensNowInTtest}}else{var notPreviousFound=true;var happensInTtest=null;length=mTemp_list.length;for(i=0;i<length;i++){var data=mTemp_list[i];if(data.getCurrentPosition()==EJSS_ODE_SOLVERS.ProblemData.POSITIVE){if(data.getH()<=-data.getEvent().getTolerance()){notPreviousFound=false;break}happensInTtest=data}else{if(data.getH()>=data.getEvent().getTolerance()){notPreviousFound=false;break}happensInTtest=data}}if(notPreviousFound&&happensInTtest!=null){happensInTtest.time=tTest;happensInTtest.maxAdvance=tFinal;for(i=0;i<mDimension;i++)final_state[i]=mIntermediate_ode_state[i];return happensInTtest}tFinal=tTest;for(i=0;i<mDimension;i++)final_state[i]=mIntermediate_ode_state[i];length=mEventList.length;for(i=0;i<length;i++){var eventData=mEventList[i];eventData.setHAfter(eventData.getH())}mHappened=[];length=mTemp_list.length;for(i=0;i<length;i++)mHappened.push(mTemp_list[i])}length=mHappened.length;for(i=0;i<length;i++){var data=mHappened[i];if(mNumberOfAttempts>data.getEvent().getMaxIterations()){doItAgain=false;break}}}var remaining=mHappened[0];self.error(EJSS_ODE_SOLVERS.ERROR.EVENT_NOT_FOUND,"Warning : Event not found after "+mNumberOfAttempts+" attempts at t="+current_state[mTimeIndex]+" h="+remaining.getH()+".\nPlease check the code of your event, decrease the initial step size, the tolerance of the solver,"+"\nor the event maximum step, or increase the maximum number of attempts."+"\nFirst event remaining in the queue: "+remaining.getEvent());remaining.setTime((current_state[mTimeIndex]+tFinal)/2);remaining.setMaxAdvance(Number.NaN);mSolverEngine.bestInterpolate(remaining.time,final_state);return remaining};function happensRightNow(currentTime,final_state,list,id){list.splice(0,list.length);var length=mEventList.length;for(var i=0;i<length;i++){var eventData=mEventList[i];eventData.setH(eventData.getEvent().evaluate(final_state));switch(eventData.getCurrentPosition()){default:case EJSS_ODE_SOLVERS.ProblemData.POSITIVE:if(eventData.getH()<=0)list.push(eventData);break;case EJSS_ODE_SOLVERS.ProblemData.SMALL_POSITIVE:if(eventData.getH()<=0&&(eventData.hasPositiveFlag()||eventData.getEventType()==EJSS_ODE_SOLVERS.EVENT_TYPE.STATE_EVENT))return eventData;break;case EJSS_ODE_SOLVERS.ProblemData.ZERO:if(eventData.getH()<0){if(eventData.hasPositiveFlag()||eventData.getEventType()==EJSS_ODE_SOLVERS.EVENT_TYPE.STATE_EVENT)return eventData}else if(eventData.getH()>0){if(eventData.hasNegativeFlag()&&eventData.getEventType()==EJSS_ODE_SOLVERS.EVENT_TYPE.CROSSING_EVENT)return eventData}break;case EJSS_ODE_SOLVERS.ProblemData.SMALL_NEGATIVE:if(eventData.getEventType()==EJSS_ODE_SOLVERS.EVENT_TYPE.STATE_EVENT){if(eventData.getH()<=-eventData.getEvent().getTolerance())return eventData}else if(eventData.getEventType()==EJSS_ODE_SOLVERS.EVENT_TYPE.CROSSING_EVENT){if(eventData.hasNegativeFlag()&&eventData.getH()>=0)return eventData}break;case EJSS_ODE_SOLVERS.ProblemData.NEGATIVE:if(eventData.getEventType()==EJSS_ODE_SOLVERS.EVENT_TYPE.CROSSING_EVENT){if(eventData.getH()>=0)list.push(eventData)}else if(eventData.getEventType()==EJSS_ODE_SOLVERS.EVENT_TYPE.STATE_EVENT){self.error(EJSS_ODE_SOLVERS.ERROR.ILLEGAL_EVENT_STATE,"The system started from an illegal state at "+currentTime+" for the state event "+eventData.getEvent());return eventData}break}}return null}function nextPointToCheck(list,t1,t2){var i,length=list.length;var hB,tFirst=t2,dt=t2-t1,tMiddle=(t1+t2)/2;if(mRunsForwards){for(i=0;i<length;i++){var eventData=list[i];switch(eventData.getEvent().getRootFindingMethod()){default:case EJSS_ODE_SOLVERS.EVENT_METHOD.BISECTION:tFirst=Math.min(tFirst,tMiddle);break;case EJSS_ODE_SOLVERS.EVENT_METHOD.SECANT:hB=eventData.getHBefore();tFirst=Math.min(tFirst,t1-hB*dt/(eventData.getHAfter()-hB));break}}}else{for(i=0;i<length;i++){var eventData=list[i];switch(eventData.getEvent().getRootFindingMethod()){default:case EJSS_ODE_SOLVERS.EVENT_METHOD.BISECTION:tFirst=Math.max(tFirst,tMiddle);break;case EJSS_ODE_SOLVERS.EVENT_METHOD.SECANT:hB=eventData.getHBefore();tFirst=Math.max(tFirst,t1-hB*dt/(eventData.getHAfter()-hB));break}}}return tFirst}if(mODE.getDelays){mDDEdiscontinuity=EJSS_ODE_SOLVERS.ddeDiscontinuity(self,mODE)}mSolverEngine.setODE(self,mODE);return self};var EJSS_ODE_SOLVERS=EJSS_ODE_SOLVERS||{};EJSS_ODE_SOLVERS.BogackiShampine23={B3_1:2/9,B3_2:1/3,B3_3:4/9,B2_1:7/24,B2_2:1/4,B2_3:1/3,B2_4:1/8};EJSS_ODE_SOLVERS.bogackiShampine23=function(){var self=EJSS_ODE_SOLVERS.solverEngineDiscreteTimeAdaptive(3);var mRate2,mRate3,mOrder2;var superAllocateOtherArrays=self.allocateOtherArrays;self.getNumberOfEvaluations=function(){return 3};self.allocateOtherArrays=function(){superAllocateOtherArrays();mRate2=new Array(self.getDimension());mRate3=new Array(self.getDimension());mOrder2=new Array(self.getDimension())};self.computeIntermediateStep=function(step,state){var halfStep=step/2;var ode=self.getODE();var initialState=self.getInitialState();var initialRate=self.getInitialRate();var dimension=self.getDimension();var timeIndex=dimension-1;var CTS=EJSS_ODE_SOLVERS.BogackiShampine23;var i;for(i=0;i<dimension;i++)state[i]=initialState[i]+halfStep*initialRate[i];ode.getRate(state,mRate2);var threeQuarterStep=.75*step;for(i=0;i<dimension;i++)state[i]=initialState[i]+threeQuarterStep*mRate2[i];ode.getRate(state,mRate3);for(i=0;i<timeIndex;i++)state[i]=initialState[i]+step*(CTS.B3_1*initialRate[i]+CTS.B3_2*mRate2[i]+CTS.B3_3*mRate3[i]);state[timeIndex]=self.getInitialTime()+step*initialRate[timeIndex]};self.computeCarefulIntermediateStep=function(eventSolver,step,state){var halfStep=step/2;var ode=self.getODE();var initialState=self.getInitialState();var initialRate=self.getInitialRate();var dimension=self.getDimension();var timeIndex=dimension-1;var CTS=EJSS_ODE_SOLVERS.BogackiShampine23;var CODE=EJSS_ODE_SOLVERS.DISCONTINUITY_CODE;var i;for(i=0;i<dimension;i++)state[i]=initialState[i]+halfStep*initialRate[i];switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}ode.getRate(state,mRate2);var threeQuarterStep=.75*step;for(i=0;i<dimension;i++)state[i]=initialState[i]+threeQuarterStep*mRate2[i];switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}ode.getRate(state,mRate3);for(i=0;i<timeIndex;i++)state[i]=initialState[i]+step*(CTS.B3_1*initialRate[i]+CTS.B3_2*mRate2[i]+CTS.B3_3*mRate3[i]);state[timeIndex]=self.getInitialTime()+step*initialRate[timeIndex];return eventSolver.checkDiscontinuity(state,true)};self.computeFinalRateAndCreateIntervalData=function(){var ode=self.getODE();var initialState=self.getInitialState();var initialRate=self.getInitialRate();var finalState=self.getFinalState();var finalRate=self.getFinalRate();return EJSS_ODE_INTERPOLATION.hermiteIntervalData(initialState,initialRate,finalState,finalRate)};self.computeApproximation=function(step){var ode=self.getODE();var timeIndex=self.getTimeIndex();var initialState=self.getInitialState();var initialRate=self.getInitialRate();var finalState=self.getFinalState();var finalRate=self.getFinalRate();ode.getRate(finalState,finalRate);var CTS=EJSS_ODE_SOLVERS.BogackiShampine23;for(var i=0;i<timeIndex;i++)mOrder2[i]=initialState[i]+step*(CTS.B2_1*initialRate[i]+CTS.B2_2*mRate2[i]+CTS.B2_3*mRate3[i]+CTS.B2_4*finalRate[i]);mOrder2[timeIndex]=self.getInitialTime()+step*initialRate[timeIndex];return self.computeError(mOrder2)};return self};var EJSS_ODE_SOLVERS=EJSS_ODE_SOLVERS||{};EJSS_ODE_SOLVERS.CashKarp45={A_11:1/5,A_21:3/40,A_22:9/40,A_31:3/10,A_32:-9/10,A_33:6/5,A_41:-11/54,A_42:5/2,A_43:-70/27,A_44:35/27,A_51:1631/55296,A_52:175/512,A_53:575/13824,A_54:44275/110592,A_55:253/4096,B4_1:2825/27648,B4_2:0,B4_3:18575/48384,B4_4:13525/55296,B4_5:277/14336,B4_6:1/4,B5_1:37/378,B5_2:0,B5_3:250/621,B5_4:125/594,B5_5:0,B5_6:512/1771};EJSS_ODE_SOLVERS.cashKarp45=function(){var self=EJSS_ODE_SOLVERS.solverEngineDiscreteTimeAdaptive(5);var mRate2,mRate3,mRate4,mRate5,mRate6,mOrder4;var superAllocateOtherArrays=self.allocateOtherArrays;self.getNumberOfEvaluations=function(){return 6};self.allocateOtherArrays=function(){superAllocateOtherArrays();mRate2=new Array(self.getDimension());mRate3=new Array(self.getDimension());mRate4=new Array(self.getDimension());mRate5=new Array(self.getDimension());mRate6=new Array(self.getDimension());mOrder4=new Array(self.getDimension())};self.computeIntermediateStep=function(step,state){var ode=self.getODE();var initialState=self.getInitialState();var initialRate=self.getInitialRate();var dimension=self.getDimension();var timeIndex=dimension-1;var CTS=EJSS_ODE_SOLVERS.CashKarp45;var i;for(i=0;i<dimension;i++)state[i]=initialState[i]+step*CTS.A_11*initialRate[i];ode.getRate(state,mRate2);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_21*initialRate[i]+CTS.A_22*mRate2[i]);ode.getRate(state,mRate3);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_31*initialRate[i]+CTS.A_32*mRate2[i]+CTS.A_33*mRate3[i]);ode.getRate(state,mRate4);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_41*initialRate[i]+CTS.A_42*mRate2[i]+CTS.A_43*mRate3[i]+CTS.A_44*mRate4[i]);ode.getRate(state,mRate5);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_51*initialRate[i]+CTS.A_52*mRate2[i]+CTS.A_53*mRate3[i]+CTS.A_54*mRate4[i]+CTS.A_55*mRate5[i]);ode.getRate(state,mRate6);for(i=0;i<timeIndex;i++)state[i]=initialState[i]+step*(CTS.B5_1*initialRate[i]+CTS.B5_2*mRate2[i]+CTS.B5_3*mRate3[i]+CTS.B5_4*mRate4[i]+CTS.B5_5*mRate5[i]+CTS.B5_6*mRate6[i]);state[timeIndex]=self.getInitialTime()+step*initialRate[timeIndex]};self.computeCarefulIntermediateStep=function(eventSolver,step,state){var ode=self.getODE();var initialState=self.getInitialState();var initialRate=self.getInitialRate();var dimension=self.getDimension();var timeIndex=dimension-1;var CTS=EJSS_ODE_SOLVERS.CashKarp45;var CODE=EJSS_ODE_SOLVERS.DISCONTINUITY_CODE;var i;for(i=0;i<dimension;i++)state[i]=initialState[i]+step*CTS.A_11*initialRate[i];switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}ode.getRate(state,mRate2);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_21*initialRate[i]+CTS.A_22*mRate2[i]);switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}ode.getRate(state,mRate3);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_31*initialRate[i]+CTS.A_32*mRate2[i]+CTS.A_33*mRate3[i]);switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}ode.getRate(state,mRate4);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_41*initialRate[i]+CTS.A_42*mRate2[i]+CTS.A_43*mRate3[i]+CTS.A_44*mRate4[i]);switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}ode.getRate(state,mRate5);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_51*initialRate[i]+CTS.A_52*mRate2[i]+CTS.A_53*mRate3[i]+CTS.A_54*mRate4[i]+CTS.A_55*mRate5[i]);switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}ode.getRate(state,mRate6);for(i=0;i<timeIndex;i++)state[i]=initialState[i]+step*(CTS.B5_1*initialRate[i]+CTS.B5_2*mRate2[i]+CTS.B5_3*mRate3[i]+CTS.B5_4*mRate4[i]+CTS.B5_5*mRate5[i]+CTS.B5_6*mRate6[i]);state[timeIndex]=self.getInitialTime()+step*initialRate[timeIndex];return eventSolver.checkDiscontinuity(state,true)};self.computeFinalRateAndCreateIntervalData=function(){var ode=self.getODE();var initialState=self.getInitialState();var initialRate=self.getInitialRate();var finalState=self.getFinalState();var finalRate=self.getFinalRate();ode.getRate(finalState,finalRate);return EJSS_ODE_INTERPOLATION.bootstrap2IntervalData(initialState,initialRate,finalState,finalRate,ode)};self.computeApproximation=function(step){var timeIndex=self.getTimeIndex();var initialState=self.getInitialState();var initialRate=self.getInitialRate();var CTS=EJSS_ODE_SOLVERS.CashKarp45;for(var i=0;i<timeIndex;i++)mOrder4[i]=initialState[i]+step*(CTS.B4_1*initialRate[i]+CTS.B4_2*mRate2[i]+CTS.B4_3*mRate3[i]+CTS.B4_4*mRate4[i]+CTS.B4_5*mRate5[i]+CTS.B4_6*mRate6[i]);mOrder4[timeIndex]=self.getInitialTime()+step*initialRate[timeIndex];return self.computeError(mOrder4)};return self};var EJSS_ODE_SOLVERS=EJSS_ODE_SOLVERS||{};EJSS_ODE_SOLVERS.DoPri5={A_11:1/5,A_21:3/40,A_22:9/40,A_31:44/45,A_32:-56/15,A_33:32/9,A_41:19372/6561,A_42:-25360/2187,A_43:64448/6561,A_44:-212/729,A_51:9017/3168,A_52:-355/33,A_53:46732/5247,A_54:49/176,A_55:-5103/18656,B5_1:35/384,B5_2:0,B5_3:500/1113,B5_4:125/192,B5_5:-2187/6784,B5_6:11/84,D_1:-12715105075/11282082432,D_2:0,D_3:87487479700/32700410799,D_4:-10690763975/1880347072,D_5:701980252875/199316789632,D_6:-1453857185/822651844,D_7:69997945/29380423,E_1:71/57600,E_2:0,E_3:-71/16695,E_4:71/1920,E_5:-17253/339200,E_6:22/525,E_7:-1/40};EJSS_ODE_SOLVERS.doPri5=function(){var self=EJSS_ODE_SOLVERS.solverEngineDiscreteTimeAdaptive(5);var mRate2,mRate3,mRate4,mRate5,mRate6,mCoeffs;var superAllocateOtherArrays=self.allocateOtherArrays;self.getNumberOfEvaluations=function(){return 6};self.allocateOtherArrays=function(){superAllocateOtherArrays();var dim=self.getDimension();mRate2=new Array(dim);mRate3=new Array(dim);mRate4=new Array(dim);mRate5=new Array(dim);mRate6=new Array(dim);mCoeffs=new Array(5);for(var i=0;i<5;i++)mCoeffs[i]=new Array(dim)};self.computeIntermediateStep=function(step,state){var ode=self.getODE();var initialState=self.getInitialState();var initialRate=self.getInitialRate();var dimension=self.getDimension();var timeIndex=dimension-1;var CTS=EJSS_ODE_SOLVERS.DoPri5;var i;for(i=0;i<dimension;i++)state[i]=initialState[i]+step*CTS.A_11*initialRate[i];ode.getRate(state,mRate2);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_21*initialRate[i]+CTS.A_22*mRate2[i]);ode.getRate(state,mRate3);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_31*initialRate[i]+CTS.A_32*mRate2[i]+CTS.A_33*mRate3[i]);ode.getRate(state,mRate4);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_41*initialRate[i]+CTS.A_42*mRate2[i]+CTS.A_43*mRate3[i]+CTS.A_44*mRate4[i]);ode.getRate(state,mRate5);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_51*initialRate[i]+CTS.A_52*mRate2[i]+CTS.A_53*mRate3[i]+CTS.A_54*mRate4[i]+CTS.A_55*mRate5[i]);ode.getRate(state,mRate6);for(i=0;i<timeIndex;i++)state[i]=initialState[i]+step*(CTS.B5_1*initialRate[i]+CTS.B5_2*mRate2[i]+CTS.B5_3*mRate3[i]+CTS.B5_4*mRate4[i]+CTS.B5_5*mRate5[i]+CTS.B5_6*mRate6[i]);state[timeIndex]=self.getInitialTime()+step*initialRate[timeIndex]};self.computeCarefulIntermediateStep=function(eventSolver,step,state){var ode=self.getODE();var initialState=self.getInitialState();var initialRate=self.getInitialRate();var dimension=self.getDimension();var timeIndex=dimension-1;var CTS=EJSS_ODE_SOLVERS.DoPri5;var CODE=EJSS_ODE_SOLVERS.DISCONTINUITY_CODE;var i;for(i=0;i<dimension;i++)state[i]=initialState[i]+step*CTS.A_11*initialRate[i];switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}ode.getRate(state,mRate2);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_21*initialRate[i]+CTS.A_22*mRate2[i]);switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}ode.getRate(state,mRate3);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_31*initialRate[i]+CTS.A_32*mRate2[i]+CTS.A_33*mRate3[i]);switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}ode.getRate(state,mRate4);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_41*initialRate[i]+CTS.A_42*mRate2[i]+CTS.A_43*mRate3[i]+CTS.A_44*mRate4[i]);switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}ode.getRate(state,mRate5);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_51*initialRate[i]+CTS.A_52*mRate2[i]+CTS.A_53*mRate3[i]+CTS.A_54*mRate4[i]+CTS.A_55*mRate5[i]);switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}ode.getRate(state,mRate6);for(i=0;i<timeIndex;i++)state[i]=initialState[i]+step*(CTS.B5_1*initialRate[i]+CTS.B5_2*mRate2[i]+CTS.B5_3*mRate3[i]+CTS.B5_4*mRate4[i]+CTS.B5_5*mRate5[i]+CTS.B5_6*mRate6[i]);state[timeIndex]=self.getInitialTime()+step*initialRate[timeIndex];return eventSolver.checkDiscontinuity(state,true)};self.computeFinalRateAndCreateIntervalData=function(){var ode=self.getODE();var initialState=self.getInitialState();var initialRate=self.getInitialRate();var finalState=self.getFinalState();var finalRate=self.getFinalRate();var CTS=EJSS_ODE_SOLVERS.DoPri5;var dimension=self.getDimension();var timeIndex=dimension-1;var dt=finalState[timeIndex]-initialState[timeIndex];for(var i=0;i<dimension;i++){var initStateI=initialState[i];var initRateI=initialRate[i];var finalRateI=finalRate[i];mCoeffs[0][i]=initStateI;var coeff1i=finalState[i]-initStateI;var coeff2i=dt*initRateI-coeff1i;mCoeffs[3][i]=coeff1i-dt*finalRateI-coeff2i;mCoeffs[4][i]=dt*(CTS.D_1*initRateI+CTS.D_2*mRate2[i]+CTS.D_3*mRate3[i]+CTS.D_4*mRate4[i]+CTS.D_5*mRate5[i]+CTS.D_6*mRate6[i]+CTS.D_7*finalRateI);mCoeffs[1][i]=coeff1i;mCoeffs[2][i]=coeff2i}return EJSS_ODE_INTERPOLATION.dopri5IntervalData(initialState,finalState,mCoeffs)};self.computeApproximation=function(step){var ode=self.getODE();var initialState=self.getInitialState();var initialRate=self.getInitialRate();var finalState=self.getFinalState();var finalRate=self.getFinalRate();var absTol=self.getAbsTol();var relTol=self.getRelTol();var CTS=EJSS_ODE_SOLVERS.DoPri5;var dimension=self.getDimension();ode.getRate(finalState,finalRate);var error=0;for(var i=0;i<dimension;i++){var sk=absTol[i]+relTol[i]*Math.max(Math.abs(finalState[i]),Math.abs(initialState[i]));var errorI=(CTS.E_1*initialRate[i]+CTS.E_2*mRate2[i]+CTS.E_3*mRate3[i]+CTS.E_4*mRate4[i]+CTS.E_5*mRate5[i]+CTS.E_6*mRate6[i]+CTS.E_7*finalRate[i])/sk;error+=errorI*errorI}return Math.sqrt(error/dimension)};return self};var EJSS_ODE_SOLVERS=EJSS_ODE_SOLVERS||{};EJSS_ODE_SOLVERS.DoPri853={A_11:.05260015195876773,A_21:.0197250569845379,A_22:.0591751709536137,A_31:.02958758547680685,A_32:0,A_33:.08876275643042054,A_41:.2413651341592667,A_42:0,A_43:-.8845494793282861,A_44:.924834003261792,A_51:.037037037037037035,A_52:0,A_53:0,A_54:.17082860872947386,A_55:.12546768756682242,A_61:.037109375,A_62:0,A_63:0,A_64:.17025221101954405,A_65:.06021653898045596,A_66:-.017578125,A_71:.03709200011850479,A_72:0,A_73:0,A_74:.17038392571223998,A_75:.10726203044637328,A_76:-.015319437748624402,A_77:.008273789163814023,A_81:.6241109587160757,A_82:0,A_83:0,A_84:-3.3608926294469414,A_85:-.868219346841726,A_86:27.59209969944671,A_87:20.154067550477894,A_88:-43.48988418106996,A_91:.47766253643826434,A_92:0,A_93:0,A_94:-2.4881146199716677,A_95:-.590290826836843,A_96:21.230051448181193,A_97:15.279233632882423,A_98:-33.28821096898486,A_99:-.020331201708508627,A_101:-.9371424300859873,A_102:0,A_103:0,A_104:5.186372428844064,A_105:1.0914373489967295,A_106:-8.149787010746927,A_107:-18.52006565999696,A_108:22.739487099350505,A_109:2.4936055526796523,A_1010:-3.0467644718982196,A_111:2.273310147516538,A_112:0,A_113:0,A_114:-10.53449546673725,A_115:-2.0008720582248625,A_116:-17.9589318631188,A_117:27.94888452941996,A_118:-2.8589982771350235,A_119:-8.87285693353063,A_1110:12.360567175794303,A_1111:.6433927460157636,B8_1:.054293734116568765,B8_2:0,B8_3:0,B8_4:0,B8_5:0,B8_6:4.450312892752409,
B8_7:1.8915178993145003,B8_8:-5.801203960010585,B8_9:.3111643669578199,B8_10:-.1521609496625161,B8_11:.20136540080403034,B8_12:.04471061572777259,AD13_1:.056167502283047954,AD13_2:0,AD13_3:0,AD13_4:0,AD13_5:0,AD13_6:0,AD13_7:.25350021021662483,AD13_8:-.2462390374708025,AD13_9:-.12419142326381637,AD13_10:.15329179827876568,AD13_11:.00820105229563469,AD13_12:.007567897660545699,AD13_13:-.008298,AD14_1:.03183464816350214,AD14_2:0,AD14_3:0,AD14_4:0,AD14_5:0,AD14_6:.028300909672366776,AD14_7:.053541988307438566,AD14_8:-.05492374857139099,AD14_9:0,AD14_10:0,AD14_11:-.00010834732869724932,AD14_12:.0003825710908356584,AD14_13:-.00034046500868740456,AD14_14:.1413124436746325,AD15_1:-.42889630158379194,AD15_2:0,AD15_3:0,AD15_4:0,AD15_5:0,AD15_6:-4.697621415361164,AD15_7:7.683421196062599,AD15_8:4.06898981839711,AD15_9:.3567271874552811,AD15_10:0,AD15_11:0,AD15_12:0,AD15_13:-.0013990241651590145,AD15_14:2.9475147891527724,AD15_15:-9.15095847217987,D4_1:-8.428938276109013,D4_2:0,D4_3:0,D4_4:0,D4_5:0,D4_6:.5667149535193777,D4_7:-3.0689499459498917,D4_8:2.38466765651207,D4_9:2.117034582445028,D4_10:-.871391583777973,D4_11:2.2404374302607883,D4_12:.6315787787694688,D4_13:-.08899033645133331,D4_14:18.148505520854727,D4_15:-9.194632392478356,D4_16:-4.436036387594894,D5_1:10.427508642579134,D5_2:0,D5_3:0,D5_4:0,D5_5:0,D5_6:242.28349177525817,D5_7:165.20045171727028,D5_8:-374.5467547226902,D5_9:-22.113666853125306,D5_10:7.733432668472264,D5_11:-30.674084731089398,D5_12:-9.332130526430229,D5_13:15.697238121770845,D5_14:-31.139403219565178,D5_15:-9.35292435884448,D5_16:35.81684148639408,D6_1:19.985053242002433,D6_2:0,D6_3:0,D6_4:0,D6_5:0,D6_6:-387.0373087493518,D6_7:-189.17813819516758,D6_8:527.8081592054236,D6_9:-11.57390253995963,D6_10:6.8812326946963,D6_11:-1.0006050966910838,D6_12:.7777137798053443,D6_13:-2.778205752353508,D6_14:-60.19669523126412,D6_15:84.32040550667716,D6_16:11.99229113618279,D7_1:-25.69393346270375,D7_2:0,D7_3:0,D7_4:0,D7_5:0,D7_6:-154.18974869023643,D7_7:-231.5293791760455,D7_8:357.6391179106141,D7_9:93.40532418362432,D7_10:-37.45832313645163,D7_11:104.0996495089623,D7_12:29.8402934266605,D7_13:-43.53345659001114,D7_14:96.32455395918828,D7_15:-39.17726167561544,D7_16:-149.72683625798564,E3_1:-.18980075407240762,E3_2:0,E3_3:0,E3_4:0,E3_5:0,E3_6:4.450312892752409,E3_7:1.8915178993145003,E3_8:-5.801203960010585,E3_9:-.42268232132379197,E3_10:-.1521609496625161,E3_11:.20136540080403034,E3_12:.022651792198360825,E5_1:.01312004499419488,E5_2:0,E5_3:0,E5_4:0,E5_5:0,E5_6:-1.2251564463762044,E5_7:-.4957589496572502,E5_8:1.6643771824549864,E5_9:-.35032884874997366,E5_10:.3341791187130175,E5_11:.08192320648511571,E5_12:-.022355307863886294};EJSS_ODE_SOLVERS.doPri853=function(){var self=EJSS_ODE_SOLVERS.solverEngineDiscreteTimeAdaptive(8);var mRate2,mRate3,mRate4,mRate5,mRate6,mRate7,mRate8,mRate9;var mRate10,mRate11,mRate12,mRate14,mRate15,mRate16,mAuxState;var mCoeffs;var superAllocateOtherArrays=self.allocateOtherArrays;self.getNumberOfEvaluations=function(){return 16};self.allocateOtherArrays=function(){superAllocateOtherArrays();var dim=self.getDimension();mRate2=new Array(dim);mRate3=new Array(dim);mRate4=new Array(dim);mRate5=new Array(dim);mRate6=new Array(dim);mRate7=new Array(dim);mRate8=new Array(dim);mRate9=new Array(dim);mRate10=new Array(dim);mRate11=new Array(dim);mRate12=new Array(dim);mRate13=new Array(dim);mRate14=new Array(dim);mRate15=new Array(dim);mRate16=new Array(dim);mAuxState=new Array(dim);mCoeffs=new Array(8);for(var i=0;i<8;i++)mCoeffs[i]=new Array(dim)};self.computeIntermediateStep=function(step,state){var ode=self.getODE();var initialState=self.getInitialState();var initialRate=self.getInitialRate();var dimension=self.getDimension();var timeIndex=dimension-1;var CTS=EJSS_ODE_SOLVERS.DoPri853;var i;for(i=0;i<dimension;i++)state[i]=initialState[i]+step*CTS.A_11*initialRate[i];ode.getRate(state,mRate2);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_21*initialRate[i]+CTS.A_22*mRate2[i]);ode.getRate(state,mRate3);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_31*initialRate[i]+CTS.A_32*mRate2[i]+CTS.A_33*mRate3[i]);ode.getRate(state,mRate4);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_41*initialRate[i]+CTS.A_42*mRate2[i]+CTS.A_43*mRate3[i]+CTS.A_44*mRate4[i]);ode.getRate(state,mRate5);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_51*initialRate[i]+CTS.A_52*mRate2[i]+CTS.A_53*mRate3[i]+CTS.A_54*mRate4[i]+CTS.A_55*mRate5[i]);ode.getRate(state,mRate6);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_61*initialRate[i]+CTS.A_62*mRate2[i]+CTS.A_63*mRate3[i]+CTS.A_64*mRate4[i]+CTS.A_65*mRate5[i]+CTS.A_66*mRate6[i]);ode.getRate(state,mRate7);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_71*initialRate[i]+CTS.A_72*mRate2[i]+CTS.A_73*mRate3[i]+CTS.A_74*mRate4[i]+CTS.A_75*mRate5[i]+CTS.A_76*mRate6[i]+CTS.A_77*mRate7[i]);ode.getRate(state,mRate8);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_81*initialRate[i]+CTS.A_82*mRate2[i]+CTS.A_83*mRate3[i]+CTS.A_84*mRate4[i]+CTS.A_85*mRate5[i]+CTS.A_86*mRate6[i]+CTS.A_87*mRate7[i]+CTS.A_88*mRate8[i]);ode.getRate(state,mRate9);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_91*initialRate[i]+CTS.A_92*mRate2[i]+CTS.A_93*mRate3[i]+CTS.A_94*mRate4[i]+CTS.A_95*mRate5[i]+CTS.A_96*mRate6[i]+CTS.A_97*mRate7[i]+CTS.A_98*mRate8[i]+CTS.A_99*mRate9[i]);ode.getRate(state,mRate10);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_101*initialRate[i]+CTS.A_102*mRate2[i]+CTS.A_103*mRate3[i]+CTS.A_104*mRate4[i]+CTS.A_105*mRate5[i]+CTS.A_106*mRate6[i]+CTS.A_107*mRate7[i]+CTS.A_108*mRate8[i]+CTS.A_109*mRate9[i]+CTS.A_1010*mRate10[i]);ode.getRate(state,mRate11);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_111*initialRate[i]+CTS.A_112*mRate2[i]+CTS.A_113*mRate3[i]+CTS.A_114*mRate4[i]+CTS.A_115*mRate5[i]+CTS.A_116*mRate6[i]+CTS.A_117*mRate7[i]+CTS.A_118*mRate8[i]+CTS.A_119*mRate9[i]+CTS.A_1110*mRate10[i]+CTS.A_1111*mRate11[i]);ode.getRate(state,mRate12);for(i=0;i<timeIndex;i++)state[i]=initialState[i]+step*(CTS.B8_1*initialRate[i]+CTS.B8_2*mRate2[i]+CTS.B8_3*mRate3[i]+CTS.B8_4*mRate4[i]+CTS.B8_5*mRate5[i]+CTS.B8_6*mRate6[i]+CTS.B8_7*mRate7[i]+CTS.B8_8*mRate8[i]+CTS.B8_9*mRate9[i]+CTS.B8_10*mRate10[i]+CTS.B8_11*mRate11[i]+CTS.B8_12*mRate12[i]);state[timeIndex]=self.getInitialTime()+step*initialRate[timeIndex]};self.computeCarefulIntermediateStep=function(eventSolver,step,state){var ode=self.getODE();var initialState=self.getInitialState();var initialRate=self.getInitialRate();var dimension=self.getDimension();var timeIndex=dimension-1;var CTS=EJSS_ODE_SOLVERS.DoPri853;var CODE=EJSS_ODE_SOLVERS.DISCONTINUITY_CODE;var i;for(i=0;i<dimension;i++)state[i]=initialState[i]+step*CTS.A_11*initialRate[i];switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}ode.getRate(state,mRate2);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_21*initialRate[i]+CTS.A_22*mRate2[i]);switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}ode.getRate(state,mRate3);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_31*initialRate[i]+CTS.A_32*mRate2[i]+CTS.A_33*mRate3[i]);switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}ode.getRate(state,mRate4);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_41*initialRate[i]+CTS.A_42*mRate2[i]+CTS.A_43*mRate3[i]+CTS.A_44*mRate4[i]);switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}ode.getRate(state,mRate5);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_51*initialRate[i]+CTS.A_52*mRate2[i]+CTS.A_53*mRate3[i]+CTS.A_54*mRate4[i]+CTS.A_55*mRate5[i]);switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}ode.getRate(state,mRate6);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_61*initialRate[i]+CTS.A_62*mRate2[i]+CTS.A_63*mRate3[i]+CTS.A_64*mRate4[i]+CTS.A_65*mRate5[i]+CTS.A_66*mRate6[i]);switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}ode.getRate(state,mRate7);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_71*initialRate[i]+CTS.A_72*mRate2[i]+CTS.A_73*mRate3[i]+CTS.A_74*mRate4[i]+CTS.A_75*mRate5[i]+CTS.A_76*mRate6[i]+CTS.A_77*mRate7[i]);switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}ode.getRate(state,mRate8);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_81*initialRate[i]+CTS.A_82*mRate2[i]+CTS.A_83*mRate3[i]+CTS.A_84*mRate4[i]+CTS.A_85*mRate5[i]+CTS.A_86*mRate6[i]+CTS.A_87*mRate7[i]+CTS.A_88*mRate8[i]);switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}ode.getRate(state,mRate9);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_91*initialRate[i]+CTS.A_92*mRate2[i]+CTS.A_93*mRate3[i]+CTS.A_94*mRate4[i]+CTS.A_95*mRate5[i]+CTS.A_96*mRate6[i]+CTS.A_97*mRate7[i]+CTS.A_98*mRate8[i]+CTS.A_99*mRate9[i]);switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}ode.getRate(state,mRate10);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_101*initialRate[i]+CTS.A_102*mRate2[i]+CTS.A_103*mRate3[i]+CTS.A_104*mRate4[i]+CTS.A_105*mRate5[i]+CTS.A_106*mRate6[i]+CTS.A_107*mRate7[i]+CTS.A_108*mRate8[i]+CTS.A_109*mRate9[i]+CTS.A_1010*mRate10[i]);switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}ode.getRate(state,mRate11);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_111*initialRate[i]+CTS.A_112*mRate2[i]+CTS.A_113*mRate3[i]+CTS.A_114*mRate4[i]+CTS.A_115*mRate5[i]+CTS.A_116*mRate6[i]+CTS.A_117*mRate7[i]+CTS.A_118*mRate8[i]+CTS.A_119*mRate9[i]+CTS.A_1110*mRate10[i]+CTS.A_1111*mRate11[i]);switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}ode.getRate(state,mRate12);for(i=0;i<timeIndex;i++)state[i]=initialState[i]+step*(CTS.B8_1*initialRate[i]+CTS.B8_2*mRate2[i]+CTS.B8_3*mRate3[i]+CTS.B8_4*mRate4[i]+CTS.B8_5*mRate5[i]+CTS.B8_6*mRate6[i]+CTS.B8_7*mRate7[i]+CTS.B8_8*mRate8[i]+CTS.B8_9*mRate9[i]+CTS.B8_10*mRate10[i]+CTS.B8_11*mRate11[i]+CTS.B8_12*mRate12[i]);state[timeIndex]=self.getInitialTime()+step*initialRate[timeIndex];return eventSolver.checkDiscontinuity(state,true)};self.computeFinalRateAndCreateIntervalData=function(){var ode=self.getODE();var initialState=self.getInitialState();var initialRate=self.getInitialRate();var finalState=self.getFinalState();var finalRate=self.getFinalRate();var CTS=EJSS_ODE_SOLVERS.DoPri853;var dimension=self.getDimension();var timeIndex=dimension-1;var i;ode.getRate(finalState,finalRate);var deltaTime=finalState[timeIndex]-initialState[timeIndex];for(i=0;i<dimension;i++)mAuxState[i]=initialState[i]+deltaTime*(CTS.AD13_1*initialRate[i]+CTS.AD13_2*mRate2[i]+CTS.AD13_3*mRate3[i]+CTS.AD13_4*mRate4[i]+CTS.AD13_5*mRate5[i]+CTS.AD13_6*mRate6[i]+CTS.AD13_7*mRate7[i]+CTS.AD13_8*mRate8[i]+CTS.AD13_9*mRate9[i]+CTS.AD13_10*mRate10[i]+CTS.AD13_11*mRate11[i]+CTS.AD13_12*mRate12[i]+CTS.AD13_13*finalRate[i]);ode.getRate(mAuxState,mRate14);for(i=0;i<dimension;i++)mAuxState[i]=initialState[i]+deltaTime*(CTS.AD14_1*initialRate[i]+CTS.AD14_2*mRate2[i]+CTS.AD14_3*mRate3[i]+CTS.AD14_4*mRate4[i]+CTS.AD14_5*mRate5[i]+CTS.AD14_6*mRate6[i]+CTS.AD14_7*mRate7[i]+CTS.AD14_8*mRate8[i]+CTS.AD14_9*mRate9[i]+CTS.AD14_10*mRate10[i]+CTS.AD14_11*mRate11[i]+CTS.AD14_12*mRate12[i]+CTS.AD14_13*finalRate[i]+CTS.AD14_14*mRate14[i]);ode.getRate(mAuxState,mRate15);for(i=0;i<dimension;i++)mAuxState[i]=initialState[i]+deltaTime*(CTS.AD15_1*initialRate[i]+CTS.AD15_2*mRate2[i]+CTS.AD15_3*mRate3[i]+CTS.AD15_4*mRate4[i]+CTS.AD15_5*mRate5[i]+CTS.AD15_6*mRate6[i]+CTS.AD15_7*mRate7[i]+CTS.AD15_8*mRate8[i]+CTS.AD15_9*mRate9[i]+CTS.AD15_10*mRate10[i]+CTS.AD15_11*mRate11[i]+CTS.AD15_12*mRate12[i]+CTS.AD15_13*finalRate[i]+CTS.AD15_14*mRate14[i]+CTS.AD15_15*mRate15[i]);ode.getRate(mAuxState,mRate16);for(i=0;i<dimension;i++){mCoeffs[0][i]=initialState[i];mCoeffs[1][i]=finalState[i]-initialState[i];mCoeffs[2][i]=deltaTime*initialRate[i]-mCoeffs[1][i];mCoeffs[3][i]=mCoeffs[1][i]-deltaTime*finalRate[i]-mCoeffs[2][i];mCoeffs[4][i]=deltaTime*(CTS.D4_1*initialRate[i]+CTS.D4_2*mRate2[i]+CTS.D4_3*mRate3[i]+CTS.D4_4*mRate4[i]+CTS.D4_5*mRate5[i]+CTS.D4_6*mRate6[i]+CTS.D4_7*mRate7[i]+CTS.D4_8*mRate8[i]+CTS.D4_9*mRate9[i]+CTS.D4_10*mRate10[i]+CTS.D4_11*mRate11[i]+CTS.D4_12*mRate12[i]+CTS.D4_13*finalRate[i]+CTS.D4_14*mRate14[i]+CTS.D4_15*mRate15[i]+CTS.D4_16*mRate16[i]);mCoeffs[5][i]=deltaTime*(CTS.D5_1*initialRate[i]+CTS.D5_2*mRate2[i]+CTS.D5_3*mRate3[i]+CTS.D5_4*mRate4[i]+CTS.D5_5*mRate5[i]+CTS.D5_6*mRate6[i]+CTS.D5_7*mRate7[i]+CTS.D5_8*mRate8[i]+CTS.D5_9*mRate9[i]+CTS.D5_10*mRate10[i]+CTS.D5_11*mRate11[i]+CTS.D5_12*mRate12[i]+CTS.D5_13*finalRate[i]+CTS.D5_14*mRate14[i]+CTS.D5_15*mRate15[i]+CTS.D5_16*mRate16[i]);mCoeffs[6][i]=deltaTime*(CTS.D6_1*initialRate[i]+CTS.D6_2*mRate2[i]+CTS.D6_3*mRate3[i]+CTS.D6_4*mRate4[i]+CTS.D6_5*mRate5[i]+CTS.D6_6*mRate6[i]+CTS.D6_7*mRate7[i]+CTS.D6_8*mRate8[i]+CTS.D6_9*mRate9[i]+CTS.D6_10*mRate10[i]+CTS.D6_11*mRate11[i]+CTS.D6_12*mRate12[i]+CTS.D6_13*finalRate[i]+CTS.D6_14*mRate14[i]+CTS.D6_15*mRate15[i]+CTS.D6_16*mRate16[i]);mCoeffs[7][i]=deltaTime*(CTS.D7_1*initialRate[i]+CTS.D7_2*mRate2[i]+CTS.D7_3*mRate3[i]+CTS.D7_4*mRate4[i]+CTS.D7_5*mRate5[i]+CTS.D7_6*mRate6[i]+CTS.D7_7*mRate7[i]+CTS.D7_8*mRate8[i]+CTS.D7_9*mRate9[i]+CTS.D7_10*mRate10[i]+CTS.D7_11*mRate11[i]+CTS.D7_12*mRate12[i]+CTS.D7_13*finalRate[i]+CTS.D7_14*mRate14[i]+CTS.D7_15*mRate15[i]+CTS.D7_16*mRate16[i])}return EJSS_ODE_INTERPOLATION.dopri853IntervalData(initialState,finalState,mCoeffs)};self.computeApproximation=function(step){var ode=self.getODE();var initialState=self.getInitialState();var initialRate=self.getInitialRate();var finalState=self.getFinalState();var finalRate=self.getFinalRate();var absTol=self.getAbsTol();var relTol=self.getRelTol();var CTS=EJSS_ODE_SOLVERS.DoPri853;var dimension=self.getDimension();var error3=0,error5=0;for(var i=0;i<dimension;i++){var sk=absTol[i]+relTol[i]*Math.max(Math.abs(finalState[i]),Math.abs(initialState[i]));var errorI3=(CTS.E3_1*initialRate[i]+CTS.E3_2*mRate2[i]+CTS.E3_3*mRate3[i]+CTS.E3_4*mRate4[i]+CTS.E3_5*mRate5[i]+CTS.E3_6*mRate6[i]+CTS.E3_7*mRate7[i]+CTS.E3_8*mRate8[i]+CTS.E3_9*mRate9[i]+CTS.E3_10*mRate10[i]+CTS.E3_11*mRate11[i]+CTS.E3_12*mRate12[i])/sk;error3+=errorI3*errorI3;var errorI5=(CTS.E5_1*initialRate[i]+CTS.E5_2*mRate2[i]+CTS.E5_3*mRate5[i]+CTS.E5_4*mRate4[i]+CTS.E5_5*mRate5[i]+CTS.E5_6*mRate6[i]+CTS.E5_7*mRate7[i]+CTS.E5_8*mRate8[i]+CTS.E5_9*mRate9[i]+CTS.E5_10*mRate10[i]+CTS.E5_11*mRate11[i]+CTS.E5_12*mRate12[i])/sk;error5+=errorI5*errorI5}var den=error5+.01*error3;if(den<=0)den=1;return Math.abs(step)*error5*Math.sqrt(1/(dimension*den))};return self};var EJSS_ODE_SOLVERS=EJSS_ODE_SOLVERS||{};EJSS_ODE_SOLVERS.Euler={};EJSS_ODE_SOLVERS.euler=function(){var self=EJSS_ODE_SOLVERS.solverEngineDiscreteTime();self.getNumberOfEvaluations=function(){return 1};self.computeIntermediateStep=function(step,state){var dimension=self.getDimension();var initialState=self.getInitialState();var initialRate=self.getInitialRate();for(var i=0;i<dimension;i++)state[i]=initialState[i]+step*initialRate[i]};self.computeCarefulIntermediateStep=function(eventSolver,step,state){self.computeIntermediateStep(step,state);return eventSolver.checkDiscontinuity(state,true)};self.computeFinalRateAndCreateIntervalData=function(){var ode=self.getODE();var initialState=self.getInitialState();var initialRate=self.getInitialRate();var finalState=self.getFinalState();var finalRate=self.getFinalRate();ode.getRate(finalState,finalRate);return EJSS_ODE_INTERPOLATION.eulerIntervalData(initialState,initialRate,finalState[self.getTimeIndex()])};return self};var EJSS_ODE_SOLVERS=EJSS_ODE_SOLVERS||{};EJSS_ODE_SOLVERS.EulerRichardson={};EJSS_ODE_SOLVERS.eulerRichardson=function(){var self=EJSS_ODE_SOLVERS.solverEngineDiscreteTime();var mRate2;self.getNumberOfEvaluations=function(){return 2};self.allocateOtherArrays=function(){mRate2=new Array(self.getDimension())};self.computeIntermediateStep=function(step,state){var halfStep=step/2;var ode=self.getODE();var initialState=self.getInitialState();var initialRate=self.getInitialRate();var dimension=self.getDimension();var timeIndex=dimension-1;var i;for(i=0;i<dimension;i++)state[i]=initialState[i]+halfStep*initialRate[i];ode.getRate(state,mRate2);for(i=0;i<timeIndex;i++)state[i]=initialState[i]+step*mRate2[i];state[timeIndex]=self.getInitialTime()+step*initialRate[timeIndex]};self.computeCarefulIntermediateStep=function(eventSolver,step,state){var halfStep=step/2;var ode=self.getODE();var initialState=self.getInitialState();var initialRate=self.getInitialRate();var dimension=self.getDimension();var timeIndex=dimension-1;var CODE=EJSS_ODE_SOLVERS.DISCONTINUITY_CODE;var i;for(i=0;i<dimension;i++)state[i]=initialState[i]+halfStep*initialRate[i];switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}ode.getRate(state,mRate2);for(i=0;i<timeIndex;i++)state[i]=initialState[i]+step*mRate2[i];state[timeIndex]=self.getInitialTime()+step*initialRate[timeIndex];return eventSolver.checkDiscontinuity(state,true)};self.computeFinalRateAndCreateIntervalData=function(){var ode=self.getODE();var initialState=self.getInitialState();var initialRate=self.getInitialRate();var finalState=self.getFinalState();var finalRate=self.getFinalRate();var timeIndex=self.getDimension()-1;ode.getRate(finalState,finalRate);return EJSS_ODE_INTERPOLATION.eulerRichardsonIntervalData(initialState,initialRate,finalState[timeIndex],mRate2)};return self};var EJSS_ODE_SOLVERS=EJSS_ODE_SOLVERS||{};EJSS_ODE_SOLVERS.Fehlberg8={};EJSS_ODE_SOLVERS.fehlberg8=function(){var self=EJSS_ODE_SOLVERS.solverEngineDiscreteTime();var mRate2,mRate3,mRate4,mRate5,mRate6,mRate7,mRate8,mRate9,mRate10,mRate11;self.getNumberOfEvaluations=function(){return 13};self.allocateOtherArrays=function(){mRate2=new Array(self.getDimension());mRate3=new Array(self.getDimension());mRate4=new Array(self.getDimension());mRate5=new Array(self.getDimension());mRate6=new Array(self.getDimension());mRate7=new Array(self.getDimension());mRate8=new Array(self.getDimension());mRate9=new Array(self.getDimension());mRate10=new Array(self.getDimension());mRate11=new Array(self.getDimension())};self.computeIntermediateStep=function(step,state){var ode=self.getODE();var initialState=self.getInitialState();var initialRate=self.getInitialRate();var dimension=self.getDimension();var timeIndex=dimension-1;var CTS=EJSS_ODE_SOLVERS.Fehlberg78;var i;for(i=0;i<dimension;i++)state[i]=initialState[i]+step*CTS.A_11*initialRate[i];ode.getRate(state,mRate2);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_21*initialRate[i]+CTS.A_22*mRate2[i]);ode.getRate(state,mRate3);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_31*initialRate[i]+CTS.A_33*mRate3[i]);ode.getRate(state,mRate4);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_41*initialRate[i]+CTS.A_43*mRate3[i]+CTS.A_44*mRate4[i]);ode.getRate(state,mRate5);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_51*initialRate[i]+CTS.A_54*mRate4[i]+CTS.A_55*mRate5[i]);ode.getRate(state,mRate6);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_61*initialRate[i]+CTS.A_64*mRate4[i]+CTS.A_65*mRate5[i]+CTS.A_66*mRate6[i]);ode.getRate(state,mRate7);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_71*initialRate[i]+CTS.A_75*mRate5[i]+CTS.A_76*mRate6[i]+CTS.A_77*mRate7[i]);ode.getRate(state,mRate8);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_81*initialRate[i]+CTS.A_84*mRate4[i]+CTS.A_85*mRate5[i]+CTS.A_86*mRate6[i]+CTS.A_87*mRate7[i]+CTS.A_88*mRate8[i]);ode.getRate(state,mRate9);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_91*initialRate[i]+CTS.A_94*mRate4[i]+CTS.A_95*mRate5[i]+CTS.A_96*mRate6[i]+CTS.A_97*mRate7[i]+CTS.A_98*mRate8[i]+CTS.A_99*mRate9[i]);ode.getRate(state,mRate10);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_101*initialRate[i]+CTS.A_104*mRate4[i]+CTS.A_105*mRate5[i]+CTS.A_106*mRate6[i]+CTS.A_107*mRate7[i]+CTS.A_108*mRate8[i]+CTS.A_109*mRate9[i]+CTS.A_1010*mRate10[i]);ode.getRate(state,mRate11);for(i=0;i<timeIndex;i++)state[i]=initialState[i]+step*(CTS.B7_1*initialRate[i]+CTS.B7_6*mRate6[i]+CTS.B7_7*mRate7[i]+CTS.B7_8*mRate8[i]+CTS.B7_9*mRate9[i]+CTS.B7_10*mRate10[i]+CTS.B7_11*mRate11[i]);state[timeIndex]=self.getInitialTime()+step*initialRate[timeIndex]};self.computeCarefulIntermediateStep=function(eventSolver,step,state){var ode=self.getODE();var initialState=self.getInitialState();var initialRate=self.getInitialRate();var dimension=self.getDimension();var timeIndex=dimension-1;var timeRate=initialRate[timeIndex];var CTS=EJSS_ODE_SOLVERS.Fehlberg78;var CODE=EJSS_ODE_SOLVERS.DISCONTINUITY_CODE;var i;for(i=0;i<dimension;i++)state[i]=initialState[i]+step*CTS.A_11*initialRate[i];switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}mODE.getRate(state,mRate2);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_21*initialRate[i]+CTS.A_22*mRate2[i]);switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}mODE.getRate(state,mRate3);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_31*initialRate[i]+CTS.A_33*mRate3[i]);switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}mODE.getRate(state,mRate4);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_41*initialRate[i]+CTS.A_43*mRate3[i]+CTS.A_44*mRate4[i]);switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}mODE.getRate(state,mRate5);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_51*initialRate[i]+CTS.A_54*mRate4[i]+CTS.A_55*mRate5[i]);switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}mODE.getRate(state,mRate6);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_61*initialRate[i]+CTS.A_64*mRate4[i]+CTS.A_65*mRate5[i]+CTS.A_66*mRate6[i]);switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}mODE.getRate(state,mRate7);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_71*initialRate[i]+CTS.A_75*mRate5[i]+CTS.A_76*mRate6[i]+CTS.A_77*mRate7[i]);switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}mODE.getRate(state,mRate8);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_81*initialRate[i]+CTS.A_84*mRate4[i]+CTS.A_85*mRate5[i]+CTS.A_86*mRate6[i]+CTS.A_87*mRate7[i]+CTS.A_88*mRate8[i]);switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}mODE.getRate(state,mRate9);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_91*initialRate[i]+CTS.A_94*mRate4[i]+CTS.A_95*mRate5[i]+CTS.A_96*mRate6[i]+CTS.A_97*mRate7[i]+CTS.A_98*mRate8[i]+CTS.A_99*mRate9[i]);switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}mODE.getRate(state,mRate10);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_101*initialRate[i]+CTS.A_104*mRate4[i]+CTS.A_105*mRate5[i]+CTS.A_106*mRate6[i]+CTS.A_107*mRate7[i]+CTS.A_108*mRate8[i]+CTS.A_109*mRate9[i]+CTS.A_1010*mRate10[i]);switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}mODE.getRate(state,mRate11);for(i=0;i<timeIndex;i++)state[i]=initialState[i]+step*(CTS.B7_1*initialRate[i]+CTS.B7_6*mRate6[i]+CTS.B7_7*mRate7[i]+CTS.B7_8*mRate8[i]+CTS.B7_9*mRate9[i]+CTS.B7_10*mRate10[i]+CTS.B7_11*mRate11[i]);state[timeIndex]=self.getInitialTime()+step*initialRate[timeIndex];return eventSolver.checkDiscontinuity(state,true)};self.computeFinalRateAndCreateIntervalData=function(){var ode=self.getODE();var initialState=self.getInitialState();var initialRate=self.getInitialRate();var finalState=self.getFinalState();var finalRate=self.getFinalRate();ode.getRate(finalState,finalRate);return EJSS_ODE_INTERPOLATION.bootstrap2IntervalData(initialState,initialRate,finalState,finalRate,ode)};return self};var EJSS_ODE_SOLVERS=EJSS_ODE_SOLVERS||{};EJSS_ODE_SOLVERS.Fehlberg78={A_11:2/27,A_21:1/36,A_22:1/12,A_31:1/24,A_33:1/8,A_41:5/12,A_43:-25/16,A_44:25/16,A_51:1/20,A_54:1/4,A_55:1/5,A_61:-25/108,A_64:125/108,A_65:-65/27,A_66:125/54,A_71:31/300,A_75:61/225,A_76:-2/9,A_77:13/900,A_81:2,A_84:-53/6,A_85:704/45,A_86:-107/9,A_87:67/90,A_88:3,A_91:-91/108,A_94:23/108,A_95:-976/135,A_96:311/54,A_97:-19/60,A_98:17/6,A_99:-1/12,A_101:2383/4100,A_104:-341/164,A_105:4496/1025,A_106:-301/82,A_107:2133/4100,A_108:45/82,A_109:45/164,A_1010:18/41,A_111:3/205,A_116:-6/41,A_117:-3/205,A_118:-3/41,A_119:3/41,A_1110:6/41,A_121:-1777/4100,A_124:-341/164,A_125:4496/1025,A_126:-289/82,A_127:2193/4100,A_128:51/82,A_129:33/164,A_1210:12/41,A_1212:1,B7_1:41/840,B7_6:34/105,B7_7:9/35,B7_8:9/35,B7_9:9/280,B7_10:9/280,B7_11:41/840,B8_6:34/105,B8_7:9/35,B8_8:9/35,B8_9:9/280,B8_10:9/280,B8_12:41/840,B8_13:41/840};EJSS_ODE_SOLVERS.fehlberg78=function(){var self=EJSS_ODE_SOLVERS.solverEngineDiscreteTimeAdaptive(7);var mRate2,mRate3,mRate4,mRate5,mRate6,mRate7,mRate8,mRate9,mRate10,mRate11,mRate12,mRate13;var superAllocateOtherArrays=self.allocateOtherArrays;self.getNumberOfEvaluations=function(){return 6};self.allocateOtherArrays=function(){superAllocateOtherArrays();mRate2=new Array(self.getDimension());mRate3=new Array(self.getDimension());mRate4=new Array(self.getDimension());mRate5=new Array(self.getDimension());mRate6=new Array(self.getDimension());mRate7=new Array(self.getDimension());mRate8=new Array(self.getDimension());mRate9=new Array(self.getDimension());mRate10=new Array(self.getDimension());mRate11=new Array(self.getDimension());mRate12=new Array(self.getDimension());mRate13=new Array(self.getDimension())
;mOrder8=new Array(self.getDimension())};self.computeIntermediateStep=function(step,state){var ode=self.getODE();var initialState=self.getInitialState();var initialRate=self.getInitialRate();var dimension=self.getDimension();var timeIndex=dimension-1;var CTS=EJSS_ODE_SOLVERS.Fehlberg78;var i;for(i=0;i<dimension;i++)state[i]=initialState[i]+step*CTS.A_11*initialRate[i];ode.getRate(state,mRate2);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_21*initialRate[i]+CTS.A_22*mRate2[i]);ode.getRate(state,mRate3);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_31*initialRate[i]+CTS.A_33*mRate3[i]);ode.getRate(state,mRate4);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_41*initialRate[i]+CTS.A_43*mRate3[i]+CTS.A_44*mRate4[i]);ode.getRate(state,mRate5);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_51*initialRate[i]+CTS.A_54*mRate4[i]+CTS.A_55*mRate5[i]);ode.getRate(state,mRate6);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_61*initialRate[i]+CTS.A_64*mRate4[i]+CTS.A_65*mRate5[i]+CTS.A_66*mRate6[i]);ode.getRate(state,mRate7);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_71*initialRate[i]+CTS.A_75*mRate5[i]+CTS.A_76*mRate6[i]+CTS.A_77*mRate7[i]);ode.getRate(state,mRate8);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_81*initialRate[i]+CTS.A_84*mRate4[i]+CTS.A_85*mRate5[i]+CTS.A_86*mRate6[i]+CTS.A_87*mRate7[i]+CTS.A_88*mRate8[i]);ode.getRate(state,mRate9);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_91*initialRate[i]+CTS.A_94*mRate4[i]+CTS.A_95*mRate5[i]+CTS.A_96*mRate6[i]+CTS.A_97*mRate7[i]+CTS.A_98*mRate8[i]+CTS.A_99*mRate9[i]);ode.getRate(state,mRate10);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_101*initialRate[i]+CTS.A_104*mRate4[i]+CTS.A_105*mRate5[i]+CTS.A_106*mRate6[i]+CTS.A_107*mRate7[i]+CTS.A_108*mRate8[i]+CTS.A_109*mRate9[i]+CTS.A_1010*mRate10[i]);ode.getRate(state,mRate11);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_111*initialRate[i]+CTS.A_116*mRate6[i]+CTS.A_117*mRate7[i]+CTS.A_118*mRate8[i]+CTS.A_119*mRate9[i]+CTS.A_1110*mRate10[i]);ode.getRate(state,mRate12);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_121*initialRate[i]+CTS.A_124*mRate4[i]+CTS.A_125*mRate5[i]+CTS.A_126*mRate6[i]+CTS.A_127*mRate7[i]+CTS.A_128*mRate8[i]+CTS.A_129*mRate9[i]+CTS.A_1210*mRate10[i]+CTS.A_1212*mRate12[i]);ode.getRate(state,mRate13);for(i=0;i<timeIndex;i++)state[i]=initialState[i]+step*(CTS.B7_1*initialRate[i]+CTS.B7_6*mRate6[i]+CTS.B7_7*mRate7[i]+CTS.B7_8*mRate8[i]+CTS.B7_9*mRate9[i]+CTS.B7_10*mRate10[i]+CTS.B7_11*mRate11[i]);state[timeIndex]=self.getInitialTime()+step*initialRate[timeIndex]};self.computeCarefulIntermediateStep=function(eventSolver,step,state){var ode=self.getODE();var initialState=self.getInitialState();var initialRate=self.getInitialRate();var dimension=self.getDimension();var timeIndex=dimension-1;var CTS=EJSS_ODE_SOLVERS.Fehlberg78;var CODE=EJSS_ODE_SOLVERS.DISCONTINUITY_CODE;var i;for(i=0;i<dimension;i++)state[i]=initialState[i]+step*CTS.A_11*initialRate[i];switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}mODE.getRate(state,mRate2);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_21*initialRate[i]+CTS.A_22*mRate2[i]);switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}mODE.getRate(state,mRate3);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_31*initialRate[i]+CTS.A_33*mRate3[i]);switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}mODE.getRate(state,mRate4);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_41*initialRate[i]+CTS.A_43*mRate3[i]+CTS.A_44*mRate4[i]);switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}mODE.getRate(state,mRate5);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_51*initialRate[i]+CTS.A_54*mRate4[i]+CTS.A_55*mRate5[i]);switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}mODE.getRate(state,mRate6);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_61*initialRate[i]+CTS.A_64*mRate4[i]+CTS.A_65*mRate5[i]+CTS.A_66*mRate6[i]);switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}mODE.getRate(state,mRate7);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_71*initialRate[i]+CTS.A_75*mRate5[i]+CTS.A_76*mRate6[i]+CTS.A_77*mRate7[i]);switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}mODE.getRate(state,mRate8);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_81*initialRate[i]+CTS.A_84*mRate4[i]+CTS.A_85*mRate5[i]+CTS.A_86*mRate6[i]+CTS.A_87*mRate7[i]+CTS.A_88*mRate8[i]);switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}mODE.getRate(state,mRate9);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_91*initialRate[i]+CTS.A_94*mRate4[i]+CTS.A_95*mRate5[i]+CTS.A_96*mRate6[i]+CTS.A_97*mRate7[i]+CTS.A_98*mRate8[i]+CTS.A_99*mRate9[i]);switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}mODE.getRate(state,mRate10);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_101*initialRate[i]+CTS.A_104*mRate4[i]+CTS.A_105*mRate5[i]+CTS.A_106*mRate6[i]+CTS.A_107*mRate7[i]+CTS.A_108*mRate8[i]+CTS.A_109*mRate9[i]+CTS.A_1010*mRate10[i]);switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}mODE.getRate(state,mRate11);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_111*initialRate[i]+CTS.A_116*mRate6[i]+CTS.A_117*mRate7[i]+CTS.A_118*mRate8[i]+CTS.A_119*mRate9[i]+CTS.A_1110*mRate10[i]);switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}mODE.getRate(state,mRate12);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*(CTS.A_121*initialRate[i]+CTS.A_124*mRate4[i]+CTS.A_125*mRate5[i]+CTS.A_126*mRate6[i]+CTS.A_127*mRate7[i]+CTS.A_128*mRate8[i]+CTS.A_129*mRate9[i]+CTS.A_1210*mRate10[i]+CTS.A_1212*mRate12[i]);switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}mODE.getRate(state,mRate13);for(i=0;i<timeIndex;i++)state[i]=initialState[i]+step*(CTS.B7_1*initialRate[i]+CTS.B7_6*mRate6[i]+CTS.B7_7*mRate7[i]+CTS.B7_8*mRate8[i]+CTS.B7_9*mRate9[i]+CTS.B7_10*mRate10[i]+CTS.B7_11*mRate11[i]);state[timeIndex]=self.getInitialTime()+step*initialRate[timeIndex];return eventSolver.checkDiscontinuity(state,true)};self.computeFinalRateAndCreateIntervalData=function(){var ode=self.getODE();var initialState=self.getInitialState();var initialRate=self.getInitialRate();var finalState=self.getFinalState();var finalRate=self.getFinalRate();ode.getRate(finalState,finalRate);return EJSS_ODE_INTERPOLATION.bootstrap2IntervalData(initialState,initialRate,finalState,finalRate,ode)};self.computeApproximation=function(step){var timeIndex=self.getTimeIndex();var initialState=self.getInitialState();var initialRate=self.getInitialRate();var CTS=EJSS_ODE_SOLVERS.Fehlberg78;for(var i=0;i<timeIndex;i++)mOrder8[i]=initialState[i]+step*(CTS.B8_6*mRate6[i]+CTS.B8_7*mRate7[i]+CTS.B8_8*mRate8[i]+CTS.B8_9*mRate9[i]+CTS.B8_10*mRate10[i]+CTS.B8_12*mRate12[i]+CTS.B8_13*mRate13[i]);mOrder8[timeIndex]=self.getInitialTime()+step*initialRate[timeIndex];return self.computeError(mOrder8)};return self};var EJSS_ODE_SOLVERS=EJSS_ODE_SOLVERS||{};EJSS_ODE_SOLVERS.RungeKutta4={};EJSS_ODE_SOLVERS.rungeKutta4=function(){var self=EJSS_ODE_SOLVERS.solverEngineDiscreteTime();var mRate2,mRate3,mRate4;self.getNumberOfEvaluations=function(){return 4};self.allocateOtherArrays=function(){mRate2=new Array(self.getDimension());mRate3=new Array(self.getDimension());mRate4=new Array(self.getDimension())};self.computeIntermediateStep=function(step,state){var halfStep=step/2;var ode=self.getODE();var initialState=self.getInitialState();var initialRate=self.getInitialRate();var dimension=self.getDimension();var timeIndex=dimension-1;var i;for(i=0;i<dimension;i++)state[i]=initialState[i]+halfStep*initialRate[i];ode.getRate(state,mRate2);for(i=0;i<dimension;i++)state[i]=initialState[i]+halfStep*mRate2[i];ode.getRate(state,mRate3);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*mRate3[i];ode.getRate(state,mRate4);for(i=0;i<timeIndex;i++)state[i]=initialState[i]+step*(initialRate[i]+2*mRate2[i]+2*mRate3[i]+mRate4[i])/6;state[timeIndex]=self.getInitialTime()+step*initialRate[timeIndex]};self.computeCarefulIntermediateStep=function(eventSolver,step,state){var halfStep=step/2;var ode=self.getODE();var initialState=self.getInitialState();var initialRate=self.getInitialRate();var dimension=self.getDimension();var timeIndex=dimension-1;var CODE=EJSS_ODE_SOLVERS.DISCONTINUITY_CODE;var i;for(i=0;i<dimension;i++)state[i]=initialState[i]+halfStep*initialRate[i];switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}ode.getRate(state,mRate2);for(i=0;i<dimension;i++)state[i]=initialState[i]+halfStep*mRate2[i];switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}ode.getRate(state,mRate3);for(i=0;i<dimension;i++)state[i]=initialState[i]+step*mRate3[i];switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}ode.getRate(state,mRate4);for(i=0;i<timeIndex;i++)state[i]=initialState[i]+step*(initialRate[i]+2*mRate2[i]+2*mRate3[i]+mRate4[i])/6;state[timeIndex]=self.getInitialTime()+step*initialRate[timeIndex];return eventSolver.checkDiscontinuity(state,true)};self.computeFinalRateAndCreateIntervalData=function(){var ode=self.getODE();var initialState=self.getInitialState();var initialRate=self.getInitialRate();var finalState=self.getFinalState();var finalRate=self.getFinalRate();ode.getRate(finalState,finalRate);return EJSS_ODE_INTERPOLATION.bootstrapIntervalData(initialState,initialRate,finalState,finalRate,ode)};return self};var EJSS_ODE_SOLVERS=EJSS_ODE_SOLVERS||{};EJSS_ODE_SOLVERS.SolverEngineDiscreteTime={};EJSS_ODE_SOLVERS.solverEngineDiscreteTime=function(){var self={};var mErrorCode=EJSS_ODE_SOLVERS.ERROR.NO_ERROR;var mDimension;var mTimeIndex;var mAccumulatedEvaluations=0;var mStepSize=.1;var mMaximumStepSize=Number.POSITIVE_INFINITY;var mInitialTime=0;var mFinalTime=0;var mInitialState;var mInitialRate;var mFinalState;var mFinalRate;var mODE;var mEventSolver;var mStateHistory;self.getNumberOfEvaluations=function(){return 0};self.allocateOtherArrays=function(){};self.computeIntermediateStep=function(step,state){return null};self.computeCarefulIntermediateStep=function(solver,step,state){return EJSS_ODE_SOLVERS.DISCONTINUITY_CODE.NO_DISCONTINUITY_ALONG_STEP};self.computeFinalRateAndCreateIntervalData=function(){return null};self.getODE=function(){return mODE};self.getEventSolver=function(){return mEventSolver};self.getDimension=function(){return mDimension};self.getTimeIndex=function(){return mTimeIndex};self.getInitialTime=function(){return mInitialTime};self.getInitialState=function(){return mInitialState};self.getInitialRate=function(){return mInitialRate};self.getFinalState=function(){return mFinalState};self.getFinalRate=function(){return mFinalRate};self.setFinalTime=function(time){mFinalTime=time};self.getFinalTime=function(){return mFinalTime};self.setErrorCode=function(code){mErrorCode=code};self.addToEvaluations=function(evals){mAccumulatedEvaluations+=evals};self.setODE=function(eventSolver,ode){mEventSolver=eventSolver;mODE=ode;var state=mODE.getState();mDimension=state.length;mTimeIndex=mDimension-1;mStateHistory=EJSS_ODE_INTERPOLATION.stateHistory(ode);if(mODE.getMaximumDelay){mStateHistory.setMinimumLength(mODE.getMaximumDelay())}};self.initialize=function(stepSize){mStepSize=stepSize;var state=mODE.getState();if(mInitialState==null||mInitialState.length!=state.length){mDimension=state.length;mTimeIndex=mDimension-1;mInitialState=new Array(mDimension);mInitialRate=new Array(mDimension);mFinalState=new Array(mDimension);mFinalRate=new Array(mDimension);self.allocateOtherArrays()}mAccumulatedEvaluations=0;mStateHistory.clearAll();if(mODE.getMaximumDelay){mStateHistory.setMinimumLength(Math.max(Math.abs(mODE.getMaximumDelay()),Math.abs(stepSize)))}else mStateHistory.setMinimumLength(stepSize);self.reinitialize(state)};self.reinitialize=function(state){mInitialTime=state[mTimeIndex];for(var i=0;i<mDimension;i++)mInitialState[i]=state[i];mODE.getRate(mInitialState,mInitialRate);mFinalTime=Number.NaN;mErrorCode=EJSS_ODE_SOLVERS.ERROR.NO_ERROR};self.getCurrentRate=function(){return mInitialRate};self.setStepSize=function(stepSize){mStepSize=stepSize;if(mODE.getMaximumDelay){mStateHistory.setMinimumLength(Math.max(Math.abs(mODE.getMaximumDelay()),Math.abs(stepSize)))}else mStateHistory.setMinimumLength(stepSize)};self.setMaximumStepSize=function(stepSize){mMaximumStepSize=Math.abs(stepSize)};self.getMaximumStepSize=function(){return mMaximumStepSize};self.getStepSize=function(){return mStepSize};self.getInternalStepSize=function(){return mFinalTime-mInitialTime};self.setEstimateFirstStep=function(estimate){};self.setTolerances=function(absTol,relTol){};self.getMaximumTime=function(withDiscontinuities){if(mErrorCode!=EJSS_ODE_SOLVERS.ERROR.NO_ERROR)return Number.NaN;if(isNaN(mFinalTime)){self.computeOneStep(withDiscontinuities)}return mFinalTime};self.internalStep=function(withDiscontinuities){var i;mInitialTime=mFinalTime;mErrorCode=EJSS_ODE_SOLVERS.ERROR.NO_ERROR;for(i=0;i<mDimension;i++)mInitialState[i]=mFinalState[i];for(i=0;i<mDimension;i++)mInitialRate[i]=mFinalRate[i];self.computeOneStep(withDiscontinuities);return mFinalTime};self.getCounter=function(){return mAccumulatedEvaluations};self.getStateHistory=function(){return mStateHistory};self.interpolate=function(time,state){return mStateHistory.interpolateState(time,state)};self.bestInterpolate=function(time,state){var i;if(isNaN(mFinalTime))return null;if(time==mFinalTime){for(i=0;i<mDimension;i++)state[i]=mFinalState[i];return state}if(time==mInitialTime){for(i=0;i<mDimension;i++)state[i]=mInitialState[i];return state}self.computeIntermediateStep(time-mInitialTime,state);return state};self.getActualStepSize=function(){return mStepSize};self.findTheDiscontinuity=function(step){var counter=0;var left=0;var right=step;var lastValid=0;var maxAttempts=mEventSolver.getDDEIterations();var EPSILON=mEventSolver.getEPSILON();while(counter<maxAttempts){if(Math.abs(left-right)<EPSILON){break}var testPoint=(left+right)/2;switch(self.computeCarefulIntermediateStep(mEventSolver,testPoint,mFinalState)){default:case EJSS_ODE_SOLVERS.DISCONTINUITY_CODE.DISCONTINUITY_PRODUCED_ERROR:return Number.NaN;case EJSS_ODE_SOLVERS.DISCONTINUITY_CODE.NO_DISCONTINUITY_ALONG_STEP:lastValid=mFinalState[mTimeIndex];left=testPoint;break;case EJSS_ODE_SOLVERS.DISCONTINUITY_CODE.DISCONTINUITY_EXACTLY_ON_STEP:return mFinalState[mTimeIndex];case EJSS_ODE_SOLVERS.DISCONTINUITY_CODE.DISCONTINUITY_JUST_PASSED:right=right-(right-left)/4;break;case EJSS_ODE_SOLVERS.DISCONTINUITY_CODE.DISCONTINUITY_ALONG_STEP:right=testPoint;break}counter++}self.computeCarefulIntermediateStep(mEventSolver,lastValid,mFinalState);return lastValid};self.computeOneStep=function(hasDiscontinuities){var step=mStepSize;if(hasDiscontinuities){switch(self.computeCarefulIntermediateStep(mEventSolver,step,mFinalState)){case EJSS_ODE_SOLVERS.DISCONTINUITY_CODE.DISCONTINUITY_PRODUCED_ERROR:mFinalTime=Number.NaN;return;case EJSS_ODE_SOLVERS.DISCONTINUITY_CODE.NO_DISCONTINUITY_ALONG_STEP:case EJSS_ODE_SOLVERS.DISCONTINUITY_CODE.DISCONTINUITY_EXACTLY_ON_STEP:mFinalTime=mFinalState[mTimeIndex];break;case EJSS_ODE_SOLVERS.DISCONTINUITY_CODE.DISCONTINUITY_JUST_PASSED:case EJSS_ODE_SOLVERS.DISCONTINUITY_CODE.DISCONTINUITY_ALONG_STEP:mFinalTime=self.findTheDiscontinuity(step);break}if(isNaN(mFinalTime)){mErrorCode=EJSS_ODE_SOLVERS.ERROR.DISCONTINUITY_PRODUCED_ERROR;return}}else{self.computeIntermediateStep(step,mFinalState);mFinalTime=mFinalState[mTimeIndex]}mAccumulatedEvaluations+=self.getNumberOfEvaluations();mStateHistory.clean(mInitialTime);mStateHistory.addIntervalData(self.computeFinalRateAndCreateIntervalData())};return self};var EJSS_ODE_SOLVERS=EJSS_ODE_SOLVERS||{};EJSS_ODE_SOLVERS.SolverEngineDiscreteTimeAdaptive={FAC1:.33,FAC2:6,BETA:0,SAFE:.9};EJSS_ODE_SOLVERS.solverEngineDiscreteTimeAdaptive=function(mMethodOrder){var self=EJSS_ODE_SOLVERS.solverEngineDiscreteTime();var mExpO1=1/mMethodOrder-EJSS_ODE_SOLVERS.SolverEngineDiscreteTimeAdaptive.BETA*.75;var mErrOld=1e-4;var mFactor=0;var mEstimate=false;var mActualStepSize;var mAbsoluteTolerance=Number.NaN;var mRelativeTolerance=Number.NaN;var mAbsTol;var mRelTol;var superReinitialize=self.reinitialize;var superSetMaximumStepSize=self.setMaximumStepSize;self.computeApproximation=function(step){};self.getAbsTol=function(){return mAbsTol};self.getRelTol=function(){return mRelTol};self.allocateOtherArrays=function(){var dimension=self.getDimension();mAbsTol=new Array(dimension);mRelTol=new Array(dimension);self.setTolerances(1e-6,1e-6)};self.reinitialize=function(state){superReinitialize(state);if(mEstimate)mActualStepSize=limitStepSize(estimateFirstStepSize(self.getStepSize()));else mActualStepSize=limitStepSize(self.getStepSize())};self.setEstimateFirstStep=function(estimate){mEstimate=estimate};self.setMaximumStepSize=function(stepSize){superSetMaximumStepSize(stepSize);mActualStepSize=limitStepSize(mActualStepSize)};self.setTolerances=function(absTol,relTol){var i;var dimension=self.getDimension();if(absTol instanceof Array){mAbsoluteTolerance=mRelativeTolerance=Number.NaN;for(i=0;i<dimension;i++){mAbsTol[i]=absTol[i];mRelTol[i]=relTol[i]}}else{if(mAbsoluteTolerance==absTol&&mRelativeTolerance==relTol)return;mAbsoluteTolerance=absTol;mRelativeTolerance=relTol;for(i=0;i<dimension;i++){mAbsTol[i]=absTol;mRelTol[i]=relTol}}mFinalTime=Number.NaN;mErrorCode=EJSS_ODE_SOLVERS.ERROR.NO_ERROR;if(mEstimate)mActualStepSize=limitStepSize(estimateFirstStepSize(self.getStepSize()));else mActualStepSize=limitStepSize(self.getStepSize())};self.computeOneStep=function(hasDiscontinuities){var eventSolver=self.getEventSolver();var finalState=self.getFinalState();mErrorCode=EJSS_ODE_SOLVERS.ERROR.NO_ERROR;for(var iterations=0;iterations<500;iterations++){if(hasDiscontinuities){switch(self.computeCarefulIntermediateStep(eventSolver,mActualStepSize,finalState)){case EJSS_ODE_SOLVERS.DISCONTINUITY_CODE.DISCONTINUITY_PRODUCED_ERROR:self.setFinalTime(Number.NaN);return;case EJSS_ODE_SOLVERS.DISCONTINUITY_CODE.NO_DISCONTINUITY_ALONG_STEP:case EJSS_ODE_SOLVERS.DISCONTINUITY_CODE.DISCONTINUITY_EXACTLY_ON_STEP:self.setFinalTime(finalState[self.getTimeIndex()]);break;case EJSS_ODE_SOLVERS.DISCONTINUITY_CODE.DISCONTINUITY_JUST_PASSED:case EJSS_ODE_SOLVERS.DISCONTINUITY_CODE.DISCONTINUITY_ALONG_STEP:var finalTime=self.findTheDiscontinuity(mActualStepSize);self.setFinalTime(finalTime);mActualStepSize=finalTime-self.getInitialTime();break}if(isNaN(self.getFinalTime())){self.setErrorCode(EJSS_ODE_SOLVERS.ERROR.DISCONTINUITY_PRODUCED_ERROR);return}}else{self.computeIntermediateStep(mActualStepSize,finalState);self.setFinalTime(finalState[self.getTimeIndex()])}var err=self.computeApproximation(mActualStepSize);self.addToEvaluations(self.getNumberOfEvaluations());if(err<=1){self.getStateHistory().clean(self.getInitialTime());self.getStateHistory().addIntervalData(self.computeFinalRateAndCreateIntervalData());if(iterations>0)mActualStepSize=limitStepSize(mActualStepSize>0?Math.min(mActualStepSize,estimatedStepSize(err)):Math.max(mActualStepSize,estimatedStepSize(err)));else mActualStepSize=limitStepSize(estimatedStepSize(err));return}mActualStepSize=limitStepSize(mActualStepSize>0?Math.min(mActualStepSize,estimatedStepSize(err)):Math.max(mActualStepSize,estimatedStepSize(err)))}self.setFinalTime(Number.NaN);self.setErrorCode(EJSS_ODE_SOLVERS.ERROR.DID_NOT_CONVERGE)};self.getActualStepSize=function(){return mActualStepSize};self.computeError=function(state){var error=0;var dimension=self.getDimension();var initialState=self.getInitialState();var finalState=self.getFinalState();for(var i=0;i<dimension;i++){var sk=mAbsTol[i]+mRelTol[i]*Math.max(Math.abs(finalState[i]),Math.abs(initialState[i]));var errorI=(finalState[i]-state[i])/sk;error+=errorI*errorI}return Math.sqrt(error/dimension)};function estimatedStepSize(err){var fac11=0;if(err!=0){fac11=Math.pow(err,mExpO1);mFactor=fac11/Math.exp(EJSS_ODE_SOLVERS.SolverEngineDiscreteTimeAdaptive.BETA*Math.log(mErrOld));mFactor=Math.max(1/EJSS_ODE_SOLVERS.SolverEngineDiscreteTimeAdaptive.FAC2,Math.min(1/EJSS_ODE_SOLVERS.SolverEngineDiscreteTimeAdaptive.FAC1,mFactor/EJSS_ODE_SOLVERS.SolverEngineDiscreteTimeAdaptive.SAFE))}else{fac11=1/EJSS_ODE_SOLVERS.SolverEngineDiscreteTimeAdaptive.FAC1;mFactor=1/EJSS_ODE_SOLVERS.SolverEngineDiscreteTimeAdaptive.FAC2}if(err<=1){mErrOld=Math.max(err,1e-4);return mActualStepSize/mFactor}return mActualStepSize/Math.min(1/EJSS_ODE_SOLVERS.SolverEngineDiscreteTimeAdaptive.FAC1,fac11/EJSS_ODE_SOLVERS.SolverEngineDiscreteTimeAdaptive.SAFE)}function limitStepSize(intendedStep){var ode=self.getODE();var delays;var i,length;if(intendedStep>=0){if(ode.getDelays){delays=ode.getDelays(self.getInitialState());length=delays.length;for(i=0;i<length;i++)intendedStep=Math.min(intendedStep,delays[i]/2)}return Math.min(intendedStep,self.getMaximumStepSize())}if(ode.getDelays){delays=ode.getDelays(self.getInitialState());length=delays.length;for(i=0;i<length;i++)intendedStep=Math.max(intendedStep,delays[i]/2)}return Math.max(intendedStep,-self.getMaximumStepSize())}function estimateFirstStepSize(hMax){var i;var dimension=self.getDimension();var initialState=self.getInitialState();var initialRate=self.getInitialRate();var ode=self.getODE();var posneg=hMax<0?-1:1;hMax=Math.abs(hMax);var normF=0,normX=0;for(i=0;i<dimension;i++){var sk=mAbsTol[i]+mRelTol[i]*Math.abs(initialState[i]);var aux=initialRate[i]/sk;normF+=aux*aux;aux=initialState[i]/sk;normX+=aux*aux}var h;if(normF<=1e-10||normX<=1e-10)h=1e-6;else h=Math.sqrt(normX/normF)*.01;h=posneg*Math.min(h,hMax);if(ode.getDelays){var eventSolver=self.getEventSolver();eventSolver.resetDiscontinuities(initialState);var counter=0;var done=false;while(!done){for(i=0;i<dimension;i++)finalState[i]=initialState[i]+h*initialRate[i];switch(eventSolver.checkDiscontinuity(finalState,false)){case EJSS_ODE_SOLVERS.DISCONTINUITY_CODE.DISCONTINUITY_PRODUCED_ERROR:return Number.NaN;case EJSS_ODE_SOLVERS.DISCONTINUITY_CODE.DISCONTINUITY_JUST_PASSED:case EJSS_ODE_SOLVERS.DISCONTINUITY_CODE.DISCONTINUITY_ALONG_STEP:h=h/2;break;case EJSS_ODE_SOLVERS.DISCONTINUITY_CODE.DISCONTINUITY_EXACTLY_ON_STEP:done=true;break;case EJSS_ODE_SOLVERS.DISCONTINUITY_CODE.NO_DISCONTINUITY_ALONG_STEP:done=true;break}if(++counter>100)return Number.NaN}}else{for(i=0;i<dimension;i++)finalState[i]=initialState[i]+h*initialRate[i]}ode.getRate(finalState,finalRate);var der2=0;for(i=0;i<dimension;i++){var sk=mAbsTol[i]+mRelTol[i]*Math.abs(initialState[i]);var aux=(finalRate[i]-initialRate[i])/sk;der2+=aux*aux}der2=Math.sqrt(der2)/h;var der12=Math.max(Math.abs(der2),Math.sqrt(normF));var h1;if(der12<=1e-15)h1=Math.max(1e-6,Math.abs(h)*.001);else h1=Math.exp(1/mMethodOrder*Math.log(.01/der12));h=posneg*Math.min(100*h,h1);if(hMax!=0)h=posneg*Math.min(Math.abs(h),hMax);return h}return self};var EJSS_ODE_SOLVERS=EJSS_ODE_SOLVERS||{};EJSS_ODE_SOLVERS.VelocityVerlet={};EJSS_ODE_SOLVERS.velocityVerlet=function(){var self=EJSS_ODE_SOLVERS.solverEngineDiscreteTime();var mAccelerationIndependentOfVelocity;var mRate2;superSetODE=self.setODE;self.setODE=function(eventSolver,ode){superSetODE(eventSolver,ode);if(ode.isAccelerationIndependentOfVelocity)mAccelerationIndependentOfVelocity=ode.isAccelerationIndependentOfVelocity();else mAccelerationIndependentOfVelocity=false};self.getNumberOfEvaluations=function(){return 2};self.allocateOtherArrays=function(){mRate2=new Array(self.getDimension())};self.computeIntermediateStep=function(step,state){var ode=self.getODE();var initialState=self.getInitialState();var initialRate=self.getInitialRate();var dimension=self.getDimension();var timeIndex=dimension-1;var i;var dt2=step*step/2;for(i=0;i<timeIndex;i+=2)state[i]=initialState[i]+step*initialRate[i]+dt2*initialRate[i+1];ode.getRate(state,mRate2);var halfStep=step/2;for(i=1;i<timeIndex;i+=2)state[i]=initialState[i]+halfStep*(initialRate[i]+mRate2[i]);state[timeIndex]=self.getInitialTime()+step*initialRate[timeIndex]};self.computeCarefulIntermediateStep=function(eventSolver,step,state){var ode=self.getODE();var initialState=self.getInitialState();var initialRate=self.getInitialRate();var dimension=self.getDimension();var timeIndex=dimension-1;var CODE=EJSS_ODE_SOLVERS.DISCONTINUITY_CODE;var i;var dt2=step*step/2;for(i=0;i<timeIndex;i+=2)state[i]=initialState[i]+step*initialRate[i]+dt2*initialRate[i+1];switch(eventSolver.checkDiscontinuity(state,false)){case CODE.DISCONTINUITY_PRODUCED_ERROR:return CODE.DISCONTINUITY_PRODUCED_ERROR;case CODE.DISCONTINUITY_JUST_PASSED:return CODE.DISCONTINUITY_JUST_PASSED;case CODE.DISCONTINUITY_ALONG_STEP:return CODE.DISCONTINUITY_ALONG_STEP;case CODE.DISCONTINUITY_EXACTLY_ON_STEP:break;case CODE.NO_DISCONTINUITY_ALONG_STEP:break}ode.getRate(state,mRate2);var halfStep=step/2;for(i=1;i<timeIndex;i+=2)state[i]=initialState[i]+halfStep*(initialRate[i]+mRate2[i]);state[timeIndex]=self.getInitialTime()+step*timeRate;return eventSolver.checkDiscontinuity(state,true)};self.computeFinalRateAndCreateIntervalData=function(){var ode=self.getODE();var initialState=self.getInitialState();var initialRate=self.getInitialRate();var finalState=self.getFinalState();var finalRate=self.getFinalRate();var timeIndex=self.getDimension()-1;if(mAccelerationIndependentOfVelocity){for(var i=0,j=1;i<timeIndex;i+=2,j+=2){finalRate[i]=finalState[j];finalRate[j]=mRate2[j]}finalRate[timeIndex]=mRate2[timeIndex]}else{ode.getRate(finalState,finalRate);self.addToEvaluations(self.getNumberOfEvaluations())}return new EJSS_ODE_INTERPOLATION.hermiteIntervalData(initialState,initialRate,finalState,finalRate)};return self};var EJSS_ODE_SOLVERS=EJSS_ODE_SOLVERS||{};EJSS_ODE_SOLVERS.DDEDiscontinuity={};EJSS_ODE_SOLVERS.ddeDiscontinuity=function(mSolver,mDDE){var self={};var mDiscontinuities=[];var mDiIndex=[];var mRateForCorrections=[];self.initialize=function(state){if(mSolver.getRunsForwards())mDiscontinuities.push(Number.NEGATIVE_INFINITY);else mDiscontinuities.push(Number.POSITIVE_INFINITY);var initDisc=mDDE.getInitialConditionDiscontinuities();if(initDisc!=null){var length=initDisc.length;for(var i=0;i<length;i++)mDiscontinuities.push(initDisc[i])}mDiscontinuities.push(state[state.length-1]);var delays=mDDE.getDelays(state);mDiIndex=new Array(delays.length);self.reset(state);mRateForCorrections=new Array(state.length)};self.reset=function(state){var length=mDiIndex.length;for(var i=0;i<length;i++)mDiIndex[i]=0;update(state)};function update(state){var i;var delays=mDDE.getDelays(state);var n=delays.length;var discCount=mDiscontinuities.length;var timeIndex=state.length-1;if(mSolver.getRunsForwards()){for(i=0;i<n;i++){var limit=state[timeIndex]-delays[i]+self.getTolerance();for(var index=mDiIndex[i];index<discCount;index++){var disc=mDiscontinuities[index];if(disc>limit){mDiIndex[i]=index;break}}}}else{for(i=0;i<n;i++){var limit=state[timeIndex]-delays[i]-self.getTolerance();for(var index=mDiIndex[i];index<discCount;index++){var disc=mDiscontinuities[index];if(disc<limit){mDiIndex[i]=index;break}}}}}self.evaluate=function(state){var i;var t=state[state.length-1];var delays=mDDE.getDelays(state);var n=delays.length;if(mSolver.getRunsForwards()){var min=Number.POSITIVE_INFINITY;for(i=0;i<n;i++){var di=mDiscontinuities[mDiIndex[i]];min=Math.min(min,delays[i]+di-t)}return min}else{var max=Number.NEGATIVE_INFINITY;for(i=0;i<n;i++){
var di=mDiscontinuities[mDiIndex[i]];max=Math.max(max,delays[i]+di-t)}return max}};function correctTime(state){var i;var dimension=state.length;var timeIndex=dimension-1;var step=self.getTolerance()/20;var maxIterations=mSolver.getDDEIterations();var history=mSolver.getStateHistory();var counter=0;if(mSolver.getRunsForwards()){while(++counter<maxIterations){mDDE.getRate(state,mRateForCorrections);history.addIntervalData(EJSS_ODE_INTERPOLATION.eulerIntervalData(state,mRateForCorrections,state[timeIndex]+step));for(i=0;i<dimension;i++)state[i]+=step*mRateForCorrections[i];var h=self.evaluate(state);if(h<0){return state[timeIndex]}}}else{while(++counter<maxIterations){mDDE.getRate(state,mRateForCorrections);history.addIntervalData(EJSS_ODE_INTERPOLATION.eulerIntervalData(state,mRateForCorrections,state[timeIndex]-step));for(i=0;i<dimension;i++)state[i]-=step*mRateForCorrections[i];var h=evaluate(state);if(h>0)return state[timeIndex]}}return Number.NaN}self.action=function(){var state=mDDE.getState();var time=correctTime(state);mDiscontinuities.push(time);var eventData=mSolver.findFirstEvent(state,time,state);if(eventData!=null){mCurrentEventData=eventData;eventData.action()}return true};self.getTolerance=function(){return mSolver.getDDETolerance()};return self};var EJSS_ODE_SOLVERS=EJSS_ODE_SOLVERS||{};EJSS_ODE_SOLVERS.ProblemData={POSITIVE:2,SMALL_POSITIVE:1,ZERO:0,SMALL_NEGATIVE:-1,NEGATIVE:-2};EJSS_ODE_SOLVERS.eventData=function(mSolver,mEvent,mState){var self={};var mEventType=mEvent.getTypeOfEvent();var mTimeIndex=mState.length-1;var mPositiveFlag;var mNegativeFlag;var mCurrentPosition;var mHBefore;var mHAfter;var mH;var mTime;var mMaxAdvance;self.getEvent=function(){return mEvent};self.getEventType=function(){return mEventType};self.setH=function(h){mH=h};self.getH=function(){return mH};self.getTime=function(){return mTime};self.setTime=function(time){mTime=time};self.hasPositiveFlag=function(){return mPositiveFlag};self.hasNegativeFlag=function(){return mNegativeFlag};self.getHBefore=function(){return mHBefore};self.setHAfter=function(h){mHAfter=h};self.getHAfter=function(){return mHAfter};self.getCurrentPosition=function(){return mCurrentPosition};self.getMaxAdvance=function(){return mMaxAdvance};self.setMaxAdvance=function(advance){mMaxAdvance=advance};self.action=function(){return mEvent.action()};self.getProblem=function(){return mEvent};self.reset=function(state){mPositiveFlag=false;mNegativeFlag=false;var h=mEvent.evaluate(state);self.findPosition(state[mTimeIndex],h);if(mSolver.getCurrentEventData()!=self){if(mEventType==EJSS_ODE_SOLVERS.EVENT_TYPE.CROSSING_EVENT){if(h>0)mPositiveFlag=true;else if(h<0)mNegativeFlag=true}else if(mEventType==EJSS_ODE_SOLVERS.EVENT_TYPE.POSITIVE_EVENT){if(h>0)mPositiveFlag=true}}};self.findPosition=function(time,hValue){mHBefore=hValue;if(mHBefore>=mEvent.getTolerance()){mCurrentPosition=EJSS_ODE_SOLVERS.ProblemData.POSITIVE;mPositiveFlag=true}else if(mHBefore>0)mCurrentPosition=EJSS_ODE_SOLVERS.ProblemData.SMALL_POSITIVE;else if(mHBefore==0)mCurrentPosition=EJSS_ODE_SOLVERS.ProblemData.ZERO;else if(mHBefore>-mEvent.getTolerance())mCurrentPosition=EJSS_ODE_SOLVERS.ProblemData.SMALL_NEGATIVE;else{mCurrentPosition=EJSS_ODE_SOLVERS.ProblemData.NEGATIVE;mNegativeFlag=true}if(mEventType==EJSS_ODE_SOLVERS.EVENT_TYPE.STATE_EVENT&&mCurrentPosition==EJSS_ODE_SOLVERS.ProblemData.NEGATIVE){var msg="The state event "+mEvent+" is in an illegal state: "+mHBefore+" at "+time;if(mSolver.getLastEventData()==null)msg+="\nThere was no previous event";else msg+="\nLast previous event was "+mSolver.getLastEventData().getProblem()+", which took place at "+mSolver.getLastEventDataTime();mSolver.error(EJSS_ODE_SOLVERS.ERROR.ILLEGAL_EVENT_STATE,msg)}};self.reset(mState);return self};EJSS_ODE_SOLVERS.discontinuityData=function(mSolver,mDiscontinuity,mState){var self={};var mTimeIndex=mState.length-1;var mPositiveFlag;var mNegativeFlag;var mCurrentPosition;var mHBefore;var mH;var mTime;self.getDiscontinuity=function(){return mDiscontinuity};self.setH=function(h){mH=h};self.getH=function(){return mH};self.setTime=function(time){mTime=time};self.getTime=function(){return mTime};self.hasPositiveFlag=function(){return mPositiveFlag};self.hasNegativeFlag=function(){return mNegativeFlag};self.getHBefore=function(){return mHBefore};self.setHAfter=function(h){mHAfter=h};self.getHAfter=function(){return mHAfter};self.getCurrentPosition=function(){return mCurrentPosition};self.getMaxAdvance=function(){return Number.NaN};self.action=function(){return mDiscontinuity.action()};self.getProblem=function(){return mDiscontinuity};self.reset=function(state){mPositiveFlag=false;mNegativeFlag=false;var h=mDiscontinuity.evaluate(state);self.findPosition(state[mTimeIndex],h);if(mSolver.getCurrentEventData()!=self){if(h>0)mPositiveFlag=true;else if(h<0)mNegativeFlag=true}};self.findPosition=function(time,hValue){mHBefore=hValue;if(mHBefore>=mDiscontinuity.getTolerance()){mCurrentPosition=EJSS_ODE_SOLVERS.ProblemData.POSITIVE;mPositiveFlag=true}else if(mHBefore>0)mCurrentPosition=EJSS_ODE_SOLVERS.ProblemData.SMALL_POSITIVE;else if(mHBefore==0)mCurrentPosition=EJSS_ODE_SOLVERS.ProblemData.ZERO;else if(mHBefore>-mDiscontinuity.getTolerance())mCurrentPosition=EJSS_ODE_SOLVERS.ProblemData.SMALL_NEGATIVE;else{mCurrentPosition=EJSS_ODE_SOLVERS.ProblemData.NEGATIVE;mNegativeFlag=true}};self.reset(mState);return self};var EJSS_ODE_SOLVERS=EJSS_ODE_SOLVERS||{};EJSS_ODE_SOLVERS.ODEMultistepSolver={NO_ERROR:0,DID_NOT_CONVERGE:1};EJSS_ODE_SOLVERS.createODEMultistepSolver=function(mODE){var self={};var sMaxMessages=3;var mErr_code=EJSS_ODE_SOLVERS.ODEMultistepSolver.NO_ERROR;var mMaxIterations=200;var mEnableExceptions=false;var mErr_msg="";var mFixedStepSize=.1;var mInternalODE=EJSS_ODE_SOLVERS.createODEMultistepSolverInternalODE(mODE);var mODEEngine=EJSS_ODE_SOLVERS.createCashKarp45(mInternalODE);self.enableRuntimeExceptions=function(enable){mEnableExceptions=enable};self.setMaxIterations=function(n){mMaxIterations=Math.max(1,n)};self.setTolerance=function(tol){tol=Math.abs(tol);mODEEngine.setTolerance(tol)};self.getTolerance=function(){return mODEEngine.getTolerance()};self.getErrorCode=function(){return mErr_code};self.initialize=function(stepSize){mMaxMessages=4;mErr_msg="";mErr_code=EJSS_ODE_SOLVERS.ODEMultistepSolver.NO_ERROR;mFixedStepSize=stepSize;mInternalODE.setInitialConditions();mODEEngine.initialize(stepSize)};self.setStepSize=function(stepSize){mMaxMessages=4;mFixedStepSize=stepSize;if(stepSize<0){mODEEngine.setStepSize(Math.max(-Math.abs(mODEEngine.getStepSize()),stepSize))}else{mODEEngine.setStepSize(Math.min(mODEEngine.getStepSize(),stepSize))}};self.setMaximumNumberOfErrorMessages=function(n){mMaxMessages=n};self.getStepSize=function(){return mFixedStepSize};self.step=function(){mErr_code=EJSS_ODE_SOLVERS.ODEMultistepSolver.NO_ERROR;mInternalODE.setInitialConditions();var remainder=0;if(mFixedStepSize>0){remainder=plus()}else{remainder=minus()}mInternalODE.update();return mFixedStepSize-remainder};function plus(){var tol=mODEEngine.getTolerance();var remainder=mFixedStepSize;if(mODEEngine.getStepSize()<=0||mODEEngine.getStepSize()>mFixedStepSize||mFixedStepSize-mODEEngine.getStepSize()==mFixedStepSize){mODEEngine.setStepSize(mFixedStepSize)}var counter=0;while(remainder>tol*mFixedStepSize){counter++;var oldRemainder=remainder;if(remainder<mODEEngine.getStepSize()){var tempStep=mODEEngine.getStepSize();mODEEngine.setStepSize(remainder);var delta=mODEEngine.step();remainder-=delta;mODEEngine.setStepSize(tempStep)}else{remainder-=mODEEngine.step()}if(mODEEngine.getErrorCode()!=EJSS_ODE_SOLVERS.ODEMultistepSolver.NO_ERROR||Math.abs(oldRemainder-remainder)<=Number.MIN_VALUE||tol*mFixedStepSize/10>mODEEngine.getStepSize()||counter>mMaxIterations){mErr_msg="ODEMultiStep did not converge. Remainder="+remainder;mErr_code=EJSS_ODE_SOLVERS.ODEMultistepSolver.DID_NOT_CONVERGE;if(mEnableExceptions){throw mErr_msg}if(mMaxMessages>0){mMaxMessages--;console.log(mErr_msg)}break}}return remainder}function minus(){var tol=mODEEngine.getTolerance();var remainder=mFixedStepSize;if(mODEEngine.getStepSize()>=0||mODEEngine.getStepSize()<mFixedStepSize||mFixedStepSize-mODEEngine.getStepSize()==mFixedStepSize){mODEEngine.setStepSize(mFixedStepSize)}var counter=0;while(remainder<tol*mFixedStepSize){counter++;var oldRemainder=remainder;if(remainder>mODEEngine.getStepSize()){var tempStep=mODEEngine.getStepSize();mODEEngine.setStepSize(remainder);var delta=mODEEngine.step();remainder-=delta;mODEEngine.setStepSize(tempStep)}else{remainder-=mODEEngine.step()}if(mODEEngine.getErrorCode()!=EJSS_ODE_SOLVERS.ODEMultistepSolver.NO_ERROR||Math.abs(oldRemainder-remainder)<=Number.MIN_VALUE||tol*mFixedStepSize/10<mODEEngine.getStepSize()||counter>mMaxIterations){mErr_msg="ODEMultiStep did not converge. Remainder="+remainder;mErr_code=EJSS_ODE_SOLVERS.ODEMultistepSolver.DID_NOT_CONVERGE;if(enableExceptions){throw mErr_msg}if(mMaxMessages>0){mMaxMessages--;console.log(mErr_msg)}}}return remainder}return self};EJSS_ODE_SOLVERS.createODEMultistepSolverInternalODE=function(mODE){var self={};var mEngineState=[];self.getRate=function(state,rate){mODE.getRate(state,rate)};self.getState=function(){return mEngineState};self.setInitialConditions=function(){var state=mODE.getState();if(state==null){return}if(mEngineState==null||mEngineState.length!=state.length){mEngineState=new Array(state.length)}for(var i=0,n=state.length;i<n;i++){mEngineState[i]=state[i]}};self.update=function(){var state=mODE.getState();for(var i=0,n=state.length;i<n;i++){state[i]=mEngineState[i]}};self.setInitialConditions();return self};EJSS_ODE_SOLVERS.createCashKarp45=function(mODE){var self={};var sA=[[1/5],[3/40,9/40],[3/10,-9/10,6/5],[-11/54,5/2,-70/27,35/27],[1631/55296,175/512,575/13824,44275/110592,253/4096]];var sB5=[37/378,0,250/621,125/594,0,512/1771];var sEr=[277/64512,0,-6925/370944,6925/202752,277/14336,-277/7084];var sNumStages=6;var mError_code=EJSS_ODE_SOLVERS.ODEMultistepSolver.NO_ERROR;var mStepSize=.01;var mNumEqn=0;var mTemp_state=[];var mK=[];var mTruncErr;var mTol=1e-6;var mEnableExceptions=false;self.enableRuntimeExpecptions=function(enable){mEnableExceptions=enable};self.setStepSize=function(stepSize){mStepSize=stepSize};self.getStepSize=function(){return mStepSize};self.setTolerance=function(tol){mTol=Math.abs(tol);if(mTol<1e-12){var err_msg="Error: Cash-Karp ODE solver tolerance cannot be smaller than 1.0e-12.";if(mEnableExceptions){throw err_msg}console.log(err_msg);mTol=1e-12}};self.getTolerance=function(){return mTol};self.getErrorCode=function(){return mError_code};self.initialize=function(stepSize){mStepSize=stepSize;var state=mODE.getState();if(state==null){return}if(mNumEqn!=state.length){mNumEqn=state.length;mTemp_state=new Array(mNumEqn);mK=new Array(sNumStages);for(var i=0;i<sNumStages;i++)mK[i]=new Array(mNumEqn)}};self.step=function(){var i,j,s;var iterations=10;var currentStep=mStepSize;var error=0;var state=mODE.getState();mError_code=EJSS_ODE_SOLVERS.ODEMultistepSolver.NO_ERROR;mODE.getRate(state,mK[0]);do{iterations--;currentStep=mStepSize;for(s=1;s<sNumStages;s++){for(i=0;i<mNumEqn;i++){mTemp_state[i]=state[i];for(j=0;j<s;j++){mTemp_state[i]=mTemp_state[i]+mStepSize*sA[s-1][j]*mK[j][i]}}mODE.getRate(mTemp_state,mK[s])}error=0;for(i=0;i<mNumEqn;i++){mTruncErr=0;for(s=0;s<sNumStages;s++){mTruncErr=mTruncErr+mStepSize*sEr[s]*mK[s][i]}error=Math.max(error,Math.abs(mTruncErr))}if(error<=Number.MIN_VALUE){error=mTol/1e5}if(error>mTol){var fac=.9*Math.pow(error/mTol,-.25);mStepSize=mStepSize*Math.max(fac,.1)}else if(error<mTol/10){var fac=.9*Math.pow(error/mTol,-.2);if(fac>1){mStepSize=mStepSize*Math.min(fac,10)}}}while(error>mTol&&iterations>0);for(i=0;i<mNumEqn;i++){for(s=0;s<sNumStages;s++){state[i]+=currentStep*sB5[s]*mK[s][i]}}if(iterations==0){mError_code=EJSS_ODE_SOLVERS.ODEMultistepSolver.DID_NOT_CONVERGE;if(mEnableExceptions){throw"DormanPrince45 ODE solver did not converge."}}return currentStep};self.initialize(mStepSize);return self};var EJSS_ODE_SOLVERS=EJSS_ODE_SOLVERS||{};EJSS_ODE_SOLVERS.createEulerODESolver=function(mODE){var self=EJSS_ODE_SOLVERS.createSolverInterpolatorDiscreteTime(mODE);var mRate;var super_initialize=self.initialize;self.initialize=function(stepSize){super_initialize(stepSize);mRate=new Array(self.getDimension())};self.computeIntermediateStep=function(step,state){mODE.getRate(state,mRate);for(var i=0,n=state.length;i<n;i++){state[i]=state[i]+step*mRate[i]}return state};return self};var EJSS_ODE_SOLVERS=EJSS_ODE_SOLVERS||{};EJSS_ODE_SOLVERS.createRungeKutta4ODESolver=function(mODE){var self=EJSS_ODE_SOLVERS.createSolverInterpolatorDiscreteTime(mODE);var initialState;var mRate1,mRate2,mRate3,mRate4;var super_initialize=self.initialize;self.initialize=function(stepSize){super_initialize(stepSize);initialState=new Array(self.getDimension());mRate1=new Array(self.getDimension());mRate2=new Array(self.getDimension());mRate3=new Array(self.getDimension());mRate4=new Array(self.getDimension())};self.computeIntermediateStep=function(step,state){mODE.getRate(state,mRate1);for(var i=0,n=state.length;i<n;i++){initialState[i]=state[i];state[i]=initialState[i]+step*mRate1[i]/2}mODE.getRate(state,mRate2);for(var i=0,n=state.length;i<n;i++){state[i]=initialState[i]+step*mRate2[i]/2}mODE.getRate(state,mRate3);for(var i=0,n=state.length;i<n;i++){state[i]=initialState[i]+step*mRate3[i]}mODE.getRate(state,mRate4);for(var i=0,n=state.length;i<n;i++){state[i]=initialState[i]+step*(mRate1[i]+2*mRate2[i]+2*mRate3[i]+mRate4[i])/6}return state};return self};var EJSS_ODE_SOLVERS=EJSS_ODE_SOLVERS||{};EJSS_ODE_SOLVERS.SolverInterpolatorDiscreteTime={};EJSS_ODE_SOLVERS.createSolverInterpolatorDiscreteTime=function(mODE){var self={};var mErrorCode=0;var mDimension;var mTimeIndex;var mAccumulatedEvaluations=0;var mStepSize=.1;var mMaximumStepSize=Number.POSITIVE_INFINITY;var mInitialTime=0;var mFinalTime=0;var mInitialState;var mInitialRate;var mFinalState;var mFinalRate;var mRelativeTolerance=0;var mIsDDE=false;var mDiscontinuities=[];var mNextDiscontinuity;var mStateHistoryLength;self.getNumberOfEvaluations=function(){return 0};self.allocateOtherArrays=function(){};self.computeIntermediateStep=function(step,state){return null};self.computeCarefulIntermediateStep=function(eventSolver,step,state){return 0};self.setTolerance=function(tolerance){mRelativeTolerance=Math.abs(tolerance)};self.getDimension=function(){return mDimension};self.initialize=function(stepSize){mStepSize=stepSize;var state=mODE.getState();mDimension=state.length};self.step=function(){var state=mODE.getState();self.computeIntermediateStep(mStepSize,state);return 0};self.setStepSize=function(stepSize){mStepSize=stepSize};self.getStepSize=function(){return mStepSize};return self};var EJSS_CORE=EJSS_CORE||{};EJSS_CORE.createRemoteView=function(mContainer,mLocalModelPort,mModelsURL,mModel){var self=EJSS_CORE.createView(mContainer);var mNumOpenTries=10;var mOpenTimeout=500;var mWebsocket;var mMessages={};var mIsOpen=false;var mOpenTry=0;var mCurrentData={};var mVariableList=[];var mActionList=[];var mPropertyChangesList=[];var mActionsInvokedList=[];var mUpdating=false;var mDelayedUpdate=false;var mVarsMetadata=[];var mMethodsMetadata=[];var mLinkingURL="";var mShowLinkingButtons=true;var mServerModelPort=0;var wrap;var mUri="";var countTo=0;self._23=function(){return"ConnectionWS"};function sendMessage(command,data){if(!mIsOpen)return;if(data!==undefined){mWebsocket.send(command+JSON.stringify(data))}else{mWebsocket.send(command)}var f=mWebsocket.onmessage;mWebsocket.onmessage=null;mWebsocket.onmessage=f}function processInput(input){console.log(" --\x3e Processing input: "+input);var message;var usefulValues={};if(input.charAt(0)=="{"){message=JSON.parse(input);var method="";if(message.hasOwnProperty("method")){method=message.method;if(method=="reset")self._reset();else if(method=="initialize")self._initialize();else if(wrap!=undefined){usefulValues=wrap.extract(input);mCurrentData=usefulValues;coallesce(self._update)}}if(message.hasOwnProperty("apiVersion")){console.log("Metadata Obtained");wrap=new wrapper(mWebsocket,input);for(var variable in mVariableList){wrap.get(mVariableList[variable],true)}}}else{processNotSmartInput(input)}}function processNotSmartInput(input){var message;switch(input.charAt(0)){case"R":self._reset();break;case"I":self._initialize();break;case"U":mCurrentData=JSON.parse(input.substring(1));coallesce(self._update);break;case"C":mCurrentData=JSON.parse(input.substring(1));coallesce(self._collectData);break;case"M":message=JSON.parse(input.substring(1));if(!self[message.method])console.log("View function: <"+message.method+"> with data: <"+message.data+"> ignored. View function does not exist.");else self[message.method](message.data);break;case"P":message=JSON.parse(input.substring(1));if(self[message.element])self[message.element].setProperty(message.property,message.value);else console.log("setProperty<"+message.property+"> with value: <"+message.value+"> to element <"+message.element+"> ignored. Element does not exist!");break;case"E":message=JSON.parse(input.substring(1));if(self[message.element])self[message.element][message.method](message.data);else console.log("Message <"+message.method+"> to element <"+message.element+"> ignored. Element does not exist!");break;case"F":message=JSON.parse(input.substring(1));if(self[message.element])self[message.element][message.method](message.data);else console.log("Message with object <"+message.method+"> to element <"+message.element+"> ignored. Element does not exist!");break;case"D":message=JSON.parse(input.substring(1));mVarsMetadata=message.variables;mMethodsMetadata=message.methods;break;default:console.log("Not known message: Ignoring");break}}function coallesce(viewFunction){viewFunction();self._render()}self._connectToServer=function(){try{mWebsocket=new WebSocket(mUri);console.log("Connecting... (readyState "+mWebsocket.readyState+")");mWebsocket.onopen=function(message){mIsOpen=true;mOpenTry=0;console.log("Openhd Event: "+message.type+" - Message: "+message.data);sendMessage("",{method:"getMetadata"})};mWebsocket.onclose=function(message){if(mOpenTry<mNumOpenTries){window.setTimeout(function(){self._connectToServer()},mOpenTimeout);mOpenTry++}mIsOpen=false;console.log("Closehd Event: "+message.type+" - Message: "+message.data+" - Reopen: "+mOpenTry)};mWebsocket.onerror=function(message){mIsOpen=false;console.log("Errorhd Event: "+message.type+" - Message: "+message.data)};mWebsocket.onmessage=function(message){processInput(message.data)}}catch(exception){console.log(exception)}self._update();self._render()};self._getValue=function(variable){if(mIsOpen)return mCurrentData[variable];return self._10(variable)};super_registerVariable=self._5;super_registerAction=self._7;super_startUp=self._11;self._11=function(){super_startUp();self._connectToServer()};self._5=function(variable,initialValue,inputOnly){super_registerVariable(variable,initialValue);if(inputOnly){self._13(variable,function(){return self._getValue(variable)},null,initialValue)}else{mVariableList.push(variable);self._13(variable,function(){return self._getValue(variable)},function(value){mPropertyChangesList.push({name:variable,value:value})},initialValue)}};self._7=function(action){super_registerAction(action);mActionList.push(action);self._setAction(action,function(data){mActionsInvokedList.push({name:action,argument:data})})};self._18=function(){self._16();var names={};var values={};if(mPropertyChangesList.length>0){for(var propChange in mPropertyChangesList){if(mPropertyChangesList[propChange].hasOwnProperty("name"))names[propChange]=mPropertyChangesList[propChange].name;values[propChange]=mPropertyChangesList[propChange].value}wrap.set(names,values,"")}if(mActionsInvokedList.length>0){for(var actInvoke in mActionsInvokedList){wrap.callAction(mActionsInvokedList[actInvoke].name,[mActionsInvokedList[actInvoke].argument])}}mPropertyChangesList=[];mActionsInvokedList=[]};self._17=function(){return mActionsInvokedList.length};self.getLinkingURL=function(){return mLinkingURL};self.createLinkingButtons=function(){self._9(EJSS_INTERFACE.button,"_linkingButton_").setAction("OnClick",function(){var str=self.getLinkingURL();window.alert(str.toString())}).setProperties({Text:"@",FontSize:"8px"});self._9(EJSS_INTERFACE.button,"_qrButton_").setAction("OnClick",function(){var str=encodeURIComponent(self.getLinkingURL());var url="https://chart.googleapis.com/chart?cht=qr&chl="+str+"&chs=400";window.open(url,"_blank")}).setProperties({Text:"QR",FontSize:"8px"})};self.hiddenLinkingButtons=function(){_view._linkingButton_.setVisibility("hidden");_view._qrButton_.setVisibility("hidden")};self.showLinkingButtons=function(){_view._linkingButton_.setVisibility("visible");_view._qrButton_.setVisibility("visible")};if(window.location.protocol.indexOf("file")!=-1){if(typeof mLocalModelPort=="undefined"||mLocalModelPort===null||mLocalModelPort==0){mLocalModelPort=8800}mUri="ws://localhost:"+mLocalModelPort;mShowLinkingButtons=false}else{if(history.state){mServerModelPort=history.state.mServerModelPort;mShowLinkingButtons=false}if(typeof mModelsURL=="undefined"||mModelsURL===null||mModelsURL==""){var host=window.location.host;var proto=window.location.protocol;mModelsURL=proto+"//"+host+"/ejsS_library/models"}if(typeof mModel=="undefined"||mModel===null||mModel==""){var index=window.location.href.lastIndexOf("/_view");mModel=window.location.href.slice(mModelsURL.length,index)}var xmlhttp=new XMLHttpRequest;if(mServerModelPort>0){xmlhttp.open("GET",mModelsURL+"/broker.php?model="+mModel+"&port="+mServerModelPort,true)}else{xmlhttp.open("GET",mModelsURL+"/broker.php?model="+mModel,true)}xmlhttp.onreadystatechange=function(){if(xmlhttp.readyState==4&&xmlhttp.status==200){var response=JSON.parse(xmlhttp.responseText);mUri=response.webserver;mLinkingURL=mModelsURL+"/linking.php?model="+mModel+"&port="+response.port;if(mShowLinkingButtons)self.createLinkingButtons();self._11()}else console.log("WARNING: server no response!")};xmlhttp.send()}return self};var EJSS_TOOLS=EJSS_TOOLS||{};EJSS_TOOLS.addToArray=function(array,object,position){EJSS_TOOLS.removeFromArray(array,object);if(position>=0)array.splice(position,0,object);else array.push(object)};EJSS_TOOLS.arrayObjectIndexOf=function(array,object){return array.indexOf(object)};EJSS_TOOLS.removeFromArray=function(array,object){var index=array.indexOf(object);if(index>=0)array.splice(index,1)};EJSS_TOOLS.compareArrays=function(array1,array2){if(!array1||!array2)return false;if(!array1 instanceof Array||!array2 instanceof Array){return array1==array2}if(array1.length!=array2.length)return false;for(var i=0;i<array1.length;i++){if(array1[i]instanceof Array&&array2[i]instanceof Array){if(!EJSS_TOOLS.compareArrays(array1[i],array2[i]))return false}else if(array1[i]!=array2[i]){return false}}return true};var EJSS_TOOLS=EJSS_TOOLS||{};EJSS_TOOLS.ConnectionWS={};EJSS_TOOLS.connectionWS=function(mUri){var self={};var websocket;var messages={};var open;self._23=function(){return"ConnectionWS"};self.get=function(property){var result=messages[property];if(typeof result!="undefined"||result==null)return result};self.set=function(property,args){console.log("set:"+property+":"+args.toString());console.log("set:is open="+open);if(open){var message=property+" "+args.toString();websocket.send(message);self.reset()}};self.reset=function(){var f=websocket.onmessage;websocket.onmessage=null;websocket.onmessage=f};function connect(){try{websocket=new WebSocket(mUri);console.log("Connecting... (readyState "+websocket.readyState+")")}catch(exception){console.log(exception)}}function listener(event,handler){switch(event){case"onopen":websocket.onopen=function(e){handler(e)};break;case"onmessage":websocket.onmessage=function(e){handler(e)};break;case"onclose":websocket.onclose=function(e){handler(e)};break;case"onerror":websocket.onerror=function(e){handler(e)};break;default:break}}function messagehd(message){var words=message.data.split(" ");messages[words[0]]=message.data.substring(words[0].length+1)}function openhd(message){open=true;console.log("Openhd Event: "+message.type+" - Message: "+message.data)}function closehd(message){open=false;console.log("Closehd Event: "+message.type+" - Message: "+message.data)}function errorhd(message){open=false;console.log("Errorhd Event: "+message.type+" - Message: "+message.data)}connect();listener("onopen",openhd);listener("onclose",closehd);listener("onerror",errorhd);listener("onmessage",messagehd);return self};var EJSS_TOOLS=EJSS_TOOLS||{};EJSS_TOOLS.Decode={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",hex_to_ascii:function(input){var hex=input.toString();var str="";for(var n=0;n<hex.length;n+=2){str+=String.fromCharCode(parseInt(hex.substr(n,2),16))}return str},decode:function(input){input=""+input;var output="";var chr1,chr2,chr3;var enc1,enc2,enc3,enc4;var i=0;input=input.replace(/[^A-Za-z0-9\+\/\=]/g,"");while(i<input.length){enc1=this._keyStr.indexOf(input.charAt(i++));enc2=this._keyStr.indexOf(input.charAt(i++));enc3=this._keyStr.indexOf(input.charAt(i++));enc4=this._keyStr.indexOf(input.charAt(i++));chr1=enc1<<2|enc2>>4;chr2=(enc2&15)<<4|enc3>>2;chr3=(enc3&3)<<6|enc4;output=output+String.fromCharCode(chr1);if(enc3!=64){output=output+String.fromCharCode(chr2)}if(enc4!=64){output=output+String.fromCharCode(chr3)}}output=EJSS_TOOLS.Decode._utf8_decode(output);return output},_utf8_decode:function(utftext){var string="";var i=0;var c=c1=c2=0;while(i<utftext.length){c=utftext.charCodeAt(i);if(c<128){string+=String.fromCharCode(c);i++}else if(c>191&&c<224){c2=utftext.charCodeAt(i+1);string+=String.fromCharCode((c&31)<<6|c2&63);i+=2}else{c2=utftext.charCodeAt(i+1);c3=utftext.charCodeAt(i+2);string+=String.fromCharCode((c&15)<<12|(c2&63)<<6|c3&63);i+=3}}return string}};var EJSS_TOOLS=EJSS_TOOLS||{};EJSS_TOOLS.DisplayColors={phaseColors:{},lineColors:["rgb(255,0,0)","rgb(0,240,0)","rgb(0,0,255)","rgb(240,240,0)","rgb(0,240,240)","rgb(255,0,255)"],markerColors:["rgb(255,0,0)","rgb(0,240,0)","rgb(0,0,255)","rgb(240,240,0)","rgb(0,240,240)","rgb(255,0,255)"],arrayColors:{black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,160],darkcyan:[0,240,240],darkgray:[64,64,64],darkgreen:[0,240,0],darkgrey:[64,64,64],darkyellow:[240,240,0],gray:[125,125,125],green:[0,255,0],grey:[125,125,125],lightblue:[173,216,230],lightgray:[192,192,192],lightgrey:[192,192,192],magenta:[255,0,255],maroon:[128,0,0],olive:[128,128,0],orange:[255,165,0],pink:[255,175,175],purple:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]},getLineColor:function(index){var color=EJSS_TOOLS.DisplayColors.lineColors[index];if(color===undefined){var h=index*360/12%360;color="hsl("+h+",100%,50%)";EJSS_TOOLS.DisplayColors.lineColors[index]=color}return color},getMarkerColor:function(index){var color=EJSS_TOOLS.DisplayColors.markerColors[index];if(color===undefined){var h=index*360/12%360;color="hsl("+h+",100%,100%)";EJSS_TOOLS.DisplayColors.markerColors[index]=color}return color},getArrayColor:function(str){str=str.toLowerCase();if(str.indexOf("rgb")==0){var color=str.substring(4,str.length-1).replace(/ /g,"").split(",")}else if(str.indexOf("#")==0){str=str.slice(1);str=str.toUpperCase();var hex_alphabets="0123456789ABCDEF";var color=new Array(3);var k=0;var int1,int2;for(var i=0;i<6;i+=2){int1=hex_alphabets.indexOf(str.charAt(i));int2=hex_alphabets.indexOf(str.charAt(i+1));color[k]=int1*16+int2;k++}}else{var color=EJSS_TOOLS.DisplayColors.arrayColors[str];if(color===undefined){color=EJSS_TOOLS.DisplayColors.arrayColors["black"]}}return[color[0]/255,color[1]/255,color[2]/255]}};var EJSS_TOOLS=EJSS_TOOLS||{};EJSS_TOOLS.enumeration=function(namesToValues){var enumeration=function(){throw"Can't Instantiate Enumerations"};var proto=enumeration.prototype={constructor:enumeration,toString:function(){return this.name},valueOf:function(){return this.value},toJSON:function(){return this.name}};enumeration.values=[];for(var name in namesToValues){var e=inherit(proto);e.name=name;e.value=namesToValues[name];enumeration[name]=e;enumeration.values.push(e)}enumeration.foreach=function(f,c){for(var i=0;i<this.values.length;i++)f.call(c,this.values[i])};return enumeration};var EJSS_TOOLS=EJSS_TOOLS||{};EJSS_TOOLS.File={JSLoaded:"",loadJSfile:function(filename,scriptLoaded){if(EJSS_TOOLS.File.JSLoaded.indexOf("["+filename+"]")!=-1){console.log("File already loaded "+filename);scriptLoaded();return}EJSS_TOOLS.File.JSLoaded+="["+filename+"]";var fileref=document.createElement("script");fileref.setAttribute("type","text/javascript");fileref.setAttribute("src",filename);if(typeof scriptLoaded!="undefined")fileref.onload=scriptLoaded;document.getElementsByTagName("head")[0].appendChild(fileref)},plainName:function(filename){var index=filename.lastIndexOf("/");if(index>=0)filename=filename.substring(index+1);index=filename.indexOf(".");if(index>0)filename=filename.substring(0,index);return filename},download:function(filename,text){var pom=document.createElement("a");pom.setAttribute("href","data:application/ejss;charset=utf-8,"+encodeURIComponent(text));pom.setAttribute("download",filename);pom.click()},loadScript:function(scriptsrc){var s=document.createElement("script");s.type="text/javascript";s.src=scriptsrc;document.getElementsByTagName("head")[0].appendChild(s)},loadJSONFile:function(url,callback){var xmlhttp=new XMLHttpRequest;xmlhttp.onreadystatechange=function(){if(xmlhttp.readyState==4&&xmlhttp.status==200){var myArr=JSON.parse(xmlhttp.responseText);callback(myArr)}};xmlhttp.open("GET",url,true);xmlhttp.send()},requestShortUrl:function(json,callback){var encoded=escape("http://urlecho.appspot.com/echo?status=200&Content-Type=text/plain&body="+json);EJSS_TOOLS.File.CALLBACK=callback;EJSS_TOOLS.File.callFunction=function(data){EJSS_TOOLS.File.CALLBACK(data.shortUrl)};if(document.getElementById("__rtShortUrl")==null){var scb=document.createElement("script");scb.type="text/javascript";scb.id="__rtShortUrl";scb.innerHTML="function rtShortUrl(data) { EJSS_TOOLS.File.callFunction(data); }";document.getElementsByTagName("head")[0].appendChild(scb)}var s=document.getElementById("_requestShortUrl");if(s!=null)document.getElementsByTagName("head")[0].removeChild(s);s=document.createElement("script");s.id="_requestShortUrl";s.type="text/javascript";s.src="http://b1t.co/Site/api/External/MakeUrlWithGet?callback=rtShortUrl&url="+encoded;document.getElementsByTagName("head")[0].appendChild(s)}};var EJSS_TOOLS=EJSS_TOOLS||{};EJSS_TOOLS.JsonrpcBuilder={template:{METHOD:"${METHOD}",PARAMS:"${PARAMS}",ID:"${ID}",REQUEST:'{jsonrpc: "2.0", method: ${METHOD}, params: ${PARAMS}, id: ${ID}}',RESPONSE_OK:'{jsonrpc: "2.0", result: ${RESULT}, params: ${PARAMS}, id: ${ID}}',RESPONSE_ERROR:'{jsonrpc: "2.0", method: ${METHOD}, params: ${PARAMS}, id: ${ID}}',ERROR:'{code: "2.0", message: ${MESSAGE}, data: ${DATA}}'},request:function(method,params,id){if(params&&!(params instanceof Array))throw new InvalidParamsException;var request={jsonrpc:"2.0",method:method};if(params)request.params=params;if(id)request.id=id;return request},response:function(result,id){return{jsonrpc:"2.0",result:result,id:id}},responseWithError:function(error,id){return{jsonrpc:"2.0",error:error,id:id}},error:function(code,message,data){return{code:code,message:message,data:data}},parseResponse:function(resString){var response=null;try{response=JSON.parse(resString)}catch(error){console.log(error)}return response!=null?response.result:null}};var EJSS_TOOLS=EJSS_TOOLS||{};EJSS_TOOLS.JsonrpcClient={methods:{connect:"connect",open:"open",getMetadata:"getMetadata",getValue:"getValue",setValue:"setValue",close:"close",
disconnect:"disconnect"}};EJSS_TOOLS.jsonrpcClient=function(mHost,mPort){var self={};var JsonrpcClient=EJSS_TOOLS.JsonrpcClient;var JsonrpcBuilder=EJSS_TOOLS.JsonrpcBuilder;var websocket;var mCallback={};var mOpenCallback;var mCloseCallback;var mErrorCallback;var mMessageCallback;self.connect=function(callback){return callMethod(JsonrpcClient.methods.connect,null,callback)};self.open=function(callback){return callMethod(JsonrpcClient.methods.open,null,callback)};self.getValue=function(name,callback){return callMethod(JsonrpcClient.methods.getValue,[name],callback)};self.setValue=function(data,callback){return callMethod(JsonrpcClient.methods.setValue,data,callback)};self.getMetadata=function(callback){return callMethod(JsonrpcClient.methods.getMetadata,null,callback)};self.disconnect=function(callback){return callMethod(JsonrpcClient.methods.disconnect,null,callback)};self.close=function(callback){return callMethod(JsonrpcClient.methods.close,null,callback)};function idGenerator(len){var text="";var charset="abcdefghijklmnopqrstuvwxyz";for(var i=0;i<len;i++)text+=charset.charAt(Math.floor(Math.random()*charset.length));return text}function callMethod(method,params,callback,_id){var id=_id?_id:idGenerator(12);if(callback)mCallback[id]=callback;var request=JsonrpcBuilder.request(method,params,id);websocket.send(JSON.stringify(request))}self.init=function(opencb,messcb,errorcb,closecb){try{mOpenCallback=opencb;mErrorCallback=errorcb;mCloseCallback=closecb;mMessageCallback=messcb;var uri="ws://"+mHost;if(mPort)uri+=":"+mPort;websocket=new WebSocket(uri);addListener();console.log("Connecting... (readyState "+websocket.readyState+")")}catch(exception){console.log(exception)}};self.finish=function(){try{websocket.close()}catch(exception){console.log(exception)}};function addListener(){websocket.onopen=function(message){if(mOpenCallback)mOpenCallback(message);console.log("Openhd Event: "+message.type+" - Message: "+message.data)};websocket.onmessage=function(message){var data=JSON.parse(message.data);if(mMessageCallback)mMessageCallback(mCallback);if(data.id&&mCallback[data.id])mCallback[data.id](data.result)};websocket.onclose=function(emessage){if(mCloseCallback)mCloseCallback(message);console.log("Closehd Event: "+message.type+" - Message: "+message.data)};websocket.onerror=function(message){if(mErrorCallback)mErrorCallback(message);console.log("Errorhd Event: "+message.type+" - Message: "+message.data)}}return self};var EJSS_TOOLS=EJSS_TOOLS||{};EJSS_TOOLS.Mathematics={TWO_PI:2*3.1415926,TO_RADIANS:Math.PI/180,LOG10SCALE:1/Math.log(10),cosineAndSine:[],cosineAndSineForDegrees:function(degrees){degrees%=360;if(degrees<0)degrees+=360;var values=this.cosineAndSine[degrees];if(values===undefined){var radians=degrees*this.TO_RADIANS;values=[Math.cos(radians),Math.sin(radians)]}return values},radians:function(degrees){return degrees*Math.PI/180},degrees:function(radians){var angle=radians*180/Math.PI;var r=angle%360;angle=r*360<0?r+360:r;return angle},norm:function(v){var sum=0;for(var i=0;i<v.length;i++)sum+=v[i]*v[i];return Math.sqrt(sum)},crossProduct:function(v1,v2){return[v1[1]*v2[2]-v1[2]*v2[1],v1[2]*v2[0]-v1[0]*v2[2],v1[0]*v2[1]-v1[1]*v2[0]]},normalize:function(v){var r=EJSS_TOOLS.Mathematics.norm(v);if(r==0)return v;return[v[0]/r,v[1]/r,v[2]/r]},normalTo:function(v){if(v[0]==0){return[1,0,0]}else if(v[1]==0){return[0,1,0]}else if(v[2]==0){return[0,0,1]}else{var norm=EJSS_TOOLS.Mathematics.norm(v);return[-v[1]/norm,v[0]/norm,0]}},rotate:function(vc,v,radians){var cos=Math.cos(radians),sin=Math.sin(radians),nx=cos*(v[0]-vc[0])+sin*(v[1]-vc[1])+vc[0],ny=cos*(v[1]-vc[1])-sin*(v[0]-vc[0])+vc[1];return[nx,ny]}};sensors={iOS_accelerometer:{x:0,y:0,z:0},iOS_gyroscope:{x:0,y:0,z:0},setAccelerometer:function(accvalue){var value=JSON.parse(accvalue);var accelerometer=eval(value.result);if(window.innerWidth>window.innerHeight)sensors.iOS_accelerometer={x:accelerometer.y,y:-accelerometer.x,z:accelerometer.z};else sensors.iOS_accelerometer=accelerometer},setGyroscope:function(gyrvalue){var value=JSON.parse(gyrvalue);var gyroscope=eval(value.result);if(window.innerWidth>window.innerHeight)sensors.iOS_gyroscope={x:gyroscope.y,y:-gyroscope.x,z:gyroscope.z};else sensors.iOS_gyroscope=gyroscope},iOS_staccelerometer:{x:0,y:0,z:0},iOS_stgyroscope:{x:0,y:0,z:0},iOS_stmagnetometer:{x:0,y:0,z:0},iOS_sthumidity:0,iOS_sttempamb:0,iOS_sttempir:0,iOS_stpressure:0,setSensorTag:function(stvalue){var value=JSON.parse(stvalue);var results=eval(value.result);sensors.iOS_staccelerometer={x:results.accx,y:results.accy,z:results.accz};sensors.iOS_stgyroscope={x:results.gyrox,y:results.gyroy,z:results.gyroz};sensors.iOS_stmagnetometer={x:results.magx,y:results.magy,z:results.magz};sensors.iOS_sthumidity=results.hum;sensors.iOS_sttempamb=results.tamb;sensors.iOS_sttempir=results.tir;sensors.iOS_stpressure=results.press},calliOSFunction:function(functionName,args,successCallback,errorCallback){var url="ejss://";var callInfo={};callInfo.functionname=functionName;if(successCallback)callInfo.success=successCallback;if(errorCallback)callInfo.error=errorCallback;if(args)callInfo.args=args;url+=JSON.stringify(callInfo);window.location=url},isSupportedSensorTag:function(){var is_iOSwebview=/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i.test(navigator.userAgent);return is_iOSwebview},runSensorTag:function(accperiod,magperiod){var is_iOSwebview=/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i.test(navigator.userAgent);if(is_iOSwebview){var args=[];args[0]=accperiod;args[1]=magperiod;sensors.calliOSFunction("runSensorTag",args,"sensors.setSensorTag")}},stopSensorTag:function(){var is_iOSwebview=/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i.test(navigator.userAgent);if(is_iOSwebview){sensors.calliOSFunction("stopSensorTag")}},getSensorTagAccelerometer:function(){return sensors.iOS_staccelerometer},getSensorTagGyroscope:function(){return sensors.iOS_stgyroscope},getSensorTagMagnetometer:function(){return sensors.iOS_stmagnetometer},getSensorTagTempAmb:function(){return sensors.iOS_sttempamb},getSensorTagTempIR:function(){return sensors.iOS_sttempir},getSensorTagPressure:function(){return sensors.iOS_stpressure},getSensorTagHumidity:function(){return sensors.iOS_sthumidity},isAccelerometer:function(){var is_Androidwebview=window.android&&window.android.isAccelerometer();var is_iOSwebview=/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i.test(navigator.userAgent);return is_Androidwebview||is_iOSwebview},runAccelerometer:function(){var is_Androidwebview=window.android&&window.android.isAccelerometer();var is_iOSwebview=/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i.test(navigator.userAgent);if(is_Androidwebview){window.android.runAccelerometer()}else if(is_iOSwebview){sensors.calliOSFunction("runAccelerometer","","sensors.setAccelerometer")}},stopAccelerometer:function(){var is_Androidwebview=window.android&&window.android.isAccelerometer();var is_iOSwebview=/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i.test(navigator.userAgent);if(is_Androidwebview){window.android.stopAccelerometer()}else if(is_iOSwebview){sensors.calliOSFunction("stopAccelerometer")}},getAccelerometer:function(){var is_Androidwebview=window.android&&window.android.isAccelerometer();var is_iOSwebview=/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i.test(navigator.userAgent);if(is_Androidwebview){var value=eval(window.android.getAccelerometer());if(window.innerWidth>window.innerHeight)return value;else return{x:value.y,y:-value.x,z:value.z}}else if(is_iOSwebview){return sensors.iOS_accelerometer}return{x:0,y:0,z:0}},isGyroscope:function(){var is_Androidwebview=window.android&&window.android.isGyroscope();var is_iOSwebview=/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i.test(navigator.userAgent);return is_Androidwebview||is_iOSwebview},runGyroscope:function(){var is_Androidwebview=window.android&&window.android.isGyroscope();var is_iOSwebview=/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i.test(navigator.userAgent);if(is_Androidwebview){window.android.runGyroscope()}else if(is_iOSwebview){sensors.calliOSFunction("runGyroscope","","sensors.setGyroscope")}},stopGyroscope:function(){var is_Androidwebview=window.android&&window.android.isGyroscope();var is_iOSwebview=/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i.test(navigator.userAgent);if(is_Androidwebview){window.android.stopGyroscope()}else if(is_iOSwebview){sensors.calliOSFunction("stopGyroscope")}},getGyroscope:function(){var is_Androidwebview=window.android&&window.android.isGyroscope();var is_iOSwebview=/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i.test(navigator.userAgent);if(is_Androidwebview){var value=eval(window.android.getGyroscope());if(window.innerWidth>window.innerHeight)return value;else return{x:value.y,y:-value.x,z:value.z}}else if(is_iOSwebview){return sensors.iOS_gyroscope}return{x:0,y:0,z:0}},isGravity:function(){var is_Androidwebview=window.android&&window.android.isGravity();return is_Androidwebview},runGravity:function(){var is_Androidwebview=window.android&&window.android.isGravity();if(is_Androidwebview){window.android.runGravity()}},stopGravity:function(){var is_Androidwebview=window.android&&window.android.isGravity();if(is_Androidwebview){window.android.stopGravity()}},getGravity:function(){var is_Androidwebview=window.android&&window.android.isGravity();if(is_Androidwebview){return window.android.getGravity()}return{x:0,y:0,z:0}},isLinearAcceleration:function(){var is_Androidwebview=window.android&&window.android.isLinearAcceleration();return is_Androidwebview},runLinearAcceleration:function(){var is_Androidwebview=window.android&&window.android.isLinearAcceleration();if(is_Androidwebview){window.android.runLinearAcceleration()}},stopLinearAcceleration:function(){var is_Androidwebview=window.android&&window.android.isLinearAcceleration();if(is_Androidwebview){window.android.stopLinearAcceleration()}},getLinearAcceleration:function(){var is_Androidwebview=window.android&&window.android.isLinearAcceleration();if(is_Androidwebview){return window.android.getLinearAcceleration()}return{x:0,y:0,z:0}},isRotationVector:function(){var is_Androidwebview=window.android&&window.android.isRotationVector();return is_Androidwebview},runRotationVector:function(){var is_Androidwebview=window.android&&window.android.isRotationVector();if(is_Androidwebview){window.android.runRotationVector()}},stopRotationVector:function(){var is_Androidwebview=window.android&&window.android.isRotationVector();if(is_Androidwebview){window.android.stopRotationVector()}},getRotationVector:function(){var is_Androidwebview=window.android&&window.android.isRotationVector();if(is_Androidwebview){return window.android.getRotationVector()}return{x:0,y:0,z:0}},isMagneticField:function(){var is_Androidwebview=window.android&&window.android.isMagneticField();return is_Androidwebview},runMagneticField:function(){var is_Androidwebview=window.android&&window.android.isMagneticField();if(is_Androidwebview){window.android.runMagneticField()}},stopMagneticField:function(){var is_Androidwebview=window.android&&window.android.isMagneticField();if(is_Androidwebview){window.android.stopMagneticField()}},getMagneticField:function(){var is_Androidwebview=window.android&&window.android.isMagneticField();if(is_Androidwebview){return window.android.getMagneticField()}return{x:0,y:0,z:0}},isAmbientTemperature:function(){var is_Androidwebview=window.android&&window.android.isAmbientTemperature();return is_Androidwebview},runAmbientTemperature:function(){var is_Androidwebview=window.android&&window.android.isAmbientTemperature();if(is_Androidwebview){window.android.runAmbientTemperature()}},stopAmbientTemperature:function(){var is_Androidwebview=window.android&&window.android.isAmbientTemperature();if(is_Androidwebview){window.android.stopAmbientTemperature()}},getAmbientTemperature:function(){var is_Androidwebview=window.android&&window.android.isAmbientTemperature();if(is_Androidwebview){return window.android.getAmbientTemperature()}return 0},isLight:function(){var is_Androidwebview=window.android&&window.android.isLight();return is_Androidwebview},runLight:function(){var is_Androidwebview=window.android&&window.android.isLight();if(is_Androidwebview){window.android.runLight()}},stopLight:function(){var is_Androidwebview=window.android&&window.android.isLight();if(is_Androidwebview){window.android.stopLight()}},getLight:function(){var is_Androidwebview=window.android&&window.android.isLight();if(is_Androidwebview){return window.android.getLight()}return 0},isPressure:function(){var is_Androidwebview=window.android&&window.android.isPressure();return is_Androidwebview},runPressure:function(){var is_Androidwebview=window.android&&window.android.isPressure();if(is_Androidwebview){window.android.runPressure()}},stopPressure:function(){var is_Androidwebview=window.android&&window.android.isPressure();if(is_Androidwebview){window.android.stopPressure()}},getPressure:function(){var is_Androidwebview=window.android&&window.android.isPressure();if(is_Androidwebview){return window.android.getPressure()}return 0},isHumidity:function(){var is_Androidwebview=window.android&&window.android.isHumidity();return is_Androidwebview},runHumidity:function(){var is_Androidwebview=window.android&&window.android.isHumidity();if(is_Androidwebview){window.android.runHumidity()}},stopHumidity:function(){var is_Androidwebview=window.android&&window.android.isHumidity();if(is_Androidwebview){window.android.stopHumidity()}},getHumidity:function(){var is_Androidwebview=window.android&&window.android.isHumidity();if(is_Androidwebview){return window.android.getHumidity()}return 0}};function _smartDevice(ws,data){this.websocket=ws;this.loadMetadata(data);return this}_smartDevice.prototype={metadata:"",apis:[],models:"",modelsTemplate:[],apisFn:[],loadMetadata:function(data){this.metadata=JSON.parse(data)},loadModels:function(){this.models=this.metadata.models},loadApis:function(){this.apis=this.metadata.apis},getModelTemplate:function(name){if(this.models.hasOwnProperty(name)){var model=JSON.parse(JSON.stringify(this.models[name]));var name=model.id;var properties=model.properties;return model}else{writeToScreen('<span style="color: red;">ERROR:</span> '+name+" is not a key -> "+"Model Not found");return null}},generateMethodCall:function(operationName){for(var i=0;i<this.apis.length;i++){var api=this.apis[i];var operations=api.operations;for(var j=0;j<operations.length;j++){var op=operations[j];if(op.nickname==operationName||operationName==undefined){var parameters=op.parameters[0];var usingModel=this.getModelTemplate(parameters.type);var params=usingModel.properties;var required;if(usingModel.hasOwnProperty("required"))required=usingModel.required;var jsonTosend="{";var paramToSend=[];var notFirstTime=false;for(var par in params){if(notFirstTime){jsonTosend+=","}else notFirstTime=true;jsonTosend+="'"+par+"' : "+par;paramToSend.push(par)}jsonTosend+="}";var body="{";if(required!=undefined){for(var req in required){body+="if( "+required[req]+"== undefined) { \n"+"console.log('Required parameter, "+required[req]+" : must be an input'); \n"+"return null;} \n"}}body+="this.websocket.send(JSON.stringify("+jsonTosend+"))";body+="}";this[op.nickname]=new Function(paramToSend,body)}}}return true},generateModelFilling:function(modelName){for(var mod in this.models){if(mod==modelName||modelName==undefined){var usingModel=this.models[mod];var params=usingModel.properties;var required;if(usingModel.hasOwnProperty("required"))required=usingModel.required;var paramToSend=[];var body="";body+="{\n";body+="\t var json2send=this.getModelTemplate('"+mod+"').properties;\n";for(var par in params){paramToSend.push(par);body+="\t if( "+par+" != undefined) { \n";body+="\t\t json2send['"+par+"']="+par+"; \n";body+="\t }else{\n";body+="\t\t delete json2send."+par+";\n";body+="\t }\n"}if(required!=undefined){for(var req in required){body+="\t if( "+req+"== undefined) { \n"+"\t\t console.log('Required parameter, "+req+" : must be an input'); \n"+"\t\t return null; \n";body+="\t }\n"}}body+="\t return json2send;";body+="}";this["fill"+mod]=new Function(paramToSend,body)}}return true},bindFunctions:function(){},searchMethod:function(methodName){for(var i=0;i<this.apis.length;i++){var api=this.apis[i];var operations=api.operations;for(var j=0;j<operations.length;j++){var op=operations[j];if(op.nickname==methodName){return op}}}},isValidMessage:function(strMsg,type){var jsonMsg=strMsg;if(jsonMsg.hasOwnProperty("method")){var metadataMethod=this.searchMethod(jsonMsg.method)}else if(type!=undefined){var metadataMethod=this.searchMethod(type)}else{return false}var responseModel=this.getModelTemplate(metadataMethod.type);var validMsg=false;var req="";for(var i=0;i<responseModel.required.length;i++){req=responseModel.required[i];if(!jsonMsg.hasOwnProperty(req)){validMsg=false;console.log("Error processinMessage : "+strMsg+" -> Property : "+req+" is a required field");return validMsg}else{validMsg=true}}return validMsg},extract:function(names,strMsg){if(this.isValidMessage(strMsg)){var dataExtracted={};for(var i=0;i<names.length;i++){name=names[i];dataExtracted[name]=strMsg[name]}return dataExtracted}return undefined}};function wrapper(ws,data){if(ws.hasOwnProperty("ip")){wsUri="ws://"+ws.ip+":"+ws.port+"/";this.websocket=new WebSocket(wsUri)}else{this.websocket=ws}this.smartdevice=new _smartDevice(this.websocket,data);this.smartdevice.loadApis();this.smartdevice.loadModels();this.smartdevice.generateMethodCall();this.smartdevice.generateModelFilling()}wrapper.prototype={methods:{connect:"connect",disconnect:"disconnect",get:"get",set:"set",callAction:"callAction",extract:"extract",eval:"eval",open:"open",step:"step"},post:function(method,params){if(method==undefined&&!params.hasOwnProperty("method"))return;else if(method!=undefined&&!params.hasOwnProperty("method"))params["method"]=method;websocket.send(params)},sync:function(callback){if(callback!=undefined){callback(response)}},connect:function(callback){this.smartdevice=new _smartDevice(fullData);this.smartdevice.loadApis();this.smartdevice.loadModels();this.smartdevice.generateMethodCall()},disconnect:function(callback){},get:function(vars,eachStep,callback){if(eachStep===undefined||eachStep==false)this.smartdevice.getSensorData("getSensorData",vars);else{this.smartdevice.getSensorData("getSensorData",vars,[this.smartdevice.fillConfigurationItem("updateFrequency",2)])}},set:function(vars,values,auth,callback){if(vars.length==1)this.smartdevice.sendActuatorData(auth,"sendActuatorData","modelVars",[vars],[values]);else this.smartdevice.sendActuatorData(auth,"sendActuatorData","modelVars",vars,values)},callAction:function(nickname,params,callback){this.smartdevice.callAction("","callAction","modelMethods",nickname,params)},extract:function(strMsg,callback){var jsonMsg=JSON.parse(strMsg);var vars={};if(jsonMsg.hasOwnProperty("method")){var method=jsonMsg.method;var extracted={};if(method=="getSensorData"){vars=["sensorId","responseData"]}else if(method=="sendActuatorData"){vars=["lastMeasured","accessrole","payload","observerMode"]}else if(method=="getSensorMetadata"){vars=["sensors"]}else if(method=="getActuatorMetadata"){vars=["actuators"]}else if(method=="getActionsMetadata"){vars=["sensors"]}else if(method=="callAction"){vars=["method","callerName","nickName","params"]}else if(method=="actionDataResponse"){vars=["method","nickName"]}else{console.log("The method : "+jsonMsg.method+" is not handled in this wrapper. \n"+"Will be ignored.");return undefined}}extracted=this.smartdevice.extract(vars,jsonMsg);return this.toEjssReadable(method,extracted)},eval:function(code,callback){},open:function(model,callback){},step:function(vars,callback){},toEjssReadable:function(method,dataExtracted){if(method=="getSensorData"){var nameValue={};var valueNames=dataExtracted.responseData.valueNames;var dataValues=dataExtracted.responseData.data;for(var i=0;i<valueNames.length;i++){nameValue[valueNames[i]]=dataValues[i]}return nameValue}else if(method=="sendActuatorData"){return true}else if(method=="getSensorMetadata"){return dataExtracted}else if(method=="getActuatorMetadata"){return dataExtracted}else if(method=="getActionsMetadata"){return dataExtracted}else if(method=="callAction"){return dataExtracted}else if(method=="actionDataResponse"){return dataExtracted}else{console.log("The method : "+method+" is nor handled in this wrapper. \n"+"Will be ignored.");return undefined}}};var EJSS_CORE=EJSS_CORE||{};EJSS_CORE.createView=function(container){var self={};var mTopLevelElement;var mReporter;var mVariablesList={};var mActionsList={};var mUnnamedUpdateList=[];var mUpdateList=[];var mResetableList=[];var mInitializableList=[];var mRenderList=[];var mTouchList=[];var mCollectersList=[];var mInteractionList=[];var mEnableEPubList=[];var mAdjustPositionList=[];var mFontResizeListenerList=[];var mResizeListenerList=[];var mReadingInteractions=false;var mReportNeeded=true;var mInitValueList=[];var mResourcePath;var mLibraryPath;var mRegInteractions=[];var mIsRegInteractions=false;var mWSRegInteractions;var mDescriptionPages=[];var mOnBlurList=[];var mOnFocusList=[];var mDummyContainer;self._getTopLevelElement=function(){return mTopLevelElement};self._1=function(){mTopLevelElement.innerHTML="";mVariablesList={};mActionsList={};mUnnamedUpdateList=[];mUpdateList=[];mInitValueList=[];mResetableList=[];mInitializableList=[];mRenderList=[];mTouchList=[];mCollectersList=[];mEnableEPubList=[];mAdjustPositionList=[];mFontResizeListenerList=[];mResizeListenerList=[];mInteractionList=[];mReadingInteractions=false;mReportNeeded=true};self._2=function(path){mResourcePath=path};function startsWith(fullStr,str){return fullStr.match("^"+str)==str}self._3=function(filename,forIbooks){if(filename==null||filename.length<=0)return filename;if(startsWith(filename,"local:"))return filename;if(startsWith(filename,"data:"))return filename;if(startsWith(filename,"http:")||startsWith(filename,"https:")||startsWith(filename,"ws:"))return filename;if(typeof __base64Images!=="undefined"){var base64=__base64Images[filename];if(base64)return base64}if(mLibraryPath&&!startsWith(filename,mLibraryPath)&&filename.charAt(0)=="/"){filename=mLibraryPath+"images"+filename}else if(mResourcePath&&!startsWith(filename,mResourcePath)&&filename.charAt(0)!="/"){filename=mResourcePath+filename}if(forIbooks&&startsWith(window.location.protocol,"ibooks")){var path=window.location.pathname;path=path.substring(0,path.lastIndexOf("/"));if(startsWith(filename,"./"))filename=filename.substring(2);filename=window.location.protocol+"://"+window.location.host+"/"+path+"/"+filename}return filename};self._4=function(path){mLibraryPath=path};self._showDocument=function(url){window.open(self._3(url))};self._addDescriptionPage=function(name,url){mDescriptionPages[name]=url};self._openDescriptionPage=function(name){var url=mDescriptionPages[name];if(url)window.open(self._3(url));else console.log("Desription page not found: "+name)};self._5=function(variable,initialValue){mVariablesList[variable]={getter:null,setter:null,listeners:[],collectors:[],value:initialValue}};self._5s=function(variables){for(var i=0;i<variables.length;i++)self._5(variables[i])};self._7=function(action){mActionsList[action]={action:null}};self._7s=function(actions){for(var i=0;i<actions.length;i++)self._7(actions[i])};self._9=function(constructor,name,parent,args){var controlElement=EJSS_CORE.promoteToControlElement(constructor(name,args),self,name);if(controlElement.render)mRenderList.push(controlElement);if(controlElement.touch)mTouchList.push(controlElement);if(controlElement.dataCollected)mCollectersList.push(controlElement);if(controlElement.reset)mResetableList.push(controlElement);if(controlElement.initialize)mInitializableList.push(controlElement);if(controlElement.enableEPub)mEnableEPubList.push(controlElement);if(controlElement.adjustPosition)mAdjustPositionList.push(controlElement);if(name)self[name]=controlElement;if(parent)controlElement.setProperty("Parent",parent);return controlElement};self._10=function(variable){var variableDefinition=mVariablesList[variable];if(variableDefinition!==undefined)return variableDefinition.value;return undefined};self._11=function(){self._reset();self._15();self._initialize();self._update();self._render()};self._setRootProperty=function(model,property,value){switch(property){case"RunAlways":model.setRunAlways(value);break;case"OnBlur":self._addOnBlurAction(value);break;case"OnFocus":self._addOnFocusAction(value);break;case"InnerHTML":self._setInnerHTML(value);break;default:console.log("WARNING: View property not registered : "+property);break}};self._12=function(reporter){mReporter=reporter};self._13=function(variable,getter,setter,initialValue){var variableDefinition=mVariablesList[variable];if(!variableDefinition)console.log("WARNING: view._setAccessors() - Variable not found : "+variable);else{variableDefinition.getter=getter;variableDefinition.setter=setter;variableDefinition.value=initialValue;var index=mUpdateList.indexOf(variableDefinition);if(variableDefinition.getter){if(variableDefinition.listeners.length>0&&index<0)mUpdateList.push(variableDefinition)}else{if(index>=0)mUpdateList.splice(index,1)}index=mInitValueList.indexOf(variableDefinition);if(variableDefinition.value){if(variableDefinition.listeners.length>0&&index<0)mInitValueList.push(variableDefinition)}else{if(index>=0)mInitValueList.splice(index,1)}}return variableDefinition};self._setAction=function(action,whatToDo){var actionDefinition=mActionsList[action];if(!actionDefinition)console.log("WARNING: view._setAction() - Action not found : "+action);else actionDefinition.action=whatToDo;return actionDefinition};self._14=function(needed){mReportNeeded=needed};self._reset=function(){for(var i=0,n=mResetableList.length;i<n;i++)mResetableList[i].reset()};self._15=function(){for(var i=0,n=mInitValueList.length;i<n;i++){var variableDefinition=mInitValueList[i];var value=variableDefinition.value;if(value){var listeners=variableDefinition.listeners;for(var j=0,m=listeners.length;j<m;j++)listeners[j](value)}}};self._initialize=function(){for(var i=0,n=mInitializableList.length;i<n;i++)mInitializableList[i].initialize()};self._update=function(){var i,n;for(i=0,n=mUpdateList.length;i<n;i++){var variableDefinition=mUpdateList[i];var listeners=variableDefinition.listeners;var value=variableDefinition.getter();for(var j=0,m=listeners.length;j<m;j++)listeners[j](value)}for(i=0,n=mUnnamedUpdateList.length;i<n;i++){var unnamedDefinition=mUnnamedUpdateList[i];unnamedDefinition.propertySetter(unnamedDefinition.getter())}};self._collectData=function(){var i,n;for(i=0,n=mUpdateList.length;i<n;i++){var variableDefinition=mUpdateList[i];var listeners=variableDefinition.collectors;var value=variableDefinition.getter();for(var j=0,m=listeners.length;j<m;j++)listeners[j](value)}for(i=0,n=mUnnamedUpdateList.length;i<n;i++){var unnamedDefinition=mUnnamedUpdateList[i];if(unnamedDefinition.isCollector)unnamedDefinition.propertySetter(unnamedDefinition.getter())}for(i=0,n=mCollectersList.length;i<n;i++)mCollectersList[i].dataCollected()};self._render=function(){for(var i=0,n=mRenderList.length;i<n;i++)mRenderList[i].render()};self._touch=function(){for(var i=0,n=mTouchList.length;i<n;i++)mTouchList[i].touch()};self._enableEPub=function(){if(typeof _isEPub!=="undefined"&&_isEPub)for(var i=0,n=mEnableEPubList.length;i<n;i++)mEnableEPubList[i].enableEPub()};self._addFontResizeListener=function(listener){mFontResizeListenerList.push(listener)};self._fontResized=function(iBase,iSize,iDelta){for(var i=0,n=mAdjustPositionList.length;i<n;i++)mAdjustPositionList[i].adjustPosition();if(iBase){for(var j=0,m=mFontResizeListenerList.length;j<m;j++)mFontResizeListenerList[j](iBase,iSize,iDelta)}};self._addResizeListener=function(listener){mResizeListenerList.push(listener)};self._resized=function(width,height){for(var i=0,n=mAdjustPositionList.length;i<n;i++)mAdjustPositionList[i].adjustPosition();for(var j=0,m=mResizeListenerList.length;j<m;j++)mResizeListenerList[j](width,height)};self._16=function(runCount,runTime,isPlaying){var n=mInteractionList.length;if(n<=0)return false;mReadingInteractions=true;for(var i=0;i<n;i++){var interaction=mInteractionList[i];if(self.isRegInteractions()){var inter=interaction["interaction"];inter["data"]=interaction.data;inter["runCount"]=runCount;inter["runTime"]=runTime;inter["isPlaying"]=isPlaying;inter["timeStamp"]=Date.now();self.pushRegInteractions(inter)}if(interaction.data&&interaction.data.info)interaction.what(interaction.data.info,interaction.data);else interaction.what(interaction.data)}mInteractionList=[];mReadingInteractions=false;return true};self._17=function(){return mInteractionList.length};self._addOnBlurAction=function(listener){mOnBlurList.push(listener)};self._onBlur=function(){for(var j=0,m=mOnBlurList.length;j<m;j++)mOnBlurList[j]()};self._addOnFocusAction=function(listener){mOnFocusList.push(listener)};self._onFocus=function(){for(var j=0,m=mOnFocusList.length;j<m;j++)mOnFocusList[j]()};self._setInnerHTML=function(htmlCode){if(typeof mDummyContainer==="undefined"){mDummyContainer=document.createElement("div");document.body.appendChild(mDummyContainer)}mDummyContainer.innerHTML=htmlCode};self._18=function(){if(mReporter&&mReportNeeded)mReporter()};self._19=function(variable,propertySetter,isCollector){var variableDefinition=mVariablesList[variable];if(!variableDefinition)console.log("WARNING: view._19() - Variable not found : "+variable);else{if(variableDefinition.listeners.indexOf(propertySetter)<0){variableDefinition.listeners.push(propertySetter);if(isCollector)variableDefinition.collectors.push(propertySetter)}if(variableDefinition.getter){if(mUpdateList.indexOf(variableDefinition)<0)mUpdateList.push(variableDefinition)}if(variableDefinition.value){if(mInitValueList.indexOf(variableDefinition)<0)mInitValueList.push(variableDefinition)}}return variableDefinition};self._20=function(getter,propertySetter,isCollector){var found=false;for(var i=0,n=mUnnamedUpdateList.length;i<n;i++){var unnamedDefinition=mUnnamedUpdateList[i];if(unnamedDefinition.propertySetter===propertySetter){unnamedDefinition.getter=getter;found=true;break}}if(!found){mUnnamedUpdateList.push({getter:getter,propertySetter:propertySetter,isCollector:isCollector})}return found};self._21=function(action){var actionDefinition=mActionsList[action];if(!actionDefinition)console.log("WARNING: view._21() - Action not found : "+action);return actionDefinition};self._22=function(action,data,interaction){if(!mReporter){action(data);return}if(!mReadingInteractions&&mReportNeeded)mInteractionList.push({what:action,data:data,interaction:interaction})};self._format=function(value,format){var index=format.indexOf(".");var digits=0;if(index>=0)digits=Number(format.length-index-1);return parseFloat(value).toFixed(digits)};self.print=function(str){var ta=document.getElementsByTagName("textarea");if(ta.length)ta[0].innerHTML=str;else console.log(str)};self._setVisible=function(visibility){if(visibility)mTopLevelElement.style.display="inherit";else mTopLevelElement.style.display="none"};self._switchVisibility=function(){self._setVisible(mTopLevelElement.style.display=="none")};self.serialize=function(){var encoded={};for(key in self){if(self[key].serialize){encoded[key]=self[key].serialize()}}return encoded};self.unserialize=function(decoded){for(key in decoded){if(self[key]&&self[key].unserialize){self[key].unserialize(decoded[key])}else{console.log("Impossible unserialize: "+key)}}};self.registerInteractions=function(websocket){mRegInteractions=[]
;mWSRegInteractions=websocket;mIsRegInteractions=true};self.unregisterInteractions=function(){mIsRegInteractions=false};self.getRegInteractions=function(empty){if(empty)mRegInteractions=[];return mRegInteractions};self.isRegInteractions=function(){return mIsRegInteractions};self.pushRegInteractions=function(action){if(typeof mWSRegInteractions!=="undefined")mWSRegInteractions.send(JSON.stringify(action));else mRegInteractions.push(action)};if(typeof container=="string"){mTopLevelElement=self[container]=document.getElementById(container)}else mTopLevelElement=container;return self};EJSS_CORE.promoteToControlElement=function(mElement,mView,mName){mName=mName||"unnamed";var mDataObject=null;var mProperties={};var mActions={};mElement.getView=function(){return mView};mElement._0=function(name){mName=name};mElement.getName=function(){return mName};mElement.getResourcePath=function(filename){return mView._3(filename)};mElement.setDataObject=function(data){mDataObject=data};mElement.getDataObject=function(data){return mDataObject};mElement.registerProperty=function(property,setter,getter){mProperties[property]={setter:setter,getter:getter,variable:null,variableSetter:null};return mElement};mElement.registerAction=function(action,helperFunction,processFunction,actionFunction){mActions[action]={action:null,helper:helperFunction,process:processFunction};if(actionFunction)mElement.setAction(action,actionFunction);return mElement};mElement.setProperty=function(property,value){var actionDefinition=mActions[property];if(actionDefinition){return mElement.setAction(property,value)}var propertyDefinition=mProperties[property];if(!propertyDefinition){console.log("WARNING: ControlElement setProperty() - Property not registered : "+property+" for element : "+mElement.getName())}else propertyDefinition.setter(value);return mElement};mElement.setProperties=function(properties){for(var key in properties)mElement.setProperty(key,properties[key]);return mElement};mElement.linkProperty=function(property,variableOrGetter,setter){var propertyDefinition=mProperties[property];if(!propertyDefinition){console.log("WARNING: ControlElement linkProperty() - Element property not registered : "+property+" for element : "+mElement.getName());return mElement}if(typeof variableOrGetter==="string"){var viewVariable=mView._19(variableOrGetter,propertyDefinition.setter,mElement.dataCollected);if(!viewVariable){console.log("WARNING: ControlElement linkProperty() - element : "+mElement.getName()+" - property :"+property+" - View variable not registered : "+variableOrGetter);return mElement}if(setter==="InputOnly"){}else propertyDefinition.variable=viewVariable;propertyDefinition.variableSetter=null}else{mView._20(variableOrGetter,propertyDefinition.setter,mElement.dataCollected);propertyDefinition.variableSetter=setter;propertyDefinition.variable=null}return mElement};mElement.linkProperties=function(properties){for(var key in properties)mElement.linkProperty(key,properties[key]);return mElement};mElement.setAction=function(name,action){var actionDefinition=mActions[name];if(!actionDefinition){console.log("WARNING: ControlElement setAction() - action not registered : "+name+" for element : "+mElement.getName);return mElement}if(typeof action==="string"){var viewAction=mView._21(action);if(!viewAction){console.log("WARNING: ControlElement setAction() - element : "+mElement.getName()+" - View action not registered : "+action);return mElement}actionDefinition.action=viewAction}else{actionDefinition.action={action:action}}return mElement};mElement.setActions=function(actions){for(var key in actions)mElement.setAction(key,actions[key]);return mElement};mElement.invokeAction=function(name){var ia={};if(mView.isRegInteractions())ia={action:name,element:mElement.getName(),timeStamp:Date.now()};var actionDefinition=mActions[name];if(actionDefinition){if(actionDefinition.process){mView._22(actionDefinition.process,null,ia)}if(actionDefinition.action){var data=actionDefinition.helper?actionDefinition.helper():null;mView._22(actionDefinition.action.action,data,ia)}}return mElement};mElement.invokeImmediateAction=function(name){var actionDefinition=mActions[name];if(actionDefinition){if(actionDefinition.process){actionDefinition.process(null)}if(actionDefinition.action){var data=actionDefinition.helper?actionDefinition.helper():null;actionDefinition.action.action(data)}}return mElement};mElement.propertiesChanged=function(){for(var i=0,n=arguments.length;i<n;i++)mElement.propertyChanged(arguments[i]);return mElement};mElement.propertyChanged=function(property,data){var ia={};if(mView.isRegInteractions())ia={property:property,element:mElement.getName(),timeStamp:Date.now()};var propertyDefinition=mProperties[property];if(propertyDefinition){var setter=propertyDefinition.variableSetter;if(!setter){if(propertyDefinition.variable)setter=propertyDefinition.variable.setter}if(!setter){if(propertyDefinition.setter)setter=propertyDefinition.setter}if(setter){var value=typeof data!=="undefined"?data:propertyDefinition.getter();mView._22(setter,value,ia)}}return mElement};mElement.immediatePropertyChanged=function(property,data){var ia={};var propertyDefinition=mProperties[property];if(propertyDefinition){var setter=propertyDefinition.variableSetter;if(!setter){if(propertyDefinition.variable)setter=propertyDefinition.variable.setter}if(!setter){if(propertyDefinition.setter)setter=propertyDefinition.setter}if(setter){var value=typeof data!=="undefined"?data:propertyDefinition.getter();setter(value)}}return mElement};mElement.reportInteractions=function(actions,properties){var i,n;if(actions)for(i=0,n=actions.length;i<n;i++)mElement.invokeAction(actions[i]);if(properties)for(i=0,n=properties.length;i<n;i++)mElement.propertiesChanged(properties[i]);if(mView._17()>0)mView._18();return mElement};mElement.getProperty=function(property,value){var propertyDefinition=mProperties[property];if(propertyDefinition&&propertyDefinition.getter)return propertyDefinition.getter();return undefined};mElement.getProperties=function(){return mProperties};mElement.registerProperty("name",mElement._0,mElement.getName);if(mElement.registerProperties)mElement.registerProperties(mElement);return mElement};
/* _inputParameters: an object with different values for the model parameters */
function photosynthesis(_topFrame,_libraryPath,_codebasePath, _inputParameters) {
var _model = EJSS_CORE.createAnimation();
var _view;
var _isPlaying = false;
var _isPaused = true;
var _isMobile = (navigator===undefined) ? false : navigator.userAgent.match(/iPhone|iPad|iPod|Android|BlackBerry|Opera Mini|IEMobile/i);
var _stringProperties = {};
var _tools = {
showInputDialog : EJSS_INTERFACE.BoxPanel.showInputDialog,
showOkDialog : EJSS_INTERFACE.BoxPanel.showOkDialog,
showOkCancelDialog : EJSS_INTERFACE.BoxPanel.showOkCancelDialog
};
var accelerometer = EJSS_HARDWARE.accelerometer();
function _play() { _isPaused = false; _isPlaying = true; _model.play(); }
function _pause() { _isPaused = true; _isPlaying = false; _model.pause(); }
function _step() { _pause(); _model.step(); }
function _reset() { _model.reset(); _isPaused = _model.isPaused(); _isPlaying = _model.isPlaying(); }
_model._play = _play;
_model._pause = _pause;
_model._step = _step;
_model._reset = _reset;
function _update() { _model.update(); }
function _initialize() { _model.initialize(); }
function _setFPS(_fps) { _model.setFPS(_fps); }
function _setDelay(_delay) { _model.setDelay(_delay); }
function _setStepsPerDisplay(_spd) { _model.setStepsPerDisplay(_spd); }
function _setUpdateView(_updateView) { _model.setUpdateView(_updateView); }
function _setAutoplay(_auto) { _model.setAutoplay(_auto); }
function _println(_message) { console.log(_message); }
function _breakAfterThisPage() { _model.setShouldBreak(true); }
function _resetSolvers() { if (_model.resetSolvers) _model.resetSolvers(); }
function _saveText(name,type,content) { if (_model.saveText) _model.saveText(name,type,content); }
function _saveState(name) { if (_model.saveState) _model.saveState(name); }
function _saveImage(name,panelname) { if (_model.saveImage) _model.saveImage(name,panelname); }
function _readState(url,type) { if (_model.readState) _model.readState(url,type); }
function _readText(url,type,varname) { if (_model.readText) _model.readText(url,type,varname); }
function _getStringProperty(propertyName) {
var _value = _stringProperties[propertyName];
if (_value===undefined) return propertyName;
else return _value;
}
var __pagesEnabled = [];
function _setPageEnabled(pageName,enabled) { __pagesEnabled[pageName] = enabled; }
var xmin; // EjsS Model.Variables.Var Table.xmin
var xmax; // EjsS Model.Variables.Var Table.xmax
var ymin; // EjsS Model.Variables.Var Table.ymin
var ymax; // EjsS Model.Variables.Var Table.ymax
var rangex; // EjsS Model.Variables.Var Table.rangex
var rangey; // EjsS Model.Variables.Var Table.rangey
var sizex; // EjsS Model.Variables.Var Table.sizex
var sizey; // EjsS Model.Variables.Var Table.sizey
var selected; // EjsS Model.Variables.Var Table.selected
var text; // EjsS Model.Variables.Var Table.text
var pi; // EjsS Model.Variables.Var Table.pi
var y1; // EjsS Model.Variables.Var Table.y1
var ysize; // EjsS Model.Variables.Var Table.ysize
var xlamp; // EjsS Model.Variables.Var Table.xlamp
var ylamp; // EjsS Model.Variables.Var Table.ylamp
var n; // EjsS Model.Variables.Var Table.n
var r; // EjsS Model.Variables.Var Table.r
var dr; // EjsS Model.Variables.Var Table.dr
var xbubble; // EjsS Model.Variables.Var Table.xbubble
var ybubble; // EjsS Model.Variables.Var Table.ybubble
var dy; // EjsS Model.Variables.Var Table.dy
var ybubbleshow; // EjsS Model.Variables.Var Table.ybubbleshow
var count; // EjsS Model.Variables.Var Table.count
var sumcount; // EjsS Model.Variables.Var Table.sumcount
var intensity; // EjsS Model.Variables.Var Table.intensity
var intensitydrag; // EjsS Model.Variables.Var Table.intensitydrag
var carbondioxide; // EjsS Model.Variables.Var Table.carbondioxide
var carbondioxidedrag; // EjsS Model.Variables.Var Table.carbondioxidedrag
var expt; // EjsS Model.Variables.Var Table.expt
var spd; // EjsS Model.Variables.Var Table.spd
var datanMax; // EjsS Model.Variables.datatable.datanMax
var datan; // EjsS Model.Variables.datatable.datan
var intensitydata; // EjsS Model.Variables.datatable.intensitydata
var sumcountdata; // EjsS Model.Variables.datatable.sumcountdata
var carbondioxidedata; // EjsS Model.Variables.datatable.carbondioxidedata
var Width; // EjsS Model.Variables.layout.Width
var Height; // EjsS Model.Variables.layout.Height
var Width1; // EjsS Model.Variables.layout.Width1
var Width2; // EjsS Model.Variables.layout.Width2
var Width3; // EjsS Model.Variables.layout.Width3
var world; // EjsS Model.Variables.layout.world
var graph; // EjsS Model.Variables.layout.graph
var graph2; // EjsS Model.Variables.layout.graph2
var disabledworld; // EjsS Model.Variables.layout.disabledworld
var disabled; // EjsS Model.Variables.layout.disabled
var m; // EjsS Model.Variables.simplespring.m
var x; // EjsS Model.Variables.simplespring.x
var xs; // EjsS Model.Variables.simplespring.xs
var y; // EjsS Model.Variables.simplespring.y
var vx; // EjsS Model.Variables.simplespring.vx
var vxs; // EjsS Model.Variables.simplespring.vxs
var vxstored; // EjsS Model.Variables.simplespring.vxstored
var t; // EjsS Model.Variables.simplespring.t
var T; // EjsS Model.Variables.simplespring.T
var dt; // EjsS Model.Variables.simplespring.dt
var selectedmodel; // EjsS Model.Variables.functionY.selectedmodel
var functionY; // EjsS Model.Variables.functionY.functionY
var xmodel; // EjsS Model.Variables.functionY.xmodel
var showmodel; // EjsS Model.Variables.functionY.showmodel
var _privateOdesList;
var _ODEi_evolution1;
var userEvents1=[];
_model.getOdes = function() { return[_ODEi_evolution1]};
_model.removeEvents = function(){
userEvents1=[];
};
_model.addFixedRel = function(code){_model.addToFixedRelations(function() { eval(code);});};
function _serialize() { return _model.serialize(); }
_model._userSerialize = function() {
return {
xmin : xmin,
xmax : xmax,
ymin : ymin,
ymax : ymax,
rangex : rangex,
rangey : rangey,
sizex : sizex,
sizey : sizey,
selected : selected,
text : text,
pi : pi,
y1 : y1,
ysize : ysize,
xlamp : xlamp,
ylamp : ylamp,
n : n,
r : r,
dr : dr,
xbubble : xbubble,
ybubble : ybubble,
dy : dy,
ybubbleshow : ybubbleshow,
count : count,
sumcount : sumcount,
intensity : intensity,
intensitydrag : intensitydrag,
carbondioxide : carbondioxide,
carbondioxidedrag : carbondioxidedrag,
expt : expt,
spd : spd,
datanMax : datanMax,
datan : datan,
intensitydata : intensitydata,
sumcountdata : sumcountdata,
carbondioxidedata : carbondioxidedata,
Width : Width,
Height : Height,
Width1 : Width1,
Width2 : Width2,
Width3 : Width3,
world : world,
graph : graph,
graph2 : graph2,
disabledworld : disabledworld,
disabled : disabled,
m : m,
x : x,
xs : xs,
y : y,
vx : vx,
vxs : vxs,
vxstored : vxstored,
t : t,
T : T,
dt : dt,
selectedmodel : selectedmodel,
functionY : functionY,
xmodel : xmodel,
showmodel : showmodel
};
};
function _serializePublic() { return _model.serializePublic(); }
_model._userSerializePublic = function() {
return {
xmin : xmin,
xmax : xmax,
ymin : ymin,
ymax : ymax,
rangex : rangex,
rangey : rangey,
sizex : sizex,
sizey : sizey,
selected : selected,
text : text,
pi : pi,
y1 : y1,
ysize : ysize,
xlamp : xlamp,
ylamp : ylamp,
n : n,
r : r,
dr : dr,
xbubble : xbubble,
ybubble : ybubble,
dy : dy,
ybubbleshow : ybubbleshow,
count : count,
sumcount : sumcount,
intensity : intensity,
intensitydrag : intensitydrag,
carbondioxide : carbondioxide,
carbondioxidedrag : carbondioxidedrag,
expt : expt,
spd : spd,
datanMax : datanMax,
datan : datan,
intensitydata : intensitydata,
sumcountdata : sumcountdata,
carbondioxidedata : carbondioxidedata,
Width : Width,
Height : Height,
Width1 : Width1,
Width2 : Width2,
Width3 : Width3,
world : world,
graph : graph,
graph2 : graph2,
disabledworld : disabledworld,
disabled : disabled,
m : m,
x : x,
xs : xs,
y : y,
vx : vx,
vxs : vxs,
vxstored : vxstored,
t : t,
T : T,
dt : dt,
selectedmodel : selectedmodel,
functionY : functionY,
xmodel : xmodel,
showmodel : showmodel
};
};
_model._readParameters = function(json) {
if(typeof json.xmin != "undefined") xmin = json.xmin;
if(typeof json.xmax != "undefined") xmax = json.xmax;
if(typeof json.ymin != "undefined") ymin = json.ymin;
if(typeof json.ymax != "undefined") ymax = json.ymax;
if(typeof json.rangex != "undefined") rangex = json.rangex;
if(typeof json.rangey != "undefined") rangey = json.rangey;
if(typeof json.sizex != "undefined") sizex = json.sizex;
if(typeof json.sizey != "undefined") sizey = json.sizey;
if(typeof json.selected != "undefined") selected = json.selected;
if(typeof json.text != "undefined") text = json.text;
if(typeof json.pi != "undefined") pi = json.pi;
if(typeof json.y1 != "undefined") y1 = json.y1;
if(typeof json.ysize != "undefined") ysize = json.ysize;
if(typeof json.xlamp != "undefined") xlamp = json.xlamp;
if(typeof json.ylamp != "undefined") ylamp = json.ylamp;
if(typeof json.n != "undefined") n = json.n;
if(typeof json.r != "undefined") r = json.r;
if(typeof json.dr != "undefined") dr = json.dr;
if(typeof json.xbubble != "undefined") xbubble = json.xbubble;
if(typeof json.ybubble != "undefined") ybubble = json.ybubble;
if(typeof json.dy != "undefined") dy = json.dy;
if(typeof json.ybubbleshow != "undefined") ybubbleshow = json.ybubbleshow;
if(typeof json.count != "undefined") count = json.count;
if(typeof json.sumcount != "undefined") sumcount = json.sumcount;
if(typeof json.intensity != "undefined") intensity = json.intensity;
if(typeof json.intensitydrag != "undefined") intensitydrag = json.intensitydrag;
if(typeof json.carbondioxide != "undefined") carbondioxide = json.carbondioxide;
if(typeof json.carbondioxidedrag != "undefined") carbondioxidedrag = json.carbondioxidedrag;
if(typeof json.expt != "undefined") expt = json.expt;
if(typeof json.spd != "undefined") spd = json.spd;
if(typeof json.datanMax != "undefined") datanMax = json.datanMax;
if(typeof json.datan != "undefined") datan = json.datan;
if(typeof json.intensitydata != "undefined") intensitydata = json.intensitydata;
if(typeof json.sumcountdata != "undefined") sumcountdata = json.sumcountdata;
if(typeof json.carbondioxidedata != "undefined") carbondioxidedata = json.carbondioxidedata;
if(typeof json.Width != "undefined") Width = json.Width;
if(typeof json.Height != "undefined") Height = json.Height;
if(typeof json.Width1 != "undefined") Width1 = json.Width1;
if(typeof json.Width2 != "undefined") Width2 = json.Width2;
if(typeof json.Width3 != "undefined") Width3 = json.Width3;
if(typeof json.world != "undefined") world = json.world;
if(typeof json.graph != "undefined") graph = json.graph;
if(typeof json.graph2 != "undefined") graph2 = json.graph2;
if(typeof json.disabledworld != "undefined") disabledworld = json.disabledworld;
if(typeof json.disabled != "undefined") disabled = json.disabled;
if(typeof json.m != "undefined") m = json.m;
if(typeof json.x != "undefined") x = json.x;
if(typeof json.xs != "undefined") xs = json.xs;
if(typeof json.y != "undefined") y = json.y;
if(typeof json.vx != "undefined") vx = json.vx;
if(typeof json.vxs != "undefined") vxs = json.vxs;
if(typeof json.vxstored != "undefined") vxstored = json.vxstored;
if(typeof json.t != "undefined") t = json.t;
if(typeof json.T != "undefined") T = json.T;
if(typeof json.dt != "undefined") dt = json.dt;
if(typeof json.selectedmodel != "undefined") selectedmodel = json.selectedmodel;
if(typeof json.functionY != "undefined") functionY = json.functionY;
if(typeof json.xmodel != "undefined") xmodel = json.xmodel;
if(typeof json.showmodel != "undefined") showmodel = json.showmodel;
};
_model._readParametersPublic = function(json) {
if(typeof json.xmin != "undefined") xmin = json.xmin;
if(typeof json.xmax != "undefined") xmax = json.xmax;
if(typeof json.ymin != "undefined") ymin = json.ymin;
if(typeof json.ymax != "undefined") ymax = json.ymax;
if(typeof json.rangex != "undefined") rangex = json.rangex;
if(typeof json.rangey != "undefined") rangey = json.rangey;
if(typeof json.sizex != "undefined") sizex = json.sizex;
if(typeof json.sizey != "undefined") sizey = json.sizey;
if(typeof json.selected != "undefined") selected = json.selected;
if(typeof json.text != "undefined") text = json.text;
if(typeof json.pi != "undefined") pi = json.pi;
if(typeof json.y1 != "undefined") y1 = json.y1;
if(typeof json.ysize != "undefined") ysize = json.ysize;
if(typeof json.xlamp != "undefined") xlamp = json.xlamp;
if(typeof json.ylamp != "undefined") ylamp = json.ylamp;
if(typeof json.n != "undefined") n = json.n;
if(typeof json.r != "undefined") r = json.r;
if(typeof json.dr != "undefined") dr = json.dr;
if(typeof json.xbubble != "undefined") xbubble = json.xbubble;
if(typeof json.ybubble != "undefined") ybubble = json.ybubble;
if(typeof json.dy != "undefined") dy = json.dy;
if(typeof json.ybubbleshow != "undefined") ybubbleshow = json.ybubbleshow;
if(typeof json.count != "undefined") count = json.count;
if(typeof json.sumcount != "undefined") sumcount = json.sumcount;
if(typeof json.intensity != "undefined") intensity = json.intensity;
if(typeof json.intensitydrag != "undefined") intensitydrag = json.intensitydrag;
if(typeof json.carbondioxide != "undefined") carbondioxide = json.carbondioxide;
if(typeof json.carbondioxidedrag != "undefined") carbondioxidedrag = json.carbondioxidedrag;
if(typeof json.expt != "undefined") expt = json.expt;
if(typeof json.spd != "undefined") spd = json.spd;
if(typeof json.datanMax != "undefined") datanMax = json.datanMax;
if(typeof json.datan != "undefined") datan = json.datan;
if(typeof json.intensitydata != "undefined") intensitydata = json.intensitydata;
if(typeof json.sumcountdata != "undefined") sumcountdata = json.sumcountdata;
if(typeof json.carbondioxidedata != "undefined") carbondioxidedata = json.carbondioxidedata;
if(typeof json.Width != "undefined") Width = json.Width;
if(typeof json.Height != "undefined") Height = json.Height;
if(typeof json.Width1 != "undefined") Width1 = json.Width1;
if(typeof json.Width2 != "undefined") Width2 = json.Width2;
if(typeof json.Width3 != "undefined") Width3 = json.Width3;
if(typeof json.world != "undefined") world = json.world;
if(typeof json.graph != "undefined") graph = json.graph;
if(typeof json.graph2 != "undefined") graph2 = json.graph2;
if(typeof json.disabledworld != "undefined") disabledworld = json.disabledworld;
if(typeof json.disabled != "undefined") disabled = json.disabled;
if(typeof json.m != "undefined") m = json.m;
if(typeof json.x != "undefined") x = json.x;
if(typeof json.xs != "undefined") xs = json.xs;
if(typeof json.y != "undefined") y = json.y;
if(typeof json.vx != "undefined") vx = json.vx;
if(typeof json.vxs != "undefined") vxs = json.vxs;
if(typeof json.vxstored != "undefined") vxstored = json.vxstored;
if(typeof json.t != "undefined") t = json.t;
if(typeof json.T != "undefined") T = json.T;
if(typeof json.dt != "undefined") dt = json.dt;
if(typeof json.selectedmodel != "undefined") selectedmodel = json.selectedmodel;
if(typeof json.functionY != "undefined") functionY = json.functionY;
if(typeof json.xmodel != "undefined") xmodel = json.xmodel;
if(typeof json.showmodel != "undefined") showmodel = json.showmodel;
};
function _unserializePublic(json) { return _model.unserializePublic(json); }
_model._userUnserializePublic = function(json) {
_model._readParametersPublic(json);
_resetSolvers();
_model.update();
};
function _unserialize(json) { return _model.unserialize(json); }
_model._userUnserialize = function(json) {
_model._readParameters(json);
_resetSolvers();
_model.update();
};
_model.addToReset(function() {
__pagesEnabled["Init Page"] = true;
__pagesEnabled["svg"] = true;
__pagesEnabled["axes"] = true;
__pagesEnabled["Evol Page"] = true;
__pagesEnabled["Event"] = false;
__pagesEnabled["Event 3"] = false;
__pagesEnabled["Event 2"] = false;
__pagesEnabled["FixRel Page 3"] = true;
__pagesEnabled["intensitybubble"] = true;
__pagesEnabled["co2bubble"] = true;
__pagesEnabled["sumcount"] = true;
__pagesEnabled["stop"] = true;
});
_model.addToReset(function() {
xmin = -5; // EjsS Model.Variables.Var Table.xmin
xmax = 5; // EjsS Model.Variables.Var Table.xmax
ymin = -5; // EjsS Model.Variables.Var Table.ymin
ymax = 5; // EjsS Model.Variables.Var Table.ymax
rangex = xmax-xmin; // EjsS Model.Variables.Var Table.rangex
rangey = ymax-ymin; // EjsS Model.Variables.Var Table.rangey
sizex = rangex/20; // EjsS Model.Variables.Var Table.sizex
sizey = rangey/20; // EjsS Model.Variables.Var Table.sizey
selected = new Array(1); // EjsS Model.Variables.Var Table.selected
(function () {
var _i0;
for (_i0=0; _i0<1; _i0+=1) { // EjsS Model.Variables.Var Table.selected
selected[_i0] = "shm_with_xo=0,vo=2"; // EjsS Model.Variables.Var Table.selected
}
}());
text = "select dropdown menu and click play"; // EjsS Model.Variables.Var Table.text
pi = Math.PI; // EjsS Model.Variables.Var Table.pi
y1 = sizey*5/2; // EjsS Model.Variables.Var Table.y1
ysize = 0.2; // EjsS Model.Variables.Var Table.ysize
xlamp = 5.5; // EjsS Model.Variables.Var Table.xlamp
ylamp = 0; // EjsS Model.Variables.Var Table.ylamp
n = 100; // EjsS Model.Variables.Var Table.n
r = new Array(n); // EjsS Model.Variables.Var Table.r
(function () {
var _i0;
for (_i0=0; _i0<n; _i0+=1) { // EjsS Model.Variables.Var Table.r
r[_i0] = 0; // EjsS Model.Variables.Var Table.r
}
}());
dr = new Array(n); // EjsS Model.Variables.Var Table.dr
(function () {
var _i0;
for (_i0=0; _i0<n; _i0+=1) { // EjsS Model.Variables.Var Table.dr
dr[_i0] = 0; // EjsS Model.Variables.Var Table.dr
}
}());
xbubble = new Array(n); // EjsS Model.Variables.Var Table.xbubble
(function () {
var _i0;
for (_i0=0; _i0<n; _i0+=1) { // EjsS Model.Variables.Var Table.xbubble
xbubble[_i0] = 0; // EjsS Model.Variables.Var Table.xbubble
}
}());
ybubble = new Array(n); // EjsS Model.Variables.Var Table.ybubble
(function () {
var _i0;
for (_i0=0; _i0<n; _i0+=1) { // EjsS Model.Variables.Var Table.ybubble
ybubble[_i0] = 0; // EjsS Model.Variables.Var Table.ybubble
}
}());
dy = new Array(n); // EjsS Model.Variables.Var Table.dy
(function () {
var _i0;
for (_i0=0; _i0<n; _i0+=1) { // EjsS Model.Variables.Var Table.dy
dy[_i0] = 0; // EjsS Model.Variables.Var Table.dy
}
}());
ybubbleshow = new Array(n); // EjsS Model.Variables.Var Table.ybubbleshow
(function () {
var _i0;
for (_i0=0; _i0<n; _i0+=1) { // EjsS Model.Variables.Var Table.ybubbleshow
ybubbleshow[_i0] = true; // EjsS Model.Variables.Var Table.ybubbleshow
}
}());
count = new Array(n); // EjsS Model.Variables.Var Table.count
(function () {
var _i0;
for (_i0=0; _i0<n; _i0+=1) { // EjsS Model.Variables.Var Table.count
count[_i0] = 0; // EjsS Model.Variables.Var Table.count
}
}());
sumcount = 0; // EjsS Model.Variables.Var Table.sumcount
intensity = 1; // EjsS Model.Variables.Var Table.intensity
intensitydrag = intensity-3; // EjsS Model.Variables.Var Table.intensitydrag
carbondioxide = 0.05; // EjsS Model.Variables.Var Table.carbondioxide
carbondioxidedrag = -2; // EjsS Model.Variables.Var Table.carbondioxidedrag
expt = 1; // EjsS Model.Variables.Var Table.expt
spd = 1; // EjsS Model.Variables.Var Table.spd
});
_model.addToReset(function() {
datanMax = 7; // EjsS Model.Variables.datatable.datanMax
datan = 1; // EjsS Model.Variables.datatable.datan
intensitydata = new Array(datanMax); // EjsS Model.Variables.datatable.intensitydata
(function () {
var _i0;
for (_i0=0; _i0<datanMax; _i0+=1) { // EjsS Model.Variables.datatable.intensitydata
intensitydata[_i0] = 0; // EjsS Model.Variables.datatable.intensitydata
}
}());
sumcountdata = new Array(datanMax); // EjsS Model.Variables.datatable.sumcountdata
(function () {
var _i0;
for (_i0=0; _i0<datanMax; _i0+=1) { // EjsS Model.Variables.datatable.sumcountdata
sumcountdata[_i0] = 0; // EjsS Model.Variables.datatable.sumcountdata
}
}());
carbondioxidedata = new Array(datanMax); // EjsS Model.Variables.datatable.carbondioxidedata
(function () {
var _i0;
for (_i0=0; _i0<datanMax; _i0+=1) { // EjsS Model.Variables.datatable.carbondioxidedata
carbondioxidedata[_i0] = 0; // EjsS Model.Variables.datatable.carbondioxidedata
}
}());
});
_model.addToReset(function() {
Width = (_isEPub)?"400":"100%"; // EjsS Model.Variables.layout.Width
Height = (_isEPub)?"500":"100%"; // EjsS Model.Variables.layout.Height
Width1 = "50%"; // EjsS Model.Variables.layout.Width1
Width2 = "50%"; // EjsS Model.Variables.layout.Width2
Width3 = "0%"; // EjsS Model.Variables.layout.Width3
world = true; // EjsS Model.Variables.layout.world
graph = true; // EjsS Model.Variables.layout.graph
graph2 = true; // EjsS Model.Variables.layout.graph2
disabledworld = false; // EjsS Model.Variables.layout.disabledworld
disabled = false; // EjsS Model.Variables.layout.disabled
});
_model.addToReset(function() {
m = 1; // EjsS Model.Variables.simplespring.m
x = -1; // EjsS Model.Variables.simplespring.x
xs = x; // EjsS Model.Variables.simplespring.xs
y = 0; // EjsS Model.Variables.simplespring.y
vx = 0; // EjsS Model.Variables.simplespring.vx
vxs = vx; // EjsS Model.Variables.simplespring.vxs
vxstored = 0; // EjsS Model.Variables.simplespring.vxstored
t = 0; // EjsS Model.Variables.simplespring.t
T = 1; // EjsS Model.Variables.simplespring.T
dt = 0.1; // EjsS Model.Variables.simplespring.dt
});
_model.addToReset(function() {
selectedmodel = new Array(1); // EjsS Model.Variables.functionY.selectedmodel
(function () {
var _i0;
for (_i0=0; _i0<1; _i0+=1) { // EjsS Model.Variables.functionY.selectedmodel
selectedmodel[_i0] = "2*sin(t)"; // EjsS Model.Variables.functionY.selectedmodel
}
}());
functionY = selectedmodel+""; // EjsS Model.Variables.functionY.functionY
showmodel = false; // EjsS Model.Variables.functionY.showmodel
});
if (_inputParameters) {
_inputParameters = _model.parseInputParameters(_inputParameters);
if (_inputParameters) _model.addToReset(function() { _model._readParameters(_inputParameters); });
}
_model.addToReset(function() {
_privateOdesList=[];
_ODEi_evolution1 = _ODE_evolution1();
_privateOdesList.push(_ODEi_evolution1);
});
_model.addToReset(function() {
_model.setAutoplay(false);
_model.setPauseOnPageExit(true);
_model.setFPS(20);
_model.setStepsPerDisplay(spd);
});
_model.addToInitialization(function() {
if (!__pagesEnabled["Init Page"]) return;
for (var i=0; i<n ; i++) { // > Initialization.Init Page:1
xbubble[i]=(Math.random()-0.5); // > Initialization.Init Page:2
// > Initialization.Init Page:3
ybubble[i]=(Math.random()*(-3)); // > Initialization.Init Page:4
r[i]=0; //reset radius back to zero size // > Initialization.Init Page:5
dr[i] =0; // reset radius growth // > Initialization.Init Page:6
count[i]=0; //reset counting of bubbles // > Initialization.Init Page:7
ybubbleshow[i]=true; //show all bubbles // > Initialization.Init Page:8
} // > Initialization.Init Page:9
sumcount = 0; // > Initialization.Init Page:10
if (expt==1){ // > Initialization.Init Page:11
dr[0] = 0.05*intensity; //set first bubble rate of radius increase // > Initialization.Init Page:12
} // > Initialization.Init Page:13
else if (expt==2){ // > Initialization.Init Page:14
dr[0] = 0.05*carbondioxide*16; //set first bubble rate of radius increase // > Initialization.Init Page:15
} // > Initialization.Init Page:16
});
_model.addToInitialization(function() {
if (!__pagesEnabled["svg"]) return;
var container = document.createElement('div'); // > Initialization.svg:1
var svggradient = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1"><defs>'+ // > Initialization.svg:2
' <radialGradient id="mygrandient" cx="50%" cy="50%" r="90%" fx="90%" fy="10%">'+ // > Initialization.svg:3
' <stop offset="0%" style="stop-color:rgb(0,255,255); stop-opacity:0.6" />'+ // > Initialization.svg:4
' <stop offset="100%" style="stop-color:rgb(255,255,255);stop-opacity:0.7" />'+ // > Initialization.svg:5
' </radialGradient>'+ // > Initialization.svg:6
'</defs></svg>'; // > Initialization.svg:7
container.innerHTML = svggradient; // > Initialization.svg:8
document.body.appendChild(container); // > Initialization.svg:9
//"url(#mygrandient)" // > Initialization.svg:10
var container = document.createElement('div'); // > Initialization.svg:11
var svggradient = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1"><defs>'+ // > Initialization.svg:12
' <radialGradient id="mygrandient1" cx="50%" cy="50%" r="90%" fx="50%" fy="50%">'+ // > Initialization.svg:13
' <stop offset="0%" style="stop-color:rgb(255,255,255); stop-opacity:1" />'+ // > Initialization.svg:14
' <stop offset="100%" style="stop-color:rgb(200,200,200);stop-opacity:0.1" />'+ // > Initialization.svg:15
' </radialGradient>'+ // > Initialization.svg:16
'</defs></svg>'; // > Initialization.svg:17
container.innerHTML = svggradient; // > Initialization.svg:18
document.body.appendChild(container); // > Initialization.svg:19
//"url(#mygrandient1)" // > Initialization.svg:20
var container = document.createElement('div'); // > Initialization.svg:21
var svggradient = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1"><defs>'+ // > Initialization.svg:22
' <radialGradient id="mygrandient2" cx="50%" cy="50%" r="90%" fx="90%" fy="10%">'+ // > Initialization.svg:23
' <stop offset="0%" style="stop-color:rgb(255,255,255); stop-opacity:0.5" />'+ // > Initialization.svg:24
' <stop offset="100%" style="stop-color:rgb(0,255,255);stop-opacity:0.5" />'+ // > Initialization.svg:25
' </radialGradient>'+ // > Initialization.svg:26
'</defs></svg>'; // > Initialization.svg:27
container.innerHTML = svggradient; // > Initialization.svg:28
document.body.appendChild(container); // > Initialization.svg:29
//"url(#mygrandient2)" // > Initialization.svg:30
var container = document.createElement('div'); // > Initialization.svg:31
var svggradient = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1"><defs>'+ // > Initialization.svg:32
' <radialGradient id="mygrandient3" cx="50%" cy="50%" r="90%" fx="50%" fy="50%">'+ // > Initialization.svg:33
' <stop offset="0%" style="stop-color:rgb(0,0,0); stop-opacity:0.5" />'+ // > Initialization.svg:34
' <stop offset="100%" style="stop-color:rgb(200,200,200);stop-opacity:0.1" />'+ // > Initialization.svg:35
' </radialGradient>'+ // > Initialization.svg:36
'</defs></svg>'; // > Initialization.svg:37
container.innerHTML = svggradient; // > Initialization.svg:38
document.body.appendChild(container); // > Initialization.svg:39
//"url(#mygrandient3)" // > Initialization.svg:40
});
_model.addToInitialization(function() {
if (!__pagesEnabled["axes"]) return;
_view.plottingPanelxvst.getAxisX().setPosition([0,0.047]); // > Initialization.axes:1
_view.plottingPanelxvst.getTitleX().setPosition([0.95,0.1]); // > Initialization.axes:2
_view.plottingPanelxvst.getAxisY().setPosition([0.045,0]); // > Initialization.axes:3
_view.plottingPanelxvst.getTitleY().setPosition([0.1,0.9]); // > Initialization.axes:4
_view.plottingPanelxvst2.getAxisX().setPosition([0,0.047]); // > Initialization.axes:5
_view.plottingPanelxvst2.getTitleX().setPosition([0.95,0.1]); // > Initialization.axes:6
_view.plottingPanelxvst2.getAxisY().setPosition([0.045,0]); // > Initialization.axes:7
_view.plottingPanelxvst2.getTitleY().setPosition([0.1,0.9]); // > Initialization.axes:8
});
_model.addToInitialization(function() {
_initializeSolvers();
});
_model.addToEvolution(function() {
if (!__pagesEnabled["Evol Page"]) return;
_ODEi_evolution1.step();
});
_model.addToFixedRelations(function() { _isPaused = _model.isPaused(); _isPlaying = _model.isPlaying(); });
_model.addToFixedRelations(function() {
if (!__pagesEnabled["FixRel Page 3"]) return;
xmodel=_view.fField.evaluate({ t : t-10*dt, x : xmodel }); // > FixedRelations.FixRel Page 3:1
});
_model.addToFixedRelations(function() {
if (!__pagesEnabled["intensitybubble"]) return;
if (expt==1){ // > FixedRelations.intensitybubble:1
for (var i=0; i<n /* Iterations */ ; i++) { // > FixedRelations.intensitybubble:2
// > FixedRelations.intensitybubble:3
if (r[i]-0.2>=0){ // > FixedRelations.intensitybubble:4
//stop growing this bubble // > FixedRelations.intensitybubble:5
dr[i]=0; // > FixedRelations.intensitybubble:6
// start moving up // > FixedRelations.intensitybubble:7
dy[i]=3; // > FixedRelations.intensitybubble:8
count[i] = 1; // > FixedRelations.intensitybubble:9
// delay depend on intensity // > FixedRelations.intensitybubble:10
//start next bubble growing // > FixedRelations.intensitybubble:11
if (intensity==1){ // > FixedRelations.intensitybubble:12
dr[i+1]=0.05*intensity; // intensity=1, sumcount=15 calibrated // > FixedRelations.intensitybubble:13
} // > FixedRelations.intensitybubble:14
else if (intensity==2){ // > FixedRelations.intensitybubble:15
dr[i+1]=0.05*intensity; // intensity=2, sumcount=30 calibrated // > FixedRelations.intensitybubble:16
} // > FixedRelations.intensitybubble:17
else if (intensity==3){ // > FixedRelations.intensitybubble:18
dr[i+1]=0.045*intensity; // intensity=1, sumcount=15 calibrated // > FixedRelations.intensitybubble:19
} // > FixedRelations.intensitybubble:20
else if (intensity==4){ // > FixedRelations.intensitybubble:21
dr[i+1]=0.04*intensity; // intensity=1, sumcount=50 calibrated // > FixedRelations.intensitybubble:22
} // > FixedRelations.intensitybubble:23
else if (intensity==5){ // > FixedRelations.intensitybubble:24
dr[i+1]=0.034*intensity; // intensity=1, sumcount=50 calibrated // > FixedRelations.intensitybubble:25
} // > FixedRelations.intensitybubble:26
else if (intensity==6){ // > FixedRelations.intensitybubble:27
dr[i+1]=0.029*intensity; // intensity=1, sumcount=50 calibrated // > FixedRelations.intensitybubble:28
} // > FixedRelations.intensitybubble:29
} // > FixedRelations.intensitybubble:30
// > FixedRelations.intensitybubble:31
if (ybubble[i] - 2.5>0){ // > FixedRelations.intensitybubble:32
// stop // > FixedRelations.intensitybubble:33
dy[i] = 0; // > FixedRelations.intensitybubble:34
// explode // > FixedRelations.intensitybubble:35
ybubbleshow[i]=false; // > FixedRelations.intensitybubble:36
} // > FixedRelations.intensitybubble:37
if (xbubble[i]>0.35&&ybubble[i]>0.9){ //rightside // > FixedRelations.intensitybubble:38
xbubble[i]=0.3; // > FixedRelations.intensitybubble:39
} // > FixedRelations.intensitybubble:40
if (xbubble[i]<-0.35&&ybubble[i]>0.9){ //rightside // > FixedRelations.intensitybubble:41
xbubble[i]=-0.3; // > FixedRelations.intensitybubble:42
} // > FixedRelations.intensitybubble:43
// > FixedRelations.intensitybubble:44