fix issue 193 -- need to consider area.y when computing data coords
[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
285a6bda 27 Date,SeriesA,SeriesB,...
6a1aa64f
DV
28 YYYYMMDD,A1,sigmaA1,B1,sigmaB1,...
29 YYYYMMDD,A2,sigmaA2,B2,sigmaB2,...
30
31 If the 'fractions' option is set, the input should be of the form:
32
285a6bda 33 Date,SeriesA,SeriesB,...
6a1aa64f
DV
34 YYYYMMDD,A1/B1,A2/B2,...
35 YYYYMMDD,A1/B1,A2/B2,...
36
37 And error bars will be calculated automatically using a binomial distribution.
38
727439b4 39 For further documentation and examples, see http://dygraphs.com/
6a1aa64f
DV
40
41 */
42
43/**
629a09ae
DV
44 * Creates an interactive, zoomable chart.
45 *
46 * @constructor
47 * @param {div | String} div A div or the id of a div into which to construct
48 * the chart.
49 * @param {String | Function} file A file containing CSV data or a function
50 * that returns this data. The most basic expected format for each line is
51 * "YYYY/MM/DD,val1,val2,...". For more information, see
52 * http://dygraphs.com/data.html.
6a1aa64f 53 * @param {Object} attrs Various other attributes, e.g. errorBars determines
629a09ae
DV
54 * whether the input data contains error ranges. For a complete list of
55 * options, see http://dygraphs.com/options.html.
6a1aa64f 56 */
285a6bda
DV
57Dygraph = function(div, data, opts) {
58 if (arguments.length > 0) {
59 if (arguments.length == 4) {
60 // Old versions of dygraphs took in the series labels as a constructor
61 // parameter. This doesn't make sense anymore, but it's easy to continue
62 // to support this usage.
63 this.warn("Using deprecated four-argument dygraph constructor");
64 this.__old_init__(div, data, arguments[2], arguments[3]);
65 } else {
66 this.__init__(div, data, opts);
67 }
68 }
6a1aa64f
DV
69};
70
285a6bda
DV
71Dygraph.NAME = "Dygraph";
72Dygraph.VERSION = "1.2";
73Dygraph.__repr__ = function() {
6a1aa64f
DV
74 return "[" + this.NAME + " " + this.VERSION + "]";
75};
629a09ae
DV
76
77/**
78 * Returns information about the Dygraph class.
79 */
285a6bda 80Dygraph.toString = function() {
6a1aa64f
DV
81 return this.__repr__();
82};
83
84// Various default values
285a6bda
DV
85Dygraph.DEFAULT_ROLL_PERIOD = 1;
86Dygraph.DEFAULT_WIDTH = 480;
87Dygraph.DEFAULT_HEIGHT = 320;
6a1aa64f 88
d59b6f34 89Dygraph.LOG_SCALE = 10;
0037b2a4 90Dygraph.LN_TEN = Math.log(Dygraph.LOG_SCALE);
3234efcf 91/** @private */
d59b6f34 92Dygraph.log10 = function(x) {
0037b2a4 93 return Math.log(x) / Dygraph.LN_TEN;
d59b6f34 94}
062ef401 95
8e4a6af3 96// Default attribute values.
285a6bda 97Dygraph.DEFAULT_ATTRS = {
a9fc39ab 98 highlightCircleSize: 3,
8e4a6af3 99 pixelsPerXLabel: 60,
c6336f04 100 pixelsPerYLabel: 30,
285a6bda 101
8e4a6af3
DV
102 labelsDivWidth: 250,
103 labelsDivStyles: {
104 // TODO(danvk): move defaults from createStatusMessage_ here.
285a6bda
DV
105 },
106 labelsSeparateLines: false,
bcd3ebf0 107 labelsShowZeroValues: true,
285a6bda 108 labelsKMB: false,
afefbcdb 109 labelsKMG2: false,
d160cc3b 110 showLabelsOnHighlight: true,
12e4c741 111
2e1fcf1a
DV
112 yValueFormatter: function(a,b) { return Dygraph.numberFormatter(a,b); },
113 digitsAfterDecimal: 2,
114 maxNumberWidth: 6,
19589a3e 115 sigFigs: null,
285a6bda
DV
116
117 strokeWidth: 1.0,
8e4a6af3 118
8846615a
DV
119 axisTickSize: 3,
120 axisLabelFontSize: 14,
121 xAxisLabelWidth: 50,
122 yAxisLabelWidth: 50,
bf640e56 123 xAxisLabelFormatter: Dygraph.dateAxisFormatter,
8846615a 124 rightGap: 5,
285a6bda
DV
125
126 showRoller: false,
127 xValueFormatter: Dygraph.dateString_,
128 xValueParser: Dygraph.dateParser,
129 xTicker: Dygraph.dateTicker,
130
3d67f03b
DV
131 delimiter: ',',
132
285a6bda
DV
133 sigma: 2.0,
134 errorBars: false,
135 fractions: false,
136 wilsonInterval: true, // only relevant if fractions is true
5954ef32 137 customBars: false,
43af96e7
NK
138 fillGraph: false,
139 fillAlpha: 0.15,
f032c51d 140 connectSeparatedPoints: false,
43af96e7
NK
141
142 stackedGraph: false,
afdc483f
NN
143 hideOverlayOnMouseOut: true,
144
2fccd3dc
DV
145 // TODO(danvk): support 'onmouseover' and 'never', and remove synonyms.
146 legend: 'onmouseover', // the only relevant value at the moment is 'always'.
147
00c281d4 148 stepPlot: false,
062ef401
JB
149 avoidMinZero: false,
150
ad1798c2 151 // Sizes of the various chart labels.
b4202b3d 152 titleHeight: 28,
86cce9e8
DV
153 xLabelHeight: 18,
154 yLabelWidth: 18,
ad1798c2 155
423f5ed3
DV
156 drawXAxis: true,
157 drawYAxis: true,
158 axisLineColor: "black",
990d6a35
DV
159 axisLineWidth: 0.3,
160 gridLineWidth: 0.3,
161 axisLabelColor: "black",
162 axisLabelFont: "Arial", // TODO(danvk): is this implemented?
163 axisLabelWidth: 50,
164 drawYGrid: true,
165 drawXGrid: true,
166 gridLineColor: "rgb(128,128,128)",
423f5ed3 167
062ef401 168 interactionModel: null // will be set to Dygraph.defaultInteractionModel.
285a6bda
DV
169};
170
171// Various logging levels.
172Dygraph.DEBUG = 1;
173Dygraph.INFO = 2;
174Dygraph.WARNING = 3;
175Dygraph.ERROR = 3;
176
39b0e098
RK
177// Directions for panning and zooming. Use bit operations when combined
178// values are possible.
179Dygraph.HORIZONTAL = 1;
180Dygraph.VERTICAL = 2;
181
5c528fa2
DV
182// Used for initializing annotation CSS rules only once.
183Dygraph.addedAnnotationCSS = false;
184
2cf95fff 185/**
629a09ae 186 * @private
2cf95fff
RK
187 * Return the 2d context for a dygraph canvas.
188 *
189 * This method is only exposed for the sake of replacing the function in
190 * automated tests, e.g.
191 *
192 * var oldFunc = Dygraph.getContext();
193 * Dygraph.getContext = function(canvas) {
194 * var realContext = oldFunc(canvas);
195 * return new Proxy(realContext);
196 * };
197 */
198Dygraph.getContext = function(canvas) {
199 return canvas.getContext("2d");
200};
201
285a6bda
DV
202Dygraph.prototype.__old_init__ = function(div, file, labels, attrs) {
203 // Labels is no longer a constructor parameter, since it's typically set
204 // directly from the data source. It also conains a name for the x-axis,
205 // which the previous constructor form did not.
206 if (labels != null) {
207 var new_labels = ["Date"];
208 for (var i = 0; i < labels.length; i++) new_labels.push(labels[i]);
fc80a396 209 Dygraph.update(attrs, { 'labels': new_labels });
285a6bda
DV
210 }
211 this.__init__(div, file, attrs);
8e4a6af3
DV
212};
213
6a1aa64f 214/**
285a6bda 215 * Initializes the Dygraph. This creates a new DIV and constructs the PlotKit
7aedf6fe 216 * and context &lt;canvas&gt; inside of it. See the constructor for details.
6a1aa64f 217 * on the parameters.
12e4c741 218 * @param {Element} div the Element to render the graph into.
6a1aa64f 219 * @param {String | Function} file Source data
6a1aa64f
DV
220 * @param {Object} attrs Miscellaneous other options
221 * @private
222 */
285a6bda 223Dygraph.prototype.__init__ = function(div, file, attrs) {
a2c8fff4
DV
224 // Hack for IE: if we're using excanvas and the document hasn't finished
225 // loading yet (and hence may not have initialized whatever it needs to
226 // initialize), then keep calling this routine periodically until it has.
227 if (/MSIE/.test(navigator.userAgent) && !window.opera &&
228 typeof(G_vmlCanvasManager) != 'undefined' &&
229 document.readyState != 'complete') {
230 var self = this;
231 setTimeout(function() { self.__init__(div, file, attrs) }, 100);
232 }
233
285a6bda
DV
234 // Support two-argument constructor
235 if (attrs == null) { attrs = {}; }
236
6a1aa64f 237 // Copy the important bits into the object
32988383 238 // TODO(danvk): most of these should just stay in the attrs_ dictionary.
6a1aa64f 239 this.maindiv_ = div;
6a1aa64f 240 this.file_ = file;
285a6bda 241 this.rollPeriod_ = attrs.rollPeriod || Dygraph.DEFAULT_ROLL_PERIOD;
6a1aa64f 242 this.previousVerticalX_ = -1;
6a1aa64f 243 this.fractions_ = attrs.fractions || false;
6a1aa64f 244 this.dateWindow_ = attrs.dateWindow || null;
8b83c6cc 245
6a1aa64f 246 this.wilsonInterval_ = attrs.wilsonInterval || true;
fe0b7c03 247 this.is_initial_draw_ = true;
5c528fa2 248 this.annotations_ = [];
7aedf6fe 249
45f2c689 250 // Zoomed indicators - These indicate when the graph has been zoomed and on what axis.
57baab03
NN
251 this.zoomed_x_ = false;
252 this.zoomed_y_ = false;
45f2c689 253
f7d6278e
DV
254 // Clear the div. This ensure that, if multiple dygraphs are passed the same
255 // div, then only one will be drawn.
256 div.innerHTML = "";
257
c21d2c2d 258 // If the div isn't already sized then inherit from our attrs or
259 // give it a default size.
285a6bda 260 if (div.style.width == '') {
ddd1b11f 261 div.style.width = (attrs.width || Dygraph.DEFAULT_WIDTH) + "px";
285a6bda
DV
262 }
263 if (div.style.height == '') {
ddd1b11f 264 div.style.height = (attrs.height || Dygraph.DEFAULT_HEIGHT) + "px";
32988383 265 }
285a6bda
DV
266 this.width_ = parseInt(div.style.width, 10);
267 this.height_ = parseInt(div.style.height, 10);
c21d2c2d 268 // The div might have been specified as percent of the current window size,
269 // convert that to an appropriate number of pixels.
270 if (div.style.width.indexOf("%") == div.style.width.length - 1) {
c6f45033 271 this.width_ = div.offsetWidth;
c21d2c2d 272 }
273 if (div.style.height.indexOf("%") == div.style.height.length - 1) {
c6f45033 274 this.height_ = div.offsetHeight;
c21d2c2d 275 }
32988383 276
10a6456d
DV
277 if (this.width_ == 0) {
278 this.error("dygraph has zero width. Please specify a width in pixels.");
279 }
280 if (this.height_ == 0) {
281 this.error("dygraph has zero height. Please specify a height in pixels.");
282 }
283
344ba8c0 284 // TODO(danvk): set fillGraph to be part of attrs_ here, not user_attrs_.
43af96e7
NK
285 if (attrs['stackedGraph']) {
286 attrs['fillGraph'] = true;
287 // TODO(nikhilk): Add any other stackedGraph checks here.
288 }
289
285a6bda
DV
290 // Dygraphs has many options, some of which interact with one another.
291 // To keep track of everything, we maintain two sets of options:
292 //
c21d2c2d 293 // this.user_attrs_ only options explicitly set by the user.
285a6bda
DV
294 // this.attrs_ defaults, options derived from user_attrs_, data.
295 //
296 // Options are then accessed this.attr_('attr'), which first looks at
297 // user_attrs_ and then computed attrs_. This way Dygraphs can set intelligent
298 // defaults without overriding behavior that the user specifically asks for.
299 this.user_attrs_ = {};
fc80a396 300 Dygraph.update(this.user_attrs_, attrs);
6a1aa64f 301
285a6bda 302 this.attrs_ = {};
fc80a396 303 Dygraph.update(this.attrs_, Dygraph.DEFAULT_ATTRS);
6a1aa64f 304
16269f6e 305 this.boundaryIds_ = [];
6a1aa64f 306
6a1aa64f
DV
307 // Create the containing DIV and other interactive elements
308 this.createInterface_();
309
738fc797 310 this.start_();
6a1aa64f
DV
311};
312
dcb25130
NN
313/**
314 * Returns the zoomed status of the chart for one or both axes.
315 *
316 * Axis is an optional parameter. Can be set to 'x' or 'y'.
317 *
318 * The zoomed status for an axis is set whenever a user zooms using the mouse
e5152598 319 * or when the dateWindow or valueRange are updated (unless the isZoomedIgnoreProgrammaticZoom
dcb25130
NN
320 * option is also specified).
321 */
57baab03
NN
322Dygraph.prototype.isZoomed = function(axis) {
323 if (axis == null) return this.zoomed_x_ || this.zoomed_y_;
324 if (axis == 'x') return this.zoomed_x_;
325 if (axis == 'y') return this.zoomed_y_;
326 throw "axis parameter to Dygraph.isZoomed must be missing, 'x' or 'y'.";
327};
328
629a09ae
DV
329/**
330 * Returns information about the Dygraph object, including its containing ID.
331 */
22bd1dfb
RK
332Dygraph.prototype.toString = function() {
333 var maindiv = this.maindiv_;
334 var id = (maindiv && maindiv.id) ? maindiv.id : maindiv
335 return "[Dygraph " + id + "]";
336}
337
629a09ae
DV
338/**
339 * @private
340 * Returns the value of an option. This may be set by the user (either in the
341 * constructor or by calling updateOptions) or by dygraphs, and may be set to a
342 * per-series value.
343 * @param { String } name The name of the option, e.g. 'rollPeriod'.
344 * @param { String } [seriesName] The name of the series to which the option
345 * will be applied. If no per-series value of this option is available, then
346 * the global value is returned. This is optional.
347 * @return { ... } The value of the option.
348 */
227b93cc 349Dygraph.prototype.attr_ = function(name, seriesName) {
028ddf8a
DV
350// <REMOVE_FOR_COMBINED>
351 if (typeof(Dygraph.OPTIONS_REFERENCE) === 'undefined') {
352 this.error('Must include options reference JS for testing');
353 } else if (!Dygraph.OPTIONS_REFERENCE.hasOwnProperty(name)) {
354 this.error('Dygraphs is using property ' + name + ', which has no entry ' +
355 'in the Dygraphs.OPTIONS_REFERENCE listing.');
356 // Only log this error once.
357 Dygraph.OPTIONS_REFERENCE[name] = true;
358 }
359// </REMOVE_FOR_COMBINED>
227b93cc
DV
360 if (seriesName &&
361 typeof(this.user_attrs_[seriesName]) != 'undefined' &&
362 this.user_attrs_[seriesName] != null &&
363 typeof(this.user_attrs_[seriesName][name]) != 'undefined') {
364 return this.user_attrs_[seriesName][name];
450fe64b 365 } else if (typeof(this.user_attrs_[name]) != 'undefined') {
285a6bda
DV
366 return this.user_attrs_[name];
367 } else if (typeof(this.attrs_[name]) != 'undefined') {
368 return this.attrs_[name];
369 } else {
370 return null;
371 }
372};
373
374// TODO(danvk): any way I can get the line numbers to be this.warn call?
629a09ae
DV
375/**
376 * @private
377 * Log an error on the JS console at the given severity.
378 * @param { Integer } severity One of Dygraph.{DEBUG,INFO,WARNING,ERROR}
379 * @param { String } The message to log.
380 */
285a6bda
DV
381Dygraph.prototype.log = function(severity, message) {
382 if (typeof(console) != 'undefined') {
383 switch (severity) {
384 case Dygraph.DEBUG:
385 console.debug('dygraphs: ' + message);
386 break;
387 case Dygraph.INFO:
388 console.info('dygraphs: ' + message);
389 break;
390 case Dygraph.WARNING:
391 console.warn('dygraphs: ' + message);
392 break;
393 case Dygraph.ERROR:
394 console.error('dygraphs: ' + message);
395 break;
396 }
397 }
629a09ae
DV
398};
399
3234efcf 400/** @private */
285a6bda
DV
401Dygraph.prototype.info = function(message) {
402 this.log(Dygraph.INFO, message);
629a09ae
DV
403};
404
3234efcf 405/** @private */
285a6bda
DV
406Dygraph.prototype.warn = function(message) {
407 this.log(Dygraph.WARNING, message);
629a09ae
DV
408};
409
3234efcf 410/** @private */
285a6bda
DV
411Dygraph.prototype.error = function(message) {
412 this.log(Dygraph.ERROR, message);
629a09ae 413};
285a6bda 414
6a1aa64f
DV
415/**
416 * Returns the current rolling period, as set by the user or an option.
6faebb69 417 * @return {Number} The number of points in the rolling window
6a1aa64f 418 */
285a6bda 419Dygraph.prototype.rollPeriod = function() {
6a1aa64f 420 return this.rollPeriod_;
76171648
DV
421};
422
599fb4ad
DV
423/**
424 * Returns the currently-visible x-range. This can be affected by zooming,
425 * panning or a call to updateOptions.
426 * Returns a two-element array: [left, right].
427 * If the Dygraph has dates on the x-axis, these will be millis since epoch.
428 */
429Dygraph.prototype.xAxisRange = function() {
4cac8c7a
RK
430 return this.dateWindow_ ? this.dateWindow_ : this.xAxisExtremes();
431};
599fb4ad 432
4cac8c7a
RK
433/**
434 * Returns the lower- and upper-bound x-axis values of the
435 * data set.
436 */
437Dygraph.prototype.xAxisExtremes = function() {
599fb4ad
DV
438 var left = this.rawData_[0][0];
439 var right = this.rawData_[this.rawData_.length - 1][0];
440 return [left, right];
441};
442
3230c662 443/**
d58ae307
DV
444 * Returns the currently-visible y-range for an axis. This can be affected by
445 * zooming, panning or a call to updateOptions. Axis indices are zero-based. If
446 * called with no arguments, returns the range of the first axis.
3230c662
DV
447 * Returns a two-element array: [bottom, top].
448 */
d58ae307 449Dygraph.prototype.yAxisRange = function(idx) {
d63e6799 450 if (typeof(idx) == "undefined") idx = 0;
d58ae307
DV
451 if (idx < 0 || idx >= this.axes_.length) return null;
452 return [ this.axes_[idx].computedValueRange[0],
453 this.axes_[idx].computedValueRange[1] ];
454};
455
456/**
457 * Returns the currently-visible y-ranges for each axis. This can be affected by
458 * zooming, panning, calls to updateOptions, etc.
459 * Returns an array of [bottom, top] pairs, one for each y-axis.
460 */
461Dygraph.prototype.yAxisRanges = function() {
462 var ret = [];
463 for (var i = 0; i < this.axes_.length; i++) {
464 ret.push(this.yAxisRange(i));
465 }
466 return ret;
3230c662
DV
467};
468
d58ae307 469// TODO(danvk): use these functions throughout dygraphs.
3230c662
DV
470/**
471 * Convert from data coordinates to canvas/div X/Y coordinates.
d58ae307
DV
472 * If specified, do this conversion for the coordinate system of a particular
473 * axis. Uses the first axis by default.
3230c662 474 * Returns a two-element array: [X, Y]
ff022deb 475 *
0747928a 476 * Note: use toDomXCoord instead of toDomCoords(x, null) and use toDomYCoord
ff022deb 477 * instead of toDomCoords(null, y, axis).
3230c662 478 */
d58ae307 479Dygraph.prototype.toDomCoords = function(x, y, axis) {
ff022deb
RK
480 return [ this.toDomXCoord(x), this.toDomYCoord(y, axis) ];
481};
482
483/**
484 * Convert from data x coordinates to canvas/div X coordinate.
485 * If specified, do this conversion for the coordinate system of a particular
0037b2a4
RK
486 * axis.
487 * Returns a single value or null if x is null.
ff022deb
RK
488 */
489Dygraph.prototype.toDomXCoord = function(x) {
490 if (x == null) {
491 return null;
492 };
493
3230c662 494 var area = this.plotter_.area;
ff022deb
RK
495 var xRange = this.xAxisRange();
496 return area.x + (x - xRange[0]) / (xRange[1] - xRange[0]) * area.w;
497}
3230c662 498
ff022deb
RK
499/**
500 * Convert from data x coordinates to canvas/div Y coordinate and optional
501 * axis. Uses the first axis by default.
502 *
503 * returns a single value or null if y is null.
504 */
505Dygraph.prototype.toDomYCoord = function(y, axis) {
0747928a 506 var pct = this.toPercentYCoord(y, axis);
3230c662 507
ff022deb
RK
508 if (pct == null) {
509 return null;
510 }
e4416fb9 511 var area = this.plotter_.area;
ff022deb
RK
512 return area.y + pct * area.h;
513}
3230c662
DV
514
515/**
516 * Convert from canvas/div coords to data coordinates.
d58ae307
DV
517 * If specified, do this conversion for the coordinate system of a particular
518 * axis. Uses the first axis by default.
ff022deb
RK
519 * Returns a two-element array: [X, Y].
520 *
0747928a 521 * Note: use toDataXCoord instead of toDataCoords(x, null) and use toDataYCoord
ff022deb 522 * instead of toDataCoords(null, y, axis).
3230c662 523 */
d58ae307 524Dygraph.prototype.toDataCoords = function(x, y, axis) {
ff022deb
RK
525 return [ this.toDataXCoord(x), this.toDataYCoord(y, axis) ];
526};
527
528/**
529 * Convert from canvas/div x coordinate to data coordinate.
530 *
531 * If x is null, this returns null.
532 */
533Dygraph.prototype.toDataXCoord = function(x) {
534 if (x == null) {
535 return null;
3230c662
DV
536 }
537
ff022deb
RK
538 var area = this.plotter_.area;
539 var xRange = this.xAxisRange();
540 return xRange[0] + (x - area.x) / area.w * (xRange[1] - xRange[0]);
541};
542
543/**
544 * Convert from canvas/div y coord to value.
545 *
546 * If y is null, this returns null.
547 * if axis is null, this uses the first axis.
548 */
549Dygraph.prototype.toDataYCoord = function(y, axis) {
550 if (y == null) {
551 return null;
3230c662
DV
552 }
553
ff022deb
RK
554 var area = this.plotter_.area;
555 var yRange = this.yAxisRange(axis);
556
b70247dc
RK
557 if (typeof(axis) == "undefined") axis = 0;
558 if (!this.axes_[axis].logscale) {
d9816e62 559 return yRange[0] + (area.y + area.h - y) / area.h * (yRange[1] - yRange[0]);
ff022deb
RK
560 } else {
561 // Computing the inverse of toDomCoord.
562 var pct = (y - area.y) / area.h
563
564 // Computing the inverse of toPercentYCoord. The function was arrived at with
565 // the following steps:
566 //
567 // Original calcuation:
d59b6f34 568 // pct = (logr1 - Dygraph.log10(y)) / (logr1 - Dygraph.log10(yRange[0]));
ff022deb
RK
569 //
570 // Move denominator to both sides:
d59b6f34 571 // pct * (logr1 - Dygraph.log10(yRange[0])) = logr1 - Dygraph.log10(y);
ff022deb
RK
572 //
573 // subtract logr1, and take the negative value.
d59b6f34 574 // logr1 - (pct * (logr1 - Dygraph.log10(yRange[0]))) = Dygraph.log10(y);
ff022deb
RK
575 //
576 // Swap both sides of the equation, and we can compute the log of the
577 // return value. Which means we just need to use that as the exponent in
578 // e^exponent.
d59b6f34 579 // Dygraph.log10(y) = logr1 - (pct * (logr1 - Dygraph.log10(yRange[0])));
ff022deb 580
d59b6f34
RK
581 var logr1 = Dygraph.log10(yRange[1]);
582 var exponent = logr1 - (pct * (logr1 - Dygraph.log10(yRange[0])));
583 var value = Math.pow(Dygraph.LOG_SCALE, exponent);
ff022deb
RK
584 return value;
585 }
3230c662
DV
586};
587
e99fde05 588/**
ff022deb 589 * Converts a y for an axis to a percentage from the top to the
4cac8c7a 590 * bottom of the drawing area.
ff022deb
RK
591 *
592 * If the coordinate represents a value visible on the canvas, then
593 * the value will be between 0 and 1, where 0 is the top of the canvas.
594 * However, this method will return values outside the range, as
595 * values can fall outside the canvas.
596 *
597 * If y is null, this returns null.
598 * if axis is null, this uses the first axis.
629a09ae
DV
599 *
600 * @param { Number } y The data y-coordinate.
601 * @param { Number } [axis] The axis number on which the data coordinate lives.
602 * @return { Number } A fraction in [0, 1] where 0 = the top edge.
ff022deb
RK
603 */
604Dygraph.prototype.toPercentYCoord = function(y, axis) {
605 if (y == null) {
606 return null;
607 }
7d0e7a0d 608 if (typeof(axis) == "undefined") axis = 0;
ff022deb
RK
609
610 var area = this.plotter_.area;
611 var yRange = this.yAxisRange(axis);
612
613 var pct;
7d0e7a0d 614 if (!this.axes_[axis].logscale) {
4cac8c7a
RK
615 // yRange[1] - y is unit distance from the bottom.
616 // yRange[1] - yRange[0] is the scale of the range.
ff022deb
RK
617 // (yRange[1] - y) / (yRange[1] - yRange[0]) is the % from the bottom.
618 pct = (yRange[1] - y) / (yRange[1] - yRange[0]);
619 } else {
d59b6f34
RK
620 var logr1 = Dygraph.log10(yRange[1]);
621 pct = (logr1 - Dygraph.log10(y)) / (logr1 - Dygraph.log10(yRange[0]));
ff022deb
RK
622 }
623 return pct;
624}
625
626/**
4cac8c7a
RK
627 * Converts an x value to a percentage from the left to the right of
628 * the drawing area.
629 *
630 * If the coordinate represents a value visible on the canvas, then
631 * the value will be between 0 and 1, where 0 is the left of the canvas.
632 * However, this method will return values outside the range, as
633 * values can fall outside the canvas.
634 *
635 * If x is null, this returns null.
629a09ae
DV
636 * @param { Number } x The data x-coordinate.
637 * @return { Number } A fraction in [0, 1] where 0 = the left edge.
4cac8c7a
RK
638 */
639Dygraph.prototype.toPercentXCoord = function(x) {
640 if (x == null) {
641 return null;
642 }
643
4cac8c7a 644 var xRange = this.xAxisRange();
965a030e 645 return (x - xRange[0]) / (xRange[1] - xRange[0]);
629a09ae 646};
4cac8c7a
RK
647
648/**
e99fde05 649 * Returns the number of columns (including the independent variable).
629a09ae 650 * @return { Integer } The number of columns.
e99fde05
DV
651 */
652Dygraph.prototype.numColumns = function() {
653 return this.rawData_[0].length;
654};
655
656/**
657 * Returns the number of rows (excluding any header/label row).
629a09ae 658 * @return { Integer } The number of rows, less any header.
e99fde05
DV
659 */
660Dygraph.prototype.numRows = function() {
661 return this.rawData_.length;
662};
663
664/**
665 * Returns the value in the given row and column. If the row and column exceed
666 * the bounds on the data, returns null. Also returns null if the value is
667 * missing.
629a09ae
DV
668 * @param { Number} row The row number of the data (0-based). Row 0 is the
669 * first row of data, not a header row.
670 * @param { Number} col The column number of the data (0-based)
671 * @return { Number } The value in the specified cell or null if the row/col
672 * were out of range.
e99fde05
DV
673 */
674Dygraph.prototype.getValue = function(row, col) {
675 if (row < 0 || row > this.rawData_.length) return null;
676 if (col < 0 || col > this.rawData_[row].length) return null;
677
678 return this.rawData_[row][col];
679};
680
629a09ae
DV
681/**
682 * @private
683 * Add an event handler. This smooths a difference between IE and the rest of
684 * the world.
685 * @param { DOM element } el The element to add the event to.
686 * @param { String } evt The name of the event, e.g. 'click' or 'mousemove'.
687 * @param { Function } fn The function to call on the event. The function takes
688 * one parameter: the event object.
689 */
76171648
DV
690Dygraph.addEvent = function(el, evt, fn) {
691 var normed_fn = function(e) {
692 if (!e) var e = window.event;
693 fn(e);
694 };
695 if (window.addEventListener) { // Mozilla, Netscape, Firefox
696 el.addEventListener(evt, normed_fn, false);
697 } else { // IE
698 el.attachEvent('on' + evt, normed_fn);
699 }
700};
6a1aa64f 701
062ef401 702
629a09ae
DV
703/**
704 * @private
705 * Cancels further processing of an event. This is useful to prevent default
706 * browser actions, e.g. highlighting text on a double-click.
707 * Based on the article at
708 * http://www.switchonthecode.com/tutorials/javascript-tutorial-the-scroll-wheel
709 * @param { Event } e The event whose normal behavior should be canceled.
710 */
062ef401
JB
711Dygraph.cancelEvent = function(e) {
712 e = e ? e : window.event;
713 if (e.stopPropagation) {
714 e.stopPropagation();
715 }
716 if (e.preventDefault) {
717 e.preventDefault();
718 }
719 e.cancelBubble = true;
720 e.cancel = true;
721 e.returnValue = false;
722 return false;
629a09ae 723};
062ef401
JB
724
725
6a1aa64f 726/**
285a6bda 727 * Generates interface elements for the Dygraph: a containing div, a div to
6a1aa64f 728 * display the current point, and a textbox to adjust the rolling average
697e70b2 729 * period. Also creates the Renderer/Layout elements.
6a1aa64f
DV
730 * @private
731 */
285a6bda 732Dygraph.prototype.createInterface_ = function() {
6a1aa64f
DV
733 // Create the all-enclosing graph div
734 var enclosing = this.maindiv_;
735
b0c3b730
DV
736 this.graphDiv = document.createElement("div");
737 this.graphDiv.style.width = this.width_ + "px";
738 this.graphDiv.style.height = this.height_ + "px";
739 enclosing.appendChild(this.graphDiv);
740
741 // Create the canvas for interactive parts of the chart.
f8cfec73 742 this.canvas_ = Dygraph.createCanvas();
b0c3b730
DV
743 this.canvas_.style.position = "absolute";
744 this.canvas_.width = this.width_;
745 this.canvas_.height = this.height_;
f8cfec73
DV
746 this.canvas_.style.width = this.width_ + "px"; // for IE
747 this.canvas_.style.height = this.height_ + "px"; // for IE
b0c3b730 748
2cf95fff
RK
749 this.canvas_ctx_ = Dygraph.getContext(this.canvas_);
750
b0c3b730 751 // ... and for static parts of the chart.
6a1aa64f 752 this.hidden_ = this.createPlotKitCanvas_(this.canvas_);
2cf95fff 753 this.hidden_ctx_ = Dygraph.getContext(this.hidden_);
76171648 754
eb7bf005
EC
755 // The interactive parts of the graph are drawn on top of the chart.
756 this.graphDiv.appendChild(this.hidden_);
757 this.graphDiv.appendChild(this.canvas_);
758 this.mouseEventElement_ = this.canvas_;
759
76171648 760 var dygraph = this;
eb7bf005 761 Dygraph.addEvent(this.mouseEventElement_, 'mousemove', function(e) {
76171648
DV
762 dygraph.mouseMove_(e);
763 });
eb7bf005 764 Dygraph.addEvent(this.mouseEventElement_, 'mouseout', function(e) {
76171648
DV
765 dygraph.mouseOut_(e);
766 });
697e70b2
DV
767
768 // Create the grapher
b2c9222a 769 this.layout_ = new DygraphLayout(this);
697e70b2 770
697e70b2 771 this.createStatusMessage_();
697e70b2 772 this.createDragInterface_();
4cfcc38c
DV
773};
774
775/**
776 * Detach DOM elements in the dygraph and null out all data references.
777 * Calling this when you're done with a dygraph can dramatically reduce memory
778 * usage. See, e.g., the tests/perf.html example.
779 */
780Dygraph.prototype.destroy = function() {
781 var removeRecursive = function(node) {
782 while (node.hasChildNodes()) {
783 removeRecursive(node.firstChild);
784 node.removeChild(node.firstChild);
785 }
786 };
787 removeRecursive(this.maindiv_);
788
789 var nullOut = function(obj) {
790 for (var n in obj) {
791 if (typeof(obj[n]) === 'object') {
792 obj[n] = null;
793 }
794 }
795 };
796
797 // These may not all be necessary, but it can't hurt...
798 nullOut(this.layout_);
799 nullOut(this.plotter_);
800 nullOut(this);
801};
6a1aa64f
DV
802
803/**
629a09ae
DV
804 * Creates the canvas on which the chart will be drawn. Only the Renderer ever
805 * draws on this particular canvas. All Dygraph work (i.e. drawing hover dots
806 * or the zoom rectangles) is done on this.canvas_.
8846615a 807 * @param {Object} canvas The Dygraph canvas over which to overlay the plot
6a1aa64f
DV
808 * @return {Object} The newly-created canvas
809 * @private
810 */
285a6bda 811Dygraph.prototype.createPlotKitCanvas_ = function(canvas) {
f8cfec73 812 var h = Dygraph.createCanvas();
6a1aa64f 813 h.style.position = "absolute";
9ac5e4ae
DV
814 // TODO(danvk): h should be offset from canvas. canvas needs to include
815 // some extra area to make it easier to zoom in on the far left and far
816 // right. h needs to be precisely the plot area, so that clipping occurs.
6a1aa64f
DV
817 h.style.top = canvas.style.top;
818 h.style.left = canvas.style.left;
819 h.width = this.width_;
820 h.height = this.height_;
f8cfec73
DV
821 h.style.width = this.width_ + "px"; // for IE
822 h.style.height = this.height_ + "px"; // for IE
6a1aa64f
DV
823 return h;
824};
825
629a09ae
DV
826/**
827 * Convert hsv values to an rgb(r,g,b) string. Taken from MochiKit.Color. This
828 * is used to generate default series colors which are evenly spaced on the
829 * color wheel.
830 * @param { Number } hue Range is 0.0-1.0.
831 * @param { Number } saturation Range is 0.0-1.0.
832 * @param { Number } value Range is 0.0-1.0.
833 * @return { String } "rgb(r,g,b)" where r, g and b range from 0-255.
834 * @private
835 */
f474c2a3
DV
836Dygraph.hsvToRGB = function (hue, saturation, value) {
837 var red;
838 var green;
839 var blue;
840 if (saturation === 0) {
841 red = value;
842 green = value;
843 blue = value;
844 } else {
845 var i = Math.floor(hue * 6);
846 var f = (hue * 6) - i;
847 var p = value * (1 - saturation);
848 var q = value * (1 - (saturation * f));
849 var t = value * (1 - (saturation * (1 - f)));
850 switch (i) {
851 case 1: red = q; green = value; blue = p; break;
852 case 2: red = p; green = value; blue = t; break;
853 case 3: red = p; green = q; blue = value; break;
854 case 4: red = t; green = p; blue = value; break;
855 case 5: red = value; green = p; blue = q; break;
856 case 6: // fall through
857 case 0: red = value; green = t; blue = p; break;
858 }
859 }
860 red = Math.floor(255 * red + 0.5);
861 green = Math.floor(255 * green + 0.5);
862 blue = Math.floor(255 * blue + 0.5);
863 return 'rgb(' + red + ',' + green + ',' + blue + ')';
864};
865
866
6a1aa64f
DV
867/**
868 * Generate a set of distinct colors for the data series. This is done with a
869 * color wheel. Saturation/Value are customizable, and the hue is
870 * equally-spaced around the color wheel. If a custom set of colors is
871 * specified, that is used instead.
6a1aa64f
DV
872 * @private
873 */
285a6bda 874Dygraph.prototype.setColors_ = function() {
285a6bda 875 var num = this.attr_("labels").length - 1;
6a1aa64f 876 this.colors_ = [];
285a6bda
DV
877 var colors = this.attr_('colors');
878 if (!colors) {
879 var sat = this.attr_('colorSaturation') || 1.0;
880 var val = this.attr_('colorValue') || 0.5;
2aa21213 881 var half = Math.ceil(num / 2);
6a1aa64f 882 for (var i = 1; i <= num; i++) {
ec1959eb 883 if (!this.visibility()[i-1]) continue;
43af96e7 884 // alternate colors for high contrast.
2aa21213 885 var idx = i % 2 ? Math.ceil(i / 2) : (half + i / 2);
43af96e7
NK
886 var hue = (1.0 * idx/ (1 + num));
887 this.colors_.push(Dygraph.hsvToRGB(hue, sat, val));
6a1aa64f
DV
888 }
889 } else {
890 for (var i = 0; i < num; i++) {
ec1959eb 891 if (!this.visibility()[i]) continue;
285a6bda 892 var colorStr = colors[i % colors.length];
f474c2a3 893 this.colors_.push(colorStr);
6a1aa64f
DV
894 }
895 }
600d841a
DV
896
897 this.plotter_.setColors(this.colors_);
629a09ae 898};
6a1aa64f 899
43af96e7
NK
900/**
901 * Return the list of colors. This is either the list of colors passed in the
629a09ae 902 * attributes or the autogenerated list of rgb(r,g,b) strings.
43af96e7
NK
903 * @return {Array<string>} The list of colors.
904 */
905Dygraph.prototype.getColors = function() {
906 return this.colors_;
907};
908
5e60386d
DV
909// The following functions are from quirksmode.org with a modification for Safari from
910// http://blog.firetree.net/2005/07/04/javascript-find-position/
3df0ccf0 911// http://www.quirksmode.org/js/findpos.html
629a09ae 912
c39e1d93 913/** @private */
3df0ccf0
DV
914Dygraph.findPosX = function(obj) {
915 var curleft = 0;
5e60386d 916 if(obj.offsetParent)
50360fd0 917 while(1)
5e60386d 918 {
3df0ccf0 919 curleft += obj.offsetLeft;
5e60386d
DV
920 if(!obj.offsetParent)
921 break;
3df0ccf0
DV
922 obj = obj.offsetParent;
923 }
5e60386d 924 else if(obj.x)
3df0ccf0
DV
925 curleft += obj.x;
926 return curleft;
927};
c21d2c2d 928
629a09ae 929
c39e1d93 930/** @private */
3df0ccf0
DV
931Dygraph.findPosY = function(obj) {
932 var curtop = 0;
5e60386d
DV
933 if(obj.offsetParent)
934 while(1)
935 {
3df0ccf0 936 curtop += obj.offsetTop;
5e60386d
DV
937 if(!obj.offsetParent)
938 break;
3df0ccf0
DV
939 obj = obj.offsetParent;
940 }
5e60386d 941 else if(obj.y)
3df0ccf0
DV
942 curtop += obj.y;
943 return curtop;
944};
945
5e60386d 946
6a1aa64f
DV
947/**
948 * Create the div that contains information on the selected point(s)
949 * This goes in the top right of the canvas, unless an external div has already
950 * been specified.
951 * @private
952 */
fedbd797 953Dygraph.prototype.createStatusMessage_ = function() {
954 var userLabelsDiv = this.user_attrs_["labelsDiv"];
955 if (userLabelsDiv && null != userLabelsDiv
956 && (typeof(userLabelsDiv) == "string" || userLabelsDiv instanceof String)) {
957 this.user_attrs_["labelsDiv"] = document.getElementById(userLabelsDiv);
958 }
285a6bda
DV
959 if (!this.attr_("labelsDiv")) {
960 var divWidth = this.attr_('labelsDivWidth');
b0c3b730 961 var messagestyle = {
6a1aa64f
DV
962 "position": "absolute",
963 "fontSize": "14px",
964 "zIndex": 10,
965 "width": divWidth + "px",
966 "top": "0px",
8846615a 967 "left": (this.width_ - divWidth - 2) + "px",
6a1aa64f
DV
968 "background": "white",
969 "textAlign": "left",
b0c3b730 970 "overflow": "hidden"};
fc80a396 971 Dygraph.update(messagestyle, this.attr_('labelsDivStyles'));
b0c3b730
DV
972 var div = document.createElement("div");
973 for (var name in messagestyle) {
85b99f0b
DV
974 if (messagestyle.hasOwnProperty(name)) {
975 div.style[name] = messagestyle[name];
976 }
b0c3b730
DV
977 }
978 this.graphDiv.appendChild(div);
285a6bda 979 this.attrs_.labelsDiv = div;
6a1aa64f
DV
980 }
981};
982
983/**
ad1798c2
DV
984 * Position the labels div so that:
985 * - its right edge is flush with the right edge of the charting area
986 * - its top edge is flush with the top edge of the charting area
629a09ae 987 * @private
0abfbd7e
DV
988 */
989Dygraph.prototype.positionLabelsDiv_ = function() {
990 // Don't touch a user-specified labelsDiv.
991 if (this.user_attrs_.hasOwnProperty("labelsDiv")) return;
992
993 var area = this.plotter_.area;
994 var div = this.attr_("labelsDiv");
8c21adcf 995 div.style.left = area.x + area.w - this.attr_("labelsDivWidth") - 1 + "px";
ad1798c2 996 div.style.top = area.y + "px";
0abfbd7e
DV
997};
998
999/**
6a1aa64f 1000 * Create the text box to adjust the averaging period
6a1aa64f
DV
1001 * @private
1002 */
285a6bda 1003Dygraph.prototype.createRollInterface_ = function() {
8c69de65
DV
1004 // Create a roller if one doesn't exist already.
1005 if (!this.roller_) {
1006 this.roller_ = document.createElement("input");
1007 this.roller_.type = "text";
1008 this.roller_.style.display = "none";
1009 this.graphDiv.appendChild(this.roller_);
1010 }
1011
1012 var display = this.attr_('showRoller') ? 'block' : 'none';
26ca7938 1013
0c38f187 1014 var area = this.plotter_.area;
b0c3b730
DV
1015 var textAttr = { "position": "absolute",
1016 "zIndex": 10,
0c38f187
DV
1017 "top": (area.y + area.h - 25) + "px",
1018 "left": (area.x + 1) + "px",
b0c3b730 1019 "display": display
6a1aa64f 1020 };
8c69de65
DV
1021 this.roller_.size = "2";
1022 this.roller_.value = this.rollPeriod_;
b0c3b730 1023 for (var name in textAttr) {
85b99f0b 1024 if (textAttr.hasOwnProperty(name)) {
8c69de65 1025 this.roller_.style[name] = textAttr[name];
85b99f0b 1026 }
b0c3b730
DV
1027 }
1028
76171648 1029 var dygraph = this;
8c69de65 1030 this.roller_.onchange = function() { dygraph.adjustRoll(dygraph.roller_.value); };
76171648
DV
1031};
1032
629a09ae
DV
1033/**
1034 * @private
1035 * Returns the x-coordinate of the event in a coordinate system where the
1036 * top-left corner of the page (not the window) is (0,0).
1037 * Taken from MochiKit.Signal
1038 */
76171648
DV
1039Dygraph.pageX = function(e) {
1040 if (e.pageX) {
1041 return (!e.pageX || e.pageX < 0) ? 0 : e.pageX;
1042 } else {
1043 var de = document;
1044 var b = document.body;
1045 return e.clientX +
1046 (de.scrollLeft || b.scrollLeft) -
1047 (de.clientLeft || 0);
1048 }
1049};
1050
629a09ae
DV
1051/**
1052 * @private
1053 * Returns the y-coordinate of the event in a coordinate system where the
1054 * top-left corner of the page (not the window) is (0,0).
1055 * Taken from MochiKit.Signal
1056 */
76171648
DV
1057Dygraph.pageY = function(e) {
1058 if (e.pageY) {
1059 return (!e.pageY || e.pageY < 0) ? 0 : e.pageY;
1060 } else {
1061 var de = document;
1062 var b = document.body;
1063 return e.clientY +
1064 (de.scrollTop || b.scrollTop) -
1065 (de.clientTop || 0);
1066 }
1067};
6a1aa64f 1068
629a09ae
DV
1069/**
1070 * @private
1071 * Converts page the x-coordinate of the event to pixel x-coordinates on the
1072 * canvas (i.e. DOM Coords).
1073 */
062ef401
JB
1074Dygraph.prototype.dragGetX_ = function(e, context) {
1075 return Dygraph.pageX(e) - context.px
1076};
bce01b0f 1077
629a09ae
DV
1078/**
1079 * @private
1080 * Converts page the y-coordinate of the event to pixel y-coordinates on the
1081 * canvas (i.e. DOM Coords).
1082 */
062ef401
JB
1083Dygraph.prototype.dragGetY_ = function(e, context) {
1084 return Dygraph.pageY(e) - context.py
1085};
ee672584 1086
629a09ae 1087/**
0393dbfd
DV
1088 * A collection of functions to facilitate build custom interaction models.
1089 * @class
1090 */
1091Dygraph.Interaction = {};
1092
1093/**
629a09ae
DV
1094 * Called in response to an interaction model operation that
1095 * should start the default panning behavior.
1096 *
1097 * It's used in the default callback for "mousedown" operations.
1098 * Custom interaction model builders can use it to provide the default
1099 * panning behavior.
1100 *
1101 * @param { Event } event the event object which led to the startPan call.
1102 * @param { Dygraph} g The dygraph on which to act.
1103 * @param { Object} context The dragging context object (with
1104 * dragStartX/dragStartY/etc. properties). This function modifies the context.
1105 */
0393dbfd 1106Dygraph.Interaction.startPan = function(event, g, context) {
062ef401
JB
1107 context.isPanning = true;
1108 var xRange = g.xAxisRange();
1109 context.dateRange = xRange[1] - xRange[0];
ec291cbe
RK
1110 context.initialLeftmostDate = xRange[0];
1111 context.xUnitsPerPixel = context.dateRange / (g.plotter_.area.w - 1);
062ef401 1112
965a030e
RK
1113 if (g.attr_("panEdgeFraction")) {
1114 var maxXPixelsToDraw = g.width_ * g.attr_("panEdgeFraction");
4cac8c7a
RK
1115 var xExtremes = g.xAxisExtremes(); // I REALLY WANT TO CALL THIS xTremes!
1116
1117 var boundedLeftX = g.toDomXCoord(xExtremes[0]) - maxXPixelsToDraw;
1118 var boundedRightX = g.toDomXCoord(xExtremes[1]) + maxXPixelsToDraw;
1119
1120 var boundedLeftDate = g.toDataXCoord(boundedLeftX);
1121 var boundedRightDate = g.toDataXCoord(boundedRightX);
1122 context.boundedDates = [boundedLeftDate, boundedRightDate];
1123
1124 var boundedValues = [];
965a030e 1125 var maxYPixelsToDraw = g.height_ * g.attr_("panEdgeFraction");
4cac8c7a
RK
1126
1127 for (var i = 0; i < g.axes_.length; i++) {
1128 var axis = g.axes_[i];
1129 var yExtremes = axis.extremeRange;
1130
1131 var boundedTopY = g.toDomYCoord(yExtremes[0], i) + maxYPixelsToDraw;
1132 var boundedBottomY = g.toDomYCoord(yExtremes[1], i) - maxYPixelsToDraw;
1133
1134 var boundedTopValue = g.toDataYCoord(boundedTopY);
1135 var boundedBottomValue = g.toDataYCoord(boundedBottomY);
1136
4cac8c7a
RK
1137 boundedValues[i] = [boundedTopValue, boundedBottomValue];
1138 }
1139 context.boundedValues = boundedValues;
1140 }
1141
062ef401
JB
1142 // Record the range of each y-axis at the start of the drag.
1143 // If any axis has a valueRange or valueWindow, then we want a 2D pan.
1144 context.is2DPan = false;
1145 for (var i = 0; i < g.axes_.length; i++) {
1146 var axis = g.axes_[i];
1147 var yRange = g.yAxisRange(i);
ec291cbe 1148 // TODO(konigsberg): These values should be in |context|.
ed898bdd
RK
1149 // In log scale, initialTopValue, dragValueRange and unitsPerPixel are log scale.
1150 if (axis.logscale) {
1151 axis.initialTopValue = Dygraph.log10(yRange[1]);
1152 axis.dragValueRange = Dygraph.log10(yRange[1]) - Dygraph.log10(yRange[0]);
1153 } else {
1154 axis.initialTopValue = yRange[1];
1155 axis.dragValueRange = yRange[1] - yRange[0];
1156 }
ec291cbe 1157 axis.unitsPerPixel = axis.dragValueRange / (g.plotter_.area.h - 1);
ed898bdd
RK
1158
1159 // While calculating axes, set 2dpan.
062ef401
JB
1160 if (axis.valueWindow || axis.valueRange) context.is2DPan = true;
1161 }
062ef401 1162};
6a1aa64f 1163
629a09ae
DV
1164/**
1165 * Called in response to an interaction model operation that
1166 * responds to an event that pans the view.
1167 *
1168 * It's used in the default callback for "mousemove" operations.
1169 * Custom interaction model builders can use it to provide the default
1170 * panning behavior.
1171 *
1172 * @param { Event } event the event object which led to the movePan call.
1173 * @param { Dygraph} g The dygraph on which to act.
1174 * @param { Object} context The dragging context object (with
1175 * dragStartX/dragStartY/etc. properties). This function modifies the context.
1176 */
0393dbfd 1177Dygraph.Interaction.movePan = function(event, g, context) {
062ef401
JB
1178 context.dragEndX = g.dragGetX_(event, context);
1179 context.dragEndY = g.dragGetY_(event, context);
79b3ee42 1180
ec291cbe
RK
1181 var minDate = context.initialLeftmostDate -
1182 (context.dragEndX - context.dragStartX) * context.xUnitsPerPixel;
4cac8c7a
RK
1183 if (context.boundedDates) {
1184 minDate = Math.max(minDate, context.boundedDates[0]);
1185 }
062ef401 1186 var maxDate = minDate + context.dateRange;
4cac8c7a
RK
1187 if (context.boundedDates) {
1188 if (maxDate > context.boundedDates[1]) {
1189 // Adjust minDate, and recompute maxDate.
1190 minDate = minDate - (maxDate - context.boundedDates[1]);
965a030e 1191 maxDate = minDate + context.dateRange;
4cac8c7a
RK
1192 }
1193 }
1194
062ef401
JB
1195 g.dateWindow_ = [minDate, maxDate];
1196
1197 // y-axis scaling is automatic unless this is a full 2D pan.
1198 if (context.is2DPan) {
1199 // Adjust each axis appropriately.
062ef401
JB
1200 for (var i = 0; i < g.axes_.length; i++) {
1201 var axis = g.axes_[i];
ed898bdd
RK
1202
1203 var pixelsDragged = context.dragEndY - context.dragStartY;
1204 var unitsDragged = pixelsDragged * axis.unitsPerPixel;
4cac8c7a
RK
1205
1206 var boundedValue = context.boundedValues ? context.boundedValues[i] : null;
ed898bdd
RK
1207
1208 // In log scale, maxValue and minValue are the logs of those values.
1209 var maxValue = axis.initialTopValue + unitsDragged;
4cac8c7a
RK
1210 if (boundedValue) {
1211 maxValue = Math.min(maxValue, boundedValue[1]);
1212 }
062ef401 1213 var minValue = maxValue - axis.dragValueRange;
4cac8c7a
RK
1214 if (boundedValue) {
1215 if (minValue < boundedValue[0]) {
1216 // Adjust maxValue, and recompute minValue.
1217 maxValue = maxValue - (minValue - boundedValue[0]);
1218 minValue = maxValue - axis.dragValueRange;
1219 }
1220 }
ed898bdd 1221 if (axis.logscale) {
5db0e241
DV
1222 axis.valueWindow = [ Math.pow(Dygraph.LOG_SCALE, minValue),
1223 Math.pow(Dygraph.LOG_SCALE, maxValue) ];
ed898bdd
RK
1224 } else {
1225 axis.valueWindow = [ minValue, maxValue ];
1226 }
6faebb69 1227 }
062ef401 1228 }
bce01b0f 1229
062ef401 1230 g.drawGraph_();
629a09ae 1231};
ee672584 1232
629a09ae
DV
1233/**
1234 * Called in response to an interaction model operation that
1235 * responds to an event that ends panning.
1236 *
1237 * It's used in the default callback for "mouseup" operations.
1238 * Custom interaction model builders can use it to provide the default
1239 * panning behavior.
1240 *
1241 * @param { Event } event the event object which led to the startZoom call.
1242 * @param { Dygraph} g The dygraph on which to act.
1243 * @param { Object} context The dragging context object (with
1244 * dragStartX/dragStartY/etc. properties). This function modifies the context.
1245 */
0393dbfd 1246Dygraph.Interaction.endPan = function(event, g, context) {
ec291cbe
RK
1247 // TODO(konigsberg): Clear the context data from the axis.
1248 // TODO(konigsberg): mouseup should just delete the
1249 // context object, and mousedown should create a new one.
062ef401
JB
1250 context.isPanning = false;
1251 context.is2DPan = false;
ec291cbe 1252 context.initialLeftmostDate = null;
062ef401
JB
1253 context.dateRange = null;
1254 context.valueRange = null;
9ec21d0a
RK
1255 context.boundedDates = null;
1256 context.boundedValues = null;
629a09ae 1257};
ee672584 1258
629a09ae
DV
1259/**
1260 * Called in response to an interaction model operation that
1261 * responds to an event that starts zooming.
1262 *
1263 * It's used in the default callback for "mousedown" operations.
1264 * Custom interaction model builders can use it to provide the default
1265 * zooming behavior.
1266 *
1267 * @param { Event } event the event object which led to the startZoom call.
1268 * @param { Dygraph} g The dygraph on which to act.
1269 * @param { Object} context The dragging context object (with
1270 * dragStartX/dragStartY/etc. properties). This function modifies the context.
1271 */
0393dbfd 1272Dygraph.Interaction.startZoom = function(event, g, context) {
062ef401 1273 context.isZooming = true;
629a09ae 1274};
062ef401 1275
629a09ae
DV
1276/**
1277 * Called in response to an interaction model operation that
1278 * responds to an event that defines zoom boundaries.
1279 *
1280 * It's used in the default callback for "mousemove" operations.
1281 * Custom interaction model builders can use it to provide the default
1282 * zooming behavior.
1283 *
1284 * @param { Event } event the event object which led to the moveZoom call.
1285 * @param { Dygraph} g The dygraph on which to act.
1286 * @param { Object} context The dragging context object (with
1287 * dragStartX/dragStartY/etc. properties). This function modifies the context.
1288 */
0393dbfd 1289Dygraph.Interaction.moveZoom = function(event, g, context) {
062ef401
JB
1290 context.dragEndX = g.dragGetX_(event, context);
1291 context.dragEndY = g.dragGetY_(event, context);
1292
1293 var xDelta = Math.abs(context.dragStartX - context.dragEndX);
1294 var yDelta = Math.abs(context.dragStartY - context.dragEndY);
1295
1296 // drag direction threshold for y axis is twice as large as x axis
1297 context.dragDirection = (xDelta < yDelta / 2) ? Dygraph.VERTICAL : Dygraph.HORIZONTAL;
1298
1299 g.drawZoomRect_(
1300 context.dragDirection,
1301 context.dragStartX,
1302 context.dragEndX,
1303 context.dragStartY,
1304 context.dragEndY,
1305 context.prevDragDirection,
1306 context.prevEndX,
1307 context.prevEndY);
1308
1309 context.prevEndX = context.dragEndX;
1310 context.prevEndY = context.dragEndY;
1311 context.prevDragDirection = context.dragDirection;
629a09ae 1312};
062ef401 1313
629a09ae
DV
1314/**
1315 * Called in response to an interaction model operation that
1316 * responds to an event that performs a zoom based on previously defined
1317 * bounds..
1318 *
1319 * It's used in the default callback for "mouseup" operations.
1320 * Custom interaction model builders can use it to provide the default
1321 * zooming behavior.
1322 *
1323 * @param { Event } event the event object which led to the endZoom call.
1324 * @param { Dygraph} g The dygraph on which to end the zoom.
1325 * @param { Object} context The dragging context object (with
1326 * dragStartX/dragStartY/etc. properties). This function modifies the context.
1327 */
0393dbfd 1328Dygraph.Interaction.endZoom = function(event, g, context) {
629a09ae 1329 // TODO(konigsberg): Refactor or rename this fn -- it deals with clicks, too.
062ef401
JB
1330 context.isZooming = false;
1331 context.dragEndX = g.dragGetX_(event, context);
1332 context.dragEndY = g.dragGetY_(event, context);
1333 var regionWidth = Math.abs(context.dragEndX - context.dragStartX);
1334 var regionHeight = Math.abs(context.dragEndY - context.dragStartY);
1335
1336 if (regionWidth < 2 && regionHeight < 2 &&
1337 g.lastx_ != undefined && g.lastx_ != -1) {
1338 // TODO(danvk): pass along more info about the points, e.g. 'x'
1339 if (g.attr_('clickCallback') != null) {
1340 g.attr_('clickCallback')(event, g.lastx_, g.selPoints_);
1341 }
1342 if (g.attr_('pointClickCallback')) {
1343 // check if the click was on a particular point.
1344 var closestIdx = -1;
1345 var closestDistance = 0;
1346 for (var i = 0; i < g.selPoints_.length; i++) {
1347 var p = g.selPoints_[i];
1348 var distance = Math.pow(p.canvasx - context.dragEndX, 2) +
1349 Math.pow(p.canvasy - context.dragEndY, 2);
1350 if (closestIdx == -1 || distance < closestDistance) {
1351 closestDistance = distance;
1352 closestIdx = i;
d58ae307
DV
1353 }
1354 }
e3489f4f 1355
062ef401
JB
1356 // Allow any click within two pixels of the dot.
1357 var radius = g.attr_('highlightCircleSize') + 2;
1358 if (closestDistance <= 5 * 5) {
1359 g.attr_('pointClickCallback')(event, g.selPoints_[closestIdx]);
6faebb69 1360 }
062ef401
JB
1361 }
1362 }
0a52ab7a 1363
062ef401
JB
1364 if (regionWidth >= 10 && context.dragDirection == Dygraph.HORIZONTAL) {
1365 g.doZoomX_(Math.min(context.dragStartX, context.dragEndX),
1366 Math.max(context.dragStartX, context.dragEndX));
1367 } else if (regionHeight >= 10 && context.dragDirection == Dygraph.VERTICAL) {
1368 g.doZoomY_(Math.min(context.dragStartY, context.dragEndY),
1369 Math.max(context.dragStartY, context.dragEndY));
1370 } else {
2cf95fff 1371 g.canvas_ctx_.clearRect(0, 0, g.canvas_.width, g.canvas_.height);
062ef401
JB
1372 }
1373 context.dragStartX = null;
1374 context.dragStartY = null;
629a09ae 1375};
062ef401 1376
629a09ae
DV
1377/**
1378 * Default interation model for dygraphs. You can refer to specific elements of
1379 * this when constructing your own interaction model, e.g.:
1380 * g.updateOptions( {
1381 * interactionModel: {
1382 * mousedown: Dygraph.defaultInteractionModel.mousedown
1383 * }
1384 * } );
1385 */
0393dbfd 1386Dygraph.Interaction.defaultModel = {
062ef401
JB
1387 // Track the beginning of drag events
1388 mousedown: function(event, g, context) {
1389 context.initializeMouseDown(event, g, context);
1390
1391 if (event.altKey || event.shiftKey) {
1392 Dygraph.startPan(event, g, context);
bce01b0f 1393 } else {
062ef401 1394 Dygraph.startZoom(event, g, context);
bce01b0f 1395 }
062ef401 1396 },
6a1aa64f 1397
062ef401
JB
1398 // Draw zoom rectangles when the mouse is down and the user moves around
1399 mousemove: function(event, g, context) {
1400 if (context.isZooming) {
1401 Dygraph.moveZoom(event, g, context);
1402 } else if (context.isPanning) {
1403 Dygraph.movePan(event, g, context);
6a1aa64f 1404 }
062ef401 1405 },
bce01b0f 1406
062ef401
JB
1407 mouseup: function(event, g, context) {
1408 if (context.isZooming) {
1409 Dygraph.endZoom(event, g, context);
1410 } else if (context.isPanning) {
1411 Dygraph.endPan(event, g, context);
bce01b0f 1412 }
062ef401 1413 },
6a1aa64f
DV
1414
1415 // Temporarily cancel the dragging event when the mouse leaves the graph
062ef401
JB
1416 mouseout: function(event, g, context) {
1417 if (context.isZooming) {
1418 context.dragEndX = null;
1419 context.dragEndY = null;
6a1aa64f 1420 }
062ef401 1421 },
6a1aa64f 1422
062ef401
JB
1423 // Disable zooming out if panning.
1424 dblclick: function(event, g, context) {
1425 if (event.altKey || event.shiftKey) {
1426 return;
1427 }
1428 // TODO(konigsberg): replace g.doUnzoom()_ with something that is
1429 // friendlier to public use.
1430 g.doUnzoom_();
1431 }
1432};
1e1bf7df 1433
0393dbfd
DV
1434Dygraph.DEFAULT_ATTRS.interactionModel = Dygraph.Interaction.defaultModel;
1435
1436// old ways of accessing these methods/properties
1437Dygraph.defaultInteractionModel = Dygraph.Interaction.defaultModel;
1438Dygraph.endZoom = Dygraph.Interaction.endZoom;
1439Dygraph.moveZoom = Dygraph.Interaction.moveZoom;
1440Dygraph.startZoom = Dygraph.Interaction.startZoom;
1441Dygraph.endPan = Dygraph.Interaction.endPan;
1442Dygraph.movePan = Dygraph.Interaction.movePan;
1443Dygraph.startPan = Dygraph.Interaction.startPan;
6a1aa64f 1444
062ef401
JB
1445/**
1446 * Set up all the mouse handlers needed to capture dragging behavior for zoom
1447 * events.
1448 * @private
1449 */
1450Dygraph.prototype.createDragInterface_ = function() {
1451 var context = {
1452 // Tracks whether the mouse is down right now
1453 isZooming: false,
1454 isPanning: false, // is this drag part of a pan?
1455 is2DPan: false, // if so, is that pan 1- or 2-dimensional?
1456 dragStartX: null,
1457 dragStartY: null,
1458 dragEndX: null,
1459 dragEndY: null,
1460 dragDirection: null,
1461 prevEndX: null,
1462 prevEndY: null,
1463 prevDragDirection: null,
1464
ec291cbe
RK
1465 // The value on the left side of the graph when a pan operation starts.
1466 initialLeftmostDate: null,
1467
1468 // The number of units each pixel spans. (This won't be valid for log
1469 // scales)
1470 xUnitsPerPixel: null,
062ef401
JB
1471
1472 // TODO(danvk): update this comment
1473 // The range in second/value units that the viewport encompasses during a
1474 // panning operation.
1475 dateRange: null,
1476
1477 // Utility function to convert page-wide coordinates to canvas coords
1478 px: 0,
1479 py: 0,
1480
965a030e 1481 // Values for use with panEdgeFraction, which limit how far outside the
4cac8c7a
RK
1482 // graph's data boundaries it can be panned.
1483 boundedDates: null, // [minDate, maxDate]
1484 boundedValues: null, // [[minValue, maxValue] ...]
1485
062ef401
JB
1486 initializeMouseDown: function(event, g, context) {
1487 // prevents mouse drags from selecting page text.
1488 if (event.preventDefault) {
1489 event.preventDefault(); // Firefox, Chrome, etc.
6a1aa64f 1490 } else {
062ef401
JB
1491 event.returnValue = false; // IE
1492 event.cancelBubble = true;
6a1aa64f
DV
1493 }
1494
062ef401
JB
1495 context.px = Dygraph.findPosX(g.canvas_);
1496 context.py = Dygraph.findPosY(g.canvas_);
1497 context.dragStartX = g.dragGetX_(event, context);
1498 context.dragStartY = g.dragGetY_(event, context);
6a1aa64f 1499 }
062ef401 1500 };
2b188b3d 1501
062ef401 1502 var interactionModel = this.attr_("interactionModel");
8b83c6cc 1503
062ef401
JB
1504 // Self is the graph.
1505 var self = this;
6faebb69 1506
062ef401
JB
1507 // Function that binds the graph and context to the handler.
1508 var bindHandler = function(handler) {
1509 return function(event) {
1510 handler(event, self, context);
1511 };
1512 };
1513
1514 for (var eventName in interactionModel) {
1515 if (!interactionModel.hasOwnProperty(eventName)) continue;
1516 Dygraph.addEvent(this.mouseEventElement_, eventName,
1517 bindHandler(interactionModel[eventName]));
1518 }
1519
1520 // If the user releases the mouse button during a drag, but not over the
1521 // canvas, then it doesn't count as a zooming action.
1522 Dygraph.addEvent(document, 'mouseup', function(event) {
1523 if (context.isZooming || context.isPanning) {
1524 context.isZooming = false;
1525 context.dragStartX = null;
1526 context.dragStartY = null;
1527 }
1528
1529 if (context.isPanning) {
1530 context.isPanning = false;
1531 context.draggingDate = null;
1532 context.dateRange = null;
1533 for (var i = 0; i < self.axes_.length; i++) {
1534 delete self.axes_[i].draggingValue;
1535 delete self.axes_[i].dragValueRange;
1536 }
1537 }
6a1aa64f
DV
1538 });
1539};
1540
062ef401 1541
6a1aa64f
DV
1542/**
1543 * Draw a gray zoom rectangle over the desired area of the canvas. Also clears
1544 * up any previous zoom rectangles that were drawn. This could be optimized to
1545 * avoid extra redrawing, but it's tricky to avoid interactions with the status
1546 * dots.
8b83c6cc 1547 *
39b0e098
RK
1548 * @param {Number} direction the direction of the zoom rectangle. Acceptable
1549 * values are Dygraph.HORIZONTAL and Dygraph.VERTICAL.
6a1aa64f
DV
1550 * @param {Number} startX The X position where the drag started, in canvas
1551 * coordinates.
1552 * @param {Number} endX The current X position of the drag, in canvas coords.
8b83c6cc
RK
1553 * @param {Number} startY The Y position where the drag started, in canvas
1554 * coordinates.
1555 * @param {Number} endY The current Y position of the drag, in canvas coords.
39b0e098 1556 * @param {Number} prevDirection the value of direction on the previous call to
8b83c6cc 1557 * this function. Used to avoid excess redrawing
6a1aa64f
DV
1558 * @param {Number} prevEndX The value of endX on the previous call to this
1559 * function. Used to avoid excess redrawing
8b83c6cc
RK
1560 * @param {Number} prevEndY The value of endY on the previous call to this
1561 * function. Used to avoid excess redrawing
6a1aa64f
DV
1562 * @private
1563 */
7201b11e
JB
1564Dygraph.prototype.drawZoomRect_ = function(direction, startX, endX, startY,
1565 endY, prevDirection, prevEndX,
1566 prevEndY) {
2cf95fff 1567 var ctx = this.canvas_ctx_;
6a1aa64f
DV
1568
1569 // Clean up from the previous rect if necessary
39b0e098 1570 if (prevDirection == Dygraph.HORIZONTAL) {
6a1aa64f
DV
1571 ctx.clearRect(Math.min(startX, prevEndX), 0,
1572 Math.abs(startX - prevEndX), this.height_);
39b0e098 1573 } else if (prevDirection == Dygraph.VERTICAL){
8b83c6cc
RK
1574 ctx.clearRect(0, Math.min(startY, prevEndY),
1575 this.width_, Math.abs(startY - prevEndY));
6a1aa64f
DV
1576 }
1577
1578 // Draw a light-grey rectangle to show the new viewing area
39b0e098 1579 if (direction == Dygraph.HORIZONTAL) {
8b83c6cc
RK
1580 if (endX && startX) {
1581 ctx.fillStyle = "rgba(128,128,128,0.33)";
1582 ctx.fillRect(Math.min(startX, endX), 0,
1583 Math.abs(endX - startX), this.height_);
1584 }
1585 }
39b0e098 1586 if (direction == Dygraph.VERTICAL) {
8b83c6cc
RK
1587 if (endY && startY) {
1588 ctx.fillStyle = "rgba(128,128,128,0.33)";
1589 ctx.fillRect(0, Math.min(startY, endY),
1590 this.width_, Math.abs(endY - startY));
1591 }
6a1aa64f
DV
1592 }
1593};
1594
1595/**
8b83c6cc
RK
1596 * Zoom to something containing [lowX, highX]. These are pixel coordinates in
1597 * the canvas. The exact zoom window may be slightly larger if there are no data
1598 * points near lowX or highX. Don't confuse this function with doZoomXDates,
1599 * which accepts dates that match the raw data. This function redraws the graph.
d58ae307 1600 *
6a1aa64f
DV
1601 * @param {Number} lowX The leftmost pixel value that should be visible.
1602 * @param {Number} highX The rightmost pixel value that should be visible.
1603 * @private
1604 */
8b83c6cc 1605Dygraph.prototype.doZoomX_ = function(lowX, highX) {
6a1aa64f 1606 // Find the earliest and latest dates contained in this canvasx range.
8b83c6cc 1607 // Convert the call to date ranges of the raw data.
ff022deb
RK
1608 var minDate = this.toDataXCoord(lowX);
1609 var maxDate = this.toDataXCoord(highX);
8b83c6cc
RK
1610 this.doZoomXDates_(minDate, maxDate);
1611};
6a1aa64f 1612
8b83c6cc
RK
1613/**
1614 * Zoom to something containing [minDate, maxDate] values. Don't confuse this
1615 * method with doZoomX which accepts pixel coordinates. This function redraws
1616 * the graph.
d58ae307 1617 *
8b83c6cc
RK
1618 * @param {Number} minDate The minimum date that should be visible.
1619 * @param {Number} maxDate The maximum date that should be visible.
1620 * @private
1621 */
1622Dygraph.prototype.doZoomXDates_ = function(minDate, maxDate) {
6a1aa64f 1623 this.dateWindow_ = [minDate, maxDate];
57baab03 1624 this.zoomed_x_ = true;
26ca7938 1625 this.drawGraph_();
285a6bda 1626 if (this.attr_("zoomCallback")) {
ac139d19 1627 this.attr_("zoomCallback")(minDate, maxDate, this.yAxisRanges());
8b83c6cc
RK
1628 }
1629};
1630
1631/**
1632 * Zoom to something containing [lowY, highY]. These are pixel coordinates in
d58ae307
DV
1633 * the canvas. This function redraws the graph.
1634 *
8b83c6cc
RK
1635 * @param {Number} lowY The topmost pixel value that should be visible.
1636 * @param {Number} highY The lowest pixel value that should be visible.
1637 * @private
1638 */
1639Dygraph.prototype.doZoomY_ = function(lowY, highY) {
d58ae307
DV
1640 // Find the highest and lowest values in pixel range for each axis.
1641 // Note that lowY (in pixels) corresponds to the max Value (in data coords).
1642 // This is because pixels increase as you go down on the screen, whereas data
1643 // coordinates increase as you go up the screen.
1644 var valueRanges = [];
1645 for (var i = 0; i < this.axes_.length; i++) {
ff022deb
RK
1646 var hi = this.toDataYCoord(lowY, i);
1647 var low = this.toDataYCoord(highY, i);
1648 this.axes_[i].valueWindow = [low, hi];
1649 valueRanges.push([low, hi]);
d58ae307 1650 }
8b83c6cc 1651
57baab03 1652 this.zoomed_y_ = true;
66c380c4 1653 this.drawGraph_();
8b83c6cc 1654 if (this.attr_("zoomCallback")) {
d58ae307 1655 var xRange = this.xAxisRange();
45f2c689 1656 var yRange = this.yAxisRange();
d58ae307 1657 this.attr_("zoomCallback")(xRange[0], xRange[1], this.yAxisRanges());
8b83c6cc
RK
1658 }
1659};
1660
1661/**
1662 * Reset the zoom to the original view coordinates. This is the same as
1663 * double-clicking on the graph.
d58ae307 1664 *
8b83c6cc
RK
1665 * @private
1666 */
1667Dygraph.prototype.doUnzoom_ = function() {
d58ae307 1668 var dirty = false;
8b83c6cc 1669 if (this.dateWindow_ != null) {
d58ae307 1670 dirty = true;
8b83c6cc
RK
1671 this.dateWindow_ = null;
1672 }
d58ae307
DV
1673
1674 for (var i = 0; i < this.axes_.length; i++) {
1675 if (this.axes_[i].valueWindow != null) {
1676 dirty = true;
1677 delete this.axes_[i].valueWindow;
1678 }
8b83c6cc
RK
1679 }
1680
da1369a5
DV
1681 // Clear any selection, since it's likely to be drawn in the wrong place.
1682 this.clearSelection();
1683
8b83c6cc 1684 if (dirty) {
437c0979
RK
1685 // Putting the drawing operation before the callback because it resets
1686 // yAxisRange.
57baab03
NN
1687 this.zoomed_x_ = false;
1688 this.zoomed_y_ = false;
66c380c4 1689 this.drawGraph_();
8b83c6cc
RK
1690 if (this.attr_("zoomCallback")) {
1691 var minDate = this.rawData_[0][0];
1692 var maxDate = this.rawData_[this.rawData_.length - 1][0];
d58ae307 1693 this.attr_("zoomCallback")(minDate, maxDate, this.yAxisRanges());
8b83c6cc 1694 }
67e650dc 1695 }
6a1aa64f
DV
1696};
1697
1698/**
1699 * When the mouse moves in the canvas, display information about a nearby data
1700 * point and draw dots over those points in the data series. This function
1701 * takes care of cleanup of previously-drawn dots.
1702 * @param {Object} event The mousemove event from the browser.
1703 * @private
1704 */
285a6bda 1705Dygraph.prototype.mouseMove_ = function(event) {
e863a17d 1706 // This prevents JS errors when mousing over the canvas before data loads.
4cac8c7a 1707 var points = this.layout_.points;
685ebbb3 1708 if (points === undefined) return;
e863a17d 1709
4cac8c7a
RK
1710 var canvasx = Dygraph.pageX(event) - Dygraph.findPosX(this.mouseEventElement_);
1711
6a1aa64f
DV
1712 var lastx = -1;
1713 var lasty = -1;
1714
1715 // Loop through all the points and find the date nearest to our current
1716 // location.
1717 var minDist = 1e+100;
1718 var idx = -1;
1719 for (var i = 0; i < points.length; i++) {
8a7cc60e
RK
1720 var point = points[i];
1721 if (point == null) continue;
062ef401 1722 var dist = Math.abs(point.canvasx - canvasx);
f032c51d 1723 if (dist > minDist) continue;
6a1aa64f
DV
1724 minDist = dist;
1725 idx = i;
1726 }
1727 if (idx >= 0) lastx = points[idx].xval;
6a1aa64f
DV
1728
1729 // Extract the points we've selected
b258a3da 1730 this.selPoints_ = [];
50360fd0 1731 var l = points.length;
416b05ad
NK
1732 if (!this.attr_("stackedGraph")) {
1733 for (var i = 0; i < l; i++) {
1734 if (points[i].xval == lastx) {
1735 this.selPoints_.push(points[i]);
1736 }
1737 }
1738 } else {
354e15ab
DE
1739 // Need to 'unstack' points starting from the bottom
1740 var cumulative_sum = 0;
416b05ad
NK
1741 for (var i = l - 1; i >= 0; i--) {
1742 if (points[i].xval == lastx) {
354e15ab 1743 var p = {}; // Clone the point since we modify it
d4139cd8
NK
1744 for (var k in points[i]) {
1745 p[k] = points[i][k];
50360fd0
NK
1746 }
1747 p.yval -= cumulative_sum;
1748 cumulative_sum += p.yval;
d4139cd8 1749 this.selPoints_.push(p);
12e4c741 1750 }
6a1aa64f 1751 }
354e15ab 1752 this.selPoints_.reverse();
6a1aa64f
DV
1753 }
1754
b258a3da 1755 if (this.attr_("highlightCallback")) {
a4c6a67c 1756 var px = this.lastx_;
dd082dda 1757 if (px !== null && lastx != px) {
344ba8c0 1758 // only fire if the selected point has changed.
2ddb1197 1759 this.attr_("highlightCallback")(event, lastx, this.selPoints_, this.idxToRow_(idx));
43af96e7 1760 }
12e4c741 1761 }
43af96e7 1762
239c712d
NAG
1763 // Save last x position for callbacks.
1764 this.lastx_ = lastx;
50360fd0 1765
239c712d
NAG
1766 this.updateSelection_();
1767};
b258a3da 1768
239c712d 1769/**
1903f1e4 1770 * Transforms layout_.points index into data row number.
2ddb1197 1771 * @param int layout_.points index
1903f1e4 1772 * @return int row number, or -1 if none could be found.
2ddb1197
SC
1773 * @private
1774 */
1775Dygraph.prototype.idxToRow_ = function(idx) {
1903f1e4 1776 if (idx < 0) return -1;
2ddb1197 1777
1903f1e4
DV
1778 for (var i in this.layout_.datasets) {
1779 if (idx < this.layout_.datasets[i].length) {
1780 return this.boundaryIds_[0][0]+idx;
1781 }
1782 idx -= this.layout_.datasets[i].length;
1783 }
1784 return -1;
1785};
2ddb1197 1786
629a09ae
DV
1787/**
1788 * @private
1789 * @param { Number } x The number to consider.
1790 * @return { Boolean } Whether the number is zero or NaN.
1791 */
2fccd3dc 1792// TODO(danvk): rename this function to something like 'isNonZeroNan'.
e9fe4a2f
DV
1793Dygraph.isOK = function(x) {
1794 return x && !isNaN(x);
1795};
1796
629a09ae
DV
1797/**
1798 * @private
1799 * Generates HTML for the legend which is displayed when hovering over the
1800 * chart. If no selected points are specified, a default legend is returned
1801 * (this may just be the empty string).
1802 * @param { Number } [x] The x-value of the selected points.
1803 * @param { [Object] } [sel_points] List of selected points for the given
1804 * x-value. Should have properties like 'name', 'yval' and 'canvasy'.
1805 */
e9fe4a2f 1806Dygraph.prototype.generateLegendHTML_ = function(x, sel_points) {
2fccd3dc
DV
1807 // If no points are selected, we display a default legend. Traditionally,
1808 // this has been blank. But a better default would be a conventional legend,
1809 // which provides essential information for a non-interactive chart.
1810 if (typeof(x) === 'undefined') {
1811 if (this.attr_('legend') != 'always') return '';
1812
1813 var sepLines = this.attr_('labelsSeparateLines');
1814 var labels = this.attr_('labels');
1815 var html = '';
1816 for (var i = 1; i < labels.length; i++) {
352c8310 1817 if (!this.visibility()[i - 1]) continue;
bafe040e 1818 var c = this.plotter_.colors[labels[i]];
352c8310 1819 if (html != '') html += (sepLines ? '<br/>' : ' ');
bafe040e
DV
1820 html += "<b><span style='color: " + c + ";'>&mdash;" + labels[i] +
1821 "</span></b>";
2fccd3dc
DV
1822 }
1823 return html;
1824 }
1825
032e4c1d 1826 var html = this.attr_('xValueFormatter')(x) + ":";
e9fe4a2f
DV
1827
1828 var fmtFunc = this.attr_('yValueFormatter');
1829 var showZeros = this.attr_("labelsShowZeroValues");
1830 var sepLines = this.attr_("labelsSeparateLines");
1831 for (var i = 0; i < this.selPoints_.length; i++) {
1832 var pt = this.selPoints_[i];
1833 if (pt.yval == 0 && !showZeros) continue;
1834 if (!Dygraph.isOK(pt.canvasy)) continue;
1835 if (sepLines) html += "<br/>";
1836
bafe040e 1837 var c = this.plotter_.colors[pt.name];
91c10d9c 1838 var yval = fmtFunc(pt.yval, this);
2fccd3dc 1839 // TODO(danvk): use a template string here and make it an attribute.
bafe040e
DV
1840 html += " <b><span style='color: " + c + ";'>"
1841 + pt.name + "</span></b>:"
e9fe4a2f
DV
1842 + yval;
1843 }
1844 return html;
1845};
1846
629a09ae
DV
1847/**
1848 * @private
1849 * Displays information about the selected points in the legend. If there is no
1850 * selection, the legend will be cleared.
1851 * @param { Number } [x] The x-value of the selected points.
1852 * @param { [Object] } [sel_points] List of selected points for the given
1853 * x-value. Should have properties like 'name', 'yval' and 'canvasy'.
1854 */
91c10d9c
DV
1855Dygraph.prototype.setLegendHTML_ = function(x, sel_points) {
1856 var html = this.generateLegendHTML_(x, sel_points);
1857 var labelsDiv = this.attr_("labelsDiv");
1858 if (labelsDiv !== null) {
1859 labelsDiv.innerHTML = html;
1860 } else {
1861 if (typeof(this.shown_legend_error_) == 'undefined') {
1862 this.error('labelsDiv is set to something nonexistent; legend will not be shown.');
1863 this.shown_legend_error_ = true;
1864 }
1865 }
1866};
1867
2ddb1197 1868/**
239c712d
NAG
1869 * Draw dots over the selectied points in the data series. This function
1870 * takes care of cleanup of previously-drawn dots.
1871 * @private
1872 */
1873Dygraph.prototype.updateSelection_ = function() {
6a1aa64f 1874 // Clear the previously drawn vertical, if there is one
2cf95fff 1875 var ctx = this.canvas_ctx_;
6a1aa64f 1876 if (this.previousVerticalX_ >= 0) {
46dde5f9
DV
1877 // Determine the maximum highlight circle size.
1878 var maxCircleSize = 0;
227b93cc
DV
1879 var labels = this.attr_('labels');
1880 for (var i = 1; i < labels.length; i++) {
1881 var r = this.attr_('highlightCircleSize', labels[i]);
46dde5f9
DV
1882 if (r > maxCircleSize) maxCircleSize = r;
1883 }
6a1aa64f 1884 var px = this.previousVerticalX_;
46dde5f9
DV
1885 ctx.clearRect(px - maxCircleSize - 1, 0,
1886 2 * maxCircleSize + 2, this.height_);
6a1aa64f
DV
1887 }
1888
d160cc3b 1889 if (this.selPoints_.length > 0) {
6a1aa64f 1890 // Set the status message to indicate the selected point(s)
d160cc3b 1891 if (this.attr_('showLabelsOnHighlight')) {
91c10d9c 1892 this.setLegendHTML_(this.lastx_, this.selPoints_);
6a1aa64f 1893 }
6a1aa64f 1894
6a1aa64f 1895 // Draw colored circles over the center of each selected point
e9fe4a2f 1896 var canvasx = this.selPoints_[0].canvasx;
43af96e7 1897 ctx.save();
b258a3da 1898 for (var i = 0; i < this.selPoints_.length; i++) {
e9fe4a2f
DV
1899 var pt = this.selPoints_[i];
1900 if (!Dygraph.isOK(pt.canvasy)) continue;
1901
1902 var circleSize = this.attr_('highlightCircleSize', pt.name);
6a1aa64f 1903 ctx.beginPath();
e9fe4a2f
DV
1904 ctx.fillStyle = this.plotter_.colors[pt.name];
1905 ctx.arc(canvasx, pt.canvasy, circleSize, 0, 2 * Math.PI, false);
6a1aa64f
DV
1906 ctx.fill();
1907 }
1908 ctx.restore();
1909
1910 this.previousVerticalX_ = canvasx;
1911 }
1912};
1913
1914/**
629a09ae
DV
1915 * Manually set the selected points and display information about them in the
1916 * legend. The selection can be cleared using clearSelection() and queried
1917 * using getSelection().
1918 * @param { Integer } row number that should be highlighted (i.e. appear with
1919 * hover dots on the chart). Set to false to clear any selection.
239c712d
NAG
1920 */
1921Dygraph.prototype.setSelection = function(row) {
1922 // Extract the points we've selected
1923 this.selPoints_ = [];
1924 var pos = 0;
50360fd0 1925
239c712d 1926 if (row !== false) {
16269f6e
NAG
1927 row = row-this.boundaryIds_[0][0];
1928 }
50360fd0 1929
16269f6e 1930 if (row !== false && row >= 0) {
239c712d 1931 for (var i in this.layout_.datasets) {
16269f6e 1932 if (row < this.layout_.datasets[i].length) {
38f33a44 1933 var point = this.layout_.points[pos+row];
1934
1935 if (this.attr_("stackedGraph")) {
8c03ba63 1936 point = this.layout_.unstackPointAtIndex(pos+row);
38f33a44 1937 }
1938
1939 this.selPoints_.push(point);
16269f6e 1940 }
239c712d
NAG
1941 pos += this.layout_.datasets[i].length;
1942 }
16269f6e 1943 }
50360fd0 1944
16269f6e 1945 if (this.selPoints_.length) {
239c712d
NAG
1946 this.lastx_ = this.selPoints_[0].xval;
1947 this.updateSelection_();
1948 } else {
239c712d
NAG
1949 this.clearSelection();
1950 }
1951
1952};
1953
1954/**
6a1aa64f
DV
1955 * The mouse has left the canvas. Clear out whatever artifacts remain
1956 * @param {Object} event the mouseout event from the browser.
1957 * @private
1958 */
285a6bda 1959Dygraph.prototype.mouseOut_ = function(event) {
a4c6a67c
AV
1960 if (this.attr_("unhighlightCallback")) {
1961 this.attr_("unhighlightCallback")(event);
1962 }
1963
43af96e7 1964 if (this.attr_("hideOverlayOnMouseOut")) {
239c712d 1965 this.clearSelection();
43af96e7 1966 }
6a1aa64f
DV
1967};
1968
239c712d 1969/**
629a09ae
DV
1970 * Clears the current selection (i.e. points that were highlighted by moving
1971 * the mouse over the chart).
239c712d
NAG
1972 */
1973Dygraph.prototype.clearSelection = function() {
1974 // Get rid of the overlay data
2cf95fff 1975 this.canvas_ctx_.clearRect(0, 0, this.width_, this.height_);
91c10d9c 1976 this.setLegendHTML_();
239c712d
NAG
1977 this.selPoints_ = [];
1978 this.lastx_ = -1;
1979}
1980
103b7292 1981/**
629a09ae
DV
1982 * Returns the number of the currently selected row. To get data for this row,
1983 * you can use the getValue method.
1984 * @return { Integer } row number, or -1 if nothing is selected
103b7292
NAG
1985 */
1986Dygraph.prototype.getSelection = function() {
1987 if (!this.selPoints_ || this.selPoints_.length < 1) {
1988 return -1;
1989 }
50360fd0 1990
103b7292
NAG
1991 for (var row=0; row<this.layout_.points.length; row++ ) {
1992 if (this.layout_.points[row].x == this.selPoints_[0].x) {
16269f6e 1993 return row + this.boundaryIds_[0][0];
103b7292
NAG
1994 }
1995 }
1996 return -1;
2e1fcf1a 1997};
103b7292 1998
19589a3e
DV
1999/**
2000 * Number formatting function which mimicks the behavior of %g in printf, i.e.
2001 * either exponential or fixed format (without trailing 0s) is used depending on
2002 * the length of the generated string. The advantage of this format is that
2003 * there is a predictable upper bound on the resulting string length,
2004 * significant figures are not dropped, and normal numbers are not displayed in
2005 * exponential notation.
2006 *
2007 * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g.
2008 * It creates strings which are too long for absolute values between 10^-4 and
2009 * 10^-6, e.g. '0.00001' instead of '1e-5'. See tests/number-format.html for
2010 * output examples.
2011 *
2012 * @param {Number} x The number to format
2013 * @param {Number} opt_precision The precision to use, default 2.
2014 * @return {String} A string formatted like %g in printf. The max generated
2015 * string length should be precision + 6 (e.g 1.123e+300).
2016 */
2017Dygraph.floatFormat = function(x, opt_precision) {
2018 // Avoid invalid precision values; [1, 21] is the valid range.
2019 var p = Math.min(Math.max(1, opt_precision || 2), 21);
2020
2021 // This is deceptively simple. The actual algorithm comes from:
2022 //
2023 // Max allowed length = p + 4
2024 // where 4 comes from 'e+n' and '.'.
2025 //
2026 // Length of fixed format = 2 + y + p
2027 // where 2 comes from '0.' and y = # of leading zeroes.
2028 //
2029 // Equating the two and solving for y yields y = 2, or 0.00xxxx which is
2030 // 1.0e-3.
2031 //
2032 // Since the behavior of toPrecision() is identical for larger numbers, we
2033 // don't have to worry about the other bound.
2034 //
2035 // Finally, the argument for toExponential() is the number of trailing digits,
2036 // so we take off 1 for the value before the '.'.
2037 return (Math.abs(x) < 1.0e-3 && x != 0.0) ?
2038 x.toExponential(p - 1) : x.toPrecision(p);
2e1fcf1a
DV
2039};
2040
2041/**
629a09ae 2042 * @private
2e1fcf1a
DV
2043 * Return a string version of a number. This respects the digitsAfterDecimal
2044 * and maxNumberWidth options.
2045 * @param {Number} x The number to be formatted
2046 * @param {Dygraph} g The dygraph object
2047 */
2048Dygraph.numberFormatter = function(x, g) {
19589a3e
DV
2049 var sigFigs = g.attr_('sigFigs');
2050
2051 if (sigFigs !== null) {
2052 // User has opted for a fixed number of significant figures.
2053 return Dygraph.floatFormat(x, sigFigs);
2054 }
2055
2e1fcf1a
DV
2056 var digits = g.attr_('digitsAfterDecimal');
2057 var maxNumberWidth = g.attr_('maxNumberWidth');
2058
19589a3e
DV
2059 // switch to scientific notation if we underflow or overflow fixed display.
2060 if (x !== 0.0 &&
2061 (Math.abs(x) >= Math.pow(10, maxNumberWidth) ||
2062 Math.abs(x) < Math.pow(10, -digits))) {
2063 return x.toExponential(digits);
2e1fcf1a
DV
2064 } else {
2065 return '' + Dygraph.round_(x, digits);
2066 }
2067};
32988383 2068
629a09ae
DV
2069/**
2070 * @private
2071 * Converts '9' to '09' (useful for dates)
2072 */
19589a3e
DV
2073Dygraph.zeropad = function(x) {
2074 if (x < 10) return "0" + x; else return "" + x;
2075};
2076
6a1aa64f 2077/**
6b8e33dd
DV
2078 * Return a string version of the hours, minutes and seconds portion of a date.
2079 * @param {Number} date The JavaScript date (ms since epoch)
2080 * @return {String} A time of the form "HH:MM:SS"
2081 * @private
2082 */
bf640e56 2083Dygraph.hmsString_ = function(date) {
285a6bda 2084 var zeropad = Dygraph.zeropad;
6b8e33dd
DV
2085 var d = new Date(date);
2086 if (d.getSeconds()) {
2087 return zeropad(d.getHours()) + ":" +
2088 zeropad(d.getMinutes()) + ":" +
2089 zeropad(d.getSeconds());
6b8e33dd 2090 } else {
054531ca 2091 return zeropad(d.getHours()) + ":" + zeropad(d.getMinutes());
6b8e33dd 2092 }
2e1fcf1a 2093};
6b8e33dd
DV
2094
2095/**
bf640e56
AV
2096 * Convert a JS date to a string appropriate to display on an axis that
2097 * is displaying values at the stated granularity.
2098 * @param {Date} date The date to format
2099 * @param {Number} granularity One of the Dygraph granularity constants
2100 * @return {String} The formatted date
2101 * @private
2102 */
2103Dygraph.dateAxisFormatter = function(date, granularity) {
062ef401
JB
2104 if (granularity >= Dygraph.DECADAL) {
2105 return date.strftime('%Y');
2106 } else if (granularity >= Dygraph.MONTHLY) {
bf640e56
AV
2107 return date.strftime('%b %y');
2108 } else {
31eddad3 2109 var frac = date.getHours() * 3600 + date.getMinutes() * 60 + date.getSeconds() + date.getMilliseconds();
bf640e56
AV
2110 if (frac == 0 || granularity >= Dygraph.DAILY) {
2111 return new Date(date.getTime() + 3600*1000).strftime('%d%b');
2112 } else {
2113 return Dygraph.hmsString_(date.getTime());
2114 }
2115 }
2e1fcf1a 2116};
bf640e56
AV
2117
2118/**
6a1aa64f
DV
2119 * Convert a JS date (millis since epoch) to YYYY/MM/DD
2120 * @param {Number} date The JavaScript date (ms since epoch)
2121 * @return {String} A date of the form "YYYY/MM/DD"
2122 * @private
2123 */
6be8e54c 2124Dygraph.dateString_ = function(date) {
285a6bda 2125 var zeropad = Dygraph.zeropad;
6a1aa64f
DV
2126 var d = new Date(date);
2127
2128 // Get the year:
2129 var year = "" + d.getFullYear();
2130 // Get a 0 padded month string
6b8e33dd 2131 var month = zeropad(d.getMonth() + 1); //months are 0-offset, sigh
6a1aa64f 2132 // Get a 0 padded day string
6b8e33dd 2133 var day = zeropad(d.getDate());
6a1aa64f 2134
6b8e33dd
DV
2135 var ret = "";
2136 var frac = d.getHours() * 3600 + d.getMinutes() * 60 + d.getSeconds();
bf640e56 2137 if (frac) ret = " " + Dygraph.hmsString_(date);
6b8e33dd
DV
2138
2139 return year + "/" + month + "/" + day + ret;
6a1aa64f
DV
2140};
2141
2142/**
032e4c1d
DV
2143 * Round a number to the specified number of digits past the decimal point.
2144 * @param {Number} num The number to round
2145 * @param {Number} places The number of decimals to which to round
2146 * @return {Number} The rounded number
2147 * @private
2148 */
2149Dygraph.round_ = function(num, places) {
2150 var shift = Math.pow(10, places);
2151 return Math.round(num * shift)/shift;
2152};
2153
2154/**
6a1aa64f
DV
2155 * Fires when there's data available to be graphed.
2156 * @param {String} data Raw CSV data to be plotted
2157 * @private
2158 */
285a6bda 2159Dygraph.prototype.loadedEvent_ = function(data) {
6a1aa64f 2160 this.rawData_ = this.parseCSV_(data);
26ca7938 2161 this.predraw_();
6a1aa64f
DV
2162};
2163
285a6bda 2164Dygraph.prototype.months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
8846615a 2165 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
285a6bda 2166Dygraph.prototype.quarters = ["Jan", "Apr", "Jul", "Oct"];
6a1aa64f
DV
2167
2168/**
2169 * Add ticks on the x-axis representing years, months, quarters, weeks, or days
2170 * @private
2171 */
285a6bda 2172Dygraph.prototype.addXTicks_ = function() {
6a1aa64f 2173 // Determine the correct ticks scale on the x-axis: quarterly, monthly, ...
7201b11e 2174 var range;
6a1aa64f 2175 if (this.dateWindow_) {
7201b11e 2176 range = [this.dateWindow_[0], this.dateWindow_[1]];
6a1aa64f 2177 } else {
7201b11e
JB
2178 range = [this.rawData_[0][0], this.rawData_[this.rawData_.length - 1][0]];
2179 }
2180
032e4c1d 2181 var xTicks = this.attr_('xTicker')(range[0], range[1], this);
b2c9222a 2182 this.layout_.setXTicks(xTicks);
32988383
DV
2183};
2184
2185// Time granularity enumeration
285a6bda 2186Dygraph.SECONDLY = 0;
20a41c17
DV
2187Dygraph.TWO_SECONDLY = 1;
2188Dygraph.FIVE_SECONDLY = 2;
2189Dygraph.TEN_SECONDLY = 3;
2190Dygraph.THIRTY_SECONDLY = 4;
2191Dygraph.MINUTELY = 5;
2192Dygraph.TWO_MINUTELY = 6;
2193Dygraph.FIVE_MINUTELY = 7;
2194Dygraph.TEN_MINUTELY = 8;
2195Dygraph.THIRTY_MINUTELY = 9;
2196Dygraph.HOURLY = 10;
2197Dygraph.TWO_HOURLY = 11;
2198Dygraph.SIX_HOURLY = 12;
2199Dygraph.DAILY = 13;
2200Dygraph.WEEKLY = 14;
2201Dygraph.MONTHLY = 15;
2202Dygraph.QUARTERLY = 16;
2203Dygraph.BIANNUAL = 17;
2204Dygraph.ANNUAL = 18;
2205Dygraph.DECADAL = 19;
062ef401
JB
2206Dygraph.CENTENNIAL = 20;
2207Dygraph.NUM_GRANULARITIES = 21;
285a6bda
DV
2208
2209Dygraph.SHORT_SPACINGS = [];
2210Dygraph.SHORT_SPACINGS[Dygraph.SECONDLY] = 1000 * 1;
20a41c17
DV
2211Dygraph.SHORT_SPACINGS[Dygraph.TWO_SECONDLY] = 1000 * 2;
2212Dygraph.SHORT_SPACINGS[Dygraph.FIVE_SECONDLY] = 1000 * 5;
285a6bda
DV
2213Dygraph.SHORT_SPACINGS[Dygraph.TEN_SECONDLY] = 1000 * 10;
2214Dygraph.SHORT_SPACINGS[Dygraph.THIRTY_SECONDLY] = 1000 * 30;
2215Dygraph.SHORT_SPACINGS[Dygraph.MINUTELY] = 1000 * 60;
20a41c17
DV
2216Dygraph.SHORT_SPACINGS[Dygraph.TWO_MINUTELY] = 1000 * 60 * 2;
2217Dygraph.SHORT_SPACINGS[Dygraph.FIVE_MINUTELY] = 1000 * 60 * 5;
285a6bda
DV
2218Dygraph.SHORT_SPACINGS[Dygraph.TEN_MINUTELY] = 1000 * 60 * 10;
2219Dygraph.SHORT_SPACINGS[Dygraph.THIRTY_MINUTELY] = 1000 * 60 * 30;
2220Dygraph.SHORT_SPACINGS[Dygraph.HOURLY] = 1000 * 3600;
20a41c17 2221Dygraph.SHORT_SPACINGS[Dygraph.TWO_HOURLY] = 1000 * 3600 * 2;
805d5519 2222Dygraph.SHORT_SPACINGS[Dygraph.SIX_HOURLY] = 1000 * 3600 * 6;
285a6bda
DV
2223Dygraph.SHORT_SPACINGS[Dygraph.DAILY] = 1000 * 86400;
2224Dygraph.SHORT_SPACINGS[Dygraph.WEEKLY] = 1000 * 604800;
32988383 2225
629a09ae
DV
2226/**
2227 * @private
2228 * If we used this time granularity, how many ticks would there be?
2229 * This is only an approximation, but it's generally good enough.
2230 */
285a6bda
DV
2231Dygraph.prototype.NumXTicks = function(start_time, end_time, granularity) {
2232 if (granularity < Dygraph.MONTHLY) {
32988383 2233 // Generate one tick mark for every fixed interval of time.
285a6bda 2234 var spacing = Dygraph.SHORT_SPACINGS[granularity];
32988383
DV
2235 return Math.floor(0.5 + 1.0 * (end_time - start_time) / spacing);
2236 } else {
2237 var year_mod = 1; // e.g. to only print one point every 10 years.
2238 var num_months = 12;
285a6bda
DV
2239 if (granularity == Dygraph.QUARTERLY) num_months = 3;
2240 if (granularity == Dygraph.BIANNUAL) num_months = 2;
2241 if (granularity == Dygraph.ANNUAL) num_months = 1;
2242 if (granularity == Dygraph.DECADAL) { num_months = 1; year_mod = 10; }
062ef401 2243 if (granularity == Dygraph.CENTENNIAL) { num_months = 1; year_mod = 100; }
32988383
DV
2244
2245 var msInYear = 365.2524 * 24 * 3600 * 1000;
2246 var num_years = 1.0 * (end_time - start_time) / msInYear;
2247 return Math.floor(0.5 + 1.0 * num_years * num_months / year_mod);
2248 }
2249};
2250
629a09ae
DV
2251/**
2252 * @private
2253 *
2254 * Construct an x-axis of nicely-formatted times on meaningful boundaries
2255 * (e.g. 'Jan 09' rather than 'Jan 22, 2009').
2256 *
2257 * Returns an array containing {v: millis, label: label} dictionaries.
2258 */
285a6bda 2259Dygraph.prototype.GetXAxis = function(start_time, end_time, granularity) {
bf640e56 2260 var formatter = this.attr_("xAxisLabelFormatter");
32988383 2261 var ticks = [];
285a6bda 2262 if (granularity < Dygraph.MONTHLY) {
32988383 2263 // Generate one tick mark for every fixed interval of time.
285a6bda 2264 var spacing = Dygraph.SHORT_SPACINGS[granularity];
3d29302c 2265 var format = '%d%b'; // e.g. "1Jan"
076c9622
DV
2266
2267 // Find a time less than start_time which occurs on a "nice" time boundary
2268 // for this granularity.
2269 var g = spacing / 1000;
076c9622
DV
2270 var d = new Date(start_time);
2271 if (g <= 60) { // seconds
2272 var x = d.getSeconds(); d.setSeconds(x - x % g);
2273 } else {
2274 d.setSeconds(0);
2275 g /= 60;
2276 if (g <= 60) { // minutes
2277 var x = d.getMinutes(); d.setMinutes(x - x % g);
2278 } else {
2279 d.setMinutes(0);
2280 g /= 60;
2281
2282 if (g <= 24) { // days
2283 var x = d.getHours(); d.setHours(x - x % g);
2284 } else {
2285 d.setHours(0);
2286 g /= 24;
2287
2288 if (g == 7) { // one week
20a41c17 2289 d.setDate(d.getDate() - d.getDay());
076c9622
DV
2290 }
2291 }
2292 }
328bb812 2293 }
076c9622
DV
2294 start_time = d.getTime();
2295
32988383 2296 for (var t = start_time; t <= end_time; t += spacing) {
bf640e56 2297 ticks.push({ v:t, label: formatter(new Date(t), granularity) });
32988383
DV
2298 }
2299 } else {
2300 // Display a tick mark on the first of a set of months of each year.
2301 // Years get a tick mark iff y % year_mod == 0. This is useful for
2302 // displaying a tick mark once every 10 years, say, on long time scales.
2303 var months;
2304 var year_mod = 1; // e.g. to only print one point every 10 years.
2305
285a6bda 2306 if (granularity == Dygraph.MONTHLY) {
32988383 2307 months = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ];
285a6bda 2308 } else if (granularity == Dygraph.QUARTERLY) {
32988383 2309 months = [ 0, 3, 6, 9 ];
285a6bda 2310 } else if (granularity == Dygraph.BIANNUAL) {
32988383 2311 months = [ 0, 6 ];
285a6bda 2312 } else if (granularity == Dygraph.ANNUAL) {
32988383 2313 months = [ 0 ];
285a6bda 2314 } else if (granularity == Dygraph.DECADAL) {
32988383
DV
2315 months = [ 0 ];
2316 year_mod = 10;
062ef401
JB
2317 } else if (granularity == Dygraph.CENTENNIAL) {
2318 months = [ 0 ];
2319 year_mod = 100;
2320 } else {
2321 this.warn("Span of dates is too long");
32988383
DV
2322 }
2323
2324 var start_year = new Date(start_time).getFullYear();
2325 var end_year = new Date(end_time).getFullYear();
285a6bda 2326 var zeropad = Dygraph.zeropad;
32988383
DV
2327 for (var i = start_year; i <= end_year; i++) {
2328 if (i % year_mod != 0) continue;
2329 for (var j = 0; j < months.length; j++) {
2330 var date_str = i + "/" + zeropad(1 + months[j]) + "/01";
d96b7d1a 2331 var t = Dygraph.dateStrToMillis(date_str);
32988383 2332 if (t < start_time || t > end_time) continue;
bf640e56 2333 ticks.push({ v:t, label: formatter(new Date(t), granularity) });
32988383
DV
2334 }
2335 }
2336 }
2337
2338 return ticks;
2339};
2340
6a1aa64f
DV
2341
2342/**
2343 * Add ticks to the x-axis based on a date range.
2344 * @param {Number} startDate Start of the date window (millis since epoch)
2345 * @param {Number} endDate End of the date window (millis since epoch)
629a09ae
DV
2346 * @param {Dygraph} self The dygraph object
2347 * @return { [Object] } Array of {label, value} tuples.
6a1aa64f
DV
2348 * @public
2349 */
285a6bda 2350Dygraph.dateTicker = function(startDate, endDate, self) {
629a09ae 2351 // TODO(danvk): why does this take 'self' as a param?
32988383 2352 var chosen = -1;
285a6bda
DV
2353 for (var i = 0; i < Dygraph.NUM_GRANULARITIES; i++) {
2354 var num_ticks = self.NumXTicks(startDate, endDate, i);
2355 if (self.width_ / num_ticks >= self.attr_('pixelsPerXLabel')) {
32988383
DV
2356 chosen = i;
2357 break;
2769de62 2358 }
6a1aa64f
DV
2359 }
2360
32988383 2361 if (chosen >= 0) {
285a6bda 2362 return self.GetXAxis(startDate, endDate, chosen);
6a1aa64f 2363 } else {
32988383 2364 // TODO(danvk): signal error.
6a1aa64f 2365 }
6a1aa64f
DV
2366};
2367
629a09ae
DV
2368/**
2369 * @private
2370 * This is a list of human-friendly values at which to show tick marks on a log
2371 * scale. It is k * 10^n, where k=1..9 and n=-39..+39, so:
2372 * ..., 1, 2, 3, 4, 5, ..., 9, 10, 20, 30, ..., 90, 100, 200, 300, ...
2373 * NOTE: this assumes that Dygraph.LOG_SCALE = 10.
2374 */
0cfa06d1 2375Dygraph.PREFERRED_LOG_TICK_VALUES = function() {
6821efbe
RK
2376 var vals = [];
2377 for (var power = -39; power <= 39; power++) {
2378 var range = Math.pow(10, power);
4b467120
RK
2379 for (var mult = 1; mult <= 9; mult++) {
2380 var val = range * mult;
6821efbe
RK
2381 vals.push(val);
2382 }
2383 }
2384 return vals;
2385}();
2386
629a09ae
DV
2387/**
2388 * @private
2389 * Implementation of binary search over an array.
2390 * Currently does not work when val is outside the range of arry's values.
2391 * @param { Integer } val the value to search for
2392 * @param { Integer[] } arry is the value over which to search
2393 * @param { Integer } abs If abs > 0, find the lowest entry greater than val
2394 * If abs < 0, find the highest entry less than val.
2395 * if abs == 0, find the entry that equals val.
2396 * @param { Integer } [low] The first index in arry to consider (optional)
2397 * @param { Integer } [high] The last index in arry to consider (optional)
2398 */
0cfa06d1
RK
2399Dygraph.binarySearch = function(val, arry, abs, low, high) {
2400 if (low == null || high == null) {
2401 low = 0;
2402 high = arry.length - 1;
2403 }
2404 if (low > high) {
2405 return -1;
2406 }
2407 if (abs == null) {
2408 abs = 0;
2409 }
2410 var validIndex = function(idx) {
2411 return idx >= 0 && idx < arry.length;
2412 }
2413 var mid = parseInt((low + high) / 2);
2414 var element = arry[mid];
2415 if (element == val) {
2416 return mid;
2417 }
2418 if (element > val) {
2419 if (abs > 0) {
2420 // Accept if element > val, but also if prior element < val.
2421 var idx = mid - 1;
2422 if (validIndex(idx) && arry[idx] < val) {
2423 return mid;
2424 }
2425 }
c1bc242a 2426 return Dygraph.binarySearch(val, arry, abs, low, mid - 1);
0cfa06d1
RK
2427 }
2428 if (element < val) {
2429 if (abs < 0) {
2430 // Accept if element < val, but also if prior element > val.
2431 var idx = mid + 1;
2432 if (validIndex(idx) && arry[idx] > val) {
2433 return mid;
2434 }
2435 }
2436 return Dygraph.binarySearch(val, arry, abs, mid + 1, high);
2437 }
60a19014 2438};
0cfa06d1 2439
629a09ae 2440// TODO(konigsberg): Update comment.
6a1aa64f
DV
2441/**
2442 * Add ticks when the x axis has numbers on it (instead of dates)
ff022deb 2443 *
7d0e7a0d
RK
2444 * @param {Number} minV minimum value
2445 * @param {Number} maxV maximum value
84fc6aa7 2446 * @param self
f30cf740 2447 * @param {function} attribute accessor function.
629a09ae 2448 * @return {[Object]} Array of {label, value} tuples.
6a1aa64f 2449 */
0d64e596 2450Dygraph.numericTicks = function(minV, maxV, self, axis_props, vals) {
70c80071
DV
2451 var attr = function(k) {
2452 if (axis_props && axis_props.hasOwnProperty(k)) return axis_props[k];
2453 return self.attr_(k);
2454 };
f09fc545 2455
0d64e596
DV
2456 var ticks = [];
2457 if (vals) {
2458 for (var i = 0; i < vals.length; i++) {
e863a17d 2459 ticks.push({v: vals[i]});
0d64e596 2460 }
f09e46d4 2461 } else {
7d0e7a0d 2462 if (axis_props && attr("logscale")) {
ff022deb 2463 var pixelsPerTick = attr('pixelsPerYLabel');
7d0e7a0d 2464 // NOTE(konigsberg): Dan, should self.height_ be self.plotter_.area.h?
ff022deb 2465 var nTicks = Math.floor(self.height_ / pixelsPerTick);
0cfa06d1
RK
2466 var minIdx = Dygraph.binarySearch(minV, Dygraph.PREFERRED_LOG_TICK_VALUES, 1);
2467 var maxIdx = Dygraph.binarySearch(maxV, Dygraph.PREFERRED_LOG_TICK_VALUES, -1);
2468 if (minIdx == -1) {
6821efbe
RK
2469 minIdx = 0;
2470 }
0cfa06d1
RK
2471 if (maxIdx == -1) {
2472 maxIdx = Dygraph.PREFERRED_LOG_TICK_VALUES.length - 1;
6821efbe 2473 }
0cfa06d1
RK
2474 // Count the number of tick values would appear, if we can get at least
2475 // nTicks / 4 accept them.
00aa7f61 2476 var lastDisplayed = null;
0cfa06d1 2477 if (maxIdx - minIdx >= nTicks / 4) {
00aa7f61 2478 var axisId = axis_props.yAxisId;
0cfa06d1
RK
2479 for (var idx = maxIdx; idx >= minIdx; idx--) {
2480 var tickValue = Dygraph.PREFERRED_LOG_TICK_VALUES[idx];
00aa7f61
RK
2481 var domCoord = axis_props.g.toDomYCoord(tickValue, axisId);
2482 var tick = { v: tickValue };
2483 if (lastDisplayed == null) {
2484 lastDisplayed = {
2485 tickValue : tickValue,
2486 domCoord : domCoord
2487 };
2488 } else {
2489 if (domCoord - lastDisplayed.domCoord >= pixelsPerTick) {
2490 lastDisplayed = {
2491 tickValue : tickValue,
2492 domCoord : domCoord
2493 };
2494 } else {
c1bc242a 2495 tick.label = "";
00aa7f61
RK
2496 }
2497 }
2498 ticks.push(tick);
6821efbe 2499 }
0cfa06d1
RK
2500 // Since we went in backwards order.
2501 ticks.reverse();
6821efbe 2502 }
f09e46d4 2503 }
c1bc242a 2504
6821efbe
RK
2505 // ticks.length won't be 0 if the log scale function finds values to insert.
2506 if (ticks.length == 0) {
ff022deb
RK
2507 // Basic idea:
2508 // Try labels every 1, 2, 5, 10, 20, 50, 100, etc.
2509 // Calculate the resulting tick spacing (i.e. this.height_ / nTicks).
2510 // The first spacing greater than pixelsPerYLabel is what we use.
2511 // TODO(danvk): version that works on a log scale.
0d64e596 2512 if (attr("labelsKMG2")) {
ff022deb 2513 var mults = [1, 2, 4, 8];
0d64e596 2514 } else {
ff022deb 2515 var mults = [1, 2, 5];
0d64e596 2516 }
ff022deb
RK
2517 var scale, low_val, high_val, nTicks;
2518 // TODO(danvk): make it possible to set this for x- and y-axes independently.
2519 var pixelsPerTick = attr('pixelsPerYLabel');
2520 for (var i = -10; i < 50; i++) {
2521 if (attr("labelsKMG2")) {
2522 var base_scale = Math.pow(16, i);
2523 } else {
2524 var base_scale = Math.pow(10, i);
2525 }
2526 for (var j = 0; j < mults.length; j++) {
2527 scale = base_scale * mults[j];
2528 low_val = Math.floor(minV / scale) * scale;
2529 high_val = Math.ceil(maxV / scale) * scale;
2530 nTicks = Math.abs(high_val - low_val) / scale;
2531 var spacing = self.height_ / nTicks;
2532 // wish I could break out of both loops at once...
2533 if (spacing > pixelsPerTick) break;
2534 }
0d64e596
DV
2535 if (spacing > pixelsPerTick) break;
2536 }
0d64e596 2537
ff022deb
RK
2538 // Construct the set of ticks.
2539 // Allow reverse y-axis if it's explicitly requested.
2540 if (low_val > high_val) scale *= -1;
2541 for (var i = 0; i < nTicks; i++) {
2542 var tickV = low_val + i * scale;
2543 ticks.push( {v: tickV} );
2544 }
0d64e596 2545 }
6a1aa64f
DV
2546 }
2547
0d64e596 2548 // Add formatted labels to the ticks.
ed11be50
DV
2549 var k;
2550 var k_labels = [];
f09fc545 2551 if (attr("labelsKMB")) {
ed11be50
DV
2552 k = 1000;
2553 k_labels = [ "K", "M", "B", "T" ];
2554 }
f09fc545 2555 if (attr("labelsKMG2")) {
ed11be50
DV
2556 if (k) self.warn("Setting both labelsKMB and labelsKMG2. Pick one!");
2557 k = 1024;
2558 k_labels = [ "k", "M", "G", "T" ];
2559 }
3c1d225b
JB
2560 var formatter = attr('yAxisLabelFormatter') ?
2561 attr('yAxisLabelFormatter') : attr('yValueFormatter');
2562
0cfa06d1 2563 // Add labels to the ticks.
0d64e596 2564 for (var i = 0; i < ticks.length; i++) {
e863a17d 2565 if (ticks[i].label !== undefined) continue; // Use current label.
0d64e596 2566 var tickV = ticks[i].v;
0af6e346 2567 var absTickV = Math.abs(tickV);
2e1fcf1a 2568 var label = formatter(tickV, self);
3c1d225b 2569 if (k_labels.length > 0) {
ed11be50
DV
2570 // Round up to an appropriate unit.
2571 var n = k*k*k*k;
2572 for (var j = 3; j >= 0; j--, n /= k) {
2573 if (absTickV >= n) {
17d0210c 2574 label = Dygraph.round_(tickV / n, attr('digitsAfterDecimal')) + k_labels[j];
ed11be50
DV
2575 break;
2576 }
afefbcdb 2577 }
6a1aa64f 2578 }
d916677a 2579 ticks[i].label = label;
6a1aa64f 2580 }
d916677a 2581
032e4c1d 2582 return ticks;
6a1aa64f
DV
2583};
2584
629a09ae
DV
2585/**
2586 * @private
2587 * Computes the range of the data series (including confidence intervals).
2588 * @param { [Array] } series either [ [x1, y1], [x2, y2], ... ] or
2589 * [ [x1, [y1, dev_low, dev_high]], [x2, [y2, dev_low, dev_high]], ...
2590 * @return [low, high]
2591 */
5011e7a1
DV
2592Dygraph.prototype.extremeValues_ = function(series) {
2593 var minY = null, maxY = null;
2594
9922b78b 2595 var bars = this.attr_("errorBars") || this.attr_("customBars");
5011e7a1
DV
2596 if (bars) {
2597 // With custom bars, maxY is the max of the high values.
2598 for (var j = 0; j < series.length; j++) {
2599 var y = series[j][1][0];
2600 if (!y) continue;
2601 var low = y - series[j][1][1];
2602 var high = y + series[j][1][2];
2603 if (low > y) low = y; // this can happen with custom bars,
2604 if (high < y) high = y; // e.g. in tests/custom-bars.html
2605 if (maxY == null || high > maxY) {
2606 maxY = high;
2607 }
2608 if (minY == null || low < minY) {
2609 minY = low;
2610 }
2611 }
2612 } else {
2613 for (var j = 0; j < series.length; j++) {
2614 var y = series[j][1];
d12999d3 2615 if (y === null || isNaN(y)) continue;
5011e7a1
DV
2616 if (maxY == null || y > maxY) {
2617 maxY = y;
2618 }
2619 if (minY == null || y < minY) {
2620 minY = y;
2621 }
2622 }
2623 }
2624
2625 return [minY, maxY];
2626};
2627
6a1aa64f 2628/**
629a09ae 2629 * @private
26ca7938
DV
2630 * This function is called once when the chart's data is changed or the options
2631 * dictionary is updated. It is _not_ called when the user pans or zooms. The
2632 * idea is that values derived from the chart's data can be computed here,
2633 * rather than every time the chart is drawn. This includes things like the
2634 * number of axes, rolling averages, etc.
2635 */
2636Dygraph.prototype.predraw_ = function() {
2637 // TODO(danvk): move more computations out of drawGraph_ and into here.
2638 this.computeYAxes_();
2639
2640 // Create a new plotter.
70c80071 2641 if (this.plotter_) this.plotter_.clear();
26ca7938 2642 this.plotter_ = new DygraphCanvasRenderer(this,
2cf95fff
RK
2643 this.hidden_,
2644 this.hidden_ctx_,
0e23cfc6 2645 this.layout_);
26ca7938 2646
0abfbd7e
DV
2647 // The roller sits in the bottom left corner of the chart. We don't know where
2648 // this will be until the options are available, so it's positioned here.
8c69de65 2649 this.createRollInterface_();
26ca7938 2650
0abfbd7e
DV
2651 // Same thing applies for the labelsDiv. It's right edge should be flush with
2652 // the right edge of the charting area (which may not be the same as the right
2653 // edge of the div, if we have two y-axes.
2654 this.positionLabelsDiv_();
2655
26ca7938
DV
2656 // If the data or options have changed, then we'd better redraw.
2657 this.drawGraph_();
2658};
2659
2660/**
2661 * Update the graph with new data. This method is called when the viewing area
2662 * has changed. If the underlying data or options have changed, predraw_ will
2663 * be called before drawGraph_ is called.
6a1aa64f
DV
2664 * @private
2665 */
26ca7938
DV
2666Dygraph.prototype.drawGraph_ = function() {
2667 var data = this.rawData_;
2668
fe0b7c03
DV
2669 // This is used to set the second parameter to drawCallback, below.
2670 var is_initial_draw = this.is_initial_draw_;
2671 this.is_initial_draw_ = false;
2672
3bd9c228 2673 var minY = null, maxY = null;
6a1aa64f 2674 this.layout_.removeAllDatasets();
285a6bda 2675 this.setColors_();
9317362d 2676 this.attrs_['pointSize'] = 0.5 * this.attr_('highlightCircleSize');
285a6bda 2677
354e15ab
DE
2678 // Loop over the fields (series). Go from the last to the first,
2679 // because if they're stacked that's how we accumulate the values.
43af96e7 2680
354e15ab
DE
2681 var cumulative_y = []; // For stacked series.
2682 var datasets = [];
2683
f09fc545
DV
2684 var extremes = {}; // series name -> [low, high]
2685
354e15ab
DE
2686 // Loop over all fields and create datasets
2687 for (var i = data[0].length - 1; i >= 1; i--) {
1cf11047
DV
2688 if (!this.visibility()[i - 1]) continue;
2689
f09fc545 2690 var seriesName = this.attr_("labels")[i];
450fe64b 2691 var connectSeparatedPoints = this.attr_('connectSeparatedPoints', i);
6e6a2b0a 2692 var logScale = this.attr_('logscale', i);
450fe64b 2693
6a1aa64f
DV
2694 var series = [];
2695 for (var j = 0; j < data.length; j++) {
6e6a2b0a
RK
2696 var date = data[j][0];
2697 var point = data[j][i];
2698 if (logScale) {
2699 // On the log scale, points less than zero do not exist.
2700 // This will create a gap in the chart. Note that this ignores
2701 // connectSeparatedPoints.
e863a17d 2702 if (point <= 0) {
6e6a2b0a
RK
2703 point = null;
2704 }
2705 series.push([date, point]);
2706 } else {
2707 if (point != null || !connectSeparatedPoints) {
2708 series.push([date, point]);
2709 }
f032c51d 2710 }
6a1aa64f 2711 }
2f5e7e1a
DV
2712
2713 // TODO(danvk): move this into predraw_. It's insane to do it here.
6a1aa64f
DV
2714 series = this.rollingAverage(series, this.rollPeriod_);
2715
2716 // Prune down to the desired range, if necessary (for zooming)
1a26f3fb
DV
2717 // Because there can be lines going to points outside of the visible area,
2718 // we actually prune to visible points, plus one on either side.
9922b78b 2719 var bars = this.attr_("errorBars") || this.attr_("customBars");
6a1aa64f
DV
2720 if (this.dateWindow_) {
2721 var low = this.dateWindow_[0];
2722 var high= this.dateWindow_[1];
2723 var pruned = [];
1a26f3fb
DV
2724 // TODO(danvk): do binary search instead of linear search.
2725 // TODO(danvk): pass firstIdx and lastIdx directly to the renderer.
2726 var firstIdx = null, lastIdx = null;
6a1aa64f 2727 for (var k = 0; k < series.length; k++) {
1a26f3fb
DV
2728 if (series[k][0] >= low && firstIdx === null) {
2729 firstIdx = k;
2730 }
2731 if (series[k][0] <= high) {
2732 lastIdx = k;
6a1aa64f
DV
2733 }
2734 }
1a26f3fb
DV
2735 if (firstIdx === null) firstIdx = 0;
2736 if (firstIdx > 0) firstIdx--;
2737 if (lastIdx === null) lastIdx = series.length - 1;
2738 if (lastIdx < series.length - 1) lastIdx++;
16269f6e 2739 this.boundaryIds_[i-1] = [firstIdx, lastIdx];
1a26f3fb
DV
2740 for (var k = firstIdx; k <= lastIdx; k++) {
2741 pruned.push(series[k]);
6a1aa64f
DV
2742 }
2743 series = pruned;
16269f6e
NAG
2744 } else {
2745 this.boundaryIds_[i-1] = [0, series.length-1];
6a1aa64f
DV
2746 }
2747
f09fc545 2748 var seriesExtremes = this.extremeValues_(series);
5011e7a1 2749
6a1aa64f 2750 if (bars) {
354e15ab
DE
2751 for (var j=0; j<series.length; j++) {
2752 val = [series[j][0], series[j][1][0], series[j][1][1], series[j][1][2]];
2753 series[j] = val;
2754 }
43af96e7 2755 } else if (this.attr_("stackedGraph")) {
43af96e7
NK
2756 var l = series.length;
2757 var actual_y;
2758 for (var j = 0; j < l; j++) {
354e15ab
DE
2759 // If one data set has a NaN, let all subsequent stacked
2760 // sets inherit the NaN -- only start at 0 for the first set.
2761 var x = series[j][0];
41b0f691 2762 if (cumulative_y[x] === undefined) {
354e15ab 2763 cumulative_y[x] = 0;
41b0f691 2764 }
43af96e7
NK
2765
2766 actual_y = series[j][1];
354e15ab 2767 cumulative_y[x] += actual_y;
43af96e7 2768
354e15ab 2769 series[j] = [x, cumulative_y[x]]
43af96e7 2770
41b0f691
DV
2771 if (cumulative_y[x] > seriesExtremes[1]) {
2772 seriesExtremes[1] = cumulative_y[x];
2773 }
2774 if (cumulative_y[x] < seriesExtremes[0]) {
2775 seriesExtremes[0] = cumulative_y[x];
2776 }
43af96e7 2777 }
6a1aa64f 2778 }
41b0f691 2779 extremes[seriesName] = seriesExtremes;
354e15ab
DE
2780
2781 datasets[i] = series;
6a1aa64f
DV
2782 }
2783
354e15ab 2784 for (var i = 1; i < datasets.length; i++) {
4523c1f6 2785 if (!this.visibility()[i - 1]) continue;
354e15ab 2786 this.layout_.addDataset(this.attr_("labels")[i], datasets[i]);
43af96e7
NK
2787 }
2788
6faebb69 2789 this.computeYAxisRanges_(extremes);
b2c9222a
DV
2790 this.layout_.setYAxes(this.axes_);
2791
6a1aa64f
DV
2792 this.addXTicks_();
2793
b2c9222a 2794 // Save the X axis zoomed status as the updateOptions call will tend to set it erroneously
81856f70 2795 var tmp_zoomed_x = this.zoomed_x_;
6a1aa64f 2796 // Tell PlotKit to use this new data and render itself
b2c9222a 2797 this.layout_.setDateWindow(this.dateWindow_);
81856f70 2798 this.zoomed_x_ = tmp_zoomed_x;
6a1aa64f
DV
2799 this.layout_.evaluateWithError();
2800 this.plotter_.clear();
2801 this.plotter_.render();
f6401bf6 2802 this.canvas_.getContext('2d').clearRect(0, 0, this.canvas_.width,
2f5e7e1a 2803 this.canvas_.height);
599fb4ad 2804
2fccd3dc
DV
2805 if (is_initial_draw) {
2806 // Generate a static legend before any particular point is selected.
91c10d9c 2807 this.setLegendHTML_();
06303c32
DV
2808 } else {
2809 if (typeof(this.selPoints_) !== 'undefined' && this.selPoints_.length) {
da1369a5
DV
2810 // We should select the point nearest the page x/y here, but it's easier
2811 // to just clear the selection. This prevents erroneous hover dots from
2812 // being displayed.
2813 this.clearSelection();
06303c32
DV
2814 } else {
2815 this.clearSelection();
2816 }
2fccd3dc
DV
2817 }
2818
599fb4ad 2819 if (this.attr_("drawCallback") !== null) {
fe0b7c03 2820 this.attr_("drawCallback")(this, is_initial_draw);
599fb4ad 2821 }
6a1aa64f
DV
2822};
2823
2824/**
629a09ae 2825 * @private
26ca7938
DV
2826 * Determine properties of the y-axes which are independent of the data
2827 * currently being displayed. This includes things like the number of axes and
2828 * the style of the axes. It does not include the range of each axis and its
2829 * tick marks.
2830 * This fills in this.axes_ and this.seriesToAxisMap_.
2831 * axes_ = [ { options } ]
2832 * seriesToAxisMap_ = { seriesName: 0, seriesName2: 1, ... }
2833 * indices are into the axes_ array.
f09fc545 2834 */
26ca7938 2835Dygraph.prototype.computeYAxes_ = function() {
00aa7f61 2836 this.axes_ = [{ yAxisId : 0, g : this }]; // always have at least one y-axis.
26ca7938
DV
2837 this.seriesToAxisMap_ = {};
2838
2839 // Get a list of series names.
2840 var labels = this.attr_("labels");
1c77a3a1 2841 var series = {};
26ca7938 2842 for (var i = 1; i < labels.length; i++) series[labels[i]] = (i - 1);
f09fc545
DV
2843
2844 // all options which could be applied per-axis:
2845 var axisOptions = [
2846 'includeZero',
2847 'valueRange',
2848 'labelsKMB',
2849 'labelsKMG2',
2850 'pixelsPerYLabel',
2851 'yAxisLabelWidth',
2852 'axisLabelFontSize',
7d0e7a0d
RK
2853 'axisTickSize',
2854 'logscale'
f09fc545
DV
2855 ];
2856
2857 // Copy global axis options over to the first axis.
2858 for (var i = 0; i < axisOptions.length; i++) {
2859 var k = axisOptions[i];
2860 var v = this.attr_(k);
26ca7938 2861 if (v) this.axes_[0][k] = v;
f09fc545
DV
2862 }
2863
2864 // Go through once and add all the axes.
26ca7938
DV
2865 for (var seriesName in series) {
2866 if (!series.hasOwnProperty(seriesName)) continue;
f09fc545
DV
2867 var axis = this.attr_("axis", seriesName);
2868 if (axis == null) {
26ca7938 2869 this.seriesToAxisMap_[seriesName] = 0;
f09fc545
DV
2870 continue;
2871 }
2872 if (typeof(axis) == 'object') {
2873 // Add a new axis, making a copy of its per-axis options.
2874 var opts = {};
26ca7938 2875 Dygraph.update(opts, this.axes_[0]);
f09fc545 2876 Dygraph.update(opts, { valueRange: null }); // shouldn't inherit this.
00aa7f61
RK
2877 var yAxisId = this.axes_.length;
2878 opts.yAxisId = yAxisId;
2879 opts.g = this;
f09fc545 2880 Dygraph.update(opts, axis);
26ca7938 2881 this.axes_.push(opts);
00aa7f61 2882 this.seriesToAxisMap_[seriesName] = yAxisId;
f09fc545
DV
2883 }
2884 }
2885
2886 // Go through one more time and assign series to an axis defined by another
2887 // series, e.g. { 'Y1: { axis: {} }, 'Y2': { axis: 'Y1' } }
26ca7938
DV
2888 for (var seriesName in series) {
2889 if (!series.hasOwnProperty(seriesName)) continue;
f09fc545
DV
2890 var axis = this.attr_("axis", seriesName);
2891 if (typeof(axis) == 'string') {
26ca7938 2892 if (!this.seriesToAxisMap_.hasOwnProperty(axis)) {
f09fc545
DV
2893 this.error("Series " + seriesName + " wants to share a y-axis with " +
2894 "series " + axis + ", which does not define its own axis.");
2895 return null;
2896 }
26ca7938
DV
2897 var idx = this.seriesToAxisMap_[axis];
2898 this.seriesToAxisMap_[seriesName] = idx;
f09fc545
DV
2899 }
2900 }
1c77a3a1
DV
2901
2902 // Now we remove series from seriesToAxisMap_ which are not visible. We do
2903 // this last so that hiding the first series doesn't destroy the axis
2904 // properties of the primary axis.
2905 var seriesToAxisFiltered = {};
2906 var vis = this.visibility();
2907 for (var i = 1; i < labels.length; i++) {
2908 var s = labels[i];
2909 if (vis[i - 1]) seriesToAxisFiltered[s] = this.seriesToAxisMap_[s];
2910 }
2911 this.seriesToAxisMap_ = seriesToAxisFiltered;
26ca7938
DV
2912};
2913
2914/**
2915 * Returns the number of y-axes on the chart.
2916 * @return {Number} the number of axes.
2917 */
2918Dygraph.prototype.numAxes = function() {
2919 var last_axis = 0;
2920 for (var series in this.seriesToAxisMap_) {
2921 if (!this.seriesToAxisMap_.hasOwnProperty(series)) continue;
2922 var idx = this.seriesToAxisMap_[series];
2923 if (idx > last_axis) last_axis = idx;
2924 }
2925 return 1 + last_axis;
2926};
2927
2928/**
629a09ae 2929 * @private
b2c9222a
DV
2930 * Returns axis properties for the given series.
2931 * @param { String } setName The name of the series for which to get axis
2932 * properties, e.g. 'Y1'.
2933 * @return { Object } The axis properties.
2934 */
2935Dygraph.prototype.axisPropertiesForSeries = function(series) {
2936 // TODO(danvk): handle errors.
2937 return this.axes_[this.seriesToAxisMap_[series]];
2938};
2939
2940/**
2941 * @private
26ca7938
DV
2942 * Determine the value range and tick marks for each axis.
2943 * @param {Object} extremes A mapping from seriesName -> [low, high]
2944 * This fills in the valueRange and ticks fields in each entry of this.axes_.
2945 */
2946Dygraph.prototype.computeYAxisRanges_ = function(extremes) {
2947 // Build a map from axis number -> [list of series names]
2948 var seriesForAxis = [];
2949 for (var series in this.seriesToAxisMap_) {
2950 if (!this.seriesToAxisMap_.hasOwnProperty(series)) continue;
2951 var idx = this.seriesToAxisMap_[series];
2952 while (seriesForAxis.length <= idx) seriesForAxis.push([]);
2953 seriesForAxis[idx].push(series);
2954 }
f09fc545
DV
2955
2956 // Compute extreme values, a span and tick marks for each axis.
26ca7938
DV
2957 for (var i = 0; i < this.axes_.length; i++) {
2958 var axis = this.axes_[i];
4cac8c7a 2959
06fc69b6
AV
2960 if (!seriesForAxis[i]) {
2961 // If no series are defined or visible then use a reasonable default
2962 axis.extremeRange = [0, 1];
2963 } else {
1c77a3a1 2964 // Calculate the extremes of extremes.
f09fc545
DV
2965 var series = seriesForAxis[i];
2966 var minY = Infinity; // extremes[series[0]][0];
2967 var maxY = -Infinity; // extremes[series[0]][1];
ba049b89 2968 var extremeMinY, extremeMaxY;
f09fc545 2969 for (var j = 0; j < series.length; j++) {
ba049b89
NN
2970 // Only use valid extremes to stop null data series' from corrupting the scale.
2971 extremeMinY = extremes[series[j]][0];
2972 if (extremeMinY != null) {
36dfa958 2973 minY = Math.min(extremeMinY, minY);
ba049b89
NN
2974 }
2975 extremeMaxY = extremes[series[j]][1];
2976 if (extremeMaxY != null) {
36dfa958 2977 maxY = Math.max(extremeMaxY, maxY);
ba049b89 2978 }
f09fc545
DV
2979 }
2980 if (axis.includeZero && minY > 0) minY = 0;
2981
ba049b89 2982 // Ensure we have a valid scale, otherwise defualt to zero for safety.
36dfa958
DV
2983 if (minY == Infinity) minY = 0;
2984 if (maxY == -Infinity) maxY = 0;
ba049b89 2985
f09fc545
DV
2986 // Add some padding and round up to an integer to be human-friendly.
2987 var span = maxY - minY;
2988 // special case: if we have no sense of scale, use +/-10% of the sole value.
2989 if (span == 0) { span = maxY; }
f09fc545 2990
ff022deb
RK
2991 var maxAxisY;
2992 var minAxisY;
7d0e7a0d 2993 if (axis.logscale) {
ff022deb
RK
2994 var maxAxisY = maxY + 0.1 * span;
2995 var minAxisY = minY;
2996 } else {
2997 var maxAxisY = maxY + 0.1 * span;
2998 var minAxisY = minY - 0.1 * span;
f09fc545 2999
ff022deb
RK
3000 // Try to include zero and make it minAxisY (or maxAxisY) if it makes sense.
3001 if (!this.attr_("avoidMinZero")) {
3002 if (minAxisY < 0 && minY >= 0) minAxisY = 0;
3003 if (maxAxisY > 0 && maxY <= 0) maxAxisY = 0;
3004 }
f09fc545 3005
ff022deb
RK
3006 if (this.attr_("includeZero")) {
3007 if (maxY < 0) maxAxisY = 0;
3008 if (minY > 0) minAxisY = 0;
3009 }
f09fc545 3010 }
4cac8c7a
RK
3011 axis.extremeRange = [minAxisY, maxAxisY];
3012 }
3013 if (axis.valueWindow) {
3014 // This is only set if the user has zoomed on the y-axis. It is never set
3015 // by a user. It takes precedence over axis.valueRange because, if you set
3016 // valueRange, you'd still expect to be able to pan.
3017 axis.computedValueRange = [axis.valueWindow[0], axis.valueWindow[1]];
3018 } else if (axis.valueRange) {
3019 // This is a user-set value range for this axis.
3020 axis.computedValueRange = [axis.valueRange[0], axis.valueRange[1]];
3021 } else {
3022 axis.computedValueRange = axis.extremeRange;
f09fc545
DV
3023 }
3024
0d64e596
DV
3025 // Add ticks. By default, all axes inherit the tick positions of the
3026 // primary axis. However, if an axis is specifically marked as having
3027 // independent ticks, then that is permissible as well.
3028 if (i == 0 || axis.independentTicks) {
032e4c1d 3029 axis.ticks =
0d64e596
DV
3030 Dygraph.numericTicks(axis.computedValueRange[0],
3031 axis.computedValueRange[1],
3032 this,
3033 axis);
3034 } else {
3035 var p_axis = this.axes_[0];
3036 var p_ticks = p_axis.ticks;
3037 var p_scale = p_axis.computedValueRange[1] - p_axis.computedValueRange[0];
3038 var scale = axis.computedValueRange[1] - axis.computedValueRange[0];
3039 var tick_values = [];
3040 for (var i = 0; i < p_ticks.length; i++) {
3041 var y_frac = (p_ticks[i].v - p_axis.computedValueRange[0]) / p_scale;
3042 var y_val = axis.computedValueRange[0] + y_frac * scale;
3043 tick_values.push(y_val);
3044 }
3045
032e4c1d 3046 axis.ticks =
0d64e596
DV
3047 Dygraph.numericTicks(axis.computedValueRange[0],
3048 axis.computedValueRange[1],
3049 this, axis, tick_values);
3050 }
f09fc545 3051 }
f09fc545
DV
3052};
3053
3054/**
629a09ae 3055 * @private
6a1aa64f
DV
3056 * Calculates the rolling average of a data set.
3057 * If originalData is [label, val], rolls the average of those.
3058 * If originalData is [label, [, it's interpreted as [value, stddev]
3059 * and the roll is returned in the same form, with appropriately reduced
3060 * stddev for each value.
3061 * Note that this is where fractional input (i.e. '5/10') is converted into
3062 * decimal values.
3063 * @param {Array} originalData The data in the appropriate format (see above)
6faebb69
JB
3064 * @param {Number} rollPeriod The number of points over which to average the
3065 * data
6a1aa64f 3066 */
285a6bda 3067Dygraph.prototype.rollingAverage = function(originalData, rollPeriod) {
6a1aa64f
DV
3068 if (originalData.length < 2)
3069 return originalData;
3070 var rollPeriod = Math.min(rollPeriod, originalData.length - 1);
3071 var rollingData = [];
285a6bda 3072 var sigma = this.attr_("sigma");
6a1aa64f
DV
3073
3074 if (this.fractions_) {
3075 var num = 0;
3076 var den = 0; // numerator/denominator
3077 var mult = 100.0;
3078 for (var i = 0; i < originalData.length; i++) {
3079 num += originalData[i][1][0];
3080 den += originalData[i][1][1];
3081 if (i - rollPeriod >= 0) {
3082 num -= originalData[i - rollPeriod][1][0];
3083 den -= originalData[i - rollPeriod][1][1];
3084 }
3085
3086 var date = originalData[i][0];
3087 var value = den ? num / den : 0.0;
285a6bda 3088 if (this.attr_("errorBars")) {
6a1aa64f
DV
3089 if (this.wilsonInterval_) {
3090 // For more details on this confidence interval, see:
3091 // http://en.wikipedia.org/wiki/Binomial_confidence_interval
3092 if (den) {
3093 var p = value < 0 ? 0 : value, n = den;
3094 var pm = sigma * Math.sqrt(p*(1-p)/n + sigma*sigma/(4*n*n));
3095 var denom = 1 + sigma * sigma / den;
3096 var low = (p + sigma * sigma / (2 * den) - pm) / denom;
3097 var high = (p + sigma * sigma / (2 * den) + pm) / denom;
3098 rollingData[i] = [date,
3099 [p * mult, (p - low) * mult, (high - p) * mult]];
3100 } else {
3101 rollingData[i] = [date, [0, 0, 0]];
3102 }
3103 } else {
3104 var stddev = den ? sigma * Math.sqrt(value * (1 - value) / den) : 1.0;
3105 rollingData[i] = [date, [mult * value, mult * stddev, mult * stddev]];
3106 }
3107 } else {
3108 rollingData[i] = [date, mult * value];
3109 }
3110 }
9922b78b 3111 } else if (this.attr_("customBars")) {
f6885d6a
DV
3112 var low = 0;
3113 var mid = 0;
3114 var high = 0;
3115 var count = 0;
6a1aa64f
DV
3116 for (var i = 0; i < originalData.length; i++) {
3117 var data = originalData[i][1];
3118 var y = data[1];
3119 rollingData[i] = [originalData[i][0], [y, y - data[0], data[2] - y]];
f6885d6a 3120
8b91c51f 3121 if (y != null && !isNaN(y)) {
49a7d0d5
DV
3122 low += data[0];
3123 mid += y;
3124 high += data[2];
3125 count += 1;
3126 }
f6885d6a
DV
3127 if (i - rollPeriod >= 0) {
3128 var prev = originalData[i - rollPeriod];
8b91c51f 3129 if (prev[1][1] != null && !isNaN(prev[1][1])) {
49a7d0d5
DV
3130 low -= prev[1][0];
3131 mid -= prev[1][1];
3132 high -= prev[1][2];
3133 count -= 1;
3134 }
f6885d6a
DV
3135 }
3136 rollingData[i] = [originalData[i][0], [ 1.0 * mid / count,
3137 1.0 * (mid - low) / count,
3138 1.0 * (high - mid) / count ]];
2769de62 3139 }
6a1aa64f
DV
3140 } else {
3141 // Calculate the rolling average for the first rollPeriod - 1 points where
6faebb69 3142 // there is not enough data to roll over the full number of points
6a1aa64f 3143 var num_init_points = Math.min(rollPeriod - 1, originalData.length - 2);
285a6bda 3144 if (!this.attr_("errorBars")){
5011e7a1
DV
3145 if (rollPeriod == 1) {
3146 return originalData;
3147 }
3148
2847c1cf 3149 for (var i = 0; i < originalData.length; i++) {
6a1aa64f 3150 var sum = 0;
5011e7a1 3151 var num_ok = 0;
2847c1cf
DV
3152 for (var j = Math.max(0, i - rollPeriod + 1); j < i + 1; j++) {
3153 var y = originalData[j][1];
8b91c51f 3154 if (y == null || isNaN(y)) continue;
5011e7a1 3155 num_ok++;
2847c1cf 3156 sum += originalData[j][1];
6a1aa64f 3157 }
5011e7a1 3158 if (num_ok) {
2847c1cf 3159 rollingData[i] = [originalData[i][0], sum / num_ok];
5011e7a1 3160 } else {
2847c1cf 3161 rollingData[i] = [originalData[i][0], null];
5011e7a1 3162 }
6a1aa64f 3163 }
2847c1cf
DV
3164
3165 } else {
3166 for (var i = 0; i < originalData.length; i++) {
6a1aa64f
DV
3167 var sum = 0;
3168 var variance = 0;
5011e7a1 3169 var num_ok = 0;
2847c1cf 3170 for (var j = Math.max(0, i - rollPeriod + 1); j < i + 1; j++) {
5011e7a1 3171 var y = originalData[j][1][0];
8b91c51f 3172 if (y == null || isNaN(y)) continue;
5011e7a1 3173 num_ok++;
6a1aa64f
DV
3174 sum += originalData[j][1][0];
3175 variance += Math.pow(originalData[j][1][1], 2);
3176 }
5011e7a1
DV
3177 if (num_ok) {
3178 var stddev = Math.sqrt(variance) / num_ok;
3179 rollingData[i] = [originalData[i][0],
3180 [sum / num_ok, sigma * stddev, sigma * stddev]];
3181 } else {
3182 rollingData[i] = [originalData[i][0], [null, null, null]];
3183 }
6a1aa64f
DV
3184 }
3185 }
3186 }
3187
3188 return rollingData;
3189};
3190
3191/**
629a09ae 3192 * @private
6a1aa64f 3193 * Parses a date, returning the number of milliseconds since epoch. This can be
285a6bda
DV
3194 * passed in as an xValueParser in the Dygraph constructor.
3195 * TODO(danvk): enumerate formats that this understands.
6a1aa64f
DV
3196 * @param {String} A date in YYYYMMDD format.
3197 * @return {Number} Milliseconds since epoch.
6a1aa64f 3198 */
285a6bda 3199Dygraph.dateParser = function(dateStr, self) {
6a1aa64f 3200 var dateStrSlashed;
285a6bda 3201 var d;
986a5026 3202 if (dateStr.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12'
6a1aa64f 3203 dateStrSlashed = dateStr.replace("-", "/", "g");
353a0294
DV
3204 while (dateStrSlashed.search("-") != -1) {
3205 dateStrSlashed = dateStrSlashed.replace("-", "/");
3206 }
d96b7d1a 3207 d = Dygraph.dateStrToMillis(dateStrSlashed);
2769de62 3208 } else if (dateStr.length == 8) { // e.g. '20090712'
285a6bda 3209 // TODO(danvk): remove support for this format. It's confusing.
6a1aa64f
DV
3210 dateStrSlashed = dateStr.substr(0,4) + "/" + dateStr.substr(4,2)
3211 + "/" + dateStr.substr(6,2);
d96b7d1a 3212 d = Dygraph.dateStrToMillis(dateStrSlashed);
2769de62
DV
3213 } else {
3214 // Any format that Date.parse will accept, e.g. "2009/07/12" or
3215 // "2009/07/12 12:34:56"
d96b7d1a 3216 d = Dygraph.dateStrToMillis(dateStr);
285a6bda
DV
3217 }
3218
3219 if (!d || isNaN(d)) {
3220 self.error("Couldn't parse " + dateStr + " as a date");
3221 }
3222 return d;
3223};
3224
3225/**
3226 * Detects the type of the str (date or numeric) and sets the various
3227 * formatting attributes in this.attrs_ based on this type.
3228 * @param {String} str An x value.
3229 * @private
3230 */
3231Dygraph.prototype.detectTypeFromString_ = function(str) {
3232 var isDate = false;
ea62df82 3233 if (str.indexOf('-') > 0 ||
285a6bda
DV
3234 str.indexOf('/') >= 0 ||
3235 isNaN(parseFloat(str))) {
3236 isDate = true;
3237 } else if (str.length == 8 && str > '19700101' && str < '20371231') {
3238 // TODO(danvk): remove support for this format.
3239 isDate = true;
3240 }
3241
3242 if (isDate) {
3243 this.attrs_.xValueFormatter = Dygraph.dateString_;
3244 this.attrs_.xValueParser = Dygraph.dateParser;
3245 this.attrs_.xTicker = Dygraph.dateTicker;
bf640e56 3246 this.attrs_.xAxisLabelFormatter = Dygraph.dateAxisFormatter;
285a6bda 3247 } else {
17d0210c 3248 // TODO(danvk): use Dygraph.numberFormatter here?
c39e1d93 3249 /** @private (shut up, jsdoc!) */
032e4c1d 3250 this.attrs_.xValueFormatter = function(x) { return x; };
c39e1d93 3251 /** @private (shut up, jsdoc!) */
285a6bda
DV
3252 this.attrs_.xValueParser = function(x) { return parseFloat(x); };
3253 this.attrs_.xTicker = Dygraph.numericTicks;
bf640e56 3254 this.attrs_.xAxisLabelFormatter = this.attrs_.xValueFormatter;
6a1aa64f 3255 }
6a1aa64f
DV
3256};
3257
3258/**
5cd7ac68
DV
3259 * Parses the value as a floating point number. This is like the parseFloat()
3260 * built-in, but with a few differences:
3261 * - the empty string is parsed as null, rather than NaN.
3262 * - if the string cannot be parsed at all, an error is logged.
3263 * If the string can't be parsed, this method returns null.
3264 * @param {String} x The string to be parsed
3265 * @param {Number} opt_line_no The line number from which the string comes.
3266 * @param {String} opt_line The text of the line from which the string comes.
3267 * @private
3268 */
3269
3270// Parse the x as a float or return null if it's not a number.
3271Dygraph.prototype.parseFloat_ = function(x, opt_line_no, opt_line) {
3272 var val = parseFloat(x);
3273 if (!isNaN(val)) return val;
3274
3275 // Try to figure out what happeend.
3276 // If the value is the empty string, parse it as null.
3277 if (/^ *$/.test(x)) return null;
3278
3279 // If it was actually "NaN", return it as NaN.
3280 if (/^ *nan *$/i.test(x)) return NaN;
3281
3282 // Looks like a parsing error.
3283 var msg = "Unable to parse '" + x + "' as a number";
3284 if (opt_line !== null && opt_line_no !== null) {
3285 msg += " on line " + (1+opt_line_no) + " ('" + opt_line + "') of CSV.";
3286 }
3287 this.error(msg);
3288
3289 return null;
3290};
3291
3292/**
629a09ae 3293 * @private
6a1aa64f
DV
3294 * Parses a string in a special csv format. We expect a csv file where each
3295 * line is a date point, and the first field in each line is the date string.
3296 * We also expect that all remaining fields represent series.
285a6bda 3297 * if the errorBars attribute is set, then interpret the fields as:
6a1aa64f 3298 * date, series1, stddev1, series2, stddev2, ...
629a09ae 3299 * @param {[Object]} data See above.
285a6bda 3300 *
629a09ae 3301 * @return [Object] An array with one entry for each row. These entries
285a6bda
DV
3302 * are an array of cells in that row. The first entry is the parsed x-value for
3303 * the row. The second, third, etc. are the y-values. These can take on one of
3304 * three forms, depending on the CSV and constructor parameters:
3305 * 1. numeric value
3306 * 2. [ value, stddev ]
3307 * 3. [ low value, center value, high value ]
6a1aa64f 3308 */
285a6bda 3309Dygraph.prototype.parseCSV_ = function(data) {
6a1aa64f
DV
3310 var ret = [];
3311 var lines = data.split("\n");
3d67f03b
DV
3312
3313 // Use the default delimiter or fall back to a tab if that makes sense.
3314 var delim = this.attr_('delimiter');
3315 if (lines[0].indexOf(delim) == -1 && lines[0].indexOf('\t') >= 0) {
3316 delim = '\t';
3317 }
3318
285a6bda 3319 var start = 0;
d7beab6b
DV
3320 if (!('labels' in this.user_attrs_)) {
3321 // User hasn't explicitly set labels, so they're (presumably) in the CSV.
285a6bda 3322 start = 1;
d7beab6b 3323 this.attrs_.labels = lines[0].split(delim); // NOTE: _not_ user_attrs_.
6a1aa64f 3324 }
5cd7ac68 3325 var line_no = 0;
03b522a4 3326
285a6bda
DV
3327 var xParser;
3328 var defaultParserSet = false; // attempt to auto-detect x value type
3329 var expectedCols = this.attr_("labels").length;
987840a2 3330 var outOfOrder = false;
6a1aa64f
DV
3331 for (var i = start; i < lines.length; i++) {
3332 var line = lines[i];
5cd7ac68 3333 line_no = i;
6a1aa64f 3334 if (line.length == 0) continue; // skip blank lines
3d67f03b
DV
3335 if (line[0] == '#') continue; // skip comment lines
3336 var inFields = line.split(delim);
285a6bda 3337 if (inFields.length < 2) continue;
6a1aa64f
DV
3338
3339 var fields = [];
285a6bda
DV
3340 if (!defaultParserSet) {
3341 this.detectTypeFromString_(inFields[0]);
3342 xParser = this.attr_("xValueParser");
3343 defaultParserSet = true;
3344 }
3345 fields[0] = xParser(inFields[0], this);
6a1aa64f
DV
3346
3347 // If fractions are expected, parse the numbers as "A/B"
3348 if (this.fractions_) {
3349 for (var j = 1; j < inFields.length; j++) {
3350 // TODO(danvk): figure out an appropriate way to flag parse errors.
3351 var vals = inFields[j].split("/");
7219edb3
DV
3352 if (vals.length != 2) {
3353 this.error('Expected fractional "num/den" values in CSV data ' +
3354 "but found a value '" + inFields[j] + "' on line " +
3355 (1 + i) + " ('" + line + "') which is not of this form.");
3356 fields[j] = [0, 0];
3357 } else {
3358 fields[j] = [this.parseFloat_(vals[0], i, line),
3359 this.parseFloat_(vals[1], i, line)];
3360 }
6a1aa64f 3361 }
285a6bda 3362 } else if (this.attr_("errorBars")) {
6a1aa64f 3363 // If there are error bars, values are (value, stddev) pairs
7219edb3
DV
3364 if (inFields.length % 2 != 1) {
3365 this.error('Expected alternating (value, stdev.) pairs in CSV data ' +
3366 'but line ' + (1 + i) + ' has an odd number of values (' +
3367 (inFields.length - 1) + "): '" + line + "'");
3368 }
3369 for (var j = 1; j < inFields.length; j += 2) {
5cd7ac68
DV
3370 fields[(j + 1) / 2] = [this.parseFloat_(inFields[j], i, line),
3371 this.parseFloat_(inFields[j + 1], i, line)];
7219edb3 3372 }
9922b78b 3373 } else if (this.attr_("customBars")) {
6a1aa64f
DV
3374 // Bars are a low;center;high tuple
3375 for (var j = 1; j < inFields.length; j++) {
327a9279
DV
3376 var val = inFields[j];
3377 if (/^ *$/.test(val)) {
3378 fields[j] = [null, null, null];
3379 } else {
3380 var vals = val.split(";");
3381 if (vals.length == 3) {
3382 fields[j] = [ this.parseFloat_(vals[0], i, line),
3383 this.parseFloat_(vals[1], i, line),
3384 this.parseFloat_(vals[2], i, line) ];
3385 } else {
3386 this.warning('When using customBars, values must be either blank ' +
3387 'or "low;center;high" tuples (got "' + val +
3388 '" on line ' + (1+i));
3389 }
3390 }
6a1aa64f
DV
3391 }
3392 } else {
3393 // Values are just numbers
285a6bda 3394 for (var j = 1; j < inFields.length; j++) {
5cd7ac68 3395 fields[j] = this.parseFloat_(inFields[j], i, line);
285a6bda 3396 }
6a1aa64f 3397 }
987840a2
DV
3398 if (ret.length > 0 && fields[0] < ret[ret.length - 1][0]) {
3399 outOfOrder = true;
3400 }
285a6bda
DV
3401
3402 if (fields.length != expectedCols) {
3403 this.error("Number of columns in line " + i + " (" + fields.length +
3404 ") does not agree with number of labels (" + expectedCols +
3405 ") " + line);
3406 }
6d0aaa09
DV
3407
3408 // If the user specified the 'labels' option and none of the cells of the
3409 // first row parsed correctly, then they probably double-specified the
3410 // labels. We go with the values set in the option, discard this row and
3411 // log a warning to the JS console.
3412 if (i == 0 && this.attr_('labels')) {
3413 var all_null = true;
3414 for (var j = 0; all_null && j < fields.length; j++) {
3415 if (fields[j]) all_null = false;
3416 }
3417 if (all_null) {
3418 this.warn("The dygraphs 'labels' option is set, but the first row of " +
3419 "CSV data ('" + line + "') appears to also contain labels. " +
3420 "Will drop the CSV labels and use the option labels.");
3421 continue;
3422 }
3423 }
3424 ret.push(fields);
6a1aa64f 3425 }
987840a2
DV
3426
3427 if (outOfOrder) {
3428 this.warn("CSV is out of order; order it correctly to speed loading.");
3429 ret.sort(function(a,b) { return a[0] - b[0] });
3430 }
3431
6a1aa64f
DV
3432 return ret;
3433};
3434
3435/**
629a09ae 3436 * @private
285a6bda
DV
3437 * The user has provided their data as a pre-packaged JS array. If the x values
3438 * are numeric, this is the same as dygraphs' internal format. If the x values
3439 * are dates, we need to convert them from Date objects to ms since epoch.
629a09ae
DV
3440 * @param {[Object]} data
3441 * @return {[Object]} data with numeric x values.
285a6bda
DV
3442 */
3443Dygraph.prototype.parseArray_ = function(data) {
3444 // Peek at the first x value to see if it's numeric.
3445 if (data.length == 0) {
3446 this.error("Can't plot empty data set");
3447 return null;
3448 }
3449 if (data[0].length == 0) {
3450 this.error("Data set cannot contain an empty row");
3451 return null;
3452 }
3453
3454 if (this.attr_("labels") == null) {
3455 this.warn("Using default labels. Set labels explicitly via 'labels' " +
3456 "in the options parameter");
3457 this.attrs_.labels = [ "X" ];
3458 for (var i = 1; i < data[0].length; i++) {
3459 this.attrs_.labels.push("Y" + i);
3460 }
3461 }
3462
2dda3850 3463 if (Dygraph.isDateLike(data[0][0])) {
285a6bda
DV
3464 // Some intelligent defaults for a date x-axis.
3465 this.attrs_.xValueFormatter = Dygraph.dateString_;
bf640e56 3466 this.attrs_.xAxisLabelFormatter = Dygraph.dateAxisFormatter;
285a6bda
DV
3467 this.attrs_.xTicker = Dygraph.dateTicker;
3468
3469 // Assume they're all dates.
e3ab7b40 3470 var parsedData = Dygraph.clone(data);
285a6bda
DV
3471 for (var i = 0; i < data.length; i++) {
3472 if (parsedData[i].length == 0) {
a323ff4a 3473 this.error("Row " + (1 + i) + " of data is empty");
285a6bda
DV
3474 return null;
3475 }
3476 if (parsedData[i][0] == null
3a909ec5
DV
3477 || typeof(parsedData[i][0].getTime) != 'function'
3478 || isNaN(parsedData[i][0].getTime())) {
be96a1f5 3479 this.error("x value in row " + (1 + i) + " is not a Date");
285a6bda
DV
3480 return null;
3481 }
3482 parsedData[i][0] = parsedData[i][0].getTime();
3483 }
3484 return parsedData;
3485 } else {
3486 // Some intelligent defaults for a numeric x-axis.
c39e1d93 3487 /** @private (shut up, jsdoc!) */
032e4c1d 3488 this.attrs_.xValueFormatter = function(x) { return x; };
285a6bda
DV
3489 this.attrs_.xTicker = Dygraph.numericTicks;
3490 return data;
3491 }
3492};
3493
3494/**
79420a1e
DV
3495 * Parses a DataTable object from gviz.
3496 * The data is expected to have a first column that is either a date or a
3497 * number. All subsequent columns must be numbers. If there is a clear mismatch
3498 * between this.xValueParser_ and the type of the first column, it will be
a685723c 3499 * fixed. Fills out rawData_.
629a09ae 3500 * @param {[Object]} data See above.
79420a1e
DV
3501 * @private
3502 */
285a6bda 3503Dygraph.prototype.parseDataTable_ = function(data) {
79420a1e
DV
3504 var cols = data.getNumberOfColumns();
3505 var rows = data.getNumberOfRows();
3506
d955e223 3507 var indepType = data.getColumnType(0);
4440f6c8 3508 if (indepType == 'date' || indepType == 'datetime') {
285a6bda
DV
3509 this.attrs_.xValueFormatter = Dygraph.dateString_;
3510 this.attrs_.xValueParser = Dygraph.dateParser;
3511 this.attrs_.xTicker = Dygraph.dateTicker;
bf640e56 3512 this.attrs_.xAxisLabelFormatter = Dygraph.dateAxisFormatter;
33127159 3513 } else if (indepType == 'number') {
032e4c1d 3514 this.attrs_.xValueFormatter = function(x) { return x; };
285a6bda
DV
3515 this.attrs_.xValueParser = function(x) { return parseFloat(x); };
3516 this.attrs_.xTicker = Dygraph.numericTicks;
bf640e56 3517 this.attrs_.xAxisLabelFormatter = this.attrs_.xValueFormatter;
285a6bda 3518 } else {
987840a2
DV
3519 this.error("only 'date', 'datetime' and 'number' types are supported for " +
3520 "column 1 of DataTable input (Got '" + indepType + "')");
79420a1e
DV
3521 return null;
3522 }
3523
a685723c
DV
3524 // Array of the column indices which contain data (and not annotations).
3525 var colIdx = [];
3526 var annotationCols = {}; // data index -> [annotation cols]
3527 var hasAnnotations = false;
3528 for (var i = 1; i < cols; i++) {
3529 var type = data.getColumnType(i);
3530 if (type == 'number') {
3531 colIdx.push(i);
3532 } else if (type == 'string' && this.attr_('displayAnnotations')) {
3533 // This is OK -- it's an annotation column.
3534 var dataIdx = colIdx[colIdx.length - 1];
3535 if (!annotationCols.hasOwnProperty(dataIdx)) {
3536 annotationCols[dataIdx] = [i];
3537 } else {
3538 annotationCols[dataIdx].push(i);
3539 }
3540 hasAnnotations = true;
3541 } else {
3542 this.error("Only 'number' is supported as a dependent type with Gviz." +
3543 " 'string' is only supported if displayAnnotations is true");
3544 }
3545 }
3546
3547 // Read column labels
3548 // TODO(danvk): add support back for errorBars
3549 var labels = [data.getColumnLabel(0)];
3550 for (var i = 0; i < colIdx.length; i++) {
3551 labels.push(data.getColumnLabel(colIdx[i]));
f9348814 3552 if (this.attr_("errorBars")) i += 1;
a685723c
DV
3553 }
3554 this.attrs_.labels = labels;
3555 cols = labels.length;
3556
79420a1e 3557 var ret = [];
987840a2 3558 var outOfOrder = false;
a685723c 3559 var annotations = [];
79420a1e
DV
3560 for (var i = 0; i < rows; i++) {
3561 var row = [];
debe4434
DV
3562 if (typeof(data.getValue(i, 0)) === 'undefined' ||
3563 data.getValue(i, 0) === null) {
129569a5
FD
3564 this.warn("Ignoring row " + i +
3565 " of DataTable because of undefined or null first column.");
debe4434
DV
3566 continue;
3567 }
3568
c21d2c2d 3569 if (indepType == 'date' || indepType == 'datetime') {
d955e223
DV
3570 row.push(data.getValue(i, 0).getTime());
3571 } else {
3572 row.push(data.getValue(i, 0));
3573 }
3e3f84e4 3574 if (!this.attr_("errorBars")) {
a685723c
DV
3575 for (var j = 0; j < colIdx.length; j++) {
3576 var col = colIdx[j];
3577 row.push(data.getValue(i, col));
3578 if (hasAnnotations &&
3579 annotationCols.hasOwnProperty(col) &&
3580 data.getValue(i, annotationCols[col][0]) != null) {
3581 var ann = {};
3582 ann.series = data.getColumnLabel(col);
3583 ann.xval = row[0];
3584 ann.shortText = String.fromCharCode(65 /* A */ + annotations.length)
3585 ann.text = '';
3586 for (var k = 0; k < annotationCols[col].length; k++) {
3587 if (k) ann.text += "\n";
3588 ann.text += data.getValue(i, annotationCols[col][k]);
3589 }
3590 annotations.push(ann);
3591 }
3e3f84e4 3592 }
92fd68d8
DV
3593
3594 // Strip out infinities, which give dygraphs problems later on.
3595 for (var j = 0; j < row.length; j++) {
3596 if (!isFinite(row[j])) row[j] = null;
3597 }
3e3f84e4
DV
3598 } else {
3599 for (var j = 0; j < cols - 1; j++) {
3600 row.push([ data.getValue(i, 1 + 2 * j), data.getValue(i, 2 + 2 * j) ]);
3601 }
79420a1e 3602 }
987840a2
DV
3603 if (ret.length > 0 && row[0] < ret[ret.length - 1][0]) {
3604 outOfOrder = true;
3605 }
243d96e8 3606 ret.push(row);
79420a1e 3607 }
987840a2
DV
3608
3609 if (outOfOrder) {
3610 this.warn("DataTable is out of order; order it correctly to speed loading.");
3611 ret.sort(function(a,b) { return a[0] - b[0] });
3612 }
a685723c
DV
3613 this.rawData_ = ret;
3614
3615 if (annotations.length > 0) {
3616 this.setAnnotations(annotations, true);
3617 }
79420a1e
DV
3618}
3619
629a09ae
DV
3620/**
3621 * @private
3622 * This is identical to JavaScript's built-in Date.parse() method, except that
3623 * it doesn't get replaced with an incompatible method by aggressive JS
3624 * libraries like MooTools or Joomla.
3625 * @param { String } str The date string, e.g. "2011/05/06"
3626 * @return { Integer } millis since epoch
3627 */
d96b7d1a
DV
3628Dygraph.dateStrToMillis = function(str) {
3629 return new Date(str).getTime();
3630};
3631
24e5350c 3632// These functions are all based on MochiKit.
629a09ae
DV
3633/**
3634 * @private
3635 */
fc80a396
DV
3636Dygraph.update = function (self, o) {
3637 if (typeof(o) != 'undefined' && o !== null) {
3638 for (var k in o) {
85b99f0b
DV
3639 if (o.hasOwnProperty(k)) {
3640 self[k] = o[k];
3641 }
fc80a396
DV
3642 }
3643 }
3644 return self;
3645};
3646
629a09ae
DV
3647/**
3648 * @private
3649 */
2dda3850
DV
3650Dygraph.isArrayLike = function (o) {
3651 var typ = typeof(o);
3652 if (
c21d2c2d 3653 (typ != 'object' && !(typ == 'function' &&
2dda3850
DV
3654 typeof(o.item) == 'function')) ||
3655 o === null ||
3656 typeof(o.length) != 'number' ||
3657 o.nodeType === 3
3658 ) {
3659 return false;
3660 }
3661 return true;
3662};
3663
629a09ae
DV
3664/**
3665 * @private
3666 */
2dda3850
DV
3667Dygraph.isDateLike = function (o) {
3668 if (typeof(o) != "object" || o === null ||
3669 typeof(o.getTime) != 'function') {
3670 return false;
3671 }
3672 return true;
3673};
3674
629a09ae
DV
3675/**
3676 * @private
3677 */
e3ab7b40
DV
3678Dygraph.clone = function(o) {
3679 // TODO(danvk): figure out how MochiKit's version works
3680 var r = [];
3681 for (var i = 0; i < o.length; i++) {
3682 if (Dygraph.isArrayLike(o[i])) {
3683 r.push(Dygraph.clone(o[i]));
3684 } else {
3685 r.push(o[i]);
3686 }
3687 }
3688 return r;
24e5350c
DV
3689};
3690
2dda3850 3691
79420a1e 3692/**
6a1aa64f
DV
3693 * Get the CSV data. If it's in a function, call that function. If it's in a
3694 * file, do an XMLHttpRequest to get it.
3695 * @private
3696 */
285a6bda 3697Dygraph.prototype.start_ = function() {
6a1aa64f 3698 if (typeof this.file_ == 'function') {
285a6bda 3699 // CSV string. Pretend we got it via XHR.
6a1aa64f 3700 this.loadedEvent_(this.file_());
2dda3850 3701 } else if (Dygraph.isArrayLike(this.file_)) {
285a6bda 3702 this.rawData_ = this.parseArray_(this.file_);
26ca7938 3703 this.predraw_();
79420a1e
DV
3704 } else if (typeof this.file_ == 'object' &&
3705 typeof this.file_.getColumnRange == 'function') {
3706 // must be a DataTable from gviz.
a685723c 3707 this.parseDataTable_(this.file_);
26ca7938 3708 this.predraw_();
285a6bda
DV
3709 } else if (typeof this.file_ == 'string') {
3710 // Heuristic: a newline means it's CSV data. Otherwise it's an URL.
3711 if (this.file_.indexOf('\n') >= 0) {
3712 this.loadedEvent_(this.file_);
3713 } else {
3714 var req = new XMLHttpRequest();
3715 var caller = this;
3716 req.onreadystatechange = function () {
3717 if (req.readyState == 4) {
3718 if (req.status == 200) {
3719 caller.loadedEvent_(req.responseText);
3720 }
6a1aa64f 3721 }
285a6bda 3722 };
6a1aa64f 3723
285a6bda
DV
3724 req.open("GET", this.file_, true);
3725 req.send(null);
3726 }
3727 } else {
3728 this.error("Unknown data format: " + (typeof this.file_));
6a1aa64f
DV
3729 }
3730};
3731
3732/**
3733 * Changes various properties of the graph. These can include:
3734 * <ul>
3735 * <li>file: changes the source data for the graph</li>
3736 * <li>errorBars: changes whether the data contains stddev</li>
3737 * </ul>
dcb25130 3738 *
ccfcc169
DV
3739 * There's a huge variety of options that can be passed to this method. For a
3740 * full list, see http://dygraphs.com/options.html.
3741 *
6a1aa64f 3742 * @param {Object} attrs The new properties and values
ccfcc169
DV
3743 * @param {Boolean} [block_redraw] Usually the chart is redrawn after every
3744 * call to updateOptions(). If you know better, you can pass true to explicitly
3745 * block the redraw. This can be useful for chaining updateOptions() calls,
3746 * avoiding the occasional infinite loop and preventing redraws when it's not
3747 * necessary (e.g. when updating a callback).
6a1aa64f 3748 */
ccfcc169
DV
3749Dygraph.prototype.updateOptions = function(attrs, block_redraw) {
3750 if (typeof(block_redraw) == 'undefined') block_redraw = false;
3751
3752 // TODO(danvk): this is a mess. Move these options into attr_.
c65f2303 3753 if ('rollPeriod' in attrs) {
6a1aa64f
DV
3754 this.rollPeriod_ = attrs.rollPeriod;
3755 }
c65f2303 3756 if ('dateWindow' in attrs) {
6a1aa64f 3757 this.dateWindow_ = attrs.dateWindow;
e5152598 3758 if (!('isZoomedIgnoreProgrammaticZoom' in attrs)) {
81856f70
NN
3759 this.zoomed_x_ = attrs.dateWindow != null;
3760 }
b7e5862d 3761 }
e5152598 3762 if ('valueRange' in attrs && !('isZoomedIgnoreProgrammaticZoom' in attrs)) {
b7e5862d 3763 this.zoomed_y_ = attrs.valueRange != null;
6a1aa64f 3764 }
450fe64b
DV
3765
3766 // TODO(danvk): validate per-series options.
46dde5f9
DV
3767 // Supported:
3768 // strokeWidth
3769 // pointSize
3770 // drawPoints
3771 // highlightCircleSize
450fe64b 3772
fc80a396 3773 Dygraph.update(this.user_attrs_, attrs);
285a6bda 3774
5e50289f 3775 if (attrs['file']) {
6a1aa64f 3776 this.file_ = attrs['file'];
ccfcc169 3777 if (!block_redraw) this.start_();
6a1aa64f 3778 } else {
ccfcc169 3779 if (!block_redraw) this.predraw_();
6a1aa64f
DV
3780 }
3781};
3782
3783/**
697e70b2
DV
3784 * Resizes the dygraph. If no parameters are specified, resizes to fill the
3785 * containing div (which has presumably changed size since the dygraph was
3786 * instantiated. If the width/height are specified, the div will be resized.
964f30c6
DV
3787 *
3788 * This is far more efficient than destroying and re-instantiating a
3789 * Dygraph, since it doesn't have to reparse the underlying data.
3790 *
629a09ae
DV
3791 * @param {Number} [width] Width (in pixels)
3792 * @param {Number} [height] Height (in pixels)
697e70b2
DV
3793 */
3794Dygraph.prototype.resize = function(width, height) {
e8c7ef86
DV
3795 if (this.resize_lock) {
3796 return;
3797 }
3798 this.resize_lock = true;
3799
697e70b2
DV
3800 if ((width === null) != (height === null)) {
3801 this.warn("Dygraph.resize() should be called with zero parameters or " +
3802 "two non-NULL parameters. Pretending it was zero.");
3803 width = height = null;
3804 }
3805
b16e6369 3806 // TODO(danvk): there should be a clear() method.
697e70b2 3807 this.maindiv_.innerHTML = "";
b16e6369
DV
3808 this.attrs_.labelsDiv = null;
3809
697e70b2
DV
3810 if (width) {
3811 this.maindiv_.style.width = width + "px";
3812 this.maindiv_.style.height = height + "px";
3813 this.width_ = width;
3814 this.height_ = height;
3815 } else {
3816 this.width_ = this.maindiv_.offsetWidth;
3817 this.height_ = this.maindiv_.offsetHeight;
3818 }
3819
3820 this.createInterface_();
26ca7938 3821 this.predraw_();
e8c7ef86
DV
3822
3823 this.resize_lock = false;
697e70b2
DV
3824};
3825
3826/**
6faebb69 3827 * Adjusts the number of points in the rolling average. Updates the graph to
6a1aa64f 3828 * reflect the new averaging period.
6faebb69 3829 * @param {Number} length Number of points over which to average the data.
6a1aa64f 3830 */
285a6bda 3831Dygraph.prototype.adjustRoll = function(length) {
6a1aa64f 3832 this.rollPeriod_ = length;
26ca7938 3833 this.predraw_();
6a1aa64f 3834};
540d00f1 3835
f8cfec73 3836/**
1cf11047
DV
3837 * Returns a boolean array of visibility statuses.
3838 */
3839Dygraph.prototype.visibility = function() {
3840 // Do lazy-initialization, so that this happens after we know the number of
3841 // data series.
3842 if (!this.attr_("visibility")) {
f38dec01 3843 this.attrs_["visibility"] = [];
1cf11047
DV
3844 }
3845 while (this.attr_("visibility").length < this.rawData_[0].length - 1) {
f38dec01 3846 this.attr_("visibility").push(true);
1cf11047
DV
3847 }
3848 return this.attr_("visibility");
3849};
3850
3851/**
3852 * Changes the visiblity of a series.
3853 */
3854Dygraph.prototype.setVisibility = function(num, value) {
3855 var x = this.visibility();
a6c109c1 3856 if (num < 0 || num >= x.length) {
1cf11047
DV
3857 this.warn("invalid series number in setVisibility: " + num);
3858 } else {
3859 x[num] = value;
26ca7938 3860 this.predraw_();
1cf11047
DV
3861 }
3862};
3863
3864/**
5c528fa2
DV
3865 * Update the list of annotations and redraw the chart.
3866 */
a685723c 3867Dygraph.prototype.setAnnotations = function(ann, suppressDraw) {
3c51ab74
DV
3868 // Only add the annotation CSS rule once we know it will be used.
3869 Dygraph.addAnnotationRule();
5c528fa2
DV
3870 this.annotations_ = ann;
3871 this.layout_.setAnnotations(this.annotations_);
a685723c 3872 if (!suppressDraw) {
26ca7938 3873 this.predraw_();
a685723c 3874 }
5c528fa2
DV
3875};
3876
3877/**
3878 * Return the list of annotations.
3879 */
3880Dygraph.prototype.annotations = function() {
3881 return this.annotations_;
3882};
3883
46dde5f9
DV
3884/**
3885 * Get the index of a series (column) given its name. The first column is the
3886 * x-axis, so the data series start with index 1.
3887 */
3888Dygraph.prototype.indexFromSetName = function(name) {
3889 var labels = this.attr_("labels");
3890 for (var i = 0; i < labels.length; i++) {
3891 if (labels[i] == name) return i;
3892 }
3893 return null;
3894};
3895
629a09ae
DV
3896/**
3897 * @private
3898 * Adds a default style for the annotation CSS classes to the document. This is
3899 * only executed when annotations are actually used. It is designed to only be
3900 * called once -- all calls after the first will return immediately.
3901 */
5c528fa2
DV
3902Dygraph.addAnnotationRule = function() {
3903 if (Dygraph.addedAnnotationCSS) return;
3904
5c528fa2
DV
3905 var rule = "border: 1px solid black; " +
3906 "background-color: white; " +
3907 "text-align: center;";
22186871
DV
3908
3909 var styleSheetElement = document.createElement("style");
3910 styleSheetElement.type = "text/css";
3911 document.getElementsByTagName("head")[0].appendChild(styleSheetElement);
3912
3913 // Find the first style sheet that we can access.
3914 // We may not add a rule to a style sheet from another domain for security
3915 // reasons. This sometimes comes up when using gviz, since the Google gviz JS
3916 // adds its own style sheets from google.com.
3917 for (var i = 0; i < document.styleSheets.length; i++) {
3918 if (document.styleSheets[i].disabled) continue;
3919 var mysheet = document.styleSheets[i];
3920 try {
3921 if (mysheet.insertRule) { // Firefox
3922 var idx = mysheet.cssRules ? mysheet.cssRules.length : 0;
3923 mysheet.insertRule(".dygraphDefaultAnnotation { " + rule + " }", idx);
3924 } else if (mysheet.addRule) { // IE
3925 mysheet.addRule(".dygraphDefaultAnnotation", rule);
3926 }
3927 Dygraph.addedAnnotationCSS = true;
3928 return;
3929 } catch(err) {
3930 // Was likely a security exception.
3931 }
5c528fa2
DV
3932 }
3933
22186871 3934 this.warn("Unable to add default annotation CSS rule; display may be off.");
5c528fa2
DV
3935}
3936
3937/**
629a09ae 3938 * @private
f8cfec73
DV
3939 * Create a new canvas element. This is more complex than a simple
3940 * document.createElement("canvas") because of IE and excanvas.
3941 */
3942Dygraph.createCanvas = function() {
3943 var canvas = document.createElement("canvas");
3944
3945 isIE = (/MSIE/.test(navigator.userAgent) && !window.opera);
8b8f2d59 3946 if (isIE && (typeof(G_vmlCanvasManager) != 'undefined')) {
f8cfec73
DV
3947 canvas = G_vmlCanvasManager.initElement(canvas);
3948 }
3949
3950 return canvas;
3951};
3952
540d00f1
DV
3953
3954/**
285a6bda 3955 * A wrapper around Dygraph that implements the gviz API.
540d00f1
DV
3956 * @param {Object} container The DOM object the visualization should live in.
3957 */
285a6bda 3958Dygraph.GVizChart = function(container) {
540d00f1
DV
3959 this.container = container;
3960}
3961
285a6bda 3962Dygraph.GVizChart.prototype.draw = function(data, options) {
c91f4ae8
DV
3963 // Clear out any existing dygraph.
3964 // TODO(danvk): would it make more sense to simply redraw using the current
3965 // date_graph object?
540d00f1 3966 this.container.innerHTML = '';
c91f4ae8
DV
3967 if (typeof(this.date_graph) != 'undefined') {
3968 this.date_graph.destroy();
3969 }
3970
285a6bda 3971 this.date_graph = new Dygraph(this.container, data, options);
540d00f1 3972}
285a6bda 3973
239c712d
NAG
3974/**
3975 * Google charts compatible setSelection
50360fd0 3976 * Only row selection is supported, all points in the row will be highlighted
239c712d
NAG
3977 * @param {Array} array of the selected cells
3978 * @public
3979 */
3980Dygraph.GVizChart.prototype.setSelection = function(selection_array) {
3981 var row = false;
3982 if (selection_array.length) {
3983 row = selection_array[0].row;
3984 }
3985 this.date_graph.setSelection(row);
3986}
3987
103b7292
NAG
3988/**
3989 * Google charts compatible getSelection implementation
3990 * @return {Array} array of the selected cells
3991 * @public
3992 */
3993Dygraph.GVizChart.prototype.getSelection = function() {
3994 var selection = [];
50360fd0 3995
103b7292 3996 var row = this.date_graph.getSelection();
50360fd0 3997
103b7292 3998 if (row < 0) return selection;
50360fd0 3999
103b7292
NAG
4000 col = 1;
4001 for (var i in this.date_graph.layout_.datasets) {
4002 selection.push({row: row, column: col});
4003 col++;
4004 }
4005
4006 return selection;
4007}
4008
285a6bda
DV
4009// Older pages may still use this name.
4010DateGraph = Dygraph;
028ddf8a
DV
4011
4012// <REMOVE_FOR_COMBINED>
0addac07
DV
4013Dygraph.OPTIONS_REFERENCE = // <JSON>
4014{
a38e9336
DV
4015 "xValueParser": {
4016 "default": "parseFloat() or Date.parse()*",
4017 "labels": ["CSV parsing"],
4018 "type": "function(str) -> number",
4019 "description": "A function which parses x-values (i.e. the dependent series). Must return a number, even when the values are dates. In this case, millis since epoch are used. This is used primarily for parsing CSV data. *=Dygraphs is slightly more accepting in the dates which it will parse. See code for details."
4020 },
4021 "stackedGraph": {
a96f59f4 4022 "default": "false",
a38e9336
DV
4023 "labels": ["Data Line display"],
4024 "type": "boolean",
4025 "description": "If set, stack series on top of one another rather than drawing them independently."
a96f59f4 4026 },
a38e9336 4027 "pointSize": {
a96f59f4 4028 "default": "1",
a38e9336
DV
4029 "labels": ["Data Line display"],
4030 "type": "integer",
4031 "description": "The size of the dot to draw on each point in pixels (see drawPoints). A dot is always drawn when a point is \"isolated\", i.e. there is a missing point on either side of it. This also controls the size of those dots."
a96f59f4 4032 },
a38e9336
DV
4033 "labelsDivStyles": {
4034 "default": "null",
4035 "labels": ["Legend"],
4036 "type": "{}",
4037 "description": "Additional styles to apply to the currently-highlighted points div. For example, { 'font-weight': 'bold' } will make the labels bold."
a96f59f4 4038 },
a38e9336 4039 "drawPoints": {
a96f59f4 4040 "default": "false",
a38e9336
DV
4041 "labels": ["Data Line display"],
4042 "type": "boolean",
4043 "description": "Draw a small dot at each point, in addition to a line going through the point. This makes the individual data points easier to see, but can increase visual clutter in the chart."
a96f59f4 4044 },
a38e9336
DV
4045 "height": {
4046 "default": "320",
4047 "labels": ["Overall display"],
4048 "type": "integer",
4049 "description": "Height, in pixels, of the chart. If the container div has been explicitly sized, this will be ignored."
a96f59f4
DV
4050 },
4051 "zoomCallback": {
a96f59f4 4052 "default": "null",
a38e9336
DV
4053 "labels": ["Callbacks"],
4054 "type": "function(minDate, maxDate, yRanges)",
a96f59f4
DV
4055 "description": "A function to call when the zoom window is changed (either by zooming in or out). minDate and maxDate are milliseconds since epoch. yRanges is an array of [bottom, top] pairs, one for each y-axis."
4056 },
a38e9336
DV
4057 "pointClickCallback": {
4058 "default": "",
4059 "labels": ["Callbacks", "Interactive Elements"],
4060 "type": "",
4061 "description": ""
a96f59f4 4062 },
a38e9336
DV
4063 "colors": {
4064 "default": "(see description)",
4065 "labels": ["Data Series Colors"],
4066 "type": "array<string>",
4067 "example": "['red', '#00FF00']",
4068 "description": "List of colors for the data series. These can be of the form \"#AABBCC\" or \"rgb(255,100,200)\" or \"yellow\", etc. If not specified, equally-spaced points around a color wheel are used."
a96f59f4 4069 },
a38e9336 4070 "connectSeparatedPoints": {
a96f59f4 4071 "default": "false",
a38e9336
DV
4072 "labels": ["Data Line display"],
4073 "type": "boolean",
4074 "description": "Usually, when Dygraphs encounters a missing value in a data series, it interprets this as a gap and draws it as such. If, instead, the missing values represents an x-value for which only a different series has data, then you'll want to connect the dots by setting this to true. To explicitly include a gap with this option set, use a value of NaN."
a96f59f4 4075 },
a38e9336 4076 "highlightCallback": {
a96f59f4 4077 "default": "null",
a38e9336
DV
4078 "labels": ["Callbacks"],
4079 "type": "function(event, x, points,row)",
4080 "description": "When set, this callback gets called every time a new point is highlighted. The parameters are the JavaScript mousemove event, the x-coordinate of the highlighted points and an array of highlighted points: <code>[ {name: 'series', yval: y-value}, &hellip; ]</code>"
a96f59f4 4081 },
a38e9336 4082 "includeZero": {
a96f59f4 4083 "default": "false",
a38e9336 4084 "labels": ["Axis display"],
a96f59f4 4085 "type": "boolean",
a38e9336 4086 "description": "Usually, dygraphs will use the range of the data plus some padding to set the range of the y-axis. If this option is set, the y-axis will always include zero, typically as the lowest value. This can be used to avoid exaggerating the variance in the data"
a96f59f4 4087 },
a38e9336
DV
4088 "rollPeriod": {
4089 "default": "1",
4090 "labels": ["Error Bars", "Rolling Averages"],
4091 "type": "integer &gt;= 1",
4092 "description": "Number of days over which to average data. Discussed extensively above."
a96f59f4 4093 },
a38e9336 4094 "unhighlightCallback": {
a96f59f4 4095 "default": "null",
a38e9336
DV
4096 "labels": ["Callbacks"],
4097 "type": "function(event)",
4098 "description": "When set, this callback gets called every time the user stops highlighting any point by mousing out of the graph. The parameter is the mouseout event."
a96f59f4 4099 },
a38e9336
DV
4100 "axisTickSize": {
4101 "default": "3.0",
4102 "labels": ["Axis display"],
4103 "type": "number",
4104 "description": "The size of the line to display next to each tick mark on x- or y-axes."
a96f59f4 4105 },
a38e9336 4106 "labelsSeparateLines": {
a96f59f4 4107 "default": "false",
a38e9336
DV
4108 "labels": ["Legend"],
4109 "type": "boolean",
4110 "description": "Put <code>&lt;br/&gt;</code> between lines in the label string. Often used in conjunction with <strong>labelsDiv</strong>."
a96f59f4 4111 },
a38e9336
DV
4112 "xValueFormatter": {
4113 "default": "(Round to 2 decimal places)",
4114 "labels": ["Axis display"],
4115 "type": "function(x)",
4116 "description": "Function to provide a custom display format for the X value for mouseover."
a96f59f4
DV
4117 },
4118 "pixelsPerYLabel": {
a96f59f4 4119 "default": "30",
a38e9336
DV
4120 "labels": ["Axis display", "Grid"],
4121 "type": "integer",
a96f59f4
DV
4122 "description": "Number of pixels to require between each x- and y-label. Larger values will yield a sparser axis with fewer ticks."
4123 },
a38e9336 4124 "annotationMouseOverHandler": {
5cc5f631 4125 "default": "null",
a38e9336 4126 "labels": ["Annotations"],
5cc5f631
DV
4127 "type": "function(annotation, point, dygraph, event)",
4128 "description": "If provided, this function is called whenever the user mouses over an annotation."
4129 },
4130 "annotationMouseOutHandler": {
4131 "default": "null",
4132 "labels": ["Annotations"],
4133 "type": "function(annotation, point, dygraph, event)",
4134 "description": "If provided, this function is called whenever the user mouses out of an annotation."
a96f59f4 4135 },
8165189e 4136 "annotationClickHandler": {
5cc5f631 4137 "default": "null",
8165189e 4138 "labels": ["Annotations"],
5cc5f631
DV
4139 "type": "function(annotation, point, dygraph, event)",
4140 "description": "If provided, this function is called whenever the user clicks on an annotation."
8165189e
DV
4141 },
4142 "annotationDblClickHandler": {
5cc5f631 4143 "default": "null",
8165189e 4144 "labels": ["Annotations"],
5cc5f631
DV
4145 "type": "function(annotation, point, dygraph, event)",
4146 "description": "If provided, this function is called whenever the user double-clicks on an annotation."
8165189e 4147 },
a38e9336
DV
4148 "drawCallback": {
4149 "default": "null",
4150 "labels": ["Callbacks"],
4151 "type": "function(dygraph, is_initial)",
4152 "description": "When set, this callback gets called every time the dygraph is drawn. This includes the initial draw, after zooming and repeatedly while panning. The first parameter is the dygraph being drawn. The second is a boolean value indicating whether this is the initial draw."
4153 },
4154 "labelsKMG2": {
4155 "default": "false",
4156 "labels": ["Value display/formatting"],
4157 "type": "boolean",
4158 "description": "Show k/M/G for kilo/Mega/Giga on y-axis. This is different than <code>labelsKMB</code> in that it uses base 2, not 10."
4159 },
4160 "delimiter": {
4161 "default": ",",
4162 "labels": ["CSV parsing"],
4163 "type": "string",
4164 "description": "The delimiter to look for when separating fields of a CSV file. Setting this to a tab is not usually necessary, since tab-delimited data is auto-detected."
a96f59f4
DV
4165 },
4166 "axisLabelFontSize": {
a96f59f4 4167 "default": "14",
a38e9336
DV
4168 "labels": ["Axis display"],
4169 "type": "integer",
a96f59f4
DV
4170 "description": "Size of the font (in pixels) to use in the axis labels, both x- and y-axis."
4171 },
a38e9336
DV
4172 "underlayCallback": {
4173 "default": "null",
4174 "labels": ["Callbacks"],
4175 "type": "function(canvas, area, dygraph)",
4176 "description": "When set, this callback gets called before the chart is drawn. It details on how to use this."
a96f59f4 4177 },
a38e9336
DV
4178 "width": {
4179 "default": "480",
4180 "labels": ["Overall display"],
4181 "type": "integer",
4182 "description": "Width, in pixels, of the chart. If the container div has been explicitly sized, this will be ignored."
a96f59f4 4183 },
a38e9336
DV
4184 "interactionModel": {
4185 "default": "...",
4186 "labels": ["Interactive Elements"],
4187 "type": "Object",
4188 "description": "TODO(konigsberg): document this"
4189 },
4190 "xTicker": {
4191 "default": "Dygraph.dateTicker or Dygraph.numericTicks",
4192 "labels": ["Axis display"],
4193 "type": "function(min, max, dygraph) -> [{v: ..., label: ...}, ...]",
4194 "description": "This lets you specify an arbitrary function to generate tick marks on an axis. The tick marks are an array of (value, label) pairs. The built-in functions go to great lengths to choose good tick marks so, if you set this option, you'll most likely want to call one of them and modify the result."
4195 },
4196 "xAxisLabelWidth": {
4197 "default": "50",
4198 "labels": ["Axis display"],
a96f59f4 4199 "type": "integer",
a38e9336 4200 "description": "Width, in pixels, of the x-axis labels."
a96f59f4 4201 },
a38e9336
DV
4202 "showLabelsOnHighlight": {
4203 "default": "true",
4204 "labels": ["Interactive Elements", "Legend"],
a96f59f4 4205 "type": "boolean",
a38e9336 4206 "description": "Whether to show the legend upon mouseover."
a96f59f4 4207 },
a38e9336
DV
4208 "axis": {
4209 "default": "(none)",
4210 "labels": ["Axis display"],
4211 "type": "string or object",
4212 "description": "Set to either an object ({}) filled with options for this axis or to the name of an existing data series with its own axis to re-use that axis. See tests for usage."
4213 },
4214 "pixelsPerXLabel": {
4215 "default": "60",
4216 "labels": ["Axis display", "Grid"],
a96f59f4 4217 "type": "integer",
a38e9336
DV
4218 "description": "Number of pixels to require between each x- and y-label. Larger values will yield a sparser axis with fewer ticks."
4219 },
4220 "labelsDiv": {
4221 "default": "null",
4222 "labels": ["Legend"],
4223 "type": "DOM element or string",
4224 "example": "<code style='font-size: small'>document.getElementById('foo')</code>or<code>'foo'",
4225 "description": "Show data labels in an external div, rather than on the graph. This value can either be a div element or a div id."
a96f59f4
DV
4226 },
4227 "fractions": {
a96f59f4 4228 "default": "false",
a38e9336
DV
4229 "labels": ["CSV parsing", "Error Bars"],
4230 "type": "boolean",
a96f59f4
DV
4231 "description": "When set, attempt to parse each cell in the CSV file as \"a/b\", where a and b are integers. The ratio will be plotted. This allows computation of Wilson confidence intervals (see below)."
4232 },
a38e9336
DV
4233 "logscale": {
4234 "default": "false",
4235 "labels": ["Axis display"],
a96f59f4 4236 "type": "boolean",
a109b711 4237 "description": "When set for a y-axis, the graph shows that axis in log scale. Any values less than or equal to zero are not displayed.\n\nNot compatible with showZero, and ignores connectSeparatedPoints. Also, showing log scale with valueRanges that are less than zero will result in an unviewable graph."
a38e9336
DV
4238 },
4239 "strokeWidth": {
4240 "default": "1.0",
4241 "labels": ["Data Line display"],
4242 "type": "integer",
4243 "example": "0.5, 2.0",
4244 "description": "The width of the lines connecting data points. This can be used to increase the contrast or some graphs."
4245 },
4246 "wilsonInterval": {
a96f59f4 4247 "default": "true",
a38e9336
DV
4248 "labels": ["Error Bars"],
4249 "type": "boolean",
a96f59f4
DV
4250 "description": "Use in conjunction with the \"fractions\" option. Instead of plotting +/- N standard deviations, dygraphs will compute a Wilson confidence interval and plot that. This has more reasonable behavior for ratios close to 0 or 1."
4251 },
a38e9336 4252 "fillGraph": {
a96f59f4 4253 "default": "false",
a38e9336
DV
4254 "labels": ["Data Line display"],
4255 "type": "boolean",
4256 "description": "Should the area underneath the graph be filled? This option is not compatible with error bars."
a96f59f4 4257 },
a38e9336
DV
4258 "highlightCircleSize": {
4259 "default": "3",
4260 "labels": ["Interactive Elements"],
4261 "type": "integer",
4262 "description": "The size in pixels of the dot drawn over highlighted points."
a96f59f4
DV
4263 },
4264 "gridLineColor": {
a96f59f4 4265 "default": "rgb(128,128,128)",
a38e9336
DV
4266 "labels": ["Grid"],
4267 "type": "red, blue",
a96f59f4
DV
4268 "description": "The color of the gridlines."
4269 },
a38e9336
DV
4270 "visibility": {
4271 "default": "[true, true, ...]",
4272 "labels": ["Data Line display"],
4273 "type": "Array of booleans",
4274 "description": "Which series should initially be visible? Once the Dygraph has been constructed, you can access and modify the visibility of each series using the <code>visibility</code> and <code>setVisibility</code> methods."
a96f59f4 4275 },
a38e9336
DV
4276 "valueRange": {
4277 "default": "Full range of the input is shown",
4278 "labels": ["Axis display"],
4279 "type": "Array of two numbers",
4280 "example": "[10, 110]",
4281 "description": "Explicitly set the vertical range of the graph to [low, high]."
a96f59f4 4282 },
a38e9336
DV
4283 "labelsDivWidth": {
4284 "default": "250",
4285 "labels": ["Legend"],
a96f59f4 4286 "type": "integer",
a38e9336 4287 "description": "Width (in pixels) of the div which shows information on the currently-highlighted points."
a96f59f4 4288 },
a38e9336
DV
4289 "colorSaturation": {
4290 "default": "1.0",
4291 "labels": ["Data Series Colors"],
990d6a35 4292 "type": "float (0.0 - 1.0)",
a38e9336
DV
4293 "description": "If <strong>colors</strong> is not specified, saturation of the automatically-generated data series colors."
4294 },
4295 "yAxisLabelWidth": {
4296 "default": "50",
4297 "labels": ["Axis display"],
a96f59f4 4298 "type": "integer",
990d6a35 4299 "description": "Width, in pixels, of the y-axis labels. This also affects the amount of space available for a y-axis chart label."
a96f59f4 4300 },
a38e9336
DV
4301 "hideOverlayOnMouseOut": {
4302 "default": "true",
4303 "labels": ["Interactive Elements", "Legend"],
a96f59f4 4304 "type": "boolean",
a38e9336 4305 "description": "Whether to hide the legend when the mouse leaves the chart area."
a96f59f4
DV
4306 },
4307 "yValueFormatter": {
a96f59f4 4308 "default": "(Round to 2 decimal places)",
a38e9336
DV
4309 "labels": ["Axis display"],
4310 "type": "function(x)",
a96f59f4
DV
4311 "description": "Function to provide a custom display format for the Y value for mouseover."
4312 },
a38e9336
DV
4313 "legend": {
4314 "default": "onmouseover",
4315 "labels": ["Legend"],
4316 "type": "string",
4317 "description": "When to display the legend. By default, it only appears when a user mouses over the chart. Set it to \"always\" to always display a legend of some sort."
4318 },
4319 "labelsShowZeroValues": {
4320 "default": "true",
4321 "labels": ["Legend"],
a96f59f4 4322 "type": "boolean",
a38e9336
DV
4323 "description": "Show zero value labels in the labelsDiv."
4324 },
4325 "stepPlot": {
a96f59f4 4326 "default": "false",
a38e9336
DV
4327 "labels": ["Data Line display"],
4328 "type": "boolean",
4329 "description": "When set, display the graph as a step plot instead of a line plot."
a96f59f4 4330 },
a38e9336
DV
4331 "labelsKMB": {
4332 "default": "false",
4333 "labels": ["Value display/formatting"],
a96f59f4 4334 "type": "boolean",
a38e9336
DV
4335 "description": "Show K/M/B for thousands/millions/billions on y-axis."
4336 },
4337 "rightGap": {
4338 "default": "5",
4339 "labels": ["Overall display"],
4340 "type": "integer",
4341 "description": "Number of pixels to leave blank at the right edge of the Dygraph. This makes it easier to highlight the right-most data point."
4342 },
4343 "avoidMinZero": {
a96f59f4 4344 "default": "false",
a38e9336
DV
4345 "labels": ["Axis display"],
4346 "type": "boolean",
4347 "description": "When set, the heuristic that fixes the Y axis at zero for a data set with the minimum Y value of zero is disabled. \nThis is particularly useful for data sets that contain many zero values, especially for step plots which may otherwise have lines not visible running along the bottom axis."
4348 },
4349 "xAxisLabelFormatter": {
4350 "default": "Dygraph.dateAxisFormatter",
4351 "labels": ["Axis display", "Value display/formatting"],
4352 "type": "function(date, granularity)",
4353 "description": "Function to call to format values along the x axis."
4354 },
4355 "clickCallback": {
4356 "snippet": "function(e, date){<br>&nbsp;&nbsp;alert(date);<br>}",
4357 "default": "null",
4358 "labels": ["Callbacks"],
4359 "type": "function(e, date)",
4360 "description": "A function to call when a data point is clicked. The function should take two arguments, the event object for the click and the date that was clicked."
4361 },
4362 "yAxisLabelFormatter": {
4363 "default": "yValueFormatter",
4364 "labels": ["Axis display", "Value display/formatting"],
4365 "type": "function(x)",
4366 "description": "Function used to format values along the Y axis. By default it uses the same as the <code>yValueFormatter</code> unless specified."
a96f59f4
DV
4367 },
4368 "labels": {
a96f59f4 4369 "default": "[\"X\", \"Y1\", \"Y2\", ...]*",
a38e9336
DV
4370 "labels": ["Legend"],
4371 "type": "array<string>",
a96f59f4
DV
4372 "description": "A name for each data series, including the independent (X) series. For CSV files and DataTable objections, this is determined by context. For raw data, this must be specified. If it is not, default values are supplied and a warning is logged."
4373 },
a38e9336
DV
4374 "dateWindow": {
4375 "default": "Full range of the input is shown",
4376 "labels": ["Axis display"],
4377 "type": "Array of two Dates or numbers",
4378 "example": "[<br>&nbsp;&nbsp;Date.parse('2006-01-01'),<br>&nbsp;&nbsp;(new Date()).valueOf()<br>]",
4379 "description": "Initially zoom in on a section of the graph. Is of the form [earliest, latest], where earliest/latest are milliseconds since epoch. If the data for the x-axis is numeric, the values in dateWindow must also be numbers."
a96f59f4 4380 },
a38e9336
DV
4381 "showRoller": {
4382 "default": "false",
4383 "labels": ["Interactive Elements", "Rolling Averages"],
4384 "type": "boolean",
4385 "description": "If the rolling average period text box should be shown."
a96f59f4 4386 },
a38e9336
DV
4387 "sigma": {
4388 "default": "2.0",
4389 "labels": ["Error Bars"],
ca49434a 4390 "type": "float",
a38e9336 4391 "description": "When errorBars is set, shade this many standard deviations above/below each point."
a96f59f4 4392 },
a38e9336 4393 "customBars": {
a96f59f4 4394 "default": "false",
a38e9336 4395 "labels": ["CSV parsing", "Error Bars"],
a96f59f4 4396 "type": "boolean",
a38e9336 4397 "description": "When set, parse each CSV cell as \"low;middle;high\". Error bars will be drawn for each point between low and high, with the series itself going through middle."
a96f59f4 4398 },
a38e9336
DV
4399 "colorValue": {
4400 "default": "1.0",
4401 "labels": ["Data Series Colors"],
4402 "type": "float (0.0 - 1.0)",
4403 "description": "If colors is not specified, value of the data series colors, as in hue/saturation/value. (0.0-1.0, default 0.5)"
a96f59f4 4404 },
a38e9336
DV
4405 "errorBars": {
4406 "default": "false",
4407 "labels": ["CSV parsing", "Error Bars"],
a96f59f4 4408 "type": "boolean",
a38e9336 4409 "description": "Does the data contain standard deviations? Setting this to true alters the input format (see above)."
a96f59f4 4410 },
a38e9336
DV
4411 "displayAnnotations": {
4412 "default": "false",
4413 "labels": ["Annotations"],
a96f59f4 4414 "type": "boolean",
a38e9336 4415 "description": "Only applies when Dygraphs is used as a GViz chart. Causes string columns following a data series to be interpreted as annotations on points in that series. This is the same format used by Google's AnnotatedTimeLine chart."
4cac8c7a 4416 },
965a030e 4417 "panEdgeFraction": {
4cac8c7a 4418 "default": "null",
965a030e 4419 "labels": ["Axis Display", "Interactive Elements"],
4cac8c7a
RK
4420 "type": "float",
4421 "default": "null",
4422 "description": "A value representing the farthest a graph may be panned, in percent of the display. For example, a value of 0.1 means that the graph can only be panned 10% pased the edges of the displayed values. null means no bounds."
ca49434a
DV
4423 },
4424 "title": {
4425 "labels": ["Chart labels"],
4426 "type": "string",
4427 "default": "null",
4428 "description": "Text to display above the chart. You can supply any HTML for this value, not just text. If you wish to style it using CSS, use the 'dygraph-label' or 'dygraph-title' classes."
4429 },
4430 "titleHeight": {
4431 "default": "18",
4432 "labels": ["Chart labels"],
4433 "type": "integer",
4434 "description": "Height of the chart title, in pixels. This also controls the default font size of the title. If you style the title on your own, this controls how much space is set aside above the chart for the title's div."
4435 },
4436 "xlabel": {
4437 "labels": ["Chart labels"],
4438 "type": "string",
4439 "default": "null",
4440 "description": "Text to display below the chart's x-axis. You can supply any HTML for this value, not just text. If you wish to style it using CSS, use the 'dygraph-label' or 'dygraph-xlabel' classes."
4441 },
4442 "xLabelHeight": {
4443 "labels": ["Chart labels"],
4444 "type": "integer",
4445 "default": "18",
4446 "description": "Height of the x-axis label, in pixels. This also controls the default font size of the x-axis label. If you style the label on your own, this controls how much space is set aside below the chart for the x-axis label's div."
4447 },
4448 "ylabel": {
4449 "labels": ["Chart labels"],
4450 "type": "string",
4451 "default": "null",
4452 "description": "Text to display to the left of the chart's y-axis. You can supply any HTML for this value, not just text. If you wish to style it using CSS, use the 'dygraph-label' or 'dygraph-ylabel' classes. The text will be rotated 90 degrees by default, so CSS rules may behave in unintuitive ways. No additional space is set aside for a y-axis label. If you need more space, increase the width of the y-axis tick labels using the yAxisLabelWidth option. If you need a wider div for the y-axis label, either style it that way with CSS (but remember that it's rotated, so width is controlled by the 'height' property) or set the yLabelWidth option."
4453 },
4454 "yLabelWidth": {
4455 "labels": ["Chart labels"],
4456 "type": "integer",
4457 "default": "18",
4458 "description": "Width of the div which contains the y-axis label. Since the y-axis label appears rotated 90 degrees, this actually affects the height of its div."
5bc3e265 4459 },
e5152598
NN
4460 "isZoomedIgnoreProgrammaticZoom" : {
4461 "default": "false",
4462 "labels": ["Zooming"],
4463 "type": "boolean",
36dfa958 4464 "description" : "When this option is passed to updateOptions() along with either the <code>dateWindow</code> or <code>valueRange</code> options, the zoom flags are not changed to reflect a zoomed state. This is primarily useful for when the display area of a chart is changed programmatically and also where manual zooming is allowed and use is made of the <code>isZoomed</code> method to determine this."
17d0210c 4465 },
990d6a35
DV
4466 "drawXGrid": {
4467 "default": "true",
4468 "labels": ["Grid"],
4469 "type": "boolean",
4470 "description" : "Whether to display vertical gridlines under the chart."
4471 },
4472 "drawYGrid": {
4473 "default": "true",
4474 "labels": ["Grid"],
4475 "type": "boolean",
4476 "description" : "Whether to display horizontal gridlines under the chart."
4477 },
4478 "drawXAxis": {
4479 "default": "true",
4480 "labels": ["Axis display"],
4481 "type": "boolean",
4482 "description" : "Whether to draw the x-axis. Setting this to false also prevents x-axis ticks from being drawn and reclaims the space for the chart grid/lines."
4483 },
4484 "drawYAxis": {
4485 "default": "true",
4486 "labels": ["Axis display"],
4487 "type": "boolean",
4488 "description" : "Whether to draw the y-axis. Setting this to false also prevents y-axis ticks from being drawn and reclaims the space for the chart grid/lines."
4489 },
4490 "gridLineWidth": {
4491 "default": "0.3",
4492 "labels": ["Grid"],
4493 "type": "float",
4494 "description" : "Thickness (in pixels) of the gridlines drawn under the chart. The vertical/horizontal gridlines can be turned off entirely by using the drawXGrid and drawYGrid options."
4495 },
4496 "axisLineWidth": {
4497 "default": "0.3",
4498 "labels": ["Axis display"],
4499 "type": "float",
4500 "description" : "Thickness (in pixels) of the x- and y-axis lines."
4501 },
4502 "axisLineColor": {
4503 "default": "black",
4504 "labels": ["Axis display"],
4505 "type": "string",
4506 "description" : "Color of the x- and y-axis lines. Accepts any value which the HTML canvas strokeStyle attribute understands, e.g. 'black' or 'rgb(0, 100, 255)'."
4507 },
4508 "fillAlpha": {
4509 "default": "0.15",
e829f52c 4510 "labels": ["Error bars", "Data Series Colors"],
990d6a35
DV
4511 "type": "float (0.0 - 1.0)",
4512 "description" : "Error bars (or custom bars) for each series are drawn in the same color as the series, but with partial transparency. This sets the transparency. A value of 0.0 means that the error bars will not be drawn, whereas a value of 1.0 means that the error bars will be as dark as the line for the series itself. This can be used to produce chart lines whose thickness varies at each point."
4513 },
4514 "axisLabelColor": {
4515 "default": "black",
4516 "labels": ["Axis display"],
4517 "type": "string",
4518 "description" : "Color for x- and y-axis labels. This is a CSS color string."
4519 },
4520 "axisLabelWidth": {
4521 "default": "50",
6beca822 4522 "labels": ["Axis display", "Chart labels"],
990d6a35
DV
4523 "type": "integer",
4524 "description" : "Width (in pixels) of the containing divs for x- and y-axis labels. For the y-axis, this also controls "
4525 },
17d0210c
DV
4526 "sigFigs" : {
4527 "default": "null",
4528 "labels": ["Value display/formatting"],
4529 "type": "integer",
4530 "description": "By default, dygraphs displays numbers with a fixed number of digits after the decimal point. If you'd prefer to have a fixed number of significant figures, set this option to that number of sig figs. A value of 2, for instance, would cause 1 to be display as 1.0 and 1234 to be displayed as 1.23e+3."
4531 },
4532 "digitsAfterDecimal" : {
4533 "default": "2",
4534 "labels": ["Value display/formatting"],
4535 "type": "integer",
4536 "description": "Unless it's run in scientific mode (see the <code>sigFigs</code> option), dygraphs displays numbers with <code>digitsAfterDecimal</code> digits after the decimal point. Trailing zeros are not displayed, so with a value of 2 you'll get '0', '0.1', '0.12', '123.45' but not '123.456' (it will be rounded to '123.46'). Numbers with absolute value less than 0.1^digitsAfterDecimal (i.e. those which would show up as '0.00') will be displayed in scientific notation."
4537 },
4538 "maxNumberWidth" : {
4539 "default": "6",
4540 "labels": ["Value display/formatting"],
4541 "type": "integer",
4542 "description": "When displaying numbers in normal (not scientific) mode, large numbers will be displayed with many trailing zeros (e.g. 100000000 instead of 1e9). This can lead to unwieldy y-axis labels. If there are more than <code>maxNumberWidth</code> digits to the left of the decimal in a number, dygraphs will switch to scientific notation, even when not operating in scientific mode. If you'd like to see all those digits, set this to something large, like 20 or 30."
e829f52c
DV
4543 },
4544 "file": {
4545 "default": "(set when constructed)",
4546 "labels": ["Data"],
4547 "type": "string (URL of CSV or CSV), GViz DataTable or 2D Array",
4548 "description": "Sets the data being displayed in the chart. This can only be set when calling updateOptions; it cannot be set from the constructor. For a full description of valid data formats, see the <a href='http://dygraphs.com/data.html'>Data Formats</a> page."
028ddf8a 4549 }
0addac07
DV
4550}
4551; // </JSON>
4552// NOTE: in addition to parsing as JS, this snippet is expected to be valid
4553// JSON. This assumption cannot be checked in JS, but it will be checked when
ca49434a
DV
4554// documentation is generated by the generate-documentation.py script. For the
4555// most part, this just means that you should always use double quotes.
028ddf8a
DV
4556
4557// Do a quick sanity check on the options reference.
4558(function() {
4559 var warn = function(msg) { if (console) console.warn(msg); };
4560 var flds = ['type', 'default', 'description'];
a38e9336
DV
4561 var valid_cats = [
4562 'Annotations',
4563 'Axis display',
ca49434a 4564 'Chart labels',
a38e9336
DV
4565 'CSV parsing',
4566 'Callbacks',
e829f52c 4567 'Data',
a38e9336
DV
4568 'Data Line display',
4569 'Data Series Colors',
4570 'Error Bars',
4571 'Grid',
4572 'Interactive Elements',
4573 'Legend',
4574 'Overall display',
4575 'Rolling Averages',
36dfa958
DV
4576 'Value display/formatting',
4577 'Zooming'
a38e9336
DV
4578 ];
4579 var cats = {};
4580 for (var i = 0; i < valid_cats.length; i++) cats[valid_cats[i]] = true;
4581
028ddf8a
DV
4582 for (var k in Dygraph.OPTIONS_REFERENCE) {
4583 if (!Dygraph.OPTIONS_REFERENCE.hasOwnProperty(k)) continue;
4584 var op = Dygraph.OPTIONS_REFERENCE[k];
4585 for (var i = 0; i < flds.length; i++) {
4586 if (!op.hasOwnProperty(flds[i])) {
4587 warn('Option ' + k + ' missing "' + flds[i] + '" property');
4588 } else if (typeof(op[flds[i]]) != 'string') {
4589 warn(k + '.' + flds[i] + ' must be of type string');
4590 }
4591 }
a38e9336
DV
4592 var labels = op['labels'];
4593 if (typeof(labels) !== 'object') {
4594 warn('Option "' + k + '" is missing a "labels": [...] option');
4595 for (var i = 0; i < labels.length; i++) {
4596 if (!cats.hasOwnProperty(labels[i])) {
4597 warn('Option "' + k + '" has label "' + labels[i] +
4598 '", which is invalid.');
4599 }
4600 }
4601 }
028ddf8a
DV
4602 }
4603})();
4604// </REMOVE_FOR_COMBINED>