]> git.openstreetmap.org Git - osqa.git/blob - forum/skins/default/media/js/jquery.flot.js
added number of answers to the question list pages
[osqa.git] / forum / skins / default / media / js / jquery.flot.js
1 /* Javascript plotting library for jQuery, v. 0.5.
2  *
3  * Released under the MIT license by IOLA, December 2007.
4  *
5  */
6
7 (function($) {
8     function Plot(target_, data_, options_) {
9         // data is on the form:
10         //   [ series1, series2 ... ]
11         // where series is either just the data as [ [x1, y1], [x2, y2], ... ]
12         // or { data: [ [x1, y1], [x2, y2], ... ], label: "some label" }
13         
14         var series = [],
15             options = {
16                 // the color theme used for graphs
17                 colors: ["#edc240", "#afd8f8", "#cb4b4b", "#4da74d", "#9440ed"],
18                 legend: {
19                     show: true,
20                     noColumns: 1, // number of colums in legend table
21                     labelFormatter: null, // fn: string -> string
22                     labelBoxBorderColor: "#ccc", // border color for the little label boxes
23                     container: null, // container (as jQuery object) to put legend in, null means default on top of graph
24                     position: "ne", // position of default legend container within plot
25                     margin: 5, // distance from grid edge to default legend container within plot
26                     backgroundColor: null, // null means auto-detect
27                     backgroundOpacity: 0.85 // set to 0 to avoid background
28                 },
29                 xaxis: {
30                     mode: null, // null or "time"
31                     min: null, // min. value to show, null means set automatically
32                     max: null, // max. value to show, null means set automatically
33                     autoscaleMargin: null, // margin in % to add if auto-setting min/max
34                     ticks: null, // either [1, 3] or [[1, "a"], 3] or (fn: axis info -> ticks) or app. number of ticks for auto-ticks
35                     tickFormatter: null, // fn: number -> string
36                     labelWidth: null, // size of tick labels in pixels
37                     labelHeight: null,
38                     
39                     // mode specific options
40                     tickDecimals: null, // no. of decimals, null means auto
41                     tickSize: null, // number or [number, "unit"]
42                     minTickSize: null, // number or [number, "unit"]
43                     monthNames: null, // list of names of months
44                     timeformat: null // format string to use
45                 },
46                 yaxis: {
47                     autoscaleMargin: 0.02
48                 },
49                 x2axis: {
50                     autoscaleMargin: null
51                 },
52                 y2axis: {
53                     autoscaleMargin: 0.02
54                 },              
55                 points: {
56                     show: false,
57                     radius: 3,
58                     lineWidth: 2, // in pixels
59                     fill: true,
60                     fillColor: "#ffffff"
61                 },
62                 lines: {
63                     // we don't put in show: false so we can see
64                     // whether lines were actively disabled 
65                     lineWidth: 2, // in pixels
66                     fill: false,
67                     fillColor: null,
68                     steps: false
69                 },
70                 bars: {
71                     show: false,
72                     lineWidth: 2, // in pixels
73                     barWidth: 1, // in units of the x axis
74                     fill: true,
75                     fillColor: null,
76                     align: "left", // or "center" 
77                     horizontal: false // when horizontal, left is now top
78                 },
79                 threshold: null, // or { below: number, color: color spec}
80                 grid: {
81                     color: "#545454", // primary color used for outline and labels
82                     backgroundColor: null, // null for transparent, else color
83                     tickColor: "#dddddd", // color used for the ticks
84                     labelMargin: 5, // in pixels
85                     borderWidth: 2, // in pixels
86                     borderColor: null, // set if different from the grid color
87                     markings: null, // array of ranges or fn: axes -> array of ranges
88                     markingsColor: "#f4f4f4",
89                     markingsLineWidth: 2,
90                     // interactive stuff
91                     clickable: false,
92                     hoverable: false,
93                     autoHighlight: true, // highlight in case mouse is near
94                     mouseActiveRadius: 10 // how far the mouse can be away to activate an item
95                 },
96                 selection: {
97                     mode: null, // one of null, "x", "y" or "xy"
98                     color: "#e8cfac"
99                 },
100                 crosshair: {
101                     mode: null, // one of null, "x", "y" or "xy",
102                     color: "#aa0000"
103                 },
104                 shadowSize: 3
105             },
106         canvas = null,      // the canvas for the plot itself
107         overlay = null,     // canvas for interactive stuff on top of plot
108         eventHolder = null, // jQuery object that events should be bound to
109         ctx = null, octx = null,
110         target = $(target_),
111         axes = { xaxis: {}, yaxis: {}, x2axis: {}, y2axis: {} },
112         plotOffset = { left: 0, right: 0, top: 0, bottom: 0},
113         canvasWidth = 0, canvasHeight = 0,
114         plotWidth = 0, plotHeight = 0,
115         // dedicated to storing data for buggy standard compliance cases
116         workarounds = {};
117         
118         this.setData = setData;
119         this.setupGrid = setupGrid;
120         this.draw = draw;
121         this.clearSelection = clearSelection;
122         this.setSelection = setSelection;
123         this.getCanvas = function() { return canvas; };
124         this.getPlotOffset = function() { return plotOffset; };
125         this.getData = function() { return series; };
126         this.getAxes = function() { return axes; };
127         this.setCrosshair = setCrosshair;
128         this.clearCrosshair = function () { setCrosshair(null); };
129         this.highlight = highlight;
130         this.unhighlight = unhighlight;
131         
132         // initialize
133         parseOptions(options_);
134         setData(data_);
135         constructCanvas();
136         setupGrid();
137         draw();
138
139
140         function setData(d) {
141             series = parseData(d);
142
143             fillInSeriesOptions();
144             processData();
145         }
146         
147         function parseData(d) {
148             var res = [];
149             for (var i = 0; i < d.length; ++i) {
150                 var s;
151                 if (d[i].data) {
152                     s = {};
153                     for (var v in d[i])
154                         s[v] = d[i][v];
155                 }
156                 else {
157                     s = { data: d[i] };
158                 }
159                 res.push(s);
160             }
161
162             return res;
163         }
164         
165         function parseOptions(o) {
166             $.extend(true, options, o);
167             if (options.grid.borderColor == null)
168                 options.grid.borderColor = options.grid.color
169             // backwards compatibility, to be removed in future
170             if (options.xaxis.noTicks && options.xaxis.ticks == null)
171                 options.xaxis.ticks = options.xaxis.noTicks;
172             if (options.yaxis.noTicks && options.yaxis.ticks == null)
173                 options.yaxis.ticks = options.yaxis.noTicks;
174             if (options.grid.coloredAreas)
175                 options.grid.markings = options.grid.coloredAreas;
176             if (options.grid.coloredAreasColor)
177                 options.grid.markingsColor = options.grid.coloredAreasColor;
178         }
179
180         function fillInSeriesOptions() {
181             var i;
182             
183             // collect what we already got of colors
184             var neededColors = series.length,
185                 usedColors = [],
186                 assignedColors = [];
187             for (i = 0; i < series.length; ++i) {
188                 var sc = series[i].color;
189                 if (sc != null) {
190                     --neededColors;
191                     if (typeof sc == "number")
192                         assignedColors.push(sc);
193                     else
194                         usedColors.push(parseColor(series[i].color));
195                 }
196             }
197             
198             // we might need to generate more colors if higher indices
199             // are assigned
200             for (i = 0; i < assignedColors.length; ++i) {
201                 neededColors = Math.max(neededColors, assignedColors[i] + 1);
202             }
203
204             // produce colors as needed
205             var colors = [], variation = 0;
206             i = 0;
207             while (colors.length < neededColors) {
208                 var c;
209                 if (options.colors.length == i) // check degenerate case
210                     c = new Color(100, 100, 100);
211                 else
212                     c = parseColor(options.colors[i]);
213
214                 // vary color if needed
215                 var sign = variation % 2 == 1 ? -1 : 1;
216                 var factor = 1 + sign * Math.ceil(variation / 2) * 0.2;
217                 c.scale(factor, factor, factor);
218
219                 // FIXME: if we're getting to close to something else,
220                 // we should probably skip this one
221                 colors.push(c);
222                 
223                 ++i;
224                 if (i >= options.colors.length) {
225                     i = 0;
226                     ++variation;
227                 }
228             }
229
230             // fill in the options
231             var colori = 0, s;
232             for (i = 0; i < series.length; ++i) {
233                 s = series[i];
234
235                 // assign colors
236                 if (s.color == null) {
237                     s.color = colors[colori].toString();
238                     ++colori;
239                 }
240                 else if (typeof s.color == "number")
241                     s.color = colors[s.color].toString();
242
243                 // copy the rest
244                 s.lines = $.extend(true, {}, options.lines, s.lines);
245                 s.points = $.extend(true, {}, options.points, s.points);
246                 s.bars = $.extend(true, {}, options.bars, s.bars);
247
248                 // turn on lines automatically in case nothing is set
249                 if (s.lines.show == null && !s.bars.show && !s.points.show)
250                     s.lines.show = true;
251                 if (s.shadowSize == null)
252                     s.shadowSize = options.shadowSize;
253
254                 if (!s.xaxis)
255                     s.xaxis = axes.xaxis;
256
257                 if (s.xaxis == 1)
258                     s.xaxis = axes.xaxis;
259                 else if (s.xaxis == 2)
260                     s.xaxis = axes.x2axis;
261
262                 if (!s.yaxis)
263                     s.yaxis = axes.yaxis;
264
265                 if (s.yaxis == 1)
266                     s.yaxis = axes.yaxis;
267                 else if (s.yaxis == 2)
268                     s.yaxis = axes.y2axis;
269
270                 if (!s.threshold)
271                     s.threshold = options.threshold;
272                 s.subseries = null;
273             }
274         }
275         
276         function processData() {
277             var topSentry = Number.POSITIVE_INFINITY,
278                 bottomSentry = Number.NEGATIVE_INFINITY,
279                 axis, i, j, k, m, s;
280
281             for (axis in axes) {
282                 axes[axis].datamin = topSentry;
283                 axes[axis].datamax = bottomSentry;
284                 axes[axis].min = options[axis].min;
285                 axes[axis].max = options[axis].max;
286                 axes[axis].used = false;
287             }
288             
289             for (i = 0; i < series.length; ++i) {
290                 s = series[i];
291                 s.datapoints = { points: [], incr: 2 };
292                 
293                 var data = s.data,
294                     points = s.datapoints.points,
295                     axisx = s.xaxis, axisy = s.yaxis,
296                     xmin = topSentry, xmax = bottomSentry,
297                     ymin = topSentry, ymax = bottomSentry,
298                     x, y, p, incr, format = [];
299
300                 // determine the increment
301                 if (s.bars.show) {
302                     s.datapoints.incr = 3;
303                     format.push({ d: 0 });
304                 }
305
306                 /*
307                 // examine data to find out how to copy
308                 for (j = 0; j < data.length; ++j) {
309                 }*/
310                 
311                 
312                 axisx.used = axisy.used = true;
313                 incr = s.datapoints.incr;
314                 
315                 for (j = k = 0; j < data.length; ++j, k += incr) {
316                     p = data[j];
317                     x = null;
318                     y = null;
319
320                     if (data[j] != null) {
321                         x = p[0];
322                         y = p[1];
323                     }
324                     
325                     // convert to number
326                     if (x != null && !isNaN(x = +x)) {
327                         if (x < xmin)
328                             xmin = x;
329                         if (x > xmax)
330                             xmax = x
331                     }
332                     else
333                         x = null;
334                     
335                     if (y != null && !isNaN(y = +y)) {
336                         if (y < ymin)
337                             ymin = y;
338                         if (y > ymax)
339                             ymax = y;
340                     }
341                     else
342                         y = null;
343
344                     if (x == null || y == null)
345                         x = y = null; // make sure everything is cleared
346
347                     for (m = 2; m < incr; ++m)
348                         points[k + m] = p[m] == null ? format[m-2].d : p[m];
349
350                     points[k + 1] = y;
351                     points[k] = x;
352                 }
353
354                 if (s.bars.show) {
355                     // make sure we got room for the bar on the dancing floor
356                     var delta = s.bars.align == "left" ? 0 : -s.bars.barWidth/2;
357                     if(s.bars.horizontal) {
358                         ymin += delta;
359                         ymax += delta + s.bars.barWidth;
360                     }
361                     else {
362                         xmin += delta;
363                         xmax += delta + s.bars.barWidth;
364                     }
365                 }
366                 
367                 axisx.datamin = Math.min(axisx.datamin, xmin);
368                 axisx.datamax = Math.max(axisx.datamax, xmax);
369                 axisy.datamin = Math.min(axisy.datamin, ymin);
370                 axisy.datamax = Math.max(axisy.datamax, ymax);
371
372                 
373                 // step charts
374                 if (s.lines.show && s.lines.steps) {
375                     p = [];
376                     // copy, inserting extra points to make steps
377                     for (j = k = 0; j < points.length; j += incr, k += incr) {
378                         x = points[j];
379                         y = points[j + 1];
380                         if (j > 0
381                             && points[j - incr] != null
382                             && x != null
383                             && points[j - incr + 1] != y) {
384                             p[k] = x;
385                             p[k + 1] = points[j - incr + 1];
386                             k += incr;
387                         }
388                         
389                         p[k] = x;
390                         p[k + 1] = y;
391                     }
392                     s.datapoints.linespoints = p;
393                 }
394
395                 // possibly split data points because of threshold
396                 if (s.threshold) {
397                     var orig = $.extend({}, s), thresholded = $.extend({}, s);
398                     orig.datapoints = { points: [], incr: incr };
399                     thresholded.datapoints = { points: [], incr: incr };
400                     
401                     thresholded.color = s.threshold.color;
402
403                     var below = s.threshold.below,
404                         origpoints = orig.datapoints.points,
405                         threspoints = thresholded.datapoints.points;
406
407                     // ordinary points
408                     for (j = 0; j < points.length; j += incr) {
409                         x = points[j];
410                         y = points[j + 1];
411
412                         if (y < below)
413                             p = threspoints;
414                         else
415                             p = origpoints;
416
417                         p.push(x);
418                         p.push(y);
419                     }
420
421                     // possibly split lines
422                     if (s.lines.show) {
423                         var lp = s.datapoints.linespoints || points;
424                         
425                         origpoints = [];
426                         threspoints = [];
427                         p = origpoints;
428                         
429                         for (j = 0; j < lp.length; j += incr) {
430                             x = lp[j];
431                             y = lp[j + 1];
432
433                             var prevp = p;
434                             if (y != null) {
435                                 if (y < below)
436                                     p = threspoints;
437                                 else
438                                     p = origpoints;
439                             }
440
441                             if (p != prevp && x != null && j > 0 && lp[j - incr] != null) {
442                                 // find intersection and add it to both
443                                 k = (x - lp[j - incr]) / (y - lp[j - incr + 1]) * (below - y) + x;
444                                 prevp.push(k);
445                                 prevp.push(below);
446                                 p.push(null); // start new segment
447                                 p.push(null);
448                                 p.push(k);
449                                 p.push(below);
450                             }
451                             
452                             p.push(x);
453                             p.push(y);
454                         }
455
456                         orig.datapoints.linespoints = origpoints
457                         thresholded.datapoints.linespoints = threspoints;
458                     }
459
460                     s.subseries = [orig, thresholded];
461                 }
462             }
463         }
464
465         function constructCanvas() {
466             function makeCanvas(width, height) {
467                 var c = document.createElement('canvas');
468                 c.width = width;
469                 c.height = height;
470                 if ($.browser.msie) // excanvas hack
471                     c = window.G_vmlCanvasManager.initElement(c);
472                 return c;
473             }
474             
475             canvasWidth = target.width();
476             canvasHeight = target.height();
477             target.html(""); // clear target
478             if (target.css("position") == 'static')
479                 target.css("position", "relative"); // for positioning labels and overlay
480
481             if (canvasWidth <= 0 || canvasHeight <= 0)
482                 throw "Invalid dimensions for plot, width = " + canvasWidth + ", height = " + canvasHeight;
483
484             // the canvas
485             canvas = $(makeCanvas(canvasWidth, canvasHeight)).appendTo(target).get(0);
486             ctx = canvas.getContext("2d");
487
488             // overlay canvas for interactive features
489             overlay = $(makeCanvas(canvasWidth, canvasHeight)).css({ position: 'absolute', left: 0, top: 0 }).appendTo(target).get(0);
490             octx = overlay.getContext("2d");
491
492             // we include the canvas in the event holder too, because IE 7
493             // sometimes has trouble with the stacking order
494             eventHolder = $([overlay, canvas]);
495
496             // bind events
497             if (options.selection.mode != null || options.crosshair.mode != null
498                 || options.grid.hoverable) {
499                 // FIXME: temp. work-around until jQuery bug 4398 is fixed
500                 eventHolder.each(function () {
501                     this.onmousemove = onMouseMove;
502                 });
503
504                 if (options.selection.mode != null)
505                     eventHolder.mousedown(onMouseDown);
506             }
507
508             if (options.crosshair.mode != null)
509                 eventHolder.mouseout(onMouseOut);
510             
511             if (options.grid.clickable)
512                 eventHolder.click(onClick);
513         }
514
515         function setupGrid() {
516             function setupAxis(axis, options) {
517                 setRange(axis, options);
518                 prepareTickGeneration(axis, options);
519                 setTicks(axis, options);
520                 // add transformation helpers
521                 if (axis == axes.xaxis || axis == axes.x2axis) {
522                     // data point to canvas coordinate
523                     axis.p2c = function (p) { return (p - axis.min) * axis.scale; };
524                     // canvas coordinate to data point 
525                     axis.c2p = function (c) { return axis.min + c / axis.scale; };
526                 }
527                 else {
528                     axis.p2c = function (p) { return (axis.max - p) * axis.scale; };
529                     axis.c2p = function (p) { return axis.max - p / axis.scale; };
530                 }
531             }
532
533             for (var axis in axes)
534                 setupAxis(axes[axis], options[axis]);
535
536             setSpacing();
537             insertLabels();
538             insertLegend();
539         }
540         
541         function setRange(axis, axisOptions) {
542             var min = axisOptions.min != null ? +axisOptions.min : axis.datamin,
543                 max = axisOptions.max != null ? +axisOptions.max : axis.datamax;
544
545             // degenerate case
546             if (min == Number.POSITIVE_INFINITY)
547                 min = 0;
548             if (max == Number.NEGATIVE_INFINITY)
549                 max = 1;
550             
551             if (max - min == 0.0) {
552                 // degenerate case
553                 var widen = max == 0 ? 1 : 0.01;
554
555                 if (axisOptions.min == null)
556                     min -= widen;
557                 // alway widen max if we couldn't widen min to ensure we
558                 // don't fall into min == max which doesn't work
559                 if (axisOptions.max == null || axisOptions.min != null)
560                     max += widen;
561             }
562             else {
563                 // consider autoscaling
564                 var margin = axisOptions.autoscaleMargin;
565                 if (margin != null) {
566                     if (axisOptions.min == null) {
567                         min -= (max - min) * margin;
568                         // make sure we don't go below zero if all values
569                         // are positive
570                         if (min < 0 && axis.datamin >= 0)
571                             min = 0;
572                     }
573                     if (axisOptions.max == null) {
574                         max += (max - min) * margin;
575                         if (max > 0 && axis.datamax <= 0)
576                             max = 0;
577                     }
578                 }
579             }
580             axis.min = min;
581             axis.max = max;
582         }
583
584         function prepareTickGeneration(axis, axisOptions) {
585             // estimate number of ticks
586             var noTicks;
587             if (typeof axisOptions.ticks == "number" && axisOptions.ticks > 0)
588                 noTicks = axisOptions.ticks;
589             else if (axis == axes.xaxis || axis == axes.x2axis)
590                 noTicks = canvasWidth / 100;
591             else
592                 noTicks = canvasHeight / 60;
593             
594             var delta = (axis.max - axis.min) / noTicks;
595             var size, generator, unit, formatter, i, magn, norm;
596
597             if (axisOptions.mode == "time") {
598                 // pretty handling of time
599                 
600                 // map of app. size of time units in milliseconds
601                 var timeUnitSize = {
602                     "second": 1000,
603                     "minute": 60 * 1000,
604                     "hour": 60 * 60 * 1000,
605                     "day": 24 * 60 * 60 * 1000,
606                     "month": 30 * 24 * 60 * 60 * 1000,
607                     "year": 365.2425 * 24 * 60 * 60 * 1000
608                 };
609
610
611                 // the allowed tick sizes, after 1 year we use
612                 // an integer algorithm
613                 var spec = [
614                     [1, "second"], [2, "second"], [5, "second"], [10, "second"],
615                     [30, "second"], 
616                     [1, "minute"], [2, "minute"], [5, "minute"], [10, "minute"],
617                     [30, "minute"], 
618                     [1, "hour"], [2, "hour"], [4, "hour"],
619                     [8, "hour"], [12, "hour"],
620                     [1, "day"], [2, "day"], [3, "day"],
621                     [0.25, "month"], [0.5, "month"], [1, "month"],
622                     [2, "month"], [3, "month"], [6, "month"],
623                     [1, "year"]
624                 ];
625
626                 var minSize = 0;
627                 if (axisOptions.minTickSize != null) {
628                     if (typeof axisOptions.tickSize == "number")
629                         minSize = axisOptions.tickSize;
630                     else
631                         minSize = axisOptions.minTickSize[0] * timeUnitSize[axisOptions.minTickSize[1]];
632                 }
633
634                 for (i = 0; i < spec.length - 1; ++i)
635                     if (delta < (spec[i][0] * timeUnitSize[spec[i][1]]
636                                  + spec[i + 1][0] * timeUnitSize[spec[i + 1][1]]) / 2
637                        && spec[i][0] * timeUnitSize[spec[i][1]] >= minSize)
638                         break;
639                 size = spec[i][0];
640                 unit = spec[i][1];
641                 
642                 // special-case the possibility of several years
643                 if (unit == "year") {
644                     magn = Math.pow(10, Math.floor(Math.log(delta / timeUnitSize.year) / Math.LN10));
645                     norm = (delta / timeUnitSize.year) / magn;
646                     if (norm < 1.5)
647                         size = 1;
648                     else if (norm < 3)
649                         size = 2;
650                     else if (norm < 7.5)
651                         size = 5;
652                     else
653                         size = 10;
654
655                     size *= magn;
656                 }
657
658                 if (axisOptions.tickSize) {
659                     size = axisOptions.tickSize[0];
660                     unit = axisOptions.tickSize[1];
661                 }
662                 
663                 generator = function(axis) {
664                     var ticks = [],
665                         tickSize = axis.tickSize[0], unit = axis.tickSize[1],
666                         d = new Date(axis.min);
667                     
668                     var step = tickSize * timeUnitSize[unit];
669
670                     if (unit == "second")
671                         d.setUTCSeconds(floorInBase(d.getUTCSeconds(), tickSize));
672                     if (unit == "minute")
673                         d.setUTCMinutes(floorInBase(d.getUTCMinutes(), tickSize));
674                     if (unit == "hour")
675                         d.setUTCHours(floorInBase(d.getUTCHours(), tickSize));
676                     if (unit == "month")
677                         d.setUTCMonth(floorInBase(d.getUTCMonth(), tickSize));
678                     if (unit == "year")
679                         d.setUTCFullYear(floorInBase(d.getUTCFullYear(), tickSize));
680                     
681                     // reset smaller components
682                     d.setUTCMilliseconds(0);
683                     if (step >= timeUnitSize.minute)
684                         d.setUTCSeconds(0);
685                     if (step >= timeUnitSize.hour)
686                         d.setUTCMinutes(0);
687                     if (step >= timeUnitSize.day)
688                         d.setUTCHours(0);
689                     if (step >= timeUnitSize.day * 4)
690                         d.setUTCDate(1);
691                     if (step >= timeUnitSize.year)
692                         d.setUTCMonth(0);
693
694
695                     var carry = 0, v = Number.NaN, prev;
696                     do {
697                         prev = v;
698                         v = d.getTime();
699                         ticks.push({ v: v, label: axis.tickFormatter(v, axis) });
700                         if (unit == "month") {
701                             if (tickSize < 1) {
702                                 // a bit complicated - we'll divide the month
703                                 // up but we need to take care of fractions
704                                 // so we don't end up in the middle of a day
705                                 d.setUTCDate(1);
706                                 var start = d.getTime();
707                                 d.setUTCMonth(d.getUTCMonth() + 1);
708                                 var end = d.getTime();
709                                 d.setTime(v + carry * timeUnitSize.hour + (end - start) * tickSize);
710                                 carry = d.getUTCHours();
711                                 d.setUTCHours(0);
712                             }
713                             else
714                                 d.setUTCMonth(d.getUTCMonth() + tickSize);
715                         }
716                         else if (unit == "year") {
717                             d.setUTCFullYear(d.getUTCFullYear() + tickSize);
718                         }
719                         else
720                             d.setTime(v + step);
721                     } while (v < axis.max && v != prev);
722
723                     return ticks;
724                 };
725
726                 formatter = function (v, axis) {
727                     var d = new Date(v);
728
729                     // first check global format
730                     if (axisOptions.timeformat != null)
731                         return $.plot.formatDate(d, axisOptions.timeformat, axisOptions.monthNames);
732                     
733                     var t = axis.tickSize[0] * timeUnitSize[axis.tickSize[1]];
734                     var span = axis.max - axis.min;
735                     
736                     if (t < timeUnitSize.minute)
737                         fmt = "%h:%M:%S";
738                     else if (t < timeUnitSize.day) {
739                         if (span < 2 * timeUnitSize.day)
740                             fmt = "%h:%M";
741                         else
742                             fmt = "%b %d %h:%M";
743                     }
744                     else if (t < timeUnitSize.month)
745                         fmt = "%b %d";
746                     else if (t < timeUnitSize.year) {
747                         if (span < timeUnitSize.year)
748                             fmt = "%b";
749                         else
750                             fmt = "%b %y";
751                     }
752                     else
753                         fmt = "%y";
754                     
755                     return $.plot.formatDate(d, fmt, axisOptions.monthNames);
756                 };
757             }
758             else {
759                 // pretty rounding of base-10 numbers
760                 var maxDec = axisOptions.tickDecimals;
761                 var dec = -Math.floor(Math.log(delta) / Math.LN10);
762                 if (maxDec != null && dec > maxDec)
763                     dec = maxDec;
764                 
765                 magn = Math.pow(10, -dec);
766                 norm = delta / magn; // norm is between 1.0 and 10.0
767                 
768                 if (norm < 1.5)
769                     size = 1;
770                 else if (norm < 3) {
771                     size = 2;
772                     // special case for 2.5, requires an extra decimal
773                     if (norm > 2.25 && (maxDec == null || dec + 1 <= maxDec)) {
774                         size = 2.5;
775                         ++dec;
776                     }
777                 }
778                 else if (norm < 7.5)
779                     size = 5;
780                 else
781                     size = 10;
782
783                 size *= magn;
784                 
785                 if (axisOptions.minTickSize != null && size < axisOptions.minTickSize)
786                     size = axisOptions.minTickSize;
787
788                 if (axisOptions.tickSize != null)
789                     size = axisOptions.tickSize;
790                 
791                 axis.tickDecimals = Math.max(0, (maxDec != null) ? maxDec : dec);
792                 
793                 generator = function (axis) {
794                     var ticks = [];
795
796                     // spew out all possible ticks
797                     var start = floorInBase(axis.min, axis.tickSize),
798                         i = 0, v = Number.NaN, prev;
799                     do {
800                         prev = v;
801                         v = start + i * axis.tickSize;
802                         ticks.push({ v: v, label: axis.tickFormatter(v, axis) });
803                         ++i;
804                     } while (v < axis.max && v != prev);
805                     return ticks;
806                 };
807
808                 formatter = function (v, axis) {
809                     return v.toFixed(axis.tickDecimals);
810                 };
811             }
812
813             axis.tickSize = unit ? [size, unit] : size;
814             axis.tickGenerator = generator;
815             if ($.isFunction(axisOptions.tickFormatter))
816                 axis.tickFormatter = function (v, axis) { return "" + axisOptions.tickFormatter(v, axis); };
817             else
818                 axis.tickFormatter = formatter;
819             if (axisOptions.labelWidth != null)
820                 axis.labelWidth = axisOptions.labelWidth;
821             if (axisOptions.labelHeight != null)
822                 axis.labelHeight = axisOptions.labelHeight;
823         }
824         
825         function setTicks(axis, axisOptions) {
826             axis.ticks = [];
827
828             if (!axis.used)
829                 return;
830             
831             if (axisOptions.ticks == null)
832                 axis.ticks = axis.tickGenerator(axis);
833             else if (typeof axisOptions.ticks == "number") {
834                 if (axisOptions.ticks > 0)
835                     axis.ticks = axis.tickGenerator(axis);
836             }
837             else if (axisOptions.ticks) {
838                 var ticks = axisOptions.ticks;
839
840                 if ($.isFunction(ticks))
841                     // generate the ticks
842                     ticks = ticks({ min: axis.min, max: axis.max });
843                 
844                 // clean up the user-supplied ticks, copy them over
845                 var i, v;
846                 for (i = 0; i < ticks.length; ++i) {
847                     var label = null;
848                     var t = ticks[i];
849                     if (typeof t == "object") {
850                         v = t[0];
851                         if (t.length > 1)
852                             label = t[1];
853                     }
854                     else
855                         v = t;
856                     if (label == null)
857                         label = axis.tickFormatter(v, axis);
858                     axis.ticks[i] = { v: v, label: label };
859                 }
860             }
861
862             if (axisOptions.autoscaleMargin != null && axis.ticks.length > 0) {
863                 // snap to ticks
864                 if (axisOptions.min == null)
865                     axis.min = Math.min(axis.min, axis.ticks[0].v);
866                 if (axisOptions.max == null && axis.ticks.length > 1)
867                     axis.max = Math.min(axis.max, axis.ticks[axis.ticks.length - 1].v);
868             }
869         }
870         
871         function setSpacing() {
872             function measureXLabels(axis) {
873                 // to avoid measuring the widths of the labels, we
874                 // construct fixed-size boxes and put the labels inside
875                 // them, we don't need the exact figures and the
876                 // fixed-size box content is easy to center
877                 if (axis.labelWidth == null)
878                     axis.labelWidth = canvasWidth / 6;
879
880                 // measure x label heights
881                 if (axis.labelHeight == null) {
882                     labels = [];
883                     for (i = 0; i < axis.ticks.length; ++i) {
884                         l = axis.ticks[i].label;
885                         if (l)
886                             labels.push('<div class="tickLabel" style="float:left;width:' + axis.labelWidth + 'px">' + l + '</div>');
887                     }
888                     
889                     axis.labelHeight = 0;
890                     if (labels.length > 0) {
891                         var dummyDiv = $('<div style="position:absolute;top:-10000px;width:10000px;font-size:smaller">'
892                                          + labels.join("") + '<div style="clear:left"></div></div>').appendTo(target);
893                         axis.labelHeight = dummyDiv.height();
894                         dummyDiv.remove();
895                     }
896                 }
897             }
898             
899             function measureYLabels(axis) {
900                 if (axis.labelWidth == null || axis.labelHeight == null) {
901                     var i, labels = [], l;
902                     // calculate y label dimensions
903                     for (i = 0; i < axis.ticks.length; ++i) {
904                         l = axis.ticks[i].label;
905                         if (l)
906                             labels.push('<div class="tickLabel">' + l + '</div>');
907                     }
908                     
909                     if (labels.length > 0) {
910                         var dummyDiv = $('<div style="position:absolute;top:-10000px;font-size:smaller">'
911                                          + labels.join("") + '</div>').appendTo(target);
912                         if (axis.labelWidth == null)
913                             axis.labelWidth = dummyDiv.width();
914                         if (axis.labelHeight == null)
915                             axis.labelHeight = dummyDiv.find("div").height();
916                         dummyDiv.remove();
917                     }
918                     
919                     if (axis.labelWidth == null)
920                         axis.labelWidth = 0;
921                     if (axis.labelHeight == null)
922                         axis.labelHeight = 0;
923                 }
924             }
925             
926             measureXLabels(axes.xaxis);
927             measureYLabels(axes.yaxis);
928             measureXLabels(axes.x2axis);
929             measureYLabels(axes.y2axis);
930
931             // get the most space needed around the grid for things
932             // that may stick out
933             var maxOutset = options.grid.borderWidth;
934             for (i = 0; i < series.length; ++i)
935                 maxOutset = Math.max(maxOutset, 2 * (series[i].points.radius + series[i].points.lineWidth/2));
936
937             plotOffset.left = plotOffset.right = plotOffset.top = plotOffset.bottom = maxOutset;
938
939             var margin = options.grid.labelMargin + options.grid.borderWidth;
940             
941             if (axes.xaxis.labelHeight > 0)
942                 plotOffset.bottom = Math.max(maxOutset, axes.xaxis.labelHeight + margin);
943             if (axes.yaxis.labelWidth > 0)
944                 plotOffset.left = Math.max(maxOutset, axes.yaxis.labelWidth + margin);
945
946             if (axes.x2axis.labelHeight > 0)
947                 plotOffset.top = Math.max(maxOutset, axes.x2axis.labelHeight + margin);
948             
949             if (axes.y2axis.labelWidth > 0)
950                 plotOffset.right = Math.max(maxOutset, axes.y2axis.labelWidth + margin);
951
952             plotWidth = canvasWidth - plotOffset.left - plotOffset.right;
953             plotHeight = canvasHeight - plotOffset.bottom - plotOffset.top;
954
955             // precompute how much the axis is scaling a point in canvas space
956             axes.xaxis.scale = plotWidth / (axes.xaxis.max - axes.xaxis.min);
957             axes.yaxis.scale = plotHeight / (axes.yaxis.max - axes.yaxis.min);
958             axes.x2axis.scale = plotWidth / (axes.x2axis.max - axes.x2axis.min);
959             axes.y2axis.scale = plotHeight / (axes.y2axis.max - axes.y2axis.min);
960         }
961         
962         function draw() {
963             drawGrid();
964             for (var i = 0; i < series.length; ++i) {
965                 var s = series[i];
966                 if (s.subseries)
967                     for (var j = 0; j < s.subseries.length; ++j)
968                         drawSeries(s.subseries[j]);
969                 else
970                     drawSeries(s);
971             }
972         }
973
974         function extractRange(ranges, coord) {
975             var firstAxis = coord + "axis",
976                 secondaryAxis = coord + "2axis",
977                 axis, from, to, reverse;
978
979             if (ranges[firstAxis]) {
980                 axis = axes[firstAxis];
981                 from = ranges[firstAxis].from;
982                 to = ranges[firstAxis].to;
983             }
984             else if (ranges[secondaryAxis]) {
985                 axis = axes[secondaryAxis];
986                 from = ranges[secondaryAxis].from;
987                 to = ranges[secondaryAxis].to;
988             }
989             else {
990                 // backwards-compat stuff - to be removed in future
991                 axis = axes[firstAxis];
992                 from = ranges[coord + "1"];
993                 to = ranges[coord + "2"];
994             }
995
996             // auto-reverse as an added bonus
997             if (from != null && to != null && from > to)
998                 return { from: to, to: from, axis: axis };
999             
1000             return { from: from, to: to, axis: axis };
1001         }
1002         
1003         function drawGrid() {
1004             var i;
1005             
1006             ctx.save();
1007             ctx.clearRect(0, 0, canvasWidth, canvasHeight);
1008             ctx.translate(plotOffset.left, plotOffset.top);
1009
1010             // draw background, if any
1011             if (options.grid.backgroundColor) {
1012                 ctx.fillStyle = getColorOrGradient(options.grid.backgroundColor, plotHeight, 0, "rgba(255, 255, 255, 0)");
1013                 ctx.fillRect(0, 0, plotWidth, plotHeight);
1014             }
1015
1016             // draw markings
1017             var markings = options.grid.markings;
1018             if (markings) {
1019                 if ($.isFunction(markings))
1020                     // xmin etc. are backwards-compatible, to be removed in future
1021                     markings = markings({ xmin: axes.xaxis.min, xmax: axes.xaxis.max, ymin: axes.yaxis.min, ymax: axes.yaxis.max, xaxis: axes.xaxis, yaxis: axes.yaxis, x2axis: axes.x2axis, y2axis: axes.y2axis });
1022
1023                 for (i = 0; i < markings.length; ++i) {
1024                     var m = markings[i],
1025                         xrange = extractRange(m, "x"),
1026                         yrange = extractRange(m, "y");
1027
1028                     // fill in missing
1029                     if (xrange.from == null)
1030                         xrange.from = xrange.axis.min;
1031                     if (xrange.to == null)
1032                         xrange.to = xrange.axis.max;
1033                     if (yrange.from == null)
1034                         yrange.from = yrange.axis.min;
1035                     if (yrange.to == null)
1036                         yrange.to = yrange.axis.max;
1037
1038                     // clip
1039                     if (xrange.to < xrange.axis.min || xrange.from > xrange.axis.max ||
1040                         yrange.to < yrange.axis.min || yrange.from > yrange.axis.max)
1041                         continue;
1042
1043                     xrange.from = Math.max(xrange.from, xrange.axis.min);
1044                     xrange.to = Math.min(xrange.to, xrange.axis.max);
1045                     yrange.from = Math.max(yrange.from, yrange.axis.min);
1046                     yrange.to = Math.min(yrange.to, yrange.axis.max);
1047
1048                     if (xrange.from == xrange.to && yrange.from == yrange.to)
1049                         continue;
1050
1051                     // then draw
1052                     xrange.from = xrange.axis.p2c(xrange.from);
1053                     xrange.to = xrange.axis.p2c(xrange.to);
1054                     yrange.from = yrange.axis.p2c(yrange.from);
1055                     yrange.to = yrange.axis.p2c(yrange.to);
1056                     
1057                     if (xrange.from == xrange.to || yrange.from == yrange.to) {
1058                         // draw line
1059                         ctx.strokeStyle = m.color || options.grid.markingsColor;
1060                         ctx.beginPath();
1061                         ctx.lineWidth = m.lineWidth || options.grid.markingsLineWidth;
1062                         //ctx.moveTo(Math.floor(xrange.from), yrange.from);
1063                         //ctx.lineTo(Math.floor(xrange.to), yrange.to);
1064                         ctx.moveTo(xrange.from, yrange.from);
1065                         ctx.lineTo(xrange.to, yrange.to);
1066                         ctx.stroke();
1067                     }
1068                     else {
1069                         // fill area
1070                         ctx.fillStyle = m.color || options.grid.markingsColor;
1071                         ctx.fillRect(xrange.from, yrange.to,
1072                                      xrange.to - xrange.from,
1073                                      yrange.from - yrange.to);
1074                     }
1075                 }
1076             }
1077             
1078             // draw the inner grid
1079             ctx.lineWidth = 1;
1080             ctx.strokeStyle = options.grid.tickColor;
1081             ctx.beginPath();
1082             var v, axis = axes.xaxis;
1083             for (i = 0; i < axis.ticks.length; ++i) {
1084                 v = axis.ticks[i].v;
1085                 if (v <= axis.min || v >= axes.xaxis.max)
1086                     continue;   // skip those lying on the axes
1087
1088                 ctx.moveTo(Math.floor(axis.p2c(v)) + ctx.lineWidth/2, 0);
1089                 ctx.lineTo(Math.floor(axis.p2c(v)) + ctx.lineWidth/2, plotHeight);
1090             }
1091
1092             axis = axes.yaxis;
1093             for (i = 0; i < axis.ticks.length; ++i) {
1094                 v = axis.ticks[i].v;
1095                 if (v <= axis.min || v >= axis.max)
1096                     continue;
1097
1098                 ctx.moveTo(0, Math.floor(axis.p2c(v)) + ctx.lineWidth/2);
1099                 ctx.lineTo(plotWidth, Math.floor(axis.p2c(v)) + ctx.lineWidth/2);
1100             }
1101
1102             axis = axes.x2axis;
1103             for (i = 0; i < axis.ticks.length; ++i) {
1104                 v = axis.ticks[i].v;
1105                 if (v <= axis.min || v >= axis.max)
1106                     continue;
1107     
1108                 ctx.moveTo(Math.floor(axis.p2c(v)) + ctx.lineWidth/2, -5);
1109                 ctx.lineTo(Math.floor(axis.p2c(v)) + ctx.lineWidth/2, 5);
1110             }
1111
1112             axis = axes.y2axis;
1113             for (i = 0; i < axis.ticks.length; ++i) {
1114                 v = axis.ticks[i].v;
1115                 if (v <= axis.min || v >= axis.max)
1116                     continue;
1117
1118                 ctx.moveTo(plotWidth-5, Math.floor(axis.p2c(v)) + ctx.lineWidth/2);
1119                 ctx.lineTo(plotWidth+5, Math.floor(axis.p2c(v)) + ctx.lineWidth/2);
1120             }
1121             
1122             ctx.stroke();
1123             
1124             if (options.grid.borderWidth) {
1125                 // draw border
1126                 var bw = options.grid.borderWidth;
1127                 ctx.lineWidth = bw;
1128                 ctx.strokeStyle = options.grid.borderColor;
1129                 ctx.strokeRect(-bw/2, -bw/2, plotWidth + bw, plotHeight + bw);
1130             }
1131
1132             ctx.restore();
1133         }
1134         
1135         function insertLabels() {
1136             target.find(".tickLabels").remove();
1137             
1138             var html = ['<div class="tickLabels" style="font-size:smaller;color:' + options.grid.color + '">'];
1139
1140             function addLabels(axis, labelGenerator) {
1141                 for (var i = 0; i < axis.ticks.length; ++i) {
1142                     var tick = axis.ticks[i];
1143                     if (!tick.label || tick.v < axis.min || tick.v > axis.max)
1144                         continue;
1145                     html.push(labelGenerator(tick, axis));
1146                 }
1147             }
1148
1149             var margin = options.grid.labelMargin + options.grid.borderWidth;
1150             
1151             addLabels(axes.xaxis, function (tick, axis) {
1152                 return '<div style="position:absolute;top:' + (plotOffset.top + plotHeight + margin) + 'px;left:' + Math.round(plotOffset.left + axis.p2c(tick.v) - axis.labelWidth/2) + 'px;width:' + axis.labelWidth + 'px;text-align:center" class="tickLabel">' + tick.label + "</div>";
1153             });
1154             
1155             
1156             addLabels(axes.yaxis, function (tick, axis) {
1157                 return '<div style="position:absolute;top:' + Math.round(plotOffset.top + axis.p2c(tick.v) - axis.labelHeight/2) + 'px;right:' + (plotOffset.right + plotWidth + margin) + 'px;width:' + axis.labelWidth + 'px;text-align:right" class="tickLabel">' + tick.label + "</div>";
1158             });
1159             
1160             addLabels(axes.x2axis, function (tick, axis) {
1161                 return '<div style="position:absolute;bottom:' + (plotOffset.bottom + plotHeight + margin) + 'px;left:' + Math.round(plotOffset.left + axis.p2c(tick.v) - axis.labelWidth/2) + 'px;width:' + axis.labelWidth + 'px;text-align:center" class="tickLabel">' + tick.label + "</div>";
1162             });
1163             
1164             addLabels(axes.y2axis, function (tick, axis) {
1165                 return '<div style="position:absolute;top:' + Math.round(plotOffset.top + axis.p2c(tick.v) - axis.labelHeight/2) + 'px;left:' + (plotOffset.left + plotWidth + margin) +'px;width:' + axis.labelWidth + 'px;text-align:left" class="tickLabel">' + tick.label + "</div>";
1166             });
1167
1168             html.push('</div>');
1169             
1170             target.append(html.join(""));
1171         }
1172
1173         function drawSeries(series) {
1174             if (series.lines.show)
1175                 drawSeriesLines(series);
1176             if (series.bars.show)
1177                 drawSeriesBars(series);
1178             if (series.points.show)
1179                 drawSeriesPoints(series);
1180         }
1181         
1182         function drawSeriesLines(series) {
1183             function plotLine(datapoints, xoffset, yoffset, axisx, axisy) {
1184                 var points = datapoints.linespoints || datapoints.points,
1185                     incr = datapoints.incr,
1186                     prevx = null, prevy = null;
1187                 
1188                 ctx.beginPath();
1189                 for (var i = incr; i < points.length; i += incr) {
1190                     var x1 = points[i - incr], y1 = points[i - incr + 1],
1191                         x2 = points[i], y2 = points[i + 1];
1192                     
1193                     if (x1 == null || x2 == null)
1194                         continue;
1195
1196                     // clip with ymin
1197                     if (y1 <= y2 && y1 < axisy.min) {
1198                         if (y2 < axisy.min)
1199                             continue;   // line segment is outside
1200                         // compute new intersection point
1201                         x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
1202                         y1 = axisy.min;
1203                     }
1204                     else if (y2 <= y1 && y2 < axisy.min) {
1205                         if (y1 < axisy.min)
1206                             continue;
1207                         x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
1208                         y2 = axisy.min;
1209                     }
1210
1211                     // clip with ymax
1212                     if (y1 >= y2 && y1 > axisy.max) {
1213                         if (y2 > axisy.max)
1214                             continue;
1215                         x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
1216                         y1 = axisy.max;
1217                     }
1218                     else if (y2 >= y1 && y2 > axisy.max) {
1219                         if (y1 > axisy.max)
1220                             continue;
1221                         x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
1222                         y2 = axisy.max;
1223                     }
1224
1225                     // clip with xmin
1226                     if (x1 <= x2 && x1 < axisx.min) {
1227                         if (x2 < axisx.min)
1228                             continue;
1229                         y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
1230                         x1 = axisx.min;
1231                     }
1232                     else if (x2 <= x1 && x2 < axisx.min) {
1233                         if (x1 < axisx.min)
1234                             continue;
1235                         y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
1236                         x2 = axisx.min;
1237                     }
1238
1239                     // clip with xmax
1240                     if (x1 >= x2 && x1 > axisx.max) {
1241                         if (x2 > axisx.max)
1242                             continue;
1243                         y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
1244                         x1 = axisx.max;
1245                     }
1246                     else if (x2 >= x1 && x2 > axisx.max) {
1247                         if (x1 > axisx.max)
1248                             continue;
1249                         y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
1250                         x2 = axisx.max;
1251                     }
1252
1253                     if (x1 != prevx || y1 != prevy)
1254                         ctx.moveTo(axisx.p2c(x1) + xoffset, axisy.p2c(y1) + yoffset);
1255                     
1256                     prevx = x2;
1257                     prevy = y2;
1258                     ctx.lineTo(axisx.p2c(x2) + xoffset, axisy.p2c(y2) + yoffset);
1259                 }
1260                 ctx.stroke();
1261             }
1262
1263             function plotLineArea(datapoints, axisx, axisy) {
1264                 var points = datapoints.linespoints || datapoints.points,
1265                     incr = datapoints.incr,
1266                     bottom = Math.min(Math.max(0, axisy.min), axisy.max),
1267                     top, lastX = 0, areaOpen = false;
1268                 
1269                 for (var i = incr; i < points.length; i += incr) {
1270                     var x1 = points[i - incr], y1 = points[i - incr + 1],
1271                         x2 = points[i], y2 = points[i + 1];
1272                     
1273                     if (areaOpen && x1 != null && x2 == null) {
1274                         // close area
1275                         ctx.lineTo(axisx.p2c(lastX), axisy.p2c(bottom));
1276                         ctx.fill();
1277                         areaOpen = false;
1278                         continue;
1279                     }
1280
1281                     if (x1 == null || x2 == null)
1282                         continue;
1283
1284                     // clip x values
1285                     
1286                     // clip with xmin
1287                     if (x1 <= x2 && x1 < axisx.min) {
1288                         if (x2 < axisx.min)
1289                             continue;
1290                         y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
1291                         x1 = axisx.min;
1292                     }
1293                     else if (x2 <= x1 && x2 < axisx.min) {
1294                         if (x1 < axisx.min)
1295                             continue;
1296                         y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
1297                         x2 = axisx.min;
1298                     }
1299
1300                     // clip with xmax
1301                     if (x1 >= x2 && x1 > axisx.max) {
1302                         if (x2 > axisx.max)
1303                             continue;
1304                         y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
1305                         x1 = axisx.max;
1306                     }
1307                     else if (x2 >= x1 && x2 > axisx.max) {
1308                         if (x1 > axisx.max)
1309                             continue;
1310                         y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
1311                         x2 = axisx.max;
1312                     }
1313
1314                     if (!areaOpen) {
1315                         // open area
1316                         ctx.beginPath();
1317                         ctx.moveTo(axisx.p2c(x1), axisy.p2c(bottom));
1318                         areaOpen = true;
1319                     }
1320                     
1321                     // now first check the case where both is outside
1322                     if (y1 >= axisy.max && y2 >= axisy.max) {
1323                         ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.max));
1324                         ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.max));
1325                         lastX = x2;
1326                         continue;
1327                     }
1328                     else if (y1 <= axisy.min && y2 <= axisy.min) {
1329                         ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.min));
1330                         ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.min));
1331                         lastX = x2;
1332                         continue;
1333                     }
1334                     
1335                     // else it's a bit more complicated, there might
1336                     // be two rectangles and two triangles we need to fill
1337                     // in; to find these keep track of the current x values
1338                     var x1old = x1, x2old = x2;
1339
1340                     // and clip the y values, without shortcutting
1341                     
1342                     // clip with ymin
1343                     if (y1 <= y2 && y1 < axisy.min && y2 >= axisy.min) {
1344                         x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
1345                         y1 = axisy.min;
1346                     }
1347                     else if (y2 <= y1 && y2 < axisy.min && y1 >= axisy.min) {
1348                         x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
1349                         y2 = axisy.min;
1350                     }
1351
1352                     // clip with ymax
1353                     if (y1 >= y2 && y1 > axisy.max && y2 <= axisy.max) {
1354                         x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
1355                         y1 = axisy.max;
1356                     }
1357                     else if (y2 >= y1 && y2 > axisy.max && y1 <= axisy.max) {
1358                         x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
1359                         y2 = axisy.max;
1360                     }
1361
1362
1363                     // if the x value was changed we got a rectangle
1364                     // to fill
1365                     if (x1 != x1old) {
1366                         if (y1 <= axisy.min)
1367                             top = axisy.min;
1368                         else
1369                             top = axisy.max;
1370                         
1371                         ctx.lineTo(axisx.p2c(x1old), axisy.p2c(top));
1372                         ctx.lineTo(axisx.p2c(x1), axisy.p2c(top));
1373                     }
1374                     
1375                     // fill the triangles
1376                     ctx.lineTo(axisx.p2c(x1), axisy.p2c(y1));
1377                     ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2));
1378
1379                     // fill the other rectangle if it's there
1380                     if (x2 != x2old) {
1381                         if (y2 <= axisy.min)
1382                             top = axisy.min;
1383                         else
1384                             top = axisy.max;
1385                         
1386                         ctx.lineTo(axisx.p2c(x2), axisy.p2c(top));
1387                         ctx.lineTo(axisx.p2c(x2old), axisy.p2c(top));
1388                     }
1389
1390                     lastX = Math.max(x2, x2old);
1391                 }
1392
1393                 if (areaOpen) {
1394                     ctx.lineTo(axisx.p2c(lastX), axisy.p2c(bottom));
1395                     ctx.fill();
1396                 }
1397             }
1398             
1399             ctx.save();
1400             ctx.translate(plotOffset.left, plotOffset.top);
1401             ctx.lineJoin = "round";
1402
1403             var lw = series.lines.lineWidth,
1404                 sw = series.shadowSize;
1405             // FIXME: consider another form of shadow when filling is turned on
1406             if (lw > 0 && sw > 0) {
1407                 // draw shadow as a thick and thin line with transparency
1408                 ctx.lineWidth = sw;
1409                 ctx.strokeStyle = "rgba(0,0,0,0.1)";
1410                 var xoffset = 1;
1411                 plotLine(series.datapoints, xoffset, Math.sqrt((lw/2 + sw/2)*(lw/2 + sw/2) - xoffset*xoffset), series.xaxis, series.yaxis);
1412                 ctx.lineWidth = sw/2;
1413                 plotLine(series.datapoints, xoffset, Math.sqrt((lw/2 + sw/4)*(lw/2 + sw/4) - xoffset*xoffset), series.xaxis, series.yaxis);
1414             }
1415
1416             ctx.lineWidth = lw;
1417             ctx.strokeStyle = series.color;
1418             var fillStyle = getFillStyle(series.lines, series.color, 0, plotHeight);
1419             if (fillStyle) {
1420                 ctx.fillStyle = fillStyle;
1421                 plotLineArea(series.datapoints, series.xaxis, series.yaxis);
1422             }
1423
1424             if (lw > 0)
1425                 plotLine(series.datapoints, 0, 0, series.xaxis, series.yaxis);
1426             ctx.restore();
1427         }
1428
1429         function drawSeriesPoints(series) {
1430             function plotPoints(datapoints, radius, fillStyle, offset, circumference, axisx, axisy) {
1431                 var points = datapoints.points, incr = datapoints.incr;
1432                 
1433                 for (var i = 0; i < points.length; i += incr) {
1434                     var x = points[i], y = points[i + 1];
1435                     if (x == null || x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max)
1436                         continue;
1437                     
1438                     ctx.beginPath();
1439                     ctx.arc(axisx.p2c(x), axisy.p2c(y) + offset, radius, 0, circumference, true);
1440                     if (fillStyle) {
1441                         ctx.fillStyle = fillStyle;
1442                         ctx.fill();
1443                     }
1444                     ctx.stroke();
1445                 }
1446             }
1447             
1448             ctx.save();
1449             ctx.translate(plotOffset.left, plotOffset.top);
1450
1451             var lw = series.lines.lineWidth,
1452                 sw = series.shadowSize,
1453                 radius = series.points.radius;
1454             if (lw > 0 && sw > 0) {
1455                 // draw shadow in two steps
1456                 var w = sw / 2;
1457                 ctx.lineWidth = w;
1458                 ctx.strokeStyle = "rgba(0,0,0,0.1)";
1459                 plotPoints(series.datapoints, radius, null, w + w/2, 2 * Math.PI,
1460                            series.xaxis, series.yaxis);
1461
1462                 ctx.strokeStyle = "rgba(0,0,0,0.2)";
1463                 plotPoints(series.datapoints, radius, null, w/2, 2 * Math.PI,
1464                            series.xaxis, series.yaxis);
1465             }
1466
1467             ctx.lineWidth = lw;
1468             ctx.strokeStyle = series.color;
1469             plotPoints(series.datapoints, radius,
1470                        getFillStyle(series.points, series.color), 0, 2 * Math.PI,
1471                        series.xaxis, series.yaxis);
1472             ctx.restore();
1473         }
1474
1475         function drawBar(x, y, b, barLeft, barRight, offset, fillStyleCallback, axisx, axisy, c, horizontal) {
1476             var left, right, bottom, top,
1477                 drawLeft, drawRight, drawTop, drawBottom,
1478                 tmp;
1479
1480             if (horizontal) {
1481                 drawBottom = drawRight = drawTop = true;
1482                 drawLeft = false;
1483                 left = b;
1484                 right = x;
1485                 top = y + barLeft;
1486                 bottom = y + barRight;
1487
1488                 // account for negative bars
1489                 if (right < left) {
1490                     tmp = right;
1491                     right = left;
1492                     left = tmp;
1493                     drawLeft = true;
1494                     drawRight = false;
1495                 }
1496             }
1497             else {
1498                 drawLeft = drawRight = drawTop = true;
1499                 drawBottom = false;
1500                 left = x + barLeft;
1501                 right = x + barRight;
1502                 bottom = b;
1503                 top = y;
1504
1505                 // account for negative bars
1506                 if (top < bottom) {
1507                     tmp = top;
1508                     top = bottom;
1509                     bottom = tmp;
1510                     drawBottom = true;
1511                     drawTop = false;
1512                 }
1513             }
1514            
1515             // clip
1516             if (right < axisx.min || left > axisx.max ||
1517                 top < axisy.min || bottom > axisy.max)
1518                 return;
1519             
1520             if (left < axisx.min) {
1521                 left = axisx.min;
1522                 drawLeft = false;
1523             }
1524
1525             if (right > axisx.max) {
1526                 right = axisx.max;
1527                 drawRight = false;
1528             }
1529
1530             if (bottom < axisy.min) {
1531                 bottom = axisy.min;
1532                 drawBottom = false;
1533             }
1534             
1535             if (top > axisy.max) {
1536                 top = axisy.max;
1537                 drawTop = false;
1538             }
1539
1540             left = axisx.p2c(left);
1541             bottom = axisy.p2c(bottom);
1542             right = axisx.p2c(right);
1543             top = axisy.p2c(top);
1544             
1545             // fill the bar
1546             if (fillStyleCallback) {
1547                 c.beginPath();
1548                 c.moveTo(left, bottom);
1549                 c.lineTo(left, top);
1550                 c.lineTo(right, top);
1551                 c.lineTo(right, bottom);
1552                 c.fillStyle = fillStyleCallback(bottom, top);
1553                 c.fill();
1554             }
1555
1556             // draw outline
1557             if (drawLeft || drawRight || drawTop || drawBottom) {
1558                 c.beginPath();
1559
1560                 // FIXME: inline moveTo is buggy with excanvas
1561                 c.moveTo(left, bottom + offset);
1562                 if (drawLeft)
1563                     c.lineTo(left, top + offset);
1564                 else
1565                     c.moveTo(left, top + offset);
1566                 if (drawTop)
1567                     c.lineTo(right, top + offset);
1568                 else
1569                     c.moveTo(right, top + offset);
1570                 if (drawRight)
1571                     c.lineTo(right, bottom + offset);
1572                 else
1573                     c.moveTo(right, bottom + offset);
1574                 if (drawBottom)
1575                     c.lineTo(left, bottom + offset);
1576                 else
1577                     c.moveTo(left, bottom + offset);
1578                 c.stroke();
1579             }
1580         }
1581         
1582         function drawSeriesBars(series) {
1583             function plotBars(datapoints, barLeft, barRight, offset, fillStyleCallback, axisx, axisy) {
1584                 var points = datapoints.points, incr = datapoints.incr;
1585                 
1586                 for (var i = 0; i < points.length; i += incr) {
1587                     if (points[i] == null)
1588                         continue;
1589                     drawBar(points[i], points[i + 1], points[i + 2], barLeft, barRight, offset, fillStyleCallback, axisx, axisy, ctx, series.bars.horizontal);
1590                 }
1591             }
1592
1593             ctx.save();
1594             ctx.translate(plotOffset.left, plotOffset.top);
1595
1596             // FIXME: figure out a way to add shadows (for instance along the right edge)
1597             ctx.lineWidth = series.bars.lineWidth;
1598             ctx.strokeStyle = series.color;
1599             var barLeft = series.bars.align == "left" ? 0 : -series.bars.barWidth/2;
1600             var fillStyleCallback = series.bars.fill ? function (bottom, top) { return getFillStyle(series.bars, series.color, bottom, top); } : null;
1601             plotBars(series.datapoints, barLeft, barLeft + series.bars.barWidth, 0, fillStyleCallback, series.xaxis, series.yaxis);
1602             ctx.restore();
1603         }
1604
1605         function getFillStyle(filloptions, seriesColor, bottom, top) {
1606             var fill = filloptions.fill;
1607             if (!fill)
1608                 return null;
1609
1610             if (filloptions.fillColor)
1611                 return getColorOrGradient(filloptions.fillColor, bottom, top, seriesColor);
1612             
1613             var c = parseColor(seriesColor);
1614             c.a = typeof fill == "number" ? fill : 0.4;
1615             c.normalize();
1616             return c.toString();
1617         }
1618         
1619         function insertLegend() {
1620             target.find(".legend").remove();
1621
1622             if (!options.legend.show)
1623                 return;
1624             
1625             var fragments = [], rowStarted = false,
1626                 lf = options.legend.labelFormatter, s, label;
1627             for (i = 0; i < series.length; ++i) {
1628                 s = series[i];
1629                 label = s.label;
1630                 if (!label)
1631                     continue;
1632                 
1633                 if (i % options.legend.noColumns == 0) {
1634                     if (rowStarted)
1635                         fragments.push('</tr>');
1636                     fragments.push('<tr>');
1637                     rowStarted = true;
1638                 }
1639
1640                 if (lf)
1641                     label = lf(label, s);
1642                 
1643                 fragments.push(
1644                     '<td class="legendColorBox"><div style="border:1px solid ' + options.legend.labelBoxBorderColor + ';padding:1px"><div style="width:4px;height:0;border:5px solid ' + s.color + ';overflow:hidden"></div></div></td>' +
1645                     '<td class="legendLabel">' + label + '</td>');
1646             }
1647             if (rowStarted)
1648                 fragments.push('</tr>');
1649             
1650             if (fragments.length == 0)
1651                 return;
1652
1653             var table = '<table style="font-size:smaller;color:' + options.grid.color + '">' + fragments.join("") + '</table>';
1654             if (options.legend.container != null)
1655                 $(options.legend.container).html(table);
1656             else {
1657                 var pos = "",
1658                     p = options.legend.position,
1659                     m = options.legend.margin;
1660                 if (m[0] == null)
1661                     m = [m, m];
1662                 if (p.charAt(0) == "n")
1663                     pos += 'top:' + (m[1] + plotOffset.top) + 'px;';
1664                 else if (p.charAt(0) == "s")
1665                     pos += 'bottom:' + (m[1] + plotOffset.bottom) + 'px;';
1666                 if (p.charAt(1) == "e")
1667                     pos += 'right:' + (m[0] + plotOffset.right) + 'px;';
1668                 else if (p.charAt(1) == "w")
1669                     pos += 'left:' + (m[0] + plotOffset.left) + 'px;';
1670                 var legend = $('<div class="legend">' + table.replace('style="', 'style="position:absolute;' + pos +';') + '</div>').appendTo(target);
1671                 if (options.legend.backgroundOpacity != 0.0) {
1672                     // put in the transparent background
1673                     // separately to avoid blended labels and
1674                     // label boxes
1675                     var c = options.legend.backgroundColor;
1676                     if (c == null) {
1677                         var tmp;
1678                         if (options.grid.backgroundColor && typeof options.grid.backgroundColor == "string")
1679                             tmp = options.grid.backgroundColor;
1680                         else
1681                             tmp = extractColor(legend);
1682                         c = parseColor(tmp).adjust(null, null, null, 1).toString();
1683                     }
1684                     var div = legend.children();
1685                     $('<div style="position:absolute;width:' + div.width() + 'px;height:' + div.height() + 'px;' + pos +'background-color:' + c + ';"> </div>').prependTo(legend).css('opacity', options.legend.backgroundOpacity);
1686                 }
1687             }
1688         }
1689
1690
1691         // interactive features
1692         
1693         var lastMousePos = { pageX: null, pageY: null },
1694             selection = {
1695                 first: { x: -1, y: -1}, second: { x: -1, y: -1},
1696                 show: false, active: false },
1697             crosshair = { pos: { x: -1, y: -1 } },
1698             highlights = [],
1699             clickIsMouseUp = false,
1700             redrawTimeout = null,
1701             hoverTimeout = null;
1702         
1703         // Returns the data item the mouse is over, or null if none is found
1704         function findNearbyItem(mouseX, mouseY, seriesFilter) {
1705             var maxDistance = options.grid.mouseActiveRadius,
1706                 lowestDistance = maxDistance * maxDistance + 1,
1707                 item = null, foundPoint = false, i, j;
1708
1709             for (var i = 0; i < series.length; ++i) {
1710                 if (!seriesFilter(series[i]))
1711                     continue;
1712                 
1713                 var s = series[i],
1714                     axisx = s.xaxis,
1715                     axisy = s.yaxis,
1716                     points = s.datapoints.points,
1717                     incr = s.datapoints.incr,
1718                     mx = axisx.c2p(mouseX), // precompute some stuff to make the loop faster
1719                     my = axisy.c2p(mouseY),
1720                     maxx = maxDistance / axisx.scale,
1721                     maxy = maxDistance / axisy.scale;
1722
1723                 if (s.lines.show || s.points.show) {
1724                     for (j = 0; j < points.length; j += incr) {
1725                         var x = points[j], y = points[j + 1];
1726                         if (x == null)
1727                             continue;
1728                         
1729                         // For points and lines, the cursor must be within a
1730                         // certain distance to the data point
1731                         if (x - mx > maxx || x - mx < -maxx ||
1732                             y - my > maxy || y - my < -maxy)
1733                             continue;
1734
1735                         // We have to calculate distances in pixels, not in
1736                         // data units, because the scales of the axes may be different
1737                         var dx = Math.abs(axisx.p2c(x) - mouseX),
1738                             dy = Math.abs(axisy.p2c(y) - mouseY),
1739                             dist = dx * dx + dy * dy; // no idea in taking sqrt
1740                         if (dist < lowestDistance) {
1741                             lowestDistance = dist;
1742                             item = [i, j / incr];
1743                         }
1744                     }
1745                 }
1746                     
1747                 if (s.bars.show && !item) { // no other point can be nearby
1748                     var barLeft = s.bars.align == "left" ? 0 : -s.bars.barWidth/2,
1749                         barRight = barLeft + s.bars.barWidth;
1750                     
1751                     for (j = 0; j < points.length; j += incr) {
1752                         var x = points[j], y = points[j + 1], b = points[j + 2];
1753                         if (x == null)
1754                             continue;
1755   
1756                         // for a bar graph, the cursor must be inside the bar
1757                         if (series[i].bars.horizontal ? 
1758                             (mx <= Math.max(b, x) && mx >= Math.min(b, x) && 
1759                              my >= y + barLeft && my <= y + barRight) :
1760                             (mx >= x + barLeft && mx <= x + barRight &&
1761                              my >= Math.min(b, y) && my <= Math.max(b, y)))
1762                                 item = [i, j / incr];
1763                     }
1764                 }
1765             }
1766
1767             if (item) {
1768                 i = item[0];
1769                 j = item[1];
1770                 
1771                 return { datapoint: series[i].data[j],
1772                          dataIndex: j,
1773                          series: series[i],
1774                          seriesIndex: i }
1775             }
1776             
1777             return null;
1778         }
1779
1780         function onMouseMove(ev) {
1781             // FIXME: temp. work-around until jQuery bug 4398 is fixed
1782             var e = ev || window.event;
1783             if (e.pageX == null && e.clientX != null) {
1784                 var de = document.documentElement, b = document.body;
1785                 lastMousePos.pageX = e.clientX + (de && de.scrollLeft || b.scrollLeft || 0) - (de.clientLeft || 0);
1786                 lastMousePos.pageY = e.clientY + (de && de.scrollTop || b.scrollTop || 0) - (de.clientTop || 0);
1787             }
1788             else {
1789                 lastMousePos.pageX = e.pageX;
1790                 lastMousePos.pageY = e.pageY;
1791             }
1792             
1793             if (options.grid.hoverable)
1794                 triggerClickHoverEvent("plothover", lastMousePos,
1795                                        function (s) { return s["hoverable"] != false; });
1796
1797             if (options.crosshair.mode != null) {
1798                 if (!selection.active) {
1799                     setPositionFromEvent(crosshair.pos, lastMousePos);
1800                     triggerRedrawOverlay();
1801                 }
1802                 else
1803                     crosshair.pos.x = -1; // hide the crosshair while selecting
1804             }
1805
1806             if (selection.active) {
1807                 target.trigger("plotselecting", [ selectionIsSane() ? getSelectionForEvent() : null ]);
1808
1809                 updateSelection(lastMousePos);
1810             }
1811         }
1812         
1813         function onMouseDown(e) {
1814             if (e.which != 1)  // only accept left-click
1815                 return;
1816             
1817             // cancel out any text selections
1818             document.body.focus();
1819
1820             // prevent text selection and drag in old-school browsers
1821             if (document.onselectstart !== undefined && workarounds.onselectstart == null) {
1822                 workarounds.onselectstart = document.onselectstart;
1823                 document.onselectstart = function () { return false; };
1824             }
1825             if (document.ondrag !== undefined && workarounds.ondrag == null) {
1826                 workarounds.ondrag = document.ondrag;
1827                 document.ondrag = function () { return false; };
1828             }
1829             
1830             setSelectionPos(selection.first, e);
1831                 
1832             lastMousePos.pageX = null;
1833             selection.active = true;
1834             $(document).one("mouseup", onSelectionMouseUp);
1835         }
1836
1837         function onMouseOut(ev) {
1838             if (options.crosshair.mode != null && crosshair.pos.x != -1) {
1839                 crosshair.pos.x = -1;
1840                 triggerRedrawOverlay();
1841             }
1842         }
1843         
1844         function onClick(e) {
1845             if (clickIsMouseUp) {
1846                 clickIsMouseUp = false;
1847                 return;
1848             }
1849
1850             triggerClickHoverEvent("plotclick", e,
1851                                    function (s) { return s["clickable"] != false; });
1852         }
1853
1854         /*
1855         function userPositionInCanvasSpace(pos) {
1856             return { x: parseInt(pos.x != null ? axes.xaxis.p2c(pos.x) : axes.x2axis.p2c(pos.x2)),
1857                      y: parseInt(pos.y != null ? axes.yaxis.p2c(pos.y) : axes.y2axis.p2c(pos.y2)) };
1858         }
1859         
1860         function positionInDivSpace(pos) {
1861             var cpos = userPositionInCanvasSpace(pos);
1862             return { x: cpos.x + plotOffset.left,
1863                      y: cpos.y + plotOffset.top };
1864         }*/
1865         
1866         // trigger click or hover event (they send the same parameters
1867         // so we share their code)
1868         function triggerClickHoverEvent(eventname, event, seriesFilter) {
1869             var offset = eventHolder.offset(),
1870                 pos = { pageX: event.pageX, pageY: event.pageY },
1871                 canvasX = event.pageX - offset.left - plotOffset.left,
1872                 canvasY = event.pageY - offset.top - plotOffset.top;
1873
1874             if (axes.xaxis.used)
1875                 pos.x = axes.xaxis.c2p(canvasX);
1876             if (axes.yaxis.used)
1877                 pos.y = axes.yaxis.c2p(canvasY);
1878             if (axes.x2axis.used)
1879                 pos.x2 = axes.x2axis.c2p(canvasX);
1880             if (axes.y2axis.used)
1881                 pos.y2 = axes.y2axis.c2p(canvasY);
1882
1883             var item = findNearbyItem(canvasX, canvasY, seriesFilter);
1884
1885             if (item) {
1886                 // fill in mouse pos for any listeners out there
1887                 item.pageX = parseInt(item.series.xaxis.p2c(item.datapoint[0]) + offset.left + plotOffset.left);
1888                 item.pageY = parseInt(item.series.yaxis.p2c(item.datapoint[1]) + offset.top + plotOffset.top);
1889             }
1890
1891             if (options.grid.autoHighlight) {
1892                 // clear auto-highlights
1893                 for (var i = 0; i < highlights.length; ++i) {
1894                     var h = highlights[i];
1895                     if (h.auto == eventname &&
1896                         !(item && h.series == item.series && h.point == item.datapoint))
1897                         unhighlight(h.series, h.point);
1898                 }
1899                 
1900                 if (item)
1901                     highlight(item.series, item.datapoint, eventname);
1902             }
1903             
1904             target.trigger(eventname, [ pos, item ]);
1905         }
1906
1907         function triggerRedrawOverlay() {
1908             if (!redrawTimeout)
1909                 redrawTimeout = setTimeout(redrawOverlay, 30);
1910         }
1911
1912         function redrawOverlay() {
1913             redrawTimeout = null;
1914
1915             // redraw highlights
1916             octx.save();
1917             octx.clearRect(0, 0, canvasWidth, canvasHeight);
1918             octx.translate(plotOffset.left, plotOffset.top);
1919             
1920             var i, hi;
1921             for (i = 0; i < highlights.length; ++i) {
1922                 hi = highlights[i];
1923
1924                 if (hi.series.bars.show)
1925                     drawBarHighlight(hi.series, hi.point);
1926                 else
1927                     drawPointHighlight(hi.series, hi.point);
1928             }
1929
1930             // redraw selection
1931             if (selection.show && selectionIsSane()) {
1932                 octx.strokeStyle = parseColor(options.selection.color).scale(null, null, null, 0.8).toString();
1933                 octx.lineWidth = 1;
1934                 ctx.lineJoin = "round";
1935                 octx.fillStyle = parseColor(options.selection.color).scale(null, null, null, 0.4).toString();
1936                 
1937                 var x = Math.min(selection.first.x, selection.second.x),
1938                     y = Math.min(selection.first.y, selection.second.y),
1939                     w = Math.abs(selection.second.x - selection.first.x),
1940                     h = Math.abs(selection.second.y - selection.first.y);
1941                 
1942                 octx.fillRect(x, y, w, h);
1943                 octx.strokeRect(x, y, w, h);
1944             }
1945
1946             // redraw crosshair
1947             var pos = crosshair.pos, mode = options.crosshair.mode;
1948             if (mode != null && pos.x != -1) {
1949                 octx.strokeStyle = parseColor(options.crosshair.color).scale(null, null, null, 0.8).toString();
1950                 octx.lineWidth = 1;
1951                 ctx.lineJoin = "round";
1952
1953                 octx.beginPath();
1954                 if (mode.indexOf("x") != -1) {
1955                     octx.moveTo(pos.x, 0);
1956                     octx.lineTo(pos.x, plotHeight);
1957                 }
1958                 if (mode.indexOf("y") != -1) {
1959                     octx.moveTo(0, pos.y);
1960                     octx.lineTo(plotWidth, pos.y);
1961                 }
1962                 octx.stroke();
1963                 
1964             }
1965             octx.restore();
1966         }
1967         
1968         function highlight(s, point, auto) {
1969             if (typeof s == "number")
1970                 s = series[s];
1971
1972             if (typeof point == "number")
1973                 point = s.data[point];
1974
1975             var i = indexOfHighlight(s, point);
1976             if (i == -1) {
1977                 highlights.push({ series: s, point: point, auto: auto });
1978
1979                 triggerRedrawOverlay();
1980             }
1981             else if (!auto)
1982                 highlights[i].auto = false;
1983         }
1984             
1985         function unhighlight(s, point) {
1986             if (typeof s == "number")
1987                 s = series[s];
1988
1989             if (typeof point == "number")
1990                 point = s.data[point];
1991
1992             var i = indexOfHighlight(s, point);
1993             if (i != -1) {
1994                 highlights.splice(i, 1);
1995
1996                 triggerRedrawOverlay();
1997             }
1998         }
1999         
2000         function indexOfHighlight(s, p) {
2001             for (var i = 0; i < highlights.length; ++i) {
2002                 var h = highlights[i];
2003                 if (h.series == s && h.point[0] == p[0]
2004                     && h.point[1] == p[1])
2005                     return i;
2006             }
2007             return -1;
2008         }
2009         
2010         function drawPointHighlight(series, point) {
2011             var x = point[0], y = point[1],
2012                 axisx = series.xaxis, axisy = series.yaxis;
2013             
2014             if (x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max)
2015                 return;
2016             
2017             var pointRadius = series.points.radius + series.points.lineWidth / 2;
2018             octx.lineWidth = pointRadius;
2019             octx.strokeStyle = parseColor(series.color).scale(1, 1, 1, 0.5).toString();
2020             var radius = 1.5 * pointRadius;
2021             octx.beginPath();
2022             octx.arc(axisx.p2c(x), axisy.p2c(y), radius, 0, 2 * Math.PI, true);
2023             octx.stroke();
2024         }
2025
2026         function drawBarHighlight(series, point) {
2027             octx.lineWidth = series.bars.lineWidth;
2028             octx.strokeStyle = parseColor(series.color).scale(1, 1, 1, 0.5).toString();
2029             var fillStyle = parseColor(series.color).scale(1, 1, 1, 0.5).toString();
2030             var barLeft = series.bars.align == "left" ? 0 : -series.bars.barWidth/2;
2031             drawBar(point[0], point[1], point[2] || 0, barLeft, barLeft + series.bars.barWidth,
2032                     0, function () { return fillStyle; }, series.xaxis, series.yaxis, octx, series.bars.horizontal);
2033         }
2034
2035         function setPositionFromEvent(pos, e) {
2036             var offset = eventHolder.offset();
2037             pos.x = clamp(0, e.pageX - offset.left - plotOffset.left, plotWidth);
2038             pos.y = clamp(0, e.pageY - offset.top - plotOffset.top, plotHeight);
2039         }
2040
2041         function setCrosshair(pos) {
2042             if (pos == null)
2043                 crosshair.pos.x = -1;
2044             else {
2045                 crosshair.pos.x = clamp(0, pos.x != null ? axes.xaxis.p2c(pos.x) : axes.x2axis.p2c(pos.x2), plotWidth);
2046                 crosshair.pos.y = clamp(0, pos.y != null ? axes.yaxis.p2c(pos.y) : axes.y2axis.p2c(pos.y2), plotHeight);
2047             }
2048             triggerRedrawOverlay();
2049         }
2050
2051         function getSelectionForEvent() {
2052             var x1 = Math.min(selection.first.x, selection.second.x),
2053                 x2 = Math.max(selection.first.x, selection.second.x),
2054                 y1 = Math.max(selection.first.y, selection.second.y),
2055                 y2 = Math.min(selection.first.y, selection.second.y);
2056
2057             var r = {};
2058             if (axes.xaxis.used)
2059                 r.xaxis = { from: axes.xaxis.c2p(x1), to: axes.xaxis.c2p(x2) };
2060             if (axes.x2axis.used)
2061                 r.x2axis = { from: axes.x2axis.c2p(x1), to: axes.x2axis.c2p(x2) };
2062             if (axes.yaxis.used)
2063                 r.yaxis = { from: axes.yaxis.c2p(y1), to: axes.yaxis.c2p(y2) };
2064             if (axes.y2axis.used)
2065                 r.y2axis = { from: axes.y2axis.c2p(y1), to: axes.y2axis.c2p(y2) };
2066             return r;
2067         }
2068         
2069         function triggerSelectedEvent() {
2070             var r = getSelectionForEvent();
2071             
2072             target.trigger("plotselected", [ r ]);
2073
2074             // backwards-compat stuff, to be removed in future
2075             if (axes.xaxis.used && axes.yaxis.used)
2076                 target.trigger("selected", [ { x1: r.xaxis.from, y1: r.yaxis.from, x2: r.xaxis.to, y2: r.yaxis.to } ]);
2077         }
2078         
2079         function onSelectionMouseUp(e) {
2080             // revert drag stuff for old-school browsers
2081             if (document.onselectstart !== undefined)
2082                 document.onselectstart = workarounds.onselectstart;
2083             if (document.ondrag !== undefined)
2084                 document.ondrag = workarounds.ondrag;
2085             
2086             // no more draggy-dee-drag
2087             selection.active = false;
2088             updateSelection(e);
2089             
2090             if (selectionIsSane()) {
2091                 triggerSelectedEvent();
2092                 clickIsMouseUp = true;
2093             }
2094             else {
2095                 // this counts as a clear
2096                 target.trigger("plotunselected", [ ]);
2097                 target.trigger("plotselecting", [ null ]);
2098             }
2099             
2100             return false;
2101         }
2102
2103         function setSelectionPos(pos, e) {
2104             setPositionFromEvent(pos, e);
2105             
2106             if (options.selection.mode == "y") {
2107                 if (pos == selection.first)
2108                     pos.x = 0;
2109                 else
2110                     pos.x = plotWidth;
2111             }
2112
2113             if (options.selection.mode == "x") {
2114                 if (pos == selection.first)
2115                     pos.y = 0;
2116                 else
2117                     pos.y = plotHeight;
2118             }
2119         }
2120
2121         function updateSelection(pos) {
2122             if (pos.pageX == null)
2123                 return;
2124
2125             setSelectionPos(selection.second, pos);
2126             if (selectionIsSane()) {
2127                 selection.show = true;
2128                 triggerRedrawOverlay();
2129             }
2130             else
2131                 clearSelection(true);
2132         }
2133
2134         function clearSelection(preventEvent) {
2135             if (selection.show) {
2136                 selection.show = false;
2137                 triggerRedrawOverlay();
2138                 if (!preventEvent)
2139                     target.trigger("plotunselected", [ ]);
2140             }
2141         }
2142
2143         function setSelection(ranges, preventEvent) {
2144             var range;
2145             
2146             if (options.selection.mode == "y") {
2147                 selection.first.x = 0;
2148                 selection.second.x = plotWidth;
2149             }
2150             else {
2151                 range = extractRange(ranges, "x");
2152                 
2153                 selection.first.x = range.axis.p2c(range.from);
2154                 selection.second.x = range.axis.p2c(range.to);
2155             }
2156             
2157             if (options.selection.mode == "x") {
2158                 selection.first.y = 0;
2159                 selection.second.y = plotHeight;
2160             }
2161             else {
2162                 range = extractRange(ranges, "y");
2163                 
2164                 selection.first.y = range.axis.p2c(range.from);
2165                 selection.second.y = range.axis.p2c(range.to);
2166             }
2167
2168             selection.show = true;
2169             triggerRedrawOverlay();
2170             if (!preventEvent)
2171                 triggerSelectedEvent();
2172         }
2173         
2174         function selectionIsSane() {
2175             var minSize = 5;
2176             return Math.abs(selection.second.x - selection.first.x) >= minSize &&
2177                 Math.abs(selection.second.y - selection.first.y) >= minSize;
2178         }
2179         
2180         function getColorOrGradient(spec, bottom, top, defaultColor) {
2181             if (typeof spec == "string")
2182                 return spec;
2183             else {
2184                 // assume this is a gradient spec; IE currently only
2185                 // supports a simple vertical gradient properly, so that's
2186                 // what we support too
2187                 var gradient = ctx.createLinearGradient(0, top, 0, bottom);
2188                 
2189                 for (var i = 0, l = spec.colors.length; i < l; ++i) {
2190                     var c = spec.colors[i];
2191                     gradient.addColorStop(i / (l - 1), typeof c == "string" ? c : parseColor(defaultColor).scale(c.brightness, c.brightness, c.brightness, c.opacity));
2192                 }
2193                 
2194                 return gradient;
2195             }
2196         }
2197     }
2198     
2199     $.plot = function(target, data, options) {
2200         var plot = new Plot(target, data, options);
2201         /*var t0 = new Date();     
2202         var t1 = new Date();
2203         var tstr = "time used (msecs): " + (t1.getTime() - t0.getTime())
2204         if (window.console)
2205             console.log(tstr);
2206         else
2207             alert(tstr);*/
2208         return plot;
2209     };
2210
2211     // returns a string with the date d formatted according to fmt
2212     $.plot.formatDate = function(d, fmt, monthNames) {
2213         var leftPad = function(n) {
2214             n = "" + n;
2215             return n.length == 1 ? "0" + n : n;
2216         };
2217         
2218         var r = [];
2219         var escape = false;
2220         if (monthNames == null)
2221             monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
2222         for (var i = 0; i < fmt.length; ++i) {
2223             var c = fmt.charAt(i);
2224             
2225             if (escape) {
2226                 switch (c) {
2227                 case 'h': c = "" + d.getUTCHours(); break;
2228                 case 'H': c = leftPad(d.getUTCHours()); break;
2229                 case 'M': c = leftPad(d.getUTCMinutes()); break;
2230                 case 'S': c = leftPad(d.getUTCSeconds()); break;
2231                 case 'd': c = "" + d.getUTCDate(); break;
2232                 case 'm': c = "" + (d.getUTCMonth() + 1); break;
2233                 case 'y': c = "" + d.getUTCFullYear(); break;
2234                 case 'b': c = "" + monthNames[d.getUTCMonth()]; break;
2235                 }
2236                 r.push(c);
2237                 escape = false;
2238             }
2239             else {
2240                 if (c == "%")
2241                     escape = true;
2242                 else
2243                     r.push(c);
2244             }
2245         }
2246         return r.join("");
2247     };
2248     
2249     // round to nearby lower multiple of base
2250     function floorInBase(n, base) {
2251         return base * Math.floor(n / base);
2252     }
2253     
2254     function clamp(min, value, max) {
2255         if (value < min)
2256             return min;
2257         else if (value > max)
2258             return max;
2259         else
2260             return value;
2261     }
2262     
2263     // color helpers, inspiration from the jquery color animation
2264     // plugin by John Resig
2265     function Color (r, g, b, a) {
2266        
2267         var rgba = ['r','g','b','a'];
2268         var x = 4; //rgba.length
2269        
2270         while (-1<--x) {
2271             this[rgba[x]] = arguments[x] || ((x==3) ? 1.0 : 0);
2272         }
2273        
2274         this.toString = function() {
2275             if (this.a >= 1.0) {
2276                 return "rgb("+[this.r,this.g,this.b].join(",")+")";
2277             } else {
2278                 return "rgba("+[this.r,this.g,this.b,this.a].join(",")+")";
2279             }
2280         };
2281
2282         this.scale = function(rf, gf, bf, af) {
2283             x = 4; //rgba.length
2284             while (-1<--x) {
2285                 if (arguments[x] != null)
2286                     this[rgba[x]] *= arguments[x];
2287             }
2288             return this.normalize();
2289         };
2290
2291         this.adjust = function(rd, gd, bd, ad) {
2292             x = 4; //rgba.length
2293             while (-1<--x) {
2294                 if (arguments[x] != null)
2295                     this[rgba[x]] += arguments[x];
2296             }
2297             return this.normalize();
2298         };
2299
2300         this.clone = function() {
2301             return new Color(this.r, this.b, this.g, this.a);
2302         };
2303
2304         var limit = function(val,minVal,maxVal) {
2305             return Math.max(Math.min(val, maxVal), minVal);
2306         };
2307
2308         this.normalize = function() {
2309             this.r = clamp(0, parseInt(this.r), 255);
2310             this.g = clamp(0, parseInt(this.g), 255);
2311             this.b = clamp(0, parseInt(this.b), 255);
2312             this.a = clamp(0, this.a, 1);
2313             return this;
2314         };
2315
2316         this.normalize();
2317     }
2318     
2319     var lookupColors = {
2320         aqua:[0,255,255],
2321         azure:[240,255,255],
2322         beige:[245,245,220],
2323         black:[0,0,0],
2324         blue:[0,0,255],
2325         brown:[165,42,42],
2326         cyan:[0,255,255],
2327         darkblue:[0,0,139],
2328         darkcyan:[0,139,139],
2329         darkgrey:[169,169,169],
2330         darkgreen:[0,100,0],
2331         darkkhaki:[189,183,107],
2332         darkmagenta:[139,0,139],
2333         darkolivegreen:[85,107,47],
2334         darkorange:[255,140,0],
2335         darkorchid:[153,50,204],
2336         darkred:[139,0,0],
2337         darksalmon:[233,150,122],
2338         darkviolet:[148,0,211],
2339         fuchsia:[255,0,255],
2340         gold:[255,215,0],
2341         green:[0,128,0],
2342         indigo:[75,0,130],
2343         khaki:[240,230,140],
2344         lightblue:[173,216,230],
2345         lightcyan:[224,255,255],
2346         lightgreen:[144,238,144],
2347         lightgrey:[211,211,211],
2348         lightpink:[255,182,193],
2349         lightyellow:[255,255,224],
2350         lime:[0,255,0],
2351         magenta:[255,0,255],
2352         maroon:[128,0,0],
2353         navy:[0,0,128],
2354         olive:[128,128,0],
2355         orange:[255,165,0],
2356         pink:[255,192,203],
2357         purple:[128,0,128],
2358         violet:[128,0,128],
2359         red:[255,0,0],
2360         silver:[192,192,192],
2361         white:[255,255,255],
2362         yellow:[255,255,0]
2363     };    
2364
2365     function extractColor(element) {
2366         var color, elem = element;
2367         do {
2368             color = elem.css("background-color").toLowerCase();
2369             // keep going until we find an element that has color, or
2370             // we hit the body
2371             if (color != '' && color != 'transparent')
2372                 break;
2373             elem = elem.parent();
2374         } while (!$.nodeName(elem.get(0), "body"));
2375
2376         // catch Safari's way of signalling transparent
2377         if (color == "rgba(0, 0, 0, 0)")
2378             return "transparent";
2379         
2380         return color;
2381     }
2382     
2383     // parse string, returns Color
2384     function parseColor(str) {
2385         var result;
2386
2387         // Look for rgb(num,num,num)
2388         if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(str))
2389             return new Color(parseInt(result[1], 10), parseInt(result[2], 10), parseInt(result[3], 10));
2390         
2391         // Look for rgba(num,num,num,num)
2392         if (result = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str))
2393             return new Color(parseInt(result[1], 10), parseInt(result[2], 10), parseInt(result[3], 10), parseFloat(result[4]));
2394             
2395         // Look for rgb(num%,num%,num%)
2396         if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(str))
2397             return new Color(parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55);
2398
2399         // Look for rgba(num%,num%,num%,num)
2400         if (result = /rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str))
2401             return new Color(parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55, parseFloat(result[4]));
2402         
2403         // Look for #a0b1c2
2404         if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(str))
2405             return new Color(parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16));
2406
2407         // Look for #fff
2408         if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(str))
2409             return new Color(parseInt(result[1]+result[1], 16), parseInt(result[2]+result[2], 16), parseInt(result[3]+result[3], 16));
2410
2411         // Otherwise, we're most likely dealing with a named color
2412         var name = $.trim(str).toLowerCase();
2413         if (name == "transparent")
2414             return new Color(255, 255, 255, 0);
2415         else {
2416             result = lookupColors[name];
2417             return new Color(result[0], result[1], result[2]);
2418         }
2419     }
2420         
2421 })(jQuery);