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