]> git.sesse.net Git - remoteglot/blob - www/js/jquery.sparkline.js
Remove some chart types we don't need; kills 16 kb off the minified (non-gzipped...
[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, VCanvas_vml, 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 if (document.namespaces && !document.namespaces.v) {
468                 // VML is available
469                 document.namespaces.add('v', 'urn:schemas-microsoft-com:vml', '#default#VML');
470                 $.fn.sparkline.canvas = function(width, height, target, interact) {
471                     return new VCanvas_vml(width, height, target);
472                 };
473             } else {
474                 // Neither Canvas nor VML are available
475                 $.fn.sparkline.canvas = false;
476                 return false;
477             }
478         }
479
480         if (width === undefined) {
481             width = $(this).innerWidth();
482         }
483         if (height === undefined) {
484             height = $(this).innerHeight();
485         }
486
487         target = $.fn.sparkline.canvas(width, height, this, interact);
488
489         mhandler = $(this).data('_jqs_mhandler');
490         if (mhandler) {
491             mhandler.registerCanvas(target);
492         }
493         return target;
494     };
495
496     $.fn.cleardraw = function () {
497         var target = this.data('_jqs_vcanvas');
498         if (target) {
499             target.reset();
500         }
501     };
502
503     $.RangeMapClass = RangeMap = createClass({
504         init: function (map) {
505             var key, range, rangelist = [];
506             for (key in map) {
507                 if (map.hasOwnProperty(key) && typeof key === 'string' && key.indexOf(':') > -1) {
508                     range = key.split(':');
509                     range[0] = range[0].length === 0 ? -Infinity : parseFloat(range[0]);
510                     range[1] = range[1].length === 0 ? Infinity : parseFloat(range[1]);
511                     range[2] = map[key];
512                     rangelist.push(range);
513                 }
514             }
515             this.map = map;
516             this.rangelist = rangelist || false;
517         },
518
519         get: function (value) {
520             var rangelist = this.rangelist,
521                 i, range, result;
522             if ((result = this.map[value]) !== undefined) {
523                 return result;
524             }
525             if (rangelist) {
526                 for (i = rangelist.length; i--;) {
527                     range = rangelist[i];
528                     if (range[0] <= value && range[1] >= value) {
529                         return range[2];
530                     }
531                 }
532             }
533             return undefined;
534         }
535     });
536
537     // Convenience function
538     $.range_map = function(map) {
539         return new RangeMap(map);
540     };
541
542     MouseHandler = createClass({
543         init: function (el, options) {
544             var $el = $(el);
545             this.$el = $el;
546             this.options = options;
547             this.currentPageX = 0;
548             this.currentPageY = 0;
549             this.el = el;
550             this.splist = [];
551             this.tooltip = null;
552             this.over = false;
553             this.displayTooltips = !options.get('disableTooltips');
554             this.highlightEnabled = !options.get('disableHighlight');
555         },
556
557         registerSparkline: function (sp) {
558             this.splist.push(sp);
559             if (this.over) {
560                 this.updateDisplay();
561             }
562         },
563
564         registerCanvas: function (canvas) {
565             var $canvas = $(canvas.canvas);
566             this.canvas = canvas;
567             this.$canvas = $canvas;
568             $canvas.mouseenter($.proxy(this.mouseenter, this));
569             $canvas.mouseleave($.proxy(this.mouseleave, this));
570             $canvas.click($.proxy(this.mouseclick, this));
571         },
572
573         reset: function (removeTooltip) {
574             this.splist = [];
575             if (this.tooltip && removeTooltip) {
576                 this.tooltip.remove();
577                 this.tooltip = undefined;
578             }
579         },
580
581         mouseclick: function (e) {
582             var clickEvent = $.Event('sparklineClick');
583             clickEvent.originalEvent = e;
584             clickEvent.sparklines = this.splist;
585             this.$el.trigger(clickEvent);
586         },
587
588         mouseenter: function (e) {
589             $(document.body).unbind('mousemove.jqs');
590             $(document.body).bind('mousemove.jqs', $.proxy(this.mousemove, this));
591             this.over = true;
592             this.currentPageX = e.pageX;
593             this.currentPageY = e.pageY;
594             this.currentEl = e.target;
595             if (!this.tooltip && this.displayTooltips) {
596                 this.tooltip = new Tooltip(this.options);
597                 this.tooltip.updatePosition(e.pageX, e.pageY);
598             }
599             this.updateDisplay();
600         },
601
602         mouseleave: function () {
603             $(document.body).unbind('mousemove.jqs');
604             var splist = this.splist,
605                  spcount = splist.length,
606                  needsRefresh = false,
607                  sp, i;
608             this.over = false;
609             this.currentEl = null;
610
611             if (this.tooltip) {
612                 this.tooltip.remove();
613                 this.tooltip = null;
614             }
615
616             for (i = 0; i < spcount; i++) {
617                 sp = splist[i];
618                 if (sp.clearRegionHighlight()) {
619                     needsRefresh = true;
620                 }
621             }
622
623             if (needsRefresh) {
624                 this.canvas.render();
625             }
626         },
627
628         mousemove: function (e) {
629             this.currentPageX = e.pageX;
630             this.currentPageY = e.pageY;
631             this.currentEl = e.target;
632             if (this.tooltip) {
633                 this.tooltip.updatePosition(e.pageX, e.pageY);
634             }
635             this.updateDisplay();
636         },
637
638         updateDisplay: function () {
639             var splist = this.splist,
640                  spcount = splist.length,
641                  needsRefresh = false,
642                  offset = this.$canvas.offset(),
643                  localX = this.currentPageX - offset.left,
644                  localY = this.currentPageY - offset.top,
645                  tooltiphtml, sp, i, result, changeEvent;
646             if (!this.over) {
647                 return;
648             }
649             for (i = 0; i < spcount; i++) {
650                 sp = splist[i];
651                 result = sp.setRegionHighlight(this.currentEl, localX, localY);
652                 if (result) {
653                     needsRefresh = true;
654                 }
655             }
656             if (needsRefresh) {
657                 changeEvent = $.Event('sparklineRegionChange');
658                 changeEvent.sparklines = this.splist;
659                 this.$el.trigger(changeEvent);
660                 if (this.tooltip) {
661                     tooltiphtml = '';
662                     for (i = 0; i < spcount; i++) {
663                         sp = splist[i];
664                         tooltiphtml += sp.getCurrentRegionTooltip();
665                     }
666                     this.tooltip.setContent(tooltiphtml);
667                 }
668                 if (!this.disableHighlight) {
669                     this.canvas.render();
670                 }
671             }
672             if (result === null) {
673                 this.mouseleave();
674             }
675         }
676     });
677
678
679     Tooltip = createClass({
680         sizeStyle: 'position: static !important;' +
681             'display: block !important;' +
682             'visibility: hidden !important;' +
683             'float: left !important;',
684
685         init: function (options) {
686             var tooltipClassname = options.get('tooltipClassname', 'jqstooltip'),
687                 sizetipStyle = this.sizeStyle,
688                 offset;
689             this.container = options.get('tooltipContainer') || document.body;
690             this.tooltipOffsetX = options.get('tooltipOffsetX', 10);
691             this.tooltipOffsetY = options.get('tooltipOffsetY', 12);
692             // remove any previous lingering tooltip
693             $('#jqssizetip').remove();
694             $('#jqstooltip').remove();
695             this.sizetip = $('<div/>', {
696                 id: 'jqssizetip',
697                 style: sizetipStyle,
698                 'class': tooltipClassname
699             });
700             this.tooltip = $('<div/>', {
701                 id: 'jqstooltip',
702                 'class': tooltipClassname
703             }).appendTo(this.container);
704             // account for the container's location
705             offset = this.tooltip.offset();
706             this.offsetLeft = offset.left;
707             this.offsetTop = offset.top;
708             this.hidden = true;
709             $(window).unbind('resize.jqs scroll.jqs');
710             $(window).bind('resize.jqs scroll.jqs', $.proxy(this.updateWindowDims, this));
711             this.updateWindowDims();
712         },
713
714         updateWindowDims: function () {
715             this.scrollTop = $(window).scrollTop();
716             this.scrollLeft = $(window).scrollLeft();
717             this.scrollRight = this.scrollLeft + $(window).width();
718             this.updatePosition();
719         },
720
721         getSize: function (content) {
722             this.sizetip.html(content).appendTo(this.container);
723             this.width = this.sizetip.width() + 1;
724             this.height = this.sizetip.height();
725             this.sizetip.remove();
726         },
727
728         setContent: function (content) {
729             if (!content) {
730                 this.tooltip.css('visibility', 'hidden');
731                 this.hidden = true;
732                 return;
733             }
734             this.getSize(content);
735             this.tooltip.html(content)
736                 .css({
737                     'width': this.width,
738                     'height': this.height,
739                     'visibility': 'visible'
740                 });
741             if (this.hidden) {
742                 this.hidden = false;
743                 this.updatePosition();
744             }
745         },
746
747         updatePosition: function (x, y) {
748             if (x === undefined) {
749                 if (this.mousex === undefined) {
750                     return;
751                 }
752                 x = this.mousex - this.offsetLeft;
753                 y = this.mousey - this.offsetTop;
754
755             } else {
756                 this.mousex = x = x - this.offsetLeft;
757                 this.mousey = y = y - this.offsetTop;
758             }
759             if (!this.height || !this.width || this.hidden) {
760                 return;
761             }
762
763             y -= this.height + this.tooltipOffsetY;
764             x += this.tooltipOffsetX;
765
766             if (y < this.scrollTop) {
767                 y = this.scrollTop;
768             }
769             if (x < this.scrollLeft) {
770                 x = this.scrollLeft;
771             } else if (x + this.width > this.scrollRight) {
772                 x = this.scrollRight - this.width;
773             }
774
775             this.tooltip.css({
776                 'left': x,
777                 'top': y
778             });
779         },
780
781         remove: function () {
782             this.tooltip.remove();
783             this.sizetip.remove();
784             this.sizetip = this.tooltip = undefined;
785             $(window).unbind('resize.jqs scroll.jqs');
786         }
787     });
788
789     initStyles = function() {
790         addCSS(defaultStyles);
791     };
792
793     $(initStyles);
794
795     pending = [];
796     $.fn.sparkline = function (userValues, userOptions) {
797         return this.each(function () {
798             var options = new $.fn.sparkline.options(this, userOptions),
799                  $this = $(this),
800                  render, i;
801             render = function () {
802                 var values, width, height, tmp, mhandler, sp, vals;
803                 if (userValues === 'html' || userValues === undefined) {
804                     vals = this.getAttribute(options.get('tagValuesAttribute'));
805                     if (vals === undefined || vals === null) {
806                         vals = $this.html();
807                     }
808                     values = vals.replace(/(^\s*<!--)|(-->\s*$)|\s+/g, '').split(',');
809                 } else {
810                     values = userValues;
811                 }
812
813                 width = options.get('width') === 'auto' ? values.length * options.get('defaultPixelsPerValue') : options.get('width');
814                 if (options.get('height') === 'auto') {
815                     if (!options.get('composite') || !$.data(this, '_jqs_vcanvas')) {
816                         // must be a better way to get the line height
817                         tmp = document.createElement('span');
818                         tmp.innerHTML = 'a';
819                         $this.html(tmp);
820                         height = $(tmp).innerHeight() || $(tmp).height();
821                         $(tmp).remove();
822                         tmp = null;
823                     }
824                 } else {
825                     height = options.get('height');
826                 }
827
828                 if (!options.get('disableInteraction')) {
829                     mhandler = $.data(this, '_jqs_mhandler');
830                     if (!mhandler) {
831                         mhandler = new MouseHandler(this, options);
832                         $.data(this, '_jqs_mhandler', mhandler);
833                     } else if (!options.get('composite')) {
834                         mhandler.reset();
835                     }
836                 } else {
837                     mhandler = false;
838                 }
839
840                 if (options.get('composite') && !$.data(this, '_jqs_vcanvas')) {
841                     if (!$.data(this, '_jqs_errnotify')) {
842                         alert('Attempted to attach a composite sparkline to an element with no existing sparkline');
843                         $.data(this, '_jqs_errnotify', true);
844                     }
845                     return;
846                 }
847
848                 sp = new $.fn.sparkline[options.get('type')](this, values, options, width, height);
849
850                 sp.render();
851
852                 if (mhandler) {
853                     mhandler.registerSparkline(sp);
854                 }
855             };
856             if (($(this).html() && !options.get('disableHiddenCheck') && $(this).is(':hidden')) || !$(this).parents('body').length) {
857                 if (!options.get('composite') && $.data(this, '_jqs_pending')) {
858                     // remove any existing references to the element
859                     for (i = pending.length; i; i--) {
860                         if (pending[i - 1][0] == this) {
861                             pending.splice(i - 1, 1);
862                         }
863                     }
864                 }
865                 pending.push([this, render]);
866                 $.data(this, '_jqs_pending', true);
867             } else {
868                 render.call(this);
869             }
870         });
871     };
872
873     $.fn.sparkline.defaults = getDefaults();
874
875
876     $.sparkline_display_visible = function () {
877         var el, i, pl;
878         var done = [];
879         for (i = 0, pl = pending.length; i < pl; i++) {
880             el = pending[i][0];
881             if ($(el).is(':visible') && !$(el).parents().is(':hidden')) {
882                 pending[i][1].call(el);
883                 $.data(pending[i][0], '_jqs_pending', false);
884                 done.push(i);
885             } else if (!$(el).closest('html').length && !$.data(el, '_jqs_pending')) {
886                 // element has been inserted and removed from the DOM
887                 // If it was not yet inserted into the dom then the .data request
888                 // will return true.
889                 // removing from the dom causes the data to be removed.
890                 $.data(pending[i][0], '_jqs_pending', false);
891                 done.push(i);
892             }
893         }
894         for (i = done.length; i; i--) {
895             pending.splice(done[i - 1], 1);
896         }
897     };
898
899
900     /**
901      * User option handler
902      */
903     $.fn.sparkline.options = createClass({
904         init: function (tag, userOptions) {
905             var extendedOptions, defaults, base, tagOptionType;
906             this.userOptions = userOptions = userOptions || {};
907             this.tag = tag;
908             this.tagValCache = {};
909             defaults = $.fn.sparkline.defaults;
910             base = defaults.common;
911             this.tagOptionsPrefix = userOptions.enableTagOptions && (userOptions.tagOptionsPrefix || base.tagOptionsPrefix);
912
913             tagOptionType = this.getTagSetting('type');
914             if (tagOptionType === UNSET_OPTION) {
915                 extendedOptions = defaults[userOptions.type || base.type];
916             } else {
917                 extendedOptions = defaults[tagOptionType];
918             }
919             this.mergedOptions = $.extend({}, base, extendedOptions, userOptions);
920         },
921
922
923         getTagSetting: function (key) {
924             var prefix = this.tagOptionsPrefix,
925                 val, i, pairs, keyval;
926             if (prefix === false || prefix === undefined) {
927                 return UNSET_OPTION;
928             }
929             if (this.tagValCache.hasOwnProperty(key)) {
930                 val = this.tagValCache.key;
931             } else {
932                 val = this.tag.getAttribute(prefix + key);
933                 if (val === undefined || val === null) {
934                     val = UNSET_OPTION;
935                 } else if (val.substr(0, 1) === '[') {
936                     val = val.substr(1, val.length - 2).split(',');
937                     for (i = val.length; i--;) {
938                         val[i] = normalizeValue(val[i].replace(/(^\s*)|(\s*$)/g, ''));
939                     }
940                 } else if (val.substr(0, 1) === '{') {
941                     pairs = val.substr(1, val.length - 2).split(',');
942                     val = {};
943                     for (i = pairs.length; i--;) {
944                         keyval = pairs[i].split(':', 2);
945                         val[keyval[0].replace(/(^\s*)|(\s*$)/g, '')] = normalizeValue(keyval[1].replace(/(^\s*)|(\s*$)/g, ''));
946                     }
947                 } else {
948                     val = normalizeValue(val);
949                 }
950                 this.tagValCache.key = val;
951             }
952             return val;
953         },
954
955         get: function (key, defaultval) {
956             var tagOption = this.getTagSetting(key),
957                 result;
958             if (tagOption !== UNSET_OPTION) {
959                 return tagOption;
960             }
961             return (result = this.mergedOptions[key]) === undefined ? defaultval : result;
962         }
963     });
964
965
966     $.fn.sparkline._base = createClass({
967         disabled: false,
968
969         init: function (el, values, options, width, height) {
970             this.el = el;
971             this.$el = $(el);
972             this.values = values;
973             this.options = options;
974             this.width = width;
975             this.height = height;
976             this.currentRegion = undefined;
977         },
978
979         /**
980          * Setup the canvas
981          */
982         initTarget: function () {
983             var interactive = !this.options.get('disableInteraction');
984             if (!(this.target = this.$el.simpledraw(this.width, this.height, this.options.get('composite'), interactive))) {
985                 this.disabled = true;
986             } else {
987                 this.canvasWidth = this.target.pixelWidth;
988                 this.canvasHeight = this.target.pixelHeight;
989             }
990         },
991
992         /**
993          * Actually render the chart to the canvas
994          */
995         render: function () {
996             if (this.disabled) {
997                 this.el.innerHTML = '';
998                 return false;
999             }
1000             return true;
1001         },
1002
1003         /**
1004          * Return a region id for a given x/y co-ordinate
1005          */
1006         getRegion: function (x, y) {
1007         },
1008
1009         /**
1010          * Highlight an item based on the moused-over x,y co-ordinate
1011          */
1012         setRegionHighlight: function (el, x, y) {
1013             var currentRegion = this.currentRegion,
1014                 highlightEnabled = !this.options.get('disableHighlight'),
1015                 newRegion;
1016             if (x > this.canvasWidth || y > this.canvasHeight || x < 0 || y < 0) {
1017                 return null;
1018             }
1019             newRegion = this.getRegion(el, x, y);
1020             if (currentRegion !== newRegion) {
1021                 if (currentRegion !== undefined && highlightEnabled) {
1022                     this.removeHighlight();
1023                 }
1024                 this.currentRegion = newRegion;
1025                 if (newRegion !== undefined && highlightEnabled) {
1026                     this.renderHighlight();
1027                 }
1028                 return true;
1029             }
1030             return false;
1031         },
1032
1033         /**
1034          * Reset any currently highlighted item
1035          */
1036         clearRegionHighlight: function () {
1037             if (this.currentRegion !== undefined) {
1038                 this.removeHighlight();
1039                 this.currentRegion = undefined;
1040                 return true;
1041             }
1042             return false;
1043         },
1044
1045         renderHighlight: function () {
1046             this.changeHighlight(true);
1047         },
1048
1049         removeHighlight: function () {
1050             this.changeHighlight(false);
1051         },
1052
1053         changeHighlight: function (highlight)  {},
1054
1055         /**
1056          * Fetch the HTML to display as a tooltip
1057          */
1058         getCurrentRegionTooltip: function () {
1059             var options = this.options,
1060                 header = '',
1061                 entries = [],
1062                 fields, formats, formatlen, fclass, text, i,
1063                 showFields, showFieldsKey, newFields, fv,
1064                 formatter, format, fieldlen, j;
1065             if (this.currentRegion === undefined) {
1066                 return '';
1067             }
1068             fields = this.getCurrentRegionFields();
1069             formatter = options.get('tooltipFormatter');
1070             if (formatter) {
1071                 return formatter(this, options, fields);
1072             }
1073             if (options.get('tooltipChartTitle')) {
1074                 header += '<div class="jqs jqstitle">' + options.get('tooltipChartTitle') + '</div>\n';
1075             }
1076             formats = this.options.get('tooltipFormat');
1077             if (!formats) {
1078                 return '';
1079             }
1080             if (!$.isArray(formats)) {
1081                 formats = [formats];
1082             }
1083             if (!$.isArray(fields)) {
1084                 fields = [fields];
1085             }
1086             showFields = this.options.get('tooltipFormatFieldlist');
1087             showFieldsKey = this.options.get('tooltipFormatFieldlistKey');
1088             if (showFields && showFieldsKey) {
1089                 // user-selected ordering of fields
1090                 newFields = [];
1091                 for (i = fields.length; i--;) {
1092                     fv = fields[i][showFieldsKey];
1093                     if ((j = $.inArray(fv, showFields)) != -1) {
1094                         newFields[j] = fields[i];
1095                     }
1096                 }
1097                 fields = newFields;
1098             }
1099             formatlen = formats.length;
1100             fieldlen = fields.length;
1101             for (i = 0; i < formatlen; i++) {
1102                 format = formats[i];
1103                 if (typeof format === 'string') {
1104                     format = new SPFormat(format);
1105                 }
1106                 fclass = format.fclass || 'jqsfield';
1107                 for (j = 0; j < fieldlen; j++) {
1108                     if (!fields[j].isNull || !options.get('tooltipSkipNull')) {
1109                         $.extend(fields[j], {
1110                             prefix: options.get('tooltipPrefix'),
1111                             suffix: options.get('tooltipSuffix')
1112                         });
1113                         text = format.render(fields[j], options.get('tooltipValueLookups'), options);
1114                         entries.push('<div class="' + fclass + '">' + text + '</div>');
1115                     }
1116                 }
1117             }
1118             if (entries.length) {
1119                 return header + entries.join('\n');
1120             }
1121             return '';
1122         },
1123
1124         getCurrentRegionFields: function () {},
1125
1126         calcHighlightColor: function (color, options) {
1127             var highlightColor = options.get('highlightColor'),
1128                 lighten = options.get('highlightLighten'),
1129                 parse, mult, rgbnew, i;
1130             if (highlightColor) {
1131                 return highlightColor;
1132             }
1133             if (lighten) {
1134                 // extract RGB values
1135                 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);
1136                 if (parse) {
1137                     rgbnew = [];
1138                     mult = color.length === 4 ? 16 : 1;
1139                     for (i = 0; i < 3; i++) {
1140                         rgbnew[i] = clipval(Math.round(parseInt(parse[i + 1], 16) * mult * lighten), 0, 255);
1141                     }
1142                     return 'rgb(' + rgbnew.join(',') + ')';
1143                 }
1144
1145             }
1146             return color;
1147         }
1148
1149     });
1150
1151     barHighlightMixin = {
1152         changeHighlight: function (highlight) {
1153             var currentRegion = this.currentRegion,
1154                 target = this.target,
1155                 shapeids = this.regionShapes[currentRegion],
1156                 newShapes;
1157             // will be null if the region value was null
1158             if (shapeids) {
1159                 newShapes = this.renderRegion(currentRegion, highlight);
1160                 if ($.isArray(newShapes) || $.isArray(shapeids)) {
1161                     target.replaceWithShapes(shapeids, newShapes);
1162                     this.regionShapes[currentRegion] = $.map(newShapes, function (newShape) {
1163                         return newShape.id;
1164                     });
1165                 } else {
1166                     target.replaceWithShape(shapeids, newShapes);
1167                     this.regionShapes[currentRegion] = newShapes.id;
1168                 }
1169             }
1170         },
1171
1172         render: function () {
1173             var values = this.values,
1174                 target = this.target,
1175                 regionShapes = this.regionShapes,
1176                 shapes, ids, i, j;
1177
1178             if (!this.cls._super.render.call(this)) {
1179                 return;
1180             }
1181             for (i = values.length; i--;) {
1182                 shapes = this.renderRegion(i);
1183                 if (shapes) {
1184                     if ($.isArray(shapes)) {
1185                         ids = [];
1186                         for (j = shapes.length; j--;) {
1187                             shapes[j].append();
1188                             ids.push(shapes[j].id);
1189                         }
1190                         regionShapes[i] = ids;
1191                     } else {
1192                         shapes.append();
1193                         regionShapes[i] = shapes.id; // store just the shapeid
1194                     }
1195                 } else {
1196                     // null value
1197                     regionShapes[i] = null;
1198                 }
1199             }
1200             target.render();
1201         }
1202     };
1203
1204     /**
1205      * Bar charts
1206      */
1207     $.fn.sparkline.bar = bar = createClass($.fn.sparkline._base, barHighlightMixin, {
1208         type: 'bar',
1209
1210         init: function (el, values, options, width, height) {
1211             var barWidth = parseInt(options.get('barWidth'), 10),
1212                 barSpacing = parseInt(options.get('barSpacing'), 10),
1213                 chartRangeMin = options.get('chartRangeMin'),
1214                 chartRangeMax = options.get('chartRangeMax'),
1215                 chartRangeClip = options.get('chartRangeClip'),
1216                 stackMin = Infinity,
1217                 stackMax = -Infinity,
1218                 isStackString, groupMin, groupMax, stackRanges,
1219                 numValues, i, vlen, range, zeroAxis, xaxisOffset, min, max, clipMin, clipMax,
1220                 stacked, vlist, j, slen, svals, val, yoffset, yMaxCalc, canvasHeightEf;
1221             bar._super.init.call(this, el, values, options, width, height);
1222
1223             // scan values to determine whether to stack bars
1224             for (i = 0, vlen = values.length; i < vlen; i++) {
1225                 val = values[i];
1226                 isStackString = typeof(val) === 'string' && val.indexOf(':') > -1;
1227                 if (isStackString || $.isArray(val)) {
1228                     stacked = true;
1229                     if (isStackString) {
1230                         val = values[i] = normalizeValues(val.split(':'));
1231                     }
1232                     val = remove(val, null); // min/max will treat null as zero
1233                     groupMin = Math.min.apply(Math, val);
1234                     groupMax = Math.max.apply(Math, val);
1235                     if (groupMin < stackMin) {
1236                         stackMin = groupMin;
1237                     }
1238                     if (groupMax > stackMax) {
1239                         stackMax = groupMax;
1240                     }
1241                 }
1242             }
1243
1244             this.stacked = stacked;
1245             this.regionShapes = {};
1246             this.barWidth = barWidth;
1247             this.barSpacing = barSpacing;
1248             this.totalBarWidth = barWidth + barSpacing;
1249             this.width = width = (values.length * barWidth) + ((values.length - 1) * barSpacing);
1250
1251             this.initTarget();
1252
1253             if (chartRangeClip) {
1254                 clipMin = chartRangeMin === undefined ? -Infinity : chartRangeMin;
1255                 clipMax = chartRangeMax === undefined ? Infinity : chartRangeMax;
1256             }
1257
1258             numValues = [];
1259             stackRanges = stacked ? [] : numValues;
1260             var stackTotals = [];
1261             var stackRangesNeg = [];
1262             for (i = 0, vlen = values.length; i < vlen; i++) {
1263                 if (stacked) {
1264                     vlist = values[i];
1265                     values[i] = svals = [];
1266                     stackTotals[i] = 0;
1267                     stackRanges[i] = stackRangesNeg[i] = 0;
1268                     for (j = 0, slen = vlist.length; j < slen; j++) {
1269                         val = svals[j] = chartRangeClip ? clipval(vlist[j], clipMin, clipMax) : vlist[j];
1270                         if (val !== null) {
1271                             if (val > 0) {
1272                                 stackTotals[i] += val;
1273                             }
1274                             if (stackMin < 0 && stackMax > 0) {
1275                                 if (val < 0) {
1276                                     stackRangesNeg[i] += Math.abs(val);
1277                                 } else {
1278                                     stackRanges[i] += val;
1279                                 }
1280                             } else {
1281                                 stackRanges[i] += Math.abs(val - (val < 0 ? stackMax : stackMin));
1282                             }
1283                             numValues.push(val);
1284                         }
1285                     }
1286                 } else {
1287                     val = chartRangeClip ? clipval(values[i], clipMin, clipMax) : values[i];
1288                     val = values[i] = normalizeValue(val);
1289                     if (val !== null) {
1290                         numValues.push(val);
1291                     }
1292                 }
1293             }
1294             this.max = max = Math.max.apply(Math, numValues);
1295             this.min = min = Math.min.apply(Math, numValues);
1296             this.stackMax = stackMax = stacked ? Math.max.apply(Math, stackTotals) : max;
1297             this.stackMin = stackMin = stacked ? Math.min.apply(Math, numValues) : min;
1298
1299             if (options.get('chartRangeMin') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMin') < min)) {
1300                 min = options.get('chartRangeMin');
1301             }
1302             if (options.get('chartRangeMax') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMax') > max)) {
1303                 max = options.get('chartRangeMax');
1304             }
1305
1306             this.zeroAxis = zeroAxis = options.get('zeroAxis', true);
1307             if (min <= 0 && max >= 0 && zeroAxis) {
1308                 xaxisOffset = 0;
1309             } else if (zeroAxis == false) {
1310                 xaxisOffset = min;
1311             } else if (min > 0) {
1312                 xaxisOffset = min;
1313             } else {
1314                 xaxisOffset = max;
1315             }
1316             this.xaxisOffset = xaxisOffset;
1317
1318             range = stacked ? (Math.max.apply(Math, stackRanges) + Math.max.apply(Math, stackRangesNeg)) : max - min;
1319
1320             // as we plot zero/min values a single pixel line, we add a pixel to all other
1321             // values - Reduce the effective canvas size to suit
1322             this.canvasHeightEf = (zeroAxis && min < 0) ? this.canvasHeight - 2 : this.canvasHeight - 1;
1323
1324             if (min < xaxisOffset) {
1325                 yMaxCalc = (stacked && max >= 0) ? stackMax : max;
1326                 yoffset = (yMaxCalc - xaxisOffset) / range * this.canvasHeight;
1327                 if (yoffset !== Math.ceil(yoffset)) {
1328                     this.canvasHeightEf -= 2;
1329                     yoffset = Math.ceil(yoffset);
1330                 }
1331             } else {
1332                 yoffset = this.canvasHeight;
1333             }
1334             this.yoffset = yoffset;
1335
1336             if ($.isArray(options.get('colorMap'))) {
1337                 this.colorMapByIndex = options.get('colorMap');
1338                 this.colorMapByValue = null;
1339             } else {
1340                 this.colorMapByIndex = null;
1341                 this.colorMapByValue = options.get('colorMap');
1342                 if (this.colorMapByValue && this.colorMapByValue.get === undefined) {
1343                     this.colorMapByValue = new RangeMap(this.colorMapByValue);
1344                 }
1345             }
1346
1347             this.range = range;
1348         },
1349
1350         getRegion: function (el, x, y) {
1351             var result = Math.floor(x / this.totalBarWidth);
1352             return (result < 0 || result >= this.values.length) ? undefined : result;
1353         },
1354
1355         getCurrentRegionFields: function () {
1356             var currentRegion = this.currentRegion,
1357                 values = ensureArray(this.values[currentRegion]),
1358                 result = [],
1359                 value, i;
1360             for (i = values.length; i--;) {
1361                 value = values[i];
1362                 result.push({
1363                     isNull: value === null,
1364                     value: value,
1365                     color: this.calcColor(i, value, currentRegion),
1366                     offset: currentRegion
1367                 });
1368             }
1369             return result;
1370         },
1371
1372         calcColor: function (stacknum, value, valuenum) {
1373             var colorMapByIndex = this.colorMapByIndex,
1374                 colorMapByValue = this.colorMapByValue,
1375                 options = this.options,
1376                 color, newColor;
1377             if (this.stacked) {
1378                 color = options.get('stackedBarColor');
1379             } else {
1380                 color = (value < 0) ? options.get('negBarColor') : options.get('barColor');
1381             }
1382             if (value === 0 && options.get('zeroColor') !== undefined) {
1383                 color = options.get('zeroColor');
1384             }
1385             if (colorMapByValue && (newColor = colorMapByValue.get(value))) {
1386                 color = newColor;
1387             } else if (colorMapByIndex && colorMapByIndex.length > valuenum) {
1388                 color = colorMapByIndex[valuenum];
1389             }
1390             return $.isArray(color) ? color[stacknum % color.length] : color;
1391         },
1392
1393         /**
1394          * Render bar(s) for a region
1395          */
1396         renderRegion: function (valuenum, highlight) {
1397             var vals = this.values[valuenum],
1398                 options = this.options,
1399                 xaxisOffset = this.xaxisOffset,
1400                 result = [],
1401                 range = this.range,
1402                 stacked = this.stacked,
1403                 target = this.target,
1404                 x = valuenum * this.totalBarWidth,
1405                 canvasHeightEf = this.canvasHeightEf,
1406                 yoffset = this.yoffset,
1407                 y, height, color, isNull, yoffsetNeg, i, valcount, val, minPlotted, allMin;
1408
1409             vals = $.isArray(vals) ? vals : [vals];
1410             valcount = vals.length;
1411             val = vals[0];
1412             isNull = all(null, vals);
1413             allMin = all(xaxisOffset, vals, true);
1414
1415             if (isNull) {
1416                 if (options.get('nullColor')) {
1417                     color = highlight ? options.get('nullColor') : this.calcHighlightColor(options.get('nullColor'), options);
1418                     y = (yoffset > 0) ? yoffset - 1 : yoffset;
1419                     return target.drawRect(x, y, this.barWidth - 1, 0, color, color);
1420                 } else {
1421                     return undefined;
1422                 }
1423             }
1424             yoffsetNeg = yoffset;
1425             for (i = 0; i < valcount; i++) {
1426                 val = vals[i];
1427
1428                 if (stacked && val === xaxisOffset) {
1429                     if (!allMin || minPlotted) {
1430                         continue;
1431                     }
1432                     minPlotted = true;
1433                 }
1434
1435                 if (range > 0) {
1436                     height = Math.floor(canvasHeightEf * ((Math.abs(val - xaxisOffset) / range))) + 1;
1437                 } else {
1438                     height = 1;
1439                 }
1440                 if (val < xaxisOffset || (val === xaxisOffset && yoffset === 0)) {
1441                     y = yoffsetNeg;
1442                     yoffsetNeg += height;
1443                 } else {
1444                     y = yoffset - height;
1445                     yoffset -= height;
1446                 }
1447                 color = this.calcColor(i, val, valuenum);
1448                 if (highlight) {
1449                     color = this.calcHighlightColor(color, options);
1450                 }
1451                 result.push(target.drawRect(x, y, this.barWidth - 1, height - 1, color, color));
1452             }
1453             if (result.length === 1) {
1454                 return result[0];
1455             }
1456             return result;
1457         }
1458     });
1459
1460     // Setup a very simple "virtual canvas" to make drawing the few shapes we need easier
1461     // This is accessible as $(foo).simpledraw()
1462
1463     VShape = createClass({
1464         init: function (target, id, type, args) {
1465             this.target = target;
1466             this.id = id;
1467             this.type = type;
1468             this.args = args;
1469         },
1470         append: function () {
1471             this.target.appendShape(this);
1472             return this;
1473         }
1474     });
1475
1476     VCanvas_base = createClass({
1477         _pxregex: /(\d+)(px)?\s*$/i,
1478
1479         init: function (width, height, target) {
1480             if (!width) {
1481                 return;
1482             }
1483             this.width = width;
1484             this.height = height;
1485             this.target = target;
1486             this.lastShapeId = null;
1487             if (target[0]) {
1488                 target = target[0];
1489             }
1490             $.data(target, '_jqs_vcanvas', this);
1491         },
1492
1493         drawLine: function (x1, y1, x2, y2, lineColor, lineWidth) {
1494             return this.drawShape([[x1, y1], [x2, y2]], lineColor, lineWidth);
1495         },
1496
1497         drawShape: function (path, lineColor, fillColor, lineWidth) {
1498             return this._genShape('Shape', [path, lineColor, fillColor, lineWidth]);
1499         },
1500
1501         drawCircle: function (x, y, radius, lineColor, fillColor, lineWidth) {
1502             return this._genShape('Circle', [x, y, radius, lineColor, fillColor, lineWidth]);
1503         },
1504
1505         drawPieSlice: function (x, y, radius, startAngle, endAngle, lineColor, fillColor) {
1506             return this._genShape('PieSlice', [x, y, radius, startAngle, endAngle, lineColor, fillColor]);
1507         },
1508
1509         drawRect: function (x, y, width, height, lineColor, fillColor) {
1510             return this._genShape('Rect', [x, y, width, height, lineColor, fillColor]);
1511         },
1512
1513         getElement: function () {
1514             return this.canvas;
1515         },
1516
1517         /**
1518          * Return the most recently inserted shape id
1519          */
1520         getLastShapeId: function () {
1521             return this.lastShapeId;
1522         },
1523
1524         /**
1525          * Clear and reset the canvas
1526          */
1527         reset: function () {
1528             alert('reset not implemented');
1529         },
1530
1531         _insert: function (el, target) {
1532             $(target).html(el);
1533         },
1534
1535         /**
1536          * Calculate the pixel dimensions of the canvas
1537          */
1538         _calculatePixelDims: function (width, height, canvas) {
1539             // XXX This should probably be a configurable option
1540             var match;
1541             match = this._pxregex.exec(height);
1542             if (match) {
1543                 this.pixelHeight = match[1];
1544             } else {
1545                 this.pixelHeight = $(canvas).height();
1546             }
1547             match = this._pxregex.exec(width);
1548             if (match) {
1549                 this.pixelWidth = match[1];
1550             } else {
1551                 this.pixelWidth = $(canvas).width();
1552             }
1553         },
1554
1555         /**
1556          * Generate a shape object and id for later rendering
1557          */
1558         _genShape: function (shapetype, shapeargs) {
1559             var id = shapeCount++;
1560             shapeargs.unshift(id);
1561             return new VShape(this, id, shapetype, shapeargs);
1562         },
1563
1564         /**
1565          * Add a shape to the end of the render queue
1566          */
1567         appendShape: function (shape) {
1568             alert('appendShape not implemented');
1569         },
1570
1571         /**
1572          * Replace one shape with another
1573          */
1574         replaceWithShape: function (shapeid, shape) {
1575             alert('replaceWithShape not implemented');
1576         },
1577
1578         /**
1579          * Insert one shape after another in the render queue
1580          */
1581         insertAfterShape: function (shapeid, shape) {
1582             alert('insertAfterShape not implemented');
1583         },
1584
1585         /**
1586          * Remove a shape from the queue
1587          */
1588         removeShapeId: function (shapeid) {
1589             alert('removeShapeId not implemented');
1590         },
1591
1592         /**
1593          * Find a shape at the specified x/y co-ordinates
1594          */
1595         getShapeAt: function (el, x, y) {
1596             alert('getShapeAt not implemented');
1597         },
1598
1599         /**
1600          * Render all queued shapes onto the canvas
1601          */
1602         render: function () {
1603             alert('render not implemented');
1604         }
1605     });
1606
1607     VCanvas_canvas = createClass(VCanvas_base, {
1608         init: function (width, height, target, interact) {
1609             VCanvas_canvas._super.init.call(this, width, height, target);
1610             this.canvas = document.createElement('canvas');
1611             if (target[0]) {
1612                 target = target[0];
1613             }
1614             $.data(target, '_jqs_vcanvas', this);
1615             $(this.canvas).css({ display: 'inline-block', width: width, height: height, verticalAlign: 'top' });
1616             this._insert(this.canvas, target);
1617             this._calculatePixelDims(width, height, this.canvas);
1618             this.canvas.width = this.pixelWidth;
1619             this.canvas.height = this.pixelHeight;
1620             this.interact = interact;
1621             this.shapes = {};
1622             this.shapeseq = [];
1623             this.currentTargetShapeId = undefined;
1624             $(this.canvas).css({width: this.pixelWidth, height: this.pixelHeight});
1625         },
1626
1627         _getContext: function (lineColor, fillColor, lineWidth) {
1628             var context = this.canvas.getContext('2d');
1629             if (lineColor !== undefined) {
1630                 context.strokeStyle = lineColor;
1631             }
1632             context.lineWidth = lineWidth === undefined ? 1 : lineWidth;
1633             if (fillColor !== undefined) {
1634                 context.fillStyle = fillColor;
1635             }
1636             return context;
1637         },
1638
1639         reset: function () {
1640             var context = this._getContext();
1641             context.clearRect(0, 0, this.pixelWidth, this.pixelHeight);
1642             this.shapes = {};
1643             this.shapeseq = [];
1644             this.currentTargetShapeId = undefined;
1645         },
1646
1647         _drawShape: function (shapeid, path, lineColor, fillColor, lineWidth) {
1648             var context = this._getContext(lineColor, fillColor, lineWidth),
1649                 i, plen;
1650             context.beginPath();
1651             context.moveTo(path[0][0] + 0.5, path[0][1] + 0.5);
1652             for (i = 1, plen = path.length; i < plen; i++) {
1653                 context.lineTo(path[i][0] + 0.5, path[i][1] + 0.5); // the 0.5 offset gives us crisp pixel-width lines
1654             }
1655             if (lineColor !== undefined) {
1656                 context.stroke();
1657             }
1658             if (fillColor !== undefined) {
1659                 context.fill();
1660             }
1661             if (this.targetX !== undefined && this.targetY !== undefined &&
1662                 context.isPointInPath(this.targetX, this.targetY)) {
1663                 this.currentTargetShapeId = shapeid;
1664             }
1665         },
1666
1667         _drawCircle: function (shapeid, x, y, radius, lineColor, fillColor, lineWidth) {
1668             var context = this._getContext(lineColor, fillColor, lineWidth);
1669             context.beginPath();
1670             context.arc(x, y, radius, 0, 2 * Math.PI, false);
1671             if (this.targetX !== undefined && this.targetY !== undefined &&
1672                 context.isPointInPath(this.targetX, this.targetY)) {
1673                 this.currentTargetShapeId = shapeid;
1674             }
1675             if (lineColor !== undefined) {
1676                 context.stroke();
1677             }
1678             if (fillColor !== undefined) {
1679                 context.fill();
1680             }
1681         },
1682
1683         _drawPieSlice: function (shapeid, x, y, radius, startAngle, endAngle, lineColor, fillColor) {
1684             var context = this._getContext(lineColor, fillColor);
1685             context.beginPath();
1686             context.moveTo(x, y);
1687             context.arc(x, y, radius, startAngle, endAngle, false);
1688             context.lineTo(x, y);
1689             context.closePath();
1690             if (lineColor !== undefined) {
1691                 context.stroke();
1692             }
1693             if (fillColor) {
1694                 context.fill();
1695             }
1696             if (this.targetX !== undefined && this.targetY !== undefined &&
1697                 context.isPointInPath(this.targetX, this.targetY)) {
1698                 this.currentTargetShapeId = shapeid;
1699             }
1700         },
1701
1702         _drawRect: function (shapeid, x, y, width, height, lineColor, fillColor) {
1703             return this._drawShape(shapeid, [[x, y], [x + width, y], [x + width, y + height], [x, y + height], [x, y]], lineColor, fillColor);
1704         },
1705
1706         appendShape: function (shape) {
1707             this.shapes[shape.id] = shape;
1708             this.shapeseq.push(shape.id);
1709             this.lastShapeId = shape.id;
1710             return shape.id;
1711         },
1712
1713         replaceWithShape: function (shapeid, shape) {
1714             var shapeseq = this.shapeseq,
1715                 i;
1716             this.shapes[shape.id] = shape;
1717             for (i = shapeseq.length; i--;) {
1718                 if (shapeseq[i] == shapeid) {
1719                     shapeseq[i] = shape.id;
1720                 }
1721             }
1722             delete this.shapes[shapeid];
1723         },
1724
1725         replaceWithShapes: function (shapeids, shapes) {
1726             var shapeseq = this.shapeseq,
1727                 shapemap = {},
1728                 sid, i, first;
1729
1730             for (i = shapeids.length; i--;) {
1731                 shapemap[shapeids[i]] = true;
1732             }
1733             for (i = shapeseq.length; i--;) {
1734                 sid = shapeseq[i];
1735                 if (shapemap[sid]) {
1736                     shapeseq.splice(i, 1);
1737                     delete this.shapes[sid];
1738                     first = i;
1739                 }
1740             }
1741             for (i = shapes.length; i--;) {
1742                 shapeseq.splice(first, 0, shapes[i].id);
1743                 this.shapes[shapes[i].id] = shapes[i];
1744             }
1745
1746         },
1747
1748         insertAfterShape: function (shapeid, shape) {
1749             var shapeseq = this.shapeseq,
1750                 i;
1751             for (i = shapeseq.length; i--;) {
1752                 if (shapeseq[i] === shapeid) {
1753                     shapeseq.splice(i + 1, 0, shape.id);
1754                     this.shapes[shape.id] = shape;
1755                     return;
1756                 }
1757             }
1758         },
1759
1760         removeShapeId: function (shapeid) {
1761             var shapeseq = this.shapeseq,
1762                 i;
1763             for (i = shapeseq.length; i--;) {
1764                 if (shapeseq[i] === shapeid) {
1765                     shapeseq.splice(i, 1);
1766                     break;
1767                 }
1768             }
1769             delete this.shapes[shapeid];
1770         },
1771
1772         getShapeAt: function (el, x, y) {
1773             this.targetX = x;
1774             this.targetY = y;
1775             this.render();
1776             return this.currentTargetShapeId;
1777         },
1778
1779         render: function () {
1780             var shapeseq = this.shapeseq,
1781                 shapes = this.shapes,
1782                 shapeCount = shapeseq.length,
1783                 context = this._getContext(),
1784                 shapeid, shape, i;
1785             context.clearRect(0, 0, this.pixelWidth, this.pixelHeight);
1786             for (i = 0; i < shapeCount; i++) {
1787                 shapeid = shapeseq[i];
1788                 shape = shapes[shapeid];
1789                 this['_draw' + shape.type].apply(this, shape.args);
1790             }
1791             if (!this.interact) {
1792                 // not interactive so no need to keep the shapes array
1793                 this.shapes = {};
1794                 this.shapeseq = [];
1795             }
1796         }
1797
1798     });
1799
1800     VCanvas_vml = createClass(VCanvas_base, {
1801         init: function (width, height, target) {
1802             var groupel;
1803             VCanvas_vml._super.init.call(this, width, height, target);
1804             if (target[0]) {
1805                 target = target[0];
1806             }
1807             $.data(target, '_jqs_vcanvas', this);
1808             this.canvas = document.createElement('span');
1809             $(this.canvas).css({ display: 'inline-block', position: 'relative', overflow: 'hidden', width: width, height: height, margin: '0px', padding: '0px', verticalAlign: 'top'});
1810             this._insert(this.canvas, target);
1811             this._calculatePixelDims(width, height, this.canvas);
1812             this.canvas.width = this.pixelWidth;
1813             this.canvas.height = this.pixelHeight;
1814             groupel = '<v:group coordorigin="0 0" coordsize="' + this.pixelWidth + ' ' + this.pixelHeight + '"' +
1815                     ' style="position:absolute;top:0;left:0;width:' + this.pixelWidth + 'px;height=' + this.pixelHeight + 'px;"></v:group>';
1816             this.canvas.insertAdjacentHTML('beforeEnd', groupel);
1817             this.group = $(this.canvas).children()[0];
1818             this.rendered = false;
1819             this.prerender = '';
1820         },
1821
1822         _drawShape: function (shapeid, path, lineColor, fillColor, lineWidth) {
1823             var vpath = [],
1824                 initial, stroke, fill, closed, vel, plen, i;
1825             for (i = 0, plen = path.length; i < plen; i++) {
1826                 vpath[i] = '' + (path[i][0]) + ',' + (path[i][1]);
1827             }
1828             initial = vpath.splice(0, 1);
1829             lineWidth = lineWidth === undefined ? 1 : lineWidth;
1830             stroke = lineColor === undefined ? ' stroked="false" ' : ' strokeWeight="' + lineWidth + 'px" strokeColor="' + lineColor + '" ';
1831             fill = fillColor === undefined ? ' filled="false"' : ' fillColor="' + fillColor + '" filled="true" ';
1832             closed = vpath[0] === vpath[vpath.length - 1] ? 'x ' : '';
1833             vel = '<v:shape coordorigin="0 0" coordsize="' + this.pixelWidth + ' ' + this.pixelHeight + '" ' +
1834                  ' id="jqsshape' + shapeid + '" ' +
1835                  stroke +
1836                  fill +
1837                 ' style="position:absolute;left:0px;top:0px;height:' + this.pixelHeight + 'px;width:' + this.pixelWidth + 'px;padding:0px;margin:0px;" ' +
1838                 ' path="m ' + initial + ' l ' + vpath.join(', ') + ' ' + closed + 'e">' +
1839                 ' </v:shape>';
1840             return vel;
1841         },
1842
1843         _drawCircle: function (shapeid, x, y, radius, lineColor, fillColor, lineWidth) {
1844             var stroke, fill, vel;
1845             x -= radius;
1846             y -= radius;
1847             stroke = lineColor === undefined ? ' stroked="false" ' : ' strokeWeight="' + lineWidth + 'px" strokeColor="' + lineColor + '" ';
1848             fill = fillColor === undefined ? ' filled="false"' : ' fillColor="' + fillColor + '" filled="true" ';
1849             vel = '<v:oval ' +
1850                  ' id="jqsshape' + shapeid + '" ' +
1851                 stroke +
1852                 fill +
1853                 ' style="position:absolute;top:' + y + 'px; left:' + x + 'px; width:' + (radius * 2) + 'px; height:' + (radius * 2) + 'px"></v:oval>';
1854             return vel;
1855
1856         },
1857
1858         _drawPieSlice: function (shapeid, x, y, radius, startAngle, endAngle, lineColor, fillColor) {
1859             var vpath, startx, starty, endx, endy, stroke, fill, vel;
1860             if (startAngle === endAngle) {
1861                 return '';  // VML seems to have problem when start angle equals end angle.
1862             }
1863             if ((endAngle - startAngle) === (2 * Math.PI)) {
1864                 startAngle = 0.0;  // VML seems to have a problem when drawing a full circle that doesn't start 0
1865                 endAngle = (2 * Math.PI);
1866             }
1867
1868             startx = x + Math.round(Math.cos(startAngle) * radius);
1869             starty = y + Math.round(Math.sin(startAngle) * radius);
1870             endx = x + Math.round(Math.cos(endAngle) * radius);
1871             endy = y + Math.round(Math.sin(endAngle) * radius);
1872
1873             if (startx === endx && starty === endy) {
1874                 if ((endAngle - startAngle) < Math.PI) {
1875                     // Prevent very small slices from being mistaken as a whole pie
1876                     return '';
1877                 }
1878                 // essentially going to be the entire circle, so ignore startAngle
1879                 startx = endx = x + radius;
1880                 starty = endy = y;
1881             }
1882
1883             if (startx === endx && starty === endy && (endAngle - startAngle) < Math.PI) {
1884                 return '';
1885             }
1886
1887             vpath = [x - radius, y - radius, x + radius, y + radius, startx, starty, endx, endy];
1888             stroke = lineColor === undefined ? ' stroked="false" ' : ' strokeWeight="1px" strokeColor="' + lineColor + '" ';
1889             fill = fillColor === undefined ? ' filled="false"' : ' fillColor="' + fillColor + '" filled="true" ';
1890             vel = '<v:shape coordorigin="0 0" coordsize="' + this.pixelWidth + ' ' + this.pixelHeight + '" ' +
1891                  ' id="jqsshape' + shapeid + '" ' +
1892                  stroke +
1893                  fill +
1894                 ' style="position:absolute;left:0px;top:0px;height:' + this.pixelHeight + 'px;width:' + this.pixelWidth + 'px;padding:0px;margin:0px;" ' +
1895                 ' path="m ' + x + ',' + y + ' wa ' + vpath.join(', ') + ' x e">' +
1896                 ' </v:shape>';
1897             return vel;
1898         },
1899
1900         _drawRect: function (shapeid, x, y, width, height, lineColor, fillColor) {
1901             return this._drawShape(shapeid, [[x, y], [x, y + height], [x + width, y + height], [x + width, y], [x, y]], lineColor, fillColor);
1902         },
1903
1904         reset: function () {
1905             this.group.innerHTML = '';
1906         },
1907
1908         appendShape: function (shape) {
1909             var vel = this['_draw' + shape.type].apply(this, shape.args);
1910             if (this.rendered) {
1911                 this.group.insertAdjacentHTML('beforeEnd', vel);
1912             } else {
1913                 this.prerender += vel;
1914             }
1915             this.lastShapeId = shape.id;
1916             return shape.id;
1917         },
1918
1919         replaceWithShape: function (shapeid, shape) {
1920             var existing = $('#jqsshape' + shapeid),
1921                 vel = this['_draw' + shape.type].apply(this, shape.args);
1922             existing[0].outerHTML = vel;
1923         },
1924
1925         replaceWithShapes: function (shapeids, shapes) {
1926             // replace the first shapeid with all the new shapes then toast the remaining old shapes
1927             var existing = $('#jqsshape' + shapeids[0]),
1928                 replace = '',
1929                 slen = shapes.length,
1930                 i;
1931             for (i = 0; i < slen; i++) {
1932                 replace += this['_draw' + shapes[i].type].apply(this, shapes[i].args);
1933             }
1934             existing[0].outerHTML = replace;
1935             for (i = 1; i < shapeids.length; i++) {
1936                 $('#jqsshape' + shapeids[i]).remove();
1937             }
1938         },
1939
1940         insertAfterShape: function (shapeid, shape) {
1941             var existing = $('#jqsshape' + shapeid),
1942                  vel = this['_draw' + shape.type].apply(this, shape.args);
1943             existing[0].insertAdjacentHTML('afterEnd', vel);
1944         },
1945
1946         removeShapeId: function (shapeid) {
1947             var existing = $('#jqsshape' + shapeid);
1948             this.group.removeChild(existing[0]);
1949         },
1950
1951         getShapeAt: function (el, x, y) {
1952             var shapeid = el.id.substr(8);
1953             return shapeid;
1954         },
1955
1956         render: function () {
1957             if (!this.rendered) {
1958                 // batch the intial render into a single repaint
1959                 this.group.innerHTML = this.prerender;
1960                 this.rendered = true;
1961             }
1962         }
1963     });
1964
1965 }))}(document, Math));