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