-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathelroi.js
1876 lines (1560 loc) · 67.4 KB
/
elroi.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
(function($) {
var elroi = function(element, dataSeries, graphOptions, tooltips) { return new e(element, dataSeries, graphOptions, tooltips); };
elroi.fn = {};
window.elroi = elroi;
/**
* Creates an graph in a given empty div
* Usage: see /test/elroi.js for an example usage (this is commented out currently due to WebTestJS erroring out)
* @param args An object containing
* $el - jQ DOM element to insert the graph into
* data - An array of series objects containing series data, and series options
* options - options for the graph
* @return graph The graph object
* @return {function} draw Method to draw the graph
* @return {function} update Updates the graph with new data
*/
function e(element, dataSeries, graphOptions, tooltips) {
var defaults = {
animation: true,
colors: ['#99cc33', '#ffee44', '#ffbb11', '#ee5500', '#33bbcc', '#88ddee'],
labelDateFormat: 'auto',
errorMessage : false,
labelWidth : 'auto',
flagOffset : 5,
skipPointThreshhold : 18,
grid : {
show: true,
showBaseline: true,
numYLabels : 5
},
axes : {
x1 : {
customXLabel: false,
id : 'x1',
type: 'date',
show : true,
labels : [],
seriesIndex : 0 // By default, the axis values are derived from the first series of data
},
x2 : {
customXLabel: false,
id : 'x2',
type : 'text',
show : false,
labels : [],
seriesIndex : 0
},
y1 : {
id : 'y1',
show : true,
unit: '',
topUnit: '',
prefixUnit: false,
seriesIndex : 0
},
y2 : {
id : 'y2',
show : false,
unit: '',
topUnit: '',
prefixUnit: false,
seriesIndex: 0
}
},
tooltip: {
formatter : function(tip){return tip},
show: true,
width: 120
},
seriesDefaults: {
type: 'line',
showPoints: false,
fillPoints: false,
labelPoints: false,
animatePoints : false,
pointStroke: true,
interpolateNulls : false,
maxYValue : 'auto',
minYValue : 0,
unit: '',
pointLabelUnits: ''
},
bars : {
highlightBorderWidth : 2,
highlightBorderOpacity : 0.8,
highlightColor : '#ccc',
flagPosition: 'exterior' // exterior or interior - the label appears above or inside the bar
},
lines : {
width : 2,
opacity : 0.8,
fillOpacity : 0.2,
pointRadius : 3,
pointStrokeWidth : 2,
highlightStrokeWidth : 4,
highlightRadius : 6,
highlightOpacity : 0.8
},
padding: {top:15, right:20, bottom:18, left:50}
};
var $el = $(element)
.addClass('elroi'),
$paper = $('<div></div>')
.addClass('paper')
.appendTo($el),
options = $.extend(true, {}, defaults, graphOptions);
var width = $paper.width() || $el.width(),
height = $paper.height() || $el.height();
var graph = elroi.fn.init({
padding : options.padding,
labelLineHeight: 12,
width: width,
height: height,
allSeries: dataSeries,
$el: $el,
paper: Raphael($paper.get(0), width, height),
options: options,
tooltips: tooltips
});
var html = '<div class="elroi-tooltip"><div class="elroi-tooltip-content"></div></div>';
graph.$tooltip = $(html);
graph.$tooltip.width(graph.options.tooltip.width).appendTo($el.find('.paper')).addClass('png-fix');
$el.mouseleave(function() {
graph.$tooltip.css('left', -10000);
});
/**
* Draws the graph grid, any error messaging, and any charts and graphs for all data
*/
function draw() {
var isGridDrawn = false;
if(graph.options.errorMessage) {
var $errorMsg = $('<div class="elroi-error">' + graph.options.errorMessage + '</div>')
.addClass('alert box');
graph.$el.find('.paper').prepend($errorMsg);
}
if(!graph.allSeries.length) {
elroi.fn.grid(graph).draw();
}
$(graph.allSeries).each(function(i) {
if(!isGridDrawn && graph.seriesOptions[i].type != 'pie') {
elroi.fn.grid(graph).draw();
isGridDrawn = true;
}
var type = graph.seriesOptions[i].type;
elroi.fn[type](graph, graph.allSeries[i].series, i).draw();
});
}
/**
* Deletes all of the Raphael objects, and removes the axes from the graph
*/
function clearGraph() {
graph.paper.clear();
graph.$el.find('ul').remove();
graph.$el.find('.elroi-point-flag').remove();
graph.$el.find('.elroi-point-label').remove();
}
/**
* Redraws the graph with new data
* @param newData A new data object to be graphed
*/
function update(newData) {
clearGraph();
graph.allSeries = newData;
draw();
}
draw();
return {
graph: graph,
draw: draw,
update: update
};
}
})(jQuery);
(function(elroi, $) {
/**
*
* @param {String}
The format can be combinations of the following:
d - day of month (no leading zero)
dd - day of month (two digit)
D - day name short
DD - day name long
m - month of year (no leading zero)
mm - month of year (two digit)
M - month name short
MM - month name long
y - year (two digit)
yy - year (four digit)
h - hour (single digit)
hh - hour (two digit)
H - hour (military, no leading zero)
HH - hour (military, two digit)
nn - minutes (two digit)
a - am/pm
* @param value The date to format
* @param options Options for the date format; includes ignore zero minutes, and am/pm
* @return {String} The formatted date
*/
function formatDate(format, value, options) {
var DAY_NAMES_SHORT = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],
DAY_NAMES_LONG = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],
MONTH_NAMES_SHORT = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
MONTH_NAMES_LONG = ['January','Feburary','March','April','May','June','July','August','September','October','November','December'],
date = new Date(value),
dayNamesShort,
dayNamesLong,
monthNamesShort,
monthNamesLong,
formattedDate = "",
thisChar,
isDoubled,
i;
if (!format) {
return '';
}
options = options || {};
dayNamesShort = options.dayNamesShort || DAY_NAMES_SHORT;
dayNamesLong = options.dayNamesLong || DAY_NAMES_LONG;
monthNamesShort = options.monthNamesShort || MONTH_NAMES_SHORT;
monthNamesLong = options.monthNamesLong || MONTH_NAMES_LONG;
for(i = 0; i < format.length; i++) {
thisChar = format.charAt(i);
isDoubled = i < format.length && format.charAt(i + 1) === thisChar;
switch (thisChar) {
case 'd':
if(isDoubled) {
if(date.getDate() < 10) {
formattedDate += '0'
}
formattedDate += date.getDate();
} else {
formattedDate += date.getDate();
}
break;
case 'D':
formattedDate += isDoubled ? dayNamesLong[date.getDay()] : dayNamesShort[date.getDay()];
break;
case 'm':
if(isDoubled) {
if(date.getMonth() < 10) {
formattedDate += '0'
}
formattedDate += date.getMonth() + 1;
} else {
formattedDate += date.getMonth() + 1;
}
break;
case 'M':
formattedDate += isDoubled ? monthNamesLong[date.getMonth()] : monthNamesShort[date.getMonth()];
break;
case 'y':
if(isDoubled) {
formattedDate += date.getFullYear();
} else {
if(date.getFullYear() % 100 < 10){
formattedDate += 0;
}
formattedDate += date.getFullYear() % 100;
}
break;
case 'h':
if(isDoubled && date.getHours() % 12 < 10) {
formattedDate += "0";
}
formattedDate += date.getHours() === 0 ? 12
: date.getHours() > 12 ? date.getHours() - 12
: date.getHours();
break;
case 'H':
formattedDate += isDoubled && date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
break;
case 'n':
formattedDate += date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
break;
case 'a':
formattedDate += date.getHours() < 12 ? 'am' : 'pm';
break;
default:
formattedDate += thisChar;
}
if(isDoubled) {
i++;
}
}
return formattedDate;
}
elroi.fn.formatDate = formatDate;
})(elroi, jQuery);
(function(elroi, $) {
var helpers = {
/**
* Checks and sees if the graph has any data to actually display
* @param {Array} allSeries An array of all of the series in the graph
* @returns {Boolean} hasData Does the graph have data
*/
hasData : function(allSeries){
var hasData = true;
hasData = allSeries !== undefined
&& allSeries.length
&& allSeries[0] !== undefined
&& allSeries[0].series !== undefined
&& allSeries[0].series.length;
$(allSeries).each(function(i) {
if(!this || !this.series[0]) {
hasData = false;
}
});
return !!hasData;
},
/**
* Iterates through all of the data values in a single series, and puts them into an array depending on the series type
* @param {Array} allSeries All of the series in the graph
* @param {Array} seriesOptions The set of series options for the graph
* @return {Array} dataValues An array of the data values for a series
*/
getDataValues : function(allSeries, seriesOptions) {
var dataValuesSet = [];
if(!elroi.fn.helpers.hasData(allSeries)){
return [[0]];
}
$(allSeries).each(function(i) {
var dataValues = [],
series = allSeries[i].series;
$(series).each(function(j) {
var singleSeries = series[j];
$(singleSeries).each(function(k) {
if (j === 0 || seriesOptions[i].type != 'stackedBar') {
dataValues.push(+this.value);
}
else {
dataValues[k] += this.value;
}
});
});
dataValuesSet.push(dataValues);
});
return dataValuesSet;
},
/**
* Iterates a data set and returns the sum of all values
* @param {Array} dataSet
* @return {Int} sum
*/
sumSeries : function(allData) {
var sums = [];
$(allData).each(function(i){
var singleSeries = this,
sum = 0;
$(singleSeries).each(function (j){
sum += this;
});
sums.push(sum);
});
return sums;
},
/**
* Goes through each data point in every series and figures out if any of them have point flags
* @param {Array} allSeries All of the series to be shown on the graph
* @returns {Boolean} hasPointFlags
*/
hasPointFlags: function(allSeries){
var hasPointFlags = false;
$(allSeries).each(function(i){
$(allSeries[i].series).each(function(j){
$(allSeries[i].series[j]).each(function(k){
if (allSeries[i].series[j][k].pointFlag) {
hasPointFlags = true;
}
});
});
});
return hasPointFlags;
},
/**
* Determines minimum values for each datavalues set
* @param {Object} dataValuesSet
* @param {Object} seriesOptions
* @returns {Array} The array of minumum values to use in the scaling & axes
*/
minValues : function(dataValuesSet, seriesOptions) {
var minVals = [];
$(dataValuesSet).each(function(i) {
minVals.push(seriesOptions[i].minYValue);
});
return minVals;
},
/**
* Gets the maximum values for each series
* @param {Array} dataValuesSet
* @param {Array} seriesOptions
* @param {Object} graph
* @returns {Array} The array of each values to use for scales & axes
*/
maxValues : function(dataValuesSet, seriesOptions, graph) {
var maxVals = [];
$(dataValuesSet).each(function(i) {
if (seriesOptions[i].maxYValue == 'auto') {
maxVals.push(Math.max.apply(Math, dataValuesSet[i]));
} else {
maxVals.push(seriesOptions[i].maxYValue);
}
});
/**
* Helper function to figure out of we should distort the maximum values to make room for flags, messages, et
* @returns {Number} The scale to multiply against each of the max values to make some room
*/
function distortMaxValuesBy() {
var pixelsNeeded = 0;
if(graph.options.errorMessage) {
var $errorMsg = $('<div id="graph-error">' + graph.options.errorMessage + '</div>').addClass('alert box').appendTo(graph.$el.find('.paper'));
pixelsNeeded += $errorMsg.outerHeight() + $errorMsg.position().top * 2;
$errorMsg.remove();
}
var hasPointFlags = elroi.fn.helpers.hasPointFlags(graph.allSeries);
if (hasPointFlags && graph.options.bars.flagPosition != 'interior') {
var $pointFlag = $('<div class="point-flag"><div class="flag-content">Test flag</div></div>').appendTo(graph.$el.find('.paper'));
pixelsNeeded += $pointFlag.outerHeight();
$pointFlag.remove();
}
if(graph.options.axes.x2.show) {
var $x2 = $('<ul class="x-ticks x2"><li>test axis</li></ul>').appendTo(graph.$el);
pixelsNeeded += $x2.find('li').outerHeight() + graph.labelLineHeight;
$x2.remove();
}
return 1 + pixelsNeeded/graph.height;
}
var scaleDistortion = distortMaxValuesBy();
maxVals = $.map(maxVals, function(val){
return !!val ? val * scaleDistortion : 1;
});
return maxVals;
},
/**
* Sets up an array of series specific options for each series to graph
* @param {Array} allSeries An array of series, each with their own options
* @param defaults Default options to merge in
* @returns {Array} seriesOptions
*/
seriesOptions : function(allSeries, defaults) {
var seriesOptions = [];
if(! allSeries.length) {
return [defaults];
}
$(allSeries).each(function(i) {
seriesOptions.push($.extend({}, true, defaults, allSeries[i].options));
});
return seriesOptions;
},
buildDefaultTooltips : function(allSeries) {
var tooltips = [];
$(allSeries).each(function(i) {
$(this.series).each(function(j){
$(this).each(function(k){
if(tooltips[k]) {
tooltips[k] += "<br/>" + this.value;
} else {
tooltips[k] = "" + this.value;
}
});
});
});
return tooltips;
},
determineDateFormat : function(allSeries){
var firstPoint,
lastPoint,
firstPointDate,
lastPointDate,
numPoints = allSeries[0].series[0].length,
MILLISECONDS_PER_DAY = 86400000,
MILLISECONDS_PER_MONTH = 2678400000, // 31 day month
MILLISECONDS_PER_YEAR = 31536000000,
averageGap,
format;
firstPoint = allSeries[0].series[0][0];
firstPointDate = new Date(firstPoint.endDate || firstPoint.date);
lastPoint = allSeries[0].series[0][numPoints-1];
lastPointDate = new Date(lastPoint.endDate || lastPoint.date);
averageGap = (lastPointDate - firstPointDate);
if(averageGap <= MILLISECONDS_PER_DAY) {
format = "h:nna";
} else if(averageGap < MILLISECONDS_PER_MONTH) {
format = "M, d";
} else if(averageGap < MILLISECONDS_PER_YEAR){
format = "M";
} else {
format = "YY";
}
return format;
},
dataCleaner : function(allSeries) {
var cleanData = [],
temp,
i;
if(typeof(allSeries[0]) == "number") {
temp = { series: [[]]};
for(i=0; i<allSeries.length; i++) {
temp.series[0].push({value: allSeries[i]});
}
cleanData.push(temp);
} else {
if(!(allSeries instanceof Array)) {
if(!(allSeries.series[0] instanceof Array)) {
temp = { series: [], options: {}};
temp.series.push(allSeries.series);
temp.options = allSeries.options || {};
cleanData.push(temp);
} else {
cleanData = allSeries;
}
} else if (!(allSeries[0] instanceof Array)){
if(allSeries[0].series === undefined) {
temp = { series: [] };
temp.series.push(allSeries);
cleanData.push(temp);
} else {
cleanData = allSeries;
}
} else {
cleanData = allSeries;
}
}
return cleanData;
}
};
/**
* Goes over the data series passed in, and sets things up for use by other elroi functions.
* This adds the following properties to the graph object:
* numPoints - The number of points on the graph
* showEvery - This is used to suppress some points on the line graph, and some labels on the x-axis
* xTicks - The number of x ticks on the graph per pixel
* yTicks - an array of y ticks on the graph per pixel, per series
* seriesOptions - an array of options per series, merged with the defaults
* maxVals - an array of the maximum values of each series
* minVals - an array of the minimum values of each series
*
* @see elroi
* @param graph The initial graph object
* @return graph The updated graph object containing the new values listed above
*/
function init(graph) {
var seriesOptions,
maxVals,
minVals,
dataValuesSet,
sums,
hasData;
graph.allSeries = elroi.fn.helpers.dataCleaner(graph.allSeries);
seriesOptions = elroi.fn.helpers.seriesOptions(graph.allSeries, graph.options.seriesDefaults);
maxVals = [];
minVals = [];
dataValuesSet = elroi.fn.helpers.getDataValues(graph.allSeries, seriesOptions);
sums = elroi.fn.helpers.sumSeries(dataValuesSet);
hasData = elroi.fn.helpers.hasData(graph.allSeries)
if(graph.options.labelDateFormat === 'auto') {
graph.options.labelDateFormat = elroi.fn.helpers.determineDateFormat(graph.allSeries);
}
var numPoints = !hasData ? 1 : graph.allSeries[0].series[0].length;
var showEvery = graph.options.showEvery ||
((numPoints > graph.options.skipPointThreshhold) ? Math.round(numPoints / graph.options.skipPointThreshhold) : 1);
var xTick = (graph.width - graph.padding.left - graph.padding.right) / numPoints;
var yTicks = [];
maxVals = elroi.fn.helpers.maxValues(dataValuesSet, seriesOptions, graph);
minVals = elroi.fn.helpers.minValues(dataValuesSet, seriesOptions);
$(dataValuesSet).each(function(i) {
var avalaibleArea = graph.height - graph.padding.top - graph.padding.bottom,
dataRange = maxVals[i] + Math.abs(minVals[i]);
yTicks.push(avalaibleArea/dataRange);
});
var labelWidth =
graph.options.labelWidth == 'auto' ?
(graph.width - graph.padding.left - graph.padding.right) / (numPoints/showEvery) - 2 : //padding of 2px between labels
graph.options.labelWidth;
var barWidth = xTick * 2/3; // 2/3 is magic number for padding between bars
var barWhiteSpace = (xTick * 1/3) / 2;
$.extend(graph, {
hasData : hasData,
seriesOptions: seriesOptions,
dataValuesSet: dataValuesSet,
maxVals: maxVals,
minVals: minVals,
sums: sums,
numPoints: numPoints,
showEvery: showEvery,
xTick: xTick,
yTicks: yTicks,
labelWidth: labelWidth,
barWidth: barWidth,
barWhiteSpace: barWhiteSpace
});
if(graph.options.tooltip.show && graph.tooltips === undefined) {
graph.tooltips = elroi.fn.helpers.buildDefaultTooltips(graph.allSeries);
}
return graph;
}
elroi.fn.helpers = helpers;
elroi.fn.init = init;
})(elroi, jQuery);
(function(elroi, $){
/**
* This function creates the grid that is used by the graph
* @param {graph} graph The graph object defined by elroi
* @return {function} draw Draws the grid, x-axis, and y-axes
*/
function grid(graph){
/**
* Goes through the first series in a data set and creates a set of labels for the x-axis
* @param data All series to be graphed
* @param {String} dateFormat
* @return {Array} xLabels An array of correctly formatted labels for the x-axis
*/
function getXLabels(series, dateFormat){
var xLabels = [];
$(series).each(function(){
var startDate,
startDateFormat = dateFormat,
endDateFormat = dateFormat,
endDate,
label = '';
if(this.startDate) {
startDate = new Date(this.startDate);
}
if (this.endDate || this.date) {
endDate = this.endDate ? new Date(this.endDate) : this.date;
}
if (startDate && endDate) {
if (startDate.getMonth() == endDate.getMonth()) {
endDateFormat = endDateFormat.replace('M', '' && startDateFormat.match('M'));
}
if (startDate.getFullYear() == endDate.getFullYear() && startDateFormat.match(', yy')) {
startDateFormat = startDateFormat.replace(', yy', '');
}
}
if (startDate) {
label += elroi.fn.formatDate(startDateFormat, startDate);
}
if(startDate && endDate) {
label += " –";
}
if(endDate) {
label += elroi.fn.formatDate(endDateFormat, endDate);
label = label.replace(/\s/g, ' ');
}
xLabels.push(label);
});
return xLabels;
}
/**
* Draws the gridlines based on graph.grid.numYLabels
*/
function drawGrid(){
var i, y,
gridLine,
gridLines = graph.paper.set(),
avalaibleArea = graph.height - graph.padding.top - graph.padding.bottom;
if (graph.options.grid.show) {
for (i = 0; i < graph.options.grid.numYLabels; i++) {
y = graph.height -
i / (graph.options.grid.numYLabels - 1) * avalaibleArea -
graph.padding.bottom +
graph.padding.top;
gridLine = graph.paper.path("M0" + " " + y + "L" + graph.width + " " + y).attr('stroke', '#ddd');
gridLines.push(gridLine);
}
} else if (graph.options.grid.showBaseline) {
y = graph.height -
graph.padding.bottom +
graph.padding.top;
gridLine = graph.paper.path("M0" + " " + y + "L" + graph.width + " " + y).attr('stroke', '#ddd');
gridLines.push(gridLine);
}
graph.grid = {
lines: gridLines
};
}
/**
* Draws the x-axis
* @param axis An axis object as defined in the elroi options
*/
function drawXLabels(axis) {
var $labels, axisY;
if (axis.id == 'x1') {
axisY = graph.height;
} else if (axis.id == 'x2') {
axisY = graph.padding.top;
}
if(axis.customXLabel) {
$labels = $(axis.customXLabel);
} else {
$labels = $('<ul></ul>')
.addClass('x-ticks')
.addClass(axis.id);
$(axis.labels).each(function(i){
if(i % graph.showEvery === 0) {
var x = i * graph.xTick + graph.padding.left;
var label = (axis.labels[i].replace(/^\s+|\s+$/g, '') || '');
$('<li></li>')
.css({top: axisY, left: x})
.html(label)
.appendTo($labels);
}
});
}
$labels.find('li').each(function(){
var $label = $(this);
var x = parseInt($label.css('left'), 10) + ($label.width())/2;
$label.css({ left: x, width: graph.labelWidth });
if (axis.id == 'x2') {
$label.css( { top: axisY + $labels.height() + graph.padding.top });
}
});
$labels.appendTo(graph.$el);
}
/**
* Takes in a maximum value and a precision level, and returns an array of numbers for use in the y label
* @param {number} maxVal The maximum value in a dataset
* @param {number} precision The number of digits to show
* @returns {Array} yLabels A set of labels for the y axis
*/
function getYLabels(maxVal, minVal, precision){
var yLabels = [],
i;
for (i = 0; i < graph.options.grid.numYLabels; i++) {
var yLabel = i/(graph.options.grid.numYLabels-1) * (maxVal - minVal) + minVal;
yLabel = yLabel.toFixed(precision);
yLabels.push(yLabel);
}
return yLabels;
}
/**
* This draws either the y1 or y2 axis, depending on the series data
* @param {int} seriesDataIndex The index of the data series associated to this y-axis
* @param {number} maxVal The maximum value in the data series
* @param {number} minVal The minimum value in the data series
* @param {String} unit The units of the data
*/
function drawYLabels(maxVal, minVal, axis){
var $yLabels = $('<ul></ul>')
.addClass("y-ticks")
.addClass(axis.id);
var precision = 0,
yLabels = getYLabels(maxVal, minVal, precision),
avalaibleArea = graph.height - graph.padding.top - graph.padding.bottom;
while(containsDupes(yLabels)) {
precision++;
yLabels = getYLabels(maxVal, minVal, precision);
}
$(yLabels).each(function(i){
var yLabel = commaFormat(yLabels[i], precision);
var y = graph.height
- i / (graph.options.grid.numYLabels - 1) * avalaibleArea
- graph.padding.bottom
+ graph.padding.top
- graph.labelLineHeight;
if(i === graph.options.grid.numYLabels-1) {
yLabel = (axis.prefixUnit ? axis.topUnit : '')
+ yLabel
+ (!axis.prefixUnit ? " " + axis.topUnit : '');
} else {
yLabel = (axis.prefixUnit ? axis.unit : '')
+ yLabel
+ (!axis.prefixUnit ? " " + axis.unit : '');
}
var cssPosition;
if (axis.id == 'y1') {
cssPosition = { 'top' : y, 'left' : 0 };
}
if (axis.id == 'y2') {
cssPosition = { 'top' : y, 'right' : 0 };
}
$('<li></li>')
.css(cssPosition)
.html(yLabel)
.appendTo($yLabels);
});
$yLabels.appendTo(graph.$el);
}
/**
* Calls all other draw methods
*/
function draw(){
drawGrid();
var seriesIndex;
if(!graph.hasData) {
return;
}
if(graph.options.axes.x1.show){
if(!graph.options.axes.x1.labels || graph.options.axes.x1.labels.length === 0) {
seriesIndex = graph.options.axes.x1.seriesIndex;
graph.options.axes.x1.labels= getXLabels(graph.allSeries[seriesIndex].series[0], graph.options.labelDateFormat);
}
drawXLabels(graph.options.axes.x1);
}
if(graph.options.axes.x2.show && graph.hasData){
if (!graph.options.axes.x2.labels || graph.options.axes.x2.labels.length === 0) {
seriesIndex = graph.options.axes.x2.seriesIndex;
graph.options.axes.x2.labels = getXLabels(graph.allSeries[seriesIndex].series[0], graph.options.labelDateFormat);
}
drawXLabels(graph.options.axes.x2);
}
if (graph.options.axes.y1.show) {
drawYLabels(graph.maxVals[graph.options.axes.y1.seriesIndex], graph.minVals[graph.options.axes.y1.seriesIndex], graph.options.axes.y1);
}
if (graph.options.axes.y2.show) {
drawYLabels(graph.maxVals[graph.options.axes.y2.seriesIndex], graph.minVals[graph.options.axes.y2.seriesIndex], graph.options.axes.y2);
}
}
return {
draw : draw
};
}
function containsDupes(arr){
var i, j, n;
n= arr.length;
for (i=0; i<n; i++) {
for (j=i+1; j<n; j++) {
if (arr[i] == arr[j]) {
return true;
}
}
}
return false;
}
function commaFormat (num, precision) {
if (precision) {
num = parseFloat(num); // Make sure this is a number
num = precision === 'round' ? Math.round(num) : num.toFixed(precision);
}
num += '';
var preDecimal,
postDecimal,
splitNum = num.split('.'),
rgx = /(\d+)(\d{3})/;
preDecimal = splitNum[0];
postDecimal = splitNum[1] ? '.' + splitNum[1] : '';