1 /* Javascript plotting library for jQuery, v. 0.5.
 
   3  * Released under the MIT license by IOLA, December 2007.
 
   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" }
 
  16                 // the color theme used for graphs
 
  17                 colors: ["#edc240", "#afd8f8", "#cb4b4b", "#4da74d", "#9440ed"],
 
  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
 
  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
 
  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
 
  58                     lineWidth: 2, // in pixels
 
  63                     // we don't put in show: false so we can see
 
  64                     // whether lines were actively disabled 
 
  65                     lineWidth: 2, // in pixels
 
  72                     lineWidth: 2, // in pixels
 
  73                     barWidth: 1, // in units of the x axis
 
  76                     align: "left", // or "center" 
 
  77                     horizontal: false // when horizontal, left is now top
 
  79                 threshold: null, // or { below: number, color: color spec}
 
  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",
 
  93                     autoHighlight: true, // highlight in case mouse is near
 
  94                     mouseActiveRadius: 10 // how far the mouse can be away to activate an item
 
  97                     mode: null, // one of null, "x", "y" or "xy"
 
 101                     mode: null, // one of null, "x", "y" or "xy",
 
 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,
 
 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
 
 118         this.setData = setData;
 
 119         this.setupGrid = setupGrid;
 
 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;
 
 133         parseOptions(options_);
 
 140         function setData(d) {
 
 141             series = parseData(d);
 
 143             fillInSeriesOptions();
 
 147         function parseData(d) {
 
 149             for (var i = 0; i < d.length; ++i) {
 
 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;
 
 180         function fillInSeriesOptions() {
 
 183             // collect what we already got of colors
 
 184             var neededColors = series.length,
 
 187             for (i = 0; i < series.length; ++i) {
 
 188                 var sc = series[i].color;
 
 191                     if (typeof sc == "number")
 
 192                         assignedColors.push(sc);
 
 194                         usedColors.push(parseColor(series[i].color));
 
 198             // we might need to generate more colors if higher indices
 
 200             for (i = 0; i < assignedColors.length; ++i) {
 
 201                 neededColors = Math.max(neededColors, assignedColors[i] + 1);
 
 204             // produce colors as needed
 
 205             var colors = [], variation = 0;
 
 207             while (colors.length < neededColors) {
 
 209                 if (options.colors.length == i) // check degenerate case
 
 210                     c = new Color(100, 100, 100);
 
 212                     c = parseColor(options.colors[i]);
 
 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);
 
 219                 // FIXME: if we're getting to close to something else,
 
 220                 // we should probably skip this one
 
 224                 if (i >= options.colors.length) {
 
 230             // fill in the options
 
 232             for (i = 0; i < series.length; ++i) {
 
 236                 if (s.color == null) {
 
 237                     s.color = colors[colori].toString();
 
 240                 else if (typeof s.color == "number")
 
 241                     s.color = colors[s.color].toString();
 
 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);
 
 248                 // turn on lines automatically in case nothing is set
 
 249                 if (s.lines.show == null && !s.bars.show && !s.points.show)
 
 251                 if (s.shadowSize == null)
 
 252                     s.shadowSize = options.shadowSize;
 
 255                     s.xaxis = axes.xaxis;
 
 258                     s.xaxis = axes.xaxis;
 
 259                 else if (s.xaxis == 2)
 
 260                     s.xaxis = axes.x2axis;
 
 263                     s.yaxis = axes.yaxis;
 
 266                     s.yaxis = axes.yaxis;
 
 267                 else if (s.yaxis == 2)
 
 268                     s.yaxis = axes.y2axis;
 
 271                     s.threshold = options.threshold;
 
 276         function processData() {
 
 277             var topSentry = Number.POSITIVE_INFINITY,
 
 278                 bottomSentry = Number.NEGATIVE_INFINITY,
 
 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;
 
 289             for (i = 0; i < series.length; ++i) {
 
 291                 s.datapoints = { points: [], incr: 2 };
 
 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 = [];
 
 300                 // determine the increment
 
 302                     s.datapoints.incr = 3;
 
 303                     format.push({ d: 0 });
 
 307                 // examine data to find out how to copy
 
 308                 for (j = 0; j < data.length; ++j) {
 
 312                 axisx.used = axisy.used = true;
 
 313                 incr = s.datapoints.incr;
 
 315                 for (j = k = 0; j < data.length; ++j, k += incr) {
 
 320                     if (data[j] != null) {
 
 326                     if (x != null && !isNaN(x = +x)) {
 
 335                     if (y != null && !isNaN(y = +y)) {
 
 344                     if (x == null || y == null)
 
 345                         x = y = null; // make sure everything is cleared
 
 347                     for (m = 2; m < incr; ++m)
 
 348                         points[k + m] = p[m] == null ? format[m-2].d : p[m];
 
 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) {
 
 359                         ymax += delta + s.bars.barWidth;
 
 363                         xmax += delta + s.bars.barWidth;
 
 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);
 
 374                 if (s.lines.show && s.lines.steps) {
 
 376                     // copy, inserting extra points to make steps
 
 377                     for (j = k = 0; j < points.length; j += incr, k += incr) {
 
 381                             && points[j - incr] != null
 
 383                             && points[j - incr + 1] != y) {
 
 385                             p[k + 1] = points[j - incr + 1];
 
 392                     s.datapoints.linespoints = p;
 
 395                 // possibly split data points because of threshold
 
 397                     var orig = $.extend({}, s), thresholded = $.extend({}, s);
 
 398                     orig.datapoints = { points: [], incr: incr };
 
 399                     thresholded.datapoints = { points: [], incr: incr };
 
 401                     thresholded.color = s.threshold.color;
 
 403                     var below = s.threshold.below,
 
 404                         origpoints = orig.datapoints.points,
 
 405                         threspoints = thresholded.datapoints.points;
 
 408                     for (j = 0; j < points.length; j += incr) {
 
 421                     // possibly split lines
 
 423                         var lp = s.datapoints.linespoints || points;
 
 429                         for (j = 0; j < lp.length; j += incr) {
 
 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;
 
 446                                 p.push(null); // start new segment
 
 456                         orig.datapoints.linespoints = origpoints
 
 457                         thresholded.datapoints.linespoints = threspoints;
 
 460                     s.subseries = [orig, thresholded];
 
 465         function constructCanvas() {
 
 466             function makeCanvas(width, height) {
 
 467                 var c = document.createElement('canvas');
 
 470                 if ($.browser.msie) // excanvas hack
 
 471                     c = window.G_vmlCanvasManager.initElement(c);
 
 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
 
 481             if (canvasWidth <= 0 || canvasHeight <= 0)
 
 482                 throw "Invalid dimensions for plot, width = " + canvasWidth + ", height = " + canvasHeight;
 
 485             canvas = $(makeCanvas(canvasWidth, canvasHeight)).appendTo(target).get(0);
 
 486             ctx = canvas.getContext("2d");
 
 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");
 
 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]);
 
 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;
 
 504                 if (options.selection.mode != null)
 
 505                     eventHolder.mousedown(onMouseDown);
 
 508             if (options.crosshair.mode != null)
 
 509                 eventHolder.mouseout(onMouseOut);
 
 511             if (options.grid.clickable)
 
 512                 eventHolder.click(onClick);
 
 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; };
 
 528                     axis.p2c = function (p) { return (axis.max - p) * axis.scale; };
 
 529                     axis.c2p = function (p) { return axis.max - p / axis.scale; };
 
 533             for (var axis in axes)
 
 534                 setupAxis(axes[axis], options[axis]);
 
 541         function setRange(axis, axisOptions) {
 
 542             var min = axisOptions.min != null ? +axisOptions.min : axis.datamin,
 
 543                 max = axisOptions.max != null ? +axisOptions.max : axis.datamax;
 
 546             if (min == Number.POSITIVE_INFINITY)
 
 548             if (max == Number.NEGATIVE_INFINITY)
 
 551             if (max - min == 0.0) {
 
 553                 var widen = max == 0 ? 1 : 0.01;
 
 555                 if (axisOptions.min == null)
 
 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)
 
 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
 
 570                         if (min < 0 && axis.datamin >= 0)
 
 573                     if (axisOptions.max == null) {
 
 574                         max += (max - min) * margin;
 
 575                         if (max > 0 && axis.datamax <= 0)
 
 584         function prepareTickGeneration(axis, axisOptions) {
 
 585             // estimate number of ticks
 
 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;
 
 592                 noTicks = canvasHeight / 60;
 
 594             var delta = (axis.max - axis.min) / noTicks;
 
 595             var size, generator, unit, formatter, i, magn, norm;
 
 597             if (axisOptions.mode == "time") {
 
 598                 // pretty handling of time
 
 600                 // map of app. size of time units in milliseconds
 
 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
 
 611                 // the allowed tick sizes, after 1 year we use
 
 612                 // an integer algorithm
 
 614                     [1, "second"], [2, "second"], [5, "second"], [10, "second"],
 
 616                     [1, "minute"], [2, "minute"], [5, "minute"], [10, "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"],
 
 627                 if (axisOptions.minTickSize != null) {
 
 628                     if (typeof axisOptions.tickSize == "number")
 
 629                         minSize = axisOptions.tickSize;
 
 631                         minSize = axisOptions.minTickSize[0] * timeUnitSize[axisOptions.minTickSize[1]];
 
 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)
 
 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;
 
 658                 if (axisOptions.tickSize) {
 
 659                     size = axisOptions.tickSize[0];
 
 660                     unit = axisOptions.tickSize[1];
 
 663                 generator = function(axis) {
 
 665                         tickSize = axis.tickSize[0], unit = axis.tickSize[1],
 
 666                         d = new Date(axis.min);
 
 668                     var step = tickSize * timeUnitSize[unit];
 
 670                     if (unit == "second")
 
 671                         d.setUTCSeconds(floorInBase(d.getUTCSeconds(), tickSize));
 
 672                     if (unit == "minute")
 
 673                         d.setUTCMinutes(floorInBase(d.getUTCMinutes(), tickSize));
 
 675                         d.setUTCHours(floorInBase(d.getUTCHours(), tickSize));
 
 677                         d.setUTCMonth(floorInBase(d.getUTCMonth(), tickSize));
 
 679                         d.setUTCFullYear(floorInBase(d.getUTCFullYear(), tickSize));
 
 681                     // reset smaller components
 
 682                     d.setUTCMilliseconds(0);
 
 683                     if (step >= timeUnitSize.minute)
 
 685                     if (step >= timeUnitSize.hour)
 
 687                     if (step >= timeUnitSize.day)
 
 689                     if (step >= timeUnitSize.day * 4)
 
 691                     if (step >= timeUnitSize.year)
 
 695                     var carry = 0, v = Number.NaN, prev;
 
 699                         ticks.push({ v: v, label: axis.tickFormatter(v, axis) });
 
 700                         if (unit == "month") {
 
 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
 
 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();
 
 714                                 d.setUTCMonth(d.getUTCMonth() + tickSize);
 
 716                         else if (unit == "year") {
 
 717                             d.setUTCFullYear(d.getUTCFullYear() + tickSize);
 
 721                     } while (v < axis.max && v != prev);
 
 726                 formatter = function (v, axis) {
 
 729                     // first check global format
 
 730                     if (axisOptions.timeformat != null)
 
 731                         return $.plot.formatDate(d, axisOptions.timeformat, axisOptions.monthNames);
 
 733                     var t = axis.tickSize[0] * timeUnitSize[axis.tickSize[1]];
 
 734                     var span = axis.max - axis.min;
 
 736                     if (t < timeUnitSize.minute)
 
 738                     else if (t < timeUnitSize.day) {
 
 739                         if (span < 2 * timeUnitSize.day)
 
 744                     else if (t < timeUnitSize.month)
 
 746                     else if (t < timeUnitSize.year) {
 
 747                         if (span < timeUnitSize.year)
 
 755                     return $.plot.formatDate(d, fmt, axisOptions.monthNames);
 
 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)
 
 765                 magn = Math.pow(10, -dec);
 
 766                 norm = delta / magn; // norm is between 1.0 and 10.0
 
 772                     // special case for 2.5, requires an extra decimal
 
 773                     if (norm > 2.25 && (maxDec == null || dec + 1 <= maxDec)) {
 
 785                 if (axisOptions.minTickSize != null && size < axisOptions.minTickSize)
 
 786                     size = axisOptions.minTickSize;
 
 788                 if (axisOptions.tickSize != null)
 
 789                     size = axisOptions.tickSize;
 
 791                 axis.tickDecimals = Math.max(0, (maxDec != null) ? maxDec : dec);
 
 793                 generator = function (axis) {
 
 796                     // spew out all possible ticks
 
 797                     var start = floorInBase(axis.min, axis.tickSize),
 
 798                         i = 0, v = Number.NaN, prev;
 
 801                         v = start + i * axis.tickSize;
 
 802                         ticks.push({ v: v, label: axis.tickFormatter(v, axis) });
 
 804                     } while (v < axis.max && v != prev);
 
 808                 formatter = function (v, axis) {
 
 809                     return v.toFixed(axis.tickDecimals);
 
 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); };
 
 818                 axis.tickFormatter = formatter;
 
 819             if (axisOptions.labelWidth != null)
 
 820                 axis.labelWidth = axisOptions.labelWidth;
 
 821             if (axisOptions.labelHeight != null)
 
 822                 axis.labelHeight = axisOptions.labelHeight;
 
 825         function setTicks(axis, axisOptions) {
 
 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);
 
 837             else if (axisOptions.ticks) {
 
 838                 var ticks = axisOptions.ticks;
 
 840                 if ($.isFunction(ticks))
 
 841                     // generate the ticks
 
 842                     ticks = ticks({ min: axis.min, max: axis.max });
 
 844                 // clean up the user-supplied ticks, copy them over
 
 846                 for (i = 0; i < ticks.length; ++i) {
 
 849                     if (typeof t == "object") {
 
 857                         label = axis.tickFormatter(v, axis);
 
 858                     axis.ticks[i] = { v: v, label: label };
 
 862             if (axisOptions.autoscaleMargin != null && axis.ticks.length > 0) {
 
 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);
 
 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;
 
 880                 // measure x label heights
 
 881                 if (axis.labelHeight == null) {
 
 883                     for (i = 0; i < axis.ticks.length; ++i) {
 
 884                         l = axis.ticks[i].label;
 
 886                             labels.push('<div class="tickLabel" style="float:left;width:' + axis.labelWidth + 'px">' + l + '</div>');
 
 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();
 
 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;
 
 906                             labels.push('<div class="tickLabel">' + l + '</div>');
 
 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();
 
 919                     if (axis.labelWidth == null)
 
 921                     if (axis.labelHeight == null)
 
 922                         axis.labelHeight = 0;
 
 926             measureXLabels(axes.xaxis);
 
 927             measureYLabels(axes.yaxis);
 
 928             measureXLabels(axes.x2axis);
 
 929             measureYLabels(axes.y2axis);
 
 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));
 
 937             plotOffset.left = plotOffset.right = plotOffset.top = plotOffset.bottom = maxOutset;
 
 939             var margin = options.grid.labelMargin + options.grid.borderWidth;
 
 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);
 
 946             if (axes.x2axis.labelHeight > 0)
 
 947                 plotOffset.top = Math.max(maxOutset, axes.x2axis.labelHeight + margin);
 
 949             if (axes.y2axis.labelWidth > 0)
 
 950                 plotOffset.right = Math.max(maxOutset, axes.y2axis.labelWidth + margin);
 
 952             plotWidth = canvasWidth - plotOffset.left - plotOffset.right;
 
 953             plotHeight = canvasHeight - plotOffset.bottom - plotOffset.top;
 
 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);
 
 964             for (var i = 0; i < series.length; ++i) {
 
 967                     for (var j = 0; j < s.subseries.length; ++j)
 
 968                         drawSeries(s.subseries[j]);
 
 974         function extractRange(ranges, coord) {
 
 975             var firstAxis = coord + "axis",
 
 976                 secondaryAxis = coord + "2axis",
 
 977                 axis, from, to, reverse;
 
 979             if (ranges[firstAxis]) {
 
 980                 axis = axes[firstAxis];
 
 981                 from = ranges[firstAxis].from;
 
 982                 to = ranges[firstAxis].to;
 
 984             else if (ranges[secondaryAxis]) {
 
 985                 axis = axes[secondaryAxis];
 
 986                 from = ranges[secondaryAxis].from;
 
 987                 to = ranges[secondaryAxis].to;
 
 990                 // backwards-compat stuff - to be removed in future
 
 991                 axis = axes[firstAxis];
 
 992                 from = ranges[coord + "1"];
 
 993                 to = ranges[coord + "2"];
 
 996             // auto-reverse as an added bonus
 
 997             if (from != null && to != null && from > to)
 
 998                 return { from: to, to: from, axis: axis };
 
1000             return { from: from, to: to, axis: axis };
 
1003         function drawGrid() {
 
1007             ctx.clearRect(0, 0, canvasWidth, canvasHeight);
 
1008             ctx.translate(plotOffset.left, plotOffset.top);
 
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);
 
1017             var markings = options.grid.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 });
 
1023                 for (i = 0; i < markings.length; ++i) {
 
1024                     var m = markings[i],
 
1025                         xrange = extractRange(m, "x"),
 
1026                         yrange = extractRange(m, "y");
 
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;
 
1039                     if (xrange.to < xrange.axis.min || xrange.from > xrange.axis.max ||
 
1040                         yrange.to < yrange.axis.min || yrange.from > yrange.axis.max)
 
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);
 
1048                     if (xrange.from == xrange.to && yrange.from == yrange.to)
 
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);
 
1057                     if (xrange.from == xrange.to || yrange.from == yrange.to) {
 
1059                         ctx.strokeStyle = m.color || options.grid.markingsColor;
 
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);
 
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);
 
1078             // draw the inner grid
 
1080             ctx.strokeStyle = options.grid.tickColor;
 
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
 
1088                 ctx.moveTo(Math.floor(axis.p2c(v)) + ctx.lineWidth/2, 0);
 
1089                 ctx.lineTo(Math.floor(axis.p2c(v)) + ctx.lineWidth/2, plotHeight);
 
1093             for (i = 0; i < axis.ticks.length; ++i) {
 
1094                 v = axis.ticks[i].v;
 
1095                 if (v <= axis.min || v >= axis.max)
 
1098                 ctx.moveTo(0, Math.floor(axis.p2c(v)) + ctx.lineWidth/2);
 
1099                 ctx.lineTo(plotWidth, Math.floor(axis.p2c(v)) + ctx.lineWidth/2);
 
1103             for (i = 0; i < axis.ticks.length; ++i) {
 
1104                 v = axis.ticks[i].v;
 
1105                 if (v <= axis.min || v >= axis.max)
 
1108                 ctx.moveTo(Math.floor(axis.p2c(v)) + ctx.lineWidth/2, -5);
 
1109                 ctx.lineTo(Math.floor(axis.p2c(v)) + ctx.lineWidth/2, 5);
 
1113             for (i = 0; i < axis.ticks.length; ++i) {
 
1114                 v = axis.ticks[i].v;
 
1115                 if (v <= axis.min || v >= axis.max)
 
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);
 
1124             if (options.grid.borderWidth) {
 
1126                 var bw = options.grid.borderWidth;
 
1128                 ctx.strokeStyle = options.grid.borderColor;
 
1129                 ctx.strokeRect(-bw/2, -bw/2, plotWidth + bw, plotHeight + bw);
 
1135         function insertLabels() {
 
1136             target.find(".tickLabels").remove();
 
1138             var html = ['<div class="tickLabels" style="font-size:smaller;color:' + options.grid.color + '">'];
 
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)
 
1145                     html.push(labelGenerator(tick, axis));
 
1149             var margin = options.grid.labelMargin + options.grid.borderWidth;
 
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>";
 
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>";
 
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>";
 
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>";
 
1168             html.push('</div>');
 
1170             target.append(html.join(""));
 
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);
 
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;
 
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];
 
1193                     if (x1 == null || x2 == null)
 
1197                     if (y1 <= y2 && y1 < axisy.min) {
 
1199                             continue;   // line segment is outside
 
1200                         // compute new intersection point
 
1201                         x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
 
1204                     else if (y2 <= y1 && y2 < axisy.min) {
 
1207                         x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
 
1212                     if (y1 >= y2 && y1 > axisy.max) {
 
1215                         x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
 
1218                     else if (y2 >= y1 && y2 > axisy.max) {
 
1221                         x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
 
1226                     if (x1 <= x2 && x1 < axisx.min) {
 
1229                         y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
 
1232                     else if (x2 <= x1 && x2 < axisx.min) {
 
1235                         y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
 
1240                     if (x1 >= x2 && x1 > axisx.max) {
 
1243                         y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
 
1246                     else if (x2 >= x1 && x2 > axisx.max) {
 
1249                         y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
 
1253                     if (x1 != prevx || y1 != prevy)
 
1254                         ctx.moveTo(axisx.p2c(x1) + xoffset, axisy.p2c(y1) + yoffset);
 
1258                     ctx.lineTo(axisx.p2c(x2) + xoffset, axisy.p2c(y2) + yoffset);
 
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;
 
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];
 
1273                     if (areaOpen && x1 != null && x2 == null) {
 
1275                         ctx.lineTo(axisx.p2c(lastX), axisy.p2c(bottom));
 
1281                     if (x1 == null || x2 == null)
 
1287                     if (x1 <= x2 && x1 < axisx.min) {
 
1290                         y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
 
1293                     else if (x2 <= x1 && x2 < axisx.min) {
 
1296                         y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
 
1301                     if (x1 >= x2 && x1 > axisx.max) {
 
1304                         y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
 
1307                     else if (x2 >= x1 && x2 > axisx.max) {
 
1310                         y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
 
1317                         ctx.moveTo(axisx.p2c(x1), axisy.p2c(bottom));
 
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));
 
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));
 
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;
 
1340                     // and clip the y values, without shortcutting
 
1343                     if (y1 <= y2 && y1 < axisy.min && y2 >= axisy.min) {
 
1344                         x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
 
1347                     else if (y2 <= y1 && y2 < axisy.min && y1 >= axisy.min) {
 
1348                         x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
 
1353                     if (y1 >= y2 && y1 > axisy.max && y2 <= axisy.max) {
 
1354                         x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
 
1357                     else if (y2 >= y1 && y2 > axisy.max && y1 <= axisy.max) {
 
1358                         x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
 
1363                     // if the x value was changed we got a rectangle
 
1366                         if (y1 <= axisy.min)
 
1371                         ctx.lineTo(axisx.p2c(x1old), axisy.p2c(top));
 
1372                         ctx.lineTo(axisx.p2c(x1), axisy.p2c(top));
 
1375                     // fill the triangles
 
1376                     ctx.lineTo(axisx.p2c(x1), axisy.p2c(y1));
 
1377                     ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2));
 
1379                     // fill the other rectangle if it's there
 
1381                         if (y2 <= axisy.min)
 
1386                         ctx.lineTo(axisx.p2c(x2), axisy.p2c(top));
 
1387                         ctx.lineTo(axisx.p2c(x2old), axisy.p2c(top));
 
1390                     lastX = Math.max(x2, x2old);
 
1394                     ctx.lineTo(axisx.p2c(lastX), axisy.p2c(bottom));
 
1400             ctx.translate(plotOffset.left, plotOffset.top);
 
1401             ctx.lineJoin = "round";
 
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
 
1409                 ctx.strokeStyle = "rgba(0,0,0,0.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);
 
1417             ctx.strokeStyle = series.color;
 
1418             var fillStyle = getFillStyle(series.lines, series.color, 0, plotHeight);
 
1420                 ctx.fillStyle = fillStyle;
 
1421                 plotLineArea(series.datapoints, series.xaxis, series.yaxis);
 
1425                 plotLine(series.datapoints, 0, 0, series.xaxis, series.yaxis);
 
1429         function drawSeriesPoints(series) {
 
1430             function plotPoints(datapoints, radius, fillStyle, offset, circumference, axisx, axisy) {
 
1431                 var points = datapoints.points, incr = datapoints.incr;
 
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)
 
1439                     ctx.arc(axisx.p2c(x), axisy.p2c(y) + offset, radius, 0, circumference, true);
 
1441                         ctx.fillStyle = fillStyle;
 
1449             ctx.translate(plotOffset.left, plotOffset.top);
 
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
 
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);
 
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);
 
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);
 
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,
 
1481                 drawBottom = drawRight = drawTop = true;
 
1486                 bottom = y + barRight;
 
1488                 // account for negative bars
 
1498                 drawLeft = drawRight = drawTop = true;
 
1501                 right = x + barRight;
 
1505                 // account for negative bars
 
1516             if (right < axisx.min || left > axisx.max ||
 
1517                 top < axisy.min || bottom > axisy.max)
 
1520             if (left < axisx.min) {
 
1525             if (right > axisx.max) {
 
1530             if (bottom < axisy.min) {
 
1535             if (top > axisy.max) {
 
1540             left = axisx.p2c(left);
 
1541             bottom = axisy.p2c(bottom);
 
1542             right = axisx.p2c(right);
 
1543             top = axisy.p2c(top);
 
1546             if (fillStyleCallback) {
 
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);
 
1557             if (drawLeft || drawRight || drawTop || drawBottom) {
 
1560                 // FIXME: inline moveTo is buggy with excanvas
 
1561                 c.moveTo(left, bottom + offset);
 
1563                     c.lineTo(left, top + offset);
 
1565                     c.moveTo(left, top + offset);
 
1567                     c.lineTo(right, top + offset);
 
1569                     c.moveTo(right, top + offset);
 
1571                     c.lineTo(right, bottom + offset);
 
1573                     c.moveTo(right, bottom + offset);
 
1575                     c.lineTo(left, bottom + offset);
 
1577                     c.moveTo(left, bottom + offset);
 
1582         function drawSeriesBars(series) {
 
1583             function plotBars(datapoints, barLeft, barRight, offset, fillStyleCallback, axisx, axisy) {
 
1584                 var points = datapoints.points, incr = datapoints.incr;
 
1586                 for (var i = 0; i < points.length; i += incr) {
 
1587                     if (points[i] == null)
 
1589                     drawBar(points[i], points[i + 1], points[i + 2], barLeft, barRight, offset, fillStyleCallback, axisx, axisy, ctx, series.bars.horizontal);
 
1594             ctx.translate(plotOffset.left, plotOffset.top);
 
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);
 
1605         function getFillStyle(filloptions, seriesColor, bottom, top) {
 
1606             var fill = filloptions.fill;
 
1610             if (filloptions.fillColor)
 
1611                 return getColorOrGradient(filloptions.fillColor, bottom, top, seriesColor);
 
1613             var c = parseColor(seriesColor);
 
1614             c.a = typeof fill == "number" ? fill : 0.4;
 
1616             return c.toString();
 
1619         function insertLegend() {
 
1620             target.find(".legend").remove();
 
1622             if (!options.legend.show)
 
1625             var fragments = [], rowStarted = false,
 
1626                 lf = options.legend.labelFormatter, s, label;
 
1627             for (i = 0; i < series.length; ++i) {
 
1633                 if (i % options.legend.noColumns == 0) {
 
1635                         fragments.push('</tr>');
 
1636                     fragments.push('<tr>');
 
1641                     label = lf(label, s);
 
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>');
 
1648                 fragments.push('</tr>');
 
1650             if (fragments.length == 0)
 
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);
 
1658                     p = options.legend.position,
 
1659                     m = options.legend.margin;
 
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
 
1675                     var c = options.legend.backgroundColor;
 
1678                         if (options.grid.backgroundColor && typeof options.grid.backgroundColor == "string")
 
1679                             tmp = options.grid.backgroundColor;
 
1681                             tmp = extractColor(legend);
 
1682                         c = parseColor(tmp).adjust(null, null, null, 1).toString();
 
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);
 
1691         // interactive features
 
1693         var lastMousePos = { pageX: null, pageY: null },
 
1695                 first: { x: -1, y: -1}, second: { x: -1, y: -1},
 
1696                 show: false, active: false },
 
1697             crosshair = { pos: { x: -1, y: -1 } },
 
1699             clickIsMouseUp = false,
 
1700             redrawTimeout = null,
 
1701             hoverTimeout = null;
 
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;
 
1709             for (var i = 0; i < series.length; ++i) {
 
1710                 if (!seriesFilter(series[i]))
 
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;
 
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];
 
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)
 
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];
 
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;
 
1751                     for (j = 0; j < points.length; j += incr) {
 
1752                         var x = points[j], y = points[j + 1], b = points[j + 2];
 
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];
 
1771                 return { datapoint: series[i].data[j],
 
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);
 
1789                 lastMousePos.pageX = e.pageX;
 
1790                 lastMousePos.pageY = e.pageY;
 
1793             if (options.grid.hoverable)
 
1794                 triggerClickHoverEvent("plothover", lastMousePos,
 
1795                                        function (s) { return s["hoverable"] != false; });
 
1797             if (options.crosshair.mode != null) {
 
1798                 if (!selection.active) {
 
1799                     setPositionFromEvent(crosshair.pos, lastMousePos);
 
1800                     triggerRedrawOverlay();
 
1803                     crosshair.pos.x = -1; // hide the crosshair while selecting
 
1806             if (selection.active) {
 
1807                 target.trigger("plotselecting", [ selectionIsSane() ? getSelectionForEvent() : null ]);
 
1809                 updateSelection(lastMousePos);
 
1813         function onMouseDown(e) {
 
1814             if (e.which != 1)  // only accept left-click
 
1817             // cancel out any text selections
 
1818             document.body.focus();
 
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; };
 
1825             if (document.ondrag !== undefined && workarounds.ondrag == null) {
 
1826                 workarounds.ondrag = document.ondrag;
 
1827                 document.ondrag = function () { return false; };
 
1830             setSelectionPos(selection.first, e);
 
1832             lastMousePos.pageX = null;
 
1833             selection.active = true;
 
1834             $(document).one("mouseup", onSelectionMouseUp);
 
1837         function onMouseOut(ev) {
 
1838             if (options.crosshair.mode != null && crosshair.pos.x != -1) {
 
1839                 crosshair.pos.x = -1;
 
1840                 triggerRedrawOverlay();
 
1844         function onClick(e) {
 
1845             if (clickIsMouseUp) {
 
1846                 clickIsMouseUp = false;
 
1850             triggerClickHoverEvent("plotclick", e,
 
1851                                    function (s) { return s["clickable"] != false; });
 
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)) };
 
1860         function positionInDivSpace(pos) {
 
1861             var cpos = userPositionInCanvasSpace(pos);
 
1862             return { x: cpos.x + plotOffset.left,
 
1863                      y: cpos.y + plotOffset.top };
 
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;
 
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);
 
1883             var item = findNearbyItem(canvasX, canvasY, seriesFilter);
 
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);
 
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);
 
1901                     highlight(item.series, item.datapoint, eventname);
 
1904             target.trigger(eventname, [ pos, item ]);
 
1907         function triggerRedrawOverlay() {
 
1909                 redrawTimeout = setTimeout(redrawOverlay, 30);
 
1912         function redrawOverlay() {
 
1913             redrawTimeout = null;
 
1915             // redraw highlights
 
1917             octx.clearRect(0, 0, canvasWidth, canvasHeight);
 
1918             octx.translate(plotOffset.left, plotOffset.top);
 
1921             for (i = 0; i < highlights.length; ++i) {
 
1924                 if (hi.series.bars.show)
 
1925                     drawBarHighlight(hi.series, hi.point);
 
1927                     drawPointHighlight(hi.series, hi.point);
 
1931             if (selection.show && selectionIsSane()) {
 
1932                 octx.strokeStyle = parseColor(options.selection.color).scale(null, null, null, 0.8).toString();
 
1934                 ctx.lineJoin = "round";
 
1935                 octx.fillStyle = parseColor(options.selection.color).scale(null, null, null, 0.4).toString();
 
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);
 
1942                 octx.fillRect(x, y, w, h);
 
1943                 octx.strokeRect(x, y, w, h);
 
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();
 
1951                 ctx.lineJoin = "round";
 
1954                 if (mode.indexOf("x") != -1) {
 
1955                     octx.moveTo(pos.x, 0);
 
1956                     octx.lineTo(pos.x, plotHeight);
 
1958                 if (mode.indexOf("y") != -1) {
 
1959                     octx.moveTo(0, pos.y);
 
1960                     octx.lineTo(plotWidth, pos.y);
 
1968         function highlight(s, point, auto) {
 
1969             if (typeof s == "number")
 
1972             if (typeof point == "number")
 
1973                 point = s.data[point];
 
1975             var i = indexOfHighlight(s, point);
 
1977                 highlights.push({ series: s, point: point, auto: auto });
 
1979                 triggerRedrawOverlay();
 
1982                 highlights[i].auto = false;
 
1985         function unhighlight(s, point) {
 
1986             if (typeof s == "number")
 
1989             if (typeof point == "number")
 
1990                 point = s.data[point];
 
1992             var i = indexOfHighlight(s, point);
 
1994                 highlights.splice(i, 1);
 
1996                 triggerRedrawOverlay();
 
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])
 
2010         function drawPointHighlight(series, point) {
 
2011             var x = point[0], y = point[1],
 
2012                 axisx = series.xaxis, axisy = series.yaxis;
 
2014             if (x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max)
 
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;
 
2022             octx.arc(axisx.p2c(x), axisy.p2c(y), radius, 0, 2 * Math.PI, true);
 
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);
 
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);
 
2041         function setCrosshair(pos) {
 
2043                 crosshair.pos.x = -1;
 
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);
 
2048             triggerRedrawOverlay();
 
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);
 
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) };
 
2069         function triggerSelectedEvent() {
 
2070             var r = getSelectionForEvent();
 
2072             target.trigger("plotselected", [ r ]);
 
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 } ]);
 
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;
 
2086             // no more draggy-dee-drag
 
2087             selection.active = false;
 
2090             if (selectionIsSane()) {
 
2091                 triggerSelectedEvent();
 
2092                 clickIsMouseUp = true;
 
2095                 // this counts as a clear
 
2096                 target.trigger("plotunselected", [ ]);
 
2097                 target.trigger("plotselecting", [ null ]);
 
2103         function setSelectionPos(pos, e) {
 
2104             setPositionFromEvent(pos, e);
 
2106             if (options.selection.mode == "y") {
 
2107                 if (pos == selection.first)
 
2113             if (options.selection.mode == "x") {
 
2114                 if (pos == selection.first)
 
2121         function updateSelection(pos) {
 
2122             if (pos.pageX == null)
 
2125             setSelectionPos(selection.second, pos);
 
2126             if (selectionIsSane()) {
 
2127                 selection.show = true;
 
2128                 triggerRedrawOverlay();
 
2131                 clearSelection(true);
 
2134         function clearSelection(preventEvent) {
 
2135             if (selection.show) {
 
2136                 selection.show = false;
 
2137                 triggerRedrawOverlay();
 
2139                     target.trigger("plotunselected", [ ]);
 
2143         function setSelection(ranges, preventEvent) {
 
2146             if (options.selection.mode == "y") {
 
2147                 selection.first.x = 0;
 
2148                 selection.second.x = plotWidth;
 
2151                 range = extractRange(ranges, "x");
 
2153                 selection.first.x = range.axis.p2c(range.from);
 
2154                 selection.second.x = range.axis.p2c(range.to);
 
2157             if (options.selection.mode == "x") {
 
2158                 selection.first.y = 0;
 
2159                 selection.second.y = plotHeight;
 
2162                 range = extractRange(ranges, "y");
 
2164                 selection.first.y = range.axis.p2c(range.from);
 
2165                 selection.second.y = range.axis.p2c(range.to);
 
2168             selection.show = true;
 
2169             triggerRedrawOverlay();
 
2171                 triggerSelectedEvent();
 
2174         function selectionIsSane() {
 
2176             return Math.abs(selection.second.x - selection.first.x) >= minSize &&
 
2177                 Math.abs(selection.second.y - selection.first.y) >= minSize;
 
2180         function getColorOrGradient(spec, bottom, top, defaultColor) {
 
2181             if (typeof spec == "string")
 
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);
 
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));
 
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())
 
2211     // returns a string with the date d formatted according to fmt
 
2212     $.plot.formatDate = function(d, fmt, monthNames) {
 
2213         var leftPad = function(n) {
 
2215             return n.length == 1 ? "0" + n : n;
 
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);
 
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;
 
2249     // round to nearby lower multiple of base
 
2250     function floorInBase(n, base) {
 
2251         return base * Math.floor(n / base);
 
2254     function clamp(min, value, max) {
 
2257         else if (value > max)
 
2263     // color helpers, inspiration from the jquery color animation
 
2264     // plugin by John Resig
 
2265     function Color (r, g, b, a) {
 
2267         var rgba = ['r','g','b','a'];
 
2268         var x = 4; //rgba.length
 
2271             this[rgba[x]] = arguments[x] || ((x==3) ? 1.0 : 0);
 
2274         this.toString = function() {
 
2275             if (this.a >= 1.0) {
 
2276                 return "rgb("+[this.r,this.g,this.b].join(",")+")";
 
2278                 return "rgba("+[this.r,this.g,this.b,this.a].join(",")+")";
 
2282         this.scale = function(rf, gf, bf, af) {
 
2283             x = 4; //rgba.length
 
2285                 if (arguments[x] != null)
 
2286                     this[rgba[x]] *= arguments[x];
 
2288             return this.normalize();
 
2291         this.adjust = function(rd, gd, bd, ad) {
 
2292             x = 4; //rgba.length
 
2294                 if (arguments[x] != null)
 
2295                     this[rgba[x]] += arguments[x];
 
2297             return this.normalize();
 
2300         this.clone = function() {
 
2301             return new Color(this.r, this.b, this.g, this.a);
 
2304         var limit = function(val,minVal,maxVal) {
 
2305             return Math.max(Math.min(val, maxVal), minVal);
 
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);
 
2319     var lookupColors = {
 
2321         azure:[240,255,255],
 
2322         beige:[245,245,220],
 
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],
 
2337         darksalmon:[233,150,122],
 
2338         darkviolet:[148,0,211],
 
2339         fuchsia:[255,0,255],
 
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],
 
2351         magenta:[255,0,255],
 
2360         silver:[192,192,192],
 
2361         white:[255,255,255],
 
2365     function extractColor(element) {
 
2366         var color, elem = element;
 
2368             color = elem.css("background-color").toLowerCase();
 
2369             // keep going until we find an element that has color, or
 
2371             if (color != '' && color != 'transparent')
 
2373             elem = elem.parent();
 
2374         } while (!$.nodeName(elem.get(0), "body"));
 
2376         // catch Safari's way of signalling transparent
 
2377         if (color == "rgba(0, 0, 0, 0)")
 
2378             return "transparent";
 
2383     // parse string, returns Color
 
2384     function parseColor(str) {
 
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));
 
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]));
 
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);
 
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]));
 
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));
 
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));
 
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);
 
2416             result = lookupColors[name];
 
2417             return new Color(result[0], result[1], result[2]);