-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathcustom.js
2279 lines (1963 loc) · 112 KB
/
custom.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
/*
Dear themer
You can use this file to add your own javascript functions to your theme.
Some useful things to get you started:
1.
To find out which classes are available to you, have a look at the page on the WIKI about theming.
http://domoticz.com/wiki/How_to_theme_Domoticz
2.
Here are some snippets you may find useful:
- Check is a theme feature is enabled:
if (theme.features.featurename.enabled === true) { // do something here}
- Check if the user is on a mobile device
if( $('body#onmobile') ) { // do something here }
HOW THIS THEME WORKS
- It stores all data in a local storage object called 'theme'.
- it syncs that data with Domoticz, but only which features are enabled. Design settings are only stores in the browser (for now).
- Once the theme has checked in with Domoticz to check the stored features list, it loads all the relevant JS and CSS files.
- It hooks into Domoticz by responding to succesful ajax queries, watching for page changes, and listenening for variable changes.
If the entire app is just starting:
document.ready -> themeLoadObject -> checkIfDomoticzHasThemeSettings -> get settings from domoticz (2x) -> enable theme features -> load theme featuers
Most of these functions are at the top half of this document.
If the user changes to a new view:
pageChangeDetected ->load observer & ajax(in DocumentReady) ->
The 'waterfall' of changes then starts:
1. frontendImporvement: when a new 'page' is loaded, like the dashboard or settings, for example. It removes all the divider row.
2. improve classes. This adds lots of html that is required to other fuctions to work. This must often be re-added, as Domoticz
likes to overwrite the html a lot. Especiallt on the weather and temperature pages, which rely heavily on the JS framework,
but which is really unwieldy an slow.
3. new data: this is a response to sensors and other items being continuously updated. The theme tries to quickly style these responses.
This waterfall also starts on numerous other occasions, like when new data arrives (ajax in DocumentReady), when a canary observer spots
changes, when the load observer spots bigchanges, or sometimes just through an 'oldschool' setTimeout function that just keeps checking if
things have loaded.
The theme also adds a settings tab when the settings page is opened. This has its own little waterfall at the bottom of this document.
At the very bottom of this document you will find helper functions.
OTHER DETAILS
The theme adds tags to the HTML to make theming easier. Important tags you may want to look into:
- item. This is the core div for each item where all the classes are added
- Bandleader & bandmember. These are for merged items. The bandleader gathers all data, and the other bandmembers are hidden in a hidden div.
- withstatus & statuscount. This defines if an item has multiple datafeeds to display.
- on/of. This reflects if a switch is on or off.
- sensor type tags. Sensors get tags, based on the image they have.
*/
var folder = "";
var theme = {}; // object that holds all the theme settings
var bands = {}; // object that holds all the items to be merged
var currentPage = "login";
var frontend = true;
var onMobile = false;
var themeMachineName = "";
var lastOpenedBlockly = {};
var fullscreenPossible = false;
var lastPrivacyPrunedTime = 0;
//var oldLastUpdateTime = 0; // used to check if domoticz has incorporated new updated data.
var freshJSON = {}; // the latest data from domoticz.
//var newDataWatcherIsRunning = false;
var lastUpdateWatcherisRunning = false;
var clockIsRunning = false;
var limbo = true; // When on a new page, but items have not loaded yet.
var waterfallRunning = false; // If the upgrade proces is already running, then no need to run it again.
var rerunImprovement = false; // if improvements called while already running, this helps run it again after it's done.
var loadedThemeObject = false;
var loadedSettingsFromDomoticz = false;
var loadedThemeCSSandJS = false;
var baseURL = "";
/*
try {
var pathArray = location.href.split('/');
var protocol = pathArray[0];
var host = pathArray[2];
console.log("folder = " + pathArray[3]);
if (pathArray[3] != "" && pathArray[3].charAt(0) != "#") { folder = "/" + pathArray[3] } // pathArray[3]!="#") &&
var baseURL = protocol + '//' + host + folder;
console.log("base URL = " + baseURL);
}
catch (e) {
console.log("THEME JS - ERROR: not able to find out what the base path is.");
$.get('/json.htm?type=command¶m=addlogmessage&message=Theme Error - the theme is not able to find out what the base path is.');
}
*/
// for debugging:
//localStorage.clear();
// this function sets the body ID to reflect if we ae on a mobile device or not.
function areWeOnMobile(){
console.log("THEME JS - areweonmobile: checking if on mobile device");
// mobile device detection
if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent)
|| /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(navigator.userAgent.substr(0, 4))) {
$("body").attr('id', 'onMobile');
document.body.setAttribute("id", "onMobile");
$('body').attr('id', 'onMobile');
onMobile = true;
} else {
if (typeof theme.name !== "undefined") {
if (theme.features.mobile_phoney.enabled === true && theme.features.mobile_on_non_mobile.enabled === true) {
console.log("THEME JS - setting mobile tag on non-mobile device");
//document.body.setAttribute("id", "onMobile");
$('body').attr('id', 'onMobile');
onMobile = true;
} else {
//document.body.setAttribute("id", "notMobile");
$('body').attr('id', 'notMobile');
onMobile = false;
}
}
}
if (frontend === true) {
$("body").addClass('frontend').removeClass('backend'); // a small quick hack to find out why these tags are disappearing. Probably domoticz doing that.
}
}
// This function is the start of loading the theme settings. It loads an object with all the settings from the theme.json file.
// Form then on it checks if Domoticz has alternative settings to the defaults.
function themeLoadObject() {
console.log("THEME JS - starting processes of loading theme preferences");
// If there are no locally stored settings yet, then load defaults from server.
if (typeof (Storage) !== "undefined") {
if (localStorage.getItem("themeObject") === null) {
console.log("THEME JS - No locally stored theme object found, now loading the theme json.");
loadJSON('styles/aurora/theme.json',
function (themex) {
theme = themex; // set global object
console.log("THEME JS - Theme name = " + theme.name);
themeMachineName = machineName(theme.name);
if (isEmptyObject(theme) === false) {
localStorage.setObject("themeObject", theme);
}
console.log("+++ theme object succesfully loaded from theme.json file, and stored in local storage");
pageChangeDetected(); // continue with the first-load checklist.
//checkIfDomoticzHasThemeSettings(); // if there were no local settings, perhaps Domoticz also has no settings. Let's make sure.
}, function(xhr) { console.error(xhr); }
);
} else { // If local preferences have been set, try to load those.
console.log("THEME JS - theme object was already found in the browser.");
theme = localStorage.getObject("themeObject");
console.log(theme);
themeMachineName = machineName(theme.name);
pageChangeDetected();
}
} else {
// FALL BACK. No Web Storage support.. Old browser? Loading backup css file.
var CSSfile = "styles/aurora/oldbrowser.css";
var fileref = document.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", CSSfile);
document.getElementsByTagName("head")[0].appendChild(fileref);
console.log("-----------");
console.log("THEME JS - IMPORTANT: BROWSER CANNOT REALLY RUN THIS THEME, IT DOES NOT SUPPORT LOCAL STORAGE.");
console.log("-----------");
/*HideNotify();
bootbox.alert($.t('This browser cannot really run this theme because it does not support "local storage".'));*/
$.get('/json.htm?type=command¶m=addlogmessage&message=Theme Error - your browser does not support local storage, so cannot save preferences.');
}
}
// No local settings found in the browser. Local json files was loaded as default. The next step is checking for settings inside Domoticz, and to update the preferences from that, if possible. This will take a while..
function checkIfDomoticzHasThemeSettings()
{
$.ajax({
url: "/json.htm?type=command¶m=getuservariables",
async: true,
dataType: 'json',
success: function (data) {
if (data.status == "ERR") {
console.log("server responded with error while getting user variables");
$.get('/json.htm?type=command¶m=addlogmessage&message=Theme Error - The theme was unable to load your preferences from Domoticz.');
}
// If we got good data from Domoticz, load the preferences.
else if (typeof data.result !== "undefined") {
var didDomoticzHaveSettings = false;
var featuresVarName = "theme-" + themeMachineName + "-features";
var stylingVarName = "theme-" + themeMachineName + "-styling";
$.each(data.result, function(variable, value) {
console.log("looping over user variables list");
if(value.Name == featuresVarName){
console.log("THEME JS - found theme feature settings in Domoticz database (user variable #" + value.idx + ")");
didDomoticzHaveSettings = true;
theme.userfeaturesvariable = value.idx;
getThemeFeatureSettingsFromDomoticz(value.idx);
}
if(value.Name == stylingVarName){
console.log("THEME JS - found theme styling settings in Domoticz database (user variable #" + value.idx + ")");
didDomoticzHaveSettings = true;
theme.userstylingvariable = value.idx;
getThemeStylingSettingsFromDomoticz(value.idx);
}
});
if(didDomoticzHaveSettings === false){
console.log("THEME JS - Domoticz didn't have settings for the theme, will create them now from defaults.");
enableThemeFeatures(); // load defaults from the object
storeThemeSettingsInDomoticz("add"); // store new default settings in Domoticz, for next time..
}else{
console.log("THEME JS - Succesfully received user variable numbers from Domoticz.");
}
} else {
console.log("User variable list: data.result was undefined. So the list must be completely empty. Time to save the variables.");
if(typeof theme.name !== "undefined"){
storeThemeSettingsInDomoticz("add");
enableThemeFeatures();
}
}
},
error: function () {
console.log("The theme was unable to check if Domoticz had theme settings. Permission denied? Still on login page? No connection? Stopping..");
}
});
}
// here we get the styling preferences that are stored in Domoticz (colors, background image)
function getThemeStylingSettingsFromDomoticz(idx)
{
console.log("THEME JS - getting styling settings from Domoticz. User variable ID = " + idx);
$.ajax({
url: "json.htm?type=command¶m=getuservariable" +
"&idx=" + idx,
async: true,
dataType: 'json',
success: function (data) {
if (data.status == "ERR") {
console.log("THEME JS - Although they seem to exist, there was an error loading theme styling settings from Domoticz");
}
// If we got good data from Domoticz, load the preferences.
if (typeof data.result !== "undefined") {
var themeStylingSettingsFromDomoticz = JSON.parse(decodeURIComponent(data.result[0].Value));
// Update the theme object with the settings from Domoticz.
theme.textcolor = themeStylingSettingsFromDomoticz[0];
theme.backgroundcolor = themeStylingSettingsFromDomoticz[1];
theme.backgroundimage = themeStylingSettingsFromDomoticz[2];
setUserColors();
}
console.log("THEME JS - succesfully loaded theme styling settings from Domoticz");
if (isEmptyObject(theme) === false){
localStorage.setObject("themeObject", theme);
}
},
error: function () {
console.log("THEME JS - ERROR reading styling settings from Domoticz for theme" + theme.name + "from user variable #" + idx);
}
});
}
// here we get the feature settings that are stored in domoticz as a user variable.
function getThemeFeatureSettingsFromDomoticz(idx)
{
console.log("THEME JS - getting feature settings from Domoticz. User variable ID = " + idx);
$.ajax({
url: "json.htm?type=command¶m=getuservariable" +
"&idx=" + idx,
async: true,
dataType: 'json',
success: function (data) {
if (data.status == "ERR") {
console.log("THEME JS - Although they seem to exist, there was an error loading theme preferences from Domoticz");
$.get('/json.htm?type=command¶m=addlogmessage&message=Theme Error - The theme was unable to load your user variable.');
loadedSettingsFromDomoticz = false;
pageChangeDetected();
}
// If we got good data from Domoticz, load the preferences.
else if (typeof data.result !== "undefined") {
console.log("THEME JS - succesfully loaded theme feature settings from Domoticz");
var themeSettingsFromDomoticz = JSON.parse(data.result[0].Value);
// Update the theme object with the settings from Domoticz.
$.each(theme.features, function(key,feature){
if($.inArray(feature.id, themeSettingsFromDomoticz) > -1){
theme.features[key].enabled = true;
}else{
theme.features[key].enabled = false;
}
});
localStorage.setObject("themeObject", theme); // save loaded preferences in local object.
loadedSettingsFromDomoticz = true;
pageChangeDetected();
}else{
console.log("THEME JS - ERROR, couldn't load your theme preferences from Domoticz. They were there before..");
pageChangeDetected();
}
},
error: function () {
console.log("THEME JS - ERROR reading feature settings from Domoticz for theme" + theme.name + "from user variable #" + idx);
// load defaults, just to be safe.
enableThemeFeatures();
loadedSettingsFromDomoticz = false;
pageChangeDetected();
}
});
}
function storeThemeSettingsInDomoticz(action)
{
// prepare variables
console.log("THEME JS - storing settings in Domoticz");
// 1. FEATURES
var themeSettingsForDomoticz = [];
$.each(theme.features, function(key,feature){
if(feature.enabled === true){
themeSettingsForDomoticz.push(feature.id);
}
});
// store/update features
var variableURL = 'json.htm?type=command¶m=' + action + 'uservariable&vname=theme-' + themeMachineName + '-features&vtype=2&vvalue='+ JSON.stringify(themeSettingsForDomoticz);
$.ajax({
url: variableURL,
async: true,
dataType: 'json',
success: function (data) {
if (data.status == "ERR") {
HideNotify();
bootbox.alert($.t('Unable to store theme settings in Domoticz. Try clearing ALL your cache.'));
console.log("THEME JS - unable to create theme settings storage in Domoticz. (tip:max datasze is 200 bytes)");
}
//wait 1 second
setTimeout(function () {
HideNotify();
}, 1000);
// If we got good data from Domoticz.
if (typeof data.result !== "undefined") {
console.log("THEME JS - Got this response from Domoticz about the user variable:");
console.log(data.result);
}
},
error: function () {
console.log("THEME JS - Ajax error wile creating or updating user variable in Domotcz.");
}
});
// 2. STYLING
var themeStylingSettingsForDomoticz = [];
themeStylingSettingsForDomoticz.push(theme.textcolor);
themeStylingSettingsForDomoticz.push(theme.backgroundcolor);
themeStylingSettingsForDomoticz.push(theme.backgroundimage);
// store/update user's styling preferences
var stylingURL = 'json.htm?type=command¶m=' + action + 'uservariable&vname=theme-' + themeMachineName + '-styling&vtype=2&vvalue='+ encodeURIComponent(JSON.stringify(themeStylingSettingsForDomoticz));
$.ajax({
url: stylingURL,
async: true,
dataType: 'json',
success: function (data) {
if (data.status == "ERR") {
HideNotify();
bootbox.alert($.t('Unable to store theme styling settings in Domoticz. Try clearing ALL your cache.'));
console.log("THEME JS - unable to create theme styling settings storage in Domoticz. (tip:max datasze is 200 bytes)");
}
//wait 1 second
setTimeout(function () {
HideNotify();
}, 1000);
// If we got good data from Domoticz.
if (typeof data.result !== "undefined") {
console.log("THEME JS - Got this response from Domoticz about the user styling variable:");
console.log(data.result);
}
},
error: function () {
console.log("THEME JS - Ajax error wile creating or updating user styling variable in Domotcz.");
}
});
}
function enableThemeFeatures()
{
// load all JS and CSS files
$.each(theme.features, function(key,feature){
if(feature.enabled === true){
if(feature.files.length > 0){
loadThemeFeatureFiles(key);
}
}
});
loadUserCSS();
setUserColors();
// Everything should be loaded. Let's start checking for page content
console.log("THEME JS - everything is loaded. Calling pageChangeDetected.");
//pageChangeDetected();
loadedThemeCSSandJS = true;
}
function loadThemeFeatureFiles(featureName) // feed this function the feature name
{
//console.log("THEME JS - loading files for " + featureName + " feature");
// get file list from theme settings object
var files = theme.features[featureName].files;
var arrayLength = files.length;
for (var i = 0; i < arrayLength; i++) {
if(files[i].split('.').pop() == "js"){
console.log("THEME JS - loading javascript for " + featureName + " feature");
var getviarequire = "../styles/aurora/" + featureName;
requirejs([getviarequire], function(util) {
console.log("THEME JS - Javascript loaded by RequireJS");
});
}
if(files[i].split('.').pop() == "css"){
var CSSfile = "" + baseURL + "/styles/aurora/" + files[i] + "?" + themeMachineName;
console.log(CSSfile);
var fileref = document.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", CSSfile);
document.getElementsByTagName("head")[0].appendChild(fileref);
}
}
}
function unloadThemeFeatureFiles(featureName) // feed this function the feature name
{
$('head link[href*=' + featureName + ']').remove();
$('head script[src*=' + featureName + ']').remove();
}
function setUserColors()
{
// Should we use the mobile view when on desktop?
if (theme.features.mobile_phoney.enabled === true && theme.features.mobile_on_non_mobile.enabled === true) {
console.log("THEME JS - setting mobile tag on non-mobile device");
document.body.setAttribute("id", "onMobile");
}else {
// load text color
if(theme.textcolor != ""){
console.log("THEME JS - text color: " + theme.textcolor);
$('body').css('color', theme.textcolor);
}else{
console.log("THEME JS - no text color set");
$('body').css('color', "#fff");
}
// load background color
if(theme.backgroundcolor != ""){
$('html,body').css("background", ""); // reset for styling.css
console.log("THEME JS - background color: " + theme.backgroundcolor);
$('html,body').css('background-color', theme.backgroundcolor);
}else{
console.log("THEME JS - no background color set");
}
// load background image
//if(typeof theme.backgroundimage !== "undefined"){
if(theme.backgroundimage != ""){
console.log("THEME JS - background image: " + theme.backgroundimage);
$('body').css('background-image','url(' + theme.backgroundimage + ')');
}else{
console.log("THEME JS - no background image set");
}
}
}
// this function manages the step by step loading of the theme. each loading step calls back to the function, which then moves to the next stage.
function pageChangeDetected(){
//console.log("THEME JS - inside page change detected. currentPage was " + currentPage);
waterfallRunning = false;
// 1. First we make sure that angular has done it's thing of creating a proper angular URL.
try {
// detect current page based on url in the browser.
console.log(window.location.href);
var url = window.location.href;
if(typeof url.slice(-1) === "undefined"){console.log("slice undefined");return;} // this can probably be removed.
if ( url.indexOf("/#/") < 1 ){
console.log("no /#/ in url");
return;
}else{
console.log("THEME JS - pageChangeDetected. currentPage was " + currentPage);
currentPage = url.split("/#/")[1].toLowerCase();
baseURL = url.split("/#/")[0];
console.log("THEME JS - pageChangeDetected. currentPage is " + currentPage);
//console.log("THEME JS - pagechangedetected: new base URL is " + baseURL);
}
//f(url.slice(-1) == "/"){console.log("url ended in slash. Probably just opened. Cancelling, have to wait a bit.");return}
//if(typeof url.split("/#/")[1] === "undefined"){console.log("/#/ was undefined, couldn't split url.");return}
//currentPage = url.split("/#/")[1].toLowerCase();
//console.log("THEME JS - pagechangedetected: current page is " + currentPage);
}
catch (e) {
console.log("THEME JS - ERROR: not able to find out what page we are on:");
console.log(e);
$.get('/json.htm?type=command¶m=addlogmessage&message=Theme Error - the theme is unable to figure out what page you are on!');
//currentPage = "Dashboard";
return;
}
// 2. then we check if we are on the login page or not, and if the theme object has been loaded.
console.log("+++ pagechangedetected: theme object on next line. Empty? "+ isEmptyObject(theme));
console.log(theme);
if(currentPage == "login" && isEmptyObject(theme) === true ){
console.log("THEME JS - On the login page, and theme object is empty. Cancelling, waiting for user to log in first. ");
return;
}
if(currentPage != "login" && isEmptyObject(theme) === true ){
console.log("THEME JS - pageChangeDetected: we're not on the login page, but the theme object is empty. We may be early.. or late. ");
if(loadedThemeObject === false){
loadedThemeObject = true;
themeLoadObject();
}
return;
}
// In theory you can only get here if the theme object has been loaded.
if(typeof theme.name === "undefined"){
console.log("WEIRD: no theme object yet. Cancelling. This should not be possible.");
themeLoadObject();
return;
}
// 3. we make sure there is a connection with Domoticz, and get the feature preferences stored there. Finally, the files are loaded.
if(currentPage != "login" && isEmptyObject(theme) === false){
// loading all the theme's CSS and JS files.
if(loadedSettingsFromDomoticz === false && loadedThemeCSSandJS === false){
if(typeof theme.userfeaturesvariable !== "undefined"){
console.log("THEME JS - found a locally stored index (" + theme.userfeaturesvariable + ") for preferences stored in Domoticz. Will quickly load them.");
getThemeFeatureSettingsFromDomoticz(theme.userfeaturesvariable);
console.log("THEME JS - found a locally stored styling index (" + theme.userstylingvariable + ") for preferences stored in Domoticz. Will quickly load them.");
getThemeStylingSettingsFromDomoticz(theme.userstylingvariable);
}else{
console.log("THEME JS - user variable ID was NOT found inside theme object. Will try to get user variables list from Domoticz.");
checkIfDomoticzHasThemeSettings();
//enableThemeFeatures();
}
}
else if (loadedSettingsFromDomoticz === true && loadedThemeCSSandJS === false) {
startLoadObserver();
enableThemeFeatures(); // finally!
}
}
//
if(currentPage == "login" && isEmptyObject(theme) === false && loadedThemeCSSandJS === true){
// we returned to the login page after the theme objectand files were already loaded. Period of inactivity?
console.log(" ");
console.log(" ");
console.log("_________________________________________________");
console.log("user was logged out after a period of inactivity?");
}
// are we on the front or backend?
if( currentPage == ""
|| currentPage == "dashboard"
|| currentPage == "floorplans"
|| currentPage == "lightswitches"
|| currentPage == "temperature"
|| currentPage == "weather"
|| currentPage == "scenes"
|| currentPage == "utility" ){
console.log("THEME JS - NEW FRONT END");
frontend = true;
}else{
console.log("THEME JS - NEW BACK END");
frontend = false;
}
//if( loadObserver === "undefined"){
// console.log("this shouldn't happen: pagechangedetected is starting the load observer.");
// startLoadObserver();
//}
}
// the observer checks if new things are being loaded into the main content area.
function startLoadObserver()
{
if (!$( ".bannercontent" ).length){console.log("loadObserver couldn't start: no bannercontent container yet.");return;}
var contentHolder = $( ".bannercontent" )[0];
// Create an observer instance. It will check if content has loaded.
//if(typeof loadObserver === "undefined"){
if(typeof window.loadObserver === "undefined"){
loadObserver = new window.MutationObserver(function( mutations ) {
console.log("____load observer fired");
console.log(mutations);
if(currentPage == "weather" || currentPage == "temperature" || currentPage == "dashboard"){
setTimeout(frontendImprovement,19);
}
mutations.forEach(function( mutation ) {
console.log("loadobserver: currentPage = " + currentPage);
console.log("loadobserver: frontend = " + frontend);
if (currentPage != "login"){
var newNodes = mutation.addedNodes; // DOM NodeList
if( newNodes !== null ) { // If there are new nodes added
//console.log('new nodes..');
var $nodes = $( newNodes ); // jQuery set
$nodes.each(function() {
var $node = $( this );
//console.log($node);
if ( $node.attr('id') == "main-view" ){
console.log('__observer: A new mainview was loaded.');
//loadObserver.disconnect();
limbo = false;
// here the road splits:
$("body").removeClass();
$("body").addClass(currentPage);
if(frontend === true){
$("body").addClass('frontend').removeClass('backend');
$('#backendpagetitle').hide();
console.log("__loadobserver found mainview__");
frontendImprovement();
//loadObserver.disconnect();
//loadObserver.observe(contentHolder, {childList:true});
//return;
}else{
$("body").addClass('backend').removeClass('frontend');
if(currentPage == "setup"
|| currentPage == "events"
|| currentPage == "update"
|| currentPage == "forecast"
|| currentPage == "login"
|| currentPage == "about" ){
$('#backendpagetitle').hide();
}else{
$('#backendpagetitle').text(currentPage);
$('#backendpagetitle').show();
}
//loadObserver.disconnect();
backendImprovement();
}
oncePerPage();
}
});
}
}
});
});
// Pass in the target node, as well as the observer options
if(typeof contentHolder !== "undefined"){
console.log("observer: observing mainview container");
loadObserver.observe(contentHolder, {childList:true});
//console.log("__just set loadobserver__");
//setTimeout(frontendImprovement,1);
}else{
console.log("observer: error observing main content container. starting improvement in 2 seconds. ");
console.log("__failed loadobserver__");
setTimeout(frontendImprovement,2000);
}
}
}
function oldschool()
{
function race() {
if ( !$('#name').length ) {
console.log('oldschool race');
setTimeout(race, 1);
}else {
console.log("oldschool: content loaded, starting improvement.");
frontendImprovement();
}
}
race();
}
function backendImprovement()
{
console.log("THEME JS - now in backend improvements");
areWeOnMobile();
// events
if(currentPage == "events"){
//blocklyCreateExportButtons();
/* experiment with injecting CSS and JS into the blockly iFrame.
var $iframe = $('#IMain');
$iframe.ready(function() {
console.log("THEME JS - injecting JS and CSS into events iframe");
//var iFrameHead = window.frames["IMain"].document.getElementsByTagName("head")[0];
var myscript = document.createElement('script');
myscript.type = 'text/javascript';
myscript.src = '/styles/aurora/events.js';
$("#IMain").contents().find("head").append(myscript);
//iFrameHead.appendChild(myscript);
var mycss = document.createElement('link');
mycss.rel = 'stylesheet';
mycss.type = 'text/css';
mycss.href = '/styles/aurora/events.css';
//iFrameHead.appendChild(mycss);
$("#IMain").contents().find("head").append(mycss);
});
*/
}
// settings
if(currentPage == "setup"){showThemeSettings();}
// log: privacy pruning if necessary
if(currentPage == "log"){
// full privacy: only let the error part of the log remain.
if (theme.features.extra_privacy.enabled === true && theme.features.full_privacy.enabled === true){
console.log("THEME JS - Log: going full privacy");
$('#logcontent a[data-i18n="All"]').parent().remove();
$('#logcontent a[data-i18n="Status"]').parent().remove();
$('#logcontent li:first-of-type').addClass('active'); // set error tab as active
$('#logcontent #taball').remove();
$('#logcontent #tabstatus').remove();
$('#logcontent > table td:last-of-type').hide(); // hide search
$('#logcontent #taberror').show(); // set error tab as active
// extra privacy: remove status tab and remove some items from the log feed.
} else if ( theme.features.extra_privacy.enabled === true ){
console.log("log: extra privacy pruning");
// remove status tab entirely, as it has mainly user switch commands.
$('#logcontent #tabs a[data-i18n="Status"]').parent().remove();
$('#logcontent #tabstatus').remove();
// The datalogs to be monitored
var allLogdataDiv = $( "#logdata" )[0];
var errorLogdataDiv = $( "#logdata_error" )[0];
// Create an observer instance. It will try to delete privacy data as quickly as possible.
var privacyObserver = new window.MutationObserver(function( mutations ) {
console.log("log updates that must be privacy pruned: ");
console.log(mutations);
mutations.forEach(function( mutation ) {
var newNodes = mutation.addedNodes; // DOM NodeList
if( newNodes !== null ) { // If there are new nodes added
var $nodes = $( newNodes ); // jQuery set
$nodes.each(function() {
//console.log("new log update");
var $node = $( this );
if($node.children('span').hasClass('logstatus')){
$node.remove();
}
if($node.is(':contains("User:")')){
$node.remove();
}
if($node.is(':contains("Light/Switch")')){
$node.remove();
}
});
}
});
});
// Configuration of the observer:
var config = {
childList: true,
characterData: true
};
// Pass in the target node, as well as the observer options
privacyObserver.observe(errorLogdataDiv, config);
privacyObserver.observe(allLogdataDiv, config);
}
}
// custom icons
if(currentPage == "customicons"){
$( 'body.customicons #iconsmain > table:first-of-type tr' ).prepend('<td id="customiconsmenu"><button id="browseIconsBtn" class="button">Browse..</button><p id="browseIconsLabel">No file selected.</p></td>');
$( '#browseIconsBtn' ).click(function(){
$( '#fileupload' ).click();
});
$( '#fileupload').change(function(){
$( '#browseIconsLabel' ).text($( this ).val() );
if( $( this ).val() != "No file selected."){
}
});
$('#fileupload').hide();
}
$('#holder').show();
}
$( document ).ready(function()
{
console.log( "THEME JS - DOM is ready" );
requirejs.config({ waitSeconds: 30 }); // makes sure there is no timeout. There are some synchronous calls somewhere (not in this theme!), which slow everthing down.
// first, load in the CSS file with the most changes to the styling. This could become a settings option with a dropdown, so the user can pick a 'subtheme' styling variant.
console.log("THEME JS - Loading theme.css");
var CSSfile = "styles/aurora/theme.css?aurora";
var fileref = document.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", CSSfile);
document.getElementsByTagName("head")[0].appendChild(fileref);
startLoadObserver(); // will give notice when Domoticz reloads (or unloads) entire views.
pageChangeDetected(); //bootstrap
// continuously check if the URL has changed. The theme then responds to that by setting the variable 'limbo' to true. When new content is loaded the limbo state is disabled at the end of the frontend waterfall.
$(window).on('hashchange', function(e){
console.log("THEMEJS - URL change detected");
limbo = true;
clockIsRunning = false;
freshJSON = {};
bands = {};
pageChangeDetected();
if (typeof observerCanary !== "undefined") {
observerCanary.disconnect();
delete observerCanary;
}
if (typeof privacyObserver !== "undefined") {
privacyObserver.disconnect();
delete privacyObserver;
}
if (typeof weatherAndTempObserver !== "undefined") {
weatherAndTempObserver.disconnect();
delete weatherAndTempObserver;
}
});
//screenfull.toggle();
if (screenfull.enabled) {
screenfull.request();
}
// Many changes to the Domoticz HTML output have been proposed, but not all made it in. This theme adds those changes via JS.
$('#appnavbar li.divider').remove();
$('#cLightSwitches img').attr('src', 'images/lightbulb.png');
var newbackendpagetitle = '<h1 id="backendpagetitle"></h1>';
$('#holder').prepend(newbackendpagetitle);
// add fullscreen button.
if (screenfull.enabled) {
var fullscreenMenuItem = '<li id="mFullscreen"><a id="cFullscreen"><img src="images/fullscreen32.png"> <span data-i18n="Fullscreen">Fullscreen</span></a></li>';
$('#mAbout').after(fullscreenMenuItem);
$('#mFullscreen').click(function() {
screenfull.toggle();
});
//$("#appnavbar").i18n(); // Make the translation (Add tags in languagefile mnually)
}
// hooking into the ajax responses.
$( document ).ajaxSuccess(function( event, xhr, settings ) {
//limbo = false;
waterfallRunning = false;
if(onMobile){ $('body').attr('id','onMobile'); } // this means war :-)
if (frontend === false){return;}
if(frontend === false){
console.log("I should not exist on the backend");
}
// This is where the theme hooks into the AJAX calls that are made to Domoticz, and then tries to keep the HTML updated as best as possible.
if ( settings.url.startsWith("json.htm?type=command¶m=switchdeviceorder") ) {
console.log( "THEME JS - ajax listener: switch order" );
bands = {};
pageChangeDetected();
console.log("__switch device order__");
frontendImprovement();
}
else if ( settings.url.startsWith("json.htm?type=command¶m=makefavorite") ) {
console.log( "THEME JS - ajax listener: make favourite" );
pageChangeDetected();
console.log("__make favourite__");
frontendImprovement();
}
else if ( settings.url.startsWith("json.htm?type=plans") ) {
console.log("plans:");
console.log(xhr.responseJSON.result);
//oldschool();
}
else if ( settings.url.startsWith("json.htm?type=devices") ) {
if(limbo === true){limbo = false; return;}
console.log("__//ajax devices__");
//frontendImprovement();
console.log("-------------");
console.log( "THEME JS - ajax listener: devices update" );
if(typeof xhr.responseJSON.result !== "undefined" ){
console.log("THEME JS - ajax: observer: fresh JSON for devices");
console.log(xhr.responseJSON.result);
freshJSON = xhr.responseJSON.result;
console.log("__fresh json, starting in 20 milliseconds.__");
setTimeout(frontendImprovement,20); // hell why not.
return;
}else{
console.log("ajax: boring, no real new data");
setTimeout(frontendImprovement,1);
}
if( !$('.item #name').length){
console.log( "THEME JS - got device data, but no items (#name) loaded onto the page yet." );
} else if( $('.item td#name').length != $('.item td.name').length){
console.log("THEME JS - there are items on the page, and they need to be upgraded");
} else {
console.log("THEME JS - as many items have #name as .name");
}
// EXPERIMENT use object watcher to check if domoticz updates the timestamp.
//console.log("lastUpdateWatcherisRunning = " + lastUpdateWatcherisRunning);
console.log("last update time: " + $.LastUpdateTime);
if(lastUpdateWatcherisRunning === false && typeof $.LastUpdateTime !== "undefined"){
lastUpdateWatcherisRunning = true;
console.log("+++ inside, starting lastUpdate watcher");
watch($, "LastUpdateTime", function(){
console.log("LastUpdateTime: Improving.");
console.log("__//lastUpdateWatcher__");
//frontendImprovement();
});
}
// EXPERIMENT - watch the incoming items for html change. This is very useful for the weather and temperature pages, which completely reset the html when an update comes in.
//if( currentPage == "dashboard" || lastUpdateWatcherisRunning === false){
//console.log("MUTATION OBSERVER to the resque.");
// we have good data, so let's put an observer in place to check if these items' html changes, and then immediately fix it.
if(typeof xhr.responseJSON.result !== "undefined" ){
console.log("type of observerCanary");
console.log(typeof observerCanary);
// good data means that the canary, if it existed, has to go.
if(typeof observerCanary === "undefined"){
console.log("canary undefined.");
observerCanary = new window.MutationObserver(function( mutations ) {
console.log("canary mutationobserver: mutationslength: " + mutations.length);
console.log(mutations);
console.log("mutationobserver: disconnecting observerCanary on dashboard after first hit, and starting improvement");
observerCanary.disconnect();