forked from Khan/khan-exercises
-
Notifications
You must be signed in to change notification settings - Fork 0
/
khan-exercise.js
3170 lines (2562 loc) · 96.9 KB
/
khan-exercise.js
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
/* khan-exercise.js
The main entry point here is actually the loadScripts method which is defined
as Khan.loadScripts and then evaluated around line 500.
When this loadScripts is called, it loads in many of the pre-reqs and then
calls, one way or another, prepareUserExercise concurrently with loadModules.
prepareUserExercise calls updateData and advances the problem counter
via setProblemNum. updateData refreshes the page ui based on this current
problem (among other things). setProblemNum updates some instance vars
that get looked at by other functions.
loadModules takes care of loading an individual exercise's prereqs (i.e.
word problems, etc). It _also_ loads in the khan academy site skin and
exercise template via injectSite which runs prepareSite first then
makeProblemBag and makeProblem when it finishes loading dependencies.
pepareSite and makeProblem are both fairly heavyweight functions.
If you are trying to register some behavior when the page loads, you
probably want it to go in prepareSite. (which also registers server-initiated
behavior via api.js) as well. By the time prepareSite is called, jquery and
any core plugins are already available.
If you are trying to do something each time a problem loads, you probably
want to look at makeProblem.
For obvious reasons window.userExercise is removed but it remains available
to you from within the Khan object
At the end of evaluation, the inner Khan object is returned/exposed as well
as the inner Util object.
*/
var Khan = (function() {
function warn( message, showClose ) {
jQuery(function() {
var warningBar = jQuery( "#warning-bar" );
jQuery( "#warning-bar-content" ).html( message );
if ( showClose ) {
warningBar.addClass( "warning" )
.children( "#warning-bar-close" ).show();
} else {
warningBar.addClass( "error" )
.children( "#warning-bar-close" ).hide();
}
warningBar.fadeIn( "fast" );
});
}
// Adapted from a comment on http://mathiasbynens.be/notes/localstorage-pattern
var sessionStorageEnabled = function() {
var enabled, uid = +new Date;
try {
sessionStorage[ uid ] = uid;
enabled = ( sessionStorage[ uid ] == uid );
sessionStorage.removeItem( uid );
return enabled;
}
catch( e ) {
return false;
}
}();
if ( !sessionStorageEnabled ) {
if ( typeof jQuery !== "undefined" ) {
warn( "You must enable DOM storage in your browser; see <a href='https://sites.google.com/a/khanacademy.org/forge/for-developers/how-to-enable-dom-storage'>here</a> for instructions.", false );
}
return;
}
// Clear out userExercise objects from localStorage in case we are over
// quota. They are now stored in sessionStorage when needed anyway.
(function() {
var i = 0;
while (i < localStorage.length) {
var key = localStorage.key(i);
if (key.indexOf('exercise:') === 0) {
delete localStorage[key];
}
else {
i++;
}
}
})();
// Prime numbers used for jumping through exercises
var primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,
47, 53, 59, 61, 67, 71, 73, 79, 83],
/*
===============================================================================
Crc32 is a JavaScript function for computing the CRC32 of a string
...............................................................................
Version: 1.2 - 2006/11 - http://noteslog.com/category/javascript/
-------------------------------------------------------------------------------
Copyright (c) 2006 Andrea Ercolino
http://www.opensource.org/licenses/mit-license.php
===============================================================================
*/
// CRC32 Lookup Table
table = "00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F 63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC 51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E 7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D 806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA 11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F 30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D",
/* Number */
crc32 = function( /* String */ str, /* Number */ crc ) {
if( crc == window.undefined ) { crc = 0; }
var n = 0; //a number between 0 and 255
var x = 0; //an hex number
crc = crc ^ (-1);
for( var i = 0, iTop = str.length; i < iTop; i++ ) {
n = ( crc ^ str.charCodeAt( i ) ) & 0xFF;
x = "0x" + table.substr( n * 9, 8 );
crc = ( crc >>> 8 ) ^ x;
}
return Math.abs( crc ^ (-1) );
},
// Get the userExercise object from the global scope
userExercise = window.userExercise,
// Check to see if we're in test mode
testMode = typeof userExercise === "undefined",
// The main server we're connecting to for saving data
server = typeof apiServer !== "undefined" ? apiServer :
testMode ? "http://localhost:8080" : "",
// The name of the exercise
exerciseName = typeof userExercise !== "undefined" ? userExercise.exercise : ((/([^\/.]+)(?:\.html)?$/.exec( window.location.pathname ) || [])[1]),
// Bin users into a certain number of realms so that
// there is some level of reproducability in their questions
bins = 200,
// The seed information
randomSeed,
// Holds the current username
user = null,
userCRC32,
// The current problem and its corresponding exercise
problem,
exercise,
// The number of the current problem that we're on
problemNum = 1,
// Info for constructing the seed
seedOffset = 0,
jumpNum = 1,
problemSeed = 0,
problemID,
// The current validator function
validator,
hints,
// The exercise elements
exercises,
// If we're dealing with a summative exercise
isSummative = false,
// If we're in review mode: present a mix of different exercises
reviewMode = typeof initialReviewsLeftCount === "number",
reviewQueue = [],
// Where we are in the shuffled list of problem types
problemBag,
problemBagIndex = 0,
// How many problems are we doing? (For the fair shuffle bag.)
problemCount = 10,
// For saving problems to the server
hintsUsed,
lastAction,
attempts,
once = true,
guessLog,
userActivityLog,
// A map of jQuery queues for serially sending and receiving AJAX requests.
requestQueue = {},
// For loading remote exercises
remoteCount = 0,
// Debug data dump
dataDump = {
"exercise": exerciseName,
"problems": [],
"issues": 0
},
urlBase = typeof urlBaseOverride !== "undefined" ? urlBaseOverride :
testMode ? "../" : "/khan-exercises/",
lastFocusedSolutionInput = null,
issueError = "Communication with GitHub isn't working. Please file "
+ "the issue manually at <a href=\""
+ "http://github.com/Khan/khan-exercises/issues/new\">GitHub</a>. "
+ "Please reference exercise: " + exerciseName + ".",
issueSuccess = function( url, title, suggestion ) {
return ["Thank you for your feedback! Your issue has been created and can be ",
"found at the following link:",
"<p><a id=\"issue-link\" href=\"", url, "\">", title, "</a>",
"<p>", suggestion, "</p>"].join('');
},
issueIntro = "Remember to check the hints and double check your math. All provided information will be public. Thanks for your help!",
modulesLoaded = false,
gae_bingo = window.gae_bingo || { bingo: function() {} };
// Nuke the global userExercise object to make
// it significantly harder to cheat
try {
delete window.userExercise;
}
catch(e) {} // swallow exception from IE
finally {
if (window.userExercise) {
window.userExercise = undefined;
}
}
// Add in the site stylesheets
if (testMode) {
(function(){
var link = document.createElement("link");
link.rel = "stylesheet";
link.href = urlBase + "css/khan-site.css";
document.getElementsByTagName('head')[0].appendChild(link);
link = document.createElement("link");
link.rel = "stylesheet";
link.href = urlBase + "css/khan-exercise.css";
document.getElementsByTagName('head')[0].appendChild(link);
})();
}
// The main Khan Module
var Khan = {
modules: {},
// So modules can use file paths properly
urlBase: urlBase,
moduleDependencies: {
"math": [ {
src: urlBase + "utils/MathJax/1.1a/MathJax.js?config=KAthJax-77111459c7d82564a705f9c5480e2c88"
}, "raphael" ],
// Load Raphael locally because IE8 has a problem with the 1.5.2 minified release
// http://groups.google.com/group/raphaeljs/browse_thread/thread/c34c75ad8d431544
// The normal module dependencies.
"calculus": [ "math", "expressions", "polynomials" ],
"exponents": [ "math", "math-format" ],
"kinematics": [ "math" ],
"math-format": [ "math", "expressions" ],
"polynomials": [ "math", "expressions" ],
"stat": [ "math" ],
"word-problems": [ "math" ],
"derivative-intuition": [ "jquery.mobile.vmouse" ],
"unit-circle": [ "jquery.mobile.vmouse" ],
"interactive": [ "jquery.mobile.vmouse" ],
"mean-and-median": [ "stat" ]
},
warnTimeout: function() {
warn( 'Your internet might be too slow to see an exercise. Refresh the page '
+ 'or <a href="" id="warn-report">report a problem</a>.', false );
jQuery( "#warn-report" ).click( function( e ) {
e.preventDefault();
jQuery( "#report" ).click();
});
},
warnFont: function() {
var enableFontDownload = "enable font download in your browser";
if ( jQuery.browser.msie ) {
enableFontDownload = '<a href="http://missmarcialee.com/2011/08/how-to-enable-font-download-in-internet-explorer-8/" target="_blank">enable font download</a>';
}
warn( 'You should ' + enableFontDownload + ' to improve the appearance of math expressions.', true );
},
require: function( mods ) {
if ( mods == null ) {
return;
} else if ( typeof mods === "string" ) {
mods = mods.split( " " );
} else if ( !jQuery.isArray( mods ) ) {
mods = [ mods ];
}
jQuery.each(mods, function( i, mod ) {
var src, deps;
if ( typeof mod === "string" ) {
var cachebust = "";
if ( testMode && Khan.query.nocache != null ) {
cachebust = "?" + Math.random();
}
src = urlBase + "utils/" + mod + ".js" + cachebust;
deps = Khan.moduleDependencies[ mod ];
mod = {
src: src,
name: mod
};
} else {
src = mod.src;
deps = mod.dependencies;
delete mod.dependencies;
}
if ( !Khan.modules[ src ] ) {
Khan.modules[ src ] = mod;
Khan.require( deps );
}
});
},
// Populate this with modules
Util: {
// http://burtleburtle.net/bob/hash/integer.html
// This is also used as a PRNG in the V8 benchmark suite
random: function() {
// Robert Jenkins' 32 bit integer hash function.
var seed = randomSeed;
seed = ( ( seed + 0x7ed55d16 ) + ( seed << 12 ) ) & 0xffffffff;
seed = ( ( seed ^ 0xc761c23c ) ^ ( seed >>> 19 ) ) & 0xffffffff;
seed = ( ( seed + 0x165667b1 ) + ( seed << 5 ) ) & 0xffffffff;
seed = ( ( seed + 0xd3a2646c ) ^ ( seed << 9 ) ) & 0xffffffff;
seed = ( ( seed + 0xfd7046c5 ) + ( seed << 3 ) ) & 0xffffffff;
seed = ( ( seed ^ 0xb55a4f09 ) ^ ( seed >>> 16 ) ) & 0xffffffff;
return ( randomSeed = ( seed & 0xfffffff ) ) / 0x10000000;
}
},
// Load in a collection of scripts, execute callback upon completion
loadScripts: function( urls, callback ) {
var loaded = 0,
loading = urls.length,
head = document.getElementsByTagName('head')[0];
callback || ( callback = function() { } );
for ( var i = 0; i < loading; i++ ) { (function( mod ) {
if ( !testMode && mod.src.indexOf("/khan-exercises/") === 0 && mod.src.indexOf("/MathJax/") === -1 ) {
// Don't bother loading khan-exercises content in production
// mode, this content is already packaged up and available
// (*unless* it's MathJax, which is silly still needs to be loaded)
loaded++;
return;
}
// Adapted from jQuery getScript (ajax/script.js)
var script = document.createElement("script");
script.async = "async";
for ( var prop in mod ) {
script[ prop ] = mod[ prop ];
}
script.onerror = function() {
// No error in IE, but this is mostly for debugging during development so it's probably okay
// http://stackoverflow.com/questions/2027849/how-to-trigger-script-onerror-in-internet-explorer
Khan.error( "Error loading script " + script.src );
};
script.onload = script.onreadystatechange = function() {
if ( !script.readyState || ( /loaded|complete/ ).test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( script.parentNode ) {
script.parentNode.removeChild( script );
}
// Dereference the script
script = undefined;
runCallback();
}
};
head.appendChild(script);
})( urls[i] ); }
runCallback( true );
function runCallback( check ) {
if ( check !== true ) {
loaded++;
}
if ( callback && loading === loaded ) {
callback();
}
}
},
// Query String Parser
// Original from:
// http://stackoverflow.com/questions/901115/get-querystring-values-in-javascript/2880929#2880929
queryString: function() {
var urlParams = {},
e,
a = /\+/g, // Regex for replacing addition symbol with a space
r = /([^&=]+)=?([^&]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
q = window.location.search.substring(1);
while ( (e = r.exec(q)) ) {
urlParams[d(e[1])] = d(e[2]);
}
return urlParams;
},
// Display error messages
error: function( ) {
if ( typeof console !== "undefined" ) {
jQuery.each( arguments, function( ix, arg ) {
console.error(arg);
});
}
},
scratchpad: (function() {
var disabled = false, visible = false, wasVisible, pad;
var actions = {
disable: function() {
wasVisible = visible;
actions.hide();
jQuery( "#scratchpad-show" ).hide();
jQuery( "#scratchpad-not-available" ).show();
disabled = true;
},
enable: function() {
if ( wasVisible ) {
actions.show();
wasVisible = false;
}
jQuery( "#scratchpad-show" ).show();
jQuery( "#scratchpad-not-available" ).hide();
disabled = false;
},
isVisible: function() {
return visible;
},
show: function() {
if ( visible ) {
return;
}
var makeVisible = function() {
jQuery( "#workarea, #hintsarea" ).css( "padding-left", 60 );
jQuery( "#scratchpad" ).show();
jQuery( "#scratchpad-show" ).text( "Hide scratchpad" );
visible = true;
};
if ( !pad ) {
Khan.loadScripts( [ { src: urlBase + "utils/scratchpad.js" } ], function() {
makeVisible();
pad || ( pad = new Scratchpad( jQuery( "#scratchpad div" )[0] ) );
} );
} else {
makeVisible();
}
},
hide: function() {
if ( !visible ) {
return;
}
jQuery( "#workarea, #hintsarea" ).css( "padding-left", 0 );
jQuery( "#scratchpad" ).hide();
jQuery( "#scratchpad-show" ).text( "Show scratchpad" );
visible = false;
},
toggle: function() {
visible ? actions.hide() : actions.show();
},
clear: function() {
if ( pad ) {
pad.clear();
}
},
resize: function() {
if ( pad ) {
pad.resize();
}
}
};
return actions;
})(),
relatedVideos: {
videos: [],
setVideos: function(videos) {
this.videos = videos || [];
this.render();
},
showThumbnail: function( index ) {
jQuery( "#related-video-list .related-video-list li" ).each(function(i, el) {
if ( i === index ) {
jQuery( el )
.find( 'a.related-video-inline' ).hide().end()
.find( '.thumbnail' ).show();
}
else {
jQuery( el )
.find( 'a.related-video-inline' ).show().end()
.find( '.thumbnail' ).hide();
}
});
},
// make a link to a related video, appending exercise ID.
makeHref: function(video, data) {
var exid = '';
data = data || userExercise;
if ( data ) {
exid = "?exid=" + data.exercise_model.name;
}
return video.relative_url + exid;
},
anchorElement: function( video, needComma ) {
var template = Templates.get("video.related-video-link");
return jQuery(template({
href: this.makeHref(video),
video: video,
separator: needComma
})).data('video', video);
},
renderInHeader: function() {
var container = jQuery(".related-content");
var jel = container.find(".related-video-list");
jel.empty();
_.each(this.videos, function(video, i) {
this.anchorElement(video, i < this.videos.length - 1)
.wrap("<li>").parent().appendTo(jel);
}, this);
container.toggle(this.videos.length > 0);
},
renderInSidebar: function() {
var container = jQuery(".related-video-box");
var jel = container.find(".related-video-list");
jel.empty();
var template = Templates.get('video.thumbnail');
_.each(this.videos, function(video, i) {
var thumbnailDiv = jQuery(template({
href: this.makeHref(video),
video: video
})).find('a.related-video').data('video', video).end();
var inlineLink = this.anchorElement(video)
.addClass("related-video-inline");
var sideBarLi = jQuery( "<li>" )
.append( inlineLink )
.append( thumbnailDiv );
if ( i > 0 ) {
thumbnailDiv.hide();
} else {
inlineLink.hide();
}
jel.append( sideBarLi );
}, this);
container.toggle(this.videos.length > 0);
},
hookup: function() {
// make caption slide up over the thumbnail on hover
var captionHeight = 45;
var marginTop = 23;
// queue:false to make sure these run simultaneously
var options = {duration: 150, queue: false};
jQuery(".related-video-box")
.delegate(".thumbnail", "mouseenter mouseleave", function(e) {
var el = $(e.currentTarget);
if (e.type == "mouseenter") {
el. find( ".thumbnail_label" ).animate(
{ marginTop: marginTop },
options)
.end()
.find( ".thumbnail_teaser" ).animate(
{ height: captionHeight },
options)
.end();
} else {
el .find( ".thumbnail_label" ).animate(
{ marginTop: marginTop + captionHeight },
options)
.end()
.find( ".thumbnail_teaser" ).animate(
{ height: 0 },
options)
.end();
}
});
},
render: function() {
// don't try to render if templates aren't present (dev mode)
if (!window.Templates) return;
this.renderInSidebar();
// Review queue overlaps with the content here
if ( !reviewMode ) {
this.renderInHeader();
}
}
},
showSolutionButtonText: function() {
return hintsUsed ? "Show step (" + hints.length + " left)" : "Show Solution";
}
};
// see line 183. this ends the main Khan module
// Load query string params
Khan.query = Khan.queryString();
if ( Khan.query.activity !== undefined ) {
userExercise = {
exercise_model: {},
read_only: true,
user_activity: JSON.parse( Khan.query.activity )
};
}
// Seed the random number generator with the user's hash
randomSeed = testMode && parseFloat( Khan.query.seed ) || userCRC32 || ( new Date().getTime() & 0xffffffff );
// Load in jQuery
var scripts = (typeof jQuery !== "undefined") ? [] : [ { src: "../jquery.js" } ];
// Actually load the scripts. This is getting evaluated when the file is loaded.
Khan.loadScripts( scripts, function() {
if ( testMode ) {
Khan.require( [ "../jquery-ui" ] );
}
// Base modules required for every problem
Khan.require( [ "answer-types", "tmpl", "underscore", "jquery.adhesion" ] );
Khan.require( document.documentElement.getAttribute("data-require") );
// Initialize to an empty jQuery set
exercises = jQuery();
if ( typeof userExercise !== "undefined" ) {
prepareUserExercise( userExercise );
} else {
// Load in the exercise data from the server
jQuery.ajax({
// Do a request to the server API
url: server + "/api/v1/user/exercises/" + exerciseName,
type: "GET",
dataType: "json",
// Make sure cookies are passed along
xhrFields: { withCredentials: true },
success: prepareUserExercise
});
}
jQuery(function() {
var remoteExercises = jQuery( ".exercise[data-name]" );
if ( remoteExercises.length ) {
isSummative = true;
remoteExercises.each( loadExercise );
// Only run loadModules if exercises are in the page
} else if ( jQuery( ".exercise" ).length ) {
loadModules();
}
});
jQuery.fn.extend({
// Pick a random element from a set of elements
getRandom: function() {
return this.eq( Math.floor( this.length * KhanUtil.random() ) );
},
// Run the methods provided by a module against some elements
runModules: function( problem, type ) {
type = type || "";
var info = {
testMode: testMode
};
return this.each(function( i, elem ) {
elem = jQuery( elem );
// Run the main method of any modules
jQuery.each( Khan.modules, function( src, mod ) {
var name = mod.name;
if ( jQuery.fn[ name + type ] ) {
elem[ name + type ]( problem, info );
}
});
});
}
});
// An animation that fades in then out a text shadow
jQuery.fx.step.reviewGlow = function( fx ) {
var val = -4 * Math.pow( fx.now - 0.5, 2 ) + 1;
jQuery( fx.elem ).css( 'textShadow', 'rgba(227, 93, 4, ' + val + ') 0 0 12px');
};
// See if an element is detached
jQuery.expr[":"].attached = function( elem ) {
return jQuery.contains( elem.ownerDocument.documentElement, elem );
};
});
// Add up how much total weight is in each exercise so we can adjust for
// it later
function weighExercises( problems ) {
if ( exercises.length > 1 ) {
jQuery.map( problems, function( elem ) {
elem = jQuery( elem );
var exercise = elem.parents( ".exercise" ).eq( 0 );
var exerciseTotal = exercise.data( "weight-sum" );
exerciseTotal = exerciseTotal !== undefined ? exerciseTotal : 0;
var weight = elem.data( "weight" );
weight = weight !== undefined ? weight : 1;
exercise.data( "weight-sum", exerciseTotal + weight );
});
}
}
// Create a set of n problems fairly from the weights - not random; it
// ensures that the proportions come out as fairly as possible with ints
// (still usually a little bit random).
// There has got to be a better way to do this.
function makeProblemBag( problems, n ) {
var bag = [], totalWeight = 0;
if ( testMode && Khan.query.test != null ) {
// Just do each problem 10 times
jQuery.each( problems, function( i, elem ) {
elem = jQuery( elem );
elem.data( "id", elem.attr( "id" ) || "" + i );
for ( var j = 0; j < 10; j++ ) {
bag.push( problems.eq( i ) );
}
} );
problemCount = bag.length;
} else if ( problems.length > 0 ) {
// Collect the weights for the problems and find the total weight
var weights = jQuery.map( problems, function( elem, i ) {
elem = jQuery( elem );
var exercise = elem.parents( ".exercise" ).eq( 0 );
var exerciseWeight = exercise.data( "weight" );
exerciseWeight = exerciseWeight !== undefined ? exerciseWeight : 1;
var exerciseTotal = exercise.data( "weight-sum" );
var weight = elem.data( "weight" );
weight = weight !== undefined ? weight : 1;
if ( exerciseTotal !== undefined ) {
weight = weight * exerciseWeight / exerciseTotal;
elem.data( "weight", weight );
}
// Also write down the index/id for each problem so we can do
// links to problems (?problem=17)
elem.data( "id", elem.attr( "id" ) || "" + i );
totalWeight += weight;
return weight;
});
while ( n ) {
bag.push( (function() {
// Figure out which item we're going to pick
var index = totalWeight * KhanUtil.random();
for ( var i = 0; i < problems.length; i++ ) {
if ( index < weights[i] || i === problems.length - 1 ) {
var w = Math.min( weights[i], totalWeight / ( n-- ) );
weights[i] -= w;
totalWeight -= w;
return problems.eq( i );
} else {
index -= weights[i];
}
}
// This will never happen
return Khan.error("makeProblemBag got confused w/ index " + index);
})() );
}
}
return bag;
}
function cacheUserExerciseDataLocally( exerciseName, data ) {
if ( user == null ) return;
var key = "exercise:" + user + ":" + exerciseName;
var oldVal = window.sessionStorage[ key ];
// We sometimes patch UserExercise.exercise_model with related_videos and
// sometimes don't, so extend existing objects to avoid erasing old values.
window.sessionStorage[ key ] = JSON.stringify( typeof oldVal === "string" ?
jQuery.extend( /* deep */ true, JSON.parse(oldVal), data ) : data );
}
// TODO(david): Would be preferable to use the exercise model's display_name
// property instead of duplicating that code here on the client.
function getDisplayNameFromId( id ) {
return id.charAt( 0 ).toUpperCase() + id.slice( 1 ).replace( /_/g, ' ' );
}
// This function is a closure returned from an immediately-called function so
// we can have private static variables (requestPending).
var maybeEnqueueReviewProblems = (function() {
var requestPending = false;
// Handle successful retrieval of review exercises from the server
function enqueueReviewExercises( reviewExercises ) {
// Only process and keep the first few exercises returned so we don't send
// off a huge stream of AJAX requests.
reviewExercises = reviewExercises.slice( 0, 3 );
reviewQueue = reviewQueue.concat( reviewExercises );
// Use an empty jQuery object to use as a sliding animations queue holder
var slideQueue = jQuery( {} );
jQuery.each( reviewExercises, function( i, exid ) {
// Slide up the exercise into the upcoming exercises queue, one-by-one
slideQueue.queue(function( next ) {
jQuery( "<p>" + getDisplayNameFromId( exid ) + "</p>" )
.css( "marginTop", Math.max(38 - i * 15, 10) )
.appendTo( jQuery("#next-exercises") )
.animate( { marginTop: 0 }, /* duration */ 365, next );
});
// Was this exercise's data and HTML loaded by loadExercise already?
var isLoaded = exercises.filter(function() {
return jQuery.data( this, "rootName" ) === exid;
}).length;
// Load all non-loadExercise loaded exercises
if ( !isLoaded ) {
var exerciseElem = jQuery( "<div>" )
.data( "name", exid )
.data( "rootName", exid );
loadExercise.call( exerciseElem );
// Update the cached UserExercise model for this exercise. One reason
// we do this is to update the states (for correct icon display),
// which may have changed since the user last did the exercise.
jQuery.ajax({
url: server + "/api/v1/user/exercises/" + exid,
type: "GET",
dataType: "json",
xhrFields: { withCredentials: true },
success: _.bind( cacheUserExerciseDataLocally, null, exid )
});
}
});
requestPending = false;
}
return function() {
if ( !reviewMode || reviewQueue.length >= 3 || requestPending ) return;
// Indicates to the server which reviews are already queued up, including
// the current exercise if it has not been attempted yet.
var reviewsToAttempt = ( attempts == 0 && hintsUsed == 0 ?
reviewQueue.concat( exerciseName ) : reviewQueue );
// Send the request to fetch the next set of review exercises
jQuery.ajax({
url: "/api/v1/user/exercises/review_problems",
type: "GET",
dataType: "json",
xhrFields: { withCredentials: true },
data: {
queued: reviewsToAttempt.join( "," )
},
success: enqueueReviewExercises
});
requestPending = true;
};
})();
function enableCheckAnswer() {
jQuery( "#check-answer-button" )
.removeAttr( "disabled" )
.removeClass( "buttonDisabled" )
.val('Check Answer');
}
function disableCheckAnswer() {
jQuery( "#check-answer-button" )
.attr( "disabled", "disabled" )
.addClass( "buttonDisabled" )
.val('Please wait...');
}
function switchToExercise( exid ) {
exerciseName = exid;
var newUserExercise = getData();
setProblemNum( newUserExercise.total_done + 1 );
// Get all problems of this exercise type...
var problems = exercises.filter(function() {
return jQuery.data( this, "rootName" ) === exid;
}).children( ".problems" ).children();
// ...and create a new problem bag with problems of our new exercise type.
// TODO(david): Possibly save this in hash map, so we don't have to
// recompute it?
problemBag = makeProblemBag( problems, 10 );
// Update the document title
var title = document.title;
document.title = getDisplayNameFromId( exid ) + " " +
title.slice( title.indexOf("|") );
// update related videos
Khan.relatedVideos.setVideos(newUserExercise.exercise_model.related_videos);
}
function makeProblem( id, seed ) {
if ( typeof Badges !== "undefined" ) {
Badges.hide();
}