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