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