-
Notifications
You must be signed in to change notification settings - Fork 3
/
nutrition.js
1140 lines (1008 loc) · 40.5 KB
/
nutrition.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
/**
Myfitnesspal Reports Bookmarklet Copyright 2013 Steven Irby
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* @file
* @author Steven Irby
* @email "Steven Irby" [[email protected]]
* @email "Moises Romero" [[email protected]]
* @since 2013
* @version 2
* @copyright Copyright 2013 Steven Irby
*/
// TODO - re-write time!
// - if something fails to download, try again for 2 more times, then give up,
// and show message saying, sorry didn't download
// - re-write so everything is asyncronous, so one data is downloaded, graph
// it. No waiting around for all the data to download. Lame.
// - add new default to drop-down "this week" starting from Monday.
(function () {
/**
* add method to Date for adding days
* @memberof Date.prototype
* @param days
* @returns {Date}
*/
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf())
date.setDate(date.getDate() + days);
return date;
};
/**
* @memberof Date.prototype
* @param days
* @returns {Date}
*/
Date.prototype.removeDays = function(days) {
var date = new Date(this.valueOf())
date.setDate(date.getDate() - days);
return date;
};
/**
* add script to the page
* @param src
* @param cb
*/
function addScript(src, cb) {
var script = document.createElement('script');
script.src = src;
document.documentElement.appendChild(script);
script.onload = function() {
if (typeof(cb) === 'function') {
cb();
}
};
}
/**
* add script to the page
* @param src
* @param cb
*/
function addLink(src, cb) {
var link = document.createElement('link');
link.href = src;
link.type = "text/css";
link.rel = "stylesheet";
document.getElementsByTagName('head')[0].appendChild(link);
}
/**
* Main Report Class
* @constructor
*/
function Report() {
/**
* Init script
*/
this.init = function(){
this.days = 364;
this.dates = [];
this.allGraphs = [];
this.segments = {
nutrition: [
'Net Calories',
'Calories',
'Carbs',
'Fat',
'Protein',
'Saturated Fat',
'Polyunsaturated Fat',
'Monounsaturated Fat',
'Trans Fat',
'Cholesterol',
'Sodium',
'Potassium',
'Fiber',
'Sugar',
'Vitamin A',
'Vitamin C',
'Iron',
'Calcium'
],
fitness: [
'Calories Burned',
'Exercise Minutes'
],
progress: [
'1'
]
};
this.dfds = [];
// add modal markup to page
var modal = [
'<div class="modal"><h1>Generating Report Page</h1><h2>Please wait...</h2><h3>Downloading data for: <span></span></h3>',
'</div>'
],
markup = [
'<div class="main">',
' <h1>Your Progress at a Glance</h1>',
' <div class="weight"><h4>Weight:</h4> <a href="#" title=""><h4 class="weightNumber"> </h4></a> <span class="arrow"> </span>',
' <sub><a href="#" title="This compares your current weight to your last weight in.">What\'s this?</a></sub>',
' </div>',
' <div class="calories"><h4>Net Calorie Average so far this week:</h4> <a href="#" title=""><h4 class="caloriesNumber"> </h4></a> <span class="arrow"> </span>',
' <sub><a href="#" title="This compares this weeks average with the an average from the last four weeks; before this week. This assumes you are trying to lose weight, not gain. :)">What\'s this?</a></sub>',
' </div>',
'</div>',
'<hr style="width: 600px;"><br/>'
],
me = this;
$('body').append($(modal.join('')));
this.cleanDom();
$('#content').append($(markup.join('')));
$( document ).tooltip();
this.showModal();
this.createDates();
this.generateData();
// wait for all the data before continuing on
// TODO - what if there is an error?
$.when.apply($, this.dfds).always(function () {
me.setWeightTrend();
me.setCarloriesTrend();
me.addMasterGraph();
me.addGraphs();
me.hideModal();
me.zoomAllGraphs();
});
return this;
};
this.showModal = function () {
$('body').addClass('showModal');
};
this.hideModal = function () {
$('body').removeClass('showModal');
$('.main').show();
};
/**
* generate list of dates for number of days
*/
this.createDates = function () {
var startDate,
stopDate,
currentDate,
date = new Date();
date.setDate(date.getDate() - this.days);
startDate = date;
stopDate = new Date();
// set the dates to midnight, for better accuracy
startDate.setHours(0,0,0,0);
stopDate.setHours(0,0,0,0);
currentDate = startDate;
while (currentDate <= stopDate) {
this.dates.push(currentDate.getTime());
currentDate = currentDate.addDays(1);
}
};
/**
* generate data for graphs
*/
this.generateData = function () {
this.allData = {};
var i, fields,
x = 0, f = 0, field, key,
me = this, n;
// TODO - save data to local storage, if there is no new data to fetch....
// - not sure how to know if there is or isn't data to fetch, maybe if script is ran, within an hour of last being ran
// don't pull new data in?
// - maybe if local storage is used, I could add a message somewhere that says, clear cache or something....
// iterate over segments nutrition, fitness, "1" (really why are they using "1"!?)
for (key in this.segments) {
// iterate over the fields
if (this.segments.hasOwnProperty(key)) {
fields = this.segments[key];
// run through the fields (calories, sugar, fiber, etc.)
for (f = 0; f < fields.length; f++) {
me.allData[fields[f]] = [];
// push the chained function into a list of deferreds, so we can wait for them
// all to finsh. Of course, pass in the correct reffernces
me.dfds.push(me.fetchData(key, fields[f]).done($.proxy(function (fields, f, json) {
var data = json.data, value,
text = json.label;
$('.modal h3 span').text(text);
// get dates from first row string, and only do this once!
for (n = 0; n < me.dates.length; n++) {
if(!data[n] || data[n].total === undefined)
continue;
value = data[n].total;
me.allData[fields[f]].push([me.dates[n], value]);
}
}, this, fields, f)));
}
}
}
};
/**
* asynchronously request xml from myfitnesspal
* @param segment
* @param field
* @returns {*}
*/
this.fetchData = function (segment, field) {
var url = 'https://www.myfitnesspal.com/reports/results/';
url = url + segment + '/' + field + '/365.json'; // set this to 365 - weight loss data only comes in 7, 30, 90, and 365
return $.ajax({
type: 'GET',
url: url,
dataType: "json",
success: function (json){
return json;
}
}).fail(function () {
// TODO - retry?
});
};
/**
* clear the DOM of anything
*/
this.cleanDom = function () {
$('#content').empty();
};
/**
* set the trending weight
*/
this.setWeightTrend = function () {
// first populate the progress part
var weight = this.allData["1"].slice(-1)[0][1],
lastWeight = 0,
foundNumber = false,
direction = 'down',
color = 'green',
i = this.allData["1"].length;
// loop through years worth of weighins and find the last different one
while (i-- && !foundNumber) {
if (this.allData["1"][i][1] > 0 && this.allData["1"][i][1] !== weight) {
lastWeight = this.allData["1"][i][1];
if (lastWeight < weight) {
direction = 'up';
color = 'red';
}
foundNumber = true;
}
}
var $content = $('#content'),
tooltip = 'Was: ' + lastWeight + ' Now: ' + weight;
$content.find('.main .weight .weightNumber').text(weight);
$content.find('.main .weight .weightNumber').parent().attr('title', tooltip);
$content.find('.main .weight .arrow').addClass(direction).addClass(color);
};
/**
* set the calories trend:
* - this looks at the current weeks average calorie count,
* - against the all the previous weeks averages for the last month
*/
this.setCarloriesTrend = function () {
var d = new Date(),
day = d.getDay(), // get current day 0 - 6
thisWeeksAverage,
lastMonthAverage,
direction = 'up',
color = 'red';
// get this weeks average first
if (day > 0) {
thisWeeksAverage = this._getWeekAverage(d, d.removeDays(day));
d = d.removeDays(day);
} else {
// since it's sunday, we want the whole week
thisWeeksAverage = this._getWeekAverage(d, d.removeDays(7));
d = d.removeDays(7);
}
// well just look at the last 28 days, so four weeks
lastMonthAverage = this._getWeekAverage(d, d.removeDays(28));
var direction, color;
if (lastMonthAverage > thisWeeksAverage) {
direction = 'down';
color = 'green';
}
$('#content').find('.main .calories .caloriesNumber').text(thisWeeksAverage);
var tooltip = 'Was: ' + lastMonthAverage + ' Now: ' + thisWeeksAverage;
$('#content').find('.main .calories .caloriesNumber').parent().attr('title', tooltip);
$('#content').find('.main .calories .arrow').addClass(direction).addClass(color);
};
/**
* takes one or two date objects and returns the day for that range of dates
* @param end
* @param begin
* @returns {number|*}
* @private
*/
this._getWeekAverage = function (end, begin) {
var arr = this.allData['Net Calories'],
from = this.dates.indexOf(begin.setHours(0,0,0,0)),
to = this.dates.indexOf(end.setHours(0,0,0,0)),
data = arr.slice(from, to),
dataLength = data.length,
i, sum = 0,
average,
value;
for (i = 0; i < dataLength; i++) {
value = parseFloat(data[i][1], 10);
sum += value;
}
average = Math.round(sum / dataLength);
if (!isNaN(average)) {
return average;
}
};
/**
* Add the master graph which controls the zoom for all graphs
*/
this.addMasterGraph = function () {
this.masterGraph = new MasterGraph().init(this);
};
/**
* create a new graph object for all fields
*/
this.addGraphs = function () {
this.allGraphs.push( new LookbackGraph().init(this) );
var i, key, fields, fieldsLength;
for (key in this.segments) {
if (this.segments.hasOwnProperty(key)) {
fields = this.segments[key];
fieldsLength = fields.length;
for (i = 0; i < fieldsLength; i++) {
if (fields[i] !== '1') {
this.allGraphs.push(new SegmentGraph().init(this, fields[i]));
}
}
}
}
};
/**
* zoom all graphs to specified range
*/
this.zoomAllGraphs = function () {
var i,
range = this.range,
graphsLength = this.allGraphs.length,
graph;
// loop though all graphs, and trigger the selected event, so graph
// gets updated with new subset of data.
for (i = 0; i < graphsLength; i++) {
graph = this.allGraphs[i];
// turn zooming mode on so plotselected does everything
graph.zooming = true;
graph.$graph.trigger('plotselected', [range]);
graph.zooming = false;
}
};
}
/**
* Base Graph
* @constructor
*/
function Graph(){
/**
* Initializes the graph
* @returns {Graph}
*/
this.init = function(){
// needs to be overridden
return this;
};
/**
* Renders the graph
* @returns {Graph}
*/
this.graphData = function(){
// needs to be overridden
return this;
}
}
/**
* master graph controls zooming for all graphs
* @constructor
* @extends {Graph}
*/
function MasterGraph(){
/**
* Initializes the graph
* @param parent
* @returns {MasterGraph}
*/
this.init = function(parent){
var markup = [
'<div class="master">',
' <div class="dateRange"></div>',
' <div class="masterGraph"></div>',
' <div class="masterGraphDescription">',
' <h3>Click and drag - to select a range for all graphs</h3>',
' <select id="daySelect">',
' <option value="-1">Select Range</option>',
' <optgroup label="Days">',
' <option value="7">7 days</option>',
' <option value="14">14 days</option>',
' <option value="21">21 days</option>',
' <option value="28">28 days</option>',
' </optgroup>',
' <optgroup label="Months">',
' <option value="1m">1 month</option>',
' <option value="2m">2 month</option>',
' <option value="3m">3 month</option>',
' <option value="4m">4 month</option>',
' <option value="5m">5 month</option>',
' <option value="6m">6 month</option>',
' </optgroup>',
' <optgroup label="Year">',
' <option value="365">Whole year</option>',
' </optgroup>',
' </select>',
' </div>',
'</div>'
];
this._parent = parent;
this.daysShown = 7; // default for how many days to show when page loads
this.$container = $(markup.join(''));
this.chartOptions = {
grid: {
show: true,
aboveData: false,
axisMargin: 0,
borderWidth: 0,
clickable: false,
hoverable: false,
autoHighlight: false,
mouseActiveRadius: 50
},
xaxes: [
{mode: "time", labelWidth: 30}
],
yaxes: [
{min: 0, show: false},
{show: false}
],
series: {curvedLines: {active: true}},
selection: {
mode: "x"
},
legend: {
show: false
}
};
this.graphData();
this.bindEvents();
return this;
};
/**
* graph the data
*/
this.graphData = function () {
var field = 'Net Calories';
this.series = [{
data : this._parent.allData[field],
yaxis: 1
},
{
data : this._parent.allData['1'],
yaxis: 2
}
];
$('#content').append(this.$container);
this.$graph = this.$container.find('.masterGraph');
this.plot = $.plot(this.$graph, this.series, this.chartOptions);
this.makeSelection();
this.$container.find('#daySelect').val(this.daysShown);
this.bindEvents();
};
/**
* make a selection on the master graph for number of days shown
*/
this.makeSelection = function () {
var xaxis = {
xaxis: this._getDatesFromRange(this.daysShown)
};
this.plot.setSelection(xaxis);
this._parent.range = xaxis; // keep track of current data range for all graphs
this._updateDateRange();
};
/**
* update the range so user can see date range currently being shown
* @private
*/
this._updateDateRange = function () {
var _from = new Date(this._parent.range.xaxis.from).setHours(0,0,0,0),
_to = new Date(this._parent.range.xaxis.to).setHours(0,0,0,0),
from = new Date(_from).toDateString(),
to = new Date(_to).toDateString(),
str = 'Selected Dates: ' + from + ' - ' + to;
this.$container.find('.dateRange').text(str);
};
/**
* take a number of days, and return the two dates
* @param days
* @returns {{from, to}}
* @private
*/
this._getDatesFromRange = function (days) {
var now = new Date(),
d = new Date(),
day = d.getDay(),
from = d.removeDays(days).setHours(0,0,0,0),
to = now.setHours(0,0,0,0);
// if this is set to months, then get that date instead
if (('' + days).indexOf('m') > -1) {
from = d.setMonth(d.getMonth() - parseInt(days.replace(/m/g, ''), 10));
from = new Date(from).setHours(0,0,0,0);
}
return {from: from, to: to};
};
/**
* bind events for:
* - selecting the master graph
* - selecting a range from the drop down
*/
this.bindEvents = function () {
var me = this;
this.$container.find('#daySelect').unbind('change').bind('change', function () {
var value = $(this).val();
if (value !== '-1') {
// if not a month, use the value for the days
me.dropdownChange = true;
me.daysShown = value;
me.makeSelection();
me._parent.zoomAllGraphs();
me.dropdownChange = false;
}
});
this.$graph.bind('plotselecting', function (event, ranges) {
if ($.type(ranges) !== 'null') {
me._parent.range = {
xaxis: {from: ranges.xaxis.from, to: ranges.xaxis.to}
}
me._updateDateRange();
}
});
this.$graph.bind('plotselected', function (event, ranges, dropdown) {
if ($.type(ranges) !== 'null') {
me._parent.range = {
xaxis: {from: ranges.xaxis.from, to: ranges.xaxis.to}
}
me._parent.zoomAllGraphs();
me._updateDateRange();
// is this being fired because of the drop down change or a chart selection?
// if it's not because of the drop down, then chance the drop down
if (!me.dropdownChange) {
me.$container.find('#daySelect').val(0);
}
}
});
};
}
MasterGraph.prototype = new Graph();
MasterGraph.prototype.constructor = MasterGraph;
/**
* Segment Graph
* @constructor
* @extends {Graph}
*/
function SegmentGraph() {
/**
* Initializes the graph giving the ability to override the method
* @param parent
* @param field
* @param {String} [opt_label] The optional label (hard-coded)
* @param {Object} [opt_chartOptions] The chart options
* @returns {SegmentGraph}
*/
this.init = function(parent, field, opt_label, opt_chartOptions){
var markup = [
'<div class="graphContainer"> ',
' <h2></h2> <h3>Average: <span></span></h3>',
' <div class="selectionContainer"><p>You selected: <span class="selection"></span></p></div>',
' <div class="zoomContainer"><button class="zoom" type="button">Zoom in</button><a href="#" title="Click this to start zooming only for this graph. Just click and drag a region on the graph to select a custom range of dates.">What\'s this?</a></div>',
' <div class="zoomContainer"><button class="reportButton pauseZoom" type="button">Pause Zoom</button><a href="#" title="Click this to pause the zooming, so you can click on a date to see your diary for that day.">What\'s this?</a></div> ',
' <div class="zoomContainer"><button class="reportButton resumeZoom" type="button">Resume Zoom</button><a href="#" title="Click this to zoom again.">What\'s this?</a></div> ',
' <div class="zoomContainer"><button class="reportButton cancelZoom" type="button">Reset zoom</button><a href="#" title="Click this to go back to the default zoom. (What the main graph at the top is set to show.)">What\'s this?</a></div> ',
' <div class="graph"></div>',
' <span class="clickdata"></span>',
' <div class="legend"></div>',
'</div> ',
];
this._parent = parent; // lazily pass in parent
this.field = field;
this.zooming = false;
this.$container = $(markup.join(''));
this.$container.find('h2').text(opt_label || field);
this.setAverage();
this.previousHoverPoint = null;
this.chartOptions = $.extend(true, {
grid: {
aboveData: false,
axisMargin: 0,
borderWidth: 0,
clickable: true,
hoverable: true,
autoHighlight: true,
mouseActiveRadius: 50
},
xaxes: [
{mode: "time", labelWidth: 30},
],
yaxes: [
{min: 0},
{position: 'right', labelWidth: 30}
],
series: {curvedLines: {active: true}},
selection: {
mode: "x"
},
legend: {
show: true,
position: 'nw',
container: this.$container.find('.legend'),
backgroundColor: null
}
}, opt_chartOptions);
this.graphData();
return this;
};
/**
* get the average for the current range of data shown on graph
* @param data
* @returns {number|*}
*/
this.setAverage = function (data) {
var data = data || this._parent.allData[this.field],
dataLength = data.length,
i, sum = 0,
average,
value;
for (i = 0; i < dataLength; i++) {
value = parseFloat(data[i][1], 10);
sum += value;
}
average = Math.round(sum / dataLength);
if (!isNaN(average)) {
this.$container.find('h3 span').text(average);
}
return average
};
/**
* add graphs to the page
* @param {Object[]} [opt_series]
*/
this.graphData = function (opt_series) {
this.series = opt_series || [
{
label: this.field,
data : this._parent.allData[this.field],
lines: { show: true, lineWidth: 3},
curvedLines: {apply:true},
yaxis: 1
},
{
label: 'Weight Loss',
data : this._parent.allData['1'],
lines: { show: true, lineWidth: 3},
curvedLines: {apply:true},
yaxis: 2
}
];
if (!this._parent.allData[this.field].length) {
var $msg = ' <span>Opps! Failed to download this data. This happens because myfitnesspal took to long to send this data.</span>';
this.$container.find('h2').after($msg);
}
$('#content').append(this.$container);
this.$graph = this.$container.find('.graph');
this.plot = $.plot(this.$graph, this.series, this.chartOptions);
this._fixUpLegend();
this.bindEvents();
};
/**
* fix legend that breaks because of funky css on the page
* @private
*/
this._fixUpLegend = function () {
this.$container.find('table').css('width', 'auto');
this.$container.find('td').css({'border-bottom' : '0', 'vertical-align' : 'middle'});
this.$container.find('.legendLabel').css('padding-left', '10px');
};
/**
* @param dateObj
* @param backwards
* @returns {string}
*/
this.convertDateToString = function (dateObj, backwards) {
var d = new Date(parseInt(dateObj, 10)),
month = d.getMonth() + 1,
day = d.getDate(),
year = d.getFullYear(),
date = month + "-" + day + "-" + year;
if (backwards) {
date = year + "-" + month + "-" + day;
}
return date;
};
/**
* bind all graph events
*/
this.bindEvents = function () {
var me = this;
this.$container.find('.zoomContainer:eq(0)').show();
this.$container.find('button').bind('click', $.proxy(me._zoomButton, me));
this.$graph.bind('plothover', $.proxy(me._plotHover, me));
this.$graph.bind('plotclick', $.proxy(me._plotclick, me));
this.$graph.bind('plotselecting', $.proxy(me._plotselecting, me));
this.$graph.bind('plotselected', $.proxy(me._plotselected, me));
};
/**
* hide and show zoom buttons
* @param event
* @private
*/
this._zoomButton = function (event) {
var $clicked = $(event.currentTarget);
if ($clicked.hasClass('zoom')) {
// - turn on zooming
// - hide the zoom button and show the cancel zoom button
this.zooming = true;
this.$container.find('.pauseZoom').show().parent().show();
this.$container.find('.cancelZoom').show().parent().show();
// show the selection range
this.$container.find('.selectionContainer').show();
$clicked.hide().parent().hide();
} else if ($clicked.hasClass('pauseZoom')) {
// pause the zooming
this.zooming = false;
this.$container.find('.resumeZoom').show().parent().show();
$clicked.hide().parent().hide();
} else if ($clicked.hasClass('resumeZoom')) {
// resume zooming
this.zooming = true;
this.$container.find('.pauseZoom').show().parent().show();
$clicked.hide().parent().hide();
} else {
// - turn off zooming
// - show the zoom button
// - reset the graph
this.$container.find('.selectionContainer').hide();
this.$container.find('.zoom').show().parent().show();
this.zooming = false;
this.plot = $.plot(this.$graph, this.series, this.chartOptions);
this.setAverage();
this._fixUpLegend();
$clicked.hide().parent().hide();
this.$container.find('.pauseZoom').hide().parent().hide();
this.$container.find('.resumeZoom').hide().parent().hide();
}
};
/**
* show the tooltip when you hover over points on the graph
* @param event
* @param pos
* @param item
* @private
*/
this._plotHover = function (event, pos, item) {
if (item) {
if (this.previousHoverPoint != item.dataIndex) {
this.previousHoverPoint = item.dataIndex;
$("#tooltip").remove();
var x = item.datapoint[0].toFixed(2),
date = this.convertDateToString(x),
text = 'Click to see what you ate on this date: ' + date;
if (this.zooming) {
text = '* Pause / Reset zooming to click on a date! *';
}
this._showTooltip(item.pageX, item.pageY, text);
}
} else {
$("#tooltip").remove();
this.previousHoverPoint = null;
}
};
/**
* open new page when point is clicked
* @param event
* @param pos
* @param item
* @private
*/
this._plotclick = function (event, pos, item) {
if (!this.zooming) {
if (item) {
var x = item.datapoint[0].toFixed(2),
date = this.convertDateToString(x, true);
console.log('https://www.myfitnesspal.com/food/diary?date=' + date);
window.open('https://www.myfitnesspal.com/food/diary?date=' + date, '_blank');
}
}
};
/**
* when selecting a range to zoom in on, show the selected date range
* @param event
* @param ranges
* @private
*/
this._plotselecting = function (event, ranges) {
if (this.zooming && $.type(ranges) !== 'null') {
var from = this.convertDateToString(ranges.xaxis.from.toFixed(1)),
to = this.convertDateToString(ranges.xaxis.to.toFixed(1)),
newData;
this.$container.find('.selection').text(from + " to " + to);
newData = this._getRangeOfData(ranges.xaxis.from, ranges.xaxis.to);
this.setAverage(newData);
} else {
// not zooming, so clear the selection
this.plot.clearSelection();
}
};
/**
* once an area on the graph has been selected, redraw the graph
* @param event
* @param ranges
* @private
*/
this._plotselected = function (event, ranges) {
var newData;
if (this.zooming) {
this.plot = $.plot(this.$graph, this.series, $.extend(true, {}, this.chartOptions, {
xaxis: {
min: ranges.xaxis.from,
max: ranges.xaxis.to
}
}));
// sign... isn't that cute, its returning a random *time* in a day, where
// the user selected! Not an exact date whole date. So get the full
// nearest date to where they were selecting.
newData = this._getRangeOfData(ranges.xaxis.from, ranges.xaxis.to);
this.setAverage(newData);
this._fixUpLegend();
} else {
// not zooming, so clear the selection
this.plot.clearSelection();
}
};
/**
* take in range of and convert to dates, for range of data
* @param axisFrom
* @param axisTo
* @returns {Array.<T>|string|Blob|ArrayBuffer}
* @private
*/
this._getRangeOfData = function (axisFrom, axisTo) {
var from = this._parent.dates.indexOf(this._getFullDate(axisFrom)),
to = this._parent.dates.indexOf(this._getFullDate(axisTo)),
data = this._parent.allData[this.field].slice(from, to);
return data;
};
/**
* get the current date from some random time and date; at midnight
* @param dateTime