re-add 'validate eventName' TODO.
[dygraphs.git] / dygraph.js
CommitLineData
88e95c46
DV
1/**
2 * @license
3 * Copyright 2006 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
5 */
6a1aa64f
DV
6
7/**
8 * @fileoverview Creates an interactive, zoomable graph based on a CSV file or
285a6bda
DV
9 * string. Dygraph can handle multiple series with or without error bars. The
10 * date/value ranges will be automatically set. Dygraph uses the
6a1aa64f
DV
11 * <canvas> tag, so it only works in FF1.5+.
12 * @author danvdk@gmail.com (Dan Vanderkam)
13
14 Usage:
15 <div id="graphdiv" style="width:800px; height:500px;"></div>
16 <script type="text/javascript">
285a6bda
DV
17 new Dygraph(document.getElementById("graphdiv"),
18 "datafile.csv", // CSV file with headers
19 { }); // options
6a1aa64f
DV
20 </script>
21
22 The CSV file is of the form
23
285a6bda 24 Date,SeriesA,SeriesB,SeriesC
6a1aa64f
DV
25 YYYYMMDD,A1,B1,C1
26 YYYYMMDD,A2,B2,C2
27
6a1aa64f
DV
28 If the 'errorBars' option is set in the constructor, the input should be of
29 the form
285a6bda 30 Date,SeriesA,SeriesB,...
6a1aa64f
DV
31 YYYYMMDD,A1,sigmaA1,B1,sigmaB1,...
32 YYYYMMDD,A2,sigmaA2,B2,sigmaB2,...
33
34 If the 'fractions' option is set, the input should be of the form:
35
285a6bda 36 Date,SeriesA,SeriesB,...
6a1aa64f
DV
37 YYYYMMDD,A1/B1,A2/B2,...
38 YYYYMMDD,A1/B1,A2/B2,...
39
40 And error bars will be calculated automatically using a binomial distribution.
41
727439b4 42 For further documentation and examples, see http://dygraphs.com/
6a1aa64f
DV
43
44 */
45
758a629f
DV
46/*jshint globalstrict: true */
47/*global DygraphRangeSelector:false, DygraphLayout:false, DygraphCanvasRenderer:false, G_vmlCanvasManager:false */
c0f54d4f
DV
48"use strict";
49
6a1aa64f 50/**
629a09ae
DV
51 * Creates an interactive, zoomable chart.
52 *
53 * @constructor
54 * @param {div | String} div A div or the id of a div into which to construct
55 * the chart.
56 * @param {String | Function} file A file containing CSV data or a function
57 * that returns this data. The most basic expected format for each line is
58 * "YYYY/MM/DD,val1,val2,...". For more information, see
59 * http://dygraphs.com/data.html.
6a1aa64f 60 * @param {Object} attrs Various other attributes, e.g. errorBars determines
629a09ae
DV
61 * whether the input data contains error ranges. For a complete list of
62 * options, see http://dygraphs.com/options.html.
6a1aa64f 63 */
86a3e64f
DV
64var Dygraph = function(div, data, opts, opt_fourth_param) {
65 if (opt_fourth_param !== undefined) {
66 // Old versions of dygraphs took in the series labels as a constructor
67 // parameter. This doesn't make sense anymore, but it's easy to continue
68 // to support this usage.
69 this.warn("Using deprecated four-argument dygraph constructor");
70 this.__old_init__(div, data, opts, opt_fourth_param);
71 } else {
72 this.__init__(div, data, opts);
285a6bda 73 }
6a1aa64f
DV
74};
75
285a6bda
DV
76Dygraph.NAME = "Dygraph";
77Dygraph.VERSION = "1.2";
78Dygraph.__repr__ = function() {
6a1aa64f
DV
79 return "[" + this.NAME + " " + this.VERSION + "]";
80};
629a09ae
DV
81
82/**
83 * Returns information about the Dygraph class.
84 */
285a6bda 85Dygraph.toString = function() {
6a1aa64f
DV
86 return this.__repr__();
87};
88
89// Various default values
285a6bda
DV
90Dygraph.DEFAULT_ROLL_PERIOD = 1;
91Dygraph.DEFAULT_WIDTH = 480;
92Dygraph.DEFAULT_HEIGHT = 320;
6a1aa64f 93
b1a3b195
DV
94Dygraph.ANIMATION_STEPS = 10;
95Dygraph.ANIMATION_DURATION = 200;
96
48e614ac
DV
97// These are defined before DEFAULT_ATTRS so that it can refer to them.
98/**
99 * @private
100 * Return a string version of a number. This respects the digitsAfterDecimal
101 * and maxNumberWidth options.
102 * @param {Number} x The number to be formatted
103 * @param {Dygraph} opts An options view
104 * @param {String} name The name of the point's data series
105 * @param {Dygraph} g The dygraph object
106 */
107Dygraph.numberValueFormatter = function(x, opts, pt, g) {
108 var sigFigs = opts('sigFigs');
109
110 if (sigFigs !== null) {
111 // User has opted for a fixed number of significant figures.
112 return Dygraph.floatFormat(x, sigFigs);
113 }
114
115 var digits = opts('digitsAfterDecimal');
116 var maxNumberWidth = opts('maxNumberWidth');
117
118 // switch to scientific notation if we underflow or overflow fixed display.
119 if (x !== 0.0 &&
120 (Math.abs(x) >= Math.pow(10, maxNumberWidth) ||
121 Math.abs(x) < Math.pow(10, -digits))) {
122 return x.toExponential(digits);
123 } else {
124 return '' + Dygraph.round_(x, digits);
125 }
126};
127
128/**
129 * variant for use as an axisLabelFormatter.
130 * @private
131 */
132Dygraph.numberAxisLabelFormatter = function(x, granularity, opts, g) {
133 return Dygraph.numberValueFormatter(x, opts, g);
134};
135
136/**
137 * Convert a JS date (millis since epoch) to YYYY/MM/DD
138 * @param {Number} date The JavaScript date (ms since epoch)
139 * @return {String} A date of the form "YYYY/MM/DD"
140 * @private
141 */
142Dygraph.dateString_ = function(date) {
143 var zeropad = Dygraph.zeropad;
144 var d = new Date(date);
145
146 // Get the year:
147 var year = "" + d.getFullYear();
148 // Get a 0 padded month string
149 var month = zeropad(d.getMonth() + 1); //months are 0-offset, sigh
150 // Get a 0 padded day string
151 var day = zeropad(d.getDate());
152
153 var ret = "";
154 var frac = d.getHours() * 3600 + d.getMinutes() * 60 + d.getSeconds();
155 if (frac) ret = " " + Dygraph.hmsString_(date);
156
157 return year + "/" + month + "/" + day + ret;
158};
159
160/**
161 * Convert a JS date to a string appropriate to display on an axis that
162 * is displaying values at the stated granularity.
163 * @param {Date} date The date to format
164 * @param {Number} granularity One of the Dygraph granularity constants
165 * @return {String} The formatted date
166 * @private
167 */
168Dygraph.dateAxisFormatter = function(date, granularity) {
169 if (granularity >= Dygraph.DECADAL) {
170 return date.strftime('%Y');
171 } else if (granularity >= Dygraph.MONTHLY) {
172 return date.strftime('%b %y');
173 } else {
174 var frac = date.getHours() * 3600 + date.getMinutes() * 60 + date.getSeconds() + date.getMilliseconds();
758a629f 175 if (frac === 0 || granularity >= Dygraph.DAILY) {
48e614ac
DV
176 return new Date(date.getTime() + 3600*1000).strftime('%d%b');
177 } else {
178 return Dygraph.hmsString_(date.getTime());
179 }
180 }
181};
182
183
8e4a6af3 184// Default attribute values.
285a6bda 185Dygraph.DEFAULT_ATTRS = {
a9fc39ab 186 highlightCircleSize: 3,
857a6931 187 highlightSeriesOpts: null,
afdb20d8 188 highlightSeriesBackgroundAlpha: 0.5,
285a6bda 189
8e4a6af3
DV
190 labelsDivWidth: 250,
191 labelsDivStyles: {
192 // TODO(danvk): move defaults from createStatusMessage_ here.
285a6bda
DV
193 },
194 labelsSeparateLines: false,
bcd3ebf0 195 labelsShowZeroValues: true,
285a6bda 196 labelsKMB: false,
afefbcdb 197 labelsKMG2: false,
d160cc3b 198 showLabelsOnHighlight: true,
12e4c741 199
2e1fcf1a
DV
200 digitsAfterDecimal: 2,
201 maxNumberWidth: 6,
19589a3e 202 sigFigs: null,
285a6bda
DV
203
204 strokeWidth: 1.0,
857a6931
KW
205 strokeBorderWidth: 0,
206 strokeBorderColor: "white",
8e4a6af3 207
8846615a
DV
208 axisTickSize: 3,
209 axisLabelFontSize: 14,
210 xAxisLabelWidth: 50,
211 yAxisLabelWidth: 50,
212 rightGap: 5,
285a6bda
DV
213
214 showRoller: false,
285a6bda 215 xValueParser: Dygraph.dateParser,
285a6bda 216
3d67f03b
DV
217 delimiter: ',',
218
285a6bda
DV
219 sigma: 2.0,
220 errorBars: false,
221 fractions: false,
222 wilsonInterval: true, // only relevant if fractions is true
5954ef32 223 customBars: false,
43af96e7
NK
224 fillGraph: false,
225 fillAlpha: 0.15,
f032c51d 226 connectSeparatedPoints: false,
43af96e7
NK
227
228 stackedGraph: false,
afdc483f
NN
229 hideOverlayOnMouseOut: true,
230
2fccd3dc
DV
231 // TODO(danvk): support 'onmouseover' and 'never', and remove synonyms.
232 legend: 'onmouseover', // the only relevant value at the moment is 'always'.
233
00c281d4 234 stepPlot: false,
062ef401
JB
235 avoidMinZero: false,
236
ad1798c2 237 // Sizes of the various chart labels.
b4202b3d 238 titleHeight: 28,
86cce9e8
DV
239 xLabelHeight: 18,
240 yLabelWidth: 18,
ad1798c2 241
423f5ed3
DV
242 drawXAxis: true,
243 drawYAxis: true,
244 axisLineColor: "black",
990d6a35
DV
245 axisLineWidth: 0.3,
246 gridLineWidth: 0.3,
247 axisLabelColor: "black",
248 axisLabelFont: "Arial", // TODO(danvk): is this implemented?
249 axisLabelWidth: 50,
250 drawYGrid: true,
251 drawXGrid: true,
252 gridLineColor: "rgb(128,128,128)",
423f5ed3 253
48e614ac 254 interactionModel: null, // will be set to Dygraph.Interaction.defaultModel
b1a3b195 255 animatedZooms: false, // (for now)
48e614ac 256
ccd9d7c2
PF
257 // Range selector options
258 showRangeSelector: false,
259 rangeSelectorHeight: 40,
260 rangeSelectorPlotStrokeColor: "#808FAB",
261 rangeSelectorPlotFillColor: "#A7B1C4",
262
48e614ac
DV
263 // per-axis options
264 axes: {
265 x: {
266 pixelsPerLabel: 60,
267 axisLabelFormatter: Dygraph.dateAxisFormatter,
268 valueFormatter: Dygraph.dateString_,
269 ticker: null // will be set in dygraph-tickers.js
270 },
271 y: {
272 pixelsPerLabel: 30,
273 valueFormatter: Dygraph.numberValueFormatter,
274 axisLabelFormatter: Dygraph.numberAxisLabelFormatter,
275 ticker: null // will be set in dygraph-tickers.js
276 },
277 y2: {
278 pixelsPerLabel: 30,
279 valueFormatter: Dygraph.numberValueFormatter,
280 axisLabelFormatter: Dygraph.numberAxisLabelFormatter,
281 ticker: null // will be set in dygraph-tickers.js
282 }
283 }
285a6bda
DV
284};
285
39b0e098
RK
286// Directions for panning and zooming. Use bit operations when combined
287// values are possible.
288Dygraph.HORIZONTAL = 1;
289Dygraph.VERTICAL = 2;
290
e2c21500
DV
291// Installed plugins, in order of precedence (most-general to most-specific).
292// Plugins are installed after they are defined, in plugins/install.js.
293Dygraph.PLUGINS = [
294];
295
5c528fa2
DV
296// Used for initializing annotation CSS rules only once.
297Dygraph.addedAnnotationCSS = false;
298
285a6bda
DV
299Dygraph.prototype.__old_init__ = function(div, file, labels, attrs) {
300 // Labels is no longer a constructor parameter, since it's typically set
301 // directly from the data source. It also conains a name for the x-axis,
302 // which the previous constructor form did not.
758a629f 303 if (labels !== null) {
285a6bda
DV
304 var new_labels = ["Date"];
305 for (var i = 0; i < labels.length; i++) new_labels.push(labels[i]);
fc80a396 306 Dygraph.update(attrs, { 'labels': new_labels });
285a6bda
DV
307 }
308 this.__init__(div, file, attrs);
8e4a6af3
DV
309};
310
6a1aa64f 311/**
285a6bda 312 * Initializes the Dygraph. This creates a new DIV and constructs the PlotKit
7aedf6fe 313 * and context &lt;canvas&gt; inside of it. See the constructor for details.
6a1aa64f 314 * on the parameters.
12e4c741 315 * @param {Element} div the Element to render the graph into.
6a1aa64f 316 * @param {String | Function} file Source data
6a1aa64f
DV
317 * @param {Object} attrs Miscellaneous other options
318 * @private
319 */
285a6bda 320Dygraph.prototype.__init__ = function(div, file, attrs) {
a2c8fff4
DV
321 // Hack for IE: if we're using excanvas and the document hasn't finished
322 // loading yet (and hence may not have initialized whatever it needs to
323 // initialize), then keep calling this routine periodically until it has.
324 if (/MSIE/.test(navigator.userAgent) && !window.opera &&
325 typeof(G_vmlCanvasManager) != 'undefined' &&
326 document.readyState != 'complete') {
327 var self = this;
758a629f 328 setTimeout(function() { self.__init__(div, file, attrs); }, 100);
ccd9d7c2 329 return;
a2c8fff4
DV
330 }
331
285a6bda 332 // Support two-argument constructor
758a629f 333 if (attrs === null || attrs === undefined) { attrs = {}; }
285a6bda 334
48e614ac
DV
335 attrs = Dygraph.mapLegacyOptions_(attrs);
336
337 if (!div) {
338 Dygraph.error("Constructing dygraph with a non-existent div!");
339 return;
340 }
341
920208fb
PF
342 this.isUsingExcanvas_ = typeof(G_vmlCanvasManager) != 'undefined';
343
6a1aa64f 344 // Copy the important bits into the object
32988383 345 // TODO(danvk): most of these should just stay in the attrs_ dictionary.
6a1aa64f 346 this.maindiv_ = div;
6a1aa64f 347 this.file_ = file;
285a6bda 348 this.rollPeriod_ = attrs.rollPeriod || Dygraph.DEFAULT_ROLL_PERIOD;
6a1aa64f 349 this.previousVerticalX_ = -1;
6a1aa64f 350 this.fractions_ = attrs.fractions || false;
6a1aa64f 351 this.dateWindow_ = attrs.dateWindow || null;
8b83c6cc 352
fe0b7c03 353 this.is_initial_draw_ = true;
5c528fa2 354 this.annotations_ = [];
7aedf6fe 355
45f2c689 356 // Zoomed indicators - These indicate when the graph has been zoomed and on what axis.
57baab03
NN
357 this.zoomed_x_ = false;
358 this.zoomed_y_ = false;
45f2c689 359
f7d6278e
DV
360 // Clear the div. This ensure that, if multiple dygraphs are passed the same
361 // div, then only one will be drawn.
362 div.innerHTML = "";
363
0cb9bd91
DV
364 // For historical reasons, the 'width' and 'height' options trump all CSS
365 // rules _except_ for an explicit 'width' or 'height' on the div.
366 // As an added convenience, if the div has zero height (like <div></div> does
367 // without any styles), then we use a default height/width.
758a629f 368 if (div.style.width === '' && attrs.width) {
0cb9bd91 369 div.style.width = attrs.width + "px";
285a6bda 370 }
758a629f 371 if (div.style.height === '' && attrs.height) {
0cb9bd91 372 div.style.height = attrs.height + "px";
32988383 373 }
758a629f 374 if (div.style.height === '' && div.clientHeight === 0) {
0cb9bd91 375 div.style.height = Dygraph.DEFAULT_HEIGHT + "px";
758a629f 376 if (div.style.width === '') {
0cb9bd91
DV
377 div.style.width = Dygraph.DEFAULT_WIDTH + "px";
378 }
c21d2c2d 379 }
fffad740 380 // these will be zero if the dygraph's div is hidden.
ccd9d7c2
PF
381 this.width_ = div.clientWidth;
382 this.height_ = div.clientHeight;
32988383 383
344ba8c0 384 // TODO(danvk): set fillGraph to be part of attrs_ here, not user_attrs_.
758a629f
DV
385 if (attrs.stackedGraph) {
386 attrs.fillGraph = true;
43af96e7
NK
387 // TODO(nikhilk): Add any other stackedGraph checks here.
388 }
389
285a6bda
DV
390 // Dygraphs has many options, some of which interact with one another.
391 // To keep track of everything, we maintain two sets of options:
392 //
c21d2c2d 393 // this.user_attrs_ only options explicitly set by the user.
285a6bda
DV
394 // this.attrs_ defaults, options derived from user_attrs_, data.
395 //
396 // Options are then accessed this.attr_('attr'), which first looks at
397 // user_attrs_ and then computed attrs_. This way Dygraphs can set intelligent
398 // defaults without overriding behavior that the user specifically asks for.
399 this.user_attrs_ = {};
fc80a396 400 Dygraph.update(this.user_attrs_, attrs);
6a1aa64f 401
48e614ac 402 // This sequence ensures that Dygraph.DEFAULT_ATTRS is never modified.
285a6bda 403 this.attrs_ = {};
48e614ac 404 Dygraph.updateDeep(this.attrs_, Dygraph.DEFAULT_ATTRS);
6a1aa64f 405
16269f6e 406 this.boundaryIds_ = [];
82c6fe4d 407 this.setIndexByName_ = {};
857a6931 408 this.datasetIndex_ = [];
6a1aa64f 409
6a1aa64f
DV
410 // Create the containing DIV and other interactive elements
411 this.createInterface_();
412
e2c21500
DV
413 // Activate plugins.
414 this.plugins_ = [];
415 for (var i = 0; i < Dygraph.PLUGINS.length; i++) {
416 var plugin = Dygraph.PLUGINS[i];
417 var pluginInstance = new plugin();
418 var pluginDict = {
419 plugin: pluginInstance,
420 events: {},
421 options: {},
422 pluginOptions: {}
423 };
424
6a4457b4
KW
425 var handlers = pluginInstance.activate(this);
426 for (var eventName in handlers) {
28aa77ac 427 // TODO(danvk): validate eventName.
6a4457b4
KW
428 pluginDict.events[eventName] = handlers[eventName];
429 }
e2c21500
DV
430
431 this.plugins_.push(pluginDict);
432 }
433
434 // At this point, plugins can no longer register event handlers.
435 // Construct a map from event -> ordered list of [callback, plugin].
436 this.eventListeners_ = {};
437 for (var i = 0; i < this.plugins_.length; i++) {
438 var plugin_dict = this.plugins_[i];
439 for (var eventName in plugin_dict.events) {
440 if (!plugin_dict.events.hasOwnProperty(eventName)) continue;
441 var callback = plugin_dict.events[eventName];
442
443 var pair = [plugin_dict.plugin, callback];
444 if (!(eventName in this.eventListeners_)) {
445 this.eventListeners_[eventName] = [pair];
446 } else {
447 this.eventListeners_[eventName].push(pair);
448 }
449 }
450 }
451
738fc797 452 this.start_();
6a1aa64f
DV
453};
454
dcb25130 455/**
e2c21500
DV
456 * Triggers a cascade of events to the various plugins which are interested in them.
457 * Returns true if the "default behavior" should be performed, i.e. if none of
458 * the event listeners called event.preventDefault().
459 * @private
460 */
461Dygraph.prototype.cascadeEvents_ = function(name, extra_props) {
462 if (!name in this.eventListeners_) return true;
463
464 // QUESTION: can we use objects & prototypes to speed this up?
465 var e = {
466 dygraph: this,
467 cancelable: false,
468 defaultPrevented: false,
469 preventDefault: function() {
470 if (!e.cancelable) throw "Cannot call preventDefault on non-cancelable event.";
471 e.defaultPrevented = true;
472 },
473 propagationStopped: false,
474 stopPropagation: function() {
5bd29cf4 475 e.propagationStopped = true;
e2c21500
DV
476 }
477 };
478 Dygraph.update(e, extra_props);
479
480 var callback_plugin_pairs = this.eventListeners_[name];
da1c187b
KW
481 if (callback_plugin_pairs) {
482 for (var i = callback_plugin_pairs.length - 1; i >= 0; i--) {
483 var plugin = callback_plugin_pairs[i][0];
484 var callback = callback_plugin_pairs[i][1];
485 callback.call(plugin, e);
486 if (e.propagationStopped) break;
487 }
e2c21500
DV
488 }
489 return e.defaultPrevented;
490};
491
492/**
dcb25130
NN
493 * Returns the zoomed status of the chart for one or both axes.
494 *
495 * Axis is an optional parameter. Can be set to 'x' or 'y'.
496 *
497 * The zoomed status for an axis is set whenever a user zooms using the mouse
e5152598 498 * or when the dateWindow or valueRange are updated (unless the isZoomedIgnoreProgrammaticZoom
dcb25130
NN
499 * option is also specified).
500 */
57baab03 501Dygraph.prototype.isZoomed = function(axis) {
94ea5744 502 if (axis == null) return this.zoomed_x_ || this.zoomed_y_;
758a629f
DV
503 if (axis === 'x') return this.zoomed_x_;
504 if (axis === 'y') return this.zoomed_y_;
94ea5744 505 throw "axis parameter is [" + axis + "] must be null, 'x' or 'y'.";
57baab03
NN
506};
507
629a09ae
DV
508/**
509 * Returns information about the Dygraph object, including its containing ID.
510 */
22bd1dfb
RK
511Dygraph.prototype.toString = function() {
512 var maindiv = this.maindiv_;
758a629f 513 var id = (maindiv && maindiv.id) ? maindiv.id : maindiv;
22bd1dfb 514 return "[Dygraph " + id + "]";
758a629f 515};
22bd1dfb 516
629a09ae
DV
517/**
518 * @private
519 * Returns the value of an option. This may be set by the user (either in the
520 * constructor or by calling updateOptions) or by dygraphs, and may be set to a
521 * per-series value.
522 * @param { String } name The name of the option, e.g. 'rollPeriod'.
523 * @param { String } [seriesName] The name of the series to which the option
524 * will be applied. If no per-series value of this option is available, then
525 * the global value is returned. This is optional.
526 * @return { ... } The value of the option.
527 */
227b93cc 528Dygraph.prototype.attr_ = function(name, seriesName) {
028ddf8a
DV
529// <REMOVE_FOR_COMBINED>
530 if (typeof(Dygraph.OPTIONS_REFERENCE) === 'undefined') {
531 this.error('Must include options reference JS for testing');
532 } else if (!Dygraph.OPTIONS_REFERENCE.hasOwnProperty(name)) {
533 this.error('Dygraphs is using property ' + name + ', which has no entry ' +
534 'in the Dygraphs.OPTIONS_REFERENCE listing.');
535 // Only log this error once.
536 Dygraph.OPTIONS_REFERENCE[name] = true;
537 }
538// </REMOVE_FOR_COMBINED>
857a6931
KW
539
540 var sources = [];
541 sources.push(this.attrs_);
475f7420
KW
542 if (this.user_attrs_) {
543 sources.push(this.user_attrs_);
544 if (seriesName) {
545 if (this.user_attrs_.hasOwnProperty(seriesName)) {
546 sources.push(this.user_attrs_[seriesName]);
547 }
548 if (seriesName === this.highlightSet_ &&
549 this.user_attrs_.hasOwnProperty('highlightSeriesOpts')) {
550 sources.push(this.user_attrs_['highlightSeriesOpts']);
551 }
857a6931 552 }
285a6bda 553 }
857a6931
KW
554
555 var ret = null;
556 for (var i = sources.length - 1; i >= 0; --i) {
557 var source = sources[i];
558 if (source.hasOwnProperty(name)) {
559 ret = source[name];
560 break;
561 }
285a6bda 562 }
857a6931 563 return ret;
285a6bda
DV
564};
565
6a1aa64f 566/**
e2c21500
DV
567 * Returns the current value for an option, as set in the constructor or via
568 * updateOptions. You may pass in an (optional) series name to get per-series
569 * values for the option.
570 *
571 * All values returned by this method should be considered immutable. If you
572 * modify them, there is no guarantee that the changes will be honored or that
573 * dygraphs will remain in a consistent state. If you want to modify an option,
574 * use updateOptions() instead.
575 *
576 * @param { String } name The name of the option (e.g. 'strokeWidth')
577 * @param { String } [opt_seriesName] Series name to get per-series values.
578 * @return { ... } The value of the option.
579 */
580Dygraph.prototype.getOption = function(name, opt_seriesName) {
581 return this.attr_(name, opt_seriesName);
582};
583
584/**
48e614ac
DV
585 * @private
586 * @param String} axis The name of the axis (i.e. 'x', 'y' or 'y2')
587 * @return { ... } A function mapping string -> option value
588 */
589Dygraph.prototype.optionsViewForAxis_ = function(axis) {
590 var self = this;
591 return function(opt) {
758a629f 592 var axis_opts = self.user_attrs_.axes;
48e614ac
DV
593 if (axis_opts && axis_opts[axis] && axis_opts[axis][opt]) {
594 return axis_opts[axis][opt];
595 }
596 // user-specified attributes always trump defaults, even if they're less
597 // specific.
598 if (typeof(self.user_attrs_[opt]) != 'undefined') {
599 return self.user_attrs_[opt];
600 }
601
758a629f 602 axis_opts = self.attrs_.axes;
48e614ac
DV
603 if (axis_opts && axis_opts[axis] && axis_opts[axis][opt]) {
604 return axis_opts[axis][opt];
605 }
606 // check old-style axis options
607 // TODO(danvk): add a deprecation warning if either of these match.
608 if (axis == 'y' && self.axes_[0].hasOwnProperty(opt)) {
609 return self.axes_[0][opt];
610 } else if (axis == 'y2' && self.axes_[1].hasOwnProperty(opt)) {
611 return self.axes_[1][opt];
612 }
613 return self.attr_(opt);
614 };
615};
616
617/**
6a1aa64f 618 * Returns the current rolling period, as set by the user or an option.
6faebb69 619 * @return {Number} The number of points in the rolling window
6a1aa64f 620 */
285a6bda 621Dygraph.prototype.rollPeriod = function() {
6a1aa64f 622 return this.rollPeriod_;
76171648
DV
623};
624
599fb4ad
DV
625/**
626 * Returns the currently-visible x-range. This can be affected by zooming,
627 * panning or a call to updateOptions.
628 * Returns a two-element array: [left, right].
629 * If the Dygraph has dates on the x-axis, these will be millis since epoch.
630 */
631Dygraph.prototype.xAxisRange = function() {
4cac8c7a
RK
632 return this.dateWindow_ ? this.dateWindow_ : this.xAxisExtremes();
633};
599fb4ad 634
4cac8c7a
RK
635/**
636 * Returns the lower- and upper-bound x-axis values of the
637 * data set.
638 */
639Dygraph.prototype.xAxisExtremes = function() {
599fb4ad
DV
640 var left = this.rawData_[0][0];
641 var right = this.rawData_[this.rawData_.length - 1][0];
642 return [left, right];
643};
644
3230c662 645/**
d58ae307
DV
646 * Returns the currently-visible y-range for an axis. This can be affected by
647 * zooming, panning or a call to updateOptions. Axis indices are zero-based. If
648 * called with no arguments, returns the range of the first axis.
3230c662
DV
649 * Returns a two-element array: [bottom, top].
650 */
d58ae307 651Dygraph.prototype.yAxisRange = function(idx) {
d63e6799 652 if (typeof(idx) == "undefined") idx = 0;
d64b8fea
RK
653 if (idx < 0 || idx >= this.axes_.length) {
654 return null;
655 }
656 var axis = this.axes_[idx];
657 return [ axis.computedValueRange[0], axis.computedValueRange[1] ];
d58ae307
DV
658};
659
660/**
661 * Returns the currently-visible y-ranges for each axis. This can be affected by
662 * zooming, panning, calls to updateOptions, etc.
663 * Returns an array of [bottom, top] pairs, one for each y-axis.
664 */
665Dygraph.prototype.yAxisRanges = function() {
666 var ret = [];
667 for (var i = 0; i < this.axes_.length; i++) {
668 ret.push(this.yAxisRange(i));
669 }
670 return ret;
3230c662
DV
671};
672
d58ae307 673// TODO(danvk): use these functions throughout dygraphs.
3230c662
DV
674/**
675 * Convert from data coordinates to canvas/div X/Y coordinates.
d58ae307
DV
676 * If specified, do this conversion for the coordinate system of a particular
677 * axis. Uses the first axis by default.
3230c662 678 * Returns a two-element array: [X, Y]
ff022deb 679 *
0747928a 680 * Note: use toDomXCoord instead of toDomCoords(x, null) and use toDomYCoord
ff022deb 681 * instead of toDomCoords(null, y, axis).
3230c662 682 */
d58ae307 683Dygraph.prototype.toDomCoords = function(x, y, axis) {
ff022deb
RK
684 return [ this.toDomXCoord(x), this.toDomYCoord(y, axis) ];
685};
686
687/**
688 * Convert from data x coordinates to canvas/div X coordinate.
689 * If specified, do this conversion for the coordinate system of a particular
0037b2a4
RK
690 * axis.
691 * Returns a single value or null if x is null.
ff022deb
RK
692 */
693Dygraph.prototype.toDomXCoord = function(x) {
758a629f 694 if (x === null) {
ff022deb 695 return null;
758a629f 696 }
ff022deb 697
3230c662 698 var area = this.plotter_.area;
ff022deb
RK
699 var xRange = this.xAxisRange();
700 return area.x + (x - xRange[0]) / (xRange[1] - xRange[0]) * area.w;
758a629f 701};
3230c662 702
ff022deb
RK
703/**
704 * Convert from data x coordinates to canvas/div Y coordinate and optional
705 * axis. Uses the first axis by default.
706 *
707 * returns a single value or null if y is null.
708 */
709Dygraph.prototype.toDomYCoord = function(y, axis) {
0747928a 710 var pct = this.toPercentYCoord(y, axis);
3230c662 711
758a629f 712 if (pct === null) {
ff022deb
RK
713 return null;
714 }
e4416fb9 715 var area = this.plotter_.area;
ff022deb 716 return area.y + pct * area.h;
758a629f 717};
3230c662
DV
718
719/**
720 * Convert from canvas/div coords to data coordinates.
d58ae307
DV
721 * If specified, do this conversion for the coordinate system of a particular
722 * axis. Uses the first axis by default.
ff022deb
RK
723 * Returns a two-element array: [X, Y].
724 *
0747928a 725 * Note: use toDataXCoord instead of toDataCoords(x, null) and use toDataYCoord
ff022deb 726 * instead of toDataCoords(null, y, axis).
3230c662 727 */
d58ae307 728Dygraph.prototype.toDataCoords = function(x, y, axis) {
ff022deb
RK
729 return [ this.toDataXCoord(x), this.toDataYCoord(y, axis) ];
730};
731
732/**
733 * Convert from canvas/div x coordinate to data coordinate.
734 *
735 * If x is null, this returns null.
736 */
737Dygraph.prototype.toDataXCoord = function(x) {
758a629f 738 if (x === null) {
ff022deb 739 return null;
3230c662
DV
740 }
741
ff022deb
RK
742 var area = this.plotter_.area;
743 var xRange = this.xAxisRange();
744 return xRange[0] + (x - area.x) / area.w * (xRange[1] - xRange[0]);
745};
746
747/**
748 * Convert from canvas/div y coord to value.
749 *
750 * If y is null, this returns null.
751 * if axis is null, this uses the first axis.
752 */
753Dygraph.prototype.toDataYCoord = function(y, axis) {
758a629f 754 if (y === null) {
ff022deb 755 return null;
3230c662
DV
756 }
757
ff022deb
RK
758 var area = this.plotter_.area;
759 var yRange = this.yAxisRange(axis);
760
b70247dc
RK
761 if (typeof(axis) == "undefined") axis = 0;
762 if (!this.axes_[axis].logscale) {
d9816e62 763 return yRange[0] + (area.y + area.h - y) / area.h * (yRange[1] - yRange[0]);
ff022deb
RK
764 } else {
765 // Computing the inverse of toDomCoord.
758a629f 766 var pct = (y - area.y) / area.h;
ff022deb
RK
767
768 // Computing the inverse of toPercentYCoord. The function was arrived at with
769 // the following steps:
770 //
771 // Original calcuation:
d59b6f34 772 // pct = (logr1 - Dygraph.log10(y)) / (logr1 - Dygraph.log10(yRange[0]));
ff022deb
RK
773 //
774 // Move denominator to both sides:
d59b6f34 775 // pct * (logr1 - Dygraph.log10(yRange[0])) = logr1 - Dygraph.log10(y);
ff022deb
RK
776 //
777 // subtract logr1, and take the negative value.
d59b6f34 778 // logr1 - (pct * (logr1 - Dygraph.log10(yRange[0]))) = Dygraph.log10(y);
ff022deb
RK
779 //
780 // Swap both sides of the equation, and we can compute the log of the
781 // return value. Which means we just need to use that as the exponent in
782 // e^exponent.
d59b6f34 783 // Dygraph.log10(y) = logr1 - (pct * (logr1 - Dygraph.log10(yRange[0])));
ff022deb 784
d59b6f34
RK
785 var logr1 = Dygraph.log10(yRange[1]);
786 var exponent = logr1 - (pct * (logr1 - Dygraph.log10(yRange[0])));
787 var value = Math.pow(Dygraph.LOG_SCALE, exponent);
ff022deb
RK
788 return value;
789 }
3230c662
DV
790};
791
e99fde05 792/**
ff022deb 793 * Converts a y for an axis to a percentage from the top to the
4cac8c7a 794 * bottom of the drawing area.
ff022deb
RK
795 *
796 * If the coordinate represents a value visible on the canvas, then
797 * the value will be between 0 and 1, where 0 is the top of the canvas.
798 * However, this method will return values outside the range, as
799 * values can fall outside the canvas.
800 *
801 * If y is null, this returns null.
802 * if axis is null, this uses the first axis.
629a09ae
DV
803 *
804 * @param { Number } y The data y-coordinate.
805 * @param { Number } [axis] The axis number on which the data coordinate lives.
806 * @return { Number } A fraction in [0, 1] where 0 = the top edge.
ff022deb
RK
807 */
808Dygraph.prototype.toPercentYCoord = function(y, axis) {
758a629f 809 if (y === null) {
ff022deb
RK
810 return null;
811 }
7d0e7a0d 812 if (typeof(axis) == "undefined") axis = 0;
ff022deb 813
ff022deb
RK
814 var yRange = this.yAxisRange(axis);
815
816 var pct;
7d0e7a0d 817 if (!this.axes_[axis].logscale) {
4cac8c7a
RK
818 // yRange[1] - y is unit distance from the bottom.
819 // yRange[1] - yRange[0] is the scale of the range.
ff022deb
RK
820 // (yRange[1] - y) / (yRange[1] - yRange[0]) is the % from the bottom.
821 pct = (yRange[1] - y) / (yRange[1] - yRange[0]);
822 } else {
d59b6f34
RK
823 var logr1 = Dygraph.log10(yRange[1]);
824 pct = (logr1 - Dygraph.log10(y)) / (logr1 - Dygraph.log10(yRange[0]));
ff022deb
RK
825 }
826 return pct;
758a629f 827};
ff022deb
RK
828
829/**
4cac8c7a
RK
830 * Converts an x value to a percentage from the left to the right of
831 * the drawing area.
832 *
833 * If the coordinate represents a value visible on the canvas, then
834 * the value will be between 0 and 1, where 0 is the left of the canvas.
835 * However, this method will return values outside the range, as
836 * values can fall outside the canvas.
837 *
838 * If x is null, this returns null.
629a09ae
DV
839 * @param { Number } x The data x-coordinate.
840 * @return { Number } A fraction in [0, 1] where 0 = the left edge.
4cac8c7a
RK
841 */
842Dygraph.prototype.toPercentXCoord = function(x) {
758a629f 843 if (x === null) {
4cac8c7a
RK
844 return null;
845 }
846
4cac8c7a 847 var xRange = this.xAxisRange();
965a030e 848 return (x - xRange[0]) / (xRange[1] - xRange[0]);
629a09ae 849};
4cac8c7a
RK
850
851/**
e99fde05 852 * Returns the number of columns (including the independent variable).
629a09ae 853 * @return { Integer } The number of columns.
e99fde05
DV
854 */
855Dygraph.prototype.numColumns = function() {
395e98a3 856 return this.rawData_[0] ? this.rawData_[0].length : this.attr_("labels").length;
e99fde05
DV
857};
858
859/**
860 * Returns the number of rows (excluding any header/label row).
629a09ae 861 * @return { Integer } The number of rows, less any header.
e99fde05
DV
862 */
863Dygraph.prototype.numRows = function() {
864 return this.rawData_.length;
865};
866
867/**
395e98a3
DV
868 * Returns the full range of the x-axis, as determined by the most extreme
869 * values in the data set. Not affected by zooming, visibility, etc.
769e8bc7 870 * TODO(danvk): merge w/ xAxisExtremes
395e98a3
DV
871 * @return { Array<Number> } A [low, high] pair
872 * @private
873 */
874Dygraph.prototype.fullXRange_ = function() {
875 if (this.numRows() > 0) {
876 return [this.rawData_[0][0], this.rawData_[this.numRows() - 1][0]];
877 } else {
878 return [0, 1];
879 }
758a629f 880};
395e98a3
DV
881
882/**
e99fde05
DV
883 * Returns the value in the given row and column. If the row and column exceed
884 * the bounds on the data, returns null. Also returns null if the value is
885 * missing.
629a09ae
DV
886 * @param { Number} row The row number of the data (0-based). Row 0 is the
887 * first row of data, not a header row.
888 * @param { Number} col The column number of the data (0-based)
889 * @return { Number } The value in the specified cell or null if the row/col
890 * were out of range.
e99fde05
DV
891 */
892Dygraph.prototype.getValue = function(row, col) {
893 if (row < 0 || row > this.rawData_.length) return null;
894 if (col < 0 || col > this.rawData_[row].length) return null;
895
896 return this.rawData_[row][col];
897};
898
629a09ae 899/**
285a6bda 900 * Generates interface elements for the Dygraph: a containing div, a div to
6a1aa64f 901 * display the current point, and a textbox to adjust the rolling average
697e70b2 902 * period. Also creates the Renderer/Layout elements.
6a1aa64f
DV
903 * @private
904 */
285a6bda 905Dygraph.prototype.createInterface_ = function() {
6a1aa64f
DV
906 // Create the all-enclosing graph div
907 var enclosing = this.maindiv_;
908
b0c3b730
DV
909 this.graphDiv = document.createElement("div");
910 this.graphDiv.style.width = this.width_ + "px";
911 this.graphDiv.style.height = this.height_ + "px";
912 enclosing.appendChild(this.graphDiv);
913
914 // Create the canvas for interactive parts of the chart.
f8cfec73 915 this.canvas_ = Dygraph.createCanvas();
b0c3b730
DV
916 this.canvas_.style.position = "absolute";
917 this.canvas_.width = this.width_;
918 this.canvas_.height = this.height_;
f8cfec73
DV
919 this.canvas_.style.width = this.width_ + "px"; // for IE
920 this.canvas_.style.height = this.height_ + "px"; // for IE
b0c3b730 921
2cf95fff
RK
922 this.canvas_ctx_ = Dygraph.getContext(this.canvas_);
923
b0c3b730 924 // ... and for static parts of the chart.
6a1aa64f 925 this.hidden_ = this.createPlotKitCanvas_(this.canvas_);
2cf95fff 926 this.hidden_ctx_ = Dygraph.getContext(this.hidden_);
76171648 927
ccd9d7c2
PF
928 if (this.attr_('showRangeSelector')) {
929 // The range selector must be created here so that its canvases and contexts get created here.
930 // For some reason, if the canvases and contexts don't get created here, things don't work in IE.
931 // The range selector also sets xAxisHeight in order to reserve space.
932 this.rangeSelector_ = new DygraphRangeSelector(this);
933 }
934
eb7bf005
EC
935 // The interactive parts of the graph are drawn on top of the chart.
936 this.graphDiv.appendChild(this.hidden_);
937 this.graphDiv.appendChild(this.canvas_);
920208fb
PF
938 this.mouseEventElement_ = this.createMouseEventElement_();
939
940 // Create the grapher
941 this.layout_ = new DygraphLayout(this);
942
943 if (this.rangeSelector_) {
944 // This needs to happen after the graph canvases are added to the div and the layout object is created.
945 this.rangeSelector_.addToGraph(this.graphDiv, this.layout_);
946 }
eb7bf005 947
76171648 948 var dygraph = this;
d7eddd78
US
949
950 this.mouseMoveHandler = function(e) {
421f1773 951 dygraph.mouseMove_(e);
d7eddd78
US
952 };
953 Dygraph.addEvent(this.mouseEventElement_, 'mousemove', this.mouseMoveHandler);
954
955 this.mouseOutHandler = function(e) {
421f1773 956 dygraph.mouseOut_(e);
d7eddd78
US
957 };
958 Dygraph.addEvent(this.mouseEventElement_, 'mouseout', this.mouseOutHandler);
697e70b2 959
697e70b2 960 this.createDragInterface_();
4b4d1a63 961
1c6b239c 962 this.resizeHandler = function(e) {
963 dygraph.resize();
d7eddd78 964 };
1c6b239c 965
4b4d1a63
DV
966 // Update when the window is resized.
967 // TODO(danvk): drop frames depending on complexity of the chart.
1c6b239c 968 Dygraph.addEvent(window, 'resize', this.resizeHandler);
4cfcc38c
DV
969};
970
971/**
972 * Detach DOM elements in the dygraph and null out all data references.
973 * Calling this when you're done with a dygraph can dramatically reduce memory
974 * usage. See, e.g., the tests/perf.html example.
975 */
976Dygraph.prototype.destroy = function() {
977 var removeRecursive = function(node) {
978 while (node.hasChildNodes()) {
979 removeRecursive(node.firstChild);
980 node.removeChild(node.firstChild);
981 }
982 };
d7eddd78
US
983
984 // remove mouse event handlers
985 Dygraph.removeEvent(this.mouseEventElement_, 'mouseout', this.mouseOutHandler);
986 Dygraph.removeEvent(this.mouseEventElement_, 'mousemove', this.mouseMoveHandler);
cb1261cb 987 Dygraph.removeEvent(this.mouseEventElement_, 'mousemove', this.mouseUpHandler_);
4cfcc38c
DV
988 removeRecursive(this.maindiv_);
989
990 var nullOut = function(obj) {
991 for (var n in obj) {
992 if (typeof(obj[n]) === 'object') {
993 obj[n] = null;
994 }
995 }
996 };
1c6b239c 997 // remove event handlers
998 Dygraph.removeEvent(window,'resize',this.resizeHandler);
999 this.resizeHandler = null;
4cfcc38c
DV
1000 // These may not all be necessary, but it can't hurt...
1001 nullOut(this.layout_);
1002 nullOut(this.plotter_);
1003 nullOut(this);
1004};
6a1aa64f
DV
1005
1006/**
629a09ae
DV
1007 * Creates the canvas on which the chart will be drawn. Only the Renderer ever
1008 * draws on this particular canvas. All Dygraph work (i.e. drawing hover dots
1009 * or the zoom rectangles) is done on this.canvas_.
8846615a 1010 * @param {Object} canvas The Dygraph canvas over which to overlay the plot
6a1aa64f
DV
1011 * @return {Object} The newly-created canvas
1012 * @private
1013 */
285a6bda 1014Dygraph.prototype.createPlotKitCanvas_ = function(canvas) {
f8cfec73 1015 var h = Dygraph.createCanvas();
6a1aa64f 1016 h.style.position = "absolute";
9ac5e4ae
DV
1017 // TODO(danvk): h should be offset from canvas. canvas needs to include
1018 // some extra area to make it easier to zoom in on the far left and far
1019 // right. h needs to be precisely the plot area, so that clipping occurs.
6a1aa64f
DV
1020 h.style.top = canvas.style.top;
1021 h.style.left = canvas.style.left;
1022 h.width = this.width_;
1023 h.height = this.height_;
f8cfec73
DV
1024 h.style.width = this.width_ + "px"; // for IE
1025 h.style.height = this.height_ + "px"; // for IE
6a1aa64f
DV
1026 return h;
1027};
1028
629a09ae 1029/**
920208fb
PF
1030 * Creates an overlay element used to handle mouse events.
1031 * @return {Object} The mouse event element.
1032 * @private
1033 */
1034Dygraph.prototype.createMouseEventElement_ = function() {
1035 if (this.isUsingExcanvas_) {
1036 var elem = document.createElement("div");
1037 elem.style.position = 'absolute';
1038 elem.style.backgroundColor = 'white';
1039 elem.style.filter = 'alpha(opacity=0)';
1040 elem.style.width = this.width_ + "px";
1041 elem.style.height = this.height_ + "px";
1042 this.graphDiv.appendChild(elem);
1043 return elem;
1044 } else {
1045 return this.canvas_;
1046 }
1047};
1048
1049/**
6a1aa64f
DV
1050 * Generate a set of distinct colors for the data series. This is done with a
1051 * color wheel. Saturation/Value are customizable, and the hue is
1052 * equally-spaced around the color wheel. If a custom set of colors is
1053 * specified, that is used instead.
6a1aa64f
DV
1054 * @private
1055 */
285a6bda 1056Dygraph.prototype.setColors_ = function() {
285a6bda 1057 var num = this.attr_("labels").length - 1;
6a1aa64f 1058 this.colors_ = [];
285a6bda 1059 var colors = this.attr_('colors');
758a629f 1060 var i;
285a6bda
DV
1061 if (!colors) {
1062 var sat = this.attr_('colorSaturation') || 1.0;
1063 var val = this.attr_('colorValue') || 0.5;
2aa21213 1064 var half = Math.ceil(num / 2);
758a629f 1065 for (i = 1; i <= num; i++) {
ec1959eb 1066 if (!this.visibility()[i-1]) continue;
43af96e7 1067 // alternate colors for high contrast.
2aa21213 1068 var idx = i % 2 ? Math.ceil(i / 2) : (half + i / 2);
43af96e7
NK
1069 var hue = (1.0 * idx/ (1 + num));
1070 this.colors_.push(Dygraph.hsvToRGB(hue, sat, val));
6a1aa64f
DV
1071 }
1072 } else {
758a629f 1073 for (i = 0; i < num; i++) {
ec1959eb 1074 if (!this.visibility()[i]) continue;
285a6bda 1075 var colorStr = colors[i % colors.length];
f474c2a3 1076 this.colors_.push(colorStr);
6a1aa64f
DV
1077 }
1078 }
600d841a
DV
1079
1080 this.plotter_.setColors(this.colors_);
629a09ae 1081};
6a1aa64f 1082
43af96e7
NK
1083/**
1084 * Return the list of colors. This is either the list of colors passed in the
629a09ae 1085 * attributes or the autogenerated list of rgb(r,g,b) strings.
e2c21500 1086 * This does not return colors for invisible series.
43af96e7
NK
1087 * @return {Array<string>} The list of colors.
1088 */
1089Dygraph.prototype.getColors = function() {
1090 return this.colors_;
1091};
1092
6a1aa64f 1093/**
e2c21500
DV
1094 * Returns a few attributes of a series, i.e. its color, its visibility, which
1095 * axis it's assigned to, and its column in the original data.
1096 * Returns null if the series does not exist.
1097 * Otherwise, returns an object with column, visibility, color and axis properties.
1098 * The "axis" property will be set to 1 for y1 and 2 for y2.
1099 * The "column" property can be fed back into getValue(row, column) to get
1100 * values for this series.
6a1aa64f 1101 */
e2c21500
DV
1102Dygraph.prototype.getPropertiesForSeries = function(series_name) {
1103 var idx = -1;
1104 var labels = this.getLabels();
1105 for (var i = 1; i < labels.length; i++) {
1106 if (labels[i] == series_name) {
1107 idx = i;
1108 break;
b0c3b730 1109 }
6a1aa64f 1110 }
e2c21500 1111 if (idx == -1) return null;
0abfbd7e 1112
e2c21500
DV
1113 return {
1114 name: series_name,
1115 column: idx,
1116 visible: this.visibility()[idx - 1],
1117 color: this.plotter_.colors[series_name],
1118 axis: 1 + this.seriesToAxisMap_[series_name]
1119 };
0abfbd7e
DV
1120};
1121
1122/**
6a1aa64f 1123 * Create the text box to adjust the averaging period
6a1aa64f
DV
1124 * @private
1125 */
285a6bda 1126Dygraph.prototype.createRollInterface_ = function() {
8c69de65
DV
1127 // Create a roller if one doesn't exist already.
1128 if (!this.roller_) {
1129 this.roller_ = document.createElement("input");
1130 this.roller_.type = "text";
1131 this.roller_.style.display = "none";
1132 this.graphDiv.appendChild(this.roller_);
1133 }
1134
1135 var display = this.attr_('showRoller') ? 'block' : 'none';
26ca7938 1136
0c38f187 1137 var area = this.plotter_.area;
b0c3b730
DV
1138 var textAttr = { "position": "absolute",
1139 "zIndex": 10,
0c38f187
DV
1140 "top": (area.y + area.h - 25) + "px",
1141 "left": (area.x + 1) + "px",
b0c3b730 1142 "display": display
6a1aa64f 1143 };
8c69de65
DV
1144 this.roller_.size = "2";
1145 this.roller_.value = this.rollPeriod_;
b0c3b730 1146 for (var name in textAttr) {
85b99f0b 1147 if (textAttr.hasOwnProperty(name)) {
8c69de65 1148 this.roller_.style[name] = textAttr[name];
85b99f0b 1149 }
b0c3b730
DV
1150 }
1151
76171648 1152 var dygraph = this;
8c69de65 1153 this.roller_.onchange = function() { dygraph.adjustRoll(dygraph.roller_.value); };
76171648
DV
1154};
1155
629a09ae
DV
1156/**
1157 * @private
629a09ae
DV
1158 * Converts page the x-coordinate of the event to pixel x-coordinates on the
1159 * canvas (i.e. DOM Coords).
1160 */
062ef401 1161Dygraph.prototype.dragGetX_ = function(e, context) {
758a629f 1162 return Dygraph.pageX(e) - context.px;
062ef401 1163};
bce01b0f 1164
629a09ae
DV
1165/**
1166 * @private
1167 * Converts page the y-coordinate of the event to pixel y-coordinates on the
1168 * canvas (i.e. DOM Coords).
1169 */
062ef401 1170Dygraph.prototype.dragGetY_ = function(e, context) {
758a629f 1171 return Dygraph.pageY(e) - context.py;
062ef401 1172};
ee672584 1173
629a09ae 1174/**
062ef401
JB
1175 * Set up all the mouse handlers needed to capture dragging behavior for zoom
1176 * events.
1177 * @private
1178 */
1179Dygraph.prototype.createDragInterface_ = function() {
1180 var context = {
1181 // Tracks whether the mouse is down right now
1182 isZooming: false,
1183 isPanning: false, // is this drag part of a pan?
1184 is2DPan: false, // if so, is that pan 1- or 2-dimensional?
8442269f
RK
1185 dragStartX: null, // pixel coordinates
1186 dragStartY: null, // pixel coordinates
1187 dragEndX: null, // pixel coordinates
1188 dragEndY: null, // pixel coordinates
062ef401 1189 dragDirection: null,
8442269f
RK
1190 prevEndX: null, // pixel coordinates
1191 prevEndY: null, // pixel coordinates
062ef401 1192 prevDragDirection: null,
421f1773 1193 cancelNextDblclick: false, // see comment in dygraph-interaction-model.js
062ef401 1194
ec291cbe
RK
1195 // The value on the left side of the graph when a pan operation starts.
1196 initialLeftmostDate: null,
1197
1198 // The number of units each pixel spans. (This won't be valid for log
1199 // scales)
1200 xUnitsPerPixel: null,
062ef401
JB
1201
1202 // TODO(danvk): update this comment
1203 // The range in second/value units that the viewport encompasses during a
1204 // panning operation.
1205 dateRange: null,
1206
8442269f
RK
1207 // Top-left corner of the canvas, in DOM coords
1208 // TODO(konigsberg): Rename topLeftCanvasX, topLeftCanvasY.
062ef401
JB
1209 px: 0,
1210 py: 0,
1211
965a030e 1212 // Values for use with panEdgeFraction, which limit how far outside the
4cac8c7a
RK
1213 // graph's data boundaries it can be panned.
1214 boundedDates: null, // [minDate, maxDate]
1215 boundedValues: null, // [[minValue, maxValue] ...]
1216
062ef401
JB
1217 initializeMouseDown: function(event, g, context) {
1218 // prevents mouse drags from selecting page text.
1219 if (event.preventDefault) {
1220 event.preventDefault(); // Firefox, Chrome, etc.
6a1aa64f 1221 } else {
062ef401
JB
1222 event.returnValue = false; // IE
1223 event.cancelBubble = true;
6a1aa64f
DV
1224 }
1225
062ef401
JB
1226 context.px = Dygraph.findPosX(g.canvas_);
1227 context.py = Dygraph.findPosY(g.canvas_);
1228 context.dragStartX = g.dragGetX_(event, context);
1229 context.dragStartY = g.dragGetY_(event, context);
421f1773 1230 context.cancelNextDblclick = false;
6a1aa64f 1231 }
062ef401 1232 };
2b188b3d 1233
062ef401 1234 var interactionModel = this.attr_("interactionModel");
8b83c6cc 1235
062ef401
JB
1236 // Self is the graph.
1237 var self = this;
6faebb69 1238
062ef401
JB
1239 // Function that binds the graph and context to the handler.
1240 var bindHandler = function(handler) {
1241 return function(event) {
1242 handler(event, self, context);
1243 };
1244 };
1245
1246 for (var eventName in interactionModel) {
1247 if (!interactionModel.hasOwnProperty(eventName)) continue;
1248 Dygraph.addEvent(this.mouseEventElement_, eventName,
1249 bindHandler(interactionModel[eventName]));
1250 }
1251
1252 // If the user releases the mouse button during a drag, but not over the
1253 // canvas, then it doesn't count as a zooming action.
cb1261cb 1254 this.mouseUpHandler_ = function(event) {
062ef401
JB
1255 if (context.isZooming || context.isPanning) {
1256 context.isZooming = false;
1257 context.dragStartX = null;
1258 context.dragStartY = null;
1259 }
1260
1261 if (context.isPanning) {
1262 context.isPanning = false;
1263 context.draggingDate = null;
1264 context.dateRange = null;
1265 for (var i = 0; i < self.axes_.length; i++) {
1266 delete self.axes_[i].draggingValue;
1267 delete self.axes_[i].dragValueRange;
1268 }
1269 }
cb1261cb
DV
1270 };
1271
1272 Dygraph.addEvent(document, 'mouseup', this.mouseUpHandler_);
6a1aa64f
DV
1273};
1274
1275/**
1276 * Draw a gray zoom rectangle over the desired area of the canvas. Also clears
1277 * up any previous zoom rectangles that were drawn. This could be optimized to
1278 * avoid extra redrawing, but it's tricky to avoid interactions with the status
1279 * dots.
ccd9d7c2 1280 *
39b0e098
RK
1281 * @param {Number} direction the direction of the zoom rectangle. Acceptable
1282 * values are Dygraph.HORIZONTAL and Dygraph.VERTICAL.
6a1aa64f
DV
1283 * @param {Number} startX The X position where the drag started, in canvas
1284 * coordinates.
1285 * @param {Number} endX The current X position of the drag, in canvas coords.
8b83c6cc
RK
1286 * @param {Number} startY The Y position where the drag started, in canvas
1287 * coordinates.
1288 * @param {Number} endY The current Y position of the drag, in canvas coords.
39b0e098 1289 * @param {Number} prevDirection the value of direction on the previous call to
8b83c6cc 1290 * this function. Used to avoid excess redrawing
6a1aa64f
DV
1291 * @param {Number} prevEndX The value of endX on the previous call to this
1292 * function. Used to avoid excess redrawing
8b83c6cc
RK
1293 * @param {Number} prevEndY The value of endY on the previous call to this
1294 * function. Used to avoid excess redrawing
6a1aa64f
DV
1295 * @private
1296 */
7201b11e
JB
1297Dygraph.prototype.drawZoomRect_ = function(direction, startX, endX, startY,
1298 endY, prevDirection, prevEndX,
1299 prevEndY) {
2cf95fff 1300 var ctx = this.canvas_ctx_;
6a1aa64f
DV
1301
1302 // Clean up from the previous rect if necessary
39b0e098 1303 if (prevDirection == Dygraph.HORIZONTAL) {
fa54c193
FXB
1304 ctx.clearRect(Math.min(startX, prevEndX), this.layout_.getPlotArea().y,
1305 Math.abs(startX - prevEndX), this.layout_.getPlotArea().h);
39b0e098 1306 } else if (prevDirection == Dygraph.VERTICAL){
fa54c193
FXB
1307 ctx.clearRect(this.layout_.getPlotArea().x, Math.min(startY, prevEndY),
1308 this.layout_.getPlotArea().w, Math.abs(startY - prevEndY));
6a1aa64f
DV
1309 }
1310
1311 // Draw a light-grey rectangle to show the new viewing area
39b0e098 1312 if (direction == Dygraph.HORIZONTAL) {
8b83c6cc
RK
1313 if (endX && startX) {
1314 ctx.fillStyle = "rgba(128,128,128,0.33)";
fa54c193
FXB
1315 ctx.fillRect(Math.min(startX, endX), this.layout_.getPlotArea().y,
1316 Math.abs(endX - startX), this.layout_.getPlotArea().h);
8b83c6cc 1317 }
920208fb 1318 } else if (direction == Dygraph.VERTICAL) {
8b83c6cc
RK
1319 if (endY && startY) {
1320 ctx.fillStyle = "rgba(128,128,128,0.33)";
fa54c193
FXB
1321 ctx.fillRect(this.layout_.getPlotArea().x, Math.min(startY, endY),
1322 this.layout_.getPlotArea().w, Math.abs(endY - startY));
8b83c6cc 1323 }
6a1aa64f 1324 }
920208fb
PF
1325
1326 if (this.isUsingExcanvas_) {
1327 this.currentZoomRectArgs_ = [direction, startX, endX, startY, endY, 0, 0, 0];
1328 }
1329};
1330
1331/**
1332 * Clear the zoom rectangle (and perform no zoom).
1333 * @private
1334 */
1335Dygraph.prototype.clearZoomRect_ = function() {
1336 this.currentZoomRectArgs_ = null;
1337 this.canvas_ctx_.clearRect(0, 0, this.canvas_.width, this.canvas_.height);
6a1aa64f
DV
1338};
1339
1340/**
8b83c6cc
RK
1341 * Zoom to something containing [lowX, highX]. These are pixel coordinates in
1342 * the canvas. The exact zoom window may be slightly larger if there are no data
1343 * points near lowX or highX. Don't confuse this function with doZoomXDates,
1344 * which accepts dates that match the raw data. This function redraws the graph.
d58ae307 1345 *
6a1aa64f
DV
1346 * @param {Number} lowX The leftmost pixel value that should be visible.
1347 * @param {Number} highX The rightmost pixel value that should be visible.
1348 * @private
1349 */
8b83c6cc 1350Dygraph.prototype.doZoomX_ = function(lowX, highX) {
920208fb 1351 this.currentZoomRectArgs_ = null;
6a1aa64f 1352 // Find the earliest and latest dates contained in this canvasx range.
8b83c6cc 1353 // Convert the call to date ranges of the raw data.
ff022deb
RK
1354 var minDate = this.toDataXCoord(lowX);
1355 var maxDate = this.toDataXCoord(highX);
8b83c6cc
RK
1356 this.doZoomXDates_(minDate, maxDate);
1357};
6a1aa64f 1358
8b83c6cc 1359/**
b1a3b195
DV
1360 * Transition function to use in animations. Returns values between 0.0
1361 * (totally old values) and 1.0 (totally new values) for each frame.
1362 * @private
1363 */
1364Dygraph.zoomAnimationFunction = function(frame, numFrames) {
1365 var k = 1.5;
1366 return (1.0 - Math.pow(k, -frame)) / (1.0 - Math.pow(k, -numFrames));
1367};
1368
1369/**
8b83c6cc
RK
1370 * Zoom to something containing [minDate, maxDate] values. Don't confuse this
1371 * method with doZoomX which accepts pixel coordinates. This function redraws
1372 * the graph.
d58ae307 1373 *
8b83c6cc
RK
1374 * @param {Number} minDate The minimum date that should be visible.
1375 * @param {Number} maxDate The maximum date that should be visible.
1376 * @private
1377 */
1378Dygraph.prototype.doZoomXDates_ = function(minDate, maxDate) {
b1a3b195
DV
1379 // TODO(danvk): when yAxisRange is null (i.e. "fit to data", the animation
1380 // can produce strange effects. Rather than the y-axis transitioning slowly
1381 // between values, it can jerk around.)
1382 var old_window = this.xAxisRange();
1383 var new_window = [minDate, maxDate];
57baab03 1384 this.zoomed_x_ = true;
b1a3b195
DV
1385 var that = this;
1386 this.doAnimatedZoom(old_window, new_window, null, null, function() {
1387 if (that.attr_("zoomCallback")) {
1388 that.attr_("zoomCallback")(minDate, maxDate, that.yAxisRanges());
1389 }
1390 });
8b83c6cc
RK
1391};
1392
1393/**
1394 * Zoom to something containing [lowY, highY]. These are pixel coordinates in
d58ae307
DV
1395 * the canvas. This function redraws the graph.
1396 *
8b83c6cc
RK
1397 * @param {Number} lowY The topmost pixel value that should be visible.
1398 * @param {Number} highY The lowest pixel value that should be visible.
1399 * @private
1400 */
1401Dygraph.prototype.doZoomY_ = function(lowY, highY) {
920208fb 1402 this.currentZoomRectArgs_ = null;
d58ae307
DV
1403 // Find the highest and lowest values in pixel range for each axis.
1404 // Note that lowY (in pixels) corresponds to the max Value (in data coords).
1405 // This is because pixels increase as you go down on the screen, whereas data
1406 // coordinates increase as you go up the screen.
b1a3b195
DV
1407 var oldValueRanges = this.yAxisRanges();
1408 var newValueRanges = [];
d58ae307 1409 for (var i = 0; i < this.axes_.length; i++) {
ff022deb
RK
1410 var hi = this.toDataYCoord(lowY, i);
1411 var low = this.toDataYCoord(highY, i);
b1a3b195 1412 newValueRanges.push([low, hi]);
d58ae307 1413 }
8b83c6cc 1414
57baab03 1415 this.zoomed_y_ = true;
b1a3b195
DV
1416 var that = this;
1417 this.doAnimatedZoom(null, null, oldValueRanges, newValueRanges, function() {
1418 if (that.attr_("zoomCallback")) {
1419 var xRange = that.xAxisRange();
b1a3b195
DV
1420 that.attr_("zoomCallback")(xRange[0], xRange[1], that.yAxisRanges());
1421 }
1422 });
8b83c6cc
RK
1423};
1424
1425/**
1426 * Reset the zoom to the original view coordinates. This is the same as
1427 * double-clicking on the graph.
d58ae307 1428 *
8b83c6cc
RK
1429 * @private
1430 */
1431Dygraph.prototype.doUnzoom_ = function() {
b1a3b195 1432 var dirty = false, dirtyX = false, dirtyY = false;
758a629f 1433 if (this.dateWindow_ !== null) {
d58ae307 1434 dirty = true;
b1a3b195 1435 dirtyX = true;
8b83c6cc 1436 }
d58ae307
DV
1437
1438 for (var i = 0; i < this.axes_.length; i++) {
1f6a6254 1439 if (typeof(this.axes_[i].valueWindow) !== 'undefined' && this.axes_[i].valueWindow !== null) {
d58ae307 1440 dirty = true;
b1a3b195 1441 dirtyY = true;
d58ae307 1442 }
8b83c6cc
RK
1443 }
1444
da1369a5
DV
1445 // Clear any selection, since it's likely to be drawn in the wrong place.
1446 this.clearSelection();
1447
8b83c6cc 1448 if (dirty) {
57baab03
NN
1449 this.zoomed_x_ = false;
1450 this.zoomed_y_ = false;
b1a3b195
DV
1451
1452 var minDate = this.rawData_[0][0];
1453 var maxDate = this.rawData_[this.rawData_.length - 1][0];
1454
1455 // With only one frame, don't bother calculating extreme ranges.
1456 // TODO(danvk): merge this block w/ the code below.
1457 if (!this.attr_("animatedZooms")) {
1458 this.dateWindow_ = null;
758a629f
DV
1459 for (i = 0; i < this.axes_.length; i++) {
1460 if (this.axes_[i].valueWindow !== null) {
b1a3b195
DV
1461 delete this.axes_[i].valueWindow;
1462 }
1463 }
1464 this.drawGraph_();
1465 if (this.attr_("zoomCallback")) {
1466 this.attr_("zoomCallback")(minDate, maxDate, this.yAxisRanges());
1467 }
1468 return;
1469 }
1470
1471 var oldWindow=null, newWindow=null, oldValueRanges=null, newValueRanges=null;
1472 if (dirtyX) {
1473 oldWindow = this.xAxisRange();
1474 newWindow = [minDate, maxDate];
1475 }
1476
1477 if (dirtyY) {
1478 oldValueRanges = this.yAxisRanges();
1479 // TODO(danvk): this is pretty inefficient
1480 var packed = this.gatherDatasets_(this.rolledSeries_, null);
1481 var extremes = packed[1];
1482
1483 // this has the side-effect of modifying this.axes_.
1484 // this doesn't make much sense in this context, but it's convenient (we
1485 // need this.axes_[*].extremeValues) and not harmful since we'll be
1486 // calling drawGraph_ shortly, which clobbers these values.
1487 this.computeYAxisRanges_(extremes);
1488
1489 newValueRanges = [];
758a629f 1490 for (i = 0; i < this.axes_.length; i++) {
1f6a6254
US
1491 var axis = this.axes_[i];
1492 newValueRanges.push(axis.valueRange != null ? axis.valueRange : axis.extremeRange);
b1a3b195
DV
1493 }
1494 }
1495
1496 var that = this;
1497 this.doAnimatedZoom(oldWindow, newWindow, oldValueRanges, newValueRanges,
1498 function() {
1499 that.dateWindow_ = null;
1500 for (var i = 0; i < that.axes_.length; i++) {
758a629f 1501 if (that.axes_[i].valueWindow !== null) {
b1a3b195
DV
1502 delete that.axes_[i].valueWindow;
1503 }
1504 }
1505 if (that.attr_("zoomCallback")) {
1506 that.attr_("zoomCallback")(minDate, maxDate, that.yAxisRanges());
1507 }
1508 });
1509 }
1510};
1511
1512/**
1513 * Combined animation logic for all zoom functions.
1514 * either the x parameters or y parameters may be null.
1515 * @private
1516 */
1517Dygraph.prototype.doAnimatedZoom = function(oldXRange, newXRange, oldYRanges, newYRanges, callback) {
1518 var steps = this.attr_("animatedZooms") ? Dygraph.ANIMATION_STEPS : 1;
1519
1520 var windows = [];
1521 var valueRanges = [];
758a629f 1522 var step, frac;
b1a3b195 1523
758a629f
DV
1524 if (oldXRange !== null && newXRange !== null) {
1525 for (step = 1; step <= steps; step++) {
1526 frac = Dygraph.zoomAnimationFunction(step, steps);
b1a3b195
DV
1527 windows[step-1] = [oldXRange[0]*(1-frac) + frac*newXRange[0],
1528 oldXRange[1]*(1-frac) + frac*newXRange[1]];
8b83c6cc 1529 }
67e650dc 1530 }
b1a3b195 1531
758a629f
DV
1532 if (oldYRanges !== null && newYRanges !== null) {
1533 for (step = 1; step <= steps; step++) {
1534 frac = Dygraph.zoomAnimationFunction(step, steps);
b1a3b195
DV
1535 var thisRange = [];
1536 for (var j = 0; j < this.axes_.length; j++) {
1537 thisRange.push([oldYRanges[j][0]*(1-frac) + frac*newYRanges[j][0],
1538 oldYRanges[j][1]*(1-frac) + frac*newYRanges[j][1]]);
1539 }
1540 valueRanges[step-1] = thisRange;
1541 }
1542 }
1543
1544 var that = this;
1545 Dygraph.repeatAndCleanup(function(step) {
1546 if (valueRanges.length) {
1547 for (var i = 0; i < that.axes_.length; i++) {
1548 var w = valueRanges[step][i];
1549 that.axes_[i].valueWindow = [w[0], w[1]];
1550 }
1551 }
1552 if (windows.length) {
1553 that.dateWindow_ = windows[step];
1554 }
1555 that.drawGraph_();
1556 }, steps, Dygraph.ANIMATION_DURATION / steps, callback);
6a1aa64f
DV
1557};
1558
1559/**
857a6931
KW
1560 * Get the current graph's area object.
1561 *
1562 * Returns: {x, y, w, h}
6a1aa64f 1563 */
857a6931
KW
1564Dygraph.prototype.getArea = function() {
1565 return this.plotter_.area;
1566};
e863a17d 1567
857a6931
KW
1568/**
1569 * Convert a mouse event to DOM coordinates relative to the graph origin.
1570 *
1571 * Returns a two-element array: [X, Y].
1572 */
1573Dygraph.prototype.eventToDomCoords = function(event) {
4cac8c7a 1574 var canvasx = Dygraph.pageX(event) - Dygraph.findPosX(this.mouseEventElement_);
857a6931
KW
1575 var canvasy = Dygraph.pageY(event) - Dygraph.findPosY(this.mouseEventElement_);
1576 return [canvasx, canvasy];
1577};
4cac8c7a 1578
857a6931
KW
1579/**
1580 * Given a canvas X coordinate, find the closest row.
1581 * @param {Number} domX graph-relative DOM X coordinate
1582 * Returns: row number, integer
1583 * @private
1584 */
1585Dygraph.prototype.findClosestRow = function(domX) {
81cb07d6 1586 var minDistX = Infinity;
6a1aa64f 1587 var idx = -1;
857a6931
KW
1588 var points = this.layout_.points;
1589 var l = points.length;
1590 for (var i = 0; i < l; i++) {
8a7cc60e 1591 var point = points[i];
04c104d7 1592 if (!Dygraph.isValidPoint(point, true)) continue;
857a6931 1593 var dist = Math.abs(point.canvasx - domX);
81cb07d6 1594 if (dist < minDistX) {
a937d031
KW
1595 minDistX = dist;
1596 idx = i;
1597 }
6a1aa64f 1598 }
857a6931
KW
1599 return this.idxToRow_(idx);
1600};
6a1aa64f 1601
857a6931 1602/**
2a02e5dd
KW
1603 * Given canvas X,Y coordinates, find the closest point.
1604 *
1605 * This finds the individual data point across all visible series
1606 * that's closest to the supplied DOM coordinates using the standard
1607 * Euclidean X,Y distance.
1608 *
857a6931
KW
1609 * @param {Number} domX graph-relative DOM X coordinate
1610 * @param {Number} domY graph-relative DOM Y coordinate
1611 * Returns: {row, seriesName, point}
1612 * @private
1613 */
1614Dygraph.prototype.findClosestPoint = function(domX, domY) {
81cb07d6 1615 var minDist = Infinity;
857a6931
KW
1616 var idx = -1;
1617 var points = this.layout_.points;
1618 var dist, dx, dy, point, closestPoint, closestSeries;
1619 for (var setIdx = 0; setIdx < this.layout_.datasets.length; ++setIdx) {
1620 var first = this.layout_.setPointsOffsets[setIdx];
1621 var len = this.layout_.setPointsLengths[setIdx];
1622 for (var i = 0; i < len; ++i) {
1623 var point = points[first + i];
62c3d2fd 1624 if (!Dygraph.isValidPoint(point)) continue;
857a6931
KW
1625 dx = point.canvasx - domX;
1626 dy = point.canvasy - domY;
1627 dist = dx * dx + dy * dy;
81cb07d6 1628 if (dist < minDist) {
62c3d2fd 1629 minDist = dist;
a937d031
KW
1630 closestPoint = point;
1631 closestSeries = setIdx;
1632 idx = i;
1633 }
857a6931
KW
1634 }
1635 }
1636 var name = this.layout_.setNames[closestSeries];
1637 return {
81cb07d6 1638 row: idx + this.getLeftBoundary_(),
857a6931
KW
1639 seriesName: name,
1640 point: closestPoint
1641 };
1642};
1643
1644/**
1645 * Given canvas X,Y coordinates, find the touched area in a stacked graph.
2a02e5dd
KW
1646 *
1647 * This first finds the X data point closest to the supplied DOM X coordinate,
1648 * then finds the series which puts the Y coordinate on top of its filled area,
1649 * using linear interpolation between adjacent point pairs.
1650 *
857a6931
KW
1651 * @param {Number} domX graph-relative DOM X coordinate
1652 * @param {Number} domY graph-relative DOM Y coordinate
1653 * Returns: {row, seriesName, point}
1654 * @private
1655 */
1656Dygraph.prototype.findStackedPoint = function(domX, domY) {
1657 var row = this.findClosestRow(domX);
81cb07d6
KW
1658 var boundary = this.getLeftBoundary_();
1659 var rowIdx = row - boundary;
857a6931
KW
1660 var points = this.layout_.points;
1661 var closestPoint, closestSeries;
1662 for (var setIdx = 0; setIdx < this.layout_.datasets.length; ++setIdx) {
1663 var first = this.layout_.setPointsOffsets[setIdx];
1664 var len = this.layout_.setPointsLengths[setIdx];
81cb07d6
KW
1665 if (rowIdx >= len) continue;
1666 var p1 = points[first + rowIdx];
62c3d2fd 1667 if (!Dygraph.isValidPoint(p1)) continue;
857a6931 1668 var py = p1.canvasy;
81cb07d6 1669 if (domX > p1.canvasx && rowIdx + 1 < len) {
857a6931 1670 // interpolate series Y value using next point
81cb07d6 1671 var p2 = points[first + rowIdx + 1];
62c3d2fd
KW
1672 if (Dygraph.isValidPoint(p2)) {
1673 var dx = p2.canvasx - p1.canvasx;
1674 if (dx > 0) {
1675 var r = (domX - p1.canvasx) / dx;
1676 py += r * (p2.canvasy - p1.canvasy);
1677 }
416b05ad 1678 }
81cb07d6 1679 } else if (domX < p1.canvasx && rowIdx > 0) {
857a6931 1680 // interpolate series Y value using previous point
81cb07d6 1681 var p0 = points[first + rowIdx - 1];
62c3d2fd
KW
1682 if (Dygraph.isValidPoint(p0)) {
1683 var dx = p1.canvasx - p0.canvasx;
1684 if (dx > 0) {
1685 var r = (p1.canvasx - domX) / dx;
1686 py += r * (p0.canvasy - p1.canvasy);
1687 }
12e4c741 1688 }
6a1aa64f 1689 }
857a6931 1690 // Stop if the point (domX, py) is above this series' upper edge
a937d031
KW
1691 if (setIdx == 0 || py < domY) {
1692 closestPoint = p1;
1693 closestSeries = setIdx;
1694 }
6a1aa64f 1695 }
857a6931
KW
1696 var name = this.layout_.setNames[closestSeries];
1697 return {
1698 row: row,
1699 seriesName: name,
1700 point: closestPoint
1701 };
1702};
6a1aa64f 1703
857a6931 1704/**
6a1aa64f
DV
1705 * When the mouse moves in the canvas, display information about a nearby data
1706 * point and draw dots over those points in the data series. This function
1707 * takes care of cleanup of previously-drawn dots.
1708 * @param {Object} event The mousemove event from the browser.
1709 * @private
1710 */
285a6bda 1711Dygraph.prototype.mouseMove_ = function(event) {
e863a17d 1712 // This prevents JS errors when mousing over the canvas before data loads.
4cac8c7a 1713 var points = this.layout_.points;
685ebbb3 1714 if (points === undefined) return;
e863a17d 1715
857a6931
KW
1716 var canvasCoords = this.eventToDomCoords(event);
1717 var canvasx = canvasCoords[0];
1718 var canvasy = canvasCoords[1];
6a1aa64f 1719
857a6931
KW
1720 var highlightSeriesOpts = this.attr_("highlightSeriesOpts");
1721 var selectionChanged = false;
1722 if (highlightSeriesOpts) {
1723 var closest;
1724 if (this.attr_("stackedGraph")) {
1725 closest = this.findStackedPoint(canvasx, canvasy);
1726 } else {
1727 closest = this.findClosestPoint(canvasx, canvasy);
43af96e7 1728 }
857a6931 1729 selectionChanged = this.setSelection(closest.row, closest.seriesName);
416b05ad 1730 } else {
857a6931
KW
1731 var idx = this.findClosestRow(canvasx);
1732 selectionChanged = this.setSelection(idx);
12e4c741 1733 }
43af96e7 1734
857a6931
KW
1735 var callback = this.attr_("highlightCallback");
1736 if (callback && selectionChanged) {
1737 callback(event, this.lastx_, this.selPoints_, this.lastRow_, this.highlightSet_);
12e4c741 1738 }
239c712d 1739};
b258a3da 1740
239c712d 1741/**
81cb07d6 1742 * Fetch left offset from first defined boundaryIds record (see bug #236).
e2c21500 1743 * @private
81cb07d6
KW
1744 */
1745Dygraph.prototype.getLeftBoundary_ = function() {
1746 for (var i = 0; i < this.boundaryIds_.length; i++) {
1747 if (this.boundaryIds_[i] !== undefined) {
1748 return this.boundaryIds_[i][0];
1749 }
1750 }
1751 return 0;
1752};
1753
1754/**
1903f1e4 1755 * Transforms layout_.points index into data row number.
2ddb1197 1756 * @param int layout_.points index
1903f1e4 1757 * @return int row number, or -1 if none could be found.
2ddb1197
SC
1758 * @private
1759 */
1760Dygraph.prototype.idxToRow_ = function(idx) {
1903f1e4 1761 if (idx < 0) return -1;
2ddb1197 1762
81cb07d6 1763 var boundary = this.getLeftBoundary_();
82c6fe4d
KW
1764 for (var setIdx = 0; setIdx < this.layout_.datasets.length; ++setIdx) {
1765 var set = this.layout_.datasets[setIdx];
1766 if (idx < set.length) {
81cb07d6 1767 return boundary + idx;
1903f1e4 1768 }
82c6fe4d 1769 idx -= set.length;
1903f1e4
DV
1770 }
1771 return -1;
1772};
2ddb1197 1773
857a6931
KW
1774Dygraph.prototype.animateSelection_ = function(direction) {
1775 var totalSteps = 10;
1776 var millis = 30;
1d44ee5e
KW
1777 if (this.fadeLevel === undefined) this.fadeLevel = 0;
1778 if (this.animateId === undefined) this.animateId = 0;
857a6931
KW
1779 var start = this.fadeLevel;
1780 var steps = direction < 0 ? start : totalSteps - start;
1781 if (steps <= 0) {
1782 if (this.fadeLevel) {
1783 this.updateSelection_(1.0);
1784 }
1785 return;
1786 }
1787
1788 var thisId = ++this.animateId;
1789 var that = this;
475f7420
KW
1790 Dygraph.repeatAndCleanup(
1791 function(n) {
1792 // ignore simultaneous animations
1793 if (that.animateId != thisId) return;
1794
1795 that.fadeLevel += direction;
1796 if (that.fadeLevel === 0) {
1797 that.clearSelection();
1798 } else {
1799 that.updateSelection_(that.fadeLevel / totalSteps);
1800 }
1801 },
1802 steps, millis, function() {});
857a6931
KW
1803};
1804
2ddb1197 1805/**
239c712d
NAG
1806 * Draw dots over the selectied points in the data series. This function
1807 * takes care of cleanup of previously-drawn dots.
1808 * @private
1809 */
857a6931 1810Dygraph.prototype.updateSelection_ = function(opt_animFraction) {
e2c21500
DV
1811 var defaultPrevented = this.cascadeEvents_('select', {
1812 selectedX: this.lastx_,
1813 selectedPoints: this.selPoints_
1814 });
1815 // TODO(danvk): use defaultPrevented here?
1816
6a1aa64f 1817 // Clear the previously drawn vertical, if there is one
758a629f 1818 var i;
2cf95fff 1819 var ctx = this.canvas_ctx_;
857a6931
KW
1820 if (this.attr_('highlightSeriesOpts')) {
1821 ctx.clearRect(0, 0, this.width_, this.height_);
afdb20d8 1822 var alpha = 1.0 - this.attr_('highlightSeriesBackgroundAlpha');
857a6931 1823 if (alpha) {
2a02e5dd
KW
1824 // Activating background fade includes an animation effect for a gradual
1825 // fade. TODO(klausw): make this independently configurable if it causes
1826 // issues? Use a shared preference to control animations?
1827 var animateBackgroundFade = true;
1828 if (animateBackgroundFade) {
857a6931
KW
1829 if (opt_animFraction === undefined) {
1830 // start a new animation
1831 this.animateSelection_(1);
1832 return;
1833 }
1834 alpha *= opt_animFraction;
1835 }
1836 ctx.fillStyle = 'rgba(255,255,255,' + alpha + ')';
1837 ctx.fillRect(0, 0, this.width_, this.height_);
1838 }
1839 var setIdx = this.datasetIndexFromSetName_(this.highlightSet_);
857a6931
KW
1840 this.plotter_._drawLine(ctx, setIdx);
1841 } else if (this.previousVerticalX_ >= 0) {
46dde5f9
DV
1842 // Determine the maximum highlight circle size.
1843 var maxCircleSize = 0;
227b93cc 1844 var labels = this.attr_('labels');
758a629f 1845 for (i = 1; i < labels.length; i++) {
227b93cc 1846 var r = this.attr_('highlightCircleSize', labels[i]);
46dde5f9
DV
1847 if (r > maxCircleSize) maxCircleSize = r;
1848 }
6a1aa64f 1849 var px = this.previousVerticalX_;
46dde5f9
DV
1850 ctx.clearRect(px - maxCircleSize - 1, 0,
1851 2 * maxCircleSize + 2, this.height_);
6a1aa64f
DV
1852 }
1853
920208fb
PF
1854 if (this.isUsingExcanvas_ && this.currentZoomRectArgs_) {
1855 Dygraph.prototype.drawZoomRect_.apply(this, this.currentZoomRectArgs_);
1856 }
1857
d160cc3b 1858 if (this.selPoints_.length > 0) {
6a1aa64f 1859 // Draw colored circles over the center of each selected point
e9fe4a2f 1860 var canvasx = this.selPoints_[0].canvasx;
43af96e7 1861 ctx.save();
758a629f 1862 for (i = 0; i < this.selPoints_.length; i++) {
e9fe4a2f
DV
1863 var pt = this.selPoints_[i];
1864 if (!Dygraph.isOK(pt.canvasy)) continue;
1865
1866 var circleSize = this.attr_('highlightCircleSize', pt.name);
5879307d 1867 var callback = this.attr_("drawHighlightPointCallback", pt.name);
a8ef67a8 1868 var color = this.plotter_.colors[pt.name];
78e58af4
RK
1869 if (!callback) {
1870 callback = Dygraph.Circles.DEFAULT;
1871 }
a8ef67a8
KW
1872 ctx.lineWidth = this.attr_('strokeWidth', pt.name);
1873 ctx.strokeStyle = color;
1874 ctx.fillStyle = color;
78e58af4 1875 callback(this.g, pt.name, ctx, canvasx, pt.canvasy,
a8ef67a8 1876 color, circleSize);
6a1aa64f
DV
1877 }
1878 ctx.restore();
1879
1880 this.previousVerticalX_ = canvasx;
1881 }
1882};
1883
1884/**
629a09ae
DV
1885 * Manually set the selected points and display information about them in the
1886 * legend. The selection can be cleared using clearSelection() and queried
1887 * using getSelection().
1888 * @param { Integer } row number that should be highlighted (i.e. appear with
1889 * hover dots on the chart). Set to false to clear any selection.
857a6931
KW
1890 * @param { seriesName } optional series name to highlight that series with the
1891 * the highlightSeriesOpts setting.
239c712d 1892 */
857a6931 1893Dygraph.prototype.setSelection = function(row, opt_seriesName) {
239c712d
NAG
1894 // Extract the points we've selected
1895 this.selPoints_ = [];
1896 var pos = 0;
50360fd0 1897
239c712d 1898 if (row !== false) {
81cb07d6 1899 row -= this.getLeftBoundary_();
16269f6e 1900 }
50360fd0 1901
857a6931 1902 var changed = false;
16269f6e 1903 if (row !== false && row >= 0) {
857a6931
KW
1904 if (row != this.lastRow_) changed = true;
1905 this.lastRow_ = row;
82c6fe4d
KW
1906 for (var setIdx = 0; setIdx < this.layout_.datasets.length; ++setIdx) {
1907 var set = this.layout_.datasets[setIdx];
1908 if (row < set.length) {
38f33a44 1909 var point = this.layout_.points[pos+row];
ccd9d7c2 1910
38f33a44 1911 if (this.attr_("stackedGraph")) {
8c03ba63 1912 point = this.layout_.unstackPointAtIndex(pos+row);
38f33a44 1913 }
ccd9d7c2 1914
04c104d7 1915 if (!(point.yval === null)) this.selPoints_.push(point);
16269f6e 1916 }
82c6fe4d 1917 pos += set.length;
239c712d 1918 }
857a6931
KW
1919 } else {
1920 if (this.lastRow_ >= 0) changed = true;
1921 this.lastRow_ = -1;
16269f6e 1922 }
50360fd0 1923
16269f6e 1924 if (this.selPoints_.length) {
239c712d 1925 this.lastx_ = this.selPoints_[0].xval;
239c712d 1926 } else {
857a6931 1927 this.lastx_ = -1;
239c712d
NAG
1928 }
1929
857a6931
KW
1930 if (opt_seriesName !== undefined) {
1931 if (this.highlightSet_ !== opt_seriesName) changed = true;
1932 this.highlightSet_ = opt_seriesName;
239c712d
NAG
1933 }
1934
857a6931
KW
1935 if (changed) {
1936 this.updateSelection_(undefined);
1937 }
1938 return changed;
239c712d
NAG
1939};
1940
1941/**
6a1aa64f
DV
1942 * The mouse has left the canvas. Clear out whatever artifacts remain
1943 * @param {Object} event the mouseout event from the browser.
1944 * @private
1945 */
285a6bda 1946Dygraph.prototype.mouseOut_ = function(event) {
a4c6a67c
AV
1947 if (this.attr_("unhighlightCallback")) {
1948 this.attr_("unhighlightCallback")(event);
1949 }
1950
43af96e7 1951 if (this.attr_("hideOverlayOnMouseOut")) {
239c712d 1952 this.clearSelection();
43af96e7 1953 }
6a1aa64f
DV
1954};
1955
239c712d 1956/**
629a09ae
DV
1957 * Clears the current selection (i.e. points that were highlighted by moving
1958 * the mouse over the chart).
239c712d
NAG
1959 */
1960Dygraph.prototype.clearSelection = function() {
e2c21500
DV
1961 this.cascadeEvents_('deselect', {});
1962
239c712d 1963 // Get rid of the overlay data
857a6931
KW
1964 if (this.fadeLevel) {
1965 this.animateSelection_(-1);
1966 return;
1967 }
2cf95fff 1968 this.canvas_ctx_.clearRect(0, 0, this.width_, this.height_);
857a6931 1969 this.fadeLevel = 0;
239c712d
NAG
1970 this.selPoints_ = [];
1971 this.lastx_ = -1;
857a6931
KW
1972 this.lastRow_ = -1;
1973 this.highlightSet_ = null;
758a629f 1974};
239c712d 1975
103b7292 1976/**
629a09ae
DV
1977 * Returns the number of the currently selected row. To get data for this row,
1978 * you can use the getValue method.
1979 * @return { Integer } row number, or -1 if nothing is selected
103b7292
NAG
1980 */
1981Dygraph.prototype.getSelection = function() {
1982 if (!this.selPoints_ || this.selPoints_.length < 1) {
1983 return -1;
1984 }
50360fd0 1985
103b7292
NAG
1986 for (var row=0; row<this.layout_.points.length; row++ ) {
1987 if (this.layout_.points[row].x == this.selPoints_[0].x) {
81cb07d6 1988 return row + this.getLeftBoundary_();
103b7292
NAG
1989 }
1990 }
1991 return -1;
2e1fcf1a 1992};
103b7292 1993
e2c21500
DV
1994/**
1995 * Returns the name of the currently-highlighted series.
1996 * Only available when the highlightSeriesOpts option is in use.
1997 */
857a6931
KW
1998Dygraph.prototype.getHighlightSeries = function() {
1999 return this.highlightSet_;
2000};
2001
19589a3e 2002/**
6a1aa64f
DV
2003 * Fires when there's data available to be graphed.
2004 * @param {String} data Raw CSV data to be plotted
2005 * @private
2006 */
285a6bda 2007Dygraph.prototype.loadedEvent_ = function(data) {
6a1aa64f 2008 this.rawData_ = this.parseCSV_(data);
26ca7938 2009 this.predraw_();
6a1aa64f
DV
2010};
2011
6a1aa64f
DV
2012/**
2013 * Add ticks on the x-axis representing years, months, quarters, weeks, or days
2014 * @private
2015 */
285a6bda 2016Dygraph.prototype.addXTicks_ = function() {
6a1aa64f 2017 // Determine the correct ticks scale on the x-axis: quarterly, monthly, ...
7201b11e 2018 var range;
6a1aa64f 2019 if (this.dateWindow_) {
7201b11e 2020 range = [this.dateWindow_[0], this.dateWindow_[1]];
6a1aa64f 2021 } else {
395e98a3 2022 range = this.fullXRange_();
7201b11e
JB
2023 }
2024
48e614ac
DV
2025 var xAxisOptionsView = this.optionsViewForAxis_('x');
2026 var xTicks = xAxisOptionsView('ticker')(
2027 range[0],
2028 range[1],
2029 this.width_, // TODO(danvk): should be area.width
2030 xAxisOptionsView,
2031 this);
2032 // var msg = 'ticker(' + range[0] + ', ' + range[1] + ', ' + this.width_ + ', ' + this.attr_('pixelsPerXLabel') + ') -> ' + JSON.stringify(xTicks);
2033 // console.log(msg);
b2c9222a 2034 this.layout_.setXTicks(xTicks);
32988383
DV
2035};
2036
629a09ae
DV
2037/**
2038 * @private
2039 * Computes the range of the data series (including confidence intervals).
2040 * @param { [Array] } series either [ [x1, y1], [x2, y2], ... ] or
2041 * [ [x1, [y1, dev_low, dev_high]], [x2, [y2, dev_low, dev_high]], ...
2042 * @return [low, high]
2043 */
5011e7a1 2044Dygraph.prototype.extremeValues_ = function(series) {
758a629f 2045 var minY = null, maxY = null, j, y;
5011e7a1 2046
9922b78b 2047 var bars = this.attr_("errorBars") || this.attr_("customBars");
5011e7a1
DV
2048 if (bars) {
2049 // With custom bars, maxY is the max of the high values.
758a629f
DV
2050 for (j = 0; j < series.length; j++) {
2051 y = series[j][1][0];
5011e7a1
DV
2052 if (!y) continue;
2053 var low = y - series[j][1][1];
2054 var high = y + series[j][1][2];
2055 if (low > y) low = y; // this can happen with custom bars,
2056 if (high < y) high = y; // e.g. in tests/custom-bars.html
758a629f 2057 if (maxY === null || high > maxY) {
5011e7a1
DV
2058 maxY = high;
2059 }
758a629f 2060 if (minY === null || low < minY) {
5011e7a1
DV
2061 minY = low;
2062 }
2063 }
2064 } else {
758a629f
DV
2065 for (j = 0; j < series.length; j++) {
2066 y = series[j][1];
d12999d3 2067 if (y === null || isNaN(y)) continue;
758a629f 2068 if (maxY === null || y > maxY) {
5011e7a1
DV
2069 maxY = y;
2070 }
758a629f 2071 if (minY === null || y < minY) {
5011e7a1
DV
2072 minY = y;
2073 }
2074 }
2075 }
2076
2077 return [minY, maxY];
2078};
2079
6a1aa64f 2080/**
629a09ae 2081 * @private
26ca7938
DV
2082 * This function is called once when the chart's data is changed or the options
2083 * dictionary is updated. It is _not_ called when the user pans or zooms. The
2084 * idea is that values derived from the chart's data can be computed here,
2085 * rather than every time the chart is drawn. This includes things like the
2086 * number of axes, rolling averages, etc.
2087 */
2088Dygraph.prototype.predraw_ = function() {
7153e001
DV
2089 var start = new Date();
2090
26ca7938
DV
2091 // TODO(danvk): move more computations out of drawGraph_ and into here.
2092 this.computeYAxes_();
2093
2094 // Create a new plotter.
70c80071 2095 if (this.plotter_) this.plotter_.clear();
26ca7938 2096 this.plotter_ = new DygraphCanvasRenderer(this,
2cf95fff
RK
2097 this.hidden_,
2098 this.hidden_ctx_,
0e23cfc6 2099 this.layout_);
26ca7938 2100
0abfbd7e
DV
2101 // The roller sits in the bottom left corner of the chart. We don't know where
2102 // this will be until the options are available, so it's positioned here.
8c69de65 2103 this.createRollInterface_();
26ca7938 2104
e2c21500 2105 this.cascadeEvents_('predraw');
0abfbd7e 2106
ccd9d7c2
PF
2107 if (this.rangeSelector_) {
2108 this.rangeSelector_.renderStaticLayer();
2109 }
2110
b1a3b195
DV
2111 // Convert the raw data (a 2D array) into the internal format and compute
2112 // rolling averages.
2113 this.rolledSeries_ = [null]; // x-axis is the first series and it's special
395e98a3 2114 for (var i = 1; i < this.numColumns(); i++) {
04c104d7
KW
2115 var logScale = this.attr_('logscale', i); // TODO(klausw): this looks wrong
2116 var series = this.extractSeries_(this.rawData_, i, logScale);
b1a3b195
DV
2117 series = this.rollingAverage(series, this.rollPeriod_);
2118 this.rolledSeries_.push(series);
2119 }
2120
26ca7938
DV
2121 // If the data or options have changed, then we'd better redraw.
2122 this.drawGraph_();
4b4d1a63
DV
2123
2124 // This is used to determine whether to do various animations.
2125 var end = new Date();
2126 this.drawingTimeMs_ = (end - start);
26ca7938
DV
2127};
2128
2129/**
b1a3b195
DV
2130 * Loop over all fields and create datasets, calculating extreme y-values for
2131 * each series and extreme x-indices as we go.
fc4e84fa 2132 *
b1a3b195
DV
2133 * dateWindow is passed in as an explicit parameter so that we can compute
2134 * extreme values "speculatively", i.e. without actually setting state on the
2135 * dygraph.
fc4e84fa 2136 *
b1a3b195
DV
2137 * TODO(danvk): make this more of a true function
2138 * @return [ datasets, seriesExtremes, boundaryIds ]
6a1aa64f
DV
2139 * @private
2140 */
b1a3b195
DV
2141Dygraph.prototype.gatherDatasets_ = function(rolledSeries, dateWindow) {
2142 var boundaryIds = [];
354e15ab
DE
2143 var cumulative_y = []; // For stacked series.
2144 var datasets = [];
f09fc545 2145 var extremes = {}; // series name -> [low, high]
758a629f 2146 var i, j, k;
f09fc545 2147
b1a3b195
DV
2148 // Loop over the fields (series). Go from the last to the first,
2149 // because if they're stacked that's how we accumulate the values.
2150 var num_series = rolledSeries.length - 1;
758a629f 2151 for (i = num_series; i >= 1; i--) {
1cf11047
DV
2152 if (!this.visibility()[i - 1]) continue;
2153
b1a3b195 2154 // TODO(danvk): is this copy really necessary?
6a1aa64f 2155 var series = [];
758a629f 2156 for (j = 0; j < rolledSeries[i].length; j++) {
b1a3b195 2157 series.push(rolledSeries[i][j]);
6a1aa64f 2158 }
2f5e7e1a 2159
6a1aa64f 2160 // Prune down to the desired range, if necessary (for zooming)
1a26f3fb
DV
2161 // Because there can be lines going to points outside of the visible area,
2162 // we actually prune to visible points, plus one on either side.
9922b78b 2163 var bars = this.attr_("errorBars") || this.attr_("customBars");
b1a3b195
DV
2164 if (dateWindow) {
2165 var low = dateWindow[0];
2166 var high = dateWindow[1];
6a1aa64f 2167 var pruned = [];
1a26f3fb
DV
2168 // TODO(danvk): do binary search instead of linear search.
2169 // TODO(danvk): pass firstIdx and lastIdx directly to the renderer.
2170 var firstIdx = null, lastIdx = null;
758a629f 2171 for (k = 0; k < series.length; k++) {
1a26f3fb
DV
2172 if (series[k][0] >= low && firstIdx === null) {
2173 firstIdx = k;
2174 }
2175 if (series[k][0] <= high) {
2176 lastIdx = k;
6a1aa64f
DV
2177 }
2178 }
1a26f3fb
DV
2179 if (firstIdx === null) firstIdx = 0;
2180 if (firstIdx > 0) firstIdx--;
2181 if (lastIdx === null) lastIdx = series.length - 1;
2182 if (lastIdx < series.length - 1) lastIdx++;
b1a3b195 2183 boundaryIds[i-1] = [firstIdx, lastIdx];
758a629f 2184 for (k = firstIdx; k <= lastIdx; k++) {
1a26f3fb 2185 pruned.push(series[k]);
6a1aa64f
DV
2186 }
2187 series = pruned;
16269f6e 2188 } else {
b1a3b195 2189 boundaryIds[i-1] = [0, series.length-1];
6a1aa64f
DV
2190 }
2191
f09fc545 2192 var seriesExtremes = this.extremeValues_(series);
5011e7a1 2193
6a1aa64f 2194 if (bars) {
758a629f 2195 for (j=0; j<series.length; j++) {
5061b42f
DV
2196 series[j] = [series[j][0],
2197 series[j][1][0],
2198 series[j][1][1],
2199 series[j][1][2]];
354e15ab 2200 }
43af96e7 2201 } else if (this.attr_("stackedGraph")) {
43af96e7
NK
2202 var l = series.length;
2203 var actual_y;
758a629f 2204 for (j = 0; j < l; j++) {
354e15ab
DE
2205 // If one data set has a NaN, let all subsequent stacked
2206 // sets inherit the NaN -- only start at 0 for the first set.
2207 var x = series[j][0];
41b0f691 2208 if (cumulative_y[x] === undefined) {
354e15ab 2209 cumulative_y[x] = 0;
41b0f691 2210 }
43af96e7
NK
2211
2212 actual_y = series[j][1];
04c104d7
KW
2213 if (actual_y === null) {
2214 series[j] = [x, null];
2215 continue;
2216 }
2217
354e15ab 2218 cumulative_y[x] += actual_y;
43af96e7 2219
758a629f 2220 series[j] = [x, cumulative_y[x]];
43af96e7 2221
41b0f691
DV
2222 if (cumulative_y[x] > seriesExtremes[1]) {
2223 seriesExtremes[1] = cumulative_y[x];
2224 }
2225 if (cumulative_y[x] < seriesExtremes[0]) {
2226 seriesExtremes[0] = cumulative_y[x];
2227 }
43af96e7 2228 }
6a1aa64f 2229 }
354e15ab 2230
b1a3b195
DV
2231 var seriesName = this.attr_("labels")[i];
2232 extremes[seriesName] = seriesExtremes;
354e15ab 2233 datasets[i] = series;
6a1aa64f
DV
2234 }
2235
7d463f49
KW
2236 // For stacked graphs, a NaN value for any point in the sum should create a
2237 // clean gap in the graph. Back-propagate NaNs to all points at this X value.
2238 if (this.attr_("stackedGraph")) {
2239 for (k = datasets.length - 1; k >= 0; --k) {
2240 // Use the first nonempty dataset to get X values.
2241 if (!datasets[k]) continue;
2242 for (j = 0; j < datasets[k].length; j++) {
2243 var x = datasets[k][j][0];
2244 if (isNaN(cumulative_y[x])) {
2245 // Set all Y values to NaN at that X value.
2246 for (i = datasets.length - 1; i >= 0; i--) {
2247 if (!datasets[i]) continue;
2248 datasets[i][j][1] = NaN;
2249 }
2250 }
2251 }
2252 break;
2253 }
2254 }
2255
b1a3b195
DV
2256 return [ datasets, extremes, boundaryIds ];
2257};
2258
2259/**
2260 * Update the graph with new data. This method is called when the viewing area
2261 * has changed. If the underlying data or options have changed, predraw_ will
2262 * be called before drawGraph_ is called.
2263 *
b1a3b195
DV
2264 * @private
2265 */
e2c21500 2266Dygraph.prototype.drawGraph_ = function() {
b1a3b195
DV
2267 var start = new Date();
2268
b1a3b195
DV
2269 // This is used to set the second parameter to drawCallback, below.
2270 var is_initial_draw = this.is_initial_draw_;
2271 this.is_initial_draw_ = false;
2272
b1a3b195
DV
2273 this.layout_.removeAllDatasets();
2274 this.setColors_();
758a629f 2275 this.attrs_.pointSize = 0.5 * this.attr_('highlightCircleSize');
b1a3b195
DV
2276
2277 var packed = this.gatherDatasets_(this.rolledSeries_, this.dateWindow_);
2278 var datasets = packed[0];
2279 var extremes = packed[1];
2280 this.boundaryIds_ = packed[2];
2281
82c6fe4d
KW
2282 this.setIndexByName_ = {};
2283 var labels = this.attr_("labels");
2284 if (labels.length > 0) {
2285 this.setIndexByName_[labels[0]] = 0;
2286 }
857a6931 2287 var dataIdx = 0;
354e15ab 2288 for (var i = 1; i < datasets.length; i++) {
82c6fe4d 2289 this.setIndexByName_[labels[i]] = i;
4523c1f6 2290 if (!this.visibility()[i - 1]) continue;
82c6fe4d 2291 this.layout_.addDataset(labels[i], datasets[i]);
857a6931 2292 this.datasetIndex_[i] = dataIdx++;
43af96e7
NK
2293 }
2294
6faebb69 2295 this.computeYAxisRanges_(extremes);
b2c9222a
DV
2296 this.layout_.setYAxes(this.axes_);
2297
6a1aa64f
DV
2298 this.addXTicks_();
2299
b2c9222a 2300 // Save the X axis zoomed status as the updateOptions call will tend to set it erroneously
81856f70 2301 var tmp_zoomed_x = this.zoomed_x_;
6a1aa64f 2302 // Tell PlotKit to use this new data and render itself
b2c9222a 2303 this.layout_.setDateWindow(this.dateWindow_);
81856f70 2304 this.zoomed_x_ = tmp_zoomed_x;
6a1aa64f 2305 this.layout_.evaluateWithError();
e2c21500 2306 this.renderGraph_(is_initial_draw);
9ca829f2
DV
2307
2308 if (this.attr_("timingName")) {
2309 var end = new Date();
2310 if (console) {
758a629f 2311 console.log(this.attr_("timingName") + " - drawGraph: " + (end - start) + "ms");
9ca829f2
DV
2312 }
2313 }
2314};
2315
e2c21500
DV
2316/**
2317 * This does the work of drawing the chart. It assumes that the layout and axis
2318 * scales have already been set (e.g. by predraw_).
2319 *
2320 * @private
2321 */
2322Dygraph.prototype.renderGraph_ = function(is_initial_draw) {
6a1aa64f
DV
2323 this.plotter_.clear();
2324 this.plotter_.render();
f6401bf6 2325 this.canvas_.getContext('2d').clearRect(0, 0, this.canvas_.width,
2f5e7e1a 2326 this.canvas_.height);
599fb4ad 2327
4a0cb9c4 2328 // Generate a static legend before any particular point is selected.
2fccd3dc 2329
ccd9d7c2
PF
2330 if (this.rangeSelector_) {
2331 this.rangeSelector_.renderInteractiveLayer();
2332 }
2333
e2c21500 2334 this.cascadeEvents_('drawChart');
599fb4ad 2335 if (this.attr_("drawCallback") !== null) {
fe0b7c03 2336 this.attr_("drawCallback")(this, is_initial_draw);
599fb4ad 2337 }
6a1aa64f
DV
2338};
2339
2340/**
629a09ae 2341 * @private
26ca7938
DV
2342 * Determine properties of the y-axes which are independent of the data
2343 * currently being displayed. This includes things like the number of axes and
2344 * the style of the axes. It does not include the range of each axis and its
2345 * tick marks.
2346 * This fills in this.axes_ and this.seriesToAxisMap_.
2347 * axes_ = [ { options } ]
2348 * seriesToAxisMap_ = { seriesName: 0, seriesName2: 1, ... }
2349 * indices are into the axes_ array.
f09fc545 2350 */
26ca7938 2351Dygraph.prototype.computeYAxes_ = function() {
d64b8fea
RK
2352 // Preserve valueWindow settings if they exist, and if the user hasn't
2353 // specified a new valueRange.
4dd0ac55 2354 var i, valueWindows, seriesName, axis, index, opts, v;
758a629f 2355 if (this.axes_ !== undefined && this.user_attrs_.hasOwnProperty("valueRange") === false) {
d64b8fea 2356 valueWindows = [];
758a629f 2357 for (index = 0; index < this.axes_.length; index++) {
d64b8fea
RK
2358 valueWindows.push(this.axes_[index].valueWindow);
2359 }
2360 }
2361
00aa7f61 2362 this.axes_ = [{ yAxisId : 0, g : this }]; // always have at least one y-axis.
26ca7938
DV
2363 this.seriesToAxisMap_ = {};
2364
2365 // Get a list of series names.
2366 var labels = this.attr_("labels");
1c77a3a1 2367 var series = {};
758a629f 2368 for (i = 1; i < labels.length; i++) series[labels[i]] = (i - 1);
f09fc545
DV
2369
2370 // all options which could be applied per-axis:
2371 var axisOptions = [
2372 'includeZero',
2373 'valueRange',
2374 'labelsKMB',
2375 'labelsKMG2',
2376 'pixelsPerYLabel',
2377 'yAxisLabelWidth',
2378 'axisLabelFontSize',
7d0e7a0d
RK
2379 'axisTickSize',
2380 'logscale'
f09fc545
DV
2381 ];
2382
2383 // Copy global axis options over to the first axis.
758a629f 2384 for (i = 0; i < axisOptions.length; i++) {
f09fc545 2385 var k = axisOptions[i];
4dd0ac55 2386 v = this.attr_(k);
26ca7938 2387 if (v) this.axes_[0][k] = v;
f09fc545
DV
2388 }
2389
2390 // Go through once and add all the axes.
758a629f 2391 for (seriesName in series) {
26ca7938 2392 if (!series.hasOwnProperty(seriesName)) continue;
758a629f
DV
2393 axis = this.attr_("axis", seriesName);
2394 if (axis === null) {
26ca7938 2395 this.seriesToAxisMap_[seriesName] = 0;
f09fc545
DV
2396 continue;
2397 }
2398 if (typeof(axis) == 'object') {
2399 // Add a new axis, making a copy of its per-axis options.
4dd0ac55 2400 opts = {};
26ca7938 2401 Dygraph.update(opts, this.axes_[0]);
f09fc545 2402 Dygraph.update(opts, { valueRange: null }); // shouldn't inherit this.
00aa7f61
RK
2403 var yAxisId = this.axes_.length;
2404 opts.yAxisId = yAxisId;
2405 opts.g = this;
f09fc545 2406 Dygraph.update(opts, axis);
26ca7938 2407 this.axes_.push(opts);
00aa7f61 2408 this.seriesToAxisMap_[seriesName] = yAxisId;
f09fc545
DV
2409 }
2410 }
2411
2412 // Go through one more time and assign series to an axis defined by another
2413 // series, e.g. { 'Y1: { axis: {} }, 'Y2': { axis: 'Y1' } }
758a629f 2414 for (seriesName in series) {
26ca7938 2415 if (!series.hasOwnProperty(seriesName)) continue;
758a629f 2416 axis = this.attr_("axis", seriesName);
f09fc545 2417 if (typeof(axis) == 'string') {
26ca7938 2418 if (!this.seriesToAxisMap_.hasOwnProperty(axis)) {
f09fc545
DV
2419 this.error("Series " + seriesName + " wants to share a y-axis with " +
2420 "series " + axis + ", which does not define its own axis.");
2421 return null;
2422 }
26ca7938
DV
2423 var idx = this.seriesToAxisMap_[axis];
2424 this.seriesToAxisMap_[seriesName] = idx;
f09fc545
DV
2425 }
2426 }
1c77a3a1 2427
758a629f 2428 if (valueWindows !== undefined) {
d64b8fea 2429 // Restore valueWindow settings.
758a629f 2430 for (index = 0; index < valueWindows.length; index++) {
d64b8fea
RK
2431 this.axes_[index].valueWindow = valueWindows[index];
2432 }
2433 }
4dd0ac55
RV
2434
2435 // New axes options
2436 for (axis = 0; axis < this.axes_.length; axis++) {
2437 if (axis === 0) {
2438 opts = this.optionsViewForAxis_('y' + (axis ? '2' : ''));
2439 v = opts("valueRange");
2440 if (v) this.axes_[axis].valueRange = v;
2441 } else { // To keep old behavior
2442 var axes = this.user_attrs_.axes;
2443 if (axes && axes.y2) {
2444 v = axes.y2.valueRange;
2445 if (v) this.axes_[axis].valueRange = v;
2446 }
2447 }
2448 }
2449
26ca7938
DV
2450};
2451
2452/**
2453 * Returns the number of y-axes on the chart.
2454 * @return {Number} the number of axes.
2455 */
2456Dygraph.prototype.numAxes = function() {
2457 var last_axis = 0;
2458 for (var series in this.seriesToAxisMap_) {
2459 if (!this.seriesToAxisMap_.hasOwnProperty(series)) continue;
2460 var idx = this.seriesToAxisMap_[series];
2461 if (idx > last_axis) last_axis = idx;
2462 }
2463 return 1 + last_axis;
2464};
2465
2466/**
629a09ae 2467 * @private
b2c9222a
DV
2468 * Returns axis properties for the given series.
2469 * @param { String } setName The name of the series for which to get axis
2470 * properties, e.g. 'Y1'.
2471 * @return { Object } The axis properties.
2472 */
2473Dygraph.prototype.axisPropertiesForSeries = function(series) {
2474 // TODO(danvk): handle errors.
2475 return this.axes_[this.seriesToAxisMap_[series]];
2476};
2477
2478/**
2479 * @private
26ca7938
DV
2480 * Determine the value range and tick marks for each axis.
2481 * @param {Object} extremes A mapping from seriesName -> [low, high]
2482 * This fills in the valueRange and ticks fields in each entry of this.axes_.
2483 */
2484Dygraph.prototype.computeYAxisRanges_ = function(extremes) {
2485 // Build a map from axis number -> [list of series names]
758a629f
DV
2486 var seriesForAxis = [], series;
2487 for (series in this.seriesToAxisMap_) {
26ca7938
DV
2488 if (!this.seriesToAxisMap_.hasOwnProperty(series)) continue;
2489 var idx = this.seriesToAxisMap_[series];
2490 while (seriesForAxis.length <= idx) seriesForAxis.push([]);
2491 seriesForAxis[idx].push(series);
2492 }
f09fc545
DV
2493
2494 // Compute extreme values, a span and tick marks for each axis.
26ca7938
DV
2495 for (var i = 0; i < this.axes_.length; i++) {
2496 var axis = this.axes_[i];
25f76ae3 2497
06fc69b6
AV
2498 if (!seriesForAxis[i]) {
2499 // If no series are defined or visible then use a reasonable default
2500 axis.extremeRange = [0, 1];
2501 } else {
1c77a3a1 2502 // Calculate the extremes of extremes.
758a629f 2503 series = seriesForAxis[i];
f09fc545
DV
2504 var minY = Infinity; // extremes[series[0]][0];
2505 var maxY = -Infinity; // extremes[series[0]][1];
ba049b89 2506 var extremeMinY, extremeMaxY;
a2da3777 2507
f09fc545 2508 for (var j = 0; j < series.length; j++) {
a2da3777
DV
2509 // this skips invisible series
2510 if (!extremes.hasOwnProperty(series[j])) continue;
2511
ba049b89
NN
2512 // Only use valid extremes to stop null data series' from corrupting the scale.
2513 extremeMinY = extremes[series[j]][0];
758a629f 2514 if (extremeMinY !== null) {
36dfa958 2515 minY = Math.min(extremeMinY, minY);
ba049b89
NN
2516 }
2517 extremeMaxY = extremes[series[j]][1];
758a629f 2518 if (extremeMaxY !== null) {
36dfa958 2519 maxY = Math.max(extremeMaxY, maxY);
ba049b89 2520 }
f09fc545
DV
2521 }
2522 if (axis.includeZero && minY > 0) minY = 0;
2523
a2da3777 2524 // Ensure we have a valid scale, otherwise default to [0, 1] for safety.
36dfa958 2525 if (minY == Infinity) minY = 0;
a2da3777 2526 if (maxY == -Infinity) maxY = 1;
ba049b89 2527
f09fc545
DV
2528 // Add some padding and round up to an integer to be human-friendly.
2529 var span = maxY - minY;
2530 // special case: if we have no sense of scale, use +/-10% of the sole value.
758a629f 2531 if (span === 0) { span = maxY; }
f09fc545 2532
758a629f 2533 var maxAxisY, minAxisY;
7d0e7a0d 2534 if (axis.logscale) {
758a629f
DV
2535 maxAxisY = maxY + 0.1 * span;
2536 minAxisY = minY;
ff022deb 2537 } else {
758a629f
DV
2538 maxAxisY = maxY + 0.1 * span;
2539 minAxisY = minY - 0.1 * span;
f09fc545 2540
ff022deb
RK
2541 // Try to include zero and make it minAxisY (or maxAxisY) if it makes sense.
2542 if (!this.attr_("avoidMinZero")) {
2543 if (minAxisY < 0 && minY >= 0) minAxisY = 0;
2544 if (maxAxisY > 0 && maxY <= 0) maxAxisY = 0;
2545 }
f09fc545 2546
ff022deb
RK
2547 if (this.attr_("includeZero")) {
2548 if (maxY < 0) maxAxisY = 0;
2549 if (minY > 0) minAxisY = 0;
2550 }
f09fc545 2551 }
4cac8c7a
RK
2552 axis.extremeRange = [minAxisY, maxAxisY];
2553 }
2554 if (axis.valueWindow) {
2555 // This is only set if the user has zoomed on the y-axis. It is never set
2556 // by a user. It takes precedence over axis.valueRange because, if you set
2557 // valueRange, you'd still expect to be able to pan.
2558 axis.computedValueRange = [axis.valueWindow[0], axis.valueWindow[1]];
2559 } else if (axis.valueRange) {
2560 // This is a user-set value range for this axis.
2561 axis.computedValueRange = [axis.valueRange[0], axis.valueRange[1]];
2562 } else {
2563 axis.computedValueRange = axis.extremeRange;
f09fc545
DV
2564 }
2565
0d64e596
DV
2566 // Add ticks. By default, all axes inherit the tick positions of the
2567 // primary axis. However, if an axis is specifically marked as having
2568 // independent ticks, then that is permissible as well.
48e614ac
DV
2569 var opts = this.optionsViewForAxis_('y' + (i ? '2' : ''));
2570 var ticker = opts('ticker');
758a629f 2571 if (i === 0 || axis.independentTicks) {
48e614ac
DV
2572 axis.ticks = ticker(axis.computedValueRange[0],
2573 axis.computedValueRange[1],
2574 this.height_, // TODO(danvk): should be area.height
2575 opts,
2576 this);
0d64e596
DV
2577 } else {
2578 var p_axis = this.axes_[0];
2579 var p_ticks = p_axis.ticks;
2580 var p_scale = p_axis.computedValueRange[1] - p_axis.computedValueRange[0];
2581 var scale = axis.computedValueRange[1] - axis.computedValueRange[0];
2582 var tick_values = [];
25f76ae3
DV
2583 for (var k = 0; k < p_ticks.length; k++) {
2584 var y_frac = (p_ticks[k].v - p_axis.computedValueRange[0]) / p_scale;
0d64e596
DV
2585 var y_val = axis.computedValueRange[0] + y_frac * scale;
2586 tick_values.push(y_val);
2587 }
2588
48e614ac
DV
2589 axis.ticks = ticker(axis.computedValueRange[0],
2590 axis.computedValueRange[1],
2591 this.height_, // TODO(danvk): should be area.height
2592 opts,
2593 this,
2594 tick_values);
0d64e596 2595 }
f09fc545 2596 }
f09fc545 2597};
25f76ae3 2598
f09fc545 2599/**
b1a3b195
DV
2600 * Extracts one series from the raw data (a 2D array) into an array of (date,
2601 * value) tuples.
2602 *
2603 * This is where undesirable points (i.e. negative values on log scales and
2604 * missing values through which we wish to connect lines) are dropped.
2605 *
2606 * @private
2607 */
04c104d7 2608Dygraph.prototype.extractSeries_ = function(rawData, i, logScale) {
b1a3b195
DV
2609 var series = [];
2610 for (var j = 0; j < rawData.length; j++) {
2611 var x = rawData[j][0];
2612 var point = rawData[j][i];
2613 if (logScale) {
2614 // On the log scale, points less than zero do not exist.
04c104d7 2615 // This will create a gap in the chart.
b1a3b195
DV
2616 if (point <= 0) {
2617 point = null;
2618 }
b1a3b195 2619 }
04c104d7 2620 series.push([x, point]);
b1a3b195
DV
2621 }
2622 return series;
2623};
2624
2625/**
629a09ae 2626 * @private
6a1aa64f
DV
2627 * Calculates the rolling average of a data set.
2628 * If originalData is [label, val], rolls the average of those.
2629 * If originalData is [label, [, it's interpreted as [value, stddev]
2630 * and the roll is returned in the same form, with appropriately reduced
2631 * stddev for each value.
2632 * Note that this is where fractional input (i.e. '5/10') is converted into
2633 * decimal values.
2634 * @param {Array} originalData The data in the appropriate format (see above)
6faebb69
JB
2635 * @param {Number} rollPeriod The number of points over which to average the
2636 * data
6a1aa64f 2637 */
285a6bda 2638Dygraph.prototype.rollingAverage = function(originalData, rollPeriod) {
6a1aa64f
DV
2639 if (originalData.length < 2)
2640 return originalData;
758a629f 2641 rollPeriod = Math.min(rollPeriod, originalData.length);
6a1aa64f 2642 var rollingData = [];
285a6bda 2643 var sigma = this.attr_("sigma");
6a1aa64f 2644
758a629f 2645 var low, high, i, j, y, sum, num_ok, stddev;
6a1aa64f
DV
2646 if (this.fractions_) {
2647 var num = 0;
2648 var den = 0; // numerator/denominator
2649 var mult = 100.0;
758a629f 2650 for (i = 0; i < originalData.length; i++) {
6a1aa64f
DV
2651 num += originalData[i][1][0];
2652 den += originalData[i][1][1];
2653 if (i - rollPeriod >= 0) {
2654 num -= originalData[i - rollPeriod][1][0];
2655 den -= originalData[i - rollPeriod][1][1];
2656 }
2657
2658 var date = originalData[i][0];
2659 var value = den ? num / den : 0.0;
285a6bda 2660 if (this.attr_("errorBars")) {
395e98a3 2661 if (this.attr_("wilsonInterval")) {
6a1aa64f
DV
2662 // For more details on this confidence interval, see:
2663 // http://en.wikipedia.org/wiki/Binomial_confidence_interval
2664 if (den) {
2665 var p = value < 0 ? 0 : value, n = den;
2666 var pm = sigma * Math.sqrt(p*(1-p)/n + sigma*sigma/(4*n*n));
2667 var denom = 1 + sigma * sigma / den;
758a629f
DV
2668 low = (p + sigma * sigma / (2 * den) - pm) / denom;
2669 high = (p + sigma * sigma / (2 * den) + pm) / denom;
6a1aa64f
DV
2670 rollingData[i] = [date,
2671 [p * mult, (p - low) * mult, (high - p) * mult]];
2672 } else {
2673 rollingData[i] = [date, [0, 0, 0]];
2674 }
2675 } else {
758a629f 2676 stddev = den ? sigma * Math.sqrt(value * (1 - value) / den) : 1.0;
6a1aa64f
DV
2677 rollingData[i] = [date, [mult * value, mult * stddev, mult * stddev]];
2678 }
2679 } else {
2680 rollingData[i] = [date, mult * value];
2681 }
2682 }
9922b78b 2683 } else if (this.attr_("customBars")) {
758a629f 2684 low = 0;
f6885d6a 2685 var mid = 0;
758a629f 2686 high = 0;
f6885d6a 2687 var count = 0;
758a629f 2688 for (i = 0; i < originalData.length; i++) {
6a1aa64f 2689 var data = originalData[i][1];
758a629f 2690 y = data[1];
6a1aa64f 2691 rollingData[i] = [originalData[i][0], [y, y - data[0], data[2] - y]];
f6885d6a 2692
758a629f 2693 if (y !== null && !isNaN(y)) {
49a7d0d5
DV
2694 low += data[0];
2695 mid += y;
2696 high += data[2];
2697 count += 1;
2698 }
f6885d6a
DV
2699 if (i - rollPeriod >= 0) {
2700 var prev = originalData[i - rollPeriod];
758a629f 2701 if (prev[1][1] !== null && !isNaN(prev[1][1])) {
49a7d0d5
DV
2702 low -= prev[1][0];
2703 mid -= prev[1][1];
2704 high -= prev[1][2];
2705 count -= 1;
2706 }
f6885d6a 2707 }
502d5996
DV
2708 if (count) {
2709 rollingData[i] = [originalData[i][0], [ 1.0 * mid / count,
2710 1.0 * (mid - low) / count,
2711 1.0 * (high - mid) / count ]];
2712 } else {
2713 rollingData[i] = [originalData[i][0], [null, null, null]];
2714 }
2769de62 2715 }
6a1aa64f
DV
2716 } else {
2717 // Calculate the rolling average for the first rollPeriod - 1 points where
6faebb69 2718 // there is not enough data to roll over the full number of points
285a6bda 2719 if (!this.attr_("errorBars")){
5011e7a1
DV
2720 if (rollPeriod == 1) {
2721 return originalData;
2722 }
2723
758a629f
DV
2724 for (i = 0; i < originalData.length; i++) {
2725 sum = 0;
2726 num_ok = 0;
2727 for (j = Math.max(0, i - rollPeriod + 1); j < i + 1; j++) {
2728 y = originalData[j][1];
2729 if (y === null || isNaN(y)) continue;
5011e7a1 2730 num_ok++;
2847c1cf 2731 sum += originalData[j][1];
6a1aa64f 2732 }
5011e7a1 2733 if (num_ok) {
2847c1cf 2734 rollingData[i] = [originalData[i][0], sum / num_ok];
5011e7a1 2735 } else {
2847c1cf 2736 rollingData[i] = [originalData[i][0], null];
5011e7a1 2737 }
6a1aa64f 2738 }
2847c1cf
DV
2739
2740 } else {
758a629f
DV
2741 for (i = 0; i < originalData.length; i++) {
2742 sum = 0;
6a1aa64f 2743 var variance = 0;
758a629f
DV
2744 num_ok = 0;
2745 for (j = Math.max(0, i - rollPeriod + 1); j < i + 1; j++) {
2746 y = originalData[j][1][0];
2747 if (y === null || isNaN(y)) continue;
5011e7a1 2748 num_ok++;
6a1aa64f
DV
2749 sum += originalData[j][1][0];
2750 variance += Math.pow(originalData[j][1][1], 2);
2751 }
5011e7a1 2752 if (num_ok) {
758a629f 2753 stddev = Math.sqrt(variance) / num_ok;
5011e7a1
DV
2754 rollingData[i] = [originalData[i][0],
2755 [sum / num_ok, sigma * stddev, sigma * stddev]];
2756 } else {
2757 rollingData[i] = [originalData[i][0], [null, null, null]];
2758 }
6a1aa64f
DV
2759 }
2760 }
2761 }
2762
2763 return rollingData;
2764};
2765
2766/**
285a6bda
DV
2767 * Detects the type of the str (date or numeric) and sets the various
2768 * formatting attributes in this.attrs_ based on this type.
2769 * @param {String} str An x value.
2770 * @private
2771 */
2772Dygraph.prototype.detectTypeFromString_ = function(str) {
2773 var isDate = false;
0842b24b
DV
2774 var dashPos = str.indexOf('-'); // could be 2006-01-01 _or_ 1.0e-2
2775 if ((dashPos > 0 && (str[dashPos-1] != 'e' && str[dashPos-1] != 'E')) ||
285a6bda
DV
2776 str.indexOf('/') >= 0 ||
2777 isNaN(parseFloat(str))) {
2778 isDate = true;
2779 } else if (str.length == 8 && str > '19700101' && str < '20371231') {
2780 // TODO(danvk): remove support for this format.
2781 isDate = true;
2782 }
2783
2784 if (isDate) {
285a6bda 2785 this.attrs_.xValueParser = Dygraph.dateParser;
48e614ac
DV
2786 this.attrs_.axes.x.valueFormatter = Dygraph.dateString_;
2787 this.attrs_.axes.x.ticker = Dygraph.dateTicker;
2788 this.attrs_.axes.x.axisLabelFormatter = Dygraph.dateAxisFormatter;
285a6bda 2789 } else {
c39e1d93 2790 /** @private (shut up, jsdoc!) */
285a6bda 2791 this.attrs_.xValueParser = function(x) { return parseFloat(x); };
48e614ac
DV
2792 // TODO(danvk): use Dygraph.numberValueFormatter here?
2793 /** @private (shut up, jsdoc!) */
2794 this.attrs_.axes.x.valueFormatter = function(x) { return x; };
44462ba3 2795 this.attrs_.axes.x.ticker = Dygraph.numericLinearTicks;
48e614ac 2796 this.attrs_.axes.x.axisLabelFormatter = this.attrs_.axes.x.valueFormatter;
6a1aa64f 2797 }
6a1aa64f
DV
2798};
2799
2800/**
5cd7ac68
DV
2801 * Parses the value as a floating point number. This is like the parseFloat()
2802 * built-in, but with a few differences:
2803 * - the empty string is parsed as null, rather than NaN.
2804 * - if the string cannot be parsed at all, an error is logged.
2805 * If the string can't be parsed, this method returns null.
2806 * @param {String} x The string to be parsed
2807 * @param {Number} opt_line_no The line number from which the string comes.
2808 * @param {String} opt_line The text of the line from which the string comes.
2809 * @private
2810 */
2811
2812// Parse the x as a float or return null if it's not a number.
2813Dygraph.prototype.parseFloat_ = function(x, opt_line_no, opt_line) {
2814 var val = parseFloat(x);
2815 if (!isNaN(val)) return val;
2816
2817 // Try to figure out what happeend.
2818 // If the value is the empty string, parse it as null.
2819 if (/^ *$/.test(x)) return null;
2820
2821 // If it was actually "NaN", return it as NaN.
2822 if (/^ *nan *$/i.test(x)) return NaN;
2823
2824 // Looks like a parsing error.
2825 var msg = "Unable to parse '" + x + "' as a number";
2826 if (opt_line !== null && opt_line_no !== null) {
2827 msg += " on line " + (1+opt_line_no) + " ('" + opt_line + "') of CSV.";
2828 }
2829 this.error(msg);
2830
2831 return null;
2832};
2833
2834/**
629a09ae 2835 * @private
6a1aa64f
DV
2836 * Parses a string in a special csv format. We expect a csv file where each
2837 * line is a date point, and the first field in each line is the date string.
2838 * We also expect that all remaining fields represent series.
285a6bda 2839 * if the errorBars attribute is set, then interpret the fields as:
6a1aa64f 2840 * date, series1, stddev1, series2, stddev2, ...
629a09ae 2841 * @param {[Object]} data See above.
285a6bda 2842 *
629a09ae 2843 * @return [Object] An array with one entry for each row. These entries
285a6bda
DV
2844 * are an array of cells in that row. The first entry is the parsed x-value for
2845 * the row. The second, third, etc. are the y-values. These can take on one of
2846 * three forms, depending on the CSV and constructor parameters:
2847 * 1. numeric value
2848 * 2. [ value, stddev ]
2849 * 3. [ low value, center value, high value ]
6a1aa64f 2850 */
285a6bda 2851Dygraph.prototype.parseCSV_ = function(data) {
6a1aa64f
DV
2852 var ret = [];
2853 var lines = data.split("\n");
758a629f 2854 var vals, j;
3d67f03b
DV
2855
2856 // Use the default delimiter or fall back to a tab if that makes sense.
2857 var delim = this.attr_('delimiter');
2858 if (lines[0].indexOf(delim) == -1 && lines[0].indexOf('\t') >= 0) {
2859 delim = '\t';
2860 }
2861
285a6bda 2862 var start = 0;
d7beab6b
DV
2863 if (!('labels' in this.user_attrs_)) {
2864 // User hasn't explicitly set labels, so they're (presumably) in the CSV.
285a6bda 2865 start = 1;
d7beab6b 2866 this.attrs_.labels = lines[0].split(delim); // NOTE: _not_ user_attrs_.
6a1aa64f 2867 }
5cd7ac68 2868 var line_no = 0;
03b522a4 2869
285a6bda
DV
2870 var xParser;
2871 var defaultParserSet = false; // attempt to auto-detect x value type
2872 var expectedCols = this.attr_("labels").length;
987840a2 2873 var outOfOrder = false;
6a1aa64f
DV
2874 for (var i = start; i < lines.length; i++) {
2875 var line = lines[i];
5cd7ac68 2876 line_no = i;
758a629f 2877 if (line.length === 0) continue; // skip blank lines
3d67f03b
DV
2878 if (line[0] == '#') continue; // skip comment lines
2879 var inFields = line.split(delim);
285a6bda 2880 if (inFields.length < 2) continue;
6a1aa64f
DV
2881
2882 var fields = [];
285a6bda
DV
2883 if (!defaultParserSet) {
2884 this.detectTypeFromString_(inFields[0]);
2885 xParser = this.attr_("xValueParser");
2886 defaultParserSet = true;
2887 }
2888 fields[0] = xParser(inFields[0], this);
6a1aa64f
DV
2889
2890 // If fractions are expected, parse the numbers as "A/B"
2891 if (this.fractions_) {
758a629f 2892 for (j = 1; j < inFields.length; j++) {
6a1aa64f 2893 // TODO(danvk): figure out an appropriate way to flag parse errors.
758a629f 2894 vals = inFields[j].split("/");
7219edb3
DV
2895 if (vals.length != 2) {
2896 this.error('Expected fractional "num/den" values in CSV data ' +
2897 "but found a value '" + inFields[j] + "' on line " +
2898 (1 + i) + " ('" + line + "') which is not of this form.");
2899 fields[j] = [0, 0];
2900 } else {
2901 fields[j] = [this.parseFloat_(vals[0], i, line),
2902 this.parseFloat_(vals[1], i, line)];
2903 }
6a1aa64f 2904 }
285a6bda 2905 } else if (this.attr_("errorBars")) {
6a1aa64f 2906 // If there are error bars, values are (value, stddev) pairs
7219edb3
DV
2907 if (inFields.length % 2 != 1) {
2908 this.error('Expected alternating (value, stdev.) pairs in CSV data ' +
2909 'but line ' + (1 + i) + ' has an odd number of values (' +
2910 (inFields.length - 1) + "): '" + line + "'");
2911 }
758a629f 2912 for (j = 1; j < inFields.length; j += 2) {
5cd7ac68
DV
2913 fields[(j + 1) / 2] = [this.parseFloat_(inFields[j], i, line),
2914 this.parseFloat_(inFields[j + 1], i, line)];
7219edb3 2915 }
9922b78b 2916 } else if (this.attr_("customBars")) {
6a1aa64f 2917 // Bars are a low;center;high tuple
758a629f 2918 for (j = 1; j < inFields.length; j++) {
327a9279
DV
2919 var val = inFields[j];
2920 if (/^ *$/.test(val)) {
2921 fields[j] = [null, null, null];
2922 } else {
758a629f 2923 vals = val.split(";");
327a9279
DV
2924 if (vals.length == 3) {
2925 fields[j] = [ this.parseFloat_(vals[0], i, line),
2926 this.parseFloat_(vals[1], i, line),
2927 this.parseFloat_(vals[2], i, line) ];
2928 } else {
1a5dc2af
RK
2929 this.warn('When using customBars, values must be either blank ' +
2930 'or "low;center;high" tuples (got "' + val +
2931 '" on line ' + (1+i));
327a9279
DV
2932 }
2933 }
6a1aa64f
DV
2934 }
2935 } else {
2936 // Values are just numbers
758a629f 2937 for (j = 1; j < inFields.length; j++) {
5cd7ac68 2938 fields[j] = this.parseFloat_(inFields[j], i, line);
285a6bda 2939 }
6a1aa64f 2940 }
987840a2
DV
2941 if (ret.length > 0 && fields[0] < ret[ret.length - 1][0]) {
2942 outOfOrder = true;
2943 }
285a6bda
DV
2944
2945 if (fields.length != expectedCols) {
2946 this.error("Number of columns in line " + i + " (" + fields.length +
2947 ") does not agree with number of labels (" + expectedCols +
2948 ") " + line);
2949 }
6d0aaa09
DV
2950
2951 // If the user specified the 'labels' option and none of the cells of the
2952 // first row parsed correctly, then they probably double-specified the
2953 // labels. We go with the values set in the option, discard this row and
2954 // log a warning to the JS console.
758a629f 2955 if (i === 0 && this.attr_('labels')) {
6d0aaa09 2956 var all_null = true;
758a629f 2957 for (j = 0; all_null && j < fields.length; j++) {
6d0aaa09
DV
2958 if (fields[j]) all_null = false;
2959 }
2960 if (all_null) {
2961 this.warn("The dygraphs 'labels' option is set, but the first row of " +
2962 "CSV data ('" + line + "') appears to also contain labels. " +
2963 "Will drop the CSV labels and use the option labels.");
2964 continue;
2965 }
2966 }
2967 ret.push(fields);
6a1aa64f 2968 }
987840a2
DV
2969
2970 if (outOfOrder) {
2971 this.warn("CSV is out of order; order it correctly to speed loading.");
758a629f 2972 ret.sort(function(a,b) { return a[0] - b[0]; });
987840a2
DV
2973 }
2974
6a1aa64f
DV
2975 return ret;
2976};
2977
2978/**
629a09ae 2979 * @private
285a6bda
DV
2980 * The user has provided their data as a pre-packaged JS array. If the x values
2981 * are numeric, this is the same as dygraphs' internal format. If the x values
2982 * are dates, we need to convert them from Date objects to ms since epoch.
629a09ae
DV
2983 * @param {[Object]} data
2984 * @return {[Object]} data with numeric x values.
285a6bda
DV
2985 */
2986Dygraph.prototype.parseArray_ = function(data) {
2987 // Peek at the first x value to see if it's numeric.
758a629f 2988 if (data.length === 0) {
285a6bda
DV
2989 this.error("Can't plot empty data set");
2990 return null;
2991 }
758a629f 2992 if (data[0].length === 0) {
285a6bda
DV
2993 this.error("Data set cannot contain an empty row");
2994 return null;
2995 }
2996
758a629f
DV
2997 var i;
2998 if (this.attr_("labels") === null) {
285a6bda
DV
2999 this.warn("Using default labels. Set labels explicitly via 'labels' " +
3000 "in the options parameter");
3001 this.attrs_.labels = [ "X" ];
758a629f 3002 for (i = 1; i < data[0].length; i++) {
285a6bda
DV
3003 this.attrs_.labels.push("Y" + i);
3004 }
3005 }
3006
2dda3850 3007 if (Dygraph.isDateLike(data[0][0])) {
285a6bda 3008 // Some intelligent defaults for a date x-axis.
48e614ac
DV
3009 this.attrs_.axes.x.valueFormatter = Dygraph.dateString_;
3010 this.attrs_.axes.x.axisLabelFormatter = Dygraph.dateAxisFormatter;
3011 this.attrs_.axes.x.ticker = Dygraph.dateTicker;
285a6bda
DV
3012
3013 // Assume they're all dates.
e3ab7b40 3014 var parsedData = Dygraph.clone(data);
758a629f
DV
3015 for (i = 0; i < data.length; i++) {
3016 if (parsedData[i].length === 0) {
a323ff4a 3017 this.error("Row " + (1 + i) + " of data is empty");
285a6bda
DV
3018 return null;
3019 }
758a629f
DV
3020 if (parsedData[i][0] === null ||
3021 typeof(parsedData[i][0].getTime) != 'function' ||
3022 isNaN(parsedData[i][0].getTime())) {
be96a1f5 3023 this.error("x value in row " + (1 + i) + " is not a Date");
285a6bda
DV
3024 return null;
3025 }
3026 parsedData[i][0] = parsedData[i][0].getTime();
3027 }
3028 return parsedData;
3029 } else {
3030 // Some intelligent defaults for a numeric x-axis.
c39e1d93 3031 /** @private (shut up, jsdoc!) */
48e614ac
DV
3032 this.attrs_.axes.x.valueFormatter = function(x) { return x; };
3033 this.attrs_.axes.x.axisLabelFormatter = Dygraph.numberAxisLabelFormatter;
44462ba3 3034 this.attrs_.axes.x.ticker = Dygraph.numericLinearTicks;
285a6bda
DV
3035 return data;
3036 }
3037};
3038
3039/**
79420a1e
DV
3040 * Parses a DataTable object from gviz.
3041 * The data is expected to have a first column that is either a date or a
3042 * number. All subsequent columns must be numbers. If there is a clear mismatch
3043 * between this.xValueParser_ and the type of the first column, it will be
a685723c 3044 * fixed. Fills out rawData_.
629a09ae 3045 * @param {[Object]} data See above.
79420a1e
DV
3046 * @private
3047 */
285a6bda 3048Dygraph.prototype.parseDataTable_ = function(data) {
5829af3d 3049 var shortTextForAnnotationNum = function(num) {
3050 // converts [0-9]+ [A-Z][a-z]*
3051 // example: 0=A, 1=B, 25=Z, 26=Aa, 27=Ab
3052 // and continues like.. Ba Bb .. Za .. Zz..Aaa...Zzz Aaaa Zzzz
3053 var shortText = String.fromCharCode(65 /* A */ + num % 26);
3054 num = Math.floor(num / 26);
3055 while ( num > 0 ) {
3056 shortText = String.fromCharCode(65 /* A */ + (num - 1) % 26 ) + shortText.toLowerCase();
3057 num = Math.floor((num - 1) / 26);
3058 }
3059 return shortText;
3060 }
3061
79420a1e
DV
3062 var cols = data.getNumberOfColumns();
3063 var rows = data.getNumberOfRows();
3064
d955e223 3065 var indepType = data.getColumnType(0);
4440f6c8 3066 if (indepType == 'date' || indepType == 'datetime') {
285a6bda 3067 this.attrs_.xValueParser = Dygraph.dateParser;
48e614ac
DV
3068 this.attrs_.axes.x.valueFormatter = Dygraph.dateString_;
3069 this.attrs_.axes.x.ticker = Dygraph.dateTicker;
3070 this.attrs_.axes.x.axisLabelFormatter = Dygraph.dateAxisFormatter;
33127159 3071 } else if (indepType == 'number') {
285a6bda 3072 this.attrs_.xValueParser = function(x) { return parseFloat(x); };
48e614ac 3073 this.attrs_.axes.x.valueFormatter = function(x) { return x; };
44462ba3 3074 this.attrs_.axes.x.ticker = Dygraph.numericLinearTicks;
48e614ac 3075 this.attrs_.axes.x.axisLabelFormatter = this.attrs_.axes.x.valueFormatter;
285a6bda 3076 } else {
987840a2
DV
3077 this.error("only 'date', 'datetime' and 'number' types are supported for " +
3078 "column 1 of DataTable input (Got '" + indepType + "')");
79420a1e
DV
3079 return null;
3080 }
3081
a685723c
DV
3082 // Array of the column indices which contain data (and not annotations).
3083 var colIdx = [];
3084 var annotationCols = {}; // data index -> [annotation cols]
3085 var hasAnnotations = false;
758a629f
DV
3086 var i, j;
3087 for (i = 1; i < cols; i++) {
a685723c
DV
3088 var type = data.getColumnType(i);
3089 if (type == 'number') {
3090 colIdx.push(i);
3091 } else if (type == 'string' && this.attr_('displayAnnotations')) {
3092 // This is OK -- it's an annotation column.
3093 var dataIdx = colIdx[colIdx.length - 1];
3094 if (!annotationCols.hasOwnProperty(dataIdx)) {
3095 annotationCols[dataIdx] = [i];
3096 } else {
3097 annotationCols[dataIdx].push(i);
3098 }
3099 hasAnnotations = true;
3100 } else {
3101 this.error("Only 'number' is supported as a dependent type with Gviz." +
3102 " 'string' is only supported if displayAnnotations is true");
3103 }
3104 }
3105
3106 // Read column labels
3107 // TODO(danvk): add support back for errorBars
3108 var labels = [data.getColumnLabel(0)];
758a629f 3109 for (i = 0; i < colIdx.length; i++) {
a685723c 3110 labels.push(data.getColumnLabel(colIdx[i]));
f9348814 3111 if (this.attr_("errorBars")) i += 1;
a685723c
DV
3112 }
3113 this.attrs_.labels = labels;
3114 cols = labels.length;
3115
79420a1e 3116 var ret = [];
987840a2 3117 var outOfOrder = false;
a685723c 3118 var annotations = [];
758a629f 3119 for (i = 0; i < rows; i++) {
79420a1e 3120 var row = [];
debe4434
DV
3121 if (typeof(data.getValue(i, 0)) === 'undefined' ||
3122 data.getValue(i, 0) === null) {
129569a5
FD
3123 this.warn("Ignoring row " + i +
3124 " of DataTable because of undefined or null first column.");
debe4434
DV
3125 continue;
3126 }
3127
c21d2c2d 3128 if (indepType == 'date' || indepType == 'datetime') {
d955e223
DV
3129 row.push(data.getValue(i, 0).getTime());
3130 } else {
3131 row.push(data.getValue(i, 0));
3132 }
3e3f84e4 3133 if (!this.attr_("errorBars")) {
758a629f 3134 for (j = 0; j < colIdx.length; j++) {
a685723c
DV
3135 var col = colIdx[j];
3136 row.push(data.getValue(i, col));
3137 if (hasAnnotations &&
3138 annotationCols.hasOwnProperty(col) &&
758a629f 3139 data.getValue(i, annotationCols[col][0]) !== null) {
a685723c
DV
3140 var ann = {};
3141 ann.series = data.getColumnLabel(col);
3142 ann.xval = row[0];
5829af3d 3143 ann.shortText = shortTextForAnnotationNum(annotations.length);
a685723c
DV
3144 ann.text = '';
3145 for (var k = 0; k < annotationCols[col].length; k++) {
3146 if (k) ann.text += "\n";
3147 ann.text += data.getValue(i, annotationCols[col][k]);
3148 }
3149 annotations.push(ann);
3150 }
3e3f84e4 3151 }
92fd68d8
DV
3152
3153 // Strip out infinities, which give dygraphs problems later on.
758a629f 3154 for (j = 0; j < row.length; j++) {
92fd68d8
DV
3155 if (!isFinite(row[j])) row[j] = null;
3156 }
3e3f84e4 3157 } else {
758a629f 3158 for (j = 0; j < cols - 1; j++) {
3e3f84e4
DV
3159 row.push([ data.getValue(i, 1 + 2 * j), data.getValue(i, 2 + 2 * j) ]);
3160 }
79420a1e 3161 }
987840a2
DV
3162 if (ret.length > 0 && row[0] < ret[ret.length - 1][0]) {
3163 outOfOrder = true;
3164 }
243d96e8 3165 ret.push(row);
79420a1e 3166 }
987840a2
DV
3167
3168 if (outOfOrder) {
3169 this.warn("DataTable is out of order; order it correctly to speed loading.");
758a629f 3170 ret.sort(function(a,b) { return a[0] - b[0]; });
987840a2 3171 }
a685723c
DV
3172 this.rawData_ = ret;
3173
3174 if (annotations.length > 0) {
3175 this.setAnnotations(annotations, true);
3176 }
758a629f 3177};
79420a1e 3178
629a09ae 3179/**
6a1aa64f
DV
3180 * Get the CSV data. If it's in a function, call that function. If it's in a
3181 * file, do an XMLHttpRequest to get it.
3182 * @private
3183 */
285a6bda 3184Dygraph.prototype.start_ = function() {
36d4fabf
RK
3185 var data = this.file_;
3186
3187 // Functions can return references of all other types.
3188 if (typeof data == 'function') {
3189 data = data();
3190 }
3191
3192 if (Dygraph.isArrayLike(data)) {
3193 this.rawData_ = this.parseArray_(data);
26ca7938 3194 this.predraw_();
36d4fabf
RK
3195 } else if (typeof data == 'object' &&
3196 typeof data.getColumnRange == 'function') {
79420a1e 3197 // must be a DataTable from gviz.
36d4fabf 3198 this.parseDataTable_(data);
26ca7938 3199 this.predraw_();
36d4fabf 3200 } else if (typeof data == 'string') {
285a6bda 3201 // Heuristic: a newline means it's CSV data. Otherwise it's an URL.
36d4fabf
RK
3202 if (data.indexOf('\n') >= 0) {
3203 this.loadedEvent_(data);
285a6bda
DV
3204 } else {
3205 var req = new XMLHttpRequest();
3206 var caller = this;
3207 req.onreadystatechange = function () {
3208 if (req.readyState == 4) {
758a629f
DV
3209 if (req.status === 200 || // Normal http
3210 req.status === 0) { // Chrome w/ --allow-file-access-from-files
285a6bda
DV
3211 caller.loadedEvent_(req.responseText);
3212 }
6a1aa64f 3213 }
285a6bda 3214 };
6a1aa64f 3215
36d4fabf 3216 req.open("GET", data, true);
285a6bda
DV
3217 req.send(null);
3218 }
3219 } else {
36d4fabf 3220 this.error("Unknown data format: " + (typeof data));
6a1aa64f
DV
3221 }
3222};
3223
3224/**
3225 * Changes various properties of the graph. These can include:
3226 * <ul>
3227 * <li>file: changes the source data for the graph</li>
3228 * <li>errorBars: changes whether the data contains stddev</li>
3229 * </ul>
dcb25130 3230 *
ccfcc169
DV
3231 * There's a huge variety of options that can be passed to this method. For a
3232 * full list, see http://dygraphs.com/options.html.
3233 *
6a1aa64f 3234 * @param {Object} attrs The new properties and values
ccfcc169
DV
3235 * @param {Boolean} [block_redraw] Usually the chart is redrawn after every
3236 * call to updateOptions(). If you know better, you can pass true to explicitly
3237 * block the redraw. This can be useful for chaining updateOptions() calls,
3238 * avoiding the occasional infinite loop and preventing redraws when it's not
3239 * necessary (e.g. when updating a callback).
6a1aa64f 3240 */
48e614ac 3241Dygraph.prototype.updateOptions = function(input_attrs, block_redraw) {
ccfcc169
DV
3242 if (typeof(block_redraw) == 'undefined') block_redraw = false;
3243
48e614ac 3244 // mapLegacyOptions_ drops the "file" parameter as a convenience to us.
758a629f 3245 var file = input_attrs.file;
48e614ac
DV
3246 var attrs = Dygraph.mapLegacyOptions_(input_attrs);
3247
ccfcc169 3248 // TODO(danvk): this is a mess. Move these options into attr_.
c65f2303 3249 if ('rollPeriod' in attrs) {
6a1aa64f
DV
3250 this.rollPeriod_ = attrs.rollPeriod;
3251 }
c65f2303 3252 if ('dateWindow' in attrs) {
6a1aa64f 3253 this.dateWindow_ = attrs.dateWindow;
e5152598 3254 if (!('isZoomedIgnoreProgrammaticZoom' in attrs)) {
758a629f 3255 this.zoomed_x_ = (attrs.dateWindow !== null);
81856f70 3256 }
b7e5862d 3257 }
e5152598 3258 if ('valueRange' in attrs && !('isZoomedIgnoreProgrammaticZoom' in attrs)) {
758a629f 3259 this.zoomed_y_ = (attrs.valueRange !== null);
6a1aa64f 3260 }
450fe64b
DV
3261
3262 // TODO(danvk): validate per-series options.
46dde5f9
DV
3263 // Supported:
3264 // strokeWidth
3265 // pointSize
3266 // drawPoints
3267 // highlightCircleSize
450fe64b 3268
9ca829f2
DV
3269 // Check if this set options will require new points.
3270 var requiresNewPoints = Dygraph.isPixelChangingOptionList(this.attr_("labels"), attrs);
3271
48e614ac 3272 Dygraph.updateDeep(this.user_attrs_, attrs);
285a6bda 3273
48e614ac
DV
3274 if (file) {
3275 this.file_ = file;
ccfcc169 3276 if (!block_redraw) this.start_();
6a1aa64f 3277 } else {
9ca829f2
DV
3278 if (!block_redraw) {
3279 if (requiresNewPoints) {
48e614ac 3280 this.predraw_();
9ca829f2 3281 } else {
e2c21500 3282 this.renderGraph_(false);
9ca829f2
DV
3283 }
3284 }
6a1aa64f
DV
3285 }
3286};
3287
3288/**
48e614ac
DV
3289 * Returns a copy of the options with deprecated names converted into current
3290 * names. Also drops the (potentially-large) 'file' attribute. If the caller is
3291 * interested in that, they should save a copy before calling this.
3292 * @private
3293 */
3294Dygraph.mapLegacyOptions_ = function(attrs) {
3295 var my_attrs = {};
3296 for (var k in attrs) {
3297 if (k == 'file') continue;
3298 if (attrs.hasOwnProperty(k)) my_attrs[k] = attrs[k];
3299 }
3300
3301 var set = function(axis, opt, value) {
3302 if (!my_attrs.axes) my_attrs.axes = {};
3303 if (!my_attrs.axes[axis]) my_attrs.axes[axis] = {};
3304 my_attrs.axes[axis][opt] = value;
3305 };
3306 var map = function(opt, axis, new_opt) {
3307 if (typeof(attrs[opt]) != 'undefined') {
3308 set(axis, new_opt, attrs[opt]);
3309 delete my_attrs[opt];
3310 }
3311 };
3312
3313 // This maps, e.g., xValueFormater -> axes: { x: { valueFormatter: ... } }
3314 map('xValueFormatter', 'x', 'valueFormatter');
3315 map('pixelsPerXLabel', 'x', 'pixelsPerLabel');
3316 map('xAxisLabelFormatter', 'x', 'axisLabelFormatter');
3317 map('xTicker', 'x', 'ticker');
3318 map('yValueFormatter', 'y', 'valueFormatter');
3319 map('pixelsPerYLabel', 'y', 'pixelsPerLabel');
3320 map('yAxisLabelFormatter', 'y', 'axisLabelFormatter');
3321 map('yTicker', 'y', 'ticker');
3322 return my_attrs;
3323};
3324
3325/**
697e70b2
DV
3326 * Resizes the dygraph. If no parameters are specified, resizes to fill the
3327 * containing div (which has presumably changed size since the dygraph was
3328 * instantiated. If the width/height are specified, the div will be resized.
964f30c6
DV
3329 *
3330 * This is far more efficient than destroying and re-instantiating a
3331 * Dygraph, since it doesn't have to reparse the underlying data.
3332 *
629a09ae
DV
3333 * @param {Number} [width] Width (in pixels)
3334 * @param {Number} [height] Height (in pixels)
697e70b2
DV
3335 */
3336Dygraph.prototype.resize = function(width, height) {
e8c7ef86
DV
3337 if (this.resize_lock) {
3338 return;
3339 }
3340 this.resize_lock = true;
3341
697e70b2
DV
3342 if ((width === null) != (height === null)) {
3343 this.warn("Dygraph.resize() should be called with zero parameters or " +
3344 "two non-NULL parameters. Pretending it was zero.");
3345 width = height = null;
3346 }
3347
4b4d1a63
DV
3348 var old_width = this.width_;
3349 var old_height = this.height_;
b16e6369 3350
697e70b2
DV
3351 if (width) {
3352 this.maindiv_.style.width = width + "px";
3353 this.maindiv_.style.height = height + "px";
3354 this.width_ = width;
3355 this.height_ = height;
3356 } else {
ccd9d7c2
PF
3357 this.width_ = this.maindiv_.clientWidth;
3358 this.height_ = this.maindiv_.clientHeight;
697e70b2
DV
3359 }
3360
4b4d1a63
DV
3361 if (old_width != this.width_ || old_height != this.height_) {
3362 // TODO(danvk): there should be a clear() method.
3363 this.maindiv_.innerHTML = "";
77b5e09d 3364 this.roller_ = null;
4b4d1a63
DV
3365 this.attrs_.labelsDiv = null;
3366 this.createInterface_();
c9faeafd
DV
3367 if (this.annotations_.length) {
3368 // createInterface_ reset the layout, so we need to do this.
3369 this.layout_.setAnnotations(this.annotations_);
3370 }
4b4d1a63
DV
3371 this.predraw_();
3372 }
e8c7ef86
DV
3373
3374 this.resize_lock = false;
697e70b2
DV
3375};
3376
3377/**
6faebb69 3378 * Adjusts the number of points in the rolling average. Updates the graph to
6a1aa64f 3379 * reflect the new averaging period.
6faebb69 3380 * @param {Number} length Number of points over which to average the data.
6a1aa64f 3381 */
285a6bda 3382Dygraph.prototype.adjustRoll = function(length) {
6a1aa64f 3383 this.rollPeriod_ = length;
26ca7938 3384 this.predraw_();
6a1aa64f 3385};
540d00f1 3386
f8cfec73 3387/**
1cf11047
DV
3388 * Returns a boolean array of visibility statuses.
3389 */
3390Dygraph.prototype.visibility = function() {
3391 // Do lazy-initialization, so that this happens after we know the number of
3392 // data series.
3393 if (!this.attr_("visibility")) {
758a629f 3394 this.attrs_.visibility = [];
1cf11047 3395 }
758a629f 3396 // TODO(danvk): it looks like this could go into an infinite loop w/ user_attrs.
395e98a3 3397 while (this.attr_("visibility").length < this.numColumns() - 1) {
758a629f 3398 this.attrs_.visibility.push(true);
1cf11047
DV
3399 }
3400 return this.attr_("visibility");
3401};
3402
3403/**
3404 * Changes the visiblity of a series.
3405 */
3406Dygraph.prototype.setVisibility = function(num, value) {
3407 var x = this.visibility();
a6c109c1 3408 if (num < 0 || num >= x.length) {
1cf11047
DV
3409 this.warn("invalid series number in setVisibility: " + num);
3410 } else {
3411 x[num] = value;
26ca7938 3412 this.predraw_();
1cf11047
DV
3413 }
3414};
3415
3416/**
0cb9bd91
DV
3417 * How large of an area will the dygraph render itself in?
3418 * This is used for testing.
3419 * @return A {width: w, height: h} object.
3420 * @private
3421 */
3422Dygraph.prototype.size = function() {
3423 return { width: this.width_, height: this.height_ };
3424};
3425
3426/**
5c528fa2 3427 * Update the list of annotations and redraw the chart.
41ee764f
DV
3428 * See dygraphs.com/annotations.html for more info on how to use annotations.
3429 * @param ann {Array} An array of annotation objects.
3430 * @param suppressDraw {Boolean} Set to "true" to block chart redraw (optional).
5c528fa2 3431 */
a685723c 3432Dygraph.prototype.setAnnotations = function(ann, suppressDraw) {
3c51ab74
DV
3433 // Only add the annotation CSS rule once we know it will be used.
3434 Dygraph.addAnnotationRule();
5c528fa2
DV
3435 this.annotations_ = ann;
3436 this.layout_.setAnnotations(this.annotations_);
a685723c 3437 if (!suppressDraw) {
26ca7938 3438 this.predraw_();
a685723c 3439 }
5c528fa2
DV
3440};
3441
3442/**
3443 * Return the list of annotations.
3444 */
3445Dygraph.prototype.annotations = function() {
3446 return this.annotations_;
3447};
3448
46dde5f9 3449/**
82c6fe4d
KW
3450 * Get the list of label names for this graph. The first column is the
3451 * x-axis, so the data series names start at index 1.
3452 */
e2c21500 3453Dygraph.prototype.getLabels = function() {
82c6fe4d
KW
3454 return this.attr_("labels").slice();
3455};
3456
3457/**
46dde5f9
DV
3458 * Get the index of a series (column) given its name. The first column is the
3459 * x-axis, so the data series start with index 1.
3460 */
3461Dygraph.prototype.indexFromSetName = function(name) {
82c6fe4d 3462 return this.setIndexByName_[name];
46dde5f9
DV
3463};
3464
629a09ae 3465/**
857a6931
KW
3466 * Get the internal dataset index given its name. These are numbered starting from 0,
3467 * and only count visible sets.
3468 * @private
3469 */
3470Dygraph.prototype.datasetIndexFromSetName_ = function(name) {
3471 return this.datasetIndex_[this.indexFromSetName(name)];
3472};
3473
3474/**
629a09ae
DV
3475 * @private
3476 * Adds a default style for the annotation CSS classes to the document. This is
3477 * only executed when annotations are actually used. It is designed to only be
3478 * called once -- all calls after the first will return immediately.
3479 */
5c528fa2
DV
3480Dygraph.addAnnotationRule = function() {
3481 if (Dygraph.addedAnnotationCSS) return;
3482
5c528fa2
DV
3483 var rule = "border: 1px solid black; " +
3484 "background-color: white; " +
3485 "text-align: center;";
22186871
DV
3486
3487 var styleSheetElement = document.createElement("style");
3488 styleSheetElement.type = "text/css";
3489 document.getElementsByTagName("head")[0].appendChild(styleSheetElement);
3490
3491 // Find the first style sheet that we can access.
3492 // We may not add a rule to a style sheet from another domain for security
3493 // reasons. This sometimes comes up when using gviz, since the Google gviz JS
3494 // adds its own style sheets from google.com.
3495 for (var i = 0; i < document.styleSheets.length; i++) {
3496 if (document.styleSheets[i].disabled) continue;
3497 var mysheet = document.styleSheets[i];
3498 try {
3499 if (mysheet.insertRule) { // Firefox
3500 var idx = mysheet.cssRules ? mysheet.cssRules.length : 0;
3501 mysheet.insertRule(".dygraphDefaultAnnotation { " + rule + " }", idx);
3502 } else if (mysheet.addRule) { // IE
3503 mysheet.addRule(".dygraphDefaultAnnotation", rule);
3504 }
3505 Dygraph.addedAnnotationCSS = true;
3506 return;
3507 } catch(err) {
3508 // Was likely a security exception.
3509 }
5c528fa2
DV
3510 }
3511
22186871 3512 this.warn("Unable to add default annotation CSS rule; display may be off.");
758a629f 3513};
5c528fa2 3514
285a6bda 3515// Older pages may still use this name.
c0f54d4f 3516var DateGraph = Dygraph;