]> git.sesse.net Git - remoteglot/blob - www/js/jquery.sparkline.js
Remove VML support from jQuery Sparkline (only relevant for old IE). Another 4 kB.
[remoteglot] / www / js / jquery.sparkline.js
1 /**
2 *
3 * jquery.sparkline.js
4 *
5 * v2.1.2
6 * (c) Splunk, Inc
7 * Contact: Gareth Watts (gareth@splunk.com)
8 * http://omnipotent.net/jquery.sparkline/
9 *
10 * Generates inline sparkline charts from data supplied either to the method
11 * or inline in HTML
12 *
13 * Compatible with Internet Explorer 6.0+ and modern browsers equipped with the canvas tag
14 * (Firefox 2.0+, Safari, Opera, etc)
15 *
16 * License: New BSD License
17 *
18 * Copyright (c) 2012, Splunk Inc.
19 * All rights reserved.
20 *
21 * Redistribution and use in source and binary forms, with or without modification,
22 * are permitted provided that the following conditions are met:
23 *
24 *     * Redistributions of source code must retain the above copyright notice,
25 *       this list of conditions and the following disclaimer.
26 *     * Redistributions in binary form must reproduce the above copyright notice,
27 *       this list of conditions and the following disclaimer in the documentation
28 *       and/or other materials provided with the distribution.
29 *     * Neither the name of Splunk Inc nor the names of its contributors may
30 *       be used to endorse or promote products derived from this software without
31 *       specific prior written permission.
32 *
33 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
34 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
35 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
36 * SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
37 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
38 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
39 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
40 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
41 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42 *
43 *
44 * Usage:
45 *  $(selector).sparkline(values, options)
46 *
47 * If values is undefined or set to 'html' then the data values are read from the specified tag:
48 *   <p>Sparkline: <span class="sparkline">1,4,6,6,8,5,3,5</span></p>
49 *   $('.sparkline').sparkline();
50 * There must be no spaces in the enclosed data set
51 *
52 * Otherwise values must be an array of numbers or null values
53 *    <p>Sparkline: <span id="sparkline1">This text replaced if the browser is compatible</span></p>
54 *    $('#sparkline1').sparkline([1,4,6,6,8,5,3,5])
55 *    $('#sparkline2').sparkline([1,4,6,null,null,5,3,5])
56 *
57 * Values can also be specified in an HTML comment, or as a values attribute:
58 *    <p>Sparkline: <span class="sparkline"><!--1,4,6,6,8,5,3,5 --></span></p>
59 *    <p>Sparkline: <span class="sparkline" values="1,4,6,6,8,5,3,5"></span></p>
60 *    $('.sparkline').sparkline();
61 *
62 * By default, options should be passed in as teh second argument to the sparkline function:
63 *   $('.sparkline').sparkline([1,2,3,4], {type: 'bar'})
64 *
65 * Options can also be set by passing them on the tag itself.  This feature is disabled by default though
66 * as there's a slight performance overhead:
67 *   $('.sparkline').sparkline([1,2,3,4], {enableTagOptions: true})
68 *   <p>Sparkline: <span class="sparkline" sparkType="bar" sparkBarColor="red">loading</span></p>
69 * Prefix all options supplied as tag attribute with "spark" (configurable by setting tagOptionPrefix)
70 *
71 * Supported options:
72 *   lineColor - Color of the line used for the chart
73 *   fillColor - Color used to fill in the chart - Set to '' or false for a transparent chart
74 *   width - Width of the chart - Defaults to 3 times the number of values in pixels
75 *   height - Height of the chart - Defaults to the height of the containing element
76 *   chartRangeMin - Specify the minimum value to use for the Y range of the chart - Defaults to the minimum value supplied
77 *   chartRangeMax - Specify the maximum value to use for the Y range of the chart - Defaults to the maximum value supplied
78 *   chartRangeClip - Clip out of range values to the max/min specified by chartRangeMin and chartRangeMax
79 *   chartRangeMinX - Specify the minimum value to use for the X range of the chart - Defaults to the minimum value supplied
80 *   chartRangeMaxX - Specify the maximum value to use for the X range of the chart - Defaults to the maximum value supplied
81 *   composite - If true then don't erase any existing chart attached to the tag, but draw
82 *           another chart over the top - Note that width and height are ignored if an
83 *           existing chart is detected.
84 *   tagValuesAttribute - Name of tag attribute to check for data values - Defaults to 'values'
85 *   enableTagOptions - Whether to check tags for sparkline options
86 *   tagOptionPrefix - Prefix used for options supplied as tag attributes - Defaults to 'spark'
87 *   disableHiddenCheck - If set to true, then the plugin will assume that charts will never be drawn into a
88 *           hidden dom element, avoding a browser reflow
89 *   disableInteraction - If set to true then all mouseover/click interaction behaviour will be disabled,
90 *       making the plugin perform much like it did in 1.x
91 *   disableTooltips - If set to true then tooltips will be disabled - Defaults to false (tooltips enabled)
92 *   disableHighlight - If set to true then highlighting of selected chart elements on mouseover will be disabled
93 *       defaults to false (highlights enabled)
94 *   highlightLighten - Factor to lighten/darken highlighted chart values by - Defaults to 1.4 for a 40% increase
95 *   tooltipContainer - Specify which DOM element the tooltip should be rendered into - defaults to document.body
96 *   tooltipClassname - Optional CSS classname to apply to tooltips - If not specified then a default style will be applied
97 *   tooltipOffsetX - How many pixels away from the mouse pointer to render the tooltip on the X axis
98 *   tooltipOffsetY - How many pixels away from the mouse pointer to render the tooltip on the r axis
99 *   tooltipFormatter  - Optional callback that allows you to override the HTML displayed in the tooltip
100 *       callback is given arguments of (sparkline, options, fields)
101 *   tooltipChartTitle - If specified then the tooltip uses the string specified by this setting as a title
102 *   tooltipFormat - A format string or SPFormat object  (or an array thereof for multiple entries)
103 *       to control the format of the tooltip
104 *   tooltipPrefix - A string to prepend to each field displayed in a tooltip
105 *   tooltipSuffix - A string to append to each field displayed in a tooltip
106 *   tooltipSkipNull - If true then null values will not have a tooltip displayed (defaults to true)
107 *   tooltipValueLookups - An object or range map to map field values to tooltip strings
108 *       (eg. to map -1 to "Lost", 0 to "Draw", and 1 to "Win")
109 *   numberFormatter - Optional callback for formatting numbers in tooltips
110 *   numberDigitGroupSep - Character to use for group separator in numbers "1,234" - Defaults to ","
111 *   numberDecimalMark - Character to use for the decimal point when formatting numbers - Defaults to "."
112 *   numberDigitGroupCount - Number of digits between group separator - Defaults to 3
113 *
114 * There is 1 type of sparkline, selected by supplying a "type" option of 'bar' (default),
115 *
116 *   bar - Bar chart.  Options:
117 *       barColor - Color of bars for postive values
118 *       negBarColor - Color of bars for negative values
119 *       zeroColor - Color of bars with zero values
120 *       nullColor - Color of bars with null values - Defaults to omitting the bar entirely
121 *       barWidth - Width of bars in pixels
122 *       colorMap - Optional mappnig of values to colors to override the *BarColor values above
123 *                  can be an Array of values to control the color of individual bars or a range map
124 *                  to specify colors for individual ranges of values
125 *       barSpacing - Gap between bars in pixels
126 *       zeroAxis - Centers the y-axis around zero if true
127 *
128 *
129 *
130 *
131 *
132 *
133 *   Examples:
134 *   $('#sparkline1').sparkline(myvalues, { lineColor: '#f00', fillColor: false });
135 *   $('.barsparks').sparkline('html', { type:'bar', height:'40px', barWidth:5 });
136 */
137
138 /*jslint regexp: true, browser: true, jquery: true, white: true, nomen: false, plusplus: false, maxerr: 500, indent: 4 */
139
140 (function(document, Math, undefined) { // performance/minified-size optimization
141 (function(factory) {
142     if(typeof define === 'function' && define.amd) {
143         define(['jquery'], factory);
144     } else if (jQuery && !jQuery.fn.sparkline) {
145         factory(jQuery);
146     }
147 }
148 (function($) {
149     'use strict';
150
151     var UNSET_OPTION = {},
152         getDefaults, createClass, SPFormat, clipval, quartile, normalizeValue, normalizeValues,
153         remove, isNumber, all, sum, addCSS, ensureArray, formatNumber, RangeMap,
154         MouseHandler, Tooltip, barHighlightMixin,
155         bar, defaultStyles, initStyles,
156         VShape, VCanvas_base, VCanvas_canvas, pending, shapeCount = 0;
157
158     /**
159      * Default configuration settings
160      */
161     getDefaults = function () {
162         return {
163             // Settings common to most/all chart types
164             common: {
165                 type: 'bar',
166                 lineColor: '#00f',
167                 fillColor: '#cdf',
168                 defaultPixelsPerValue: 3,
169                 width: 'auto',
170                 height: 'auto',
171                 composite: false,
172                 tagValuesAttribute: 'values',
173                 tagOptionsPrefix: 'spark',
174                 enableTagOptions: false,
175                 enableHighlight: true,
176                 highlightLighten: 1.4,
177                 tooltipSkipNull: true,
178                 tooltipPrefix: '',
179                 tooltipSuffix: '',
180                 disableHiddenCheck: false,
181                 numberFormatter: false,
182                 numberDigitGroupCount: 3,
183                 numberDigitGroupSep: ',',
184                 numberDecimalMark: '.',
185                 disableTooltips: false,
186                 disableInteraction: false
187             },
188             // Defaults for bar charts
189             bar: {
190                 barColor: '#3366cc',
191                 negBarColor: '#f44',
192                 stackedBarColor: ['#3366cc', '#dc3912', '#ff9900', '#109618', '#66aa00',
193                     '#dd4477', '#0099c6', '#990099'],
194                 zeroColor: undefined,
195                 nullColor: undefined,
196                 zeroAxis: true,
197                 barWidth: 4,
198                 barSpacing: 1,
199                 chartRangeMax: undefined,
200                 chartRangeMin: undefined,
201                 chartRangeClip: false,
202                 colorMap: undefined,
203                 tooltipFormat: new SPFormat('<span style="color: {{color}}">&#9679;</span> {{prefix}}{{value}}{{suffix}}')
204             },
205         };
206     };
207
208     // You can have tooltips use a css class other than jqstooltip by specifying tooltipClassname
209     defaultStyles = '.jqstooltip { ' +
210             'position: absolute;' +
211             'left: 0px;' +
212             'top: 0px;' +
213             'visibility: hidden;' +
214             'background: rgb(0, 0, 0) transparent;' +
215             'background-color: rgba(0,0,0,0.6);' +
216             'filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000);' +
217             '-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000)";' +
218             'color: white;' +
219             'font: 10px arial, san serif;' +
220             'text-align: left;' +
221             'white-space: nowrap;' +
222             'padding: 5px;' +
223             'border: 1px solid white;' +
224             'z-index: 10000;' +
225             '}' +
226             '.jqsfield { ' +
227             'color: white;' +
228             'font: 10px arial, san serif;' +
229             'text-align: left;' +
230             '}';
231
232     /**
233      * Utilities
234      */
235
236     createClass = function (/* [baseclass, [mixin, ...]], definition */) {
237         var Class, args;
238         Class = function () {
239             this.init.apply(this, arguments);
240         };
241         if (arguments.length > 1) {
242             if (arguments[0]) {
243                 Class.prototype = $.extend(new arguments[0](), arguments[arguments.length - 1]);
244                 Class._super = arguments[0].prototype;
245             } else {
246                 Class.prototype = arguments[arguments.length - 1];
247             }
248             if (arguments.length > 2) {
249                 args = Array.prototype.slice.call(arguments, 1, -1);
250                 args.unshift(Class.prototype);
251                 $.extend.apply($, args);
252             }
253         } else {
254             Class.prototype = arguments[0];
255         }
256         Class.prototype.cls = Class;
257         return Class;
258     };
259
260     /**
261      * Wraps a format string for tooltips
262      * {{x}}
263      * {{x.2}
264      * {{x:months}}
265      */
266     $.SPFormatClass = SPFormat = createClass({
267         fre: /\{\{([\w.]+?)(:(.+?))?\}\}/g,
268         precre: /(\w+)\.(\d+)/,
269
270         init: function (format, fclass) {
271             this.format = format;
272             this.fclass = fclass;
273         },
274
275         render: function (fieldset, lookups, options) {
276             var self = this,
277                 fields = fieldset,
278                 match, token, lookupkey, fieldvalue, prec;
279             return this.format.replace(this.fre, function () {
280                 var lookup;
281                 token = arguments[1];
282                 lookupkey = arguments[3];
283                 match = self.precre.exec(token);
284                 if (match) {
285                     prec = match[2];
286                     token = match[1];
287                 } else {
288                     prec = false;
289                 }
290                 fieldvalue = fields[token];
291                 if (fieldvalue === undefined) {
292                     return '';
293                 }
294                 if (lookupkey && lookups && lookups[lookupkey]) {
295                     lookup = lookups[lookupkey];
296                     if (lookup.get) { // RangeMap
297                         return lookups[lookupkey].get(fieldvalue) || fieldvalue;
298                     } else {
299                         return lookups[lookupkey][fieldvalue] || fieldvalue;
300                     }
301                 }
302                 if (isNumber(fieldvalue)) {
303                     if (options.get('numberFormatter')) {
304                         fieldvalue = options.get('numberFormatter')(fieldvalue);
305                     } else {
306                         fieldvalue = formatNumber(fieldvalue, prec,
307                             options.get('numberDigitGroupCount'),
308                             options.get('numberDigitGroupSep'),
309                             options.get('numberDecimalMark'));
310                     }
311                 }
312                 return fieldvalue;
313             });
314         }
315     });
316
317     // convience method to avoid needing the new operator
318     $.spformat = function(format, fclass) {
319         return new SPFormat(format, fclass);
320     };
321
322     clipval = function (val, min, max) {
323         if (val < min) {
324             return min;
325         }
326         if (val > max) {
327             return max;
328         }
329         return val;
330     };
331
332     quartile = function (values, q) {
333         var vl;
334         if (q === 2) {
335             vl = Math.floor(values.length / 2);
336             return values.length % 2 ? values[vl] : (values[vl-1] + values[vl]) / 2;
337         } else {
338             if (values.length % 2 ) { // odd
339                 vl = (values.length * q + q) / 4;
340                 return vl % 1 ? (values[Math.floor(vl)] + values[Math.floor(vl) - 1]) / 2 : values[vl-1];
341             } else { //even
342                 vl = (values.length * q + 2) / 4;
343                 return vl % 1 ? (values[Math.floor(vl)] + values[Math.floor(vl) - 1]) / 2 :  values[vl-1];
344
345             }
346         }
347     };
348
349     normalizeValue = function (val) {
350         var nf;
351         switch (val) {
352             case 'undefined':
353                 val = undefined;
354                 break;
355             case 'null':
356                 val = null;
357                 break;
358             case 'true':
359                 val = true;
360                 break;
361             case 'false':
362                 val = false;
363                 break;
364             default:
365                 nf = parseFloat(val);
366                 if (val == nf) {
367                     val = nf;
368                 }
369         }
370         return val;
371     };
372
373     normalizeValues = function (vals) {
374         var i, result = [];
375         for (i = vals.length; i--;) {
376             result[i] = normalizeValue(vals[i]);
377         }
378         return result;
379     };
380
381     remove = function (vals, filter) {
382         var i, vl, result = [];
383         for (i = 0, vl = vals.length; i < vl; i++) {
384             if (vals[i] !== filter) {
385                 result.push(vals[i]);
386             }
387         }
388         return result;
389     };
390
391     isNumber = function (num) {
392         return !isNaN(parseFloat(num)) && isFinite(num);
393     };
394
395     formatNumber = function (num, prec, groupsize, groupsep, decsep) {
396         var p, i;
397         num = (prec === false ? parseFloat(num).toString() : num.toFixed(prec)).split('');
398         p = (p = $.inArray('.', num)) < 0 ? num.length : p;
399         if (p < num.length) {
400             num[p] = decsep;
401         }
402         for (i = p - groupsize; i > 0; i -= groupsize) {
403             num.splice(i, 0, groupsep);
404         }
405         return num.join('');
406     };
407
408     // determine if all values of an array match a value
409     // returns true if the array is empty
410     all = function (val, arr, ignoreNull) {
411         var i;
412         for (i = arr.length; i--; ) {
413             if (ignoreNull && arr[i] === null) continue;
414             if (arr[i] !== val) {
415                 return false;
416             }
417         }
418         return true;
419     };
420
421     // sums the numeric values in an array, ignoring other values
422     sum = function (vals) {
423         var total = 0, i;
424         for (i = vals.length; i--;) {
425             total += typeof vals[i] === 'number' ? vals[i] : 0;
426         }
427         return total;
428     };
429
430     ensureArray = function (val) {
431         return $.isArray(val) ? val : [val];
432     };
433
434     // http://paulirish.com/2008/bookmarklet-inject-new-css-rules/
435     addCSS = function(css) {
436         var tag;
437         //if ('\v' == 'v') /* ie only */ {
438         if (document.createStyleSheet) {
439             document.createStyleSheet().cssText = css;
440         } else {
441             tag = document.createElement('style');
442             tag.type = 'text/css';
443             document.getElementsByTagName('head')[0].appendChild(tag);
444             tag[(typeof document.body.style.WebkitAppearance == 'string') /* webkit only */ ? 'innerText' : 'innerHTML'] = css;
445         }
446     };
447
448     // Provide a cross-browser interface to a few simple drawing primitives
449     $.fn.simpledraw = function (width, height, useExisting, interact) {
450         var target, mhandler;
451         if (useExisting && (target = this.data('_jqs_vcanvas'))) {
452             return target;
453         }
454
455         if ($.fn.sparkline.canvas === false) {
456             // We've already determined that neither Canvas nor VML are available
457             return false;
458
459         } else if ($.fn.sparkline.canvas === undefined) {
460             // No function defined yet -- need to see if we support Canvas or VML
461             var el = document.createElement('canvas');
462             if (!!(el.getContext && el.getContext('2d'))) {
463                 // Canvas is available
464                 $.fn.sparkline.canvas = function(width, height, target, interact) {
465                     return new VCanvas_canvas(width, height, target, interact);
466                 };
467             } else {
468                 // Neither Canvas nor VML are available
469                 $.fn.sparkline.canvas = false;
470                 return false;
471             }
472         }
473
474         if (width === undefined) {
475             width = $(this).innerWidth();
476         }
477         if (height === undefined) {
478             height = $(this).innerHeight();
479         }
480
481         target = $.fn.sparkline.canvas(width, height, this, interact);
482
483         mhandler = $(this).data('_jqs_mhandler');
484         if (mhandler) {
485             mhandler.registerCanvas(target);
486         }
487         return target;
488     };
489
490     $.fn.cleardraw = function () {
491         var target = this.data('_jqs_vcanvas');
492         if (target) {
493             target.reset();
494         }
495     };
496
497     $.RangeMapClass = RangeMap = createClass({
498         init: function (map) {
499             var key, range, rangelist = [];
500             for (key in map) {
501                 if (map.hasOwnProperty(key) && typeof key === 'string' && key.indexOf(':') > -1) {
502                     range = key.split(':');
503                     range[0] = range[0].length === 0 ? -Infinity : parseFloat(range[0]);
504                     range[1] = range[1].length === 0 ? Infinity : parseFloat(range[1]);
505                     range[2] = map[key];
506                     rangelist.push(range);
507                 }
508             }
509             this.map = map;
510             this.rangelist = rangelist || false;
511         },
512
513         get: function (value) {
514             var rangelist = this.rangelist,
515                 i, range, result;
516             if ((result = this.map[value]) !== undefined) {
517                 return result;
518             }
519             if (rangelist) {
520                 for (i = rangelist.length; i--;) {
521                     range = rangelist[i];
522                     if (range[0] <= value && range[1] >= value) {
523                         return range[2];
524                     }
525                 }
526             }
527             return undefined;
528         }
529     });
530
531     // Convenience function
532     $.range_map = function(map) {
533         return new RangeMap(map);
534     };
535
536     MouseHandler = createClass({
537         init: function (el, options) {
538             var $el = $(el);
539             this.$el = $el;
540             this.options = options;
541             this.currentPageX = 0;
542             this.currentPageY = 0;
543             this.el = el;
544             this.splist = [];
545             this.tooltip = null;
546             this.over = false;
547             this.displayTooltips = !options.get('disableTooltips');
548             this.highlightEnabled = !options.get('disableHighlight');
549         },
550
551         registerSparkline: function (sp) {
552             this.splist.push(sp);
553             if (this.over) {
554                 this.updateDisplay();
555             }
556         },
557
558         registerCanvas: function (canvas) {
559             var $canvas = $(canvas.canvas);
560             this.canvas = canvas;
561             this.$canvas = $canvas;
562             $canvas.mouseenter($.proxy(this.mouseenter, this));
563             $canvas.mouseleave($.proxy(this.mouseleave, this));
564             $canvas.click($.proxy(this.mouseclick, this));
565         },
566
567         reset: function (removeTooltip) {
568             this.splist = [];
569             if (this.tooltip && removeTooltip) {
570                 this.tooltip.remove();
571                 this.tooltip = undefined;
572             }
573         },
574
575         mouseclick: function (e) {
576             var clickEvent = $.Event('sparklineClick');
577             clickEvent.originalEvent = e;
578             clickEvent.sparklines = this.splist;
579             this.$el.trigger(clickEvent);
580         },
581
582         mouseenter: function (e) {
583             $(document.body).unbind('mousemove.jqs');
584             $(document.body).bind('mousemove.jqs', $.proxy(this.mousemove, this));
585             this.over = true;
586             this.currentPageX = e.pageX;
587             this.currentPageY = e.pageY;
588             this.currentEl = e.target;
589             if (!this.tooltip && this.displayTooltips) {
590                 this.tooltip = new Tooltip(this.options);
591                 this.tooltip.updatePosition(e.pageX, e.pageY);
592             }
593             this.updateDisplay();
594         },
595
596         mouseleave: function () {
597             $(document.body).unbind('mousemove.jqs');
598             var splist = this.splist,
599                  spcount = splist.length,
600                  needsRefresh = false,
601                  sp, i;
602             this.over = false;
603             this.currentEl = null;
604
605             if (this.tooltip) {
606                 this.tooltip.remove();
607                 this.tooltip = null;
608             }
609
610             for (i = 0; i < spcount; i++) {
611                 sp = splist[i];
612                 if (sp.clearRegionHighlight()) {
613                     needsRefresh = true;
614                 }
615             }
616
617             if (needsRefresh) {
618                 this.canvas.render();
619             }
620         },
621
622         mousemove: function (e) {
623             this.currentPageX = e.pageX;
624             this.currentPageY = e.pageY;
625             this.currentEl = e.target;
626             if (this.tooltip) {
627                 this.tooltip.updatePosition(e.pageX, e.pageY);
628             }
629             this.updateDisplay();
630         },
631
632         updateDisplay: function () {
633             var splist = this.splist,
634                  spcount = splist.length,
635                  needsRefresh = false,
636                  offset = this.$canvas.offset(),
637                  localX = this.currentPageX - offset.left,
638                  localY = this.currentPageY - offset.top,
639                  tooltiphtml, sp, i, result, changeEvent;
640             if (!this.over) {
641                 return;
642             }
643             for (i = 0; i < spcount; i++) {
644                 sp = splist[i];
645                 result = sp.setRegionHighlight(this.currentEl, localX, localY);
646                 if (result) {
647                     needsRefresh = true;
648                 }
649             }
650             if (needsRefresh) {
651                 changeEvent = $.Event('sparklineRegionChange');
652                 changeEvent.sparklines = this.splist;
653                 this.$el.trigger(changeEvent);
654                 if (this.tooltip) {
655                     tooltiphtml = '';
656                     for (i = 0; i < spcount; i++) {
657                         sp = splist[i];
658                         tooltiphtml += sp.getCurrentRegionTooltip();
659                     }
660                     this.tooltip.setContent(tooltiphtml);
661                 }
662                 if (!this.disableHighlight) {
663                     this.canvas.render();
664                 }
665             }
666             if (result === null) {
667                 this.mouseleave();
668             }
669         }
670     });
671
672
673     Tooltip = createClass({
674         sizeStyle: 'position: static !important;' +
675             'display: block !important;' +
676             'visibility: hidden !important;' +
677             'float: left !important;',
678
679         init: function (options) {
680             var tooltipClassname = options.get('tooltipClassname', 'jqstooltip'),
681                 sizetipStyle = this.sizeStyle,
682                 offset;
683             this.container = options.get('tooltipContainer') || document.body;
684             this.tooltipOffsetX = options.get('tooltipOffsetX', 10);
685             this.tooltipOffsetY = options.get('tooltipOffsetY', 12);
686             // remove any previous lingering tooltip
687             $('#jqssizetip').remove();
688             $('#jqstooltip').remove();
689             this.sizetip = $('<div/>', {
690                 id: 'jqssizetip',
691                 style: sizetipStyle,
692                 'class': tooltipClassname
693             });
694             this.tooltip = $('<div/>', {
695                 id: 'jqstooltip',
696                 'class': tooltipClassname
697             }).appendTo(this.container);
698             // account for the container's location
699             offset = this.tooltip.offset();
700             this.offsetLeft = offset.left;
701             this.offsetTop = offset.top;
702             this.hidden = true;
703             $(window).unbind('resize.jqs scroll.jqs');
704             $(window).bind('resize.jqs scroll.jqs', $.proxy(this.updateWindowDims, this));
705             this.updateWindowDims();
706         },
707
708         updateWindowDims: function () {
709             this.scrollTop = $(window).scrollTop();
710             this.scrollLeft = $(window).scrollLeft();
711             this.scrollRight = this.scrollLeft + $(window).width();
712             this.updatePosition();
713         },
714
715         getSize: function (content) {
716             this.sizetip.html(content).appendTo(this.container);
717             this.width = this.sizetip.width() + 1;
718             this.height = this.sizetip.height();
719             this.sizetip.remove();
720         },
721
722         setContent: function (content) {
723             if (!content) {
724                 this.tooltip.css('visibility', 'hidden');
725                 this.hidden = true;
726                 return;
727             }
728             this.getSize(content);
729             this.tooltip.html(content)
730                 .css({
731                     'width': this.width,
732                     'height': this.height,
733                     'visibility': 'visible'
734                 });
735             if (this.hidden) {
736                 this.hidden = false;
737                 this.updatePosition();
738             }
739         },
740
741         updatePosition: function (x, y) {
742             if (x === undefined) {
743                 if (this.mousex === undefined) {
744                     return;
745                 }
746                 x = this.mousex - this.offsetLeft;
747                 y = this.mousey - this.offsetTop;
748
749             } else {
750                 this.mousex = x = x - this.offsetLeft;
751                 this.mousey = y = y - this.offsetTop;
752             }
753             if (!this.height || !this.width || this.hidden) {
754                 return;
755             }
756
757             y -= this.height + this.tooltipOffsetY;
758             x += this.tooltipOffsetX;
759
760             if (y < this.scrollTop) {
761                 y = this.scrollTop;
762             }
763             if (x < this.scrollLeft) {
764                 x = this.scrollLeft;
765             } else if (x + this.width > this.scrollRight) {
766                 x = this.scrollRight - this.width;
767             }
768
769             this.tooltip.css({
770                 'left': x,
771                 'top': y
772             });
773         },
774
775         remove: function () {
776             this.tooltip.remove();
777             this.sizetip.remove();
778             this.sizetip = this.tooltip = undefined;
779             $(window).unbind('resize.jqs scroll.jqs');
780         }
781     });
782
783     initStyles = function() {
784         addCSS(defaultStyles);
785     };
786
787     $(initStyles);
788
789     pending = [];
790     $.fn.sparkline = function (userValues, userOptions) {
791         return this.each(function () {
792             var options = new $.fn.sparkline.options(this, userOptions),
793                  $this = $(this),
794                  render, i;
795             render = function () {
796                 var values, width, height, tmp, mhandler, sp, vals;
797                 if (userValues === 'html' || userValues === undefined) {
798                     vals = this.getAttribute(options.get('tagValuesAttribute'));
799                     if (vals === undefined || vals === null) {
800                         vals = $this.html();
801                     }
802                     values = vals.replace(/(^\s*<!--)|(-->\s*$)|\s+/g, '').split(',');
803                 } else {
804                     values = userValues;
805                 }
806
807                 width = options.get('width') === 'auto' ? values.length * options.get('defaultPixelsPerValue') : options.get('width');
808                 if (options.get('height') === 'auto') {
809                     if (!options.get('composite') || !$.data(this, '_jqs_vcanvas')) {
810                         // must be a better way to get the line height
811                         tmp = document.createElement('span');
812                         tmp.innerHTML = 'a';
813                         $this.html(tmp);
814                         height = $(tmp).innerHeight() || $(tmp).height();
815                         $(tmp).remove();
816                         tmp = null;
817                     }
818                 } else {
819                     height = options.get('height');
820                 }
821
822                 if (!options.get('disableInteraction')) {
823                     mhandler = $.data(this, '_jqs_mhandler');
824                     if (!mhandler) {
825                         mhandler = new MouseHandler(this, options);
826                         $.data(this, '_jqs_mhandler', mhandler);
827                     } else if (!options.get('composite')) {
828                         mhandler.reset();
829                     }
830                 } else {
831                     mhandler = false;
832                 }
833
834                 if (options.get('composite') && !$.data(this, '_jqs_vcanvas')) {
835                     if (!$.data(this, '_jqs_errnotify')) {
836                         alert('Attempted to attach a composite sparkline to an element with no existing sparkline');
837                         $.data(this, '_jqs_errnotify', true);
838                     }
839                     return;
840                 }
841
842                 sp = new $.fn.sparkline[options.get('type')](this, values, options, width, height);
843
844                 sp.render();
845
846                 if (mhandler) {
847                     mhandler.registerSparkline(sp);
848                 }
849             };
850             if (($(this).html() && !options.get('disableHiddenCheck') && $(this).is(':hidden')) || !$(this).parents('body').length) {
851                 if (!options.get('composite') && $.data(this, '_jqs_pending')) {
852                     // remove any existing references to the element
853                     for (i = pending.length; i; i--) {
854                         if (pending[i - 1][0] == this) {
855                             pending.splice(i - 1, 1);
856                         }
857                     }
858                 }
859                 pending.push([this, render]);
860                 $.data(this, '_jqs_pending', true);
861             } else {
862                 render.call(this);
863             }
864         });
865     };
866
867     $.fn.sparkline.defaults = getDefaults();
868
869
870     $.sparkline_display_visible = function () {
871         var el, i, pl;
872         var done = [];
873         for (i = 0, pl = pending.length; i < pl; i++) {
874             el = pending[i][0];
875             if ($(el).is(':visible') && !$(el).parents().is(':hidden')) {
876                 pending[i][1].call(el);
877                 $.data(pending[i][0], '_jqs_pending', false);
878                 done.push(i);
879             } else if (!$(el).closest('html').length && !$.data(el, '_jqs_pending')) {
880                 // element has been inserted and removed from the DOM
881                 // If it was not yet inserted into the dom then the .data request
882                 // will return true.
883                 // removing from the dom causes the data to be removed.
884                 $.data(pending[i][0], '_jqs_pending', false);
885                 done.push(i);
886             }
887         }
888         for (i = done.length; i; i--) {
889             pending.splice(done[i - 1], 1);
890         }
891     };
892
893
894     /**
895      * User option handler
896      */
897     $.fn.sparkline.options = createClass({
898         init: function (tag, userOptions) {
899             var extendedOptions, defaults, base, tagOptionType;
900             this.userOptions = userOptions = userOptions || {};
901             this.tag = tag;
902             this.tagValCache = {};
903             defaults = $.fn.sparkline.defaults;
904             base = defaults.common;
905             this.tagOptionsPrefix = userOptions.enableTagOptions && (userOptions.tagOptionsPrefix || base.tagOptionsPrefix);
906
907             tagOptionType = this.getTagSetting('type');
908             if (tagOptionType === UNSET_OPTION) {
909                 extendedOptions = defaults[userOptions.type || base.type];
910             } else {
911                 extendedOptions = defaults[tagOptionType];
912             }
913             this.mergedOptions = $.extend({}, base, extendedOptions, userOptions);
914         },
915
916
917         getTagSetting: function (key) {
918             var prefix = this.tagOptionsPrefix,
919                 val, i, pairs, keyval;
920             if (prefix === false || prefix === undefined) {
921                 return UNSET_OPTION;
922             }
923             if (this.tagValCache.hasOwnProperty(key)) {
924                 val = this.tagValCache.key;
925             } else {
926                 val = this.tag.getAttribute(prefix + key);
927                 if (val === undefined || val === null) {
928                     val = UNSET_OPTION;
929                 } else if (val.substr(0, 1) === '[') {
930                     val = val.substr(1, val.length - 2).split(',');
931                     for (i = val.length; i--;) {
932                         val[i] = normalizeValue(val[i].replace(/(^\s*)|(\s*$)/g, ''));
933                     }
934                 } else if (val.substr(0, 1) === '{') {
935                     pairs = val.substr(1, val.length - 2).split(',');
936                     val = {};
937                     for (i = pairs.length; i--;) {
938                         keyval = pairs[i].split(':', 2);
939                         val[keyval[0].replace(/(^\s*)|(\s*$)/g, '')] = normalizeValue(keyval[1].replace(/(^\s*)|(\s*$)/g, ''));
940                     }
941                 } else {
942                     val = normalizeValue(val);
943                 }
944                 this.tagValCache.key = val;
945             }
946             return val;
947         },
948
949         get: function (key, defaultval) {
950             var tagOption = this.getTagSetting(key),
951                 result;
952             if (tagOption !== UNSET_OPTION) {
953                 return tagOption;
954             }
955             return (result = this.mergedOptions[key]) === undefined ? defaultval : result;
956         }
957     });
958
959
960     $.fn.sparkline._base = createClass({
961         disabled: false,
962
963         init: function (el, values, options, width, height) {
964             this.el = el;
965             this.$el = $(el);
966             this.values = values;
967             this.options = options;
968             this.width = width;
969             this.height = height;
970             this.currentRegion = undefined;
971         },
972
973         /**
974          * Setup the canvas
975          */
976         initTarget: function () {
977             var interactive = !this.options.get('disableInteraction');
978             if (!(this.target = this.$el.simpledraw(this.width, this.height, this.options.get('composite'), interactive))) {
979                 this.disabled = true;
980             } else {
981                 this.canvasWidth = this.target.pixelWidth;
982                 this.canvasHeight = this.target.pixelHeight;
983             }
984         },
985
986         /**
987          * Actually render the chart to the canvas
988          */
989         render: function () {
990             if (this.disabled) {
991                 this.el.innerHTML = '';
992                 return false;
993             }
994             return true;
995         },
996
997         /**
998          * Return a region id for a given x/y co-ordinate
999          */
1000         getRegion: function (x, y) {
1001         },
1002
1003         /**
1004          * Highlight an item based on the moused-over x,y co-ordinate
1005          */
1006         setRegionHighlight: function (el, x, y) {
1007             var currentRegion = this.currentRegion,
1008                 highlightEnabled = !this.options.get('disableHighlight'),
1009                 newRegion;
1010             if (x > this.canvasWidth || y > this.canvasHeight || x < 0 || y < 0) {
1011                 return null;
1012             }
1013             newRegion = this.getRegion(el, x, y);
1014             if (currentRegion !== newRegion) {
1015                 if (currentRegion !== undefined && highlightEnabled) {
1016                     this.removeHighlight();
1017                 }
1018                 this.currentRegion = newRegion;
1019                 if (newRegion !== undefined && highlightEnabled) {
1020                     this.renderHighlight();
1021                 }
1022                 return true;
1023             }
1024             return false;
1025         },
1026
1027         /**
1028          * Reset any currently highlighted item
1029          */
1030         clearRegionHighlight: function () {
1031             if (this.currentRegion !== undefined) {
1032                 this.removeHighlight();
1033                 this.currentRegion = undefined;
1034                 return true;
1035             }
1036             return false;
1037         },
1038
1039         renderHighlight: function () {
1040             this.changeHighlight(true);
1041         },
1042
1043         removeHighlight: function () {
1044             this.changeHighlight(false);
1045         },
1046
1047         changeHighlight: function (highlight)  {},
1048
1049         /**
1050          * Fetch the HTML to display as a tooltip
1051          */
1052         getCurrentRegionTooltip: function () {
1053             var options = this.options,
1054                 header = '',
1055                 entries = [],
1056                 fields, formats, formatlen, fclass, text, i,
1057                 showFields, showFieldsKey, newFields, fv,
1058                 formatter, format, fieldlen, j;
1059             if (this.currentRegion === undefined) {
1060                 return '';
1061             }
1062             fields = this.getCurrentRegionFields();
1063             formatter = options.get('tooltipFormatter');
1064             if (formatter) {
1065                 return formatter(this, options, fields);
1066             }
1067             if (options.get('tooltipChartTitle')) {
1068                 header += '<div class="jqs jqstitle">' + options.get('tooltipChartTitle') + '</div>\n';
1069             }
1070             formats = this.options.get('tooltipFormat');
1071             if (!formats) {
1072                 return '';
1073             }
1074             if (!$.isArray(formats)) {
1075                 formats = [formats];
1076             }
1077             if (!$.isArray(fields)) {
1078                 fields = [fields];
1079             }
1080             showFields = this.options.get('tooltipFormatFieldlist');
1081             showFieldsKey = this.options.get('tooltipFormatFieldlistKey');
1082             if (showFields && showFieldsKey) {
1083                 // user-selected ordering of fields
1084                 newFields = [];
1085                 for (i = fields.length; i--;) {
1086                     fv = fields[i][showFieldsKey];
1087                     if ((j = $.inArray(fv, showFields)) != -1) {
1088                         newFields[j] = fields[i];
1089                     }
1090                 }
1091                 fields = newFields;
1092             }
1093             formatlen = formats.length;
1094             fieldlen = fields.length;
1095             for (i = 0; i < formatlen; i++) {
1096                 format = formats[i];
1097                 if (typeof format === 'string') {
1098                     format = new SPFormat(format);
1099                 }
1100                 fclass = format.fclass || 'jqsfield';
1101                 for (j = 0; j < fieldlen; j++) {
1102                     if (!fields[j].isNull || !options.get('tooltipSkipNull')) {
1103                         $.extend(fields[j], {
1104                             prefix: options.get('tooltipPrefix'),
1105                             suffix: options.get('tooltipSuffix')
1106                         });
1107                         text = format.render(fields[j], options.get('tooltipValueLookups'), options);
1108                         entries.push('<div class="' + fclass + '">' + text + '</div>');
1109                     }
1110                 }
1111             }
1112             if (entries.length) {
1113                 return header + entries.join('\n');
1114             }
1115             return '';
1116         },
1117
1118         getCurrentRegionFields: function () {},
1119
1120         calcHighlightColor: function (color, options) {
1121             var highlightColor = options.get('highlightColor'),
1122                 lighten = options.get('highlightLighten'),
1123                 parse, mult, rgbnew, i;
1124             if (highlightColor) {
1125                 return highlightColor;
1126             }
1127             if (lighten) {
1128                 // extract RGB values
1129                 parse = /^#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec(color) || /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(color);
1130                 if (parse) {
1131                     rgbnew = [];
1132                     mult = color.length === 4 ? 16 : 1;
1133                     for (i = 0; i < 3; i++) {
1134                         rgbnew[i] = clipval(Math.round(parseInt(parse[i + 1], 16) * mult * lighten), 0, 255);
1135                     }
1136                     return 'rgb(' + rgbnew.join(',') + ')';
1137                 }
1138
1139             }
1140             return color;
1141         }
1142
1143     });
1144
1145     barHighlightMixin = {
1146         changeHighlight: function (highlight) {
1147             var currentRegion = this.currentRegion,
1148                 target = this.target,
1149                 shapeids = this.regionShapes[currentRegion],
1150                 newShapes;
1151             // will be null if the region value was null
1152             if (shapeids) {
1153                 newShapes = this.renderRegion(currentRegion, highlight);
1154                 if ($.isArray(newShapes) || $.isArray(shapeids)) {
1155                     target.replaceWithShapes(shapeids, newShapes);
1156                     this.regionShapes[currentRegion] = $.map(newShapes, function (newShape) {
1157                         return newShape.id;
1158                     });
1159                 } else {
1160                     target.replaceWithShape(shapeids, newShapes);
1161                     this.regionShapes[currentRegion] = newShapes.id;
1162                 }
1163             }
1164         },
1165
1166         render: function () {
1167             var values = this.values,
1168                 target = this.target,
1169                 regionShapes = this.regionShapes,
1170                 shapes, ids, i, j;
1171
1172             if (!this.cls._super.render.call(this)) {
1173                 return;
1174             }
1175             for (i = values.length; i--;) {
1176                 shapes = this.renderRegion(i);
1177                 if (shapes) {
1178                     if ($.isArray(shapes)) {
1179                         ids = [];
1180                         for (j = shapes.length; j--;) {
1181                             shapes[j].append();
1182                             ids.push(shapes[j].id);
1183                         }
1184                         regionShapes[i] = ids;
1185                     } else {
1186                         shapes.append();
1187                         regionShapes[i] = shapes.id; // store just the shapeid
1188                     }
1189                 } else {
1190                     // null value
1191                     regionShapes[i] = null;
1192                 }
1193             }
1194             target.render();
1195         }
1196     };
1197
1198     /**
1199      * Bar charts
1200      */
1201     $.fn.sparkline.bar = bar = createClass($.fn.sparkline._base, barHighlightMixin, {
1202         type: 'bar',
1203
1204         init: function (el, values, options, width, height) {
1205             var barWidth = parseInt(options.get('barWidth'), 10),
1206                 barSpacing = parseInt(options.get('barSpacing'), 10),
1207                 chartRangeMin = options.get('chartRangeMin'),
1208                 chartRangeMax = options.get('chartRangeMax'),
1209                 chartRangeClip = options.get('chartRangeClip'),
1210                 stackMin = Infinity,
1211                 stackMax = -Infinity,
1212                 isStackString, groupMin, groupMax, stackRanges,
1213                 numValues, i, vlen, range, zeroAxis, xaxisOffset, min, max, clipMin, clipMax,
1214                 stacked, vlist, j, slen, svals, val, yoffset, yMaxCalc, canvasHeightEf;
1215             bar._super.init.call(this, el, values, options, width, height);
1216
1217             // scan values to determine whether to stack bars
1218             for (i = 0, vlen = values.length; i < vlen; i++) {
1219                 val = values[i];
1220                 isStackString = typeof(val) === 'string' && val.indexOf(':') > -1;
1221                 if (isStackString || $.isArray(val)) {
1222                     stacked = true;
1223                     if (isStackString) {
1224                         val = values[i] = normalizeValues(val.split(':'));
1225                     }
1226                     val = remove(val, null); // min/max will treat null as zero
1227                     groupMin = Math.min.apply(Math, val);
1228                     groupMax = Math.max.apply(Math, val);
1229                     if (groupMin < stackMin) {
1230                         stackMin = groupMin;
1231                     }
1232                     if (groupMax > stackMax) {
1233                         stackMax = groupMax;
1234                     }
1235                 }
1236             }
1237
1238             this.stacked = stacked;
1239             this.regionShapes = {};
1240             this.barWidth = barWidth;
1241             this.barSpacing = barSpacing;
1242             this.totalBarWidth = barWidth + barSpacing;
1243             this.width = width = (values.length * barWidth) + ((values.length - 1) * barSpacing);
1244
1245             this.initTarget();
1246
1247             if (chartRangeClip) {
1248                 clipMin = chartRangeMin === undefined ? -Infinity : chartRangeMin;
1249                 clipMax = chartRangeMax === undefined ? Infinity : chartRangeMax;
1250             }
1251
1252             numValues = [];
1253             stackRanges = stacked ? [] : numValues;
1254             var stackTotals = [];
1255             var stackRangesNeg = [];
1256             for (i = 0, vlen = values.length; i < vlen; i++) {
1257                 if (stacked) {
1258                     vlist = values[i];
1259                     values[i] = svals = [];
1260                     stackTotals[i] = 0;
1261                     stackRanges[i] = stackRangesNeg[i] = 0;
1262                     for (j = 0, slen = vlist.length; j < slen; j++) {
1263                         val = svals[j] = chartRangeClip ? clipval(vlist[j], clipMin, clipMax) : vlist[j];
1264                         if (val !== null) {
1265                             if (val > 0) {
1266                                 stackTotals[i] += val;
1267                             }
1268                             if (stackMin < 0 && stackMax > 0) {
1269                                 if (val < 0) {
1270                                     stackRangesNeg[i] += Math.abs(val);
1271                                 } else {
1272                                     stackRanges[i] += val;
1273                                 }
1274                             } else {
1275                                 stackRanges[i] += Math.abs(val - (val < 0 ? stackMax : stackMin));
1276                             }
1277                             numValues.push(val);
1278                         }
1279                     }
1280                 } else {
1281                     val = chartRangeClip ? clipval(values[i], clipMin, clipMax) : values[i];
1282                     val = values[i] = normalizeValue(val);
1283                     if (val !== null) {
1284                         numValues.push(val);
1285                     }
1286                 }
1287             }
1288             this.max = max = Math.max.apply(Math, numValues);
1289             this.min = min = Math.min.apply(Math, numValues);
1290             this.stackMax = stackMax = stacked ? Math.max.apply(Math, stackTotals) : max;
1291             this.stackMin = stackMin = stacked ? Math.min.apply(Math, numValues) : min;
1292
1293             if (options.get('chartRangeMin') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMin') < min)) {
1294                 min = options.get('chartRangeMin');
1295             }
1296             if (options.get('chartRangeMax') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMax') > max)) {
1297                 max = options.get('chartRangeMax');
1298             }
1299
1300             this.zeroAxis = zeroAxis = options.get('zeroAxis', true);
1301             if (min <= 0 && max >= 0 && zeroAxis) {
1302                 xaxisOffset = 0;
1303             } else if (zeroAxis == false) {
1304                 xaxisOffset = min;
1305             } else if (min > 0) {
1306                 xaxisOffset = min;
1307             } else {
1308                 xaxisOffset = max;
1309             }
1310             this.xaxisOffset = xaxisOffset;
1311
1312             range = stacked ? (Math.max.apply(Math, stackRanges) + Math.max.apply(Math, stackRangesNeg)) : max - min;
1313
1314             // as we plot zero/min values a single pixel line, we add a pixel to all other
1315             // values - Reduce the effective canvas size to suit
1316             this.canvasHeightEf = (zeroAxis && min < 0) ? this.canvasHeight - 2 : this.canvasHeight - 1;
1317
1318             if (min < xaxisOffset) {
1319                 yMaxCalc = (stacked && max >= 0) ? stackMax : max;
1320                 yoffset = (yMaxCalc - xaxisOffset) / range * this.canvasHeight;
1321                 if (yoffset !== Math.ceil(yoffset)) {
1322                     this.canvasHeightEf -= 2;
1323                     yoffset = Math.ceil(yoffset);
1324                 }
1325             } else {
1326                 yoffset = this.canvasHeight;
1327             }
1328             this.yoffset = yoffset;
1329
1330             if ($.isArray(options.get('colorMap'))) {
1331                 this.colorMapByIndex = options.get('colorMap');
1332                 this.colorMapByValue = null;
1333             } else {
1334                 this.colorMapByIndex = null;
1335                 this.colorMapByValue = options.get('colorMap');
1336                 if (this.colorMapByValue && this.colorMapByValue.get === undefined) {
1337                     this.colorMapByValue = new RangeMap(this.colorMapByValue);
1338                 }
1339             }
1340
1341             this.range = range;
1342         },
1343
1344         getRegion: function (el, x, y) {
1345             var result = Math.floor(x / this.totalBarWidth);
1346             return (result < 0 || result >= this.values.length) ? undefined : result;
1347         },
1348
1349         getCurrentRegionFields: function () {
1350             var currentRegion = this.currentRegion,
1351                 values = ensureArray(this.values[currentRegion]),
1352                 result = [],
1353                 value, i;
1354             for (i = values.length; i--;) {
1355                 value = values[i];
1356                 result.push({
1357                     isNull: value === null,
1358                     value: value,
1359                     color: this.calcColor(i, value, currentRegion),
1360                     offset: currentRegion
1361                 });
1362             }
1363             return result;
1364         },
1365
1366         calcColor: function (stacknum, value, valuenum) {
1367             var colorMapByIndex = this.colorMapByIndex,
1368                 colorMapByValue = this.colorMapByValue,
1369                 options = this.options,
1370                 color, newColor;
1371             if (this.stacked) {
1372                 color = options.get('stackedBarColor');
1373             } else {
1374                 color = (value < 0) ? options.get('negBarColor') : options.get('barColor');
1375             }
1376             if (value === 0 && options.get('zeroColor') !== undefined) {
1377                 color = options.get('zeroColor');
1378             }
1379             if (colorMapByValue && (newColor = colorMapByValue.get(value))) {
1380                 color = newColor;
1381             } else if (colorMapByIndex && colorMapByIndex.length > valuenum) {
1382                 color = colorMapByIndex[valuenum];
1383             }
1384             return $.isArray(color) ? color[stacknum % color.length] : color;
1385         },
1386
1387         /**
1388          * Render bar(s) for a region
1389          */
1390         renderRegion: function (valuenum, highlight) {
1391             var vals = this.values[valuenum],
1392                 options = this.options,
1393                 xaxisOffset = this.xaxisOffset,
1394                 result = [],
1395                 range = this.range,
1396                 stacked = this.stacked,
1397                 target = this.target,
1398                 x = valuenum * this.totalBarWidth,
1399                 canvasHeightEf = this.canvasHeightEf,
1400                 yoffset = this.yoffset,
1401                 y, height, color, isNull, yoffsetNeg, i, valcount, val, minPlotted, allMin;
1402
1403             vals = $.isArray(vals) ? vals : [vals];
1404             valcount = vals.length;
1405             val = vals[0];
1406             isNull = all(null, vals);
1407             allMin = all(xaxisOffset, vals, true);
1408
1409             if (isNull) {
1410                 if (options.get('nullColor')) {
1411                     color = highlight ? options.get('nullColor') : this.calcHighlightColor(options.get('nullColor'), options);
1412                     y = (yoffset > 0) ? yoffset - 1 : yoffset;
1413                     return target.drawRect(x, y, this.barWidth - 1, 0, color, color);
1414                 } else {
1415                     return undefined;
1416                 }
1417             }
1418             yoffsetNeg = yoffset;
1419             for (i = 0; i < valcount; i++) {
1420                 val = vals[i];
1421
1422                 if (stacked && val === xaxisOffset) {
1423                     if (!allMin || minPlotted) {
1424                         continue;
1425                     }
1426                     minPlotted = true;
1427                 }
1428
1429                 if (range > 0) {
1430                     height = Math.floor(canvasHeightEf * ((Math.abs(val - xaxisOffset) / range))) + 1;
1431                 } else {
1432                     height = 1;
1433                 }
1434                 if (val < xaxisOffset || (val === xaxisOffset && yoffset === 0)) {
1435                     y = yoffsetNeg;
1436                     yoffsetNeg += height;
1437                 } else {
1438                     y = yoffset - height;
1439                     yoffset -= height;
1440                 }
1441                 color = this.calcColor(i, val, valuenum);
1442                 if (highlight) {
1443                     color = this.calcHighlightColor(color, options);
1444                 }
1445                 result.push(target.drawRect(x, y, this.barWidth - 1, height - 1, color, color));
1446             }
1447             if (result.length === 1) {
1448                 return result[0];
1449             }
1450             return result;
1451         }
1452     });
1453
1454     // Setup a very simple "virtual canvas" to make drawing the few shapes we need easier
1455     // This is accessible as $(foo).simpledraw()
1456
1457     VShape = createClass({
1458         init: function (target, id, type, args) {
1459             this.target = target;
1460             this.id = id;
1461             this.type = type;
1462             this.args = args;
1463         },
1464         append: function () {
1465             this.target.appendShape(this);
1466             return this;
1467         }
1468     });
1469
1470     VCanvas_base = createClass({
1471         _pxregex: /(\d+)(px)?\s*$/i,
1472
1473         init: function (width, height, target) {
1474             if (!width) {
1475                 return;
1476             }
1477             this.width = width;
1478             this.height = height;
1479             this.target = target;
1480             this.lastShapeId = null;
1481             if (target[0]) {
1482                 target = target[0];
1483             }
1484             $.data(target, '_jqs_vcanvas', this);
1485         },
1486
1487         drawLine: function (x1, y1, x2, y2, lineColor, lineWidth) {
1488             return this.drawShape([[x1, y1], [x2, y2]], lineColor, lineWidth);
1489         },
1490
1491         drawShape: function (path, lineColor, fillColor, lineWidth) {
1492             return this._genShape('Shape', [path, lineColor, fillColor, lineWidth]);
1493         },
1494
1495         drawCircle: function (x, y, radius, lineColor, fillColor, lineWidth) {
1496             return this._genShape('Circle', [x, y, radius, lineColor, fillColor, lineWidth]);
1497         },
1498
1499         drawPieSlice: function (x, y, radius, startAngle, endAngle, lineColor, fillColor) {
1500             return this._genShape('PieSlice', [x, y, radius, startAngle, endAngle, lineColor, fillColor]);
1501         },
1502
1503         drawRect: function (x, y, width, height, lineColor, fillColor) {
1504             return this._genShape('Rect', [x, y, width, height, lineColor, fillColor]);
1505         },
1506
1507         getElement: function () {
1508             return this.canvas;
1509         },
1510
1511         /**
1512          * Return the most recently inserted shape id
1513          */
1514         getLastShapeId: function () {
1515             return this.lastShapeId;
1516         },
1517
1518         /**
1519          * Clear and reset the canvas
1520          */
1521         reset: function () {
1522             alert('reset not implemented');
1523         },
1524
1525         _insert: function (el, target) {
1526             $(target).html(el);
1527         },
1528
1529         /**
1530          * Calculate the pixel dimensions of the canvas
1531          */
1532         _calculatePixelDims: function (width, height, canvas) {
1533             // XXX This should probably be a configurable option
1534             var match;
1535             match = this._pxregex.exec(height);
1536             if (match) {
1537                 this.pixelHeight = match[1];
1538             } else {
1539                 this.pixelHeight = $(canvas).height();
1540             }
1541             match = this._pxregex.exec(width);
1542             if (match) {
1543                 this.pixelWidth = match[1];
1544             } else {
1545                 this.pixelWidth = $(canvas).width();
1546             }
1547         },
1548
1549         /**
1550          * Generate a shape object and id for later rendering
1551          */
1552         _genShape: function (shapetype, shapeargs) {
1553             var id = shapeCount++;
1554             shapeargs.unshift(id);
1555             return new VShape(this, id, shapetype, shapeargs);
1556         },
1557
1558         /**
1559          * Add a shape to the end of the render queue
1560          */
1561         appendShape: function (shape) {
1562             alert('appendShape not implemented');
1563         },
1564
1565         /**
1566          * Replace one shape with another
1567          */
1568         replaceWithShape: function (shapeid, shape) {
1569             alert('replaceWithShape not implemented');
1570         },
1571
1572         /**
1573          * Insert one shape after another in the render queue
1574          */
1575         insertAfterShape: function (shapeid, shape) {
1576             alert('insertAfterShape not implemented');
1577         },
1578
1579         /**
1580          * Remove a shape from the queue
1581          */
1582         removeShapeId: function (shapeid) {
1583             alert('removeShapeId not implemented');
1584         },
1585
1586         /**
1587          * Find a shape at the specified x/y co-ordinates
1588          */
1589         getShapeAt: function (el, x, y) {
1590             alert('getShapeAt not implemented');
1591         },
1592
1593         /**
1594          * Render all queued shapes onto the canvas
1595          */
1596         render: function () {
1597             alert('render not implemented');
1598         }
1599     });
1600
1601     VCanvas_canvas = createClass(VCanvas_base, {
1602         init: function (width, height, target, interact) {
1603             VCanvas_canvas._super.init.call(this, width, height, target);
1604             this.canvas = document.createElement('canvas');
1605             if (target[0]) {
1606                 target = target[0];
1607             }
1608             $.data(target, '_jqs_vcanvas', this);
1609             $(this.canvas).css({ display: 'inline-block', width: width, height: height, verticalAlign: 'top' });
1610             this._insert(this.canvas, target);
1611             this._calculatePixelDims(width, height, this.canvas);
1612             this.canvas.width = this.pixelWidth;
1613             this.canvas.height = this.pixelHeight;
1614             this.interact = interact;
1615             this.shapes = {};
1616             this.shapeseq = [];
1617             this.currentTargetShapeId = undefined;
1618             $(this.canvas).css({width: this.pixelWidth, height: this.pixelHeight});
1619         },
1620
1621         _getContext: function (lineColor, fillColor, lineWidth) {
1622             var context = this.canvas.getContext('2d');
1623             if (lineColor !== undefined) {
1624                 context.strokeStyle = lineColor;
1625             }
1626             context.lineWidth = lineWidth === undefined ? 1 : lineWidth;
1627             if (fillColor !== undefined) {
1628                 context.fillStyle = fillColor;
1629             }
1630             return context;
1631         },
1632
1633         reset: function () {
1634             var context = this._getContext();
1635             context.clearRect(0, 0, this.pixelWidth, this.pixelHeight);
1636             this.shapes = {};
1637             this.shapeseq = [];
1638             this.currentTargetShapeId = undefined;
1639         },
1640
1641         _drawShape: function (shapeid, path, lineColor, fillColor, lineWidth) {
1642             var context = this._getContext(lineColor, fillColor, lineWidth),
1643                 i, plen;
1644             context.beginPath();
1645             context.moveTo(path[0][0] + 0.5, path[0][1] + 0.5);
1646             for (i = 1, plen = path.length; i < plen; i++) {
1647                 context.lineTo(path[i][0] + 0.5, path[i][1] + 0.5); // the 0.5 offset gives us crisp pixel-width lines
1648             }
1649             if (lineColor !== undefined) {
1650                 context.stroke();
1651             }
1652             if (fillColor !== undefined) {
1653                 context.fill();
1654             }
1655             if (this.targetX !== undefined && this.targetY !== undefined &&
1656                 context.isPointInPath(this.targetX, this.targetY)) {
1657                 this.currentTargetShapeId = shapeid;
1658             }
1659         },
1660
1661         _drawCircle: function (shapeid, x, y, radius, lineColor, fillColor, lineWidth) {
1662             var context = this._getContext(lineColor, fillColor, lineWidth);
1663             context.beginPath();
1664             context.arc(x, y, radius, 0, 2 * Math.PI, false);
1665             if (this.targetX !== undefined && this.targetY !== undefined &&
1666                 context.isPointInPath(this.targetX, this.targetY)) {
1667                 this.currentTargetShapeId = shapeid;
1668             }
1669             if (lineColor !== undefined) {
1670                 context.stroke();
1671             }
1672             if (fillColor !== undefined) {
1673                 context.fill();
1674             }
1675         },
1676
1677         _drawPieSlice: function (shapeid, x, y, radius, startAngle, endAngle, lineColor, fillColor) {
1678             var context = this._getContext(lineColor, fillColor);
1679             context.beginPath();
1680             context.moveTo(x, y);
1681             context.arc(x, y, radius, startAngle, endAngle, false);
1682             context.lineTo(x, y);
1683             context.closePath();
1684             if (lineColor !== undefined) {
1685                 context.stroke();
1686             }
1687             if (fillColor) {
1688                 context.fill();
1689             }
1690             if (this.targetX !== undefined && this.targetY !== undefined &&
1691                 context.isPointInPath(this.targetX, this.targetY)) {
1692                 this.currentTargetShapeId = shapeid;
1693             }
1694         },
1695
1696         _drawRect: function (shapeid, x, y, width, height, lineColor, fillColor) {
1697             return this._drawShape(shapeid, [[x, y], [x + width, y], [x + width, y + height], [x, y + height], [x, y]], lineColor, fillColor);
1698         },
1699
1700         appendShape: function (shape) {
1701             this.shapes[shape.id] = shape;
1702             this.shapeseq.push(shape.id);
1703             this.lastShapeId = shape.id;
1704             return shape.id;
1705         },
1706
1707         replaceWithShape: function (shapeid, shape) {
1708             var shapeseq = this.shapeseq,
1709                 i;
1710             this.shapes[shape.id] = shape;
1711             for (i = shapeseq.length; i--;) {
1712                 if (shapeseq[i] == shapeid) {
1713                     shapeseq[i] = shape.id;
1714                 }
1715             }
1716             delete this.shapes[shapeid];
1717         },
1718
1719         replaceWithShapes: function (shapeids, shapes) {
1720             var shapeseq = this.shapeseq,
1721                 shapemap = {},
1722                 sid, i, first;
1723
1724             for (i = shapeids.length; i--;) {
1725                 shapemap[shapeids[i]] = true;
1726             }
1727             for (i = shapeseq.length; i--;) {
1728                 sid = shapeseq[i];
1729                 if (shapemap[sid]) {
1730                     shapeseq.splice(i, 1);
1731                     delete this.shapes[sid];
1732                     first = i;
1733                 }
1734             }
1735             for (i = shapes.length; i--;) {
1736                 shapeseq.splice(first, 0, shapes[i].id);
1737                 this.shapes[shapes[i].id] = shapes[i];
1738             }
1739
1740         },
1741
1742         insertAfterShape: function (shapeid, shape) {
1743             var shapeseq = this.shapeseq,
1744                 i;
1745             for (i = shapeseq.length; i--;) {
1746                 if (shapeseq[i] === shapeid) {
1747                     shapeseq.splice(i + 1, 0, shape.id);
1748                     this.shapes[shape.id] = shape;
1749                     return;
1750                 }
1751             }
1752         },
1753
1754         removeShapeId: function (shapeid) {
1755             var shapeseq = this.shapeseq,
1756                 i;
1757             for (i = shapeseq.length; i--;) {
1758                 if (shapeseq[i] === shapeid) {
1759                     shapeseq.splice(i, 1);
1760                     break;
1761                 }
1762             }
1763             delete this.shapes[shapeid];
1764         },
1765
1766         getShapeAt: function (el, x, y) {
1767             this.targetX = x;
1768             this.targetY = y;
1769             this.render();
1770             return this.currentTargetShapeId;
1771         },
1772
1773         render: function () {
1774             var shapeseq = this.shapeseq,
1775                 shapes = this.shapes,
1776                 shapeCount = shapeseq.length,
1777                 context = this._getContext(),
1778                 shapeid, shape, i;
1779             context.clearRect(0, 0, this.pixelWidth, this.pixelHeight);
1780             for (i = 0; i < shapeCount; i++) {
1781                 shapeid = shapeseq[i];
1782                 shape = shapes[shapeid];
1783                 this['_draw' + shape.type].apply(this, shape.args);
1784             }
1785             if (!this.interact) {
1786                 // not interactive so no need to keep the shapes array
1787                 this.shapes = {};
1788                 this.shapeseq = [];
1789             }
1790         }
1791
1792     });
1793 }))}(document, Math));