-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathmawrid-app.js
1521 lines (1320 loc) · 44.1 KB
/
mawrid-app.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
// Some global vars that we need:
var debugmode = false;
var version = "4.0 - beta";
var title_text = '... ' + " - powered by Mawrid Reader" + " v" + version;
$("#version").append(title_text);
var toggle = 1;
var starting_hash = "#";
var state = {};
// Available configurations and descriptions
var confs = [
{ "aa": "Root based Arabic dictionaries in various languages" },
{ "mr": "Regular (non-root based) Arabic dictionaries in various languages" }
]
// default configuration from the above
var requested_conf = "aa"
//var all_roots = {};
// reload_page()
var initial_book_order = "";
//var aa_book_order = initial_book_order;
var toggle_view_auto = 1;
var toggle_view_mode;
var fitwidth = false;
var last_input = "";
var searched_word = "";
// This is the base directory under which all image directories will be placed:
var img_base_dir = "../aa-data/img/";
//var img_base_dir = "img/";
var text_base_dir = "text/";
// Only allow .dev classes to show up when we're not live:
// Make not allow it in file: either ? TODO
if ( (document.location.hostname == "localhost") || (document.location.hostname == "abd.ejtaal.net") || (window.location.protocol=='file:') )
$(".dev").show();
// Setup shortcuts:
shortcut.add("F",function() { searchandgo(); });
shortcut.add("V",function() { toggle_view(); });
shortcut.add("Z",function() { visible_book_shift( -1); });
shortcut.add("D",function() { visible_book_shift( -1); });
shortcut.add("Left",function() { visible_book_shift( -1); });
shortcut.add("X",function() { visible_book_shift( 1); });
shortcut.add("G",function() { visible_book_shift( 1); });
shortcut.add("Right",function() { visible_book_shift( 1); });
shortcut.add("P",function() { testing123(); });
shortcut.add("W",function() { toggle_fitwidth(); });
// Bind the swipeHandler callback function to the swipe css classes
$( ".swipe" ).on( "swiperight", swipe_it);
$( ".swipe" ).on( "swipeleft", swipe_it );
// Callback function references the event target and adds the 'swipe' class to it
function swipe_it( event ){
if ( state['enable_swipe'] == 1) {
var pid = $(event.target).closest("div.book").attr("id");
debug("JQM Swipe event for img under "+pid+":");
console.log(event);
if ( event.type == 'swiperight') shift_page( pid, -1);
if ( event.type == 'swipeleft') shift_page( pid, 1);
}
}
$( window ).hashchange(function() {
parse_hash();
});
$(".swipe").click(function(){
searchandgo()
});
// **********************************************
// *** -------------------------------------- ***
// Beware, there be subroutines beyond this point
// *** -------------------------------------- ***
// **********************************************
function make_suggestions( root, arr) {
//debug( "Start finding suggestions: ")
// This little array produces yamli-like magic :)
var yamli_map = {
"ي": "يوا",
"و": "ويا",
"ا": "اوي",
"ت": "تط",
"ط": "طت",
"د": "دذضظ",
"ظ": "ظز",
"ز": "زظ",
"ك": "كق",
"ق": "قك",
"ه": "هح",
"ح": "حه",
"a": "awye",
"w": "way",
"y": "ywa",
"d": "dD*Z",
"h": "hH",
"t": "tT",
"s": "sSv",
"z": "zZ",
"k": "kx"
}
var suggestions = [];
var building = [];
suggestions[0] = '';
for ( var letter = 0; letter < root.length; letter++) {
var mapping_found = false;
var la = root.substring( letter, letter+1)
for ( var search in yamli_map) {
//debug( "la: "+la+" == search:" + search)
var cur_suggestion_size = suggestions.length;
building = [];
if ( la == search) {
mapping_found = true;
var replace = yamli_map[search];
//debug( "letter " + letter + " in '" + root +"' equals search '"
//+ search + "': '" + replace +"'");
for ( var c = 0; c < suggestions.length; c++) {
//debug( "r = " + r);
for ( var r = 0; r < replace.length; r++ ) {
//debug( "c = " + c);
var newbuild = suggestions[c] + replace.substring( r, r+1);
building.push( newbuild)
}
}
suggestions = building;
}
}
if (! mapping_found)
for ( var c = 0; c < suggestions.length; c++)
suggestions[c] += la;
}
// If any of the suggestions are 2 letters long,
// suggest one straight after with the 2nd letter repeated
for (var i = 0; i < suggestions.length; i++)
if ( suggestions[i].length == 2)
suggestions.splice( i + 1, 0, suggestions[i] + suggestions[i].substring( 1, 2))
//debug( "suggestions: ")
//debug( suggestions)
var suggestions_bw = [];
// Now buckwalterize the suggestions:
for ( var c = 0; c < suggestions.length; c++)
suggestions_bw[c] = buckwalter( 'encode', suggestions[c]);
//debug( "suggestions buckwaltered: ")
//debug( suggestions_bw)
//arr=['ﺍ','آﺍ','ﺍب','ﺍبﺍ','ﺍبب','ﺍبت','ﺍبجد'];
//arr=['ا','آا','اب','ابا','ابب','ابت','ابجد','ابخ','ابد'];
// filter suggestions to those that match arr
// beware, the next bit gets slow quickly the more you type :(
//debug( "start filtering")
// 4 phases:
// 1: collect ones that are equal
var found = 0
var suggestions_bw_filtered = jQuery.grep( suggestions_bw, function( n, i ) {
if ( found > 10) return false
for ( var r = 0; r < arr.length; r++) {
if ( n == arr[r]) {
found++
return true;
}
}
return false;
});
//debug( "after phase 1, results:")
//debug( suggestions_bw_filtered)
found = 0
out_of_the_matrix_2:
for ( var s = 0; s < suggestions_bw.length; s++) {
for ( var a = 0; a < arr.length; a++) {
if ( arr[a].indexOf( suggestions_bw[s]) == 0) {
found++
suggestions_bw_filtered.push( arr[a])
}
if ( found > 10) break out_of_the_matrix_2
}
}
/*
// 2: collect ones that begin with search term
suggestions_bw_filtered = suggestions_bw_filtered.concat(
jQuery.grep( arr, function( n, i ) {
if ( found > 10) return false
for ( var s = 0; s < suggestions_bw.length; s++) {
//debug( "n = ["+n+'], root = [' +suggestions_bw[s]+']')
//debug( n.indexOf( suggestions_bw[s] ))
if ( n.indexOf( suggestions_bw[s] ) == 0) {
found++
return true
}
}
return false;
})
);
*/
//debug( "after phase 2, results:")
//debug( suggestions_bw_filtered)
found = 0
// 3: collect ones that match any other part
suggestions_bw_filtered = suggestions_bw_filtered.concat(
jQuery.grep( arr, function( n, i ) {
if ( found > 10) return false
for ( var s = 0; s < suggestions_bw.length; s++) {
if ( n.indexOf( suggestions_bw[s] ) !== -1) {
found++
return true
}
}
return false;
})
);
//debug( "end of collection, results:")
//debug( suggestions_bw_filtered)
// 4: remove duplicates
for ( var i = 0; i < suggestions_bw_filtered.length; i++)
for ( var j = suggestions_bw_filtered.length - 1; j > i; j--)
if ( suggestions_bw_filtered[i] == suggestions_bw_filtered[j])
suggestions_bw_filtered.splice( j, 1);
//debug( "end filtering, results:")
//debug( suggestions_bw_filtered)
//debug( "Finished finding suggestions.")
//response = [ 'a', 'b', 'c']
return suggestions_bw_filtered
}
function suggest_completions( typed, callback) {
// This function is only used by the autocomplete input field.
suggestions_bw_filtered = make_suggestions( typed, all_roots)
typed_bw = buckwalter( 'encode', typed)
response = []
for ( var i = 0; i < suggestions_bw_filtered.length; i++)
response.push({
'value': suggestions_bw_filtered[i],
'count': count_root_occurances( suggestions_bw_filtered[i]),
'label':
suggestions_bw_filtered[i].replace(
new RegExp('('+typed_bw+')'), '<b>\$1</b>')
})
//response = suggestions_bw_filtered
callback(response)
}
function load_page ( book, page) {
books[book]['wanted'] = page
load_book_texts()
//build_hash()
}
function buckwalter( action, str) {
// Very limited functionality as only needed for root letters
// and we don't deal with diacritics etc.
if ( action == 'encode') {
// From android: ء ٱ آ إ
//str = str.replace(/[إآٱأءﺀﺀﺁﺃﺅﺇﺉ]/g,"ا");
//str = str.replace(/[ﻯ]/g,"ي");
// Firstly the letters that take IMHO 2 letters to transliterate
str = str.replace(/v/g,"ث");
str = str.replace(/[gG]/g,"غ");
str = str.replace(/x/g,"خ");
str = str.replace(/\$/g,"ش");
str = str.replace(/\*/g,"ذ");
// Hmm, make the following case insensitive and assign different letters to different cases:
str = str.replace(/d/g,"د");
str = str.replace(/D/g,"ض");
str = str.replace(/z/g,"ز");
str = str.replace(/Z/g,"ظ");
str = str.replace(/s/g,"س");
str = str.replace(/S/g,"ص");
str = str.replace(/t/g,"ت");
str = str.replace(/T/g,"ط");
str = str.replace(/h/g,"ه");
str = str.replace(/H/g,"ح");
// Include chat arabic?
//str = str.replace(/[7]/g,"ح");
//str = str.replace(/[3]/g,"ع");
// Not much iktilaaf over these I guess:
str = str.replace(/[xX]/g,"خ");
str = str.replace(/[vV]/g,"ث");
str = str.replace(/[aA]/g,"ا");
str = str.replace(/[bB]/g,"ب");
str = str.replace(/[jJ]/g,"ج");
str = str.replace(/[rR]/g,"ر");
str = str.replace(/[eE]/g,"ع");
str = str.replace(/[fF]/g,"ف");
str = str.replace(/[qQ]/g,"ق");
str = str.replace(/[kK]/g,"ك");
str = str.replace(/[lL]/g,"ل");
str = str.replace(/[mM]/g,"م");
str = str.replace(/[nN]/g,"ن");
str = str.replace(/[wW]/g,"و");
str = str.replace(/[yY]/g,"ي");
}
if ( action == 'decode' ) {
//well that's a bit trickier
}
return str
}
/*
$(function() {
$(".swipe").swipe({
swipeLeft: shift_the_page,
swipeRight: shift_the_page,
swipe: shift_the_page,
tap:function(event, target) {
//var pid = $(this).parent().attr("id");
debug("You tapped" );
searchandgo();
},
allowPageScroll:"vertical"
});
function shift_the_page(event, direction) {
//var pid = $(this).parent().parent().parent().attr("id");
var pid = $(this).closest("div.book").attr("id");
//$(this).text("You swiped " + direction );
debug("You swiped " + direction + ' on ' + pid);
//alert("You swiped " + direction + ' on ' + pid);
if ( direction == 'right') shift_page( pid, -1);
if ( direction == 'left') shift_page( pid, 1);
}
});
*/
function move_build( id, where) {
move( id, where)
build_hash()
}
function move( id, where) {
var objects = [ '#'+id, '#'+id+"_setting"];
for (i = 0; i < objects.length; i++) {
obj = objects[i]
//$(obj).fadeOut({ duration: 100})
if ( where == "top" ) {
// Move to top
//debug( "moving "+obj+" to top")
$(obj).parent().prepend($(obj));
}
else if (where == "bottom" ) {
//debug( "moving "+obj+" to bottom")
$(obj).parent().append($(obj));
//$('#all_objs').append($(obj));
//$(obj).remove().insertAfter($("#all_objs div:last"));
//$("#all_objs" .row:first").remove().insertAfter($("#container .row:last));
}
else if (where == "up" ) {
// Move one up
//debug( "moving "+obj+" 1 up")
$(obj).after( $(obj).prev() );
}
else if (where == "down") {
// Move one down
//debug( "moving "+obj+" 1 down")
$(obj).before( $(obj).next() );
}
//$(obj).fadeIn({ duration: 100})
}
}
function toggle_hide( book) {
if ( books[book]["should_hide"] == 1)
books[book]["should_hide"] = 0
else books[book]["should_hide"] = 1
build_hash()
}
function hide_book_build( target, should_hide) {
hide_book( target, should_hide)
build_hash()
}
function hide_book( target, should_hide) {
//debug( "hide: " + target + "=" + should_hide)
books[target]["should_hide"] = should_hide;
if ( should_hide) {
hide_show( target+'_page', target+'_toggle');
$("#"+target+"_hidebutton").removeClass("disabled_button").addClass( "enabled_button" )
}
else {
hide_show( target+'_toggle', target+'_page');
$("#"+target+"_hidebutton").css('border','')
$("#"+target+"_hidebutton").removeClass("enabled_button").addClass( "disabled_button" )
}
}
function hideme_show( hideobj, showobj) {
hideobj.style.display = "none";
//document.getElementById(showobj).style.display = "block";
$("#"+showobj).show('fast');
}
function hide_id( id, scrollto) {
//document.getElementById( id).style.display = "none";
//debug( 'hiding ' + id);
$("#"+id).hide('fast');
if (scrollto) {
//debug( 'scrolling to: ' +id);
$(window).scrollTop( $("#"+id).offset().top);
}
}
function hide_show( hideid, showid, scrollto) {
$("#"+hideid).hide('fast');
$("#"+showid).show('fast');
if (scrollto) {
//debug( 'scrolling to: ' +showid);
$(window).scrollTop( $("#"+showid).offset().top);
}
}
function set_hash( s) {
hide_id('about');
window.location.hash = s;
setCookie( project["prefix"]+"last_hash", window.location.hash, 365);
}
function build_hash() {
var new_hash = "#"
new_hash += "conf=" + requested_conf + ','
$('#all_books').children().each(function(){
var book = $(this).attr('id');
// debug( book);
new_hash += book + "="
if (books[book]["should_hide"] == 1) new_hash += "h"
new_hash += books[book]["wanted"] + ','
})
if ( project['type'] == 'text' && searched_word != '')
new_hash += 'q=' + searched_word
new_hash = new_hash.replace(/,$/,'')
debug("new_hash = " + new_hash);
window.location.hash = new_hash;
setCookie( project["prefix"]+"last_hash", window.location.hash, 365);
}
function set_title() {
var title = "";
var i = 1;
//TODO: in order of books displayed:
if ( searched_word == "" ) {
$('#all_books').children().each(function(){
var id = $(this).attr('id');
// debug( 'CCC')
// debug( id);
var add_text = "";
if ( ! books[id]["should_hide"]) add_text = id + ": " + books[id]["index"][books[id]["current"]]
if ( add_text != "")
if ( title != "") title += " / " + add_text;
else title = add_text;
});
}
else title = "Search: " + searched_word;
if (title != "") title += " - ";
title += title_text;
if (document.location.protocol == 'file:' ||
document.location.protocol == 'content:') {
title = "[L] " + title;
}
//alert( title);
document.title = title;
}
function user_debug_1() {
alert( 'Protocol = ' + document.location.protocol)
}
var presets = []
var project = []
var books = []
function switch_config( c) {
debug( 'XXXXX')
// debug( c)
// debug( all_presets[c])
presets = all_presets[c]
debug(presets)
project = all_project[c]
books = all_books[c]
title_text = project["title"] + " v" + project["version"] + " - powered by Mawrid Reader" + " v" + version;
// debug('LLL')
// debug(books)
// Initiate books array with extra needed vars:
$( "#all_books" ).html("");
var book_id = 0
for (var key in books) {
// debug('FFF')
// debug(books[key])
//book_id++
books[key]["key"] = key
books[key]["id"] = ++book_id
books[key]["current"] = -1 // i.e. no page has been loaded
books[key]["wanted"] = books[key]["offset"];
if ( project["type"] == "text") {
// Do something
template = "text-book-template"
for (i = 0; i < books[key]["index"].length; i++) {
//all_roots[books[key]["index"][i]]
}
} else {
template = "image-book-template"
// Images based dictionaries assumed. Will there be a point in the future
// where text and image dictionaries can be mixed? Perhaps...
// Set up the right column order for viewing on mobiles
books[key]["col1_id"] = 1
books[key]["col2_id"] = 2
books[key]["col3_id"] = 3
if ( books[key]['columns'] == 1) {
$( '#' + key+'col_2').hide()
$( books[key]['columns']+'col_3').hide()
}
else if ( books[key]['columns'] == 2) {
$( books[key]['columns']+'col_3').hide()
if ( books[key]['direction'] == 'rtl') {
books[key]["col1_id"] = 2
books[key]["col2_id"] = 1
}
}
else if ( books[key]['columns'] == 3) {
if ( books[key]['direction'] == 'rtl') {
books[key]["col1_id"] = 3
books[key]["col2_id"] = 2
books[key]["col3_id"] = 1
}
}
}
// var book = books[key]
// for (var prop in book)
// if (book.hasOwnProperty(prop)) debug(key + "." + prop + " = " + book[prop])
$( "#"+template ).tmpl( books[key]).appendTo( "#all_books" );
$("#"+key+"_toggle").hide()
// Settings must be set for both text and image based dicts
$( "#settings-row" ).tmpl( books[key]).appendTo( "#settings_rows" );
starting_hash += key + '=' + books[key]["offset"] + ',';
$("."+key+"_color").css('background-color', books[key]["color"])
$("#"+key+"_wideviewimg").css('border', '3px solid ' + books[key]["color"])
if ( books[key]['columns'] < 2) $( '#' + key+'_col2').hide()
if ( books[key]['columns'] < 3) $( '#' + key+'_col3').hide()
}
debug( 'YYY')
debug(presets)
$( "#preset-cells" ).html("");
for (var key in presets) {
// debug('PRESET')
// debug(key)
presets[key]["key"] = key
$( "#preset-cell" ).tmpl( presets[key]).appendTo( "#preset-cells" );
}
// debug( books)
// reload_page()
// parse_hash();
}
function reload_page() {
// debug( 'YYY')
// debug( books)
/*
Run this when first setting a desired configuration.
Run it again if the config changes so new books,
presets etc are initialized
TODO: clear out books in DOM, config?
build_hash?
set_title?
*/
if ( project["type"] == "text") {
$("#text-input-field").show()
$("#text-input-field").keypress(function(e) {
code= (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
$(".ui-menu-item").hide();
text_search( buckwalter( 'encode', $("#text-input-field").val() ));
build_hash()
}
});
$("#text-input-field").autocomplete({
source: function( request, callback){
var t = request.term;
suggest_completions( t, callback)
},
select: function (a, b) {
$(this).val(b.item.value);
text_search( buckwalter( 'encode', $("#text-input-field").val() ));
build_hash()
},
delay: 0
})
.data( "ui-autocomplete" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a><table class='suggestion-table'><tr><td>(" + item.count + ")</td><td class='rtl'>" + item.label + "</td></tr></table></a>" )
.appendTo( ul );
};
// console.log(books)
set_title()
//.append( "<a><tablediv class='suggestion-label'>" + item.label + "</div><div class='suggestion_count'>(" + item.count + ")</span></a>" )
}
// JQM causes each link to work through AJAX, please
// don't do that!!! This or setting data-ajax="false"
// is supposed to fix that
$(document).ready(function(){
$("a").each(function(){
$(this).attr("rel","external");
});
// Do page_load once
// first_page_load();
// reload_page();
});
starting_hash = starting_hash.replace(/,$/,'')
debug("starting_hash = " + starting_hash)
initial_book_order = presets["default"];
title_text = project["title"] + " v" + project["version"] + " - powered by Mawrid Reader" + " v" + version;
}
function parse_hash() {
debug('PARSING HASH')
var hashstring = window.location.hash.replace(/^#/,'');
var i, vars = hashstring.split(',');
if (vars.length > 0) {
// Variables present in hash
var hide_following = false
for (i = vars.length - 1; i >= 0; i--) {
keyValuePair = vars[i].split('=');
//alert( "Var found: " + keyValuePair[0] + ' = ' + keyValuePair[1] );
var key = keyValuePair[0];
var value = keyValuePair[1];
//debug( "Var found: " + keyValuePair[0] + ' = ' + keyValuePair[1] );
if ( key == "conf" ) {
old_conf = requested_conf;
requested_conf = value;
if ( old_conf != requested_conf) {
// Somehow reload new configuration
debug('SWITCHING CONFIG')
switch_config( requested_conf)
}
}
if ( key == "Q" || key == "q" ) {
if ( project['type'] == 'text') searched_word = value
else do_search(value);
}
else if ( key == "BWQ" || key == "bwq" ) {
if ( project['type'] == 'text') searched_bw_word = value
else do_bw_search(value);
}
else if ( key == "SEARCH" || key == "search" ) { searchandgo(); }
else {
if ( books.hasOwnProperty(key)) {
books[key]["should_hide"] = 0
if (value.match( /^h/ )) {
books[key]["should_hide"] = 1
value = value.replace(/^h/, '')
}
hide_book( key, books[key]["should_hide"]);
books[key]["wanted"] = parseInt(value)
// all this moving, is it necessary?
book_index = $('#'+key).index()
//debug("index: " + book_index + ", arrayindex = " + i)
// Only move books around if order has changed:
// i - 1 because we now have mandatory extra value
// in the hash: 'conf'
if ( book_index != i - 1) move(key, "top");
//move_to_top(key+"_setting");
}
}
}
}
else {
alert ('Nothing found');
// No variables in the hash
}
if ( project['type'] == 'text') {
load_book_texts();
} else {
display_images();
}
set_title();
}
function load_book_texts() {
for (var book in books) {
suggestions = make_suggestions( searched_word, books[book]["index"]);
$( '#'+book+'_suggestions').html("")
// Only load the book text if it's not hidden
if ( books[book]['should_hide'] != 1) {
var status_string = "";
if ( books[book]["wanted"] == -1) {
status_string = searched_word+ ": Not found unfortunately."
$("#"+book+"_text").html( '')
if ( suggestions.length > 0) {
status_string += " Loaded 1st suggestion '" + suggestions[0] + "' instead."
books[book]['current'] = books[book]["index"].indexOf( suggestions[0])
var url = get_text_url( book, suggestions[0])
load_jsonp( url)
} else
status_string += " No suggestions found either doubly unfortunately."
} else if ( books[book]["wanted"] != books[book]["current"]) {
var root = books[book]["index"][ books[book]["wanted"]]
books[book]["current"] = books[book]["wanted"]
var status_string =
" <b>" + root + "</b> | " +
books[book]["name"] + ", entry no. " + books[book]["current"] +
" <small>(of " + books[book]["index"].length + ") " +
"</small>"
//debug( 'offset = ' + books[book]['offset'] + ", wanted = " + books[book]["wanted"] + ", current = " + books[book]["current"]);
var url = get_text_url( book, root)
load_jsonp( url)
}
$("#"+book+"_status_line").html( status_string);
}
var selected_sug = -1
for (var i = 0; i < suggestions.length; i++) {
var index = books[book]["index"].indexOf( suggestions[i])
var t = {
'book': book,
'root': suggestions[i],
'sug_index': i,
'index': index
}
if ( books[book]["current"] == index) selected_sug = i
$( "#suggestion-template" ).tmpl( t).appendTo( '#'+book+'_suggestions');
}
if ( selected_sug != -1) {
//debug( "#sug_"+book+'_'+selected_sug)
//debug( $("#sug_"+book+'_'+selected_sug).css('border'))
$("#sug_"+book+'_'+selected_sug).css('border', '3px solid ' + books[book]['color'])
}
}
}
function shift_page( book, offset) {
hide_id('about');
debug( 'offset = ' + offset +
", wanted = " + books[book]["wanted"] +
", current = " + books[book]["current"]);
books[book]["wanted"] = books[book]["current"] + offset;
$(window).scrollTop( $("#"+book).offset().top);
searched_word = "";
build_hash();
}
function percentVisible( elem)
{
// This returns how many % of the screen contains element 'elem'
if ( $(elem).css('display') == "none" ) return 0;
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();
//debug( $(elem).height());
//debug( 'docViewTop = ' + docViewTop + ', docViewBottom = ' + docViewBottom)
//debug( 'elem id = ' + $(elem).attr('id') + ', elemTop = ' + elemTop + ', elemBottom = ' + elemBottom)
var perc_vis = 0;
// The only assumption here is that the element spans more than 1 screen height
if ( elemTop <= docViewTop && elemBottom >= docViewBottom) perc_vis = 100;
else if ( elemBottom < docViewTop || elemTop > docViewBottom) perc_vis = 0;
else if ( elemTop >= docViewTop ) perc_vis = (docViewBottom-elemTop) * 100 / $(window).height();
else if ( elemBottom <= docViewBottom ) perc_vis = ( elemBottom-docViewTop) * 100 / $(window).height();
//debug( '=> % = ' + perc_vis + '?');
return perc_vis;
}
function visible_book_shift( offset) {
for (var key in books)
if ( percentVisible("#"+key) > 50) { shift_page( key, offset); break }
}
function get_text_url( book, root) {
var fn = text_base_dir + book + '/'
+ root.substring( 0, 1) + '/' + root + '.txt';
//debug("filename = "+fn)
return fn
}
function get_img_url( book) {
//debug( "get_img_url( " + book +")")
var page = books[book]["wanted"]
if (page < 1) books[book]["wanted"] = page = 1
if (page > books[book]["index"].length)
books[book]["wanted"] = page = books[book]["index"].length - 1
var str = "" + page
var pad = "0000"
prefixed_page = pad.substring(0, pad.length - str.length) + str
return img_base_dir + books[book]["image-prefix"] + "/" + Math.floor(page/100) + "/" +
books[book]["image-prefix"] + "-" + prefixed_page + ".png"
}
function display_images() {
//ll_display_page( page);
//debug ( ll_get_img_url( page));
//document.getElementById("ll-narrow").src = ll_get_img_url( cur_ll_vol, cur_ll_page);
// TODO: jQuery-fy the stuff below
for (var key in books)
if ( ! books[key]["should_hide"]) {
// Clear image if it's being changed so it's clearer to user that a new imagine
// is being downloaded
//Fine in theory but we want to move to: "if current != wanted logic"
//if ( $("#"+key+"_col1").attr('src') != img_url) {
if ( books[key]['wanted'] != books[key]["current"]) {
var img_url = get_img_url(key)
books[key]["current"] = books[key]['wanted']
var status_string =
" <b>" + books[key]["index"][books[key]["current"]] + "</b> | " +
books[key]["name"] + ", page " + (books[key]["current"] - books[key]["offset"] + 1) +
" <small>(of " + (books[key]["index"].length-1-books[key]["offset"]) + ") " +
"</small>"
var debug_txt = books[key]['name'] + ': Loading new image url: ' + img_url
user_debug( debug_txt)
/*
$("#"+key+"_col1").attr('src', '');
$("#"+key+"_col2").attr('src', '');
$("#"+key+"_col3").attr('src', '');
$("#"+key+"_wideviewimg").attr('src', '');
*/
$("#"+key+"_col1").attr('src', img_url);
$("#"+key+"_col2").attr('src', img_url);
$("#"+key+"_col3").attr('src', img_url);
$("#"+key+"_wideviewimg").attr('src', img_url);
$("#"+key+"_status_line").html( status_string);
}
}
}
function user_debug( text) {
var d = new Date(); // for now
var str = d.getHours()+':'+d.getMinutes()+':'+d.getSeconds()
+ ' - ' + text
debug( "user_debug: " + str )
if ( state['enable_debug'] == 1) {
$('#user_debug').val(function(index, old) { return str + "\n" + old; });
// Limit it to 100 lines:
var lines = $('#user_debug').val().split("\n")
var new_lines = lines.slice(0,100).join("\n")
}
}
function debug( text) {
var obj = text
var time = new Date().getTime();
var date = new Date(time);
var msecs = time % 1000;
var time_info = date.toString().replace(/(..:..) /,"$1"+"."+msecs+" ")
var oCallStackTrack = new Error();
// console.log(oCallStackTrack.stack.replace('Error', 'Call Stack:'),
var str = time_info + " - [" + text + "] " + '\n' +
oCallStackTrack.stack.replace('Error', 'Call Stack:')
if (debugmode) {
document.getElementById("debug").innerHTML += "<br>" + str
}
// Thank you IE for not creating the console element until debug tools
// are opened!
if (window.console) console.log(str)
if (typeof obj != "string") console.log( obj)
}
// http://constc.blogspot.com/2008/07/undeclared-undefined-null-in-javascript.html
function isUndefined(x) { return x == null && x !== null; }
function first_page_load() {
switch_config( requested_conf)
/*
Default cookie setting:
- do enable swiping for mobile devices
- make swipe less sensitive so pages won't skip when scrolling down
*/
var cookie = getCookie( project["prefix"]+"state");
if ( cookie == '' || cookie === null)
state = {
'fitwidth': 0,
'enable_swipe': 1,
'less_sensitive_swipe': 1,
'retain_search': 1,
'enable_debug': 0,
'enable_columns': 0,
'enable_fitwidth': 0
}
else state = JSON.parse( cookie)
if ( $(document.body).width() < 750) state['enable_columns'] = 1
else state['enable_columns'] = 0
for (var s in state) update_setting( s);
enforce_settings()
// Set default hash value, and show About if this appears to be the first visit
if ( window.location.hash.replace(/^#/,'') == "") {
var mr_last_hash = getCookie( project["prefix"]+"last_hash");
debug( mr_last_hash);
if ( isUndefined(mr_last_hash) || mr_last_hash == "" || mr_last_hash == null) {
debug('hash = empty, first visit?')
window.location.hash = starting_hash;
// Then set the books to default order
set_order_preset("default");
//toggle_about();
//parse_hash();
} else {
window.location.hash = mr_last_hash;
}
} else parse_hash();
/*
// Not working for some reason...
$('.wideview').load(function() {
var book = $(event.target).closest("div.book").attr("id");
var debug_txt =
books[book]['name'] + ": image " + $(this).attr('src') + " loaded."
user_debug( debug_txt)
})
$('.wideview').error(function() {
var book = $(event.target).closest("div.book").attr("id");
var debug_txt =
books[book]['name'] + ': error loading: ' + $(this).attr('src')
user_debug( debug_txt)
});
*/
// Set favicon