-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathMigaDV.js
1833 lines (1682 loc) · 62.4 KB
/
MigaDV.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
/**
* The main file for the Miga Data Viewer application.
*
* This file currently holds three types of functions: those that control
* the flow of the application, those that display HTML for each screen, and
* some random utility functions.
* At some point, it would be good to move the last two into a separate file.
*
* @author Yaron Koren
*
* @version 2.0
*/
// Global variables - sorry if this offends anyone. :)
var gDBRandomString = null;
//var gDataTimestamp = null;
var gAppSettings = null;
var gDataSchema = null;
var gCurCategory = null;
var gPagesInfo = null;
var gDBConn = null;
var gMapScriptLoaded = false;
var gURLHash = window.location.hash;
// Various utility functions that could probably go somewhere else.
function getURLPath() {
return window.location.host + window.location.pathname + window.location.search;
}
function HTMLEscapeString( str ) {
// Bizarrely, JS does not contain an HTML-escaping function, and
// jQuery can only do it via the DOM, so we'll just have one here.
return str.replace('<', '<').replace('>', '>').replace('"', '"').replace("'", ''');
}
function androidOnlyAlert( msg ) {
// For now, don't do anything - the Android-only alert may no
// longer be useful.
/*
var ua = navigator.userAgent.toLowerCase();
var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");
if ( isAndroid ) {
alert(msg + " (Android-only message)");
}
*/
}
/**
* Used to show the time since the last data refresh.
*/
function getTimeDifferenceString( earlierTime, laterTime ) {
millisecondDifference = laterTime - earlierTime;
secondDifference = millisecondDifference / 1000;
if ( secondDifference < 2 ) {
return "1 second";
} else if ( secondDifference < 60 ) {
return secondDifference.toFixed(0) + " seconds";
}
minuteDifference = secondDifference / 60;
if ( minuteDifference < 2 ) {
return "1 minute";
} else if ( minuteDifference < 60 ) {
return minuteDifference.toFixed(0) + " minutes";
}
hourDifference = minuteDifference / 60;
if ( hourDifference < 2 ) {
return "1 hour";
} else if ( hourDifference < 24 ) {
return hourDifference.toFixed(0) + " hours";
}
dayDifference = hourDifference / 24;
if ( dayDifference < 2 ) {
return "1 day";
}
return dayDifference.toFixed(0) + " days";
}
function categoryHasNameField( categoryName ) {
for ( fieldName in gDataSchema[categoryName]['fields'] ) {
if ( gDataSchema[categoryName]['fields'][fieldName]['fieldType'] == 'Name' ) {
return true;
}
}
return false;
}
function getCategoryStartTimeField( categoryName ) {
for ( fieldName in gDataSchema[categoryName]['fields'] ) {
if ( gDataSchema[categoryName]['fields'][fieldName]['fieldType'] == 'Start time' ) {
return fieldName;
}
}
return null;
}
function getCategoryEndTimeField( categoryName ) {
for ( fieldName in gDataSchema[categoryName]['fields'] ) {
if ( gDataSchema[categoryName]['fields'][fieldName]['fieldType'] == 'End time' ) {
return fieldName;
}
}
return null;
}
function categoryHasStartAndEndTimeFields( categoryName ) {
var startTimeField = getCategoryStartTimeField( categoryName );
var endTimeField = getCategoryEndTimeField( categoryName );
return ( startTimeField != null && endTimeField != null );
}
// This is where the core functionality starts.
function saveDataToLocalStorage() {
// Save all the settings data to LocalStorage!
var allAppInfo = {};
allAppInfo['dbRandomString'] = gDBRandomString;
allAppInfo['dataSchema'] = gDataSchema;
allAppInfo['appSettings'] = gAppSettings;
allAppInfo['pagesInfo'] = gPagesInfo;
allAppInfo['dataTimestamp'] = gDataTimestamp;
localStorage.setItem( 'Miga ' + getURLPath(), JSON.stringify( allAppInfo ) );
}
function setAllFromAppSettings() {
try {
gDBConn = new WebSQLConnector( gAppSettings['Name'] );
} catch (e) {
if ( e.code == 18 ) {
// An exception that shows up in the Android
// browser - it seems to go away if you just refresh
// a few times.
// The setTimeout()/displayMainText() call doesn't
// seem to work, unfortunately.
// @TODO - get this exception to not happen at all.
setTimeout( displayMainText('Encountered error connecting to database; reloading page...'), 2000 );
window.location.reload();
}
displayMainText('<h1>Error!</h1><h2>' + e + '</h2>');
return;
}
if ( gAppSettings.hasOwnProperty('Logo')) {
if ( gAppSettings['Logo'].indexOf('://') > 0 ) {
var logoHTML = '<img src="' + gAppSettings['Logo'] + "\" />\n";
} else {
var logoHTML = '<img src="apps/' + gAppSettings['Directory'] + "/" + gAppSettings['Logo'] + "\" />\n";
}
jQuery('#logo').html('<a href="#">' + logoHTML + '</a>');
} else {
jQuery('#logo').html("");
}
if ( gAppSettings.hasOwnProperty('Favicon') ) {
// Copied from http://stackoverflow.com/questions/260857/changing-website-favicon-dynamically/260876#260876
var link = document.createElement('link');
link.type = 'image/x-icon';
link.rel = 'icon';
if ( gAppSettings['Favicon'].indexOf('://') > 0 ) {
link.href = gAppSettings['Favicon'];
} else {
link.href = "apps/" + gAppSettings['Directory'] + "/" + gAppSettings['Favicon'];
}
document.getElementsByTagName('head')[0].appendChild(link);
}
if ( gAppSettings.hasOwnProperty('CSS file') ) {
var link = document.createElement('link');
link.type = 'text/css';
link.rel = 'stylesheet';
if ( gAppSettings['CSS file'].indexOf('://') > 0 ) {
link.href = gAppSettings['CSS file'];
} else {
link.href = "apps/" + gAppSettings['Directory'] + "/" + gAppSettings['CSS file'];
}
document.getElementsByTagName('head')[0].appendChild(link);
}
if ( gAppSettings.hasOwnProperty('App icon') ) {
var link = document.createElement('link');
// Set whether or not it's 'precomposed' based on whether
// or not it's an Android browser. For iOS, it shouldn't be
// precomposed, because we want the nice "shiny" addition
// to the icon. (Or do we?)
var ua = navigator.userAgent.toLowerCase();
var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");
if ( isAndroid ) {
link.rel = 'apple-touch-icon-precomposed';
} else {
link.rel = 'apple-touch-icon';
}
if ( gAppSettings['App icon'].indexOf('://') > 0 ) {
link.href = gAppSettings['App icon'];
} else {
link.href = "apps/" + gAppSettings['Directory'] + "/" + gAppSettings['App icon'];
}
document.getElementsByTagName('head')[0].appendChild(link);
}
// This <meta> tag removes the browser's URL bar at the top and
// navigation bar at the bottom, making it look like a native app.
// Unfortunately, it currently only works in iOS, not Android.
// Also, the fact that it removes the navigation bar means that Miga
// would at least need to add a "back" button (and ideally a "forward"
// button as well) before it was activated.
/*
var meta = document.createElement('meta');
meta.name = "apple-mobile-web-app-capable";
meta.content = "yes";
document.getElementsByTagName('head')[0].appendChild(meta);
*/
displayTitle( null );
}
function getSettingsAndLoadData() {
// If we need the settings, retrieve them from LocalStorage, if
// they're there.
if ( gDataSchema == null ) {
var allAppInfoJSON = localStorage.getItem('Miga ' + getURLPath() );
if ( allAppInfoJSON != null ) {
var allAppInfo = JSON.parse( allAppInfoJSON );
gDBRandomString = allAppInfo['dbRandomString'];
gDataSchema = allAppInfo['dataSchema'];
gAppSettings = allAppInfo['appSettings'];
gPagesInfo = allAppInfo['pagesInfo'];
// gDataTimestamp, unlike the other global variables,
// does not come from LocalStorage but rather from
// the data JS file. timestampFromLocalStorage is the
// value that comes from Local Storage.
var timestampFromLocalStorage = allAppInfo['dataTimestamp'];
if ( typeof gDataTimestamp !== 'undefined' && timestampFromLocalStorage < gDataTimestamp ) {
refreshData();
} else {
setAllFromAppSettings();
}
}
}
if ( gAppSettings == null ) {
// If there was no data in LocalStorage, get the data from
// the data JS file.
DataLoader.getAppSettingsAndSchema();
if ( gAppSettings != null ) {
setAllFromAppSettings();
gDBConn.loadDataIfNecessary();
saveDataToLocalStorage();
}
} else {
gDBConn.loadDataIfNecessary();
}
}
/**
* Sets both the header and the document title of the page.
*/
function displayTitle( mdvState ) {
var titleText = gAppSettings['Name'];
jQuery('#title').html('<a href="#">' + titleText + '</a>');
var documentTitleText = gAppSettings['Name'];
if ( mdvState == null ) {
// Do nothing
} else if ( mdvState.useSearchForm ) {
documentTitleText += ": Search";
} else if ( mdvState.categoryName != null ) {
//documentTitleText += ": " + mdvState.categoryName;
if ( mdvState.itemName != null ) {
documentTitleText += ": " + mdvState.itemName;
}
} else if ( mdvState.pageName == '_start' ) {
// Start page - just show the site name.
} else if ( mdvState.pageName != null ) {
documentTitleText += ": " + mdvState.pageName;
}
document.title = documentTitleText;
jQuery('#searchInputWrapper').html(null);
}
function displayMainText( msg ) {
jQuery('#resultsMain').html(msg);
}
function addToMainText( msg ) {
jQuery('#resultsMain').append(msg);
}
function displayLoadingMessage( msg ) {
msg = "<div style=\"position: absolute; z-index; 5000; left: 50%; margin-left: -20px;\">";// + msg;
msg += '<img src="images/Ajax-loader.gif" /></div>';
jQuery('#resultsMain').prepend(msg);
//displayMainText( msg );
}
function showCurrentEventsLink( categoryName ) {
// It was already there - just un-hide it.
jQuery('#view-current-' + categoryName).show();
}
function blankFiltersInfo() {
jQuery('#furtherFiltersWrapper').html("");
jQuery('#categoryAndSelectedFilters').hide();
}
function displayCategorySelector() {
blankFiltersInfo();
displayTitle( null );
jQuery('#topSearchInput').html('');
var categoryNames = [];
for ( categoryName in gDataSchema ) {
if ( categoryHasNameField( categoryName ) ) {
categoryNames.push( categoryName );
if ( categoryHasStartAndEndTimeFields( categoryName ) ) {
// Just add on another value in to this array -
// unfortunately, we can't get an answer back
// from the database as to whether or not
// there are any events in this category that
// actually are current or upcoming by the
// time we need to decide whether or not to
// display a "category selector" page, so just
// assume that there are some, and that we do
// need to display the category selector.
categoryNames.push( '_current' );
}
}
}
var numPages = 0;
for ( pageName in gPagesInfo ) { numPages++; }
if ( numPages > 0 ) {
len = numPages;
} else {
len = categoryNames.length;
}
// If there's just one category or page, display it right away.
if ( len == 1 ) {
mdvState = new MDVState();
mdvState.categoryName = categoryNames[0];
displayItemsScreen( mdvState );
return;
} else if ( len == 0 ) {
displayMainText( "<h2>No data found!</h2>" );
return;
}
var msg = "<ul id=\"categoriesList\" class=\"rows\">\n";
if ( numPages > 0 ) {
for ( pageName in gPagesInfo ) {
var mdvState = new MDVState();
var curPage = gPagesInfo[pageName];
if ( curPage[0] == 'File' ) {
//var fileName = curPage['File'];
mdvState.pageName = pageName;
} else if ( curPage[0] == 'Category' ) {
mdvState.categoryName = curPage[1];
}
msg += listElementHTML( mdvState, pageName, false );
}
} else {
for ( var i = 0; i < categoryNames.length; i++ ) {
var categoryName = categoryNames[i];
if ( categoryName == '_current' ) {
// mdvState still holds the previous category
// name, which is good.
// This will print out a hidden element - which
// will get un-hidden if there are any
// events currently happening.
mdvState.currentEventsOnly = true;
msg += listElementHTML( mdvState, ' View Current ' + mdvState.categoryName, false );
gDBConn.possiblyShowCurrentEventsLink( mdvState );
continue;
}
var mdvState = new MDVState( categoryName );
msg += listElementHTML( mdvState, 'View ' + categoryName, false );
}
}
msg += "</ul>\n";
displayMainText( msg );
makeRowsClickable();
}
function displayCategoryAndSelectedFiltersList( mdvState ) {
var mdvStateForCategory = new MDVState();
mdvStateForCategory.categoryName = mdvState.categoryName;
if ( mdvState.showSearchFormResults ) {
var categoryDisplay = '<strong>' + mdvStateForCategory.categoryName + '</strong>';
} else {
var categoryDisplay = '<strong><a href="' + mdvStateForCategory.getURLHash() + '">' + mdvStateForCategory.categoryName + '</a></strong>';
}
var filtersDisplay = '<ul id="selectedFilters">';
if ( mdvState.currentEventsOnly ) {
filtersDisplay += "<li>Currently-occurring events only.</li>\n";
}
var filterNum = 0;
var selectedFilters = mdvState.selectedFilters;
for ( var propName in selectedFilters ) {
filterNum++;
filtersDisplay += "<li>";
var propValueParts = selectedFilters[propName].split(decodeURI('%0C'));
var propValueDisplay = '<strong>' + propValueParts.join('</strong> or <strong>') + '</strong>';
if ( selectedFilters[propName] == '__null' ) {
propValueDisplay = "<em>No value</em>";
}
if ( filterNum > 1 ) { filtersDisplay += '& '; }
filtersDisplay += propName + " = " + propValueDisplay;
if ( ! mdvState.showSearchFormResults ) {
var newDBState = mdvState.clone();
delete newDBState.selectedFilters[propName];
filtersDisplay += ' <a href="' + newDBState.getURLHash() + '">[✕]</a>';
}
filtersDisplay += "</li>";
}
filtersDisplay += "</ul>";
// Re-show, in case it was hidden.
jQuery('#categoryAndSelectedFilters').show();
jQuery('#categoryAndSelectedFilters').html( categoryDisplay + filtersDisplay );
}
function getUnusedFilters( mdvState ) {
var categoryHeaders = [];
categoryFields = gDataSchema[mdvState.categoryName]['fields'];
for ( fieldName in categoryFields ) {
if ( categoryFields[fieldName]['isFilter'] ) {
categoryHeaders.push(fieldName);
}
}
var furtherFilters = [];
for (i = 0; i < categoryHeaders.length; i++) {
var filterName = categoryHeaders[i];
var filterAttribs = gDataSchema[mdvState.categoryName]['fields'][filterName];
if ( !filterAttribs.hasOwnProperty('isFilter') ) {
continue;
}
if ( mdvState.useSearchForm || mdvState.selectedFilters[filterName] == null || DataLoader.isDateType(filterAttribs['fieldType']) || filterAttribs['fieldType'] == 'Number' ) {
furtherFilters.push(filterName);
}
}
return furtherFilters;
}
function displayAdditionalFilters( mdvState ) {
var furtherFilters = getUnusedFilters( mdvState );
// This code needs to be improved a lot!
// We're looking for "connector" categories - categories other than
// this one, that don't have a "Name" field, but do have a field
// pointing back to this one (of type "Entity") - for any such
// category, we want to filter on the first field we find, that's not
// being filtered on already.
var compoundItemFilters = [];
for ( categoryName in gDataSchema ) {
var foundMatch = false;
var mainFilterField = null;
if ( categoryName == mdvState.categoryName ) continue;
if ( categoryHasNameField( categoryName ) ) continue;
for ( fieldName in gDataSchema[categoryName]['fields'] ) {
if ( gDataSchema[categoryName]['fields'][fieldName]['fieldType'] == 'Entity' ) {
if ( gDataSchema[categoryName]['fields'][fieldName]['connectedCategory'] == mdvState.categoryName ) {
foundMatch = true;
}
}
var categoryFieldString = categoryName + "::" + fieldName;
if ( mainFilterField == null && gDataSchema[categoryName]['fields'][fieldName]['fieldType'] == 'Text' && !mdvState.selectedFilters.hasOwnProperty( categoryFieldString ) ) {
mainFilterField = fieldName;
}
}
if ( foundMatch && mainFilterField != null ) {
compoundItemFilters.push( categoryName + '::' + mainFilterField );
}
}
furtherFilters = furtherFilters.concat(compoundItemFilters);
var msg = '';
if ( furtherFilters.length > 0 ) {
if ( jQuery.isEmptyObject( mdvState.selectedFilters ) ) {
msg += "Filter by:";
} else {
msg += "Filter further by:";
}
for ( var i = 0; i < furtherFilters.length; i++ ) {
var filterName = furtherFilters[i];
var isCompoundFilter = false;
if ( ( filterColonsLoc = filterName.indexOf('::') ) > 0 ) {
isCompoundFilter = true;
}
var newDBState = mdvState.clone();
newDBState.displayFilter = filterName;
// Remove page number, filter display from URL
newDBState.pageNum = null;
newDBState.filterDisplayFormat = null;
if ( i > 0 ) {
msg += " ·\n";
}
if ( filterName == mdvState.displayFilter ) {
if ( isCompoundFilter ) {
msg += ' <span class="compoundFilterName">' + filterName.substring( filterColonsLoc + 2 ) + '</span>';
} else {
msg += " <span>" + filterName + '</span>';
}
} else {
if ( isCompoundFilter ) {
msg += ' <span class="clickable compoundFilterName" real-href="' + newDBState.getURLHash() + '">' + filterName.substring( filterColonsLoc + 2 ) + '</span>';
} else {
msg += ' <span class="clickable" real-href="' + newDBState.getURLHash() + '">' + filterName + "</span>";
}
}
}
}
if ( msg == '' ) {
jQuery('#furtherFiltersWrapper').html('');
} else {
jQuery('#furtherFiltersWrapper').html('<div id="furtherFilters">' + msg + '</div>');
}
}
function displayItem( mdvState, itemID, itemName ) {
jQuery('#furtherFiltersWrapper').html("");
displayMainText('<ul id="itemValues"></ul>');
// This displayItem() function will itself call displayItemValues().
gDBConn.displayItem( mdvState, itemID, itemName );
}
function listElementHTML( mdvState, internalHTML, isDiv ) {
msg = ( isDiv ) ? '<div ' : '<li ';
if ( mdvState.currentEventsOnly ) {
msg += 'id="view-current-' + mdvState.categoryName + '" ';
msg += 'style="display: none;" ';
}
msg += 'class="clickable" real-href="' + mdvState.getURLHash() + '">';
msg += '<table class="listElement"><tr>';
msg += '<td>' + internalHTML + "</td>";
msg += '<td style="text-align: right; font-weight: bold;">></td>';
msg += '</tr></table>';
msg += ( isDiv ) ? '</div>' : '</li>';
msg += "\n";
return msg;
}
function displayFormatTabs( mdvState, allDisplayFormats ) {
msg = '<ul id="displaySelector">';
for ( i = 0; i < allDisplayFormats.length; i++ ) {
var curFormat = allDisplayFormats[i];
var curFormatDisplayName = curFormat;
if ( curFormat == null ) {
curFormatDisplayName = 'list';
}
if ( mdvState.displayFormat == curFormat ) {
msg += '<li class="selectedDisplay">View ' + curFormatDisplayName + '</li>';
} else {
var newDBState = mdvState.clone();
newDBState.displayFormat = curFormat;
msg += '<li class="display clickable" real-href="' + newDBState.getURLHash() + '">View ' + curFormatDisplayName + '</li>';
}
}
msg += '</ul>';
displayMainText( msg );
}
// @TODO - remove duplicate code that's in both of the below functions.
function setTrueFilterDisplayFormat( mdvState, hasNumericalVariation ) {
var filterType = mdvState.getDisplayFilterType();
if ( DataLoader.isDateType(filterType) ) {
if ( mdvState.filterDisplayFormat == null ) {
mdvState.filterDisplayFormat = 'date';
}
} else {
if ( mdvState.filterDisplayFormat == null ) {
if ( hasNumericalVariation ) {
if ( gAppSettings.hasOwnProperty('Hide quantity tab') && gAppSettings['Hide quantity tab'] == 'true' ) {
mdvState.filterDisplayFormat = 'alphabetical';
} else {
mdvState.filterDisplayFormat = 'number';
}
} else {
mdvState.filterDisplayFormat = 'alphabetical';
}
}
}
}
function displayFilterFormatTabs( mdvState ) {
// If we're supposed to hide the quantity/number tab, it means no
// tabs will be shown - just exit. If the display ever had more than
// two tabs, though, this would have to change.
if ( gAppSettings.hasOwnProperty('Hide quantity tab') && gAppSettings['Hide quantity tab'] == 'true' ) {
return;
}
var filterType = mdvState.getDisplayFilterType();
if ( DataLoader.isDateType(filterType) ) {
//if ( mdvState.filterDisplayFormat == null ) {
// mdvState.filterDisplayFormat = 'date';
//}
var filterDisplayFormats = ['date', 'number'];
} else {
//if ( mdvState.filterDisplayFormat == null ) {
// mdvState.filterDisplayFormat = 'number';
//}
var filterDisplayFormats = ['number', 'alphabetical'];
}
var msg = '<ul id="displaySelector">';
for ( i = 0; i < filterDisplayFormats.length; i++ ) {
var curFormat = filterDisplayFormats[i];
if ( DataLoader.isDateType(filterType) ) {
if ( curFormat == null ) {
curFormat = 'date';
}
} else {
if ( curFormat == null ) {
curFormat = 'number';
}
}
var curFormatDisplayName = curFormat;
if ( curFormat == 'number' ) {
curFormatDisplayName = 'By quantity';
} else if ( curFormat == 'date' ) {
curFormatDisplayName = 'Chronological';
} else if ( curFormat == 'alphabetical' ) {
curFormatDisplayName = 'Alphabetical';
}
if ( mdvState.filterDisplayFormat == curFormat ) {
msg += '<li class="selectedDisplay">' + curFormatDisplayName + '</li>';
} else {
var newDBState = mdvState.clone();
newDBState.filterDisplayFormat = curFormat;
msg += '<li class="display clickable" real-href="' + newDBState.getURLHash() + '">' + curFormatDisplayName + '</li>';
}
}
msg += '</ul>';
addToMainText( msg );
}
function pageNavigationHTML( mdvState, numItems, itemsPerPage ) {
msg = '<ul id="pageNumbers">';
msg += '<li id="pageNumbersLabel">Go to page:</li>';
numPages = Math.ceil( numItems / itemsPerPage );
if ( mdvState.pageNum == null ) mdvState.pageNum = 1;
for ( var curPage = 1; curPage <= numPages; curPage++ ) {
if ( curPage == mdvState.pageNum ) {
msg += '<li class="selected">' + curPage + '</li>';
} else {
var newDBState = mdvState.clone();
newDBState.pageNum = curPage;
msg += '<li class="clickable" real-href="' + newDBState.getURLHash() + '">' + curPage + '</li>';
}
}
msg += "</ul>";
return msg;
}
function displaySearchFormInput( mdvState, filterValues ) {
var msg = '';
var len = filterValues.length;
for (var i = 0; i < len; i++) {
var curFilter = filterValues[i];
// 'numValues' is really the number of *items*, and 'filterName'
// is really the filter *value*... oh well.
var numValues = curFilter['numValues'];
if ( numValues == 0 ) continue;
var filterValue = curFilter['filterName'];
if ( filterValue == null ) {
continue;
}
var filterName = mdvState.displayFilter;
var selectedValuesForCurFilter = [];
if ( mdvState.selectedFilters.hasOwnProperty(filterName) ) {
selectedValuesForCurFilter = mdvState.selectedFilters[filterName].split(decodeURI('%0C'));
}
msg += ' <span class="searchFormCheckbox"><label><input type="checkbox" class="searchFormCheckbox" filtername="' + filterName + '" filtervalue="' + filterValue + '"';
var checked = ( jQuery.inArray( filterValue, selectedValuesForCurFilter ) > -1 );
if ( checked ) { msg += ' checked'; }
var escapedFilterValue = HTMLEscapeString( filterValue );
msg += ' />' + escapedFilterValue + '</label></span>';
}
jQuery('#searchFormInput-' + mdvState.displayFilter.replace(' ', '-')).html(msg);
}
function displaySearchForm( mdvState ) {
var categorySchema = gDataSchema[mdvState.categoryName]['fields'];
displayTitle( mdvState );
blankFiltersInfo();
var msg = "<h1>Search</h1>\n";
msg += "<form>\n";
var allFilters = getUnusedFilters( mdvState );
msg += '<div id="searchInputs">';
for ( var i = 0; i < allFilters.length; i++ ) {
var filterName = allFilters[i];
// For now, we only search on fields of type Text or Entity.
var filterType = categorySchema[filterName]['fieldType'];
if ( filterType != 'Text' && filterType != 'Entity' ) {
continue;
}
msg += '<div class="searchFormInput">';
msg += '<h2>' + filterName + "</h2>\n";
msg += '<div id="searchFormInput-' + filterName.replace(' ', '-') + '">';
var newMDVState = mdvState.clone();
newMDVState.displayFilter = filterName;
gDBConn.displayFilterValues( newMDVState );
msg += "</div>";
msg += "</div>";
}
msg += "</div>";
msg += '<input type="button" value="Search" onclick="handleSubmittedSearchForm(mdvState, this.form)">';
msg += "</form>";
displayMainText(msg);
}
function handleSubmittedSearchForm( mdvState, form ) {
mdvState.selectedFilters = [];
jQuery(".searchFormCheckbox").each( function() {
if ( $(this).prop('checked') ) {
var filterName = $(this).attr('filtername');
var filterValue = $(this).attr('filtervalue');
if ( mdvState.selectedFilters.hasOwnProperty(filterName) ) {
// Use an obscure character to separate the
// values - a "form feed".
mdvState.selectedFilters[filterName] += decodeURI('%0C') + filterValue;
} else {
mdvState.selectedFilters[filterName] = filterValue;
}
}
});
window.location = mdvState.getURLHash();
mdvState.useSearchForm = false;
mdvState.showSearchFormResults = true;
window.location = mdvState.getURLHash();
}
function displaySearchFormResults( mdvState ) {
displayCategoryAndSelectedFiltersList( mdvState );
getDisplayDetailsAndDisplayItems( mdvState );
}
function getDisplayDetailsAndDisplayItems( mdvState ) {
var imageProperty = null;
var firstTextField = null;
var firstEntityField = null;
var coordinatesProperty = null;
var dateProperty = null;
var categoryFields = gDataSchema[mdvState.categoryName]['fields'];
for ( propName in categoryFields ) {
var propType = categoryFields[propName]['fieldType'];
if ( mdvState.displayFormat == 'map' && propType == 'Coordinates' ) {
coordinatesProperty = propName;
}
// Restrict schedule to just 'Start time' type
if ( dateProperty == null && propType == 'Start time' ) {
dateProperty = propName;
}
if ( imageProperty == null && propType == 'Image URL' ) {
imageProperty = propName;
}
if ( firstTextField == null && firstEntityField == null ) {
if ( propType == 'Text' ) {
firstTextField = propName;
} else if ( propType == 'Entity' ) {
firstEntityField = propName;
}
}
}
gDBConn.displayItems( mdvState, imageProperty, coordinatesProperty, dateProperty, firstTextField, firstEntityField );
}
function displayItemsScreen( mdvState ) {
displayTitle( mdvState );
displayTopSearchInput( mdvState );
displayCategoryAndSelectedFiltersList( mdvState );
displayAdditionalFilters( mdvState );
getDisplayDetailsAndDisplayItems( mdvState );
}
function displayMap( allItemValues ) {
addToMainText('<div id="mapCanvas"></div><div id="coordinates"></div>');
// Calculate center, and bounds, of map
var numItems = allItemValues.length;
var totalLatitude = 0;
var totalLongitude = 0;
for ( i = 0; i < numItems; i++ ) {
totalLatitude += allItemValues[i]['Latitude'];
totalLongitude += allItemValues[i]['Longitude'];
}
var averageLatitude = totalLatitude / numItems;
var averageLongitude = totalLongitude / numItems;
var furthestDistanceEast = 0;
var furthestDistanceWest = 0;
var furthestDistanceNorth = 0;
var furthestDistanceSouth = 0;
for ( i = 0; i < numItems; i++ ) {
var latitudeDiff = allItemValues[i]['Latitude'] - averageLatitude;
var longitudeDiff = allItemValues[i]['Longitude'] - averageLongitude;
if ( latitudeDiff > furthestDistanceNorth ) {
furthestDistanceNorth = latitudeDiff;
} else if ( latitudeDiff < furthestDistanceSouth ) {
furthestDistanceSouth = latitudeDiff;
}
if ( longitudeDiff > furthestDistanceEast ) {
furthestDistanceEast = longitudeDiff;
} else if ( longitudeDiff < furthestDistanceWest ) {
furthestDistanceWest = longitudeDiff;
}
}
// In case there was only one point (or all points have the same
// coordinates), add in some reasonable padding.
if ( furthestDistanceNorth == 0 && furthestDistanceSouth == 0 && furthestDistanceEast == 0 && furthestDistanceWest == 0 ) {
furthestDistanceNorth = 0.0015;
furthestDistanceSouth = -0.0015;
furthestDistanceEast = 0.0015;
furthestDistanceWest = -0.0015;
}
var northLatitude = averageLatitude + furthestDistanceNorth;
var southLatitude = averageLatitude + furthestDistanceSouth;
var eastLongitude = averageLongitude + furthestDistanceEast;
var westLongitude = averageLongitude + furthestDistanceWest;
var centerOfMap = new MDVCoordinates( averageLatitude, averageLongitude );
var northEastCorner = new MDVCoordinates( northLatitude, eastLongitude );
var southWestCorner = new MDVCoordinates( southLatitude, westLongitude );
if ( gAppSettings['Map service'] == 'OpenLayers' ) {
if ( gMapScriptLoaded ) {
displayOpenLayersMap( allItemValues, centerOfMap, northEastCorner, southWestCorner );
} else {
jQuery.getScript("http://www.openlayers.org/api/OpenLayers.js")
.done( function( script, textStatus ) {
gMapScriptLoaded = true;
displayOpenLayersMap( allItemValues, centerOfMap, northEastCorner, southWestCorner );
});
}
} else { // default is Google Maps
if ( gMapScriptLoaded ) {
displayGoogleMapsMap( allItemValues, centerOfMap, northEastCorner, southWestCorner );
} else {
// With Google Maps, you have to define a callback
// function, and pass it in to their API.
displayGoogleMapsWrapper = function() {
gMapScriptLoaded = true;
// Get the MarkerClusterer script, while
// we're at it - not a big deal if it
// doesn't get used.
jQuery.getScript("libs/markerclusterer.js")
.done( function( script, textStatus ) {
displayGoogleMapsMap( allItemValues, centerOfMap, northEastCorner, southWestCorner );
});
}
jQuery.getScript("https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=displayGoogleMapsWrapper");
}
}
// Display coordinates below the map
if ( numItems == 1 ) {
var mdvCoords = new MDVCoordinates();
mdvCoords.setFromDBItem( allItemValues[0] );
jQuery('#coordinates').html('<span class="fieldName">Coordinates:</span> ' + mdvCoords.toString());
}
}
function displayGoogleMapsMap( allItemValues, centerOfMap, northEastCorner, southWestCorner ) {
var centerLatLng = centerOfMap.toGoogleMapsLatLng();
var northEastLatLng = northEastCorner.toGoogleMapsLatLng();
var southWestLatLng = southWestCorner.toGoogleMapsLatLng();
var mapBounds = new google.maps.LatLngBounds( southWestLatLng, northEastLatLng );
var mapOptions = {
zoom: 4,
center: centerLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('mapCanvas'), mapOptions);
map.fitBounds( mapBounds );
var infoWindows = [];
var numItems = allItemValues.length;
for ( i = 0; i < numItems; i++ ) {
var itemName = allItemValues[i]['SubjectName'];
var mdvState = new MDVState();
mdvState.itemID = allItemValues[i]['SubjectID'];
infoWindows[i] = new google.maps.InfoWindow({
content: '<a href="' + mdvState.getURLHash() + '">' + itemName + '</a>'
});
}
var doMarkerClustering = false;
if ( gAppSettings.hasOwnProperty('Marker clustering') && gAppSettings['Marker clustering'] == 'true' ) {
doMarkerClustering = true;
}
if ( doMarkerClustering ) {
var markers = [];
}
for ( i = 0; i < numItems; i++ ) {
var curCoordinates = new MDVCoordinates();
curCoordinates.setFromDBItem( allItemValues[i] );
var curLatLng = curCoordinates.toGoogleMapsLatLng();
var marker = new google.maps.Marker({
position: curLatLng,
map: map,
title: allItemValues[i]['SubjectName'],
itemNum: i // MDV-specific
});
if ( doMarkerClustering ) {
markers.push( marker );
}
// If there's just one point on the map, don't make the
// marker clickable.
if ( numItems == 1 ) continue;
google.maps.event.addListener(marker, 'click', function() {
for ( i = 0; i < numItems; i++ ) {
infoWindows[i].close();
}
infoWindows[this.itemNum].open(map,this);
});
}
if ( doMarkerClustering ) {
var mc = new MarkerClusterer( map, markers );
}
makeRowsClickable();
}
function displayOpenLayersMap( allItemValues, centerOfMap, northEastCorner, southWestCorner ) {
var map = new OpenLayers.Map( 'mapCanvas' );
map.addLayer( new OpenLayers.Layer.OSM() );
var southWestLonLat = southWestCorner.toOpenLayersLonLat(map);
var northEastLonLat = northEastCorner.toOpenLayersLonLat(map);
var mapBounds = new OpenLayers.Bounds();
mapBounds.extend( southWestLonLat );
mapBounds.extend( northEastLonLat );
map.zoomToExtent( mapBounds );
var markers = new OpenLayers.Layer.Markers( "Markers" );
map.addLayer( markers );
var popupClass = OpenLayers.Class(OpenLayers.Popup.FramedCloud, {
"autoSize": true,
"minSize": new OpenLayers.Size(300, 50),
"maxSize": new OpenLayers.Size(500, 300),
"keepInMap": true
});
var numItems = allItemValues.length;
for ( i = 0; i < numItems; i++ ) {
var curItem = allItemValues[i];
var curCoordinates = new MDVCoordinates();
curCoordinates.setFromDBItem( curItem );
var curLonLat = curCoordinates.toOpenLayersLonLat(map);
var feature = new OpenLayers.Feature( markers, curLonLat );
feature.closeBox = true;
feature.popupClass = popupClass;
var mdvState = new MDVState();
mdvState.itemID = curItem['SubjectID'];
feature.data.popupContentHTML = '<a href="' + mdvState.getURLHash() + '">' + curItem['SubjectName'] + '</a>';
var marker = new OpenLayers.Marker( curLonLat );
markers.addMarker( marker );
// If there's just one point on the map, don't make the
// marker clickable.
if ( numItems == 1 ) continue;
marker.events.register( 'mousedown', feature, function(evt) {
if (this.popup == null ) {
this.popup = this.createPopup( true );
map.addPopup( this.popup );
this.popup.show();
} else {
this.popup.toggle();
}
currentPopup = this.popup;
OpenLayers.Event.stop( evt );
});
}
}
function displaySchedule( allItemValues ) {
var distinctDates = {};
for ( i = 0; i < allItemValues.length; i++ ) {
if ( allItemValues[i].hasOwnProperty('Date') && allItemValues[i]['Date'] != null ) {
distinctDates[allItemValues[i]['Date']] = true;
}
}
var msg = '';