* Altered formatting to use the shorter of floatFormat() or intFormat(). This
[dygraphs.git] / dygraph.js
CommitLineData
6a1aa64f
DV
1// Copyright 2006 Dan Vanderkam (danvdk@gmail.com)
2// All Rights Reserved.
3
4/**
5 * @fileoverview Creates an interactive, zoomable graph based on a CSV file or
285a6bda
DV
6 * string. Dygraph can handle multiple series with or without error bars. The
7 * date/value ranges will be automatically set. Dygraph uses the
6a1aa64f
DV
8 * <canvas> tag, so it only works in FF1.5+.
9 * @author danvdk@gmail.com (Dan Vanderkam)
10
11 Usage:
12 <div id="graphdiv" style="width:800px; height:500px;"></div>
13 <script type="text/javascript">
285a6bda
DV
14 new Dygraph(document.getElementById("graphdiv"),
15 "datafile.csv", // CSV file with headers
16 { }); // options
6a1aa64f
DV
17 </script>
18
19 The CSV file is of the form
20
285a6bda 21 Date,SeriesA,SeriesB,SeriesC
6a1aa64f
DV
22 YYYYMMDD,A1,B1,C1
23 YYYYMMDD,A2,B2,C2
24
6a1aa64f
DV
25 If the 'errorBars' option is set in the constructor, the input should be of
26 the form
27
285a6bda 28 Date,SeriesA,SeriesB,...
6a1aa64f
DV
29 YYYYMMDD,A1,sigmaA1,B1,sigmaB1,...
30 YYYYMMDD,A2,sigmaA2,B2,sigmaB2,...
31
32 If the 'fractions' option is set, the input should be of the form:
33
285a6bda 34 Date,SeriesA,SeriesB,...
6a1aa64f
DV
35 YYYYMMDD,A1/B1,A2/B2,...
36 YYYYMMDD,A1/B1,A2/B2,...
37
38 And error bars will be calculated automatically using a binomial distribution.
39
727439b4 40 For further documentation and examples, see http://dygraphs.com/
6a1aa64f
DV
41
42 */
43
44/**
45 * An interactive, zoomable graph
46 * @param {String | Function} file A file containing CSV data or a function that
47 * returns this data. The expected format for each line is
48 * YYYYMMDD,val1,val2,... or, if attrs.errorBars is set,
49 * YYYYMMDD,val1,stddev1,val2,stddev2,...
6a1aa64f
DV
50 * @param {Object} attrs Various other attributes, e.g. errorBars determines
51 * whether the input data contains error ranges.
52 */
285a6bda
DV
53Dygraph = function(div, data, opts) {
54 if (arguments.length > 0) {
55 if (arguments.length == 4) {
56 // Old versions of dygraphs took in the series labels as a constructor
57 // parameter. This doesn't make sense anymore, but it's easy to continue
58 // to support this usage.
59 this.warn("Using deprecated four-argument dygraph constructor");
60 this.__old_init__(div, data, arguments[2], arguments[3]);
61 } else {
62 this.__init__(div, data, opts);
63 }
64 }
6a1aa64f
DV
65};
66
285a6bda
DV
67Dygraph.NAME = "Dygraph";
68Dygraph.VERSION = "1.2";
69Dygraph.__repr__ = function() {
6a1aa64f
DV
70 return "[" + this.NAME + " " + this.VERSION + "]";
71};
285a6bda 72Dygraph.toString = function() {
6a1aa64f
DV
73 return this.__repr__();
74};
75
15b00ba8 76/**
7201b11e
JB
77 * Formatting to use for an integer number.
78 *
79 * @param {Number} x The number to format
80 * @param {Number} unused_precision The precision to use, ignored.
81 * @return {String} A string formatted like %g in printf. The max generated
82 * string length should be precision + 6 (e.g 1.123e+300).
83 */
84Dygraph.intFormat = function(x, unused_precision) {
85 return x.toString();
86}
87
88/**
15b00ba8
JB
89 * Number formatting function which mimicks the behavior of %g in printf, i.e.
90 * either exponential or fixed format (without trailing 0s) is used depending on
91 * the length of the generated string. The advantage of this format is that
062ef401
JB
92 * there is a predictable upper bound on the resulting string length,
93 * significant figures are not dropped, and normal numbers are not displayed in
94 * exponential notation.
15b00ba8
JB
95 *
96 * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g.
97 * It creates strings which are too long for absolute values between 10^-4 and
062ef401 98 * 10^-6. See tests/number-format.html for output examples.
15b00ba8
JB
99 *
100 * @param {Number} x The number to format
101 * @param {Number} opt_precision The precision to use, default 2.
102 * @return {String} A string formatted like %g in printf. The max generated
062ef401 103 * string length should be precision + 6 (e.g 1.123e+300).
15b00ba8 104 */
7201b11e 105Dygraph.floatFormat = function(x, opt_precision) {
15b00ba8
JB
106 // Avoid invalid precision values; [1, 21] is the valid range.
107 var p = Math.min(Math.max(1, opt_precision || 2), 21);
108
109 // This is deceptively simple. The actual algorithm comes from:
110 //
111 // Max allowed length = p + 4
112 // where 4 comes from 'e+n' and '.'.
113 //
114 // Length of fixed format = 2 + y + p
115 // where 2 comes from '0.' and y = # of leading zeroes.
116 //
117 // Equating the two and solving for y yields y = 2, or 0.00xxxx which is
118 // 1.0e-3.
119 //
120 // Since the behavior of toPrecision() is identical for larger numbers, we
121 // don't have to worry about the other bound.
122 //
123 // Finally, the argument for toExponential() is the number of trailing digits,
124 // so we take off 1 for the value before the '.'.
125 return (Math.abs(x) < 1.0e-3 && x != 0.0) ?
126 x.toExponential(p - 1) : x.toPrecision(p);
127};
128
6a1aa64f 129// Various default values
285a6bda
DV
130Dygraph.DEFAULT_ROLL_PERIOD = 1;
131Dygraph.DEFAULT_WIDTH = 480;
132Dygraph.DEFAULT_HEIGHT = 320;
133Dygraph.AXIS_LINE_WIDTH = 0.3;
6a1aa64f 134
062ef401 135
8e4a6af3 136// Default attribute values.
285a6bda 137Dygraph.DEFAULT_ATTRS = {
a9fc39ab 138 highlightCircleSize: 3,
8e4a6af3 139 pixelsPerXLabel: 60,
c6336f04 140 pixelsPerYLabel: 30,
285a6bda 141
8e4a6af3
DV
142 labelsDivWidth: 250,
143 labelsDivStyles: {
144 // TODO(danvk): move defaults from createStatusMessage_ here.
285a6bda
DV
145 },
146 labelsSeparateLines: false,
bcd3ebf0 147 labelsShowZeroValues: true,
285a6bda 148 labelsKMB: false,
afefbcdb 149 labelsKMG2: false,
d160cc3b 150 showLabelsOnHighlight: true,
12e4c741 151
4cb5e2d2
JB
152 yValueFormatter: function(x, opt_precision) {
153 var s = Dygraph.floatFormat(x, opt_precision);
154 var s2 = Dygraph.intFormat(x);
155 return s.length <= s2.length ? s : s2;
156 },
285a6bda
DV
157
158 strokeWidth: 1.0,
8e4a6af3 159
8846615a
DV
160 axisTickSize: 3,
161 axisLabelFontSize: 14,
162 xAxisLabelWidth: 50,
163 yAxisLabelWidth: 50,
bf640e56 164 xAxisLabelFormatter: Dygraph.dateAxisFormatter,
8846615a 165 rightGap: 5,
285a6bda
DV
166
167 showRoller: false,
168 xValueFormatter: Dygraph.dateString_,
169 xValueParser: Dygraph.dateParser,
170 xTicker: Dygraph.dateTicker,
171
3d67f03b
DV
172 delimiter: ',',
173
ff00d3e2 174 logScale: false,
285a6bda
DV
175 sigma: 2.0,
176 errorBars: false,
177 fractions: false,
178 wilsonInterval: true, // only relevant if fractions is true
5954ef32 179 customBars: false,
43af96e7
NK
180 fillGraph: false,
181 fillAlpha: 0.15,
f032c51d 182 connectSeparatedPoints: false,
43af96e7
NK
183
184 stackedGraph: false,
afdc483f
NN
185 hideOverlayOnMouseOut: true,
186
00c281d4 187 stepPlot: false,
062ef401
JB
188 avoidMinZero: false,
189
190 interactionModel: null // will be set to Dygraph.defaultInteractionModel.
285a6bda
DV
191};
192
193// Various logging levels.
194Dygraph.DEBUG = 1;
195Dygraph.INFO = 2;
196Dygraph.WARNING = 3;
197Dygraph.ERROR = 3;
198
39b0e098
RK
199// Directions for panning and zooming. Use bit operations when combined
200// values are possible.
201Dygraph.HORIZONTAL = 1;
202Dygraph.VERTICAL = 2;
203
5c528fa2
DV
204// Used for initializing annotation CSS rules only once.
205Dygraph.addedAnnotationCSS = false;
206
285a6bda
DV
207Dygraph.prototype.__old_init__ = function(div, file, labels, attrs) {
208 // Labels is no longer a constructor parameter, since it's typically set
209 // directly from the data source. It also conains a name for the x-axis,
210 // which the previous constructor form did not.
211 if (labels != null) {
212 var new_labels = ["Date"];
213 for (var i = 0; i < labels.length; i++) new_labels.push(labels[i]);
fc80a396 214 Dygraph.update(attrs, { 'labels': new_labels });
285a6bda
DV
215 }
216 this.__init__(div, file, attrs);
8e4a6af3
DV
217};
218
6a1aa64f 219/**
285a6bda 220 * Initializes the Dygraph. This creates a new DIV and constructs the PlotKit
062ef401 221 * and context &lt;canvas&gt; inside of it. See the constructor for details
6a1aa64f 222 * on the parameters.
12e4c741 223 * @param {Element} div the Element to render the graph into.
6a1aa64f 224 * @param {String | Function} file Source data
6a1aa64f
DV
225 * @param {Object} attrs Miscellaneous other options
226 * @private
227 */
285a6bda 228Dygraph.prototype.__init__ = function(div, file, attrs) {
a2c8fff4
DV
229 // Hack for IE: if we're using excanvas and the document hasn't finished
230 // loading yet (and hence may not have initialized whatever it needs to
231 // initialize), then keep calling this routine periodically until it has.
232 if (/MSIE/.test(navigator.userAgent) && !window.opera &&
233 typeof(G_vmlCanvasManager) != 'undefined' &&
234 document.readyState != 'complete') {
235 var self = this;
236 setTimeout(function() { self.__init__(div, file, attrs) }, 100);
237 }
238
285a6bda
DV
239 // Support two-argument constructor
240 if (attrs == null) { attrs = {}; }
241
6a1aa64f 242 // Copy the important bits into the object
32988383 243 // TODO(danvk): most of these should just stay in the attrs_ dictionary.
6a1aa64f 244 this.maindiv_ = div;
6a1aa64f 245 this.file_ = file;
285a6bda 246 this.rollPeriod_ = attrs.rollPeriod || Dygraph.DEFAULT_ROLL_PERIOD;
6a1aa64f 247 this.previousVerticalX_ = -1;
6a1aa64f 248 this.fractions_ = attrs.fractions || false;
6a1aa64f 249 this.dateWindow_ = attrs.dateWindow || null;
8b83c6cc 250
6a1aa64f 251 this.wilsonInterval_ = attrs.wilsonInterval || true;
fe0b7c03 252 this.is_initial_draw_ = true;
5c528fa2 253 this.annotations_ = [];
6be8e54c
JB
254
255 // Number of digits to use when labeling the x (if numeric) and y axis
256 // ticks.
257 this.numXDigits_ = 2;
258 this.numYDigits_ = 2;
259
260 // When labeling x (if numeric) or y values in the legend, there are
261 // numDigits + numExtraDigits of precision used. For axes labels with N
262 // digits of precision, the data should be displayed with at least N+1 digits
263 // of precision. The reason for this is to divide each interval between
264 // successive ticks into tenths (for 1) or hundredths (for 2), etc. For
265 // example, if the labels are [0, 1, 2], we want data to be displayed as
266 // 0.1, 1.3, etc.
267 this.numExtraDigits_ = 1;
8e4a6af3 268
f7d6278e
DV
269 // Clear the div. This ensure that, if multiple dygraphs are passed the same
270 // div, then only one will be drawn.
271 div.innerHTML = "";
272
c21d2c2d 273 // If the div isn't already sized then inherit from our attrs or
274 // give it a default size.
285a6bda 275 if (div.style.width == '') {
ddd1b11f 276 div.style.width = (attrs.width || Dygraph.DEFAULT_WIDTH) + "px";
285a6bda
DV
277 }
278 if (div.style.height == '') {
ddd1b11f 279 div.style.height = (attrs.height || Dygraph.DEFAULT_HEIGHT) + "px";
32988383 280 }
285a6bda
DV
281 this.width_ = parseInt(div.style.width, 10);
282 this.height_ = parseInt(div.style.height, 10);
c21d2c2d 283 // The div might have been specified as percent of the current window size,
284 // convert that to an appropriate number of pixels.
285 if (div.style.width.indexOf("%") == div.style.width.length - 1) {
c6f45033 286 this.width_ = div.offsetWidth;
c21d2c2d 287 }
288 if (div.style.height.indexOf("%") == div.style.height.length - 1) {
c6f45033 289 this.height_ = div.offsetHeight;
c21d2c2d 290 }
32988383 291
10a6456d
DV
292 if (this.width_ == 0) {
293 this.error("dygraph has zero width. Please specify a width in pixels.");
294 }
295 if (this.height_ == 0) {
296 this.error("dygraph has zero height. Please specify a height in pixels.");
297 }
298
344ba8c0 299 // TODO(danvk): set fillGraph to be part of attrs_ here, not user_attrs_.
43af96e7
NK
300 if (attrs['stackedGraph']) {
301 attrs['fillGraph'] = true;
302 // TODO(nikhilk): Add any other stackedGraph checks here.
303 }
304
285a6bda
DV
305 // Dygraphs has many options, some of which interact with one another.
306 // To keep track of everything, we maintain two sets of options:
307 //
c21d2c2d 308 // this.user_attrs_ only options explicitly set by the user.
285a6bda
DV
309 // this.attrs_ defaults, options derived from user_attrs_, data.
310 //
311 // Options are then accessed this.attr_('attr'), which first looks at
312 // user_attrs_ and then computed attrs_. This way Dygraphs can set intelligent
313 // defaults without overriding behavior that the user specifically asks for.
314 this.user_attrs_ = {};
fc80a396 315 Dygraph.update(this.user_attrs_, attrs);
6a1aa64f 316
285a6bda 317 this.attrs_ = {};
fc80a396 318 Dygraph.update(this.attrs_, Dygraph.DEFAULT_ATTRS);
6a1aa64f 319
16269f6e 320 this.boundaryIds_ = [];
6a1aa64f 321
285a6bda
DV
322 // Make a note of whether labels will be pulled from the CSV file.
323 this.labelsFromCSV_ = (this.attr_("labels") == null);
6a1aa64f
DV
324
325 // Create the containing DIV and other interactive elements
326 this.createInterface_();
327
738fc797 328 this.start_();
6a1aa64f
DV
329};
330
227b93cc
DV
331Dygraph.prototype.attr_ = function(name, seriesName) {
332 if (seriesName &&
333 typeof(this.user_attrs_[seriesName]) != 'undefined' &&
334 this.user_attrs_[seriesName] != null &&
335 typeof(this.user_attrs_[seriesName][name]) != 'undefined') {
336 return this.user_attrs_[seriesName][name];
450fe64b 337 } else if (typeof(this.user_attrs_[name]) != 'undefined') {
285a6bda
DV
338 return this.user_attrs_[name];
339 } else if (typeof(this.attrs_[name]) != 'undefined') {
340 return this.attrs_[name];
341 } else {
342 return null;
343 }
344};
345
346// TODO(danvk): any way I can get the line numbers to be this.warn call?
347Dygraph.prototype.log = function(severity, message) {
348 if (typeof(console) != 'undefined') {
349 switch (severity) {
350 case Dygraph.DEBUG:
351 console.debug('dygraphs: ' + message);
352 break;
353 case Dygraph.INFO:
354 console.info('dygraphs: ' + message);
355 break;
356 case Dygraph.WARNING:
357 console.warn('dygraphs: ' + message);
358 break;
359 case Dygraph.ERROR:
360 console.error('dygraphs: ' + message);
361 break;
362 }
363 }
364}
365Dygraph.prototype.info = function(message) {
366 this.log(Dygraph.INFO, message);
367}
368Dygraph.prototype.warn = function(message) {
369 this.log(Dygraph.WARNING, message);
370}
371Dygraph.prototype.error = function(message) {
372 this.log(Dygraph.ERROR, message);
373}
374
6a1aa64f
DV
375/**
376 * Returns the current rolling period, as set by the user or an option.
6faebb69 377 * @return {Number} The number of points in the rolling window
6a1aa64f 378 */
285a6bda 379Dygraph.prototype.rollPeriod = function() {
6a1aa64f 380 return this.rollPeriod_;
76171648
DV
381};
382
599fb4ad
DV
383/**
384 * Returns the currently-visible x-range. This can be affected by zooming,
385 * panning or a call to updateOptions.
386 * Returns a two-element array: [left, right].
387 * If the Dygraph has dates on the x-axis, these will be millis since epoch.
388 */
389Dygraph.prototype.xAxisRange = function() {
390 if (this.dateWindow_) return this.dateWindow_;
391
392 // The entire chart is visible.
393 var left = this.rawData_[0][0];
394 var right = this.rawData_[this.rawData_.length - 1][0];
395 return [left, right];
396};
397
3230c662 398/**
d58ae307
DV
399 * Returns the currently-visible y-range for an axis. This can be affected by
400 * zooming, panning or a call to updateOptions. Axis indices are zero-based. If
401 * called with no arguments, returns the range of the first axis.
3230c662
DV
402 * Returns a two-element array: [bottom, top].
403 */
d58ae307 404Dygraph.prototype.yAxisRange = function(idx) {
d63e6799 405 if (typeof(idx) == "undefined") idx = 0;
d58ae307
DV
406 if (idx < 0 || idx >= this.axes_.length) return null;
407 return [ this.axes_[idx].computedValueRange[0],
408 this.axes_[idx].computedValueRange[1] ];
409};
410
411/**
412 * Returns the currently-visible y-ranges for each axis. This can be affected by
413 * zooming, panning, calls to updateOptions, etc.
414 * Returns an array of [bottom, top] pairs, one for each y-axis.
415 */
416Dygraph.prototype.yAxisRanges = function() {
417 var ret = [];
418 for (var i = 0; i < this.axes_.length; i++) {
419 ret.push(this.yAxisRange(i));
420 }
421 return ret;
3230c662
DV
422};
423
d58ae307 424// TODO(danvk): use these functions throughout dygraphs.
3230c662
DV
425/**
426 * Convert from data coordinates to canvas/div X/Y coordinates.
d58ae307
DV
427 * If specified, do this conversion for the coordinate system of a particular
428 * axis. Uses the first axis by default.
3230c662
DV
429 * Returns a two-element array: [X, Y]
430 */
d58ae307 431Dygraph.prototype.toDomCoords = function(x, y, axis) {
3230c662
DV
432 var ret = [null, null];
433 var area = this.plotter_.area;
434 if (x !== null) {
435 var xRange = this.xAxisRange();
436 ret[0] = area.x + (x - xRange[0]) / (xRange[1] - xRange[0]) * area.w;
437 }
438
439 if (y !== null) {
d58ae307 440 var yRange = this.yAxisRange(axis);
891ad846 441 ret[1] = area.y + (yRange[1] - y) / (yRange[1] - yRange[0]) * area.h;
3230c662
DV
442 }
443
444 return ret;
445};
446
447/**
448 * Convert from canvas/div coords to data coordinates.
d58ae307
DV
449 * If specified, do this conversion for the coordinate system of a particular
450 * axis. Uses the first axis by default.
3230c662
DV
451 * Returns a two-element array: [X, Y]
452 */
d58ae307 453Dygraph.prototype.toDataCoords = function(x, y, axis) {
3230c662
DV
454 var ret = [null, null];
455 var area = this.plotter_.area;
456 if (x !== null) {
457 var xRange = this.xAxisRange();
458 ret[0] = xRange[0] + (x - area.x) / area.w * (xRange[1] - xRange[0]);
459 }
460
461 if (y !== null) {
d58ae307 462 var yRange = this.yAxisRange(axis);
3230c662
DV
463 ret[1] = yRange[0] + (area.h - y) / area.h * (yRange[1] - yRange[0]);
464 }
465
466 return ret;
467};
468
e99fde05
DV
469/**
470 * Returns the number of columns (including the independent variable).
471 */
472Dygraph.prototype.numColumns = function() {
473 return this.rawData_[0].length;
474};
475
476/**
477 * Returns the number of rows (excluding any header/label row).
478 */
479Dygraph.prototype.numRows = function() {
480 return this.rawData_.length;
481};
482
483/**
484 * Returns the value in the given row and column. If the row and column exceed
485 * the bounds on the data, returns null. Also returns null if the value is
486 * missing.
487 */
488Dygraph.prototype.getValue = function(row, col) {
489 if (row < 0 || row > this.rawData_.length) return null;
490 if (col < 0 || col > this.rawData_[row].length) return null;
491
492 return this.rawData_[row][col];
493};
494
76171648
DV
495Dygraph.addEvent = function(el, evt, fn) {
496 var normed_fn = function(e) {
497 if (!e) var e = window.event;
498 fn(e);
499 };
500 if (window.addEventListener) { // Mozilla, Netscape, Firefox
501 el.addEventListener(evt, normed_fn, false);
502 } else { // IE
503 el.attachEvent('on' + evt, normed_fn);
504 }
505};
6a1aa64f 506
062ef401
JB
507
508// Based on the article at
509// http://www.switchonthecode.com/tutorials/javascript-tutorial-the-scroll-wheel
510Dygraph.cancelEvent = function(e) {
511 e = e ? e : window.event;
512 if (e.stopPropagation) {
513 e.stopPropagation();
514 }
515 if (e.preventDefault) {
516 e.preventDefault();
517 }
518 e.cancelBubble = true;
519 e.cancel = true;
520 e.returnValue = false;
521 return false;
522}
523
524
6a1aa64f 525/**
285a6bda 526 * Generates interface elements for the Dygraph: a containing div, a div to
6a1aa64f 527 * display the current point, and a textbox to adjust the rolling average
697e70b2 528 * period. Also creates the Renderer/Layout elements.
6a1aa64f
DV
529 * @private
530 */
285a6bda 531Dygraph.prototype.createInterface_ = function() {
6a1aa64f
DV
532 // Create the all-enclosing graph div
533 var enclosing = this.maindiv_;
534
b0c3b730
DV
535 this.graphDiv = document.createElement("div");
536 this.graphDiv.style.width = this.width_ + "px";
537 this.graphDiv.style.height = this.height_ + "px";
538 enclosing.appendChild(this.graphDiv);
539
540 // Create the canvas for interactive parts of the chart.
f8cfec73 541 this.canvas_ = Dygraph.createCanvas();
b0c3b730
DV
542 this.canvas_.style.position = "absolute";
543 this.canvas_.width = this.width_;
544 this.canvas_.height = this.height_;
f8cfec73
DV
545 this.canvas_.style.width = this.width_ + "px"; // for IE
546 this.canvas_.style.height = this.height_ + "px"; // for IE
b0c3b730
DV
547
548 // ... and for static parts of the chart.
6a1aa64f 549 this.hidden_ = this.createPlotKitCanvas_(this.canvas_);
76171648 550
eb7bf005
EC
551 // The interactive parts of the graph are drawn on top of the chart.
552 this.graphDiv.appendChild(this.hidden_);
553 this.graphDiv.appendChild(this.canvas_);
554 this.mouseEventElement_ = this.canvas_;
555
76171648 556 var dygraph = this;
eb7bf005 557 Dygraph.addEvent(this.mouseEventElement_, 'mousemove', function(e) {
76171648
DV
558 dygraph.mouseMove_(e);
559 });
eb7bf005 560 Dygraph.addEvent(this.mouseEventElement_, 'mouseout', function(e) {
76171648
DV
561 dygraph.mouseOut_(e);
562 });
697e70b2
DV
563
564 // Create the grapher
565 // TODO(danvk): why does the Layout need its own set of options?
566 this.layoutOptions_ = { 'xOriginIsZero': false };
567 Dygraph.update(this.layoutOptions_, this.attrs_);
568 Dygraph.update(this.layoutOptions_, this.user_attrs_);
569 Dygraph.update(this.layoutOptions_, {
570 'errorBars': (this.attr_("errorBars") || this.attr_("customBars")) });
571
572 this.layout_ = new DygraphLayout(this, this.layoutOptions_);
573
574 // TODO(danvk): why does the Renderer need its own set of options?
575 this.renderOptions_ = { colorScheme: this.colors_,
576 strokeColor: null,
577 axisLineWidth: Dygraph.AXIS_LINE_WIDTH };
578 Dygraph.update(this.renderOptions_, this.attrs_);
579 Dygraph.update(this.renderOptions_, this.user_attrs_);
697e70b2
DV
580
581 this.createStatusMessage_();
697e70b2 582 this.createDragInterface_();
4cfcc38c
DV
583};
584
585/**
586 * Detach DOM elements in the dygraph and null out all data references.
587 * Calling this when you're done with a dygraph can dramatically reduce memory
588 * usage. See, e.g., the tests/perf.html example.
589 */
590Dygraph.prototype.destroy = function() {
591 var removeRecursive = function(node) {
592 while (node.hasChildNodes()) {
593 removeRecursive(node.firstChild);
594 node.removeChild(node.firstChild);
595 }
596 };
597 removeRecursive(this.maindiv_);
598
599 var nullOut = function(obj) {
600 for (var n in obj) {
601 if (typeof(obj[n]) === 'object') {
602 obj[n] = null;
603 }
604 }
605 };
606
607 // These may not all be necessary, but it can't hurt...
608 nullOut(this.layout_);
609 nullOut(this.plotter_);
610 nullOut(this);
611};
6a1aa64f
DV
612
613/**
614 * Creates the canvas containing the PlotKit graph. Only plotkit ever draws on
285a6bda 615 * this particular canvas. All Dygraph work is done on this.canvas_.
8846615a 616 * @param {Object} canvas The Dygraph canvas over which to overlay the plot
6a1aa64f
DV
617 * @return {Object} The newly-created canvas
618 * @private
619 */
285a6bda 620Dygraph.prototype.createPlotKitCanvas_ = function(canvas) {
f8cfec73 621 var h = Dygraph.createCanvas();
6a1aa64f 622 h.style.position = "absolute";
9ac5e4ae
DV
623 // TODO(danvk): h should be offset from canvas. canvas needs to include
624 // some extra area to make it easier to zoom in on the far left and far
625 // right. h needs to be precisely the plot area, so that clipping occurs.
6a1aa64f
DV
626 h.style.top = canvas.style.top;
627 h.style.left = canvas.style.left;
628 h.width = this.width_;
629 h.height = this.height_;
f8cfec73
DV
630 h.style.width = this.width_ + "px"; // for IE
631 h.style.height = this.height_ + "px"; // for IE
6a1aa64f
DV
632 return h;
633};
634
f474c2a3
DV
635// Taken from MochiKit.Color
636Dygraph.hsvToRGB = function (hue, saturation, value) {
637 var red;
638 var green;
639 var blue;
640 if (saturation === 0) {
641 red = value;
642 green = value;
643 blue = value;
644 } else {
645 var i = Math.floor(hue * 6);
646 var f = (hue * 6) - i;
647 var p = value * (1 - saturation);
648 var q = value * (1 - (saturation * f));
649 var t = value * (1 - (saturation * (1 - f)));
650 switch (i) {
651 case 1: red = q; green = value; blue = p; break;
652 case 2: red = p; green = value; blue = t; break;
653 case 3: red = p; green = q; blue = value; break;
654 case 4: red = t; green = p; blue = value; break;
655 case 5: red = value; green = p; blue = q; break;
656 case 6: // fall through
657 case 0: red = value; green = t; blue = p; break;
658 }
659 }
660 red = Math.floor(255 * red + 0.5);
661 green = Math.floor(255 * green + 0.5);
662 blue = Math.floor(255 * blue + 0.5);
663 return 'rgb(' + red + ',' + green + ',' + blue + ')';
664};
665
666
6a1aa64f
DV
667/**
668 * Generate a set of distinct colors for the data series. This is done with a
669 * color wheel. Saturation/Value are customizable, and the hue is
670 * equally-spaced around the color wheel. If a custom set of colors is
671 * specified, that is used instead.
6a1aa64f
DV
672 * @private
673 */
285a6bda
DV
674Dygraph.prototype.setColors_ = function() {
675 // TODO(danvk): compute this directly into this.attrs_['colorScheme'] and do
676 // away with this.renderOptions_.
677 var num = this.attr_("labels").length - 1;
6a1aa64f 678 this.colors_ = [];
285a6bda
DV
679 var colors = this.attr_('colors');
680 if (!colors) {
681 var sat = this.attr_('colorSaturation') || 1.0;
682 var val = this.attr_('colorValue') || 0.5;
2aa21213 683 var half = Math.ceil(num / 2);
6a1aa64f 684 for (var i = 1; i <= num; i++) {
ec1959eb 685 if (!this.visibility()[i-1]) continue;
43af96e7 686 // alternate colors for high contrast.
2aa21213 687 var idx = i % 2 ? Math.ceil(i / 2) : (half + i / 2);
43af96e7
NK
688 var hue = (1.0 * idx/ (1 + num));
689 this.colors_.push(Dygraph.hsvToRGB(hue, sat, val));
6a1aa64f
DV
690 }
691 } else {
692 for (var i = 0; i < num; i++) {
ec1959eb 693 if (!this.visibility()[i]) continue;
285a6bda 694 var colorStr = colors[i % colors.length];
f474c2a3 695 this.colors_.push(colorStr);
6a1aa64f
DV
696 }
697 }
285a6bda 698
c21d2c2d 699 // TODO(danvk): update this w/r/t/ the new options system.
285a6bda 700 this.renderOptions_.colorScheme = this.colors_;
fc80a396
DV
701 Dygraph.update(this.plotter_.options, this.renderOptions_);
702 Dygraph.update(this.layoutOptions_, this.user_attrs_);
703 Dygraph.update(this.layoutOptions_, this.attrs_);
6a1aa64f
DV
704}
705
43af96e7
NK
706/**
707 * Return the list of colors. This is either the list of colors passed in the
708 * attributes, or the autogenerated list of rgb(r,g,b) strings.
709 * @return {Array<string>} The list of colors.
710 */
711Dygraph.prototype.getColors = function() {
712 return this.colors_;
713};
714
5e60386d
DV
715// The following functions are from quirksmode.org with a modification for Safari from
716// http://blog.firetree.net/2005/07/04/javascript-find-position/
3df0ccf0
DV
717// http://www.quirksmode.org/js/findpos.html
718Dygraph.findPosX = function(obj) {
719 var curleft = 0;
5e60386d 720 if(obj.offsetParent)
50360fd0 721 while(1)
5e60386d 722 {
3df0ccf0 723 curleft += obj.offsetLeft;
5e60386d
DV
724 if(!obj.offsetParent)
725 break;
3df0ccf0
DV
726 obj = obj.offsetParent;
727 }
5e60386d 728 else if(obj.x)
3df0ccf0
DV
729 curleft += obj.x;
730 return curleft;
731};
c21d2c2d 732
3df0ccf0
DV
733Dygraph.findPosY = function(obj) {
734 var curtop = 0;
5e60386d
DV
735 if(obj.offsetParent)
736 while(1)
737 {
3df0ccf0 738 curtop += obj.offsetTop;
5e60386d
DV
739 if(!obj.offsetParent)
740 break;
3df0ccf0
DV
741 obj = obj.offsetParent;
742 }
5e60386d 743 else if(obj.y)
3df0ccf0
DV
744 curtop += obj.y;
745 return curtop;
746};
747
5e60386d 748
71a11a8e 749
6a1aa64f
DV
750/**
751 * Create the div that contains information on the selected point(s)
752 * This goes in the top right of the canvas, unless an external div has already
753 * been specified.
754 * @private
755 */
fedbd797 756Dygraph.prototype.createStatusMessage_ = function() {
757 var userLabelsDiv = this.user_attrs_["labelsDiv"];
758 if (userLabelsDiv && null != userLabelsDiv
759 && (typeof(userLabelsDiv) == "string" || userLabelsDiv instanceof String)) {
760 this.user_attrs_["labelsDiv"] = document.getElementById(userLabelsDiv);
761 }
285a6bda
DV
762 if (!this.attr_("labelsDiv")) {
763 var divWidth = this.attr_('labelsDivWidth');
b0c3b730 764 var messagestyle = {
6a1aa64f
DV
765 "position": "absolute",
766 "fontSize": "14px",
767 "zIndex": 10,
768 "width": divWidth + "px",
769 "top": "0px",
8846615a 770 "left": (this.width_ - divWidth - 2) + "px",
6a1aa64f
DV
771 "background": "white",
772 "textAlign": "left",
b0c3b730 773 "overflow": "hidden"};
fc80a396 774 Dygraph.update(messagestyle, this.attr_('labelsDivStyles'));
b0c3b730
DV
775 var div = document.createElement("div");
776 for (var name in messagestyle) {
85b99f0b
DV
777 if (messagestyle.hasOwnProperty(name)) {
778 div.style[name] = messagestyle[name];
779 }
b0c3b730
DV
780 }
781 this.graphDiv.appendChild(div);
285a6bda 782 this.attrs_.labelsDiv = div;
6a1aa64f
DV
783 }
784};
785
786/**
0abfbd7e
DV
787 * Position the labels div so that its right edge is flush with the right edge
788 * of the charting area.
789 */
790Dygraph.prototype.positionLabelsDiv_ = function() {
791 // Don't touch a user-specified labelsDiv.
792 if (this.user_attrs_.hasOwnProperty("labelsDiv")) return;
793
794 var area = this.plotter_.area;
795 var div = this.attr_("labelsDiv");
8c21adcf 796 div.style.left = area.x + area.w - this.attr_("labelsDivWidth") - 1 + "px";
0abfbd7e
DV
797};
798
799/**
6a1aa64f 800 * Create the text box to adjust the averaging period
6a1aa64f
DV
801 * @private
802 */
285a6bda 803Dygraph.prototype.createRollInterface_ = function() {
8c69de65
DV
804 // Create a roller if one doesn't exist already.
805 if (!this.roller_) {
806 this.roller_ = document.createElement("input");
807 this.roller_.type = "text";
808 this.roller_.style.display = "none";
809 this.graphDiv.appendChild(this.roller_);
810 }
811
812 var display = this.attr_('showRoller') ? 'block' : 'none';
26ca7938 813
b0c3b730
DV
814 var textAttr = { "position": "absolute",
815 "zIndex": 10,
816 "top": (this.plotter_.area.h - 25) + "px",
817 "left": (this.plotter_.area.x + 1) + "px",
818 "display": display
6a1aa64f 819 };
8c69de65
DV
820 this.roller_.size = "2";
821 this.roller_.value = this.rollPeriod_;
b0c3b730 822 for (var name in textAttr) {
85b99f0b 823 if (textAttr.hasOwnProperty(name)) {
8c69de65 824 this.roller_.style[name] = textAttr[name];
85b99f0b 825 }
b0c3b730
DV
826 }
827
76171648 828 var dygraph = this;
8c69de65 829 this.roller_.onchange = function() { dygraph.adjustRoll(dygraph.roller_.value); };
76171648
DV
830};
831
832// These functions are taken from MochiKit.Signal
833Dygraph.pageX = function(e) {
834 if (e.pageX) {
835 return (!e.pageX || e.pageX < 0) ? 0 : e.pageX;
836 } else {
837 var de = document;
838 var b = document.body;
839 return e.clientX +
840 (de.scrollLeft || b.scrollLeft) -
841 (de.clientLeft || 0);
842 }
843};
844
845Dygraph.pageY = function(e) {
846 if (e.pageY) {
847 return (!e.pageY || e.pageY < 0) ? 0 : e.pageY;
848 } else {
849 var de = document;
850 var b = document.body;
851 return e.clientY +
852 (de.scrollTop || b.scrollTop) -
853 (de.clientTop || 0);
854 }
855};
6a1aa64f 856
062ef401
JB
857Dygraph.prototype.dragGetX_ = function(e, context) {
858 return Dygraph.pageX(e) - context.px
859};
bce01b0f 860
062ef401
JB
861Dygraph.prototype.dragGetY_ = function(e, context) {
862 return Dygraph.pageY(e) - context.py
863};
ee672584 864
062ef401
JB
865// Called in response to an interaction model operation that
866// should start the default panning behavior.
867//
868// It's used in the default callback for "mousedown" operations.
869// Custom interaction model builders can use it to provide the default
870// panning behavior.
871//
872Dygraph.startPan = function(event, g, context) {
873 // have to be zoomed in to pan.
874 // TODO(konigsberg): Let's loosen this zoom-to-pan restriction, also
875 // perhaps create panning boundaries? A more flexible pan would make it,
876 // ahem, 'pan-useful'.
877 var zoomedY = false;
878 for (var i = 0; i < g.axes_.length; i++) {
879 if (g.axes_[i].valueWindow || g.axes_[i].valueRange) {
880 zoomedY = true;
881 break;
882 }
883 }
884 if (!g.dateWindow_ && !zoomedY) return;
885
886 context.isPanning = true;
887 var xRange = g.xAxisRange();
888 context.dateRange = xRange[1] - xRange[0];
889
890 // Record the range of each y-axis at the start of the drag.
891 // If any axis has a valueRange or valueWindow, then we want a 2D pan.
892 context.is2DPan = false;
893 for (var i = 0; i < g.axes_.length; i++) {
894 var axis = g.axes_[i];
895 var yRange = g.yAxisRange(i);
896 axis.dragValueRange = yRange[1] - yRange[0];
897 var r = g.toDataCoords(null, context.dragStartY, i);
898 axis.draggingValue = r[1];
899 if (axis.valueWindow || axis.valueRange) context.is2DPan = true;
900 }
ee672584 901
062ef401
JB
902 // TODO(konigsberg): Switch from all this math to toDataCoords?
903 // Seems to work for the dragging value.
904 context.draggingDate = (context.dragStartX / g.width_) * context.dateRange + xRange[0];
905};
6a1aa64f 906
062ef401
JB
907// Called in response to an interaction model operation that
908// responds to an event that pans the view.
909//
910// It's used in the default callback for "mousemove" operations.
911// Custom interaction model builders can use it to provide the default
912// panning behavior.
913//
914Dygraph.movePan = function(event, g, context) {
915 context.dragEndX = g.dragGetX_(event, context);
916 context.dragEndY = g.dragGetY_(event, context);
79b3ee42 917
062ef401
JB
918 // TODO(danvk): update this comment
919 // Want to have it so that:
920 // 1. draggingDate appears at dragEndX, draggingValue appears at dragEndY.
921 // 2. daterange = (dateWindow_[1] - dateWindow_[0]) is unaltered.
922 // 3. draggingValue appears at dragEndY.
923 // 4. valueRange is unaltered.
924
925 var minDate = context.draggingDate - (context.dragEndX / g.width_) * context.dateRange;
926 var maxDate = minDate + context.dateRange;
927 g.dateWindow_ = [minDate, maxDate];
928
929 // y-axis scaling is automatic unless this is a full 2D pan.
930 if (context.is2DPan) {
931 // Adjust each axis appropriately.
932 var y_frac = context.dragEndY / g.height_;
933 for (var i = 0; i < g.axes_.length; i++) {
934 var axis = g.axes_[i];
935 var maxValue = axis.draggingValue + y_frac * axis.dragValueRange;
936 var minValue = maxValue - axis.dragValueRange;
937 axis.valueWindow = [ minValue, maxValue ];
6faebb69 938 }
062ef401 939 }
bce01b0f 940
062ef401
JB
941 g.drawGraph_();
942}
ee672584 943
062ef401
JB
944// Called in response to an interaction model operation that
945// responds to an event that ends panning.
946//
947// It's used in the default callback for "mouseup" operations.
948// Custom interaction model builders can use it to provide the default
949// panning behavior.
950//
951Dygraph.endPan = function(event, g, context) {
952 context.isPanning = false;
953 context.is2DPan = false;
954 context.draggingDate = null;
955 context.dateRange = null;
956 context.valueRange = null;
957}
ee672584 958
062ef401
JB
959// Called in response to an interaction model operation that
960// responds to an event that starts zooming.
961//
962// It's used in the default callback for "mousedown" operations.
963// Custom interaction model builders can use it to provide the default
964// zooming behavior.
965//
966Dygraph.startZoom = function(event, g, context) {
967 context.isZooming = true;
968}
969
970// Called in response to an interaction model operation that
971// responds to an event that defines zoom boundaries.
972//
973// It's used in the default callback for "mousemove" operations.
974// Custom interaction model builders can use it to provide the default
975// zooming behavior.
976//
977Dygraph.moveZoom = function(event, g, context) {
978 context.dragEndX = g.dragGetX_(event, context);
979 context.dragEndY = g.dragGetY_(event, context);
980
981 var xDelta = Math.abs(context.dragStartX - context.dragEndX);
982 var yDelta = Math.abs(context.dragStartY - context.dragEndY);
983
984 // drag direction threshold for y axis is twice as large as x axis
985 context.dragDirection = (xDelta < yDelta / 2) ? Dygraph.VERTICAL : Dygraph.HORIZONTAL;
986
987 g.drawZoomRect_(
988 context.dragDirection,
989 context.dragStartX,
990 context.dragEndX,
991 context.dragStartY,
992 context.dragEndY,
993 context.prevDragDirection,
994 context.prevEndX,
995 context.prevEndY);
996
997 context.prevEndX = context.dragEndX;
998 context.prevEndY = context.dragEndY;
999 context.prevDragDirection = context.dragDirection;
1000}
1001
1002// Called in response to an interaction model operation that
1003// responds to an event that performs a zoom based on previously defined
1004// bounds..
1005//
1006// It's used in the default callback for "mouseup" operations.
1007// Custom interaction model builders can use it to provide the default
1008// zooming behavior.
1009//
1010Dygraph.endZoom = function(event, g, context) {
1011 context.isZooming = false;
1012 context.dragEndX = g.dragGetX_(event, context);
1013 context.dragEndY = g.dragGetY_(event, context);
1014 var regionWidth = Math.abs(context.dragEndX - context.dragStartX);
1015 var regionHeight = Math.abs(context.dragEndY - context.dragStartY);
1016
1017 if (regionWidth < 2 && regionHeight < 2 &&
1018 g.lastx_ != undefined && g.lastx_ != -1) {
1019 // TODO(danvk): pass along more info about the points, e.g. 'x'
1020 if (g.attr_('clickCallback') != null) {
1021 g.attr_('clickCallback')(event, g.lastx_, g.selPoints_);
1022 }
1023 if (g.attr_('pointClickCallback')) {
1024 // check if the click was on a particular point.
1025 var closestIdx = -1;
1026 var closestDistance = 0;
1027 for (var i = 0; i < g.selPoints_.length; i++) {
1028 var p = g.selPoints_[i];
1029 var distance = Math.pow(p.canvasx - context.dragEndX, 2) +
1030 Math.pow(p.canvasy - context.dragEndY, 2);
1031 if (closestIdx == -1 || distance < closestDistance) {
1032 closestDistance = distance;
1033 closestIdx = i;
d58ae307
DV
1034 }
1035 }
e3489f4f 1036
062ef401
JB
1037 // Allow any click within two pixels of the dot.
1038 var radius = g.attr_('highlightCircleSize') + 2;
1039 if (closestDistance <= 5 * 5) {
1040 g.attr_('pointClickCallback')(event, g.selPoints_[closestIdx]);
6faebb69 1041 }
062ef401
JB
1042 }
1043 }
0a52ab7a 1044
062ef401
JB
1045 if (regionWidth >= 10 && context.dragDirection == Dygraph.HORIZONTAL) {
1046 g.doZoomX_(Math.min(context.dragStartX, context.dragEndX),
1047 Math.max(context.dragStartX, context.dragEndX));
1048 } else if (regionHeight >= 10 && context.dragDirection == Dygraph.VERTICAL) {
1049 g.doZoomY_(Math.min(context.dragStartY, context.dragEndY),
1050 Math.max(context.dragStartY, context.dragEndY));
1051 } else {
1052 g.canvas_.getContext("2d").clearRect(0, 0,
1053 g.canvas_.width,
1054 g.canvas_.height);
1055 }
1056 context.dragStartX = null;
1057 context.dragStartY = null;
1058}
1059
1060Dygraph.defaultInteractionModel = {
1061 // Track the beginning of drag events
1062 mousedown: function(event, g, context) {
1063 context.initializeMouseDown(event, g, context);
1064
1065 if (event.altKey || event.shiftKey) {
1066 Dygraph.startPan(event, g, context);
bce01b0f 1067 } else {
062ef401 1068 Dygraph.startZoom(event, g, context);
bce01b0f 1069 }
062ef401 1070 },
6a1aa64f 1071
062ef401
JB
1072 // Draw zoom rectangles when the mouse is down and the user moves around
1073 mousemove: function(event, g, context) {
1074 if (context.isZooming) {
1075 Dygraph.moveZoom(event, g, context);
1076 } else if (context.isPanning) {
1077 Dygraph.movePan(event, g, context);
6a1aa64f 1078 }
062ef401 1079 },
bce01b0f 1080
062ef401
JB
1081 mouseup: function(event, g, context) {
1082 if (context.isZooming) {
1083 Dygraph.endZoom(event, g, context);
1084 } else if (context.isPanning) {
1085 Dygraph.endPan(event, g, context);
bce01b0f 1086 }
062ef401 1087 },
6a1aa64f
DV
1088
1089 // Temporarily cancel the dragging event when the mouse leaves the graph
062ef401
JB
1090 mouseout: function(event, g, context) {
1091 if (context.isZooming) {
1092 context.dragEndX = null;
1093 context.dragEndY = null;
6a1aa64f 1094 }
062ef401 1095 },
6a1aa64f 1096
062ef401
JB
1097 // Disable zooming out if panning.
1098 dblclick: function(event, g, context) {
1099 if (event.altKey || event.shiftKey) {
1100 return;
1101 }
1102 // TODO(konigsberg): replace g.doUnzoom()_ with something that is
1103 // friendlier to public use.
1104 g.doUnzoom_();
1105 }
1106};
1e1bf7df 1107
062ef401 1108Dygraph.DEFAULT_ATTRS.interactionModel = Dygraph.defaultInteractionModel;
6a1aa64f 1109
062ef401
JB
1110/**
1111 * Set up all the mouse handlers needed to capture dragging behavior for zoom
1112 * events.
1113 * @private
1114 */
1115Dygraph.prototype.createDragInterface_ = function() {
1116 var context = {
1117 // Tracks whether the mouse is down right now
1118 isZooming: false,
1119 isPanning: false, // is this drag part of a pan?
1120 is2DPan: false, // if so, is that pan 1- or 2-dimensional?
1121 dragStartX: null,
1122 dragStartY: null,
1123 dragEndX: null,
1124 dragEndY: null,
1125 dragDirection: null,
1126 prevEndX: null,
1127 prevEndY: null,
1128 prevDragDirection: null,
1129
1130 // TODO(danvk): update this comment
1131 // draggingDate and draggingValue represent the [date,value] point on the
1132 // graph at which the mouse was pressed. As the mouse moves while panning,
1133 // the viewport must pan so that the mouse position points to
1134 // [draggingDate, draggingValue]
1135 draggingDate: null,
1136
1137 // TODO(danvk): update this comment
1138 // The range in second/value units that the viewport encompasses during a
1139 // panning operation.
1140 dateRange: null,
1141
1142 // Utility function to convert page-wide coordinates to canvas coords
1143 px: 0,
1144 py: 0,
1145
1146 initializeMouseDown: function(event, g, context) {
1147 // prevents mouse drags from selecting page text.
1148 if (event.preventDefault) {
1149 event.preventDefault(); // Firefox, Chrome, etc.
6a1aa64f 1150 } else {
062ef401
JB
1151 event.returnValue = false; // IE
1152 event.cancelBubble = true;
6a1aa64f
DV
1153 }
1154
062ef401
JB
1155 context.px = Dygraph.findPosX(g.canvas_);
1156 context.py = Dygraph.findPosY(g.canvas_);
1157 context.dragStartX = g.dragGetX_(event, context);
1158 context.dragStartY = g.dragGetY_(event, context);
6a1aa64f 1159 }
062ef401 1160 };
2b188b3d 1161
062ef401 1162 var interactionModel = this.attr_("interactionModel");
8b83c6cc 1163
062ef401
JB
1164 // Self is the graph.
1165 var self = this;
6faebb69 1166
062ef401
JB
1167 // Function that binds the graph and context to the handler.
1168 var bindHandler = function(handler) {
1169 return function(event) {
1170 handler(event, self, context);
1171 };
1172 };
1173
1174 for (var eventName in interactionModel) {
1175 if (!interactionModel.hasOwnProperty(eventName)) continue;
1176 Dygraph.addEvent(this.mouseEventElement_, eventName,
1177 bindHandler(interactionModel[eventName]));
1178 }
1179
1180 // If the user releases the mouse button during a drag, but not over the
1181 // canvas, then it doesn't count as a zooming action.
1182 Dygraph.addEvent(document, 'mouseup', function(event) {
1183 if (context.isZooming || context.isPanning) {
1184 context.isZooming = false;
1185 context.dragStartX = null;
1186 context.dragStartY = null;
1187 }
1188
1189 if (context.isPanning) {
1190 context.isPanning = false;
1191 context.draggingDate = null;
1192 context.dateRange = null;
1193 for (var i = 0; i < self.axes_.length; i++) {
1194 delete self.axes_[i].draggingValue;
1195 delete self.axes_[i].dragValueRange;
1196 }
1197 }
6a1aa64f
DV
1198 });
1199};
1200
062ef401 1201
6a1aa64f
DV
1202/**
1203 * Draw a gray zoom rectangle over the desired area of the canvas. Also clears
1204 * up any previous zoom rectangles that were drawn. This could be optimized to
1205 * avoid extra redrawing, but it's tricky to avoid interactions with the status
1206 * dots.
8b83c6cc 1207 *
39b0e098
RK
1208 * @param {Number} direction the direction of the zoom rectangle. Acceptable
1209 * values are Dygraph.HORIZONTAL and Dygraph.VERTICAL.
6a1aa64f
DV
1210 * @param {Number} startX The X position where the drag started, in canvas
1211 * coordinates.
1212 * @param {Number} endX The current X position of the drag, in canvas coords.
8b83c6cc
RK
1213 * @param {Number} startY The Y position where the drag started, in canvas
1214 * coordinates.
1215 * @param {Number} endY The current Y position of the drag, in canvas coords.
39b0e098 1216 * @param {Number} prevDirection the value of direction on the previous call to
8b83c6cc 1217 * this function. Used to avoid excess redrawing
6a1aa64f
DV
1218 * @param {Number} prevEndX The value of endX on the previous call to this
1219 * function. Used to avoid excess redrawing
8b83c6cc
RK
1220 * @param {Number} prevEndY The value of endY on the previous call to this
1221 * function. Used to avoid excess redrawing
6a1aa64f
DV
1222 * @private
1223 */
7201b11e
JB
1224Dygraph.prototype.drawZoomRect_ = function(direction, startX, endX, startY,
1225 endY, prevDirection, prevEndX,
1226 prevEndY) {
6a1aa64f
DV
1227 var ctx = this.canvas_.getContext("2d");
1228
1229 // Clean up from the previous rect if necessary
39b0e098 1230 if (prevDirection == Dygraph.HORIZONTAL) {
6a1aa64f
DV
1231 ctx.clearRect(Math.min(startX, prevEndX), 0,
1232 Math.abs(startX - prevEndX), this.height_);
39b0e098 1233 } else if (prevDirection == Dygraph.VERTICAL){
8b83c6cc
RK
1234 ctx.clearRect(0, Math.min(startY, prevEndY),
1235 this.width_, Math.abs(startY - prevEndY));
6a1aa64f
DV
1236 }
1237
1238 // Draw a light-grey rectangle to show the new viewing area
39b0e098 1239 if (direction == Dygraph.HORIZONTAL) {
8b83c6cc
RK
1240 if (endX && startX) {
1241 ctx.fillStyle = "rgba(128,128,128,0.33)";
1242 ctx.fillRect(Math.min(startX, endX), 0,
1243 Math.abs(endX - startX), this.height_);
1244 }
1245 }
39b0e098 1246 if (direction == Dygraph.VERTICAL) {
8b83c6cc
RK
1247 if (endY && startY) {
1248 ctx.fillStyle = "rgba(128,128,128,0.33)";
1249 ctx.fillRect(0, Math.min(startY, endY),
1250 this.width_, Math.abs(endY - startY));
1251 }
6a1aa64f
DV
1252 }
1253};
1254
1255/**
8b83c6cc
RK
1256 * Zoom to something containing [lowX, highX]. These are pixel coordinates in
1257 * the canvas. The exact zoom window may be slightly larger if there are no data
1258 * points near lowX or highX. Don't confuse this function with doZoomXDates,
1259 * which accepts dates that match the raw data. This function redraws the graph.
d58ae307 1260 *
6a1aa64f
DV
1261 * @param {Number} lowX The leftmost pixel value that should be visible.
1262 * @param {Number} highX The rightmost pixel value that should be visible.
1263 * @private
1264 */
8b83c6cc 1265Dygraph.prototype.doZoomX_ = function(lowX, highX) {
6a1aa64f 1266 // Find the earliest and latest dates contained in this canvasx range.
8b83c6cc 1267 // Convert the call to date ranges of the raw data.
56623f3b
DV
1268 var r = this.toDataCoords(lowX, null);
1269 var minDate = r[0];
1270 r = this.toDataCoords(highX, null);
1271 var maxDate = r[0];
8b83c6cc
RK
1272 this.doZoomXDates_(minDate, maxDate);
1273};
6a1aa64f 1274
8b83c6cc
RK
1275/**
1276 * Zoom to something containing [minDate, maxDate] values. Don't confuse this
1277 * method with doZoomX which accepts pixel coordinates. This function redraws
1278 * the graph.
d58ae307 1279 *
8b83c6cc
RK
1280 * @param {Number} minDate The minimum date that should be visible.
1281 * @param {Number} maxDate The maximum date that should be visible.
1282 * @private
1283 */
1284Dygraph.prototype.doZoomXDates_ = function(minDate, maxDate) {
6a1aa64f 1285 this.dateWindow_ = [minDate, maxDate];
26ca7938 1286 this.drawGraph_();
285a6bda 1287 if (this.attr_("zoomCallback")) {
ac139d19 1288 this.attr_("zoomCallback")(minDate, maxDate, this.yAxisRanges());
8b83c6cc
RK
1289 }
1290};
1291
1292/**
1293 * Zoom to something containing [lowY, highY]. These are pixel coordinates in
d58ae307
DV
1294 * the canvas. This function redraws the graph.
1295 *
8b83c6cc
RK
1296 * @param {Number} lowY The topmost pixel value that should be visible.
1297 * @param {Number} highY The lowest pixel value that should be visible.
1298 * @private
1299 */
1300Dygraph.prototype.doZoomY_ = function(lowY, highY) {
d58ae307
DV
1301 // Find the highest and lowest values in pixel range for each axis.
1302 // Note that lowY (in pixels) corresponds to the max Value (in data coords).
1303 // This is because pixels increase as you go down on the screen, whereas data
1304 // coordinates increase as you go up the screen.
1305 var valueRanges = [];
1306 for (var i = 0; i < this.axes_.length; i++) {
1307 var hi = this.toDataCoords(null, lowY, i);
1308 var low = this.toDataCoords(null, highY, i);
1309 this.axes_[i].valueWindow = [low[1], hi[1]];
1310 valueRanges.push([low[1], hi[1]]);
1311 }
8b83c6cc 1312
66c380c4 1313 this.drawGraph_();
8b83c6cc 1314 if (this.attr_("zoomCallback")) {
d58ae307
DV
1315 var xRange = this.xAxisRange();
1316 this.attr_("zoomCallback")(xRange[0], xRange[1], this.yAxisRanges());
8b83c6cc
RK
1317 }
1318};
1319
1320/**
1321 * Reset the zoom to the original view coordinates. This is the same as
1322 * double-clicking on the graph.
d58ae307 1323 *
8b83c6cc
RK
1324 * @private
1325 */
1326Dygraph.prototype.doUnzoom_ = function() {
d58ae307 1327 var dirty = false;
8b83c6cc 1328 if (this.dateWindow_ != null) {
d58ae307 1329 dirty = true;
8b83c6cc
RK
1330 this.dateWindow_ = null;
1331 }
d58ae307
DV
1332
1333 for (var i = 0; i < this.axes_.length; i++) {
1334 if (this.axes_[i].valueWindow != null) {
1335 dirty = true;
1336 delete this.axes_[i].valueWindow;
1337 }
8b83c6cc
RK
1338 }
1339
1340 if (dirty) {
437c0979
RK
1341 // Putting the drawing operation before the callback because it resets
1342 // yAxisRange.
66c380c4 1343 this.drawGraph_();
8b83c6cc
RK
1344 if (this.attr_("zoomCallback")) {
1345 var minDate = this.rawData_[0][0];
1346 var maxDate = this.rawData_[this.rawData_.length - 1][0];
d58ae307 1347 this.attr_("zoomCallback")(minDate, maxDate, this.yAxisRanges());
8b83c6cc 1348 }
67e650dc 1349 }
6a1aa64f
DV
1350};
1351
1352/**
1353 * When the mouse moves in the canvas, display information about a nearby data
1354 * point and draw dots over those points in the data series. This function
1355 * takes care of cleanup of previously-drawn dots.
1356 * @param {Object} event The mousemove event from the browser.
1357 * @private
1358 */
285a6bda 1359Dygraph.prototype.mouseMove_ = function(event) {
eb7bf005 1360 var canvasx = Dygraph.pageX(event) - Dygraph.findPosX(this.mouseEventElement_);
6a1aa64f
DV
1361 var points = this.layout_.points;
1362
1363 var lastx = -1;
1364 var lasty = -1;
1365
1366 // Loop through all the points and find the date nearest to our current
1367 // location.
1368 var minDist = 1e+100;
1369 var idx = -1;
1370 for (var i = 0; i < points.length; i++) {
8a7cc60e
RK
1371 var point = points[i];
1372 if (point == null) continue;
062ef401 1373 var dist = Math.abs(point.canvasx - canvasx);
f032c51d 1374 if (dist > minDist) continue;
6a1aa64f
DV
1375 minDist = dist;
1376 idx = i;
1377 }
1378 if (idx >= 0) lastx = points[idx].xval;
1379 // Check that you can really highlight the last day's data
8a7cc60e
RK
1380 var last = points[points.length-1];
1381 if (last != null && canvasx > last.canvasx)
6a1aa64f
DV
1382 lastx = points[points.length-1].xval;
1383
1384 // Extract the points we've selected
b258a3da 1385 this.selPoints_ = [];
50360fd0 1386 var l = points.length;
416b05ad
NK
1387 if (!this.attr_("stackedGraph")) {
1388 for (var i = 0; i < l; i++) {
1389 if (points[i].xval == lastx) {
1390 this.selPoints_.push(points[i]);
1391 }
1392 }
1393 } else {
354e15ab
DE
1394 // Need to 'unstack' points starting from the bottom
1395 var cumulative_sum = 0;
416b05ad
NK
1396 for (var i = l - 1; i >= 0; i--) {
1397 if (points[i].xval == lastx) {
354e15ab 1398 var p = {}; // Clone the point since we modify it
d4139cd8
NK
1399 for (var k in points[i]) {
1400 p[k] = points[i][k];
50360fd0
NK
1401 }
1402 p.yval -= cumulative_sum;
1403 cumulative_sum += p.yval;
d4139cd8 1404 this.selPoints_.push(p);
12e4c741 1405 }
6a1aa64f 1406 }
354e15ab 1407 this.selPoints_.reverse();
6a1aa64f
DV
1408 }
1409
b258a3da 1410 if (this.attr_("highlightCallback")) {
a4c6a67c 1411 var px = this.lastx_;
dd082dda 1412 if (px !== null && lastx != px) {
344ba8c0 1413 // only fire if the selected point has changed.
2ddb1197 1414 this.attr_("highlightCallback")(event, lastx, this.selPoints_, this.idxToRow_(idx));
43af96e7 1415 }
12e4c741 1416 }
43af96e7 1417
239c712d
NAG
1418 // Save last x position for callbacks.
1419 this.lastx_ = lastx;
50360fd0 1420
239c712d
NAG
1421 this.updateSelection_();
1422};
b258a3da 1423
239c712d 1424/**
1903f1e4 1425 * Transforms layout_.points index into data row number.
2ddb1197 1426 * @param int layout_.points index
1903f1e4 1427 * @return int row number, or -1 if none could be found.
2ddb1197
SC
1428 * @private
1429 */
1430Dygraph.prototype.idxToRow_ = function(idx) {
1903f1e4 1431 if (idx < 0) return -1;
2ddb1197 1432
1903f1e4
DV
1433 for (var i in this.layout_.datasets) {
1434 if (idx < this.layout_.datasets[i].length) {
1435 return this.boundaryIds_[0][0]+idx;
1436 }
1437 idx -= this.layout_.datasets[i].length;
1438 }
1439 return -1;
1440};
2ddb1197
SC
1441
1442/**
239c712d
NAG
1443 * Draw dots over the selectied points in the data series. This function
1444 * takes care of cleanup of previously-drawn dots.
1445 * @private
1446 */
1447Dygraph.prototype.updateSelection_ = function() {
6a1aa64f 1448 // Clear the previously drawn vertical, if there is one
6a1aa64f
DV
1449 var ctx = this.canvas_.getContext("2d");
1450 if (this.previousVerticalX_ >= 0) {
46dde5f9
DV
1451 // Determine the maximum highlight circle size.
1452 var maxCircleSize = 0;
227b93cc
DV
1453 var labels = this.attr_('labels');
1454 for (var i = 1; i < labels.length; i++) {
1455 var r = this.attr_('highlightCircleSize', labels[i]);
46dde5f9
DV
1456 if (r > maxCircleSize) maxCircleSize = r;
1457 }
6a1aa64f 1458 var px = this.previousVerticalX_;
46dde5f9
DV
1459 ctx.clearRect(px - maxCircleSize - 1, 0,
1460 2 * maxCircleSize + 2, this.height_);
6a1aa64f
DV
1461 }
1462
584ceeaa
DV
1463 var isOK = function(x) { return x && !isNaN(x); };
1464
d160cc3b 1465 if (this.selPoints_.length > 0) {
b258a3da 1466 var canvasx = this.selPoints_[0].canvasx;
6a1aa64f
DV
1467
1468 // Set the status message to indicate the selected point(s)
6be8e54c
JB
1469 var replace = this.attr_('xValueFormatter')(
1470 this.lastx_, this.numXDigits_ + this.numExtraDigits_) + ":";
50360fd0 1471 var fmtFunc = this.attr_('yValueFormatter');
6a1aa64f 1472 var clen = this.colors_.length;
d160cc3b
NK
1473
1474 if (this.attr_('showLabelsOnHighlight')) {
1475 // Set the status message to indicate the selected point(s)
d160cc3b 1476 for (var i = 0; i < this.selPoints_.length; i++) {
129569a5 1477 if (!this.attr_("labelsShowZeroValues") && this.selPoints_[i].yval == 0) continue;
d160cc3b
NK
1478 if (!isOK(this.selPoints_[i].canvasy)) continue;
1479 if (this.attr_("labelsSeparateLines")) {
1480 replace += "<br/>";
1481 }
1482 var point = this.selPoints_[i];
8fb6dc24 1483 var c = new RGBColor(this.plotter_.colors[point.name]);
6be8e54c 1484 var yval = fmtFunc(point.yval, this.numYDigits_ + this.numExtraDigits_);
d160cc3b
NK
1485 replace += " <b><font color='" + c.toHex() + "'>"
1486 + point.name + "</font></b>:"
1487 + yval;
6a1aa64f 1488 }
50360fd0 1489
d160cc3b 1490 this.attr_("labelsDiv").innerHTML = replace;
6a1aa64f 1491 }
6a1aa64f 1492
6a1aa64f 1493 // Draw colored circles over the center of each selected point
43af96e7 1494 ctx.save();
b258a3da 1495 for (var i = 0; i < this.selPoints_.length; i++) {
f032c51d 1496 if (!isOK(this.selPoints_[i].canvasy)) continue;
227b93cc
DV
1497 var circleSize =
1498 this.attr_('highlightCircleSize', this.selPoints_[i].name);
6a1aa64f 1499 ctx.beginPath();
563c70ca 1500 ctx.fillStyle = this.plotter_.colors[this.selPoints_[i].name];
f032c51d 1501 ctx.arc(canvasx, this.selPoints_[i].canvasy, circleSize,
7bf6a9fe 1502 0, 2 * Math.PI, false);
6a1aa64f
DV
1503 ctx.fill();
1504 }
1505 ctx.restore();
1506
1507 this.previousVerticalX_ = canvasx;
1508 }
1509};
1510
1511/**
239c712d
NAG
1512 * Set manually set selected dots, and display information about them
1513 * @param int row number that should by highlighted
1514 * false value clears the selection
1515 * @public
1516 */
1517Dygraph.prototype.setSelection = function(row) {
1518 // Extract the points we've selected
1519 this.selPoints_ = [];
1520 var pos = 0;
50360fd0 1521
239c712d 1522 if (row !== false) {
16269f6e
NAG
1523 row = row-this.boundaryIds_[0][0];
1524 }
50360fd0 1525
16269f6e 1526 if (row !== false && row >= 0) {
239c712d 1527 for (var i in this.layout_.datasets) {
16269f6e 1528 if (row < this.layout_.datasets[i].length) {
38f33a44 1529 var point = this.layout_.points[pos+row];
1530
1531 if (this.attr_("stackedGraph")) {
8c03ba63 1532 point = this.layout_.unstackPointAtIndex(pos+row);
38f33a44 1533 }
1534
1535 this.selPoints_.push(point);
16269f6e 1536 }
239c712d
NAG
1537 pos += this.layout_.datasets[i].length;
1538 }
16269f6e 1539 }
50360fd0 1540
16269f6e 1541 if (this.selPoints_.length) {
239c712d
NAG
1542 this.lastx_ = this.selPoints_[0].xval;
1543 this.updateSelection_();
1544 } else {
1545 this.lastx_ = -1;
1546 this.clearSelection();
1547 }
1548
1549};
1550
1551/**
6a1aa64f
DV
1552 * The mouse has left the canvas. Clear out whatever artifacts remain
1553 * @param {Object} event the mouseout event from the browser.
1554 * @private
1555 */
285a6bda 1556Dygraph.prototype.mouseOut_ = function(event) {
a4c6a67c
AV
1557 if (this.attr_("unhighlightCallback")) {
1558 this.attr_("unhighlightCallback")(event);
1559 }
1560
43af96e7 1561 if (this.attr_("hideOverlayOnMouseOut")) {
239c712d 1562 this.clearSelection();
43af96e7 1563 }
6a1aa64f
DV
1564};
1565
239c712d
NAG
1566/**
1567 * Remove all selection from the canvas
1568 * @public
1569 */
1570Dygraph.prototype.clearSelection = function() {
1571 // Get rid of the overlay data
1572 var ctx = this.canvas_.getContext("2d");
1573 ctx.clearRect(0, 0, this.width_, this.height_);
1574 this.attr_("labelsDiv").innerHTML = "";
1575 this.selPoints_ = [];
1576 this.lastx_ = -1;
1577}
1578
103b7292
NAG
1579/**
1580 * Returns the number of the currently selected row
1581 * @return int row number, of -1 if nothing is selected
1582 * @public
1583 */
1584Dygraph.prototype.getSelection = function() {
1585 if (!this.selPoints_ || this.selPoints_.length < 1) {
1586 return -1;
1587 }
50360fd0 1588
103b7292
NAG
1589 for (var row=0; row<this.layout_.points.length; row++ ) {
1590 if (this.layout_.points[row].x == this.selPoints_[0].x) {
16269f6e 1591 return row + this.boundaryIds_[0][0];
103b7292
NAG
1592 }
1593 }
1594 return -1;
1595}
1596
285a6bda 1597Dygraph.zeropad = function(x) {
32988383
DV
1598 if (x < 10) return "0" + x; else return "" + x;
1599}
1600
6a1aa64f 1601/**
6b8e33dd
DV
1602 * Return a string version of the hours, minutes and seconds portion of a date.
1603 * @param {Number} date The JavaScript date (ms since epoch)
1604 * @return {String} A time of the form "HH:MM:SS"
1605 * @private
1606 */
bf640e56 1607Dygraph.hmsString_ = function(date) {
285a6bda 1608 var zeropad = Dygraph.zeropad;
6b8e33dd
DV
1609 var d = new Date(date);
1610 if (d.getSeconds()) {
1611 return zeropad(d.getHours()) + ":" +
1612 zeropad(d.getMinutes()) + ":" +
1613 zeropad(d.getSeconds());
6b8e33dd 1614 } else {
054531ca 1615 return zeropad(d.getHours()) + ":" + zeropad(d.getMinutes());
6b8e33dd
DV
1616 }
1617}
1618
1619/**
bf640e56
AV
1620 * Convert a JS date to a string appropriate to display on an axis that
1621 * is displaying values at the stated granularity.
1622 * @param {Date} date The date to format
1623 * @param {Number} granularity One of the Dygraph granularity constants
1624 * @return {String} The formatted date
1625 * @private
1626 */
1627Dygraph.dateAxisFormatter = function(date, granularity) {
062ef401
JB
1628 if (granularity >= Dygraph.DECADAL) {
1629 return date.strftime('%Y');
1630 } else if (granularity >= Dygraph.MONTHLY) {
bf640e56
AV
1631 return date.strftime('%b %y');
1632 } else {
31eddad3 1633 var frac = date.getHours() * 3600 + date.getMinutes() * 60 + date.getSeconds() + date.getMilliseconds();
bf640e56
AV
1634 if (frac == 0 || granularity >= Dygraph.DAILY) {
1635 return new Date(date.getTime() + 3600*1000).strftime('%d%b');
1636 } else {
1637 return Dygraph.hmsString_(date.getTime());
1638 }
1639 }
1640}
1641
1642/**
6a1aa64f
DV
1643 * Convert a JS date (millis since epoch) to YYYY/MM/DD
1644 * @param {Number} date The JavaScript date (ms since epoch)
1645 * @return {String} A date of the form "YYYY/MM/DD"
1646 * @private
1647 */
6be8e54c 1648Dygraph.dateString_ = function(date) {
285a6bda 1649 var zeropad = Dygraph.zeropad;
6a1aa64f
DV
1650 var d = new Date(date);
1651
1652 // Get the year:
1653 var year = "" + d.getFullYear();
1654 // Get a 0 padded month string
6b8e33dd 1655 var month = zeropad(d.getMonth() + 1); //months are 0-offset, sigh
6a1aa64f 1656 // Get a 0 padded day string
6b8e33dd 1657 var day = zeropad(d.getDate());
6a1aa64f 1658
6b8e33dd
DV
1659 var ret = "";
1660 var frac = d.getHours() * 3600 + d.getMinutes() * 60 + d.getSeconds();
bf640e56 1661 if (frac) ret = " " + Dygraph.hmsString_(date);
6b8e33dd
DV
1662
1663 return year + "/" + month + "/" + day + ret;
6a1aa64f
DV
1664};
1665
1666/**
6a1aa64f
DV
1667 * Fires when there's data available to be graphed.
1668 * @param {String} data Raw CSV data to be plotted
1669 * @private
1670 */
285a6bda 1671Dygraph.prototype.loadedEvent_ = function(data) {
6a1aa64f 1672 this.rawData_ = this.parseCSV_(data);
26ca7938 1673 this.predraw_();
6a1aa64f
DV
1674};
1675
285a6bda 1676Dygraph.prototype.months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
8846615a 1677 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
285a6bda 1678Dygraph.prototype.quarters = ["Jan", "Apr", "Jul", "Oct"];
6a1aa64f
DV
1679
1680/**
1681 * Add ticks on the x-axis representing years, months, quarters, weeks, or days
1682 * @private
1683 */
285a6bda 1684Dygraph.prototype.addXTicks_ = function() {
6a1aa64f 1685 // Determine the correct ticks scale on the x-axis: quarterly, monthly, ...
7201b11e 1686 var range;
6a1aa64f 1687 if (this.dateWindow_) {
7201b11e 1688 range = [this.dateWindow_[0], this.dateWindow_[1]];
6a1aa64f 1689 } else {
7201b11e
JB
1690 range = [this.rawData_[0][0], this.rawData_[this.rawData_.length - 1][0]];
1691 }
1692
1693 var formatter = this.attr_('xTicker');
1694 var ret = formatter(range[0], range[1], this);
1695 var xTicks = [];
1696
1697 if (ret.ticks !== undefined) {
6be8e54c 1698 // numericTicks() returns multiple values.
7201b11e 1699 xTicks = ret.ticks;
6be8e54c 1700 this.numXDigits_ = ret.numDigits;
7201b11e
JB
1701 } else {
1702 xTicks = ret;
3c1d225b 1703 }
7201b11e
JB
1704
1705 this.layout_.updateOptions({xTicks: xTicks});
32988383
DV
1706};
1707
1708// Time granularity enumeration
285a6bda 1709Dygraph.SECONDLY = 0;
20a41c17
DV
1710Dygraph.TWO_SECONDLY = 1;
1711Dygraph.FIVE_SECONDLY = 2;
1712Dygraph.TEN_SECONDLY = 3;
1713Dygraph.THIRTY_SECONDLY = 4;
1714Dygraph.MINUTELY = 5;
1715Dygraph.TWO_MINUTELY = 6;
1716Dygraph.FIVE_MINUTELY = 7;
1717Dygraph.TEN_MINUTELY = 8;
1718Dygraph.THIRTY_MINUTELY = 9;
1719Dygraph.HOURLY = 10;
1720Dygraph.TWO_HOURLY = 11;
1721Dygraph.SIX_HOURLY = 12;
1722Dygraph.DAILY = 13;
1723Dygraph.WEEKLY = 14;
1724Dygraph.MONTHLY = 15;
1725Dygraph.QUARTERLY = 16;
1726Dygraph.BIANNUAL = 17;
1727Dygraph.ANNUAL = 18;
1728Dygraph.DECADAL = 19;
062ef401
JB
1729Dygraph.CENTENNIAL = 20;
1730Dygraph.NUM_GRANULARITIES = 21;
285a6bda
DV
1731
1732Dygraph.SHORT_SPACINGS = [];
1733Dygraph.SHORT_SPACINGS[Dygraph.SECONDLY] = 1000 * 1;
20a41c17
DV
1734Dygraph.SHORT_SPACINGS[Dygraph.TWO_SECONDLY] = 1000 * 2;
1735Dygraph.SHORT_SPACINGS[Dygraph.FIVE_SECONDLY] = 1000 * 5;
285a6bda
DV
1736Dygraph.SHORT_SPACINGS[Dygraph.TEN_SECONDLY] = 1000 * 10;
1737Dygraph.SHORT_SPACINGS[Dygraph.THIRTY_SECONDLY] = 1000 * 30;
1738Dygraph.SHORT_SPACINGS[Dygraph.MINUTELY] = 1000 * 60;
20a41c17
DV
1739Dygraph.SHORT_SPACINGS[Dygraph.TWO_MINUTELY] = 1000 * 60 * 2;
1740Dygraph.SHORT_SPACINGS[Dygraph.FIVE_MINUTELY] = 1000 * 60 * 5;
285a6bda
DV
1741Dygraph.SHORT_SPACINGS[Dygraph.TEN_MINUTELY] = 1000 * 60 * 10;
1742Dygraph.SHORT_SPACINGS[Dygraph.THIRTY_MINUTELY] = 1000 * 60 * 30;
1743Dygraph.SHORT_SPACINGS[Dygraph.HOURLY] = 1000 * 3600;
20a41c17 1744Dygraph.SHORT_SPACINGS[Dygraph.TWO_HOURLY] = 1000 * 3600 * 2;
805d5519 1745Dygraph.SHORT_SPACINGS[Dygraph.SIX_HOURLY] = 1000 * 3600 * 6;
285a6bda
DV
1746Dygraph.SHORT_SPACINGS[Dygraph.DAILY] = 1000 * 86400;
1747Dygraph.SHORT_SPACINGS[Dygraph.WEEKLY] = 1000 * 604800;
32988383
DV
1748
1749// NumXTicks()
1750//
1751// If we used this time granularity, how many ticks would there be?
1752// This is only an approximation, but it's generally good enough.
1753//
285a6bda
DV
1754Dygraph.prototype.NumXTicks = function(start_time, end_time, granularity) {
1755 if (granularity < Dygraph.MONTHLY) {
32988383 1756 // Generate one tick mark for every fixed interval of time.
285a6bda 1757 var spacing = Dygraph.SHORT_SPACINGS[granularity];
32988383
DV
1758 return Math.floor(0.5 + 1.0 * (end_time - start_time) / spacing);
1759 } else {
1760 var year_mod = 1; // e.g. to only print one point every 10 years.
1761 var num_months = 12;
285a6bda
DV
1762 if (granularity == Dygraph.QUARTERLY) num_months = 3;
1763 if (granularity == Dygraph.BIANNUAL) num_months = 2;
1764 if (granularity == Dygraph.ANNUAL) num_months = 1;
1765 if (granularity == Dygraph.DECADAL) { num_months = 1; year_mod = 10; }
062ef401 1766 if (granularity == Dygraph.CENTENNIAL) { num_months = 1; year_mod = 100; }
32988383
DV
1767
1768 var msInYear = 365.2524 * 24 * 3600 * 1000;
1769 var num_years = 1.0 * (end_time - start_time) / msInYear;
1770 return Math.floor(0.5 + 1.0 * num_years * num_months / year_mod);
1771 }
1772};
1773
1774// GetXAxis()
1775//
1776// Construct an x-axis of nicely-formatted times on meaningful boundaries
1777// (e.g. 'Jan 09' rather than 'Jan 22, 2009').
1778//
1779// Returns an array containing {v: millis, label: label} dictionaries.
1780//
285a6bda 1781Dygraph.prototype.GetXAxis = function(start_time, end_time, granularity) {
bf640e56 1782 var formatter = this.attr_("xAxisLabelFormatter");
32988383 1783 var ticks = [];
285a6bda 1784 if (granularity < Dygraph.MONTHLY) {
32988383 1785 // Generate one tick mark for every fixed interval of time.
285a6bda 1786 var spacing = Dygraph.SHORT_SPACINGS[granularity];
3d29302c 1787 var format = '%d%b'; // e.g. "1Jan"
076c9622
DV
1788
1789 // Find a time less than start_time which occurs on a "nice" time boundary
1790 // for this granularity.
1791 var g = spacing / 1000;
076c9622
DV
1792 var d = new Date(start_time);
1793 if (g <= 60) { // seconds
1794 var x = d.getSeconds(); d.setSeconds(x - x % g);
1795 } else {
1796 d.setSeconds(0);
1797 g /= 60;
1798 if (g <= 60) { // minutes
1799 var x = d.getMinutes(); d.setMinutes(x - x % g);
1800 } else {
1801 d.setMinutes(0);
1802 g /= 60;
1803
1804 if (g <= 24) { // days
1805 var x = d.getHours(); d.setHours(x - x % g);
1806 } else {
1807 d.setHours(0);
1808 g /= 24;
1809
1810 if (g == 7) { // one week
20a41c17 1811 d.setDate(d.getDate() - d.getDay());
076c9622
DV
1812 }
1813 }
1814 }
328bb812 1815 }
076c9622
DV
1816 start_time = d.getTime();
1817
32988383 1818 for (var t = start_time; t <= end_time; t += spacing) {
bf640e56 1819 ticks.push({ v:t, label: formatter(new Date(t), granularity) });
32988383
DV
1820 }
1821 } else {
1822 // Display a tick mark on the first of a set of months of each year.
1823 // Years get a tick mark iff y % year_mod == 0. This is useful for
1824 // displaying a tick mark once every 10 years, say, on long time scales.
1825 var months;
1826 var year_mod = 1; // e.g. to only print one point every 10 years.
1827
285a6bda 1828 if (granularity == Dygraph.MONTHLY) {
32988383 1829 months = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ];
285a6bda 1830 } else if (granularity == Dygraph.QUARTERLY) {
32988383 1831 months = [ 0, 3, 6, 9 ];
285a6bda 1832 } else if (granularity == Dygraph.BIANNUAL) {
32988383 1833 months = [ 0, 6 ];
285a6bda 1834 } else if (granularity == Dygraph.ANNUAL) {
32988383 1835 months = [ 0 ];
285a6bda 1836 } else if (granularity == Dygraph.DECADAL) {
32988383
DV
1837 months = [ 0 ];
1838 year_mod = 10;
062ef401
JB
1839 } else if (granularity == Dygraph.CENTENNIAL) {
1840 months = [ 0 ];
1841 year_mod = 100;
1842 } else {
1843 this.warn("Span of dates is too long");
32988383
DV
1844 }
1845
1846 var start_year = new Date(start_time).getFullYear();
1847 var end_year = new Date(end_time).getFullYear();
285a6bda 1848 var zeropad = Dygraph.zeropad;
32988383
DV
1849 for (var i = start_year; i <= end_year; i++) {
1850 if (i % year_mod != 0) continue;
1851 for (var j = 0; j < months.length; j++) {
1852 var date_str = i + "/" + zeropad(1 + months[j]) + "/01";
1853 var t = Date.parse(date_str);
1854 if (t < start_time || t > end_time) continue;
bf640e56 1855 ticks.push({ v:t, label: formatter(new Date(t), granularity) });
32988383
DV
1856 }
1857 }
1858 }
1859
1860 return ticks;
1861};
1862
6a1aa64f
DV
1863
1864/**
1865 * Add ticks to the x-axis based on a date range.
1866 * @param {Number} startDate Start of the date window (millis since epoch)
1867 * @param {Number} endDate End of the date window (millis since epoch)
1868 * @return {Array.<Object>} Array of {label, value} tuples.
1869 * @public
1870 */
285a6bda 1871Dygraph.dateTicker = function(startDate, endDate, self) {
32988383 1872 var chosen = -1;
285a6bda
DV
1873 for (var i = 0; i < Dygraph.NUM_GRANULARITIES; i++) {
1874 var num_ticks = self.NumXTicks(startDate, endDate, i);
1875 if (self.width_ / num_ticks >= self.attr_('pixelsPerXLabel')) {
32988383
DV
1876 chosen = i;
1877 break;
2769de62 1878 }
6a1aa64f
DV
1879 }
1880
32988383 1881 if (chosen >= 0) {
285a6bda 1882 return self.GetXAxis(startDate, endDate, chosen);
6a1aa64f 1883 } else {
32988383 1884 // TODO(danvk): signal error.
6a1aa64f 1885 }
6a1aa64f
DV
1886};
1887
1888/**
3c1d225b
JB
1889 * Determine the number of significant figures in a Number up to the specified
1890 * precision. Note that there is no way to determine if a trailing '0' is
1891 * significant or not, so by convention we return 1 for all of the following
1892 * inputs: 1, 1.0, 1.00, 1.000 etc.
1893 * @param {Number} x The input value.
1894 * @param {Number} opt_maxPrecision Optional maximum precision to consider.
1895 * Default and maximum allowed value is 13.
1896 * @return {Number} The number of significant figures which is >= 1.
1897 */
1898Dygraph.significantFigures = function(x, opt_maxPrecision) {
1899 var precision = Math.max(opt_maxPrecision || 13, 13);
1900
fff1de86 1901 // Convert the number to its exponential notation form and work backwards,
3c1d225b
JB
1902 // ignoring the 'e+xx' bit. This may seem like a hack, but doing a loop and
1903 // dividing by 10 leads to roundoff errors. By using toExponential(), we let
1904 // the JavaScript interpreter handle the low level bits of the Number for us.
1905 var s = x.toExponential(precision);
1906 var ePos = s.lastIndexOf('e'); // -1 case handled by return below.
1907
1908 for (var i = ePos - 1; i >= 0; i--) {
1909 if (s[i] == '.') {
1910 // Got to the decimal place. We'll call this 1 digit of precision because
1911 // we can't know for sure how many trailing 0s are significant.
1912 return 1;
1913 } else if (s[i] != '0') {
1914 // Found the first non-zero digit. Return the number of characters
1915 // except for the '.'.
1916 return i; // This is i - 1 + 1 (-1 is for '.', +1 is for 0 based index).
1917 }
1918 }
1919
1920 // Occurs if toExponential() doesn't return a string containing 'e', which
1921 // should never happen.
1922 return 1;
1923};
1924
1925/**
6a1aa64f
DV
1926 * Add ticks when the x axis has numbers on it (instead of dates)
1927 * @param {Number} startDate Start of the date window (millis since epoch)
1928 * @param {Number} endDate End of the date window (millis since epoch)
84fc6aa7 1929 * @param self
f30cf740 1930 * @param {function} attribute accessor function.
6a1aa64f
DV
1931 * @return {Array.<Object>} Array of {label, value} tuples.
1932 * @public
1933 */
0d64e596 1934Dygraph.numericTicks = function(minV, maxV, self, axis_props, vals) {
70c80071
DV
1935 var attr = function(k) {
1936 if (axis_props && axis_props.hasOwnProperty(k)) return axis_props[k];
1937 return self.attr_(k);
1938 };
f09fc545 1939
0d64e596
DV
1940 var ticks = [];
1941 if (vals) {
1942 for (var i = 0; i < vals.length; i++) {
fff1de86 1943 ticks[i].push({v: vals[i]});
0d64e596 1944 }
f09e46d4 1945 } else {
0d64e596
DV
1946 // Basic idea:
1947 // Try labels every 1, 2, 5, 10, 20, 50, 100, etc.
1948 // Calculate the resulting tick spacing (i.e. this.height_ / nTicks).
1949 // The first spacing greater than pixelsPerYLabel is what we use.
1950 // TODO(danvk): version that works on a log scale.
f09fc545 1951 if (attr("labelsKMG2")) {
0d64e596 1952 var mults = [1, 2, 4, 8];
f09e46d4 1953 } else {
0d64e596 1954 var mults = [1, 2, 5];
f09e46d4 1955 }
0d64e596
DV
1956 var scale, low_val, high_val, nTicks;
1957 // TODO(danvk): make it possible to set this for x- and y-axes independently.
1958 var pixelsPerTick = attr('pixelsPerYLabel');
1959 for (var i = -10; i < 50; i++) {
1960 if (attr("labelsKMG2")) {
1961 var base_scale = Math.pow(16, i);
1962 } else {
1963 var base_scale = Math.pow(10, i);
1964 }
1965 for (var j = 0; j < mults.length; j++) {
1966 scale = base_scale * mults[j];
1967 low_val = Math.floor(minV / scale) * scale;
1968 high_val = Math.ceil(maxV / scale) * scale;
1969 nTicks = Math.abs(high_val - low_val) / scale;
1970 var spacing = self.height_ / nTicks;
1971 // wish I could break out of both loops at once...
1972 if (spacing > pixelsPerTick) break;
1973 }
285a6bda 1974 if (spacing > pixelsPerTick) break;
c6336f04 1975 }
0d64e596
DV
1976
1977 // Construct the set of ticks.
1978 // Allow reverse y-axis if it's explicitly requested.
1979 if (low_val > high_val) scale *= -1;
1980 for (var i = 0; i < nTicks; i++) {
1981 var tickV = low_val + i * scale;
fff1de86 1982 ticks.push( {v: tickV} );
0d64e596 1983 }
6a1aa64f
DV
1984 }
1985
0d64e596 1986 // Add formatted labels to the ticks.
ed11be50
DV
1987 var k;
1988 var k_labels = [];
f09fc545 1989 if (attr("labelsKMB")) {
ed11be50
DV
1990 k = 1000;
1991 k_labels = [ "K", "M", "B", "T" ];
1992 }
f09fc545 1993 if (attr("labelsKMG2")) {
ed11be50
DV
1994 if (k) self.warn("Setting both labelsKMB and labelsKMG2. Pick one!");
1995 k = 1024;
1996 k_labels = [ "k", "M", "G", "T" ];
1997 }
3c1d225b
JB
1998 var formatter = attr('yAxisLabelFormatter') ?
1999 attr('yAxisLabelFormatter') : attr('yValueFormatter');
2000
2001 // Determine the number of decimal places needed for the labels below by
2002 // taking the maximum number of significant figures for any label. We must
2003 // take the max because we can't tell if trailing 0s are significant.
2004 var numDigits = 0;
2005 for (var i = 0; i < ticks.length; i++) {
fff1de86 2006 numDigits = Math.max(Dygraph.significantFigures(ticks[i].v), numDigits);
3c1d225b 2007 }
ed11be50 2008
0d64e596
DV
2009 for (var i = 0; i < ticks.length; i++) {
2010 var tickV = ticks[i].v;
0af6e346 2011 var absTickV = Math.abs(tickV);
3c1d225b
JB
2012 var label = (formatter !== undefined) ?
2013 formatter(tickV, numDigits) : tickV.toPrecision(numDigits);
2014 if (k_labels.length > 0) {
ed11be50
DV
2015 // Round up to an appropriate unit.
2016 var n = k*k*k*k;
2017 for (var j = 3; j >= 0; j--, n /= k) {
2018 if (absTickV >= n) {
3c1d225b 2019 label = (tickV / n).toPrecision(numDigits) + k_labels[j];
ed11be50
DV
2020 break;
2021 }
afefbcdb 2022 }
6a1aa64f 2023 }
0d64e596 2024 ticks[i].label = label;
6a1aa64f 2025 }
3c1d225b 2026 return {ticks: ticks, numDigits: numDigits};
6a1aa64f
DV
2027};
2028
5011e7a1
DV
2029// Computes the range of the data series (including confidence intervals).
2030// series is either [ [x1, y1], [x2, y2], ... ] or
2031// [ [x1, [y1, dev_low, dev_high]], [x2, [y2, dev_low, dev_high]], ...
2032// Returns [low, high]
2033Dygraph.prototype.extremeValues_ = function(series) {
2034 var minY = null, maxY = null;
2035
9922b78b 2036 var bars = this.attr_("errorBars") || this.attr_("customBars");
5011e7a1
DV
2037 if (bars) {
2038 // With custom bars, maxY is the max of the high values.
2039 for (var j = 0; j < series.length; j++) {
2040 var y = series[j][1][0];
2041 if (!y) continue;
2042 var low = y - series[j][1][1];
2043 var high = y + series[j][1][2];
2044 if (low > y) low = y; // this can happen with custom bars,
2045 if (high < y) high = y; // e.g. in tests/custom-bars.html
2046 if (maxY == null || high > maxY) {
2047 maxY = high;
2048 }
2049 if (minY == null || low < minY) {
2050 minY = low;
2051 }
2052 }
2053 } else {
2054 for (var j = 0; j < series.length; j++) {
2055 var y = series[j][1];
d12999d3 2056 if (y === null || isNaN(y)) continue;
5011e7a1
DV
2057 if (maxY == null || y > maxY) {
2058 maxY = y;
2059 }
2060 if (minY == null || y < minY) {
2061 minY = y;
2062 }
2063 }
2064 }
2065
2066 return [minY, maxY];
2067};
2068
6a1aa64f 2069/**
26ca7938
DV
2070 * This function is called once when the chart's data is changed or the options
2071 * dictionary is updated. It is _not_ called when the user pans or zooms. The
2072 * idea is that values derived from the chart's data can be computed here,
2073 * rather than every time the chart is drawn. This includes things like the
2074 * number of axes, rolling averages, etc.
2075 */
2076Dygraph.prototype.predraw_ = function() {
2077 // TODO(danvk): move more computations out of drawGraph_ and into here.
2078 this.computeYAxes_();
2079
2080 // Create a new plotter.
70c80071 2081 if (this.plotter_) this.plotter_.clear();
26ca7938
DV
2082 this.plotter_ = new DygraphCanvasRenderer(this,
2083 this.hidden_, this.layout_,
2084 this.renderOptions_);
2085
0abfbd7e
DV
2086 // The roller sits in the bottom left corner of the chart. We don't know where
2087 // this will be until the options are available, so it's positioned here.
8c69de65 2088 this.createRollInterface_();
26ca7938 2089
0abfbd7e
DV
2090 // Same thing applies for the labelsDiv. It's right edge should be flush with
2091 // the right edge of the charting area (which may not be the same as the right
2092 // edge of the div, if we have two y-axes.
2093 this.positionLabelsDiv_();
2094
26ca7938
DV
2095 // If the data or options have changed, then we'd better redraw.
2096 this.drawGraph_();
2097};
2098
2099/**
2f5e7e1a 2100=======
26ca7938
DV
2101 * Update the graph with new data. This method is called when the viewing area
2102 * has changed. If the underlying data or options have changed, predraw_ will
2103 * be called before drawGraph_ is called.
6a1aa64f
DV
2104 * @private
2105 */
26ca7938
DV
2106Dygraph.prototype.drawGraph_ = function() {
2107 var data = this.rawData_;
2108
fe0b7c03
DV
2109 // This is used to set the second parameter to drawCallback, below.
2110 var is_initial_draw = this.is_initial_draw_;
2111 this.is_initial_draw_ = false;
2112
3bd9c228 2113 var minY = null, maxY = null;
6a1aa64f 2114 this.layout_.removeAllDatasets();
285a6bda 2115 this.setColors_();
9317362d 2116 this.attrs_['pointSize'] = 0.5 * this.attr_('highlightCircleSize');
285a6bda 2117
354e15ab
DE
2118 // Loop over the fields (series). Go from the last to the first,
2119 // because if they're stacked that's how we accumulate the values.
43af96e7 2120
354e15ab
DE
2121 var cumulative_y = []; // For stacked series.
2122 var datasets = [];
2123
f09fc545
DV
2124 var extremes = {}; // series name -> [low, high]
2125
354e15ab
DE
2126 // Loop over all fields and create datasets
2127 for (var i = data[0].length - 1; i >= 1; i--) {
1cf11047
DV
2128 if (!this.visibility()[i - 1]) continue;
2129
f09fc545 2130 var seriesName = this.attr_("labels")[i];
450fe64b
DV
2131 var connectSeparatedPoints = this.attr_('connectSeparatedPoints', i);
2132
6a1aa64f
DV
2133 var series = [];
2134 for (var j = 0; j < data.length; j++) {
4a634fc7 2135 if (data[j][i] != null || !connectSeparatedPoints) {
f032c51d 2136 var date = data[j][0];
563c70ca 2137 series.push([date, data[j][i]]);
f032c51d 2138 }
6a1aa64f 2139 }
2f5e7e1a
DV
2140
2141 // TODO(danvk): move this into predraw_. It's insane to do it here.
6a1aa64f
DV
2142 series = this.rollingAverage(series, this.rollPeriod_);
2143
2144 // Prune down to the desired range, if necessary (for zooming)
1a26f3fb
DV
2145 // Because there can be lines going to points outside of the visible area,
2146 // we actually prune to visible points, plus one on either side.
9922b78b 2147 var bars = this.attr_("errorBars") || this.attr_("customBars");
6a1aa64f
DV
2148 if (this.dateWindow_) {
2149 var low = this.dateWindow_[0];
2150 var high= this.dateWindow_[1];
2151 var pruned = [];
1a26f3fb
DV
2152 // TODO(danvk): do binary search instead of linear search.
2153 // TODO(danvk): pass firstIdx and lastIdx directly to the renderer.
2154 var firstIdx = null, lastIdx = null;
6a1aa64f 2155 for (var k = 0; k < series.length; k++) {
1a26f3fb
DV
2156 if (series[k][0] >= low && firstIdx === null) {
2157 firstIdx = k;
2158 }
2159 if (series[k][0] <= high) {
2160 lastIdx = k;
6a1aa64f
DV
2161 }
2162 }
1a26f3fb
DV
2163 if (firstIdx === null) firstIdx = 0;
2164 if (firstIdx > 0) firstIdx--;
2165 if (lastIdx === null) lastIdx = series.length - 1;
2166 if (lastIdx < series.length - 1) lastIdx++;
16269f6e 2167 this.boundaryIds_[i-1] = [firstIdx, lastIdx];
1a26f3fb
DV
2168 for (var k = firstIdx; k <= lastIdx; k++) {
2169 pruned.push(series[k]);
6a1aa64f
DV
2170 }
2171 series = pruned;
16269f6e
NAG
2172 } else {
2173 this.boundaryIds_[i-1] = [0, series.length-1];
6a1aa64f
DV
2174 }
2175
f09fc545 2176 var seriesExtremes = this.extremeValues_(series);
5011e7a1 2177
6a1aa64f 2178 if (bars) {
354e15ab
DE
2179 for (var j=0; j<series.length; j++) {
2180 val = [series[j][0], series[j][1][0], series[j][1][1], series[j][1][2]];
2181 series[j] = val;
2182 }
43af96e7 2183 } else if (this.attr_("stackedGraph")) {
43af96e7
NK
2184 var l = series.length;
2185 var actual_y;
2186 for (var j = 0; j < l; j++) {
354e15ab
DE
2187 // If one data set has a NaN, let all subsequent stacked
2188 // sets inherit the NaN -- only start at 0 for the first set.
2189 var x = series[j][0];
41b0f691 2190 if (cumulative_y[x] === undefined) {
354e15ab 2191 cumulative_y[x] = 0;
41b0f691 2192 }
43af96e7
NK
2193
2194 actual_y = series[j][1];
354e15ab 2195 cumulative_y[x] += actual_y;
43af96e7 2196
354e15ab 2197 series[j] = [x, cumulative_y[x]]
43af96e7 2198
41b0f691
DV
2199 if (cumulative_y[x] > seriesExtremes[1]) {
2200 seriesExtremes[1] = cumulative_y[x];
2201 }
2202 if (cumulative_y[x] < seriesExtremes[0]) {
2203 seriesExtremes[0] = cumulative_y[x];
2204 }
43af96e7 2205 }
6a1aa64f 2206 }
41b0f691 2207 extremes[seriesName] = seriesExtremes;
354e15ab
DE
2208
2209 datasets[i] = series;
6a1aa64f
DV
2210 }
2211
354e15ab 2212 for (var i = 1; i < datasets.length; i++) {
4523c1f6 2213 if (!this.visibility()[i - 1]) continue;
354e15ab 2214 this.layout_.addDataset(this.attr_("labels")[i], datasets[i]);
43af96e7
NK
2215 }
2216
6faebb69
JB
2217 this.computeYAxisRanges_(extremes);
2218 this.layout_.updateOptions( { yAxes: this.axes_,
2219 seriesToAxisMap: this.seriesToAxisMap_
9012dd21 2220 } );
f09fc545 2221
6a1aa64f
DV
2222 this.addXTicks_();
2223
2224 // Tell PlotKit to use this new data and render itself
d033ae1c 2225 this.layout_.updateOptions({dateWindow: this.dateWindow_});
6a1aa64f
DV
2226 this.layout_.evaluateWithError();
2227 this.plotter_.clear();
2228 this.plotter_.render();
f6401bf6 2229 this.canvas_.getContext('2d').clearRect(0, 0, this.canvas_.width,
2f5e7e1a 2230 this.canvas_.height);
599fb4ad
DV
2231
2232 if (this.attr_("drawCallback") !== null) {
fe0b7c03 2233 this.attr_("drawCallback")(this, is_initial_draw);
599fb4ad 2234 }
6a1aa64f
DV
2235};
2236
2237/**
26ca7938
DV
2238 * Determine properties of the y-axes which are independent of the data
2239 * currently being displayed. This includes things like the number of axes and
2240 * the style of the axes. It does not include the range of each axis and its
2241 * tick marks.
2242 * This fills in this.axes_ and this.seriesToAxisMap_.
2243 * axes_ = [ { options } ]
2244 * seriesToAxisMap_ = { seriesName: 0, seriesName2: 1, ... }
2245 * indices are into the axes_ array.
f09fc545 2246 */
26ca7938
DV
2247Dygraph.prototype.computeYAxes_ = function() {
2248 this.axes_ = [{}]; // always have at least one y-axis.
2249 this.seriesToAxisMap_ = {};
2250
2251 // Get a list of series names.
2252 var labels = this.attr_("labels");
1c77a3a1 2253 var series = {};
26ca7938 2254 for (var i = 1; i < labels.length; i++) series[labels[i]] = (i - 1);
f09fc545
DV
2255
2256 // all options which could be applied per-axis:
2257 var axisOptions = [
2258 'includeZero',
2259 'valueRange',
2260 'labelsKMB',
2261 'labelsKMG2',
2262 'pixelsPerYLabel',
2263 'yAxisLabelWidth',
2264 'axisLabelFontSize',
2265 'axisTickSize'
2266 ];
2267
2268 // Copy global axis options over to the first axis.
2269 for (var i = 0; i < axisOptions.length; i++) {
2270 var k = axisOptions[i];
2271 var v = this.attr_(k);
26ca7938 2272 if (v) this.axes_[0][k] = v;
f09fc545
DV
2273 }
2274
2275 // Go through once and add all the axes.
26ca7938
DV
2276 for (var seriesName in series) {
2277 if (!series.hasOwnProperty(seriesName)) continue;
f09fc545
DV
2278 var axis = this.attr_("axis", seriesName);
2279 if (axis == null) {
26ca7938 2280 this.seriesToAxisMap_[seriesName] = 0;
f09fc545
DV
2281 continue;
2282 }
2283 if (typeof(axis) == 'object') {
2284 // Add a new axis, making a copy of its per-axis options.
2285 var opts = {};
26ca7938 2286 Dygraph.update(opts, this.axes_[0]);
f09fc545
DV
2287 Dygraph.update(opts, { valueRange: null }); // shouldn't inherit this.
2288 Dygraph.update(opts, axis);
26ca7938
DV
2289 this.axes_.push(opts);
2290 this.seriesToAxisMap_[seriesName] = this.axes_.length - 1;
f09fc545
DV
2291 }
2292 }
2293
2294 // Go through one more time and assign series to an axis defined by another
2295 // series, e.g. { 'Y1: { axis: {} }, 'Y2': { axis: 'Y1' } }
26ca7938
DV
2296 for (var seriesName in series) {
2297 if (!series.hasOwnProperty(seriesName)) continue;
f09fc545
DV
2298 var axis = this.attr_("axis", seriesName);
2299 if (typeof(axis) == 'string') {
26ca7938 2300 if (!this.seriesToAxisMap_.hasOwnProperty(axis)) {
f09fc545
DV
2301 this.error("Series " + seriesName + " wants to share a y-axis with " +
2302 "series " + axis + ", which does not define its own axis.");
2303 return null;
2304 }
26ca7938
DV
2305 var idx = this.seriesToAxisMap_[axis];
2306 this.seriesToAxisMap_[seriesName] = idx;
f09fc545
DV
2307 }
2308 }
1c77a3a1
DV
2309
2310 // Now we remove series from seriesToAxisMap_ which are not visible. We do
2311 // this last so that hiding the first series doesn't destroy the axis
2312 // properties of the primary axis.
2313 var seriesToAxisFiltered = {};
2314 var vis = this.visibility();
2315 for (var i = 1; i < labels.length; i++) {
2316 var s = labels[i];
2317 if (vis[i - 1]) seriesToAxisFiltered[s] = this.seriesToAxisMap_[s];
2318 }
2319 this.seriesToAxisMap_ = seriesToAxisFiltered;
26ca7938
DV
2320};
2321
2322/**
2323 * Returns the number of y-axes on the chart.
2324 * @return {Number} the number of axes.
2325 */
2326Dygraph.prototype.numAxes = function() {
2327 var last_axis = 0;
2328 for (var series in this.seriesToAxisMap_) {
2329 if (!this.seriesToAxisMap_.hasOwnProperty(series)) continue;
2330 var idx = this.seriesToAxisMap_[series];
2331 if (idx > last_axis) last_axis = idx;
2332 }
2333 return 1 + last_axis;
2334};
2335
2336/**
2337 * Determine the value range and tick marks for each axis.
2338 * @param {Object} extremes A mapping from seriesName -> [low, high]
2339 * This fills in the valueRange and ticks fields in each entry of this.axes_.
2340 */
2341Dygraph.prototype.computeYAxisRanges_ = function(extremes) {
2342 // Build a map from axis number -> [list of series names]
2343 var seriesForAxis = [];
2344 for (var series in this.seriesToAxisMap_) {
2345 if (!this.seriesToAxisMap_.hasOwnProperty(series)) continue;
2346 var idx = this.seriesToAxisMap_[series];
2347 while (seriesForAxis.length <= idx) seriesForAxis.push([]);
2348 seriesForAxis[idx].push(series);
2349 }
f09fc545
DV
2350
2351 // Compute extreme values, a span and tick marks for each axis.
26ca7938
DV
2352 for (var i = 0; i < this.axes_.length; i++) {
2353 var axis = this.axes_[i];
d58ae307
DV
2354 if (axis.valueWindow) {
2355 // This is only set if the user has zoomed on the y-axis. It is never set
2356 // by a user. It takes precedence over axis.valueRange because, if you set
2357 // valueRange, you'd still expect to be able to pan.
2358 axis.computedValueRange = [axis.valueWindow[0], axis.valueWindow[1]];
2359 } else if (axis.valueRange) {
2360 // This is a user-set value range for this axis.
26ca7938
DV
2361 axis.computedValueRange = [axis.valueRange[0], axis.valueRange[1]];
2362 } else {
1c77a3a1 2363 // Calculate the extremes of extremes.
f09fc545
DV
2364 var series = seriesForAxis[i];
2365 var minY = Infinity; // extremes[series[0]][0];
2366 var maxY = -Infinity; // extremes[series[0]][1];
2367 for (var j = 0; j < series.length; j++) {
2368 minY = Math.min(extremes[series[j]][0], minY);
e3b6727e 2369 maxY = Math.max(extremes[series[j]][1], maxY);
f09fc545
DV
2370 }
2371 if (axis.includeZero && minY > 0) minY = 0;
2372
2373 // Add some padding and round up to an integer to be human-friendly.
2374 var span = maxY - minY;
2375 // special case: if we have no sense of scale, use +/-10% of the sole value.
2376 if (span == 0) { span = maxY; }
2377 var maxAxisY = maxY + 0.1 * span;
2378 var minAxisY = minY - 0.1 * span;
2379
2380 // Try to include zero and make it minAxisY (or maxAxisY) if it makes sense.
2f5e7e1a
DV
2381 if (!this.attr_("avoidMinZero")) {
2382 if (minAxisY < 0 && minY >= 0) minAxisY = 0;
2383 if (maxAxisY > 0 && maxY <= 0) maxAxisY = 0;
2384 }
f09fc545
DV
2385
2386 if (this.attr_("includeZero")) {
2387 if (maxY < 0) maxAxisY = 0;
2388 if (minY > 0) minAxisY = 0;
2389 }
2390
26ca7938 2391 axis.computedValueRange = [minAxisY, maxAxisY];
f09fc545
DV
2392 }
2393
0d64e596
DV
2394 // Add ticks. By default, all axes inherit the tick positions of the
2395 // primary axis. However, if an axis is specifically marked as having
2396 // independent ticks, then that is permissible as well.
2397 if (i == 0 || axis.independentTicks) {
3c1d225b 2398 var ret =
0d64e596
DV
2399 Dygraph.numericTicks(axis.computedValueRange[0],
2400 axis.computedValueRange[1],
2401 this,
2402 axis);
3c1d225b 2403 axis.ticks = ret.ticks;
6be8e54c 2404 this.numYDigits_ = ret.numDigits;
0d64e596
DV
2405 } else {
2406 var p_axis = this.axes_[0];
2407 var p_ticks = p_axis.ticks;
2408 var p_scale = p_axis.computedValueRange[1] - p_axis.computedValueRange[0];
2409 var scale = axis.computedValueRange[1] - axis.computedValueRange[0];
2410 var tick_values = [];
2411 for (var i = 0; i < p_ticks.length; i++) {
2412 var y_frac = (p_ticks[i].v - p_axis.computedValueRange[0]) / p_scale;
2413 var y_val = axis.computedValueRange[0] + y_frac * scale;
2414 tick_values.push(y_val);
2415 }
2416
3c1d225b 2417 var ret =
0d64e596
DV
2418 Dygraph.numericTicks(axis.computedValueRange[0],
2419 axis.computedValueRange[1],
2420 this, axis, tick_values);
3c1d225b 2421 axis.ticks = ret.ticks;
6be8e54c 2422 this.numYDigits_ = ret.numDigits;
0d64e596 2423 }
f09fc545 2424 }
f09fc545
DV
2425};
2426
2427/**
6a1aa64f
DV
2428 * Calculates the rolling average of a data set.
2429 * If originalData is [label, val], rolls the average of those.
2430 * If originalData is [label, [, it's interpreted as [value, stddev]
2431 * and the roll is returned in the same form, with appropriately reduced
2432 * stddev for each value.
2433 * Note that this is where fractional input (i.e. '5/10') is converted into
2434 * decimal values.
2435 * @param {Array} originalData The data in the appropriate format (see above)
6faebb69
JB
2436 * @param {Number} rollPeriod The number of points over which to average the
2437 * data
6a1aa64f 2438 */
285a6bda 2439Dygraph.prototype.rollingAverage = function(originalData, rollPeriod) {
6a1aa64f
DV
2440 if (originalData.length < 2)
2441 return originalData;
2442 var rollPeriod = Math.min(rollPeriod, originalData.length - 1);
2443 var rollingData = [];
285a6bda 2444 var sigma = this.attr_("sigma");
6a1aa64f
DV
2445
2446 if (this.fractions_) {
2447 var num = 0;
2448 var den = 0; // numerator/denominator
2449 var mult = 100.0;
2450 for (var i = 0; i < originalData.length; i++) {
2451 num += originalData[i][1][0];
2452 den += originalData[i][1][1];
2453 if (i - rollPeriod >= 0) {
2454 num -= originalData[i - rollPeriod][1][0];
2455 den -= originalData[i - rollPeriod][1][1];
2456 }
2457
2458 var date = originalData[i][0];
2459 var value = den ? num / den : 0.0;
285a6bda 2460 if (this.attr_("errorBars")) {
6a1aa64f
DV
2461 if (this.wilsonInterval_) {
2462 // For more details on this confidence interval, see:
2463 // http://en.wikipedia.org/wiki/Binomial_confidence_interval
2464 if (den) {
2465 var p = value < 0 ? 0 : value, n = den;
2466 var pm = sigma * Math.sqrt(p*(1-p)/n + sigma*sigma/(4*n*n));
2467 var denom = 1 + sigma * sigma / den;
2468 var low = (p + sigma * sigma / (2 * den) - pm) / denom;
2469 var high = (p + sigma * sigma / (2 * den) + pm) / denom;
2470 rollingData[i] = [date,
2471 [p * mult, (p - low) * mult, (high - p) * mult]];
2472 } else {
2473 rollingData[i] = [date, [0, 0, 0]];
2474 }
2475 } else {
2476 var stddev = den ? sigma * Math.sqrt(value * (1 - value) / den) : 1.0;
2477 rollingData[i] = [date, [mult * value, mult * stddev, mult * stddev]];
2478 }
2479 } else {
2480 rollingData[i] = [date, mult * value];
2481 }
2482 }
9922b78b 2483 } else if (this.attr_("customBars")) {
f6885d6a
DV
2484 var low = 0;
2485 var mid = 0;
2486 var high = 0;
2487 var count = 0;
6a1aa64f
DV
2488 for (var i = 0; i < originalData.length; i++) {
2489 var data = originalData[i][1];
2490 var y = data[1];
2491 rollingData[i] = [originalData[i][0], [y, y - data[0], data[2] - y]];
f6885d6a 2492
8b91c51f 2493 if (y != null && !isNaN(y)) {
49a7d0d5
DV
2494 low += data[0];
2495 mid += y;
2496 high += data[2];
2497 count += 1;
2498 }
f6885d6a
DV
2499 if (i - rollPeriod >= 0) {
2500 var prev = originalData[i - rollPeriod];
8b91c51f 2501 if (prev[1][1] != null && !isNaN(prev[1][1])) {
49a7d0d5
DV
2502 low -= prev[1][0];
2503 mid -= prev[1][1];
2504 high -= prev[1][2];
2505 count -= 1;
2506 }
f6885d6a
DV
2507 }
2508 rollingData[i] = [originalData[i][0], [ 1.0 * mid / count,
2509 1.0 * (mid - low) / count,
2510 1.0 * (high - mid) / count ]];
2769de62 2511 }
6a1aa64f
DV
2512 } else {
2513 // Calculate the rolling average for the first rollPeriod - 1 points where
6faebb69 2514 // there is not enough data to roll over the full number of points
6a1aa64f 2515 var num_init_points = Math.min(rollPeriod - 1, originalData.length - 2);
285a6bda 2516 if (!this.attr_("errorBars")){
5011e7a1
DV
2517 if (rollPeriod == 1) {
2518 return originalData;
2519 }
2520
2847c1cf 2521 for (var i = 0; i < originalData.length; i++) {
6a1aa64f 2522 var sum = 0;
5011e7a1 2523 var num_ok = 0;
2847c1cf
DV
2524 for (var j = Math.max(0, i - rollPeriod + 1); j < i + 1; j++) {
2525 var y = originalData[j][1];
8b91c51f 2526 if (y == null || isNaN(y)) continue;
5011e7a1 2527 num_ok++;
2847c1cf 2528 sum += originalData[j][1];
6a1aa64f 2529 }
5011e7a1 2530 if (num_ok) {
2847c1cf 2531 rollingData[i] = [originalData[i][0], sum / num_ok];
5011e7a1 2532 } else {
2847c1cf 2533 rollingData[i] = [originalData[i][0], null];
5011e7a1 2534 }
6a1aa64f 2535 }
2847c1cf
DV
2536
2537 } else {
2538 for (var i = 0; i < originalData.length; i++) {
6a1aa64f
DV
2539 var sum = 0;
2540 var variance = 0;
5011e7a1 2541 var num_ok = 0;
2847c1cf 2542 for (var j = Math.max(0, i - rollPeriod + 1); j < i + 1; j++) {
5011e7a1 2543 var y = originalData[j][1][0];
8b91c51f 2544 if (y == null || isNaN(y)) continue;
5011e7a1 2545 num_ok++;
6a1aa64f
DV
2546 sum += originalData[j][1][0];
2547 variance += Math.pow(originalData[j][1][1], 2);
2548 }
5011e7a1
DV
2549 if (num_ok) {
2550 var stddev = Math.sqrt(variance) / num_ok;
2551 rollingData[i] = [originalData[i][0],
2552 [sum / num_ok, sigma * stddev, sigma * stddev]];
2553 } else {
2554 rollingData[i] = [originalData[i][0], [null, null, null]];
2555 }
6a1aa64f
DV
2556 }
2557 }
2558 }
2559
2560 return rollingData;
2561};
2562
2563/**
2564 * Parses a date, returning the number of milliseconds since epoch. This can be
285a6bda
DV
2565 * passed in as an xValueParser in the Dygraph constructor.
2566 * TODO(danvk): enumerate formats that this understands.
6a1aa64f
DV
2567 * @param {String} A date in YYYYMMDD format.
2568 * @return {Number} Milliseconds since epoch.
2569 * @public
2570 */
285a6bda 2571Dygraph.dateParser = function(dateStr, self) {
6a1aa64f 2572 var dateStrSlashed;
285a6bda 2573 var d;
986a5026 2574 if (dateStr.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12'
6a1aa64f 2575 dateStrSlashed = dateStr.replace("-", "/", "g");
353a0294
DV
2576 while (dateStrSlashed.search("-") != -1) {
2577 dateStrSlashed = dateStrSlashed.replace("-", "/");
2578 }
285a6bda 2579 d = Date.parse(dateStrSlashed);
2769de62 2580 } else if (dateStr.length == 8) { // e.g. '20090712'
285a6bda 2581 // TODO(danvk): remove support for this format. It's confusing.
6a1aa64f
DV
2582 dateStrSlashed = dateStr.substr(0,4) + "/" + dateStr.substr(4,2)
2583 + "/" + dateStr.substr(6,2);
285a6bda 2584 d = Date.parse(dateStrSlashed);
2769de62
DV
2585 } else {
2586 // Any format that Date.parse will accept, e.g. "2009/07/12" or
2587 // "2009/07/12 12:34:56"
285a6bda
DV
2588 d = Date.parse(dateStr);
2589 }
2590
2591 if (!d || isNaN(d)) {
2592 self.error("Couldn't parse " + dateStr + " as a date");
2593 }
2594 return d;
2595};
2596
2597/**
2598 * Detects the type of the str (date or numeric) and sets the various
2599 * formatting attributes in this.attrs_ based on this type.
2600 * @param {String} str An x value.
2601 * @private
2602 */
2603Dygraph.prototype.detectTypeFromString_ = function(str) {
2604 var isDate = false;
2605 if (str.indexOf('-') >= 0 ||
2606 str.indexOf('/') >= 0 ||
2607 isNaN(parseFloat(str))) {
2608 isDate = true;
2609 } else if (str.length == 8 && str > '19700101' && str < '20371231') {
2610 // TODO(danvk): remove support for this format.
2611 isDate = true;
2612 }
2613
2614 if (isDate) {
2615 this.attrs_.xValueFormatter = Dygraph.dateString_;
2616 this.attrs_.xValueParser = Dygraph.dateParser;
2617 this.attrs_.xTicker = Dygraph.dateTicker;
bf640e56 2618 this.attrs_.xAxisLabelFormatter = Dygraph.dateAxisFormatter;
285a6bda 2619 } else {
7201b11e 2620 this.attrs_.xValueFormatter = this.attrs_.xValueFormatter;
285a6bda
DV
2621 this.attrs_.xValueParser = function(x) { return parseFloat(x); };
2622 this.attrs_.xTicker = Dygraph.numericTicks;
bf640e56 2623 this.attrs_.xAxisLabelFormatter = this.attrs_.xValueFormatter;
6a1aa64f 2624 }
6a1aa64f
DV
2625};
2626
2627/**
2628 * Parses a string in a special csv format. We expect a csv file where each
2629 * line is a date point, and the first field in each line is the date string.
2630 * We also expect that all remaining fields represent series.
285a6bda 2631 * if the errorBars attribute is set, then interpret the fields as:
6a1aa64f
DV
2632 * date, series1, stddev1, series2, stddev2, ...
2633 * @param {Array.<Object>} data See above.
2634 * @private
285a6bda
DV
2635 *
2636 * @return Array.<Object> An array with one entry for each row. These entries
2637 * are an array of cells in that row. The first entry is the parsed x-value for
2638 * the row. The second, third, etc. are the y-values. These can take on one of
2639 * three forms, depending on the CSV and constructor parameters:
2640 * 1. numeric value
2641 * 2. [ value, stddev ]
2642 * 3. [ low value, center value, high value ]
6a1aa64f 2643 */
285a6bda 2644Dygraph.prototype.parseCSV_ = function(data) {
6a1aa64f
DV
2645 var ret = [];
2646 var lines = data.split("\n");
3d67f03b
DV
2647
2648 // Use the default delimiter or fall back to a tab if that makes sense.
2649 var delim = this.attr_('delimiter');
2650 if (lines[0].indexOf(delim) == -1 && lines[0].indexOf('\t') >= 0) {
2651 delim = '\t';
2652 }
2653
285a6bda 2654 var start = 0;
6a1aa64f 2655 if (this.labelsFromCSV_) {
285a6bda 2656 start = 1;
3d67f03b 2657 this.attrs_.labels = lines[0].split(delim);
6a1aa64f
DV
2658 }
2659
03b522a4
DV
2660 // Parse the x as a float or return null if it's not a number.
2661 var parseFloatOrNull = function(x) {
41333ec0 2662 var val = parseFloat(x);
1f7f664b
DV
2663 // isFinite() returns false for NaN and +/-Infinity.
2664 return isFinite(val) ? val : null;
03b522a4
DV
2665 };
2666
285a6bda
DV
2667 var xParser;
2668 var defaultParserSet = false; // attempt to auto-detect x value type
2669 var expectedCols = this.attr_("labels").length;
987840a2 2670 var outOfOrder = false;
6a1aa64f
DV
2671 for (var i = start; i < lines.length; i++) {
2672 var line = lines[i];
2673 if (line.length == 0) continue; // skip blank lines
3d67f03b
DV
2674 if (line[0] == '#') continue; // skip comment lines
2675 var inFields = line.split(delim);
285a6bda 2676 if (inFields.length < 2) continue;
6a1aa64f
DV
2677
2678 var fields = [];
285a6bda
DV
2679 if (!defaultParserSet) {
2680 this.detectTypeFromString_(inFields[0]);
2681 xParser = this.attr_("xValueParser");
2682 defaultParserSet = true;
2683 }
2684 fields[0] = xParser(inFields[0], this);
6a1aa64f
DV
2685
2686 // If fractions are expected, parse the numbers as "A/B"
2687 if (this.fractions_) {
2688 for (var j = 1; j < inFields.length; j++) {
2689 // TODO(danvk): figure out an appropriate way to flag parse errors.
2690 var vals = inFields[j].split("/");
03b522a4 2691 fields[j] = [parseFloatOrNull(vals[0]), parseFloatOrNull(vals[1])];
6a1aa64f 2692 }
285a6bda 2693 } else if (this.attr_("errorBars")) {
6a1aa64f
DV
2694 // If there are error bars, values are (value, stddev) pairs
2695 for (var j = 1; j < inFields.length; j += 2)
03b522a4
DV
2696 fields[(j + 1) / 2] = [parseFloatOrNull(inFields[j]),
2697 parseFloatOrNull(inFields[j + 1])];
9922b78b 2698 } else if (this.attr_("customBars")) {
6a1aa64f
DV
2699 // Bars are a low;center;high tuple
2700 for (var j = 1; j < inFields.length; j++) {
2701 var vals = inFields[j].split(";");
03b522a4
DV
2702 fields[j] = [ parseFloatOrNull(vals[0]),
2703 parseFloatOrNull(vals[1]),
2704 parseFloatOrNull(vals[2]) ];
6a1aa64f
DV
2705 }
2706 } else {
2707 // Values are just numbers
285a6bda 2708 for (var j = 1; j < inFields.length; j++) {
03b522a4 2709 fields[j] = parseFloatOrNull(inFields[j]);
285a6bda 2710 }
6a1aa64f 2711 }
987840a2
DV
2712 if (ret.length > 0 && fields[0] < ret[ret.length - 1][0]) {
2713 outOfOrder = true;
2714 }
6a1aa64f 2715 ret.push(fields);
285a6bda
DV
2716
2717 if (fields.length != expectedCols) {
2718 this.error("Number of columns in line " + i + " (" + fields.length +
2719 ") does not agree with number of labels (" + expectedCols +
2720 ") " + line);
2721 }
6a1aa64f 2722 }
987840a2
DV
2723
2724 if (outOfOrder) {
2725 this.warn("CSV is out of order; order it correctly to speed loading.");
2726 ret.sort(function(a,b) { return a[0] - b[0] });
2727 }
2728
6a1aa64f
DV
2729 return ret;
2730};
2731
2732/**
285a6bda
DV
2733 * The user has provided their data as a pre-packaged JS array. If the x values
2734 * are numeric, this is the same as dygraphs' internal format. If the x values
2735 * are dates, we need to convert them from Date objects to ms since epoch.
2736 * @param {Array.<Object>} data
2737 * @return {Array.<Object>} data with numeric x values.
2738 */
2739Dygraph.prototype.parseArray_ = function(data) {
2740 // Peek at the first x value to see if it's numeric.
2741 if (data.length == 0) {
2742 this.error("Can't plot empty data set");
2743 return null;
2744 }
2745 if (data[0].length == 0) {
2746 this.error("Data set cannot contain an empty row");
2747 return null;
2748 }
2749
2750 if (this.attr_("labels") == null) {
2751 this.warn("Using default labels. Set labels explicitly via 'labels' " +
2752 "in the options parameter");
2753 this.attrs_.labels = [ "X" ];
2754 for (var i = 1; i < data[0].length; i++) {
2755 this.attrs_.labels.push("Y" + i);
2756 }
2757 }
2758
2dda3850 2759 if (Dygraph.isDateLike(data[0][0])) {
285a6bda
DV
2760 // Some intelligent defaults for a date x-axis.
2761 this.attrs_.xValueFormatter = Dygraph.dateString_;
bf640e56 2762 this.attrs_.xAxisLabelFormatter = Dygraph.dateAxisFormatter;
285a6bda
DV
2763 this.attrs_.xTicker = Dygraph.dateTicker;
2764
2765 // Assume they're all dates.
e3ab7b40 2766 var parsedData = Dygraph.clone(data);
285a6bda
DV
2767 for (var i = 0; i < data.length; i++) {
2768 if (parsedData[i].length == 0) {
a323ff4a 2769 this.error("Row " + (1 + i) + " of data is empty");
285a6bda
DV
2770 return null;
2771 }
2772 if (parsedData[i][0] == null
3a909ec5
DV
2773 || typeof(parsedData[i][0].getTime) != 'function'
2774 || isNaN(parsedData[i][0].getTime())) {
be96a1f5 2775 this.error("x value in row " + (1 + i) + " is not a Date");
285a6bda
DV
2776 return null;
2777 }
2778 parsedData[i][0] = parsedData[i][0].getTime();
2779 }
2780 return parsedData;
2781 } else {
2782 // Some intelligent defaults for a numeric x-axis.
6be8e54c 2783 this.attrs_.xValueFormatter = this.attrs_.yValueFormatter;
285a6bda
DV
2784 this.attrs_.xTicker = Dygraph.numericTicks;
2785 return data;
2786 }
2787};
2788
2789/**
79420a1e
DV
2790 * Parses a DataTable object from gviz.
2791 * The data is expected to have a first column that is either a date or a
2792 * number. All subsequent columns must be numbers. If there is a clear mismatch
2793 * between this.xValueParser_ and the type of the first column, it will be
a685723c 2794 * fixed. Fills out rawData_.
79420a1e
DV
2795 * @param {Array.<Object>} data See above.
2796 * @private
2797 */
285a6bda 2798Dygraph.prototype.parseDataTable_ = function(data) {
79420a1e
DV
2799 var cols = data.getNumberOfColumns();
2800 var rows = data.getNumberOfRows();
2801
d955e223 2802 var indepType = data.getColumnType(0);
4440f6c8 2803 if (indepType == 'date' || indepType == 'datetime') {
285a6bda
DV
2804 this.attrs_.xValueFormatter = Dygraph.dateString_;
2805 this.attrs_.xValueParser = Dygraph.dateParser;
2806 this.attrs_.xTicker = Dygraph.dateTicker;
bf640e56 2807 this.attrs_.xAxisLabelFormatter = Dygraph.dateAxisFormatter;
33127159 2808 } else if (indepType == 'number') {
6be8e54c 2809 this.attrs_.xValueFormatter = this.attrs_.yValueFormatter;
285a6bda
DV
2810 this.attrs_.xValueParser = function(x) { return parseFloat(x); };
2811 this.attrs_.xTicker = Dygraph.numericTicks;
bf640e56 2812 this.attrs_.xAxisLabelFormatter = this.attrs_.xValueFormatter;
285a6bda 2813 } else {
987840a2
DV
2814 this.error("only 'date', 'datetime' and 'number' types are supported for " +
2815 "column 1 of DataTable input (Got '" + indepType + "')");
79420a1e
DV
2816 return null;
2817 }
2818
a685723c
DV
2819 // Array of the column indices which contain data (and not annotations).
2820 var colIdx = [];
2821 var annotationCols = {}; // data index -> [annotation cols]
2822 var hasAnnotations = false;
2823 for (var i = 1; i < cols; i++) {
2824 var type = data.getColumnType(i);
2825 if (type == 'number') {
2826 colIdx.push(i);
2827 } else if (type == 'string' && this.attr_('displayAnnotations')) {
2828 // This is OK -- it's an annotation column.
2829 var dataIdx = colIdx[colIdx.length - 1];
2830 if (!annotationCols.hasOwnProperty(dataIdx)) {
2831 annotationCols[dataIdx] = [i];
2832 } else {
2833 annotationCols[dataIdx].push(i);
2834 }
2835 hasAnnotations = true;
2836 } else {
2837 this.error("Only 'number' is supported as a dependent type with Gviz." +
2838 " 'string' is only supported if displayAnnotations is true");
2839 }
2840 }
2841
2842 // Read column labels
2843 // TODO(danvk): add support back for errorBars
2844 var labels = [data.getColumnLabel(0)];
2845 for (var i = 0; i < colIdx.length; i++) {
2846 labels.push(data.getColumnLabel(colIdx[i]));
f9348814 2847 if (this.attr_("errorBars")) i += 1;
a685723c
DV
2848 }
2849 this.attrs_.labels = labels;
2850 cols = labels.length;
2851
79420a1e 2852 var ret = [];
987840a2 2853 var outOfOrder = false;
a685723c 2854 var annotations = [];
79420a1e
DV
2855 for (var i = 0; i < rows; i++) {
2856 var row = [];
debe4434
DV
2857 if (typeof(data.getValue(i, 0)) === 'undefined' ||
2858 data.getValue(i, 0) === null) {
129569a5
FD
2859 this.warn("Ignoring row " + i +
2860 " of DataTable because of undefined or null first column.");
debe4434
DV
2861 continue;
2862 }
2863
c21d2c2d 2864 if (indepType == 'date' || indepType == 'datetime') {
d955e223
DV
2865 row.push(data.getValue(i, 0).getTime());
2866 } else {
2867 row.push(data.getValue(i, 0));
2868 }
3e3f84e4 2869 if (!this.attr_("errorBars")) {
a685723c
DV
2870 for (var j = 0; j < colIdx.length; j++) {
2871 var col = colIdx[j];
2872 row.push(data.getValue(i, col));
2873 if (hasAnnotations &&
2874 annotationCols.hasOwnProperty(col) &&
2875 data.getValue(i, annotationCols[col][0]) != null) {
2876 var ann = {};
2877 ann.series = data.getColumnLabel(col);
2878 ann.xval = row[0];
2879 ann.shortText = String.fromCharCode(65 /* A */ + annotations.length)
2880 ann.text = '';
2881 for (var k = 0; k < annotationCols[col].length; k++) {
2882 if (k) ann.text += "\n";
2883 ann.text += data.getValue(i, annotationCols[col][k]);
2884 }
2885 annotations.push(ann);
2886 }
3e3f84e4
DV
2887 }
2888 } else {
2889 for (var j = 0; j < cols - 1; j++) {
2890 row.push([ data.getValue(i, 1 + 2 * j), data.getValue(i, 2 + 2 * j) ]);
2891 }
79420a1e 2892 }
987840a2
DV
2893 if (ret.length > 0 && row[0] < ret[ret.length - 1][0]) {
2894 outOfOrder = true;
2895 }
1f7f664b
DV
2896
2897 // Strip out infinities, which give dygraphs problems later on.
2898 for (var j = 0; j < row.length; j++) {
2899 if (!isFinite(row[j])) row[j] = null;
2900 }
243d96e8 2901 ret.push(row);
79420a1e 2902 }
987840a2
DV
2903
2904 if (outOfOrder) {
2905 this.warn("DataTable is out of order; order it correctly to speed loading.");
2906 ret.sort(function(a,b) { return a[0] - b[0] });
2907 }
a685723c
DV
2908 this.rawData_ = ret;
2909
2910 if (annotations.length > 0) {
2911 this.setAnnotations(annotations, true);
2912 }
79420a1e
DV
2913}
2914
24e5350c 2915// These functions are all based on MochiKit.
fc80a396
DV
2916Dygraph.update = function (self, o) {
2917 if (typeof(o) != 'undefined' && o !== null) {
2918 for (var k in o) {
85b99f0b
DV
2919 if (o.hasOwnProperty(k)) {
2920 self[k] = o[k];
2921 }
fc80a396
DV
2922 }
2923 }
2924 return self;
2925};
2926
2dda3850
DV
2927Dygraph.isArrayLike = function (o) {
2928 var typ = typeof(o);
2929 if (
c21d2c2d 2930 (typ != 'object' && !(typ == 'function' &&
2dda3850
DV
2931 typeof(o.item) == 'function')) ||
2932 o === null ||
2933 typeof(o.length) != 'number' ||
2934 o.nodeType === 3
2935 ) {
2936 return false;
2937 }
2938 return true;
2939};
2940
2941Dygraph.isDateLike = function (o) {
2942 if (typeof(o) != "object" || o === null ||
2943 typeof(o.getTime) != 'function') {
2944 return false;
2945 }
2946 return true;
2947};
2948
e3ab7b40
DV
2949Dygraph.clone = function(o) {
2950 // TODO(danvk): figure out how MochiKit's version works
2951 var r = [];
2952 for (var i = 0; i < o.length; i++) {
2953 if (Dygraph.isArrayLike(o[i])) {
2954 r.push(Dygraph.clone(o[i]));
2955 } else {
2956 r.push(o[i]);
2957 }
2958 }
2959 return r;
24e5350c
DV
2960};
2961
2dda3850 2962
79420a1e 2963/**
6a1aa64f
DV
2964 * Get the CSV data. If it's in a function, call that function. If it's in a
2965 * file, do an XMLHttpRequest to get it.
2966 * @private
2967 */
285a6bda 2968Dygraph.prototype.start_ = function() {
6a1aa64f 2969 if (typeof this.file_ == 'function') {
285a6bda 2970 // CSV string. Pretend we got it via XHR.
6a1aa64f 2971 this.loadedEvent_(this.file_());
2dda3850 2972 } else if (Dygraph.isArrayLike(this.file_)) {
285a6bda 2973 this.rawData_ = this.parseArray_(this.file_);
26ca7938 2974 this.predraw_();
79420a1e
DV
2975 } else if (typeof this.file_ == 'object' &&
2976 typeof this.file_.getColumnRange == 'function') {
2977 // must be a DataTable from gviz.
a685723c 2978 this.parseDataTable_(this.file_);
26ca7938 2979 this.predraw_();
285a6bda
DV
2980 } else if (typeof this.file_ == 'string') {
2981 // Heuristic: a newline means it's CSV data. Otherwise it's an URL.
2982 if (this.file_.indexOf('\n') >= 0) {
2983 this.loadedEvent_(this.file_);
2984 } else {
2985 var req = new XMLHttpRequest();
2986 var caller = this;
2987 req.onreadystatechange = function () {
2988 if (req.readyState == 4) {
2989 if (req.status == 200) {
2990 caller.loadedEvent_(req.responseText);
2991 }
6a1aa64f 2992 }
285a6bda 2993 };
6a1aa64f 2994
285a6bda
DV
2995 req.open("GET", this.file_, true);
2996 req.send(null);
2997 }
2998 } else {
2999 this.error("Unknown data format: " + (typeof this.file_));
6a1aa64f
DV
3000 }
3001};
3002
3003/**
3004 * Changes various properties of the graph. These can include:
3005 * <ul>
3006 * <li>file: changes the source data for the graph</li>
3007 * <li>errorBars: changes whether the data contains stddev</li>
3008 * </ul>
3009 * @param {Object} attrs The new properties and values
3010 */
285a6bda
DV
3011Dygraph.prototype.updateOptions = function(attrs) {
3012 // TODO(danvk): this is a mess. Rethink this function.
c65f2303 3013 if ('rollPeriod' in attrs) {
6a1aa64f
DV
3014 this.rollPeriod_ = attrs.rollPeriod;
3015 }
c65f2303 3016 if ('dateWindow' in attrs) {
6a1aa64f
DV
3017 this.dateWindow_ = attrs.dateWindow;
3018 }
450fe64b
DV
3019
3020 // TODO(danvk): validate per-series options.
46dde5f9
DV
3021 // Supported:
3022 // strokeWidth
3023 // pointSize
3024 // drawPoints
3025 // highlightCircleSize
450fe64b 3026
fc80a396 3027 Dygraph.update(this.user_attrs_, attrs);
87bb7958 3028 Dygraph.update(this.renderOptions_, attrs);
285a6bda
DV
3029
3030 this.labelsFromCSV_ = (this.attr_("labels") == null);
3031
3032 // TODO(danvk): this doesn't match the constructor logic
3033 this.layout_.updateOptions({ 'errorBars': this.attr_("errorBars") });
5e50289f 3034 if (attrs['file']) {
6a1aa64f
DV
3035 this.file_ = attrs['file'];
3036 this.start_();
3037 } else {
26ca7938 3038 this.predraw_();
6a1aa64f
DV
3039 }
3040};
3041
3042/**
697e70b2
DV
3043 * Resizes the dygraph. If no parameters are specified, resizes to fill the
3044 * containing div (which has presumably changed size since the dygraph was
3045 * instantiated. If the width/height are specified, the div will be resized.
964f30c6
DV
3046 *
3047 * This is far more efficient than destroying and re-instantiating a
3048 * Dygraph, since it doesn't have to reparse the underlying data.
3049 *
697e70b2
DV
3050 * @param {Number} width Width (in pixels)
3051 * @param {Number} height Height (in pixels)
3052 */
3053Dygraph.prototype.resize = function(width, height) {
e8c7ef86
DV
3054 if (this.resize_lock) {
3055 return;
3056 }
3057 this.resize_lock = true;
3058
697e70b2
DV
3059 if ((width === null) != (height === null)) {
3060 this.warn("Dygraph.resize() should be called with zero parameters or " +
3061 "two non-NULL parameters. Pretending it was zero.");
3062 width = height = null;
3063 }
3064
b16e6369 3065 // TODO(danvk): there should be a clear() method.
697e70b2 3066 this.maindiv_.innerHTML = "";
b16e6369
DV
3067 this.attrs_.labelsDiv = null;
3068
697e70b2
DV
3069 if (width) {
3070 this.maindiv_.style.width = width + "px";
3071 this.maindiv_.style.height = height + "px";
3072 this.width_ = width;
3073 this.height_ = height;
3074 } else {
3075 this.width_ = this.maindiv_.offsetWidth;
3076 this.height_ = this.maindiv_.offsetHeight;
3077 }
3078
3079 this.createInterface_();
26ca7938 3080 this.predraw_();
e8c7ef86
DV
3081
3082 this.resize_lock = false;
697e70b2
DV
3083};
3084
3085/**
6faebb69 3086 * Adjusts the number of points in the rolling average. Updates the graph to
6a1aa64f 3087 * reflect the new averaging period.
6faebb69 3088 * @param {Number} length Number of points over which to average the data.
6a1aa64f 3089 */
285a6bda 3090Dygraph.prototype.adjustRoll = function(length) {
6a1aa64f 3091 this.rollPeriod_ = length;
26ca7938 3092 this.predraw_();
6a1aa64f 3093};
540d00f1 3094
f8cfec73 3095/**
1cf11047
DV
3096 * Returns a boolean array of visibility statuses.
3097 */
3098Dygraph.prototype.visibility = function() {
3099 // Do lazy-initialization, so that this happens after we know the number of
3100 // data series.
3101 if (!this.attr_("visibility")) {
f38dec01 3102 this.attrs_["visibility"] = [];
1cf11047
DV
3103 }
3104 while (this.attr_("visibility").length < this.rawData_[0].length - 1) {
f38dec01 3105 this.attr_("visibility").push(true);
1cf11047
DV
3106 }
3107 return this.attr_("visibility");
3108};
3109
3110/**
3111 * Changes the visiblity of a series.
3112 */
3113Dygraph.prototype.setVisibility = function(num, value) {
3114 var x = this.visibility();
a6c109c1 3115 if (num < 0 || num >= x.length) {
1cf11047
DV
3116 this.warn("invalid series number in setVisibility: " + num);
3117 } else {
3118 x[num] = value;
26ca7938 3119 this.predraw_();
1cf11047
DV
3120 }
3121};
3122
3123/**
5c528fa2
DV
3124 * Update the list of annotations and redraw the chart.
3125 */
a685723c 3126Dygraph.prototype.setAnnotations = function(ann, suppressDraw) {
3c51ab74
DV
3127 // Only add the annotation CSS rule once we know it will be used.
3128 Dygraph.addAnnotationRule();
5c528fa2
DV
3129 this.annotations_ = ann;
3130 this.layout_.setAnnotations(this.annotations_);
a685723c 3131 if (!suppressDraw) {
26ca7938 3132 this.predraw_();
a685723c 3133 }
5c528fa2
DV
3134};
3135
3136/**
3137 * Return the list of annotations.
3138 */
3139Dygraph.prototype.annotations = function() {
3140 return this.annotations_;
3141};
3142
46dde5f9
DV
3143/**
3144 * Get the index of a series (column) given its name. The first column is the
3145 * x-axis, so the data series start with index 1.
3146 */
3147Dygraph.prototype.indexFromSetName = function(name) {
3148 var labels = this.attr_("labels");
3149 for (var i = 0; i < labels.length; i++) {
3150 if (labels[i] == name) return i;
3151 }
3152 return null;
3153};
3154
5c528fa2
DV
3155Dygraph.addAnnotationRule = function() {
3156 if (Dygraph.addedAnnotationCSS) return;
3157
5c528fa2
DV
3158 var rule = "border: 1px solid black; " +
3159 "background-color: white; " +
3160 "text-align: center;";
22186871
DV
3161
3162 var styleSheetElement = document.createElement("style");
3163 styleSheetElement.type = "text/css";
3164 document.getElementsByTagName("head")[0].appendChild(styleSheetElement);
3165
3166 // Find the first style sheet that we can access.
3167 // We may not add a rule to a style sheet from another domain for security
3168 // reasons. This sometimes comes up when using gviz, since the Google gviz JS
3169 // adds its own style sheets from google.com.
3170 for (var i = 0; i < document.styleSheets.length; i++) {
3171 if (document.styleSheets[i].disabled) continue;
3172 var mysheet = document.styleSheets[i];
3173 try {
3174 if (mysheet.insertRule) { // Firefox
3175 var idx = mysheet.cssRules ? mysheet.cssRules.length : 0;
3176 mysheet.insertRule(".dygraphDefaultAnnotation { " + rule + " }", idx);
3177 } else if (mysheet.addRule) { // IE
3178 mysheet.addRule(".dygraphDefaultAnnotation", rule);
3179 }
3180 Dygraph.addedAnnotationCSS = true;
3181 return;
3182 } catch(err) {
3183 // Was likely a security exception.
3184 }
5c528fa2
DV
3185 }
3186
22186871 3187 this.warn("Unable to add default annotation CSS rule; display may be off.");
5c528fa2
DV
3188}
3189
3190/**
f8cfec73
DV
3191 * Create a new canvas element. This is more complex than a simple
3192 * document.createElement("canvas") because of IE and excanvas.
3193 */
3194Dygraph.createCanvas = function() {
3195 var canvas = document.createElement("canvas");
3196
3197 isIE = (/MSIE/.test(navigator.userAgent) && !window.opera);
8b8f2d59 3198 if (isIE && (typeof(G_vmlCanvasManager) != 'undefined')) {
f8cfec73
DV
3199 canvas = G_vmlCanvasManager.initElement(canvas);
3200 }
3201
3202 return canvas;
3203};
3204
540d00f1
DV
3205
3206/**
285a6bda 3207 * A wrapper around Dygraph that implements the gviz API.
540d00f1
DV
3208 * @param {Object} container The DOM object the visualization should live in.
3209 */
285a6bda 3210Dygraph.GVizChart = function(container) {
540d00f1
DV
3211 this.container = container;
3212}
3213
285a6bda 3214Dygraph.GVizChart.prototype.draw = function(data, options) {
c91f4ae8
DV
3215 // Clear out any existing dygraph.
3216 // TODO(danvk): would it make more sense to simply redraw using the current
3217 // date_graph object?
540d00f1 3218 this.container.innerHTML = '';
c91f4ae8
DV
3219 if (typeof(this.date_graph) != 'undefined') {
3220 this.date_graph.destroy();
3221 }
3222
285a6bda 3223 this.date_graph = new Dygraph(this.container, data, options);
540d00f1 3224}
285a6bda 3225
239c712d
NAG
3226/**
3227 * Google charts compatible setSelection
50360fd0 3228 * Only row selection is supported, all points in the row will be highlighted
239c712d
NAG
3229 * @param {Array} array of the selected cells
3230 * @public
3231 */
3232Dygraph.GVizChart.prototype.setSelection = function(selection_array) {
3233 var row = false;
3234 if (selection_array.length) {
3235 row = selection_array[0].row;
3236 }
3237 this.date_graph.setSelection(row);
3238}
3239
103b7292
NAG
3240/**
3241 * Google charts compatible getSelection implementation
3242 * @return {Array} array of the selected cells
3243 * @public
3244 */
3245Dygraph.GVizChart.prototype.getSelection = function() {
3246 var selection = [];
50360fd0 3247
103b7292 3248 var row = this.date_graph.getSelection();
50360fd0 3249
103b7292 3250 if (row < 0) return selection;
50360fd0 3251
103b7292
NAG
3252 col = 1;
3253 for (var i in this.date_graph.layout_.datasets) {
3254 selection.push({row: row, column: col});
3255 col++;
3256 }
3257
3258 return selection;
3259}
3260
285a6bda
DV
3261// Older pages may still use this name.
3262DateGraph = Dygraph;