Update IE instructions
[dygraphs.git] / dygraph-utils.js
CommitLineData
88e95c46
DV
1/**
2 * @license
3 * Copyright 2011 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
5 */
dedb4f5f 6
004b5c90
DV
7/**
8 * @fileoverview This file contains utility functions used by dygraphs. These
9 * are typically static (i.e. not related to any particular dygraph). Examples
10 * include date/time formatting functions, basic algorithms (e.g. binary
11 * search) and generic DOM-manipulation functions.
12 */
dedb4f5f 13
8887663f
DV
14(function() {
15
a14ed8aa 16/*global Dygraph:false, G_vmlCanvasManager:false, Node:false */
c0f54d4f
DV
17"use strict";
18
dedb4f5f
DV
19Dygraph.LOG_SCALE = 10;
20Dygraph.LN_TEN = Math.log(Dygraph.LOG_SCALE);
21
f11283de
DV
22/**
23 * @private
24 * @param {number} x
25 * @return {number}
26 */
dedb4f5f
DV
27Dygraph.log10 = function(x) {
28 return Math.log(x) / Dygraph.LN_TEN;
758a629f 29};
dedb4f5f 30
79253bd0 31/** A dotted line stroke pattern. */
32Dygraph.DOTTED_LINE = [2, 2];
33/** A dashed line stroke pattern. */
34Dygraph.DASHED_LINE = [7, 3];
35/** A dot dash stroke pattern. */
36Dygraph.DOT_DASH_LINE = [7, 2, 2, 2];
37
dedb4f5f 38/**
dedb4f5f
DV
39 * Return the 2d context for a dygraph canvas.
40 *
41 * This method is only exposed for the sake of replacing the function in
42 * automated tests, e.g.
43 *
44 * var oldFunc = Dygraph.getContext();
45 * Dygraph.getContext = function(canvas) {
46 * var realContext = oldFunc(canvas);
47 * return new Proxy(realContext);
48 * };
f11283de
DV
49 * @param {!HTMLCanvasElement} canvas
50 * @return {!CanvasRenderingContext2D}
51 * @private
dedb4f5f
DV
52 */
53Dygraph.getContext = function(canvas) {
f11283de 54 return /** @type{!CanvasRenderingContext2D}*/(canvas.getContext("2d"));
dedb4f5f
DV
55};
56
57/**
dedb4f5f
DV
58 * Add an event handler. This smooths a difference between IE and the rest of
59 * the world.
39b33f9f
DV
60 * @param {!Node} elem The element to add the event to.
61 * @param {string} type The type of the event, e.g. 'click' or 'mousemove'.
62 * @param {function(Event):(boolean|undefined)} fn The function to call
f11283de
DV
63 * on the event. The function takes one parameter: the event object.
64 * @private
dedb4f5f 65 */
1cc3540b 66Dygraph.addEvent = function addEvent(elem, type, fn) {
ccd9d7c2
PF
67 if (elem.addEventListener) {
68 elem.addEventListener(type, fn, false);
69 } else {
70 elem[type+fn] = function(){fn(window.event);};
71 elem.attachEvent('on'+type, elem[type+fn]);
72 }
1cc3540b
RK
73};
74
75/**
1cc3540b
RK
76 * Add an event handler. This event handler is kept until the graph is
77 * destroyed with a call to graph.destroy().
78 *
39b33f9f
DV
79 * @param {!Node} elem The element to add the event to.
80 * @param {string} type The type of the event, e.g. 'click' or 'mousemove'.
81 * @param {function(Event):(boolean|undefined)} fn The function to call
f11283de
DV
82 * on the event. The function takes one parameter: the event object.
83 * @private
1cc3540b 84 */
aeca29ac 85Dygraph.prototype.addAndTrackEvent = function(elem, type, fn) {
1cc3540b 86 Dygraph.addEvent(elem, type, fn);
6a4587ac 87 this.registeredEvents_.push({ elem : elem, type : type, fn : fn });
ccd9d7c2
PF
88};
89
90/**
f11283de
DV
91 * Remove an event handler. This smooths a difference between IE and the rest
92 * of the world.
39b33f9f 93 * @param {!Node} elem The element to remove the event from.
f11283de
DV
94 * @param {string} type The type of the event, e.g. 'click' or 'mousemove'.
95 * @param {function(Event):(boolean|undefined)} fn The function to call
96 * on the event. The function takes one parameter: the event object.
ccd9d7c2 97 * @private
ccd9d7c2 98 */
a537fd67 99Dygraph.removeEvent = function(elem, type, fn) {
ccd9d7c2
PF
100 if (elem.removeEventListener) {
101 elem.removeEventListener(type, fn, false);
102 } else {
e2769469
DV
103 try {
104 elem.detachEvent('on'+type, elem[type+fn]);
105 } catch(e) {
106 // We only detach event listeners on a "best effort" basis in IE. See:
107 // http://stackoverflow.com/questions/2553632/detachevent-not-working-with-named-inline-functions
108 }
ccd9d7c2 109 elem[type+fn] = null;
dedb4f5f
DV
110 }
111};
112
aeca29ac
RK
113Dygraph.prototype.removeTrackedEvents_ = function() {
114 if (this.registeredEvents_) {
115 for (var idx = 0; idx < this.registeredEvents_.length; idx++) {
116 var reg = this.registeredEvents_[idx];
117 Dygraph.removeEvent(reg.elem, reg.type, reg.fn);
118 }
119 }
120
121 this.registeredEvents_ = [];
f914bed1 122};
aeca29ac 123
dedb4f5f 124/**
dedb4f5f
DV
125 * Cancels further processing of an event. This is useful to prevent default
126 * browser actions, e.g. highlighting text on a double-click.
127 * Based on the article at
128 * http://www.switchonthecode.com/tutorials/javascript-tutorial-the-scroll-wheel
39b33f9f 129 * @param {!Event} e The event whose normal behavior should be canceled.
f11283de 130 * @private
dedb4f5f
DV
131 */
132Dygraph.cancelEvent = function(e) {
133 e = e ? e : window.event;
134 if (e.stopPropagation) {
135 e.stopPropagation();
136 }
137 if (e.preventDefault) {
138 e.preventDefault();
139 }
140 e.cancelBubble = true;
141 e.cancel = true;
142 e.returnValue = false;
143 return false;
144};
145
146/**
147 * Convert hsv values to an rgb(r,g,b) string. Taken from MochiKit.Color. This
148 * is used to generate default series colors which are evenly spaced on the
149 * color wheel.
f11283de
DV
150 * @param { number } hue Range is 0.0-1.0.
151 * @param { number } saturation Range is 0.0-1.0.
152 * @param { number } value Range is 0.0-1.0.
153 * @return { string } "rgb(r,g,b)" where r, g and b range from 0-255.
dedb4f5f
DV
154 * @private
155 */
156Dygraph.hsvToRGB = function (hue, saturation, value) {
157 var red;
158 var green;
159 var blue;
160 if (saturation === 0) {
161 red = value;
162 green = value;
163 blue = value;
164 } else {
165 var i = Math.floor(hue * 6);
166 var f = (hue * 6) - i;
167 var p = value * (1 - saturation);
168 var q = value * (1 - (saturation * f));
169 var t = value * (1 - (saturation * (1 - f)));
170 switch (i) {
171 case 1: red = q; green = value; blue = p; break;
172 case 2: red = p; green = value; blue = t; break;
173 case 3: red = p; green = q; blue = value; break;
174 case 4: red = t; green = p; blue = value; break;
175 case 5: red = value; green = p; blue = q; break;
176 case 6: // fall through
177 case 0: red = value; green = t; blue = p; break;
178 }
179 }
180 red = Math.floor(255 * red + 0.5);
181 green = Math.floor(255 * green + 0.5);
182 blue = Math.floor(255 * blue + 0.5);
183 return 'rgb(' + red + ',' + green + ',' + blue + ')';
184};
185
186// The following functions are from quirksmode.org with a modification for Safari from
187// http://blog.firetree.net/2005/07/04/javascript-find-position/
188// http://www.quirksmode.org/js/findpos.html
1bc38cbc 189// ... and modifications to support scrolling divs.
dedb4f5f 190
8442269f 191/**
464b5f50
DV
192 * Find the coordinates of an object relative to the top left of the page.
193 *
f11283de
DV
194 * TODO(danvk): change obj type from Node -&gt; !Node
195 * @param {Node} obj
464b5f50 196 * @return {{x:number,y:number}}
8442269f
RK
197 * @private
198 */
464b5f50
DV
199Dygraph.findPos = function(obj) {
200 var curleft = 0, curtop = 0;
201 if (obj.offsetParent) {
8442269f 202 var copyObj = obj;
464b5f50 203 while (1) {
ecdb6dff 204 // NOTE: the if statement here is for IE8.
464b5f50 205 var borderLeft = "0", borderTop = "0";
4ff8c62e 206 if (window.getComputedStyle) {
464b5f50
DV
207 var computedStyle = window.getComputedStyle(copyObj, null);
208 borderLeft = computedStyle.borderLeft || "0";
209 borderTop = computedStyle.borderTop || "0";
4ff8c62e 210 }
abc8c570 211 curleft += parseInt(borderLeft, 10) ;
abc8c570 212 curtop += parseInt(borderTop, 10) ;
464b5f50 213 curleft += copyObj.offsetLeft;
8442269f 214 curtop += copyObj.offsetTop;
464b5f50 215 if (!copyObj.offsetParent) {
dedb4f5f 216 break;
8442269f
RK
217 }
218 copyObj = copyObj.offsetParent;
dedb4f5f 219 }
464b5f50
DV
220 } else {
221 // TODO(danvk): why would obj ever have these properties?
222 if (obj.x) curleft += obj.x;
223 if (obj.y) curtop += obj.y;
8442269f 224 }
464b5f50 225
8442269f 226 // This handles the case where the object is inside a scrolled div.
464b5f50
DV
227 while (obj && obj != document.body) {
228 curleft -= obj.scrollLeft;
8442269f
RK
229 curtop -= obj.scrollTop;
230 obj = obj.parentNode;
231 }
464b5f50 232 return {x: curleft, y: curtop};
dedb4f5f
DV
233};
234
235/**
dedb4f5f
DV
236 * Returns the x-coordinate of the event in a coordinate system where the
237 * top-left corner of the page (not the window) is (0,0).
238 * Taken from MochiKit.Signal
f11283de
DV
239 * @param {!Event} e
240 * @return {number}
241 * @private
dedb4f5f
DV
242 */
243Dygraph.pageX = function(e) {
244 if (e.pageX) {
245 return (!e.pageX || e.pageX < 0) ? 0 : e.pageX;
246 } else {
f11283de 247 var de = document.documentElement;
dedb4f5f
DV
248 var b = document.body;
249 return e.clientX +
250 (de.scrollLeft || b.scrollLeft) -
251 (de.clientLeft || 0);
252 }
253};
254
255/**
dedb4f5f
DV
256 * Returns the y-coordinate of the event in a coordinate system where the
257 * top-left corner of the page (not the window) is (0,0).
258 * Taken from MochiKit.Signal
f11283de
DV
259 * @param {!Event} e
260 * @return {number}
261 * @private
dedb4f5f
DV
262 */
263Dygraph.pageY = function(e) {
264 if (e.pageY) {
265 return (!e.pageY || e.pageY < 0) ? 0 : e.pageY;
266 } else {
f11283de 267 var de = document.documentElement;
dedb4f5f
DV
268 var b = document.body;
269 return e.clientY +
270 (de.scrollTop || b.scrollTop) -
271 (de.clientTop || 0);
272 }
273};
274
275/**
806f92c1
DV
276 * Converts page the x-coordinate of the event to pixel x-coordinates on the
277 * canvas (i.e. DOM Coords).
278 * @param {!Event} e Drag event.
279 * @param {!DygraphInteractionContext} context Interaction context object.
280 * @return {number} The amount by which the drag has moved to the right.
281 */
282Dygraph.dragGetX_ = function(e, context) {
283 return Dygraph.pageX(e) - context.px;
284};
285
286/**
287 * Converts page the y-coordinate of the event to pixel y-coordinates on the
288 * canvas (i.e. DOM Coords).
289 * @param {!Event} e Drag event.
290 * @param {!DygraphInteractionContext} context Interaction context object.
291 * @return {number} The amount by which the drag has moved down.
292 */
293Dygraph.dragGetY_ = function(e, context) {
294 return Dygraph.pageY(e) - context.py;
295};
296
297/**
f11283de
DV
298 * This returns true unless the parameter is 0, null, undefined or NaN.
299 * TODO(danvk): rename this function to something like 'isNonZeroNan'.
300 *
301 * @param {number} x The number to consider.
302 * @return {boolean} Whether the number is zero or NaN.
dedb4f5f 303 * @private
dedb4f5f 304 */
dedb4f5f 305Dygraph.isOK = function(x) {
f11283de 306 return !!x && !isNaN(x);
dedb4f5f
DV
307};
308
309/**
55deb02f 310 * @param {{x:?number,y:?number,yval:?number}} p The point to consider, valid
f11283de 311 * points are {x, y} objects
55deb02f
DV
312 * @param {boolean=} opt_allowNaNY Treat point with y=NaN as valid
313 * @return {boolean} Whether the point has numeric x and y.
62c3d2fd 314 * @private
62c3d2fd 315 */
55deb02f 316Dygraph.isValidPoint = function(p, opt_allowNaNY) {
f11283de
DV
317 if (!p) return false; // null or undefined object
318 if (p.yval === null) return false; // missing point
04c104d7
KW
319 if (p.x === null || p.x === undefined) return false;
320 if (p.y === null || p.y === undefined) return false;
55deb02f 321 if (isNaN(p.x) || (!opt_allowNaNY && isNaN(p.y))) return false;
62c3d2fd
KW
322 return true;
323};
324
325/**
dedb4f5f
DV
326 * Number formatting function which mimicks the behavior of %g in printf, i.e.
327 * either exponential or fixed format (without trailing 0s) is used depending on
328 * the length of the generated string. The advantage of this format is that
329 * there is a predictable upper bound on the resulting string length,
330 * significant figures are not dropped, and normal numbers are not displayed in
331 * exponential notation.
332 *
333 * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g.
334 * It creates strings which are too long for absolute values between 10^-4 and
335 * 10^-6, e.g. '0.00001' instead of '1e-5'. See tests/number-format.html for
336 * output examples.
337 *
f11283de
DV
338 * @param {number} x The number to format
339 * @param {number=} opt_precision The precision to use, default 2.
340 * @return {string} A string formatted like %g in printf. The max generated
dedb4f5f
DV
341 * string length should be precision + 6 (e.g 1.123e+300).
342 */
343Dygraph.floatFormat = function(x, opt_precision) {
344 // Avoid invalid precision values; [1, 21] is the valid range.
345 var p = Math.min(Math.max(1, opt_precision || 2), 21);
346
347 // This is deceptively simple. The actual algorithm comes from:
348 //
349 // Max allowed length = p + 4
350 // where 4 comes from 'e+n' and '.'.
351 //
352 // Length of fixed format = 2 + y + p
353 // where 2 comes from '0.' and y = # of leading zeroes.
354 //
355 // Equating the two and solving for y yields y = 2, or 0.00xxxx which is
356 // 1.0e-3.
357 //
358 // Since the behavior of toPrecision() is identical for larger numbers, we
359 // don't have to worry about the other bound.
360 //
361 // Finally, the argument for toExponential() is the number of trailing digits,
362 // so we take off 1 for the value before the '.'.
758a629f 363 return (Math.abs(x) < 1.0e-3 && x !== 0.0) ?
dedb4f5f
DV
364 x.toExponential(p - 1) : x.toPrecision(p);
365};
366
367/**
dedb4f5f 368 * Converts '9' to '09' (useful for dates)
f11283de
DV
369 * @param {number} x
370 * @return {string}
371 * @private
dedb4f5f
DV
372 */
373Dygraph.zeropad = function(x) {
374 if (x < 10) return "0" + x; else return "" + x;
375};
376
377/**
1e7f8af0
JPB
378 * Date accessors to get the parts of a calendar date (year, month,
379 * day, hour, minute, second and millisecond) according to local time,
380 * and factory method to call the Date constructor with an array of arguments.
381 */
382Dygraph.DateAccessorsLocal = {
383 getFullYear: function(d) {return d.getFullYear();},
384 getMonth: function(d) {return d.getMonth();},
385 getDate: function(d) {return d.getDate();},
386 getHours: function(d) {return d.getHours();},
387 getMinutes: function(d) {return d.getMinutes();},
388 getSeconds: function(d) {return d.getSeconds();},
389 getMilliseconds: function(d) {return d.getMilliseconds();},
390 getDay: function(d) {return d.getDay();},
391 makeDate: function(y, m, d, hh, mm, ss, ms) {
392 return new Date(y, m, d, hh, mm, ss, ms);
393 }
394};
395
396/**
397 * Date accessors to get the parts of a calendar date (year, month,
398 * day of month, hour, minute, second and millisecond) according to UTC time,
399 * and factory method to call the Date constructor with an array of arguments.
400 */
401Dygraph.DateAccessorsUTC = {
402 getFullYear: function(d) {return d.getUTCFullYear();},
403 getMonth: function(d) {return d.getUTCMonth();},
404 getDate: function(d) {return d.getUTCDate();},
405 getHours: function(d) {return d.getUTCHours();},
406 getMinutes: function(d) {return d.getUTCMinutes();},
407 getSeconds: function(d) {return d.getUTCSeconds();},
408 getMilliseconds: function(d) {return d.getUTCMilliseconds();},
409 getDay: function(d) {return d.getUTCDay();},
410 makeDate: function(y, m, d, hh, mm, ss, ms) {
411 return new Date(Date.UTC(y, m, d, hh, mm, ss, ms));
412 }
413};
414
415/**
dedb4f5f 416 * Return a string version of the hours, minutes and seconds portion of a date.
872a6a00
DV
417 * @param {number} hh The hours (from 0-23)
418 * @param {number} mm The minutes (from 0-59)
419 * @param {number} ss The seconds (from 0-59)
420 * @return {string} A time of the form "HH:MM" or "HH:MM:SS"
dedb4f5f
DV
421 * @private
422 */
872a6a00 423Dygraph.hmsString_ = function(hh, mm, ss) {
dedb4f5f 424 var zeropad = Dygraph.zeropad;
872a6a00
DV
425 var ret = zeropad(hh) + ":" + zeropad(mm);
426 if (ss) {
427 ret += ":" + zeropad(ss);
dedb4f5f 428 }
872a6a00 429 return ret;
dedb4f5f
DV
430};
431
432/**
872a6a00 433 * Convert a JS date (millis since epoch) to a formatted string.
1e7f8af0 434 * @param {number} time The JavaScript time value (ms since epoch)
872a6a00
DV
435 * @param {boolean} utc Wether output UTC or local time
436 * @return {string} A date of one of these forms:
437 * "YYYY/MM/DD", "YYYY/MM/DD HH:MM" or "YYYY/MM/DD HH:MM:SS"
464b5f50
DV
438 * @private
439 */
1e7f8af0 440Dygraph.dateString_ = function(time, utc) {
464b5f50 441 var zeropad = Dygraph.zeropad;
1e7f8af0
JPB
442 var accessors = utc ? Dygraph.DateAccessorsUTC : Dygraph.DateAccessorsLocal;
443 var date = new Date(time);
444 var y = accessors.getFullYear(date);
445 var m = accessors.getMonth(date);
446 var d = accessors.getDate(date);
447 var hh = accessors.getHours(date);
448 var mm = accessors.getMinutes(date);
449 var ss = accessors.getSeconds(date);
872a6a00
DV
450 // Get a year string:
451 var year = "" + y;
464b5f50 452 // Get a 0 padded month string
872a6a00 453 var month = zeropad(m + 1); //months are 0-offset, sigh
464b5f50 454 // Get a 0 padded day string
872a6a00
DV
455 var day = zeropad(d);
456 var frac = hh * 3600 + mm * 60 + ss;
457 var ret = year + "/" + month + "/" + day;
458 if (frac) {
1e7f8af0 459 ret += " " + Dygraph.hmsString_(hh, mm, ss);
872a6a00
DV
460 }
461 return ret;
464b5f50
DV
462};
463
464/**
dedb4f5f 465 * Round a number to the specified number of digits past the decimal point.
f11283de
DV
466 * @param {number} num The number to round
467 * @param {number} places The number of decimals to which to round
468 * @return {number} The rounded number
dedb4f5f
DV
469 * @private
470 */
471Dygraph.round_ = function(num, places) {
472 var shift = Math.pow(10, places);
473 return Math.round(num * shift)/shift;
474};
475
476/**
dedb4f5f
DV
477 * Implementation of binary search over an array.
478 * Currently does not work when val is outside the range of arry's values.
f11283de
DV
479 * @param {number} val the value to search for
480 * @param {Array.<number>} arry is the value over which to search
481 * @param {number} abs If abs > 0, find the lowest entry greater than val
482 * If abs < 0, find the highest entry less than val.
483 * If abs == 0, find the entry that equals val.
484 * @param {number=} low The first index in arry to consider (optional)
485 * @param {number=} high The last index in arry to consider (optional)
486 * @return {number} Index of the element, or -1 if it isn't found.
487 * @private
dedb4f5f
DV
488 */
489Dygraph.binarySearch = function(val, arry, abs, low, high) {
758a629f
DV
490 if (low === null || low === undefined ||
491 high === null || high === undefined) {
dedb4f5f
DV
492 low = 0;
493 high = arry.length - 1;
494 }
495 if (low > high) {
496 return -1;
497 }
758a629f 498 if (abs === null || abs === undefined) {
dedb4f5f
DV
499 abs = 0;
500 }
501 var validIndex = function(idx) {
502 return idx >= 0 && idx < arry.length;
758a629f
DV
503 };
504 var mid = parseInt((low + high) / 2, 10);
dedb4f5f 505 var element = arry[mid];
f11283de 506 var idx;
dedb4f5f
DV
507 if (element == val) {
508 return mid;
f11283de 509 } else if (element > val) {
dedb4f5f
DV
510 if (abs > 0) {
511 // Accept if element > val, but also if prior element < val.
758a629f 512 idx = mid - 1;
dedb4f5f
DV
513 if (validIndex(idx) && arry[idx] < val) {
514 return mid;
515 }
516 }
517 return Dygraph.binarySearch(val, arry, abs, low, mid - 1);
f11283de 518 } else if (element < val) {
dedb4f5f
DV
519 if (abs < 0) {
520 // Accept if element < val, but also if prior element > val.
758a629f 521 idx = mid + 1;
dedb4f5f
DV
522 if (validIndex(idx) && arry[idx] > val) {
523 return mid;
524 }
525 }
526 return Dygraph.binarySearch(val, arry, abs, mid + 1, high);
527 }
f11283de 528 return -1; // can't actually happen, but makes closure compiler happy
dedb4f5f
DV
529};
530
531/**
dedb4f5f
DV
532 * Parses a date, returning the number of milliseconds since epoch. This can be
533 * passed in as an xValueParser in the Dygraph constructor.
534 * TODO(danvk): enumerate formats that this understands.
f11283de
DV
535 *
536 * @param {string} dateStr A date in a variety of possible string formats.
537 * @return {number} Milliseconds since epoch.
538 * @private
dedb4f5f
DV
539 */
540Dygraph.dateParser = function(dateStr) {
541 var dateStrSlashed;
542 var d;
769e8bc7 543
3f675fe5
DV
544 // Let the system try the format first, with one caveat:
545 // YYYY-MM-DD[ HH:MM:SS] is interpreted as UTC by a variety of browsers.
546 // dygraphs displays dates in local time, so this will result in surprising
547 // inconsistencies. But if you specify "T" or "Z" (i.e. YYYY-MM-DDTHH:MM:SS),
548 // then you probably know what you're doing, so we'll let you go ahead.
549 // Issue: http://code.google.com/p/dygraphs/issues/detail?id=255
550 if (dateStr.search("-") == -1 ||
551 dateStr.search("T") != -1 || dateStr.search("Z") != -1) {
552 d = Dygraph.dateStrToMillis(dateStr);
553 if (d && !isNaN(d)) return d;
554 }
769e8bc7 555
dedb4f5f
DV
556 if (dateStr.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12'
557 dateStrSlashed = dateStr.replace("-", "/", "g");
558 while (dateStrSlashed.search("-") != -1) {
559 dateStrSlashed = dateStrSlashed.replace("-", "/");
560 }
561 d = Dygraph.dateStrToMillis(dateStrSlashed);
562 } else if (dateStr.length == 8) { // e.g. '20090712'
563 // TODO(danvk): remove support for this format. It's confusing.
758a629f
DV
564 dateStrSlashed = dateStr.substr(0,4) + "/" + dateStr.substr(4,2) + "/" +
565 dateStr.substr(6,2);
dedb4f5f
DV
566 d = Dygraph.dateStrToMillis(dateStrSlashed);
567 } else {
568 // Any format that Date.parse will accept, e.g. "2009/07/12" or
569 // "2009/07/12 12:34:56"
570 d = Dygraph.dateStrToMillis(dateStr);
571 }
572
573 if (!d || isNaN(d)) {
8a68db7d 574 console.error("Couldn't parse " + dateStr + " as a date");
dedb4f5f
DV
575 }
576 return d;
577};
578
579/**
dedb4f5f
DV
580 * This is identical to JavaScript's built-in Date.parse() method, except that
581 * it doesn't get replaced with an incompatible method by aggressive JS
582 * libraries like MooTools or Joomla.
f11283de
DV
583 * @param {string} str The date string, e.g. "2011/05/06"
584 * @return {number} millis since epoch
585 * @private
dedb4f5f
DV
586 */
587Dygraph.dateStrToMillis = function(str) {
588 return new Date(str).getTime();
589};
590
591// These functions are all based on MochiKit.
592/**
593 * Copies all the properties from o to self.
594 *
f11283de
DV
595 * @param {!Object} self
596 * @param {!Object} o
597 * @return {!Object}
dedb4f5f 598 */
f11283de 599Dygraph.update = function(self, o) {
dedb4f5f
DV
600 if (typeof(o) != 'undefined' && o !== null) {
601 for (var k in o) {
602 if (o.hasOwnProperty(k)) {
603 self[k] = o[k];
604 }
605 }
606 }
607 return self;
608};
609
610/**
48e614ac
DV
611 * Copies all the properties from o to self.
612 *
f11283de
DV
613 * @param {!Object} self
614 * @param {!Object} o
615 * @return {!Object}
48e614ac
DV
616 * @private
617 */
618Dygraph.updateDeep = function (self, o) {
920208fb
PF
619 // Taken from http://stackoverflow.com/questions/384286/javascript-isdom-how-do-you-check-if-a-javascript-object-is-a-dom-object
620 function isNode(o) {
621 return (
622 typeof Node === "object" ? o instanceof Node :
623 typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName==="string"
624 );
625 }
626
48e614ac
DV
627 if (typeof(o) != 'undefined' && o !== null) {
628 for (var k in o) {
629 if (o.hasOwnProperty(k)) {
758a629f 630 if (o[k] === null) {
48e614ac
DV
631 self[k] = null;
632 } else if (Dygraph.isArrayLike(o[k])) {
633 self[k] = o[k].slice();
920208fb 634 } else if (isNode(o[k])) {
66ad3609
RK
635 // DOM objects are shallowly-copied.
636 self[k] = o[k];
48e614ac 637 } else if (typeof(o[k]) == 'object') {
c1c5dfeb 638 if (typeof(self[k]) != 'object' || self[k] === null) {
48e614ac
DV
639 self[k] = {};
640 }
641 Dygraph.updateDeep(self[k], o[k]);
642 } else {
643 self[k] = o[k];
644 }
645 }
646 }
647 }
648 return self;
649};
650
651/**
55deb02f 652 * @param {*} o
f11283de 653 * @return {boolean}
dedb4f5f
DV
654 * @private
655 */
f11283de 656Dygraph.isArrayLike = function(o) {
dedb4f5f
DV
657 var typ = typeof(o);
658 if (
659 (typ != 'object' && !(typ == 'function' &&
660 typeof(o.item) == 'function')) ||
661 o === null ||
662 typeof(o.length) != 'number' ||
663 o.nodeType === 3
664 ) {
665 return false;
666 }
667 return true;
668};
669
670/**
f11283de
DV
671 * @param {Object} o
672 * @return {boolean}
dedb4f5f
DV
673 * @private
674 */
675Dygraph.isDateLike = function (o) {
676 if (typeof(o) != "object" || o === null ||
677 typeof(o.getTime) != 'function') {
678 return false;
679 }
680 return true;
681};
682
683/**
48e614ac 684 * Note: this only seems to work for arrays.
f11283de
DV
685 * @param {!Array} o
686 * @return {!Array}
dedb4f5f
DV
687 * @private
688 */
689Dygraph.clone = function(o) {
690 // TODO(danvk): figure out how MochiKit's version works
691 var r = [];
692 for (var i = 0; i < o.length; i++) {
693 if (Dygraph.isArrayLike(o[i])) {
694 r.push(Dygraph.clone(o[i]));
695 } else {
696 r.push(o[i]);
697 }
698 }
699 return r;
700};
701
702/**
dedb4f5f
DV
703 * Create a new canvas element. This is more complex than a simple
704 * document.createElement("canvas") because of IE and excanvas.
f11283de
DV
705 *
706 * @return {!HTMLCanvasElement}
707 * @private
dedb4f5f
DV
708 */
709Dygraph.createCanvas = function() {
710 var canvas = document.createElement("canvas");
711
c0f54d4f 712 var isIE = (/MSIE/.test(navigator.userAgent) && !window.opera);
dedb4f5f 713 if (isIE && (typeof(G_vmlCanvasManager) != 'undefined')) {
f11283de
DV
714 canvas = G_vmlCanvasManager.initElement(
715 /**@type{!HTMLCanvasElement}*/(canvas));
dedb4f5f
DV
716 }
717
718 return canvas;
719};
9ca829f2
DV
720
721/**
37819481
PH
722 * Returns the context's pixel ratio, which is the ratio between the device
723 * pixel ratio and the backing store ratio. Typically this is 1 for conventional
724 * displays, and > 1 for HiDPI displays (such as the Retina MBP).
725 * See http://www.html5rocks.com/en/tutorials/canvas/hidpi/ for more details.
726 *
727 * @param {!CanvasRenderingContext2D} context The canvas's 2d context.
728 * @return {number} The ratio of the device pixel ratio and the backing store
729 * ratio for the specified context.
730 */
731Dygraph.getContextPixelRatio = function(context) {
732 try {
8241944b
GJ
733 var devicePixelRatio = window.devicePixelRatio;
734 var backingStoreRatio = context.webkitBackingStorePixelRatio ||
37819481
PH
735 context.mozBackingStorePixelRatio ||
736 context.msBackingStorePixelRatio ||
737 context.oBackingStorePixelRatio ||
3a0e53a4
AK
738 context.backingStorePixelRatio || 1;
739 if (devicePixelRatio !== undefined) {
8241944b
GJ
740 return devicePixelRatio / backingStoreRatio;
741 } else {
3a0e53a4
AK
742 // At least devicePixelRatio must be defined for this ratio to make sense.
743 // We default backingStoreRatio to 1: this does not exist on some browsers
744 // (i.e. desktop Chrome).
8241944b
GJ
745 return 1;
746 }
37819481
PH
747 } catch (e) {
748 return 1;
749 }
750};
751
752/**
971870e5
DV
753 * Checks whether the user is on an Android browser.
754 * Android does not fully support the <canvas> tag, e.g. w/r/t/ clipping.
f11283de
DV
755 * @return {boolean}
756 * @private
971870e5
DV
757 */
758Dygraph.isAndroid = function() {
758a629f 759 return (/Android/).test(navigator.userAgent);
971870e5
DV
760};
761
f11283de
DV
762
763/**
764 * TODO(danvk): use @template here when it's better supported for classes.
765 * @param {!Array} array
766 * @param {number} start
767 * @param {number} length
45a8c16f 768 * @param {function(!Array,?):boolean=} predicate
f11283de
DV
769 * @constructor
770 */
a26206cf
RK
771Dygraph.Iterator = function(array, start, length, predicate) {
772 start = start || 0;
773 length = length || array.length;
ff1074cd
RK
774 this.hasNext = true; // Use to identify if there's another element.
775 this.peek = null; // Use for look-ahead
0f20de1c 776 this.start_ = start;
a26206cf
RK
777 this.array_ = array;
778 this.predicate_ = predicate;
779 this.end_ = Math.min(array.length, start + length);
ff1074cd
RK
780 this.nextIdx_ = start - 1; // use -1 so initial advance works.
781 this.next(); // ignoring result.
42a9ebb8 782};
a26206cf 783
f11283de
DV
784/**
785 * @return {Object}
786 */
a26206cf 787Dygraph.Iterator.prototype.next = function() {
ff1074cd
RK
788 if (!this.hasNext) {
789 return null;
a26206cf 790 }
ff1074cd 791 var obj = this.peek;
a26206cf 792
ff1074cd
RK
793 var nextIdx = this.nextIdx_ + 1;
794 var found = false;
795 while (nextIdx < this.end_) {
a26206cf 796 if (!this.predicate_ || this.predicate_(this.array_, nextIdx)) {
ff1074cd
RK
797 this.peek = this.array_[nextIdx];
798 found = true;
799 break;
a26206cf
RK
800 }
801 nextIdx++;
802 }
803 this.nextIdx_ = nextIdx;
ff1074cd
RK
804 if (!found) {
805 this.hasNext = false;
806 this.peek = null;
807 }
808 return obj;
42a9ebb8 809};
a26206cf 810
971870e5 811/**
222d67c9 812 * Returns a new iterator over array, between indexes start and
7d1afbb9
RK
813 * start + length, and only returns entries that pass the accept function
814 *
f11283de
DV
815 * @param {!Array} array the array to iterate over.
816 * @param {number} start the first index to iterate over, 0 if absent.
817 * @param {number} length the number of elements in the array to iterate over.
818 * This, along with start, defines a slice of the array, and so length
819 * doesn't imply the number of elements in the iterator when accept doesn't
820 * always accept all values. array.length when absent.
45a8c16f 821 * @param {function(?):boolean=} opt_predicate a function that takes
f11283de
DV
822 * parameters array and idx, which returns true when the element should be
823 * returned. If omitted, all elements are accepted.
824 * @private
7d1afbb9 825 */
f11283de
DV
826Dygraph.createIterator = function(array, start, length, opt_predicate) {
827 return new Dygraph.Iterator(array, start, length, opt_predicate);
7d1afbb9
RK
828};
829
a96b8ba3
A
830// Shim layer with setTimeout fallback.
831// From: http://paulirish.com/2011/requestanimationframe-for-smart-animating/
e9a32469
A
832// Should be called with the window context:
833// Dygraph.requestAnimFrame.call(window, function() {})
bec100ae 834Dygraph.requestAnimFrame = (function() {
a96b8ba3
A
835 return window.requestAnimationFrame ||
836 window.webkitRequestAnimationFrame ||
837 window.mozRequestAnimationFrame ||
838 window.oRequestAnimationFrame ||
839 window.msRequestAnimationFrame ||
840 function (callback) {
841 window.setTimeout(callback, 1000 / 60);
842 };
843})();
844
845/**
d91ba598
A
846 * Call a function at most maxFrames times at an attempted interval of
847 * framePeriodInMillis, then call a cleanup function once. repeatFn is called
848 * once immediately, then at most (maxFrames - 1) times asynchronously. If
849 * maxFrames==1, then cleanup_fn() is also called synchronously. This function
850 * is used to sequence animation.
851 * @param {function(number)} repeatFn Called repeatedly -- takes the frame
852 * number (from 0 to maxFrames-1) as an argument.
853 * @param {number} maxFrames The max number of times to call repeatFn
854 * @param {number} framePeriodInMillis Max requested time between frames.
855 * @param {function()} cleanupFn A function to call after all repeatFn calls.
856 * @private
857 */
858Dygraph.repeatAndCleanup = function(repeatFn, maxFrames, framePeriodInMillis,
bec100ae 859 cleanupFn) {
d91ba598
A
860 var frameNumber = 0;
861 var previousFrameNumber;
862 var startTime = new Date().getTime();
863 repeatFn(frameNumber);
864 if (maxFrames == 1) {
865 cleanupFn();
b1a3b195
DV
866 return;
867 }
d91ba598 868 var maxFrameArg = maxFrames - 1;
b1a3b195
DV
869
870 (function loop() {
d91ba598 871 if (frameNumber >= maxFrames) return;
e9a32469 872 Dygraph.requestAnimFrame.call(window, function() {
d91ba598
A
873 // Determine which frame to draw based on the delay so far. Will skip
874 // frames if necessary.
875 var currentTime = new Date().getTime();
876 var delayInMillis = currentTime - startTime;
877 previousFrameNumber = frameNumber;
878 frameNumber = Math.floor(delayInMillis / framePeriodInMillis);
879 var frameDelta = frameNumber - previousFrameNumber;
880 // If we predict that the subsequent repeatFn call will overshoot our
881 // total frame target, so our last call will cause a stutter, then jump to
882 // the last call immediately. If we're going to cause a stutter, better
883 // to do it faster than slower.
884 var predictOvershootStutter = (frameNumber + frameDelta) > maxFrameArg;
885 if (predictOvershootStutter || (frameNumber >= maxFrameArg)) {
886 repeatFn(maxFrameArg); // Ensure final call with maxFrameArg.
887 cleanupFn();
b1a3b195 888 } else {
83b0c192 889 if (frameDelta !== 0) { // Don't call repeatFn with duplicate frames.
d91ba598
A
890 repeatFn(frameNumber);
891 }
b1a3b195
DV
892 loop();
893 }
a96b8ba3 894 });
b1a3b195
DV
895 })();
896};
897
8887663f
DV
898// A whitelist of options that do not change pixel positions.
899var pixelSafeOptions = {
900 'annotationClickHandler': true,
901 'annotationDblClickHandler': true,
902 'annotationMouseOutHandler': true,
903 'annotationMouseOverHandler': true,
904 'axisLabelColor': true,
905 'axisLineColor': true,
906 'axisLineWidth': true,
907 'clickCallback': true,
908 'drawCallback': true,
909 'drawHighlightPointCallback': true,
910 'drawPoints': true,
911 'drawPointCallback': true,
912 'drawXGrid': true,
913 'drawYGrid': true,
914 'fillAlpha': true,
915 'gridLineColor': true,
916 'gridLineWidth': true,
917 'hideOverlayOnMouseOut': true,
918 'highlightCallback': true,
919 'highlightCircleSize': true,
920 'interactionModel': true,
921 'isZoomedIgnoreProgrammaticZoom': true,
922 'labelsDiv': true,
923 'labelsDivStyles': true,
924 'labelsDivWidth': true,
925 'labelsKMB': true,
926 'labelsKMG2': true,
927 'labelsSeparateLines': true,
928 'labelsShowZeroValues': true,
929 'legend': true,
930 'panEdgeFraction': true,
931 'pixelsPerYLabel': true,
932 'pointClickCallback': true,
933 'pointSize': true,
934 'rangeSelectorPlotFillColor': true,
935 'rangeSelectorPlotStrokeColor': true,
936 'showLabelsOnHighlight': true,
937 'showRoller': true,
938 'strokeWidth': true,
939 'underlayCallback': true,
940 'unhighlightCallback': true,
941 'zoomCallback': true
942};
943
b1a3b195 944/**
9ca829f2
DV
945 * This function will scan the option list and determine if they
946 * require us to recalculate the pixel positions of each point.
8887663f 947 * TODO: move this into dygraph-options.js
f11283de 948 * @param {!Array.<string>} labels a list of options to check.
222d67c9 949 * @param {!Object} attrs
f11283de
DV
950 * @return {boolean} true if the graph needs new points else false.
951 * @private
9ca829f2
DV
952 */
953Dygraph.isPixelChangingOptionList = function(labels, attrs) {
9ca829f2
DV
954 // Assume that we do not require new points.
955 // This will change to true if we actually do need new points.
9ca829f2
DV
956
957 // Create a dictionary of series names for faster lookup.
958 // If there are no labels, then the dictionary stays empty.
959 var seriesNamesDictionary = { };
960 if (labels) {
961 for (var i = 1; i < labels.length; i++) {
962 seriesNamesDictionary[labels[i]] = true;
963 }
964 }
965
8887663f
DV
966 // Scan through a flat (i.e. non-nested) object of options.
967 // Returns true/false depending on whether new points are needed.
968 var scanFlatOptions = function(options) {
969 for (var property in options) {
970 if (options.hasOwnProperty(property) &&
971 !pixelSafeOptions[property]) {
972 return true;
973 }
974 }
975 return false;
976 };
977
9ca829f2 978 // Iterate through the list of updated options.
5061b42f 979 for (var property in attrs) {
8887663f
DV
980 if (!attrs.hasOwnProperty(property)) continue;
981
982 // Find out of this field is actually a series specific options list.
983 if (property == 'highlightSeriesOpts' ||
984 (seriesNamesDictionary[property] && !attrs.series)) {
985 // This property value is a list of options for this series.
986 if (scanFlatOptions(attrs[property])) return true;
987 } else if (property == 'series' || property == 'axes') {
988 // This is twice-nested options list.
989 var perSeries = attrs[property];
990 for (var series in perSeries) {
991 if (perSeries.hasOwnProperty(series) &&
992 scanFlatOptions(perSeries[series])) {
993 return true;
9ca829f2 994 }
ccd9d7c2 995 }
8887663f
DV
996 } else {
997 // If this was not a series specific option list, check if it's a pixel
998 // changing property.
999 if (!pixelSafeOptions[property]) return true;
9ca829f2
DV
1000 }
1001 }
1002
8887663f 1003 return false;
9ca829f2 1004};
78e58af4 1005
78e58af4
RK
1006Dygraph.Circles = {
1007 DEFAULT : function(g, name, ctx, canvasx, canvasy, color, radius) {
1008 ctx.beginPath();
1009 ctx.fillStyle = color;
1010 ctx.arc(canvasx, canvasy, radius, 0, 2 * Math.PI, false);
1011 ctx.fill();
78e58af4 1012 }
b7a1dc22 1013 // For more shapes, include extras/shapes.js
78e58af4 1014};
2bad4d92
DV
1015
1016/**
1017 * To create a "drag" interaction, you typically register a mousedown event
1018 * handler on the element where the drag begins. In that handler, you register a
1019 * mouseup handler on the window to determine when the mouse is released,
1020 * wherever that release happens. This works well, except when the user releases
1021 * the mouse over an off-domain iframe. In that case, the mouseup event is
1022 * handled by the iframe and never bubbles up to the window handler.
1023 *
1024 * To deal with this issue, we cover iframes with high z-index divs to make sure
1025 * they don't capture mouseup.
1026 *
1027 * Usage:
1028 * element.addEventListener('mousedown', function() {
1029 * var tarper = new Dygraph.IFrameTarp();
1030 * tarper.cover();
1031 * var mouseUpHandler = function() {
1032 * ...
1033 * window.removeEventListener(mouseUpHandler);
1034 * tarper.uncover();
1035 * };
1036 * window.addEventListener('mouseup', mouseUpHandler);
1037 * };
222d67c9 1038 *
2bad4d92
DV
1039 * @constructor
1040 */
1041Dygraph.IFrameTarp = function() {
f11283de 1042 /** @type {Array.<!HTMLDivElement>} */
2bad4d92
DV
1043 this.tarps = [];
1044};
1045
1046/**
1047 * Find all the iframes in the document and cover them with high z-index
1048 * transparent divs.
1049 */
1050Dygraph.IFrameTarp.prototype.cover = function() {
1051 var iframes = document.getElementsByTagName("iframe");
1052 for (var i = 0; i < iframes.length; i++) {
1053 var iframe = iframes[i];
1bc88216
DV
1054 var pos = Dygraph.findPos(iframe),
1055 x = pos.x,
1056 y = pos.y,
2bad4d92
DV
1057 width = iframe.offsetWidth,
1058 height = iframe.offsetHeight;
1059
1060 var div = document.createElement("div");
1061 div.style.position = "absolute";
1062 div.style.left = x + 'px';
1063 div.style.top = y + 'px';
1064 div.style.width = width + 'px';
1065 div.style.height = height + 'px';
1066 div.style.zIndex = 999;
1067 document.body.appendChild(div);
1068 this.tarps.push(div);
1069 }
1070};
1071
1072/**
1073 * Remove all the iframe covers. You should call this in a mouseup handler.
1074 */
1075Dygraph.IFrameTarp.prototype.uncover = function() {
1076 for (var i = 0; i < this.tarps.length; i++) {
1077 this.tarps[i].parentNode.removeChild(this.tarps[i]);
1078 }
1079 this.tarps = [];
1080};
e5763589
DV
1081
1082/**
df268bcc 1083 * Determine whether |data| is delimited by CR, CRLF, LF, LFCR.
e5763589 1084 * @param {string} data
f11283de 1085 * @return {?string} the delimiter that was detected (or null on failure).
e5763589
DV
1086 */
1087Dygraph.detectLineDelimiter = function(data) {
1088 for (var i = 0; i < data.length; i++) {
df268bcc
JH
1089 var code = data.charAt(i);
1090 if (code === '\r') {
1091 // Might actually be "\r\n".
1092 if (((i + 1) < data.length) && (data.charAt(i + 1) === '\n')) {
1093 return '\r\n';
1094 }
1095 return code;
1096 }
1097 if (code === '\n') {
e5763589 1098 // Might actually be "\n\r".
df268bcc
JH
1099 if (((i + 1) < data.length) && (data.charAt(i + 1) === '\r')) {
1100 return '\n\r';
1101 }
e5763589
DV
1102 return code;
1103 }
1104 }
1105
1106 return null;
1107};
def24194
DV
1108
1109/**
bcb545f4
LB
1110 * Is one node contained by another?
1111 * @param {Node} containee The contained node.
1112 * @param {Node} container The container node.
def24194
DV
1113 * @return {boolean} Whether containee is inside (or equal to) container.
1114 * @private
1115 */
bcb545f4 1116Dygraph.isNodeContainedBy = function(containee, container) {
def24194
DV
1117 if (container === null || containee === null) {
1118 return false;
1119 }
db775859
RK
1120 var containeeNode = /** @type {Node} */ (containee);
1121 while (containeeNode && containeeNode !== container) {
1122 containeeNode = containeeNode.parentNode;
def24194 1123 }
db775859 1124 return (containeeNode === container);
def24194 1125};
2fd143d3
DV
1126
1127
1128// This masks some numeric issues in older versions of Firefox,
1129// where 1.0/Math.pow(10,2) != Math.pow(10,-2).
1130/** @type {function(number,number):number} */
1131Dygraph.pow = function(base, exp) {
1132 if (exp < 0) {
1133 return 1.0 / Math.pow(base, -exp);
1134 }
1135 return Math.pow(base, exp);
1136};
1137
464b5f50
DV
1138/**
1139 * Converts any valid CSS color (hex, rgb(), named color) to an RGB tuple.
1140 *
b7a1dc22 1141 * @param {!string} colorStr Any valid CSS color string.
464b5f50
DV
1142 * @return {{r:number,g:number,b:number}} Parsed RGB tuple.
1143 * @private
1144 */
b7a1dc22 1145Dygraph.toRGB_ = function(colorStr) {
464b5f50
DV
1146 // TODO(danvk): cache color parses to avoid repeated DOM manipulation.
1147 var div = document.createElement('div');
b7a1dc22 1148 div.style.backgroundColor = colorStr;
464b5f50
DV
1149 div.style.visibility = 'hidden';
1150 document.body.appendChild(div);
263aca4a
DV
1151 var rgbStr;
1152 if (window.getComputedStyle) {
1153 rgbStr = window.getComputedStyle(div, null).backgroundColor;
1154 } else {
1155 // IE8
1156 rgbStr = div.currentStyle.backgroundColor;
1157 }
464b5f50 1158 document.body.removeChild(div);
b7a1dc22 1159 var bits = /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/.exec(rgbStr);
464b5f50
DV
1160 return {
1161 r: parseInt(bits[1], 10),
1162 g: parseInt(bits[2], 10),
1163 b: parseInt(bits[3], 10)
1164 };
1165};
55deb02f
DV
1166
1167/**
1168 * Checks whether the browser supports the &lt;canvas&gt; tag.
1169 * @param {HTMLCanvasElement=} opt_canvasElement Pass a canvas element as an
1170 * optimization if you have one.
1171 * @return {boolean} Whether the browser supports canvas.
1172 */
1173Dygraph.isCanvasSupported = function(opt_canvasElement) {
1174 var canvas;
1175 try {
1176 canvas = opt_canvasElement || document.createElement("canvas");
1177 canvas.getContext("2d");
1178 }
1179 catch (e) {
1180 var ie = navigator.appVersion.match(/MSIE (\d\.\d)/);
1181 var opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
1182 if ((!ie) || (ie[1] < 6) || (opera))
1183 return false;
1184 return true;
1185 }
1186 return true;
1187};
1188
1189/**
1190 * Parses the value as a floating point number. This is like the parseFloat()
1191 * built-in, but with a few differences:
1192 * - the empty string is parsed as null, rather than NaN.
1193 * - if the string cannot be parsed at all, an error is logged.
1194 * If the string can't be parsed, this method returns null.
1195 * @param {string} x The string to be parsed
1196 * @param {number=} opt_line_no The line number from which the string comes.
1197 * @param {string=} opt_line The text of the line from which the string comes.
1198 */
1199Dygraph.parseFloat_ = function(x, opt_line_no, opt_line) {
1200 var val = parseFloat(x);
1201 if (!isNaN(val)) return val;
1202
1203 // Try to figure out what happeend.
1204 // If the value is the empty string, parse it as null.
1205 if (/^ *$/.test(x)) return null;
1206
1207 // If it was actually "NaN", return it as NaN.
1208 if (/^ *nan *$/i.test(x)) return NaN;
1209
1210 // Looks like a parsing error.
1211 var msg = "Unable to parse '" + x + "' as a number";
1212 if (opt_line !== undefined && opt_line_no !== undefined) {
1213 msg += " on line " + (1+(opt_line_no||0)) + " ('" + opt_line + "') of CSV.";
1214 }
8a68db7d 1215 console.error(msg);
55deb02f
DV
1216
1217 return null;
1218};
8887663f
DV
1219
1220})();