This repository has been archived by the owner on Aug 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
berlinium.js
executable file
·1618 lines (1389 loc) · 62.5 KB
/
berlinium.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
/**
*
* Berlinium Tilde GUI
* Author: Evgeny Blokhin
*
*/
//"use strict";
var _gui = {};
_gui.version = '0.9.0';
_gui.title = '';
_gui.debug_regime = false;
_gui.rendered = [];
_gui.tab_buffer = [];
_gui.req_stack = [];
_gui.search_hash = null; // FIXME issue #3 remove as redundant
_gui.search_req = false; // FIXME: request history dispatcher
_gui.conditions = false;
_gui.socket = null;
_gui.sortdisable = false;
_gui.cwidth = 0;
_gui.connattempts = 0;
_gui.max_connattempt = 2;
_gui.searchables = []; // all categs
_gui.impliables = []; // non-faceted, but selected categs
_gui.plots = [];
_gui.player_url = 'player.html';
_gui.mendeleev = {};
_gui.mendeleev_table = ['X', 'H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne', 'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'Cl', 'Ar', 'K', 'Ca', 'Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', 'Zn', 'Ga', 'Ge', 'As', 'Se', 'Br', 'Kr', 'Rb', 'Sr', 'Y', 'Zr', 'Nb', 'Mo', 'Tc', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'In', 'Sn', 'Sb', 'Te', 'I', 'Xe', 'Cs', 'Ba', 'La', 'Ce', 'Pr', 'Nd', 'Pm', 'Sm', 'Eu', 'Gd', 'Tb', 'Dy', 'Ho', 'Er', 'Tm', 'Yb', 'Lu', 'Hf', 'Ta', 'W', 'Re', 'Os', 'Ir', 'Pt', 'Au', 'Hg', 'Tl', 'Pb', 'Bi', 'Po', 'At', 'Rn', 'Fr', 'Ra', 'Ac', 'Th', 'Pa', 'U', 'Np', 'Pu', 'Am', 'Cm', 'Bk', 'Cf', 'Es', 'Fm', 'Md', 'No', 'Lr'];
_gui.last_chkbox = null;
_gui.units = {
'energy': {'au':0.03674932601, 'eV':1, 'Ry':0.07349861206},
'phonons': {'cm<sup>-1</sup>':1, 'THz':0.029979}
};
_gui.unit_capts = {'energy':'Energy', 'phonons':'Phonon frequencies'};
_gui.default_settings = {};
_gui.default_settings.units = {'energy':'eV', 'phonons':'cm<sup>-1</sup>'};
_gui.default_settings.cols = [1, 1501, 7, 50, 22, 23, 27, 1701, 1702, 1703]; // cid's of hierarchy API
_gui.default_settings.colnum = 100;
//_gui.default_settings.objects_expand = true;
_gui.permaurl = window.location.protocol + '//' + window.location.host + window.location.pathname;
_gui.ws_server = null;
_gui.file_relay_server = 'https://tilde.pro/fileadmin/papers'; // 'http://localhost:9991';
window.playerdata = {}; // player.html iframe integration
// Polyfills
if (!Array.prototype.indexOf){
Array.prototype.indexOf = function(obj, start){
for (var i = (start || 0), j = this.length; i < j; i++){
if (this[i] === obj) { return i; }
}
return -1;
}
}
if (!console) console = {log: function(){}};
String.prototype.startswith = function(prefix){
return this.indexOf(prefix) === 0;
}
String.prototype.endswith = function(searchString, position){
var subjectString = this.toString();
if (position === undefined || position > subjectString.length) position = subjectString.length;
position -= searchString.length;
var lastIndex = subjectString.indexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
}
// SockJS
_gui.conn = function(){
_gui.socket = new SockJS(_gui.ws_server, null, ['websocket', 'xhr-polling']);
_gui.socket.onopen = function(){
console.log('CONNECTED.');
$('#notifybox').hide();
$('#abortbox').hide();
_gui.settings = $.jStorage.get(_gui.ws_server, _gui.default_settings); // initialize client-side settings
__send('login', {settings: _gui.settings} );
}
_gui.socket.onmessage = function(payload){
var response = JSON.parse(payload.data);
if (_gui.debug_regime) console.log('RECEIVED: '+response.act);
var n = _gui.req_stack.indexOf(response.act);
if (n == -1) return console.log('RECEIVED BUT UNKNOWN: '+response.act);
else _gui.req_stack.splice(n, 1);
if (!_gui.req_stack.length) $('#loadbox').hide();
if (response.error && response.error.length>1) return notify('Error while '+response.act+':<br />'+response.error);
if (window['resp__' + response.act]) window['resp__' + response.act](response.req, response.result);
else notify('Unhandled action received: ' + response.act);
}
_gui.socket.onclose = function(){
_gui.connattempts += 1;
if (_gui.connattempts > _gui.max_connattempt){
$('#loadbox').hide();
$('#abortbox').hide();
$('#connectws_holder').show();
return notify('Connection to server '+_gui.ws_server+' cannot be established.');
}
console.log('CONNECTION WITH SERVER HAS FAILED!');
setTimeout(function(){ _gui.conn() }, _gui.connattempts*1500 + 1000);
}
}
function __send(act, req){
if (_gui.debug_regime) console.log('REQUESTED: '+act); // invalid for login act
_gui.req_stack.push(act);
$('#loadbox').show();
if (act == 'browse') _gui.search_req = req; // FIXME: request history dispatcher
try{
_gui.socket.send( JSON.stringify({'act': act, 'req': req}) );
} catch(ex){
console.log('AN ERROR WHILE SENDING DATA HAS OCCURED: '+ex);
}
}
// ERRORS BOX
function notify(message) {
$('#errormsg').empty();
setTimeout(function(){ $('#errormsg').empty().append(message).parent().show(); }, 250);
}
function open_ipane(cmd, target){
if (!!target) var current = $('#o_'+target+' ul.ipane_ctrl li[rel='+cmd+']');
else var current = $('ul.ipane_ctrl li[rel='+cmd+']');
if (!current.length) return notify('Error opening pane '+cmd+'!');
current.parent().children('li').css('border-bottom-color', '#06c');
current.css('border-bottom-color', '#fff').parent().parent().children( 'div.ipane' ).hide();
current.parent().parent().find( 'div[rel='+cmd+']' ).show();
if (_gui.tab_buffer.indexOf(target + '_' + cmd) != -1) return;
switch(cmd){
case 'ph_dos':
case 'e_dos':
case 'ph_bands':
case 'e_bands':
case 'optstory':
case 'estory':
__send(cmd, {datahash: target} );
break;
case 'vib':
__send('phonons', {datahash: target} );
break;
}
_gui.tab_buffer.push(target + '_' + cmd);
}
/*function redraw_vib_links( text2link, target ){
$('#o_'+target+' td.ph_ctrl').each(function(){
var $this = $(this);
var linktxt = $this.text();
if (!!text2link) $this.empty().append( '<span class=link>'+linktxt+'</span>' );
else $this.empty().append( linktxt );
});
if (!!text2link){
// attach vibration handler
$('#o_'+target+' td.ph_ctrl span').click(function(){
$('#o_'+target+' td.ph_ctrl span').removeClass('red');
$(this).addClass('red');
var phonons = '[' + $(this).parent().attr('rev') + ']';
document.getElementById('f_'+target).contentWindow.vibrate_3D( phonons );
});
}
}*/
function render_wintabs(hashes){
$.each(hashes, function(n, item){
if (_gui.rendered.indexOf(item) != -1) return true;
//console.log('Processing ' + item + ', exists: ' + $('#i_' + item).length);
if (item.substr(item.length - 2) == 'CI'){
// dtype = ab initio calculation
__send('summary', {datahash: item});
} else if (item.substr(item.length - 3) == 'PDF'){
// dtype = journal article
var obf = $('<tr class=obj_holder></tr>').append( $('<th colspan=20></th>').append( $('#pdf_viewer_factory').clone().removeAttr('id').attr('id', 'o_' + item) ) );
$('#i_' + item).after(obf);
$('#o_' + item + ' > div > iframe').attr('src', _gui.file_relay_server + '/' + $('#i_' + item).data('filename'));
_gui.rendered.push(item);
}
});
}
function destroy_wintab(tab_id){
if (_gui.rendered.indexOf(tab_id) == -1) return;
delete _gui.rendered[tab_id];
delete window.playerdata[tab_id];
_gui.tab_buffer = $.grep(_gui.tab_buffer, function(val, index){
if (val.indexOf(tab_id) == -1) return true;
});
$('#o_' + tab_id).parent().parent().remove();
}
function e_plotter(req, plot, divclass, ordinate){
var show_points = (divclass.indexOf('estory') !== -1) ? false : true;
var options = {
legend: {show: false},
series: {lines: {show: true}, points: {show: show_points}, shadowSize: 3},
xaxis: {labelHeight: 40, minTickSize: 1, tickDecimals: 0},
yaxis: {color: '#eeeeee', labelWidth: 50},
grid: {borderWidth: 1, borderColor: '#000', hoverable: true, clickable: true}
};
if (plot[0].data.length == 1) options.xaxis.ticks = []; // awkward optimization cases
var target = $('#o_'+req.datahash+' div.'+divclass);
var cpanel = target.prev('div');
cpanel.parent().removeClass('loading');
$.plot(target, plot, options);
/*$(target).bind("plotclick", function(event, pos, item){
if (item) document.getElementById('f_'+req.datahash).contentWindow.location.replace( '#' + _gui.settings.dbs[0] + '/' + req.datahash + '/' + item.dataIndex );
});*/
target.append('<div style="position:absolute;z-index:4;width:200px;left:40%;bottom:0;text-align:center;font-size:1.5em;background:#fff;">Step</div> ');
target.append('<div style="position:absolute;z-index:4;width:200px;left:0;top:300px;text-align:center;font-size:1.25em;transform:rotate(-90deg);transform-origin:left top;-webkit-transform:rotate(-90deg);-webkit-transform-origin:left top;-moz-transform:rotate(-90deg);-moz-transform-origin:left top;background:#fff;">'+ordinate+'</div>');
}
function dos_plotter(req, plot, divclass, axes){
var options = {
legend: {show: false},
series: {lines: {show: true}, points: {show: false}, shadowSize: 0},
xaxis: {color: '#eeeeee', labelHeight: 40},
yaxis: {ticks: [], labelWidth: 30},
grid: {borderWidth: 1, borderColor: '#000'}
};
var cpanel = $('#o_'+req.datahash+' div.'+divclass).prev('div');
cpanel.parent().removeClass('loading');
for (var i=0; i < plot.length; i++){
cpanel.prepend('<input type="checkbox" name="' + plot[i].label + '" checked=checked id="cb_' + req.datahash + '_' + plot[i].label + '" rev="' + JSON.stringify(plot[i].data) + '" rel="'+plot[i].color+'" /> <label for="cb_'+ req.datahash + '_' + plot[i].label +'" style="color:' + plot[i].color + '">' + plot[i].label + '</label> ');
}
function plot_user_choice(){
var data_to_plot = [];
cpanel.find("input:checked").each(function(){
var d = $(this).attr('rev');
data_to_plot.push({color: $(this).attr('rel'), data: JSON.parse( $(this).attr('rev') )});
});
var target = $('#o_'+req.datahash+' div.'+divclass);
$.plot(target, data_to_plot, options);
target.append('<div style="position:absolute;z-index:14;width:200px;left:40%;bottom:0;text-align:center;font-size:1.5em;background:#fff;">'+axes.x+'</div> ');
target.append('<div style="position:absolute;z-index:14;width:200px;left:0;top:300px;text-align:center;font-size:1.5em;transform:rotate(-90deg);transform-origin:left top;-webkit-transform:rotate(-90deg);-webkit-transform-origin:left top;-moz-transform:rotate(-90deg);-moz-transform-origin:left top;background:#fff;">'+axes.y+'</div>');
}
cpanel.find("input").click(plot_user_choice);
plot_user_choice();
cpanel.children('div.export_plot').click(function(){ export_data(plot) });
}
function bands_plotter(req, plot, divclass, ordinate){
var options = {
legend: {show: false},
series: {lines: {show: true}, points: {show: false}, shadowSize: 0},
xaxis: {color: '#eeeeee', labelHeight: 40, font:{size: 9.5, color: '#000'}, labelAngle: 270},
yaxis: {color: '#eeeeee', labelWidth: 50},
grid: {borderWidth: 1, borderColor: '#000'}
};
var target = $('#o_'+req.datahash+' div.'+divclass);
var cpanel = target.prev('div');
cpanel.parent().removeClass('loading');
options.xaxis.ticks = plot[0].ticks
//options.xaxis.ticks[options.xaxis.ticks.length-1][1] = '' // avoid cropping in canvas
$.plot(target, plot, options);
target.append('<div style="position:absolute;z-index:14;width:200px;left:0;top:300px;text-align:center;font-size:1.25em;transform:rotate(-90deg);transform-origin:left top;-webkit-transform:rotate(-90deg);-webkit-transform-origin:left top;-moz-transform:rotate(-90deg);-moz-transform-origin:left top;background:#fff;">'+ordinate+'</div>');
target.prev('div').children('div.export_plot').click(function(){ export_data(plot) });
}
function export_data(data){
var ref = window.open('', 'export' + Math.floor(Math.random() * 100));
var dump = '';
for (var j=0; j < data[0].data.length; j++){
dump += data[0].data[j][0] + '\t';
for (var i=0; i < data.length; i++){
dump += data[i].data[j][1] + '\t';
}
dump += '\n';
}
ref.document.body.innerHTML = '<pre>' + dump + '</pre>';
}
function add_tag_expanders(){
if (!$('#splashscreen_holder').is(':visible')) return;
$('a.tagmore, a.tagless').remove();
$('div.tagarea').each(function(){
if ($(this).find('a.tag').length > 20){
$(this).prepend('<a class=tagmore href=#>→</a>');
$(this).addClass('tagarea_reduced');
} else {
$(this).removeClass('tagarea_reduced');
}
});
}
function switch_menus(which){
$('div.menu_cmds').hide();
if (!which) $('#menu_main_cmds').show();
else if (which == 1) $('#menu_row_cmds').show();
else if (which == 2) $('#menu_col_cmds').show();
}
function defaultize_tags(){
$('a.taglink').removeClass('activetag').addClass('visibletag');
$('a.mdtag').addClass('visibletag');
//$('div.tagrow').show();
//$('#initbox').hide();
_gui.impliables = [];
}
function defaultize_sliders(){
$('div.gui_slider').each(function(){
var min = parseFloat($(this).attr('min')), max = parseFloat($(this).attr('max'));
$(this).noUiSlider({ start: [min, max] }, true);
});
}
function direct_search(){
if (!$('#search_field').val().length) return notify('Please, choose the topic(s)');
var term = $('#search_field').val().toLowerCase();
//if (term.endswith(', ')) // FIXME
for (i=0; i<_gui.searchables.length; i++){
if (_gui.searchables[i][1].toLowerCase() == term) return __send('tags', {tids: [_gui.searchables[i][0]]});
}
notify('Nothing found.');
}
function clear_tags(){
$('#search_field').val('');
defaultize_tags();
add_tag_expanders();
}
function gather_tags(myself){
var found_tags = [];
if (myself){
if (myself.hasClass('activetag')){
myself.removeClass('activetag');
} else {
found_tags.push( myself.attr('rel') );
}
}
$('#splashscreen').find('a.activetag').each(function(){
found_tags.push( $(this).attr('rel') );
});
if (_gui.impliables.length) found_tags.push.apply(found_tags, _gui.impliables); // .extend
return found_tags;
}
function gather_continuous(){
var conditions = [];
$('div.gui_slider').each(function(){
var min = parseFloat($(this).attr('min')), max = parseFloat($(this).attr('max'));
var v = $(this).val();
if (parseFloat(v[0]) !== min || parseFloat(v[1]) !== max) conditions.push({cid: $(this).parent().parent().parent().attr('rel'), min: v[0], max: v[1]});
});
return (conditions.length) ? conditions : false;
}
function remdublicates(arr){
var i, len=arr.length, out=[], obj={};
for (i=0;i<len;i++){
obj[arr[i]]=0;
}
for (i in obj){
out.push(i);
}
return out;
}
function gather_plots_data(){
var data = [], ids = [];
for (var j=0; j < _gui.plots.length; j++){
data.push([]);
$('#databrowser td[rel='+_gui.plots[j]+']').each(function(index){
var t = $(this).text();
if (t.indexOf('x') != -1){
// special case
var s = t.split('x'), t = 1;
for (var i=0; i<s.length; i++){ t *= parseInt(s[i]) }
} else if (t.indexOf(',') != -1) {
// special CRYSTAL case
if (t.indexOf('biel') == -1){
var s = t.split(',');
for (var i=0; i<s.length; i++){ s[i] = parseFloat(s[i]) }
t = Math.max.apply(null, s);
}
}else {
// non-numerics
t = t.replace(/[^0-9\.\-]+/g, '');
if (!t.length) t=0;
}
data[data.length-1].push(t);
if (j==0) ids.push($(this).parent().attr('id').substr(2)); // i_
});
}
data.push(ids);
// additional checkups if the data we collected makes sense (note length-1)
for (var j=0; j < data.length-1; j++){
var c = remdublicates(data[j]);
if (c.length == 1){
notify('All values in a column are equal!');
return false;
}
}
return data;
}
function clean_plots(){
if (!_gui.plots.length) return;
$.each(_gui.plots, function(n, i){
$('#databrowser td[rel='+i+'], #databrowser th[rel='+i+']').removeClass('selected');
$('#databrowser th[rel='+i+']').children('input').prop('checked', false);
});
_gui.plots = [];
}
function align_page(){
(_gui.cwidth < 1280) ? $('div.supercat').css('width', '98%') : $('div.supercat').css('width', '49%');
} // test width!
/**
*
*
* *********************************************************************************************************************
*
*/
/* JavaScript autoComplete v1.0.3 (MIT) by Simon Steinberger / Pixabay
https://github.com/Pixabay/JavaScript-autoComplete */
var autoComplete = (function(){
// "use strict";
function autoComplete(options){
if (!document.querySelector) return;
// helpers
function hasClass(el, className){ return el.classList ? el.classList.contains(className) : new RegExp('\\b'+ className+'\\b').test(el.className); }
function addEvent(el, type, handler){
if (el.attachEvent) el.attachEvent('on'+type, handler); else el.addEventListener(type, handler);
}
function removeEvent(el, type, handler){
// if (el.removeEventListener) not working in IE11
if (el.detachEvent) el.detachEvent('on'+type, handler); else el.removeEventListener(type, handler);
}
function live(elClass, event, cb, context){
addEvent(context || document, event, function(e){
var found, el = e.target || e.srcElement;
while (el && !(found = hasClass(el, elClass))) el = el.parentElement;
if (found) cb.call(el, e);
});
}
var o = { // private options, set up in init
selector: 0,
source: 0,
minChars: 3,
delay: 150,
cache: 1,
menuClass: '',
renderItem: function (item, search){
// escape special characters
search = search.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
var re = new RegExp("(" + search.split(' ').join('|') + ")", "gi");
return '<div class="autocomplete-suggestion" data-val="' + item + '">' + item.replace(re, "<b>$1</b>") + '</div>';
},
onSelect: function(e, term, item){}
};
for (var k in options) { if (options.hasOwnProperty(k)) o[k] = options[k]; }
// init
var elems = typeof o.selector == 'object' ? [o.selector] : document.querySelectorAll(o.selector);
for (var i=0; i<elems.length; i++) {
var that = elems[i];
// create suggestions container "sc"
that.sc = document.createElement('div');
that.sc.className = 'autocomplete-suggestions '+o.menuClass;
that.autocompleteAttr = that.getAttribute('autocomplete');
that.setAttribute('autocomplete', 'off');
that.cache = {};
that.last_val = '';
that.updateSC = function(resize, next){
var rect = that.getBoundingClientRect();
that.sc.style.left = rect.left + (window.pageXOffset || document.documentElement.scrollLeft) + 'px';
that.sc.style.top = rect.bottom + (window.pageYOffset || document.documentElement.scrollTop) + 1 + 'px';
that.sc.style.width = rect.right - rect.left + 'px'; // outerWidth
if (!resize) {
that.sc.style.display = 'block';
if (!that.sc.maxHeight) { that.sc.maxHeight = parseInt((window.getComputedStyle ? getComputedStyle(that.sc, null) : that.sc.currentStyle).maxHeight); }
if (!that.sc.suggestionHeight) that.sc.suggestionHeight = that.sc.querySelector('.autocomplete-suggestion').offsetHeight;
if (that.sc.suggestionHeight)
if (!next) that.sc.scrollTop = 0;
else {
var scrTop = that.sc.scrollTop, selTop = next.getBoundingClientRect().top - that.sc.getBoundingClientRect().top;
if (selTop + that.sc.suggestionHeight - that.sc.maxHeight > 0)
that.sc.scrollTop = selTop + that.sc.suggestionHeight + scrTop - that.sc.maxHeight;
else if (selTop < 0)
that.sc.scrollTop = selTop + scrTop;
}
}
}
addEvent(window, 'resize', that.updateSC);
document.body.appendChild(that.sc);
live('autocomplete-suggestion', 'mouseleave', function(e){
var sel = that.sc.querySelector('.autocomplete-suggestion.selected');
if (sel) setTimeout(function(){ sel.className = sel.className.replace('selected', ''); }, 20);
}, that.sc);
live('autocomplete-suggestion', 'mouseover', function(e){
var sel = that.sc.querySelector('.autocomplete-suggestion.selected');
if (sel) sel.className = sel.className.replace('selected', '');
this.className += ' selected';
}, that.sc);
live('autocomplete-suggestion', 'mousedown', function(e){
if (hasClass(this, 'autocomplete-suggestion')) { // else outside click
var v = this.getAttribute('data-val');
that.value = v;
o.onSelect(e, v, this);
that.sc.style.display = 'none';
}
}, that.sc);
that.blurHandler = function(){
try { var over_sb = document.querySelector('.autocomplete-suggestions:hover'); } catch(e){ var over_sb = 0; }
if (!over_sb) {
that.last_val = that.value;
that.sc.style.display = 'none';
setTimeout(function(){ that.sc.style.display = 'none'; }, 350); // hide suggestions on fast input
} else if (that !== document.activeElement) setTimeout(function(){ that.focus(); }, 20);
};
addEvent(that, 'blur', that.blurHandler);
var suggest = function(data){
var val = that.value;
that.cache[val] = data;
if (data.length && val.length >= o.minChars) {
var s = '';
for (var i=0;i<data.length;i++) s += o.renderItem(data[i], val);
that.sc.innerHTML = s;
that.updateSC(0);
}
else
that.sc.style.display = 'none';
}
that.keydownHandler = function(e){
var key = window.event ? e.keyCode : e.which;
// down (40), up (38)
if ((key == 40 || key == 38) && that.sc.innerHTML) {
var next, sel = that.sc.querySelector('.autocomplete-suggestion.selected');
if (!sel) {
next = (key == 40) ? that.sc.querySelector('.autocomplete-suggestion') : that.sc.childNodes[that.sc.childNodes.length - 1]; // first : last
next.className += ' selected';
that.value = next.getAttribute('data-val');
} else {
next = (key == 40) ? sel.nextSibling : sel.previousSibling;
if (next) {
sel.className = sel.className.replace('selected', '');
next.className += ' selected';
that.value = next.getAttribute('data-val');
}
else { sel.className = sel.className.replace('selected', ''); that.value = that.last_val; next = 0; }
}
that.updateSC(0, next);
return false;
}
// esc
else if (key == 27) { that.value = that.last_val; that.sc.style.display = 'none'; }
// enter
else if (key == 13 || key == 9) {
var sel = that.sc.querySelector('.autocomplete-suggestion.selected');
if (sel && that.sc.style.display != 'none') { o.onSelect(e, sel.getAttribute('data-val'), sel); setTimeout(function(){ that.sc.style.display = 'none'; }, 20); }
else { // direct search : FIXME
$('#init_trigger').trigger('click'); // FIXME
}
}
// deletion : FIXME
else if (key == 8 || key == 46){
window.clear_tags();
}
};
addEvent(that, 'keydown', that.keydownHandler);
that.keyupHandler = function(e){
var key = window.event ? e.keyCode : e.which;
if (!key || (key < 35 || key > 40) && key != 13 && key != 27) {
var val = that.value;
if (val.length >= o.minChars) {
if (val != that.last_val) {
that.last_val = val;
clearTimeout(that.timer);
if (o.cache) {
if (val in that.cache) { suggest(that.cache[val]); return; }
// no requests if previous suggestions were empty
for (var i=1; i<val.length-o.minChars; i++) {
var part = val.slice(0, val.length-i);
if (part in that.cache && !that.cache[part].length) { suggest([]); return; }
}
}
that.timer = setTimeout(function(){ o.source(val, suggest) }, o.delay);
}
} else {
that.last_val = val;
that.sc.style.display = 'none';
}
}
};
addEvent(that, 'keyup', that.keyupHandler);
that.focusHandler = function(e){
that.last_val = '\n';
that.keyupHandler(e)
};
if (!o.minChars) addEvent(that, 'focus', that.focusHandler);
}
// public destroy method
this.destroy = function(){
for (var i=0; i<elems.length; i++) {
var that = elems[i];
removeEvent(window, 'resize', that.updateSC);
removeEvent(that, 'blur', that.blurHandler);
removeEvent(that, 'focus', that.focusHandler);
removeEvent(that, 'keydown', that.keydownHandler);
removeEvent(that, 'keyup', that.keyupHandler);
if (that.autocompleteAttr)
that.setAttribute('autocomplete', that.autocompleteAttr);
else
that.removeAttribute('autocomplete');
document.body.removeChild(that.sc);
that = null;
}
};
}
return autoComplete;
})();
(function(){ window.autoComplete = autoComplete })();
/**
*
*
* *********************************************************************************************************************
*
*/
function url_redraw_react(){
var anchors = window.location.hash.substr(1).split('/');
if (!anchors.length) return;
_gui.tab_buffer = [];
clean_plots();
if (window['url__' + anchors[0]]) window['url__' + anchors[0]](anchors.slice(1));
else notify('Unknown address: ' + window.location.hash);
}
function url__start(){
// MAIN TAGS SCREEN
$('#grid_holder').hide();
$('div.downscreen').hide();
$('#menu_main_cmds').hide();
$('div.data_ctrl').hide();
$('#databrowser').empty();
$('#splashscreen_holder').show();
$('#initbox').show();
add_tag_expanders();
_gui.rendered = [];
document.title = _gui.title;
}
function url__browse(arg){
$('#splashscreen_holder').hide();
$('#grid_holder').show();
switch_menus();
//$('#closeobj_trigger').hide();
//$('#readme').hide();
_gui.sortdisable = false;
_gui.rendered = [];
window.playerdata = {};
var tags = arg[0].split('+'), start = 0;
var pgnum = parseInt(arg[1]) || 1;
if (pgnum > 1) start = pgnum - 1;
var sortby = parseInt($('select.default_order_ctrl').first().val());
if (sortby === -1) sortby = 0;
__send('browse', {tids: tags, conditions: _gui.conditions, start: start, sortby: sortby});
_gui.search_hash = '#browse/' + arg.join('/');
}
function url__entries(arg){
$('#splashscreen_holder').hide();
$('#grid_holder').show();
switch_menus();
//$('#closeobj_trigger').hide();
//$('#readme').hide();
_gui.sortdisable = false;
_gui.rendered = [];
window.playerdata = {};
var hashes = arg[0].split('+');
__send('browse', {hashes: hashes});
_gui.search_hash = '#entries/' + arg.join('/');
}
function url__show(arg){
$('#splashscreen_holder').hide();
$('#grid_holder').show();
switch_menus();
//$('#closeobj_trigger').hide();
//$('#readme').hide();
_gui.sortdisable = true;
var hashes = arg[0].split('+');
var uniq_hashes = hashes.filter(function(item, pos){ return hashes.indexOf(item) == pos });
if (hashes.length !== uniq_hashes.length){
window.location.replace('#show/' + uniq_hashes.join('+'));
return;
}
if (hashes.length > 3){
var exceeded_hashes = hashes.splice(0, hashes.length-3);
$.each(exceeded_hashes, function(n, i){
destroy_wintab(i);
});
window.location.replace('#show/' + hashes.join('+'));
return;
}
var absent_hashes = $.grep(hashes, function(el, index){ return !$('#i_' + el).length });
if (absent_hashes.length) return __send('browse', {hashes: hashes});
render_wintabs(hashes);
}
function url__found(arg){
// FIXME: unlike others, no server actions are performed in this search handler by default
if (!_gui.conditions){
window.location.replace('#start');
return;
}
$('#splashscreen_holder').hide();
$('#grid_holder').show();
switch_menus();
_gui.sortdisable = false;
_gui.rendered = [];
window.playerdata = {};
if (_gui.search_req){
var start = 0;
var pgnum = parseInt(arg[1]) || 1;
if (pgnum > 1) start = pgnum - 1;
var sortby = parseInt($('select.default_order_ctrl').first().val());
if (sortby === -1) sortby = 0;
_gui.search_req.start = start, _gui.search_req.sortby = sortby;
__send('browse', _gui.search_req);
}
_gui.search_hash = '#found/' + arg.join('/');
}
/**
*
*
* *********************************************************************************************************************
*
*/
// RESPONSE FUNCTIONS
function resp__login(req, data){
//if (_gui.last_request){ // something was not completed in a production mode
// var action = _gui.last_request.split( _gui.wsock_delim );
// __send(action[0], action[1]);
//}
_gui.connattempts = 0;
if (data.debug_regime) _gui.debug_regime = true;
if (_gui.debug_regime) console.log("RECEIVED SETTINGS: " + JSON.stringify(data.settings));
for (var attrname in data.settings){ _gui.settings[attrname] = data.settings[attrname] }
$.jStorage.set(_gui.ws_server, _gui.settings);
//if (_gui.debug_regime) console.log("FINAL SETTINGS: " + JSON.stringify(_gui.settings));
// general switches (and settings)
_gui.title = data.title, document.title = data.title;
// display columns settings (depend on server + client state)
_gui.settings.avcols.sort(function(a, b){
if (a.sort < b.sort) return -1;
else if (a.sort > b.sort) return 1;
else return 0;
});
$.each(_gui.settings.avcols, function(num, item){
var checked_state = item.enabled ? ' checked=checked' : '';
$.each(data.cats, function(n, i){
if (i.includes.indexOf(item.cid) !== -1){
i.html_pocket += '<li><input type="checkbox" id="s_cb_'+item.cid+'"'+checked_state+'" value="'+item.cid+'" /><label for="s_cb_'+item.cid+'"> ' + item.category + '</label></li>';
}
});
});
var result_html = '';
$.each(data.cats, function(n, i){
if (i.settings_group && i.html_pocket.length) result_html += '<div class="ipane_cols_holder"><span>' + i.category.charAt(0).toUpperCase() + i.category.slice(1) + '</span><ul>' + i.html_pocket + '</ul></div>';
});
$('#settings_cols').empty().append( result_html );
$('#settings_trigger').show();
var colnum_str = '';
$.each([50, 100, 250], function(n, item){
var checked_state = '';
if (_gui.settings.colnum == item) checked_state = ' checked=checked';
colnum_str += ' <input type="radio"'+checked_state+' name="s_rdclnm" id="s_rdclnm_'+n+'" value="'+item+'" /><label for="s_rdclnm_'+n+'"> '+item+'</label>';
});
$('#ipane_maxitems_holder').empty().append(colnum_str);
//_gui.settings.objects_expand ? $('#settings_objects_expand').prop('checked', true) : $('#settings_objects_expand').prop('checked', false);
// display units settings (depend on client state only)
var units_str = '';
$.each(_gui.units, function(k, v){
//units_str += k.charAt(0).toUpperCase() + k.slice(1)+':';
units_str += _gui.unit_capts[k]+':';
$.each(v, function(kk, vv){
var checked_state = '';
if (_gui.settings.units[k] == kk) checked_state = ' checked=checked';
units_str += ' <input type="radio"'+checked_state+' name="'+k+'" id="s_rd_'+k+'_'+kk+'" value="'+kk+'" /><label for="s_rd_'+k+'_'+kk+'"> '+kk+'</label>';
});
units_str += '<br /><br /><br />';
});
$('#ipane_units_holder').empty().append( units_str );
if ($('#splashscreen').is(':empty')) __send('tags', {tids: false});
window.location.hash ? url_redraw_react() : window.location.replace('#start');
}
function resp__browse(req, data){
// reset objects
_gui.rendered = [];
_gui.tab_buffer = [];
_gui.plots = [];
_gui.last_chkbox = null;
if (data.msg) return notify(data.msg);
switch_menus();
$('#initbox').hide();
req.start = req.start || 0;
$('#databrowser').empty().append(data.html).show();
$('td._e').each(function(){
var val = parseFloat( $(this).text() );
if (val) $(this).text( ( Math.round(val * _gui.units.energy[ _gui.settings.units.energy ] * Math.pow(10, 5))/Math.pow(10, 5) ).toFixed(5) );
});
$('td._g').each(function(){
var val = parseFloat( $(this).text() );
if (val) $(this).text( Math.round(val * _gui.units.energy[ _gui.settings.units.energy ] * Math.pow(10, 4))/Math.pow(10, 4) );
});
$('span.units-energy').text(_gui.settings.units.energy);
if ($('#databrowser td').length > 1) $('#databrowser').tablesorter({sortMultiSortKey:'ctrlKey'});
// GRAPH CHECKBOXES
// FIXME: move to event declaration
$('input.sc').click(function(ev){
ev.stopImmediatePropagation();
var cat = $(this).parent().attr('rel');
$('.selected').removeClass('selected');
$('input.SHFT_cb').prop('checked', false);
if ($(this).is(':checked')){
_gui.plots.push(cat);
if (_gui.plots.length > 2){
var old = _gui.plots.shift();
$('#databrowser th[rel=' + old + ']').children('input').prop('checked', false);
}
} else {
$(this).parent().removeClass('selected');
var iold = _gui.plots.indexOf(cat);
_gui.plots.splice(iold, 1);
}
$.each(_gui.plots, function(n, i){
$('#databrowser td[rel=' + i + '], #databrowser th[rel=' + i + ']').addClass('selected');
});
if (_gui.plots.length) switch_menus(2);
else switch_menus();
});
if (data.count > _gui.settings.colnum){
var pcount = Math.ceil(data.count / _gui.settings.colnum);
var plinks = '';
var anchor_base = window.location.hash.substr(1).split('/').slice(0, 2).join('/');
if (anchor_base == 'start') anchor_base = 'found'; // FIXME
for (var i = 1; i<(pcount+1); i++){
var active_class = '';
if (i == req.start + 1) active_class = ' pglink_active';
if (i > Math.round(_gui.cwidth / 75)) break; // FIXME
plinks += '<a class="pglink' + active_class + '" href="#' + anchor_base + '/' + i + '">' + i + '</a>';
}
$('a.pglink').remove();
$('div.data_ctrl').append(plinks).show();
} else $('div.data_ctrl').hide();
var count_msg = 'Found: ' + data.count;
var high_bound = ((req.start +1 ) * _gui.settings.colnum > data.count) ? data.count : (req.start + 1) * _gui.settings.colnum;
if (data.count > _gui.settings.colnum) count_msg += ' (' + (req.start * _gui.settings.colnum + 1) + '-' + high_bound + ' shown)';
document.title = count_msg;
if (req.conditions && window.location.hash.indexOf('found') == -1)
window.location.hash = '#found/condition'; // FIXME
else if (req.hashes)
render_wintabs(req.hashes);
}
function resp__tags(req, data){
if (req.tids && req.tids.length){
// UPDATE AVAILABLE TAGS
var tag_names = [];
_gui.impliables = [];
//$('#initbox').show();
$('a.taglink').removeClass('visibletag'); // reset shown tags
$.each(data, function(n, i){
$('a._tag'+i).addClass('visibletag');
});
$.each(req.tids, function(n, i){
var $that = $('a.taglink._tag'+i);
if ($that.length) $that.addClass('visibletag activetag');
else _gui.impliables.push(i);
for (j=0; j<_gui.searchables.length; j++){
if (_gui.searchables[j][0] == i) tag_names.push(_gui.searchables[j][1]);
}
});
$('#search_field').val(tag_names.join(', ') + ', ');
} else {
// BUILD TAGS FROM SCRATCH
var tags_html = '';
_gui.mendeleev = {};
$.each(data.blocks, function(num, value){
var tags_piece = 'rel="' + value.cid + '"><div class=tagcapt>' + value.category.charAt(0).toUpperCase() + value.category.slice(1) + ':</div><div';
if (value.type == 'tag'){
tags_piece = '<div class="tagrow" ' + tags_piece + ' class="tagarea">';
/*value.content.sort(function(a, b){
if (a.topic < b.topic) return -1;
else if (a.topic > b.topic) return 1;
else return 0;
});*/
$.each(value.content, function(n, i){
tags_piece += '<a class="tag taglink visibletag _tag' + i.tid + '" rel="' + i.tid + '" href=#>' + i.topic + '</a>';