4 * Pure JavaScript plotting plugin for jQuery.
11 * About: Copyright & License
13 * Copyright (c) 2009-2012 Chris Leonello
14 * jqPlot is currently available for use in all personal or commercial projects
15 * under both the MIT and GPL version 2.0 licenses. This means that you can
16 * choose the license that best suits your project and use it accordingly.
18 * See <GPL Version 2> and <MIT License> contained within this distribution for further information.
20 * The author would appreciate an email letting him know of any substantial
21 * use of jqPlot. You can reach the author at: chris at jqplot dot com
22 * or see http://www.jqplot.com/info.php. This is, of course, not required.
24 * If you are feeling kind and generous, consider supporting the project by
25 * making a donation at: http://www.jqplot.com/donate.php.
27 * sprintf functions contained in jqplot.sprintf.js by Ash Searle:
31 * http://hexmen.com/blog/2007/03/printf-sprintf/
32 * http://hexmen.com/js/sprintf.js
33 * The author (Ash Searle) has placed this code in the public domain:
34 * "This code is unrestricted: you are free to use it however you like."
39 * jqPlot requires jQuery (1.4+ required for certain features). jQuery 1.4.2 is included in the distribution.
40 * To use jqPlot include jQuery, the jqPlot jQuery plugin, the jqPlot css file and optionally
41 * the excanvas script for IE support in your web page:
43 * > <!--[if lt IE 9]><script language="javascript" type="text/javascript" src="excanvas.js"></script><![endif]-->
44 * > <script language="javascript" type="text/javascript" src="jquery-1.4.4.min.js"></script>
45 * > <script language="javascript" type="text/javascript" src="jquery.jqplot.min.js"></script>
46 * > <link rel="stylesheet" type="text/css" href="jquery.jqplot.css" />
48 * jqPlot can be customized by overriding the defaults of any of the objects which make
49 * up the plot. The general usage of jqplot is:
51 * > chart = $.jqplot('targetElemId', [dataArray,...], {optionsObject});
53 * The options available to jqplot are detailed in <jqPlot Options> in the jqPlotOptions.txt file.
55 * An actual call to $.jqplot() may look like the
58 * > chart = $.jqplot('chartdiv', [[[1, 2],[3,5.12],[5,13.1],[7,33.6],[9,85.9],[11,219.9]]]);
62 * > dataArray = [34,12,43,55,77];
63 * > chart = $.jqplot('targetElemId', [dataArray, ...], {title:'My Plot', axes:{yaxis:{min:20, max:100}}});
65 * For more inforrmation, see <jqPlot Usage>.
71 * About: Available Options
73 * See <jqPlot Options> for a list of options available thorugh the options object (not complete yet!)
75 * About: Options Usage
77 * See <Options Tutorial>
86 // make sure undefined is undefined
89 $.fn.emptyForce = function() {
90 for ( var i = 0, elem; (elem = $(this)[i]) != null; i++ ) {
91 // Remove element nodes and prevent memory leaks
92 if ( elem.nodeType === 1 ) {
93 $.cleanData( elem.getElementsByTagName("*") );
96 // Remove any remaining nodes
97 if ($.jqplot.use_excanvas) {
101 while ( elem.firstChild ) {
102 elem.removeChild( elem.firstChild );
112 $.fn.removeChildForce = function(parent) {
113 while ( parent.firstChild ) {
114 this.removeChildForce( parent.firstChild );
115 parent.removeChild( parent.firstChild );
119 $.fn.jqplot = function() {
122 // see how many data arrays we have
123 for (var i=0, l=arguments.length; i<l; i++) {
124 if ($.isArray(arguments[i])) {
125 datas.push(arguments[i]);
127 else if ($.isPlainObject(arguments[i])) {
128 options.push(arguments[i]);
132 return this.each(function(index) {
145 data = dl ? datas[dl-1] : null;
149 opts = options[index];
152 opts = ol ? options[ol-1] : null;
155 // does el have an id?
156 // if not assign it one.
157 tid = $this.attr('id');
158 if (tid === undefined) {
159 tid = 'jqplot_target_' + $.jqplot.targetCounter++;
160 $this.attr('id', tid);
163 plot = $.jqplot(tid, data, opts);
165 $this.data('jqplot', plot);
171 * Namespace: $.jqplot
172 * jQuery function called by the user to create a plot.
175 * target - ID of target element to render the plot into.
176 * data - an array of data series.
177 * options - user defined options object. See the individual classes for available options.
180 * config - object to hold configuration information for jqPlot plot object.
183 * enablePlugins - False to disable plugins by default. Plugins must then be explicitly
184 * enabled in the individual plot options. Default: false.
185 * This property sets the "show" property of certain plugins to true or false.
186 * Only plugins that can be immediately active upon loading are affected. This includes
187 * non-renderer plugins like cursor, dragable, highlighter, and trendline.
188 * defaultHeight - Default height for plots where no css height specification exists. This
189 * is a jqplot wide default.
190 * defaultWidth - Default height for plots where no css height specification exists. This
191 * is a jqplot wide default.
194 $.jqplot = function(target, data, options) {
195 var _data = null, _options = null;
197 if (arguments.length === 3) {
202 else if (arguments.length === 2) {
203 if ($.isArray(data)) {
207 else if ($.isPlainObject(data)) {
212 if (_data === null && _options !== null && _options.data) {
213 _data = _options.data;
216 var plot = new jqPlot();
217 // remove any error class that may be stuck on target.
218 $('#'+target).removeClass('jqplot-error');
220 if ($.jqplot.config.catchErrors) {
222 plot.init(target, _data, _options);
224 plot.themeEngine.init.call(plot);
228 var msg = $.jqplot.config.errorMessage || e.message;
229 $('#'+target).append('<div class="jqplot-error-message">'+msg+'</div>');
230 $('#'+target).addClass('jqplot-error');
231 document.getElementById(target).style.background = $.jqplot.config.errorBackground;
232 document.getElementById(target).style.border = $.jqplot.config.errorBorder;
233 document.getElementById(target).style.fontFamily = $.jqplot.config.errorFontFamily;
234 document.getElementById(target).style.fontSize = $.jqplot.config.errorFontSize;
235 document.getElementById(target).style.fontStyle = $.jqplot.config.errorFontStyle;
236 document.getElementById(target).style.fontWeight = $.jqplot.config.errorFontWeight;
240 plot.init(target, _data, _options);
242 plot.themeEngine.init.call(plot);
247 $.jqplot.version = "1.0.4";
248 $.jqplot.revision = "1121";
250 $.jqplot.targetCounter = 1;
252 // canvas manager to reuse canvases on the plot.
253 // Should help solve problem of canvases not being freed and
254 // problem of waiting forever for firefox to decide to free memory.
255 $.jqplot.CanvasManager = function() {
256 // canvases are managed globally so that they can be reused
257 // across plots after they have been freed
258 if (typeof $.jqplot.CanvasManager.canvases == 'undefined') {
259 $.jqplot.CanvasManager.canvases = [];
260 $.jqplot.CanvasManager.free = [];
265 this.getCanvas = function() {
269 if (!$.jqplot.use_excanvas) {
270 for (var i = 0, l = $.jqplot.CanvasManager.canvases.length; i < l; i++) {
271 if ($.jqplot.CanvasManager.free[i] === true) {
273 canvas = $.jqplot.CanvasManager.canvases[i];
274 // $(canvas).removeClass('jqplot-canvasManager-free').addClass('jqplot-canvasManager-inuse');
275 $.jqplot.CanvasManager.free[i] = false;
283 canvas = document.createElement('canvas');
284 myCanvases.push($.jqplot.CanvasManager.canvases.length);
285 $.jqplot.CanvasManager.canvases.push(canvas);
286 $.jqplot.CanvasManager.free.push(false);
292 // this method has to be used after settings the dimesions
293 // on the element returned by getCanvas()
294 this.initCanvas = function(canvas) {
295 if ($.jqplot.use_excanvas) {
296 return window.G_vmlCanvasManager.initElement(canvas);
301 this.freeAllCanvases = function() {
302 for (var i = 0, l=myCanvases.length; i < l; i++) {
303 this.freeCanvas(myCanvases[i]);
308 this.freeCanvas = function(idx) {
309 if ($.jqplot.use_excanvas && window.G_vmlCanvasManager.uninitElement !== undefined) {
310 // excanvas can't be reused, but properly unset
311 window.G_vmlCanvasManager.uninitElement($.jqplot.CanvasManager.canvases[idx]);
312 $.jqplot.CanvasManager.canvases[idx] = null;
315 var canvas = $.jqplot.CanvasManager.canvases[idx];
316 canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height);
317 $(canvas).unbind().removeAttr('class').removeAttr('style');
318 // Style attributes seemed to be still hanging around. wierd. Some ticks
319 // still retained a left: 0px attribute after reusing a canvas.
320 $(canvas).css({left: '', top: '', position: ''});
321 // setting size to 0 may save memory of unused canvases?
324 $.jqplot.CanvasManager.free[idx] = true;
331 // Convienence function that won't hang IE or FF without FireBug.
332 $.jqplot.log = function() {
333 if (window.console) {
334 window.console.log.apply(window.console, arguments);
339 addDomReference: false,
344 timezoneOffset: new Date(new Date().getTimezoneOffset() * 60000),
353 defaultTickFormatString: "%.1f",
354 defaultColors: [ "#4bb2c5", "#EAA228", "#c5b47f", "#579575", "#839557", "#958c12", "#953579", "#4b5de4", "#d8b83f", "#ff5800", "#0085cc", "#c747a3", "#cddf54", "#FBD178", "#26B4E3", "#bd70c7"],
355 defaultNegativeColors: [ "#498991", "#C08840", "#9F9274", "#546D61", "#646C4A", "#6F6621", "#6E3F5F", "#4F64B0", "#A89050", "#C45923", "#187399", "#945381", "#959E5C", "#C7AF7B", "#478396", "#907294"],
359 srcLocation: 'jqplot/src/',
360 pluginLocation: 'jqplot/src/plugins/'
364 $.jqplot.arrayMax = function( array ){
365 return Math.max.apply( Math, array );
368 $.jqplot.arrayMin = function( array ){
369 return Math.min.apply( Math, array );
372 $.jqplot.enablePlugins = $.jqplot.config.enablePlugins;
374 // canvas related tests taken from modernizer:
375 // Copyright (c) 2009 - 2010 Faruk Ates.
376 // http://www.modernizr.com
378 $.jqplot.support_canvas = function() {
379 if (typeof $.jqplot.support_canvas.result == 'undefined') {
380 $.jqplot.support_canvas.result = !!document.createElement('canvas').getContext;
382 return $.jqplot.support_canvas.result;
385 $.jqplot.support_canvas_text = function() {
386 if (typeof $.jqplot.support_canvas_text.result == 'undefined') {
387 if (window.G_vmlCanvasManager !== undefined && window.G_vmlCanvasManager._version > 887) {
388 $.jqplot.support_canvas_text.result = true;
391 $.jqplot.support_canvas_text.result = !!(document.createElement('canvas').getContext && typeof document.createElement('canvas').getContext('2d').fillText == 'function');
395 return $.jqplot.support_canvas_text.result;
398 $.jqplot.use_excanvas = ($.browser.msie && !$.jqplot.support_canvas()) ? true : false;
402 * Hooks: jqPlot Pugin Hooks
404 * $.jqplot.preInitHooks - called before initialization.
405 * $.jqplot.postInitHooks - called after initialization.
406 * $.jqplot.preParseOptionsHooks - called before user options are parsed.
407 * $.jqplot.postParseOptionsHooks - called after user options are parsed.
408 * $.jqplot.preDrawHooks - called before plot draw.
409 * $.jqplot.postDrawHooks - called after plot draw.
410 * $.jqplot.preDrawSeriesHooks - called before each series is drawn.
411 * $.jqplot.postDrawSeriesHooks - called after each series is drawn.
412 * $.jqplot.preDrawLegendHooks - called before the legend is drawn.
413 * $.jqplot.addLegendRowHooks - called at the end of legend draw, so plugins
414 * can add rows to the legend table.
415 * $.jqplot.preSeriesInitHooks - called before series is initialized.
416 * $.jqplot.postSeriesInitHooks - called after series is initialized.
417 * $.jqplot.preParseSeriesOptionsHooks - called before series related options
419 * $.jqplot.postParseSeriesOptionsHooks - called after series related options
421 * $.jqplot.eventListenerHooks - called at the end of plot drawing, binds
422 * listeners to the event canvas which lays on top of the grid area.
423 * $.jqplot.preDrawSeriesShadowHooks - called before series shadows are drawn.
424 * $.jqplot.postDrawSeriesShadowHooks - called after series shadows are drawn.
428 $.jqplot.preInitHooks = [];
429 $.jqplot.postInitHooks = [];
430 $.jqplot.preParseOptionsHooks = [];
431 $.jqplot.postParseOptionsHooks = [];
432 $.jqplot.preDrawHooks = [];
433 $.jqplot.postDrawHooks = [];
434 $.jqplot.preDrawSeriesHooks = [];
435 $.jqplot.postDrawSeriesHooks = [];
436 $.jqplot.preDrawLegendHooks = [];
437 $.jqplot.addLegendRowHooks = [];
438 $.jqplot.preSeriesInitHooks = [];
439 $.jqplot.postSeriesInitHooks = [];
440 $.jqplot.preParseSeriesOptionsHooks = [];
441 $.jqplot.postParseSeriesOptionsHooks = [];
442 $.jqplot.eventListenerHooks = [];
443 $.jqplot.preDrawSeriesShadowHooks = [];
444 $.jqplot.postDrawSeriesShadowHooks = [];
446 // A superclass holding some common properties and methods.
447 $.jqplot.ElemContainer = function() {
451 this._plotDimensions = {height:null, width:null};
454 $.jqplot.ElemContainer.prototype.createElement = function(el, offsets, clss, cssopts, attrib) {
455 this._offsets = offsets;
456 var klass = clss || 'jqplot';
457 var elem = document.createElement(el);
458 this._elem = $(elem);
459 this._elem.addClass(klass);
460 this._elem.css(cssopts);
461 this._elem.attr(attrib);
462 // avoid memory leak;
467 $.jqplot.ElemContainer.prototype.getWidth = function() {
469 return this._elem.outerWidth(true);
476 $.jqplot.ElemContainer.prototype.getHeight = function() {
478 return this._elem.outerHeight(true);
485 $.jqplot.ElemContainer.prototype.getPosition = function() {
487 return this._elem.position();
490 return {top:null, left:null, bottom:null, right:null};
494 $.jqplot.ElemContainer.prototype.getTop = function() {
495 return this.getPosition().top;
498 $.jqplot.ElemContainer.prototype.getLeft = function() {
499 return this.getPosition().left;
502 $.jqplot.ElemContainer.prototype.getBottom = function() {
503 return this._elem.css('bottom');
506 $.jqplot.ElemContainer.prototype.getRight = function() {
507 return this._elem.css('right');
513 * An individual axis object. Cannot be instantiated directly, but created
514 * by the Plot oject. Axis properties can be set or overriden by the
515 * options passed in from the user.
518 function Axis(name) {
519 $.jqplot.ElemContainer.call(this);
522 // Axes options are specified within an axes object at the top level of the
523 // plot options like so:
526 // > xaxis: {min: 5},
527 // > yaxis: {min: 2, max: 8, numberTicks:4},
528 // > x2axis: {pad: 1.5},
529 // > y2axis: {ticks:[22, 44, 66, 88]}
532 // There are 2 x axes, 'xaxis' and 'x2axis', and
533 // 9 yaxes, 'yaxis', 'y2axis'. 'y3axis', ... Any or all of which may be specified.
537 // Wether to display the axis on the graph.
539 // prop: tickRenderer
540 // A class of a rendering engine for creating the ticks labels displayed on the plot,
541 // See <$.jqplot.AxisTickRenderer>.
542 this.tickRenderer = $.jqplot.AxisTickRenderer;
544 // Options that will be passed to the tickRenderer, see <$.jqplot.AxisTickRenderer> options.
545 this.tickOptions = {};
546 // prop: labelRenderer
547 // A class of a rendering engine for creating an axis label.
548 this.labelRenderer = $.jqplot.AxisLabelRenderer;
549 // prop: labelOptions
550 // Options passed to the label renderer.
551 this.labelOptions = {};
553 // Label for the axis
556 // true to show the axis label.
557 this.showLabel = true;
559 // minimum value of the axis (in data units, not pixels).
562 // maximum value of the axis (in data units, not pixels).
566 // the default scaling algorithm produces superior results.
567 this.autoscale = false;
569 // Padding to extend the range above and below the data bounds.
570 // The data range is multiplied by this factor to determine minimum and maximum axis bounds.
571 // A value of 0 will be interpreted to mean no padding, and pad will be set to 1.0.
574 // Padding to extend the range above data bounds.
575 // The top of the data range is multiplied by this factor to determine maximum axis bounds.
576 // A value of 0 will be interpreted to mean no padding, and padMax will be set to 1.0.
579 // Padding to extend the range below data bounds.
580 // The bottom of the data range is multiplied by this factor to determine minimum axis bounds.
581 // A value of 0 will be interpreted to mean no padding, and padMin will be set to 1.0.
584 // 1D [val, val, ...] or 2D [[val, label], [val, label], ...] array of ticks for the axis.
585 // If no label is specified, the value is formatted into an appropriate label.
588 // Desired number of ticks. Default is to compute automatically.
590 // prop: tickInterval
591 // number of units between ticks. Mutually exclusive with numberTicks.
594 // A class of a rendering engine that handles tick generation,
595 // scaling input data to pixel grid units and drawing the axis element.
596 this.renderer = $.jqplot.LinearAxisRenderer;
597 // prop: rendererOptions
598 // renderer specific options. See <$.jqplot.LinearAxisRenderer> for options.
599 this.rendererOptions = {};
601 // Wether to show the ticks (both marks and labels) or not.
602 // Will not override showMark and showLabel options if specified on the ticks themselves.
603 this.showTicks = true;
604 // prop: showTickMarks
605 // Wether to show the tick marks (line crossing grid) or not.
606 // Overridden by showTicks and showMark option of tick itself.
607 this.showTickMarks = true;
608 // prop: showMinorTicks
609 // Wether or not to show minor ticks. This is renderer dependent.
610 this.showMinorTicks = true;
611 // prop: drawMajorGridlines
612 // True to draw gridlines for major axis ticks.
613 this.drawMajorGridlines = true;
614 // prop: drawMinorGridlines
615 // True to draw gridlines for minor ticks.
616 this.drawMinorGridlines = false;
617 // prop: drawMajorTickMarks
618 // True to draw tick marks for major axis ticks.
619 this.drawMajorTickMarks = true;
620 // prop: drawMinorTickMarks
621 // True to draw tick marks for minor ticks. This is renderer dependent.
622 this.drawMinorTickMarks = true;
623 // prop: useSeriesColor
624 // Use the color of the first series associated with this axis for the
625 // tick marks and line bordering this axis.
626 this.useSeriesColor = false;
628 // width of line stroked at the border of the axis. Defaults
629 // to the width of the grid boarder.
630 this.borderWidth = null;
632 // color of the border adjacent to the axis. Defaults to grid border color.
633 this.borderColor = null;
634 // prop: scaleToHiddenSeries
635 // True to include hidden series when computing axes bounds and scaling.
636 this.scaleToHiddenSeries = false;
637 // minimum and maximum values on the axis.
638 this._dataBounds = {min:null, max:null};
639 // statistics (min, max, mean) as well as actual data intervals for each series attached to axis.
640 // holds collection of {intervals:[], min:, max:, mean: } objects for each series on axis.
641 this._intervalStats = [];
642 // pixel position from the top left of the min value and max value on the axis.
643 this._offsets = {min:null, max:null};
647 // true to try and synchronize tick spacing across multiple axes so that ticks and
648 // grid lines line up. This has an impact on autoscaling algorithm, however.
649 // In general, autoscaling an individual axis will work better if it does not
650 // have to sync ticks.
651 this.syncTicks = null;
653 // Approximate pixel spacing between ticks on graph. Used during autoscaling.
654 // This number will be an upper bound, actual spacing will be less.
655 this.tickSpacing = 75;
656 // Properties to hold the original values for min, max, ticks, tickInterval and numberTicks
657 // so they can be restored if altered by plugins.
660 this._tickInterval = null;
661 this._numberTicks = null;
663 // hold original user options.
667 Axis.prototype = new $.jqplot.ElemContainer();
668 Axis.prototype.constructor = Axis;
670 Axis.prototype.init = function() {
671 if ($.isFunction(this.renderer)) {
672 this.renderer = new this.renderer();
675 this.tickOptions.axis = this.name;
676 // if showMark or showLabel tick options not specified, use value of axis option.
677 // showTicks overrides showTickMarks.
678 if (this.tickOptions.showMark == null) {
679 this.tickOptions.showMark = this.showTicks;
681 if (this.tickOptions.showMark == null) {
682 this.tickOptions.showMark = this.showTickMarks;
684 if (this.tickOptions.showLabel == null) {
685 this.tickOptions.showLabel = this.showTicks;
688 if (this.label == null || this.label == '') {
689 this.showLabel = false;
692 this.labelOptions.label = this.label;
694 if (this.showLabel == false) {
695 this.labelOptions.show = false;
697 // set the default padMax, padMin if not specified
698 // special check, if no padding desired, padding
699 // should be set to 1.0
703 if (this.padMax == 0) {
706 if (this.padMin == 0) {
709 if (this.padMax == null) {
710 this.padMax = (this.pad-1)/2 + 1;
712 if (this.padMin == null) {
713 this.padMin = (this.pad-1)/2 + 1;
715 // now that padMin and padMax are correctly set, reset pad in case user has supplied
716 // padMin and/or padMax
717 this.pad = this.padMax + this.padMin - 1;
718 if (this.min != null || this.max != null) {
719 this.autoscale = false;
721 // if not set, sync ticks for y axes but not x by default.
722 if (this.syncTicks == null && this.name.indexOf('y') > -1) {
723 this.syncTicks = true;
725 else if (this.syncTicks == null){
726 this.syncTicks = false;
728 this.renderer.init.call(this, this.rendererOptions);
732 Axis.prototype.draw = function(ctx, plot) {
733 // Memory Leaks patch
738 return this.renderer.draw.call(this, ctx, plot);
742 Axis.prototype.set = function() {
743 this.renderer.set.call(this);
746 Axis.prototype.pack = function(pos, offsets) {
748 this.renderer.pack.call(this, pos, offsets);
750 // these properties should all be available now.
751 if (this._min == null) {
752 this._min = this.min;
753 this._max = this.max;
754 this._tickInterval = this.tickInterval;
755 this._numberTicks = this.numberTicks;
756 this.__ticks = this._ticks;
760 // reset the axis back to original values if it has been scaled, zoomed, etc.
761 Axis.prototype.reset = function() {
762 this.renderer.reset.call(this);
765 Axis.prototype.resetScale = function(opts) {
766 $.extend(true, this, {min: null, max: null, numberTicks: null, tickInterval: null, _ticks: [], ticks: []}, opts);
767 this.resetDataBounds();
770 Axis.prototype.resetDataBounds = function() {
771 // Go through all the series attached to this axis and find
772 // the min/max bounds for this axis.
773 var db = this._dataBounds;
777 // check for when to force min 0 on bar series plots.
778 var doforce = (this.show) ? true : false;
779 for (var i=0; i<this._series.length; i++) {
781 if (s.show || this.scaleToHiddenSeries) {
783 if (s._type === 'line' && s.renderer.bands.show && this.name.charAt(0) !== 'x') {
784 d = [[0, s.renderer.bands._min], [1, s.renderer.bands._max]];
787 var minyidx = 1, maxyidx = 1;
789 if (s._type != null && s._type == 'ohlc') {
794 for (var j=0, l=d.length; j<l; j++) {
795 if (this.name == 'xaxis' || this.name == 'x2axis') {
796 if ((d[j][0] != null && d[j][0] < db.min) || db.min == null) {
799 if ((d[j][0] != null && d[j][0] > db.max) || db.max == null) {
804 if ((d[j][minyidx] != null && d[j][minyidx] < db.min) || db.min == null) {
805 db.min = d[j][minyidx];
807 if ((d[j][maxyidx] != null && d[j][maxyidx] > db.max) || db.max == null) {
808 db.max = d[j][maxyidx];
813 // Hack to not pad out bottom of bar plots unless user has specified a padding.
814 // every series will have a chance to set doforce to false. once it is set to
815 // false, it cannot be reset to true.
816 // If any series attached to axis is not a bar, wont force 0.
817 if (doforce && s.renderer.constructor !== $.jqplot.BarRenderer) {
821 else if (doforce && this._options.hasOwnProperty('forceTickAt0') && this._options.forceTickAt0 == false) {
825 else if (doforce && s.renderer.constructor === $.jqplot.BarRenderer) {
826 if (s.barDirection == 'vertical' && this.name != 'xaxis' && this.name != 'x2axis') {
827 if (this._options.pad != null || this._options.padMin != null) {
832 else if (s.barDirection == 'horizontal' && (this.name == 'xaxis' || this.name == 'x2axis')) {
833 if (this._options.pad != null || this._options.padMin != null) {
842 if (doforce && this.renderer.constructor === $.jqplot.LinearAxisRenderer && db.min >= 0) {
844 this.forceTickAt0 = true;
850 * Legend object. Cannot be instantiated directly, but created
851 * by the Plot oject. Legend properties can be set or overriden by the
852 * options passed in from the user.
854 function Legend(options) {
855 $.jqplot.ElemContainer.call(this);
859 // Wether to display the legend on the graph.
862 // Placement of the legend. one of the compass directions: nw, n, ne, e, se, s, sw, w
863 this.location = 'ne';
865 // Array of labels to use. By default the renderer will look for labels on the series.
866 // Labels specified in this array will override labels specified on the series.
869 // true to show the label text on the legend.
870 this.showLabels = true;
872 // true to show the color swatches on the legend.
873 this.showSwatches = true;
875 // "insideGrid" places legend inside the grid area of the plot.
876 // "outsideGrid" places the legend outside the grid but inside the plot container,
877 // shrinking the grid to accomodate the legend.
878 // "inside" synonym for "insideGrid",
879 // "outside" places the legend ouside the grid area, but does not shrink the grid which
880 // can cause the legend to overflow the plot container.
881 this.placement = "insideGrid";
883 // DEPRECATED. Set the margins on the legend using the marginTop, marginLeft, etc.
884 // properties or via CSS margin styling of the .jqplot-table-legend class.
887 // DEPRECATED. Set the margins on the legend using the marginTop, marginLeft, etc.
888 // properties or via CSS margin styling of the .jqplot-table-legend class.
891 // css spec for the border around the legend box.
894 // css spec for the background of the legend box.
897 // css color spec for the legend text.
900 // css font-family spec for the legend text.
903 // css font-size spec for the legend text.
906 // css padding-top spec for the rows in the legend.
907 this.rowSpacing = '0.5em';
909 // A class that will create a DOM object for the legend,
910 // see <$.jqplot.TableLegendRenderer>.
911 this.renderer = $.jqplot.TableLegendRenderer;
912 // prop: rendererOptions
913 // renderer specific options passed to the renderer.
914 this.rendererOptions = {};
916 // Wether to draw the legend before the series or not.
917 // Used with series specific legend renderers for pie, donut, mekko charts, etc.
918 this.preDraw = false;
920 // CSS margin for the legend DOM element. This will set an element
921 // CSS style for the margin which will override any style sheet setting.
922 // The default will be taken from the stylesheet.
923 this.marginTop = null;
925 // CSS margin for the legend DOM element. This will set an element
926 // CSS style for the margin which will override any style sheet setting.
927 // The default will be taken from the stylesheet.
928 this.marginRight = null;
929 // prop: marginBottom
930 // CSS margin for the legend DOM element. This will set an element
931 // CSS style for the margin which will override any style sheet setting.
932 // The default will be taken from the stylesheet.
933 this.marginBottom = null;
935 // CSS margin for the legend DOM element. This will set an element
936 // CSS style for the margin which will override any style sheet setting.
937 // The default will be taken from the stylesheet.
938 this.marginLeft = null;
940 // True to escape special characters with their html entity equivalents
941 // in legend text. "<" becomes < and so on, so html tags are not rendered.
942 this.escapeHtml = false;
945 $.extend(true, this, options);
948 Legend.prototype = new $.jqplot.ElemContainer();
949 Legend.prototype.constructor = Legend;
951 Legend.prototype.setOptions = function(options) {
952 $.extend(true, this, options);
954 // Try to emulate deprecated behaviour
955 // if user has specified xoffset or yoffset, copy these to
956 // the margin properties.
958 if (this.placement == 'inside') {
959 this.placement = 'insideGrid';
962 if (this.xoffset >0) {
963 if (this.placement == 'insideGrid') {
964 switch (this.location) {
968 if (this.marginLeft == null) {
969 this.marginLeft = this.xoffset + 'px';
971 this.marginRight = '0px';
977 if (this.marginRight == null) {
978 this.marginRight = this.xoffset + 'px';
980 this.marginLeft = '0px';
984 else if (this.placement == 'outside') {
985 switch (this.location) {
989 if (this.marginRight == null) {
990 this.marginRight = this.xoffset + 'px';
992 this.marginLeft = '0px';
998 if (this.marginLeft == null) {
999 this.marginLeft = this.xoffset + 'px';
1001 this.marginRight = '0px';
1008 if (this.yoffset >0) {
1009 if (this.placement == 'outside') {
1010 switch (this.location) {
1014 if (this.marginTop == null) {
1015 this.marginTop = this.yoffset + 'px';
1017 this.marginBottom = '0px';
1023 if (this.marginBottom == null) {
1024 this.marginBottom = this.yoffset + 'px';
1026 this.marginTop = '0px';
1030 else if (this.placement == 'insideGrid') {
1031 switch (this.location) {
1035 if (this.marginBottom == null) {
1036 this.marginBottom = this.yoffset + 'px';
1038 this.marginTop = '0px';
1044 if (this.marginTop == null) {
1045 this.marginTop = this.yoffset + 'px';
1047 this.marginBottom = '0px';
1055 // Handle case where offsets are < 0.
1059 Legend.prototype.init = function() {
1060 if ($.isFunction(this.renderer)) {
1061 this.renderer = new this.renderer();
1063 this.renderer.init.call(this, this.rendererOptions);
1066 Legend.prototype.draw = function(offsets, plot) {
1067 for (var i=0; i<$.jqplot.preDrawLegendHooks.length; i++){
1068 $.jqplot.preDrawLegendHooks[i].call(this, offsets);
1070 return this.renderer.draw.call(this, offsets, plot);
1073 Legend.prototype.pack = function(offsets) {
1074 this.renderer.pack.call(this, offsets);
1079 * Plot Title object. Cannot be instantiated directly, but created
1080 * by the Plot oject. Title properties can be set or overriden by the
1081 * options passed in from the user.
1084 * text - text of the title.
1086 function Title(text) {
1087 $.jqplot.ElemContainer.call(this);
1088 // Group: Properties
1091 // text of the title;
1094 // wether or not to show the title
1097 // css font-family spec for the text.
1100 // css font-size spec for the text.
1103 // css text-align spec for the text.
1106 // css color spec for the text.
1109 // A class for creating a DOM element for the title,
1110 // see <$.jqplot.DivTitleRenderer>.
1111 this.renderer = $.jqplot.DivTitleRenderer;
1112 // prop: rendererOptions
1113 // renderer specific options passed to the renderer.
1114 this.rendererOptions = {};
1116 // True to escape special characters with their html entity equivalents
1117 // in title text. "<" becomes < and so on, so html tags are not rendered.
1118 this.escapeHtml = false;
1121 Title.prototype = new $.jqplot.ElemContainer();
1122 Title.prototype.constructor = Title;
1124 Title.prototype.init = function() {
1125 if ($.isFunction(this.renderer)) {
1126 this.renderer = new this.renderer();
1128 this.renderer.init.call(this, this.rendererOptions);
1131 Title.prototype.draw = function(width) {
1132 return this.renderer.draw.call(this, width);
1135 Title.prototype.pack = function() {
1136 this.renderer.pack.call(this);
1142 * An individual data series object. Cannot be instantiated directly, but created
1143 * by the Plot oject. Series properties can be set or overriden by the
1144 * options passed in from the user.
1146 function Series(options) {
1147 options = options || {};
1148 $.jqplot.ElemContainer.call(this);
1149 // Group: Properties
1150 // Properties will be assigned from a series array at the top level of the
1151 // options. If you had two series and wanted to change the color and line
1152 // width of the first and set the second to use the secondary y axis with
1153 // no shadow and supply custom labels for each:
1156 // > {color: '#ff4466', lineWidth: 5, label:'good line'},
1157 // > {yaxis: 'y2axis', shadow: false, label:'bad line'}
1162 // wether or not to draw the series.
1165 // which x axis to use with this series, either 'xaxis' or 'x2axis'.
1166 this.xaxis = 'xaxis';
1169 // which y axis to use with this series, either 'yaxis' or 'y2axis'.
1170 this.yaxis = 'yaxis';
1172 this.gridBorderWidth = 2.0;
1174 // A class of a renderer which will draw the series,
1175 // see <$.jqplot.LineRenderer>.
1176 this.renderer = $.jqplot.LineRenderer;
1177 // prop: rendererOptions
1178 // Options to pass on to the renderer.
1179 this.rendererOptions = {};
1183 // Line label to use in the legend.
1186 // true to show label for this series in the legend.
1187 this.showLabel = true;
1189 // css color spec for the series
1191 // prop: negativeColor
1192 // css color spec used for filled (area) plots that are filled to zero and
1193 // the "useNegativeColors" option is true.
1196 // width of the line in pixels. May have different meanings depending on renderer.
1197 this.lineWidth = 2.5;
1199 // Canvas lineJoin style between segments of series.
1200 this.lineJoin = 'round';
1202 // Canvas lineCap style at ends of line.
1203 this.lineCap = 'round';
1204 // prop: linePattern
1205 // line pattern 'dashed', 'dotted', 'solid', some combination
1206 // of '-' and '.' characters such as '.-.' or a numerical array like
1207 // [draw, skip, draw, skip, ...] such as [1, 10] to draw a dotted line,
1208 // [1, 10, 20, 10] to draw a dot-dash line, and so on.
1209 this.linePattern = 'solid';
1211 // prop: shadowAngle
1212 // Shadow angle in degrees
1213 this.shadowAngle = 45;
1214 // prop: shadowOffset
1215 // Shadow offset from line in pixels
1216 this.shadowOffset = 1.25;
1217 // prop: shadowDepth
1218 // Number of times shadow is stroked, each stroke offset shadowOffset from the last.
1219 this.shadowDepth = 3;
1220 // prop: shadowAlpha
1221 // Alpha channel transparency of shadow. 0 = transparent.
1222 this.shadowAlpha = '0.1';
1223 // prop: breakOnNull
1224 // Wether line segments should be be broken at null value.
1225 // False will join point on either side of line.
1226 this.breakOnNull = false;
1227 // prop: markerRenderer
1228 // A class of a renderer which will draw marker (e.g. circle, square, ...) at the data points,
1229 // see <$.jqplot.MarkerRenderer>.
1230 this.markerRenderer = $.jqplot.MarkerRenderer;
1231 // prop: markerOptions
1232 // renderer specific options to pass to the markerRenderer,
1233 // see <$.jqplot.MarkerRenderer>.
1234 this.markerOptions = {};
1236 // wether to actually draw the line or not. Series will still be renderered, even if no line is drawn.
1237 this.showLine = true;
1239 // wether or not to show the markers at the data points.
1240 this.showMarker = true;
1242 // 0 based index of this series in the plot series array.
1245 // true or false, wether to fill under lines or in bars.
1246 // May not be implemented in all renderers.
1249 // CSS color spec to use for fill under line. Defaults to line color.
1252 // Alpha transparency to apply to the fill under the line.
1253 // Use this to adjust alpha separate from fill color.
1255 // prop: fillAndStroke
1256 // If true will stroke the line (with color this.color) as well as fill under it.
1257 // Applies only when fill is true.
1258 this.fillAndStroke = false;
1259 // prop: disableStack
1260 // true to not stack this series with other series in the plot.
1261 // To render properly, non-stacked series must come after any stacked series
1262 // in the plot's data series array. So, the plot's data series array would look like:
1263 // > [stackedSeries1, stackedSeries2, ..., nonStackedSeries1, nonStackedSeries2, ...]
1264 // disableStack will put a gap in the stacking order of series, and subsequent
1265 // stacked series will not fill down through the non-stacked series and will
1266 // most likely not stack properly on top of the non-stacked series.
1267 this.disableStack = false;
1268 // _stack is set by the Plot if the plot is a stacked chart.
1269 // will stack lines or bars on top of one another to build a "mountain" style chart.
1270 // May not be implemented in all renderers.
1271 this._stack = false;
1272 // prop: neighborThreshold
1273 // how close or far (in pixels) the cursor must be from a point marker to detect the point.
1274 this.neighborThreshold = 4;
1276 // true will force bar and filled series to fill toward zero on the fill Axis.
1277 this.fillToZero = false;
1278 // prop: fillToValue
1279 // fill a filled series to this value on the fill axis.
1280 // Works in conjunction with fillToZero, so that must be true.
1281 this.fillToValue = 0;
1283 // Either 'x' or 'y'. Which axis to fill the line toward if fillToZero is true.
1284 // 'y' means fill up/down to 0 on the y axis for this series.
1285 this.fillAxis = 'y';
1286 // prop: useNegativeColors
1287 // true to color negative values differently in filled and bar charts.
1288 this.useNegativeColors = true;
1289 this._stackData = [];
1290 // _plotData accounts for stacking. If plots not stacked, _plotData and data are same. If
1291 // stacked, _plotData is accumulation of stacking data.
1292 this._plotData = [];
1293 // _plotValues hold the individual x and y values that will be plotted for this series.
1294 this._plotValues = {x:[], y:[]};
1295 // statistics about the intervals between data points. Used for auto scaling.
1296 this._intervals = {x:{}, y:{}};
1297 // data from the previous series, for stacked charts.
1298 this._prevPlotData = [];
1299 this._prevGridData = [];
1300 this._stackAxis = 'y';
1301 this._primaryAxis = '_xaxis';
1302 // give each series a canvas to draw on. This should allow for redrawing speedups.
1303 this.canvas = new $.jqplot.GenericCanvas();
1304 this.shadowCanvas = new $.jqplot.GenericCanvas();
1306 // sum of y values in this series.
1312 Series.prototype = new $.jqplot.ElemContainer();
1313 Series.prototype.constructor = Series;
1315 Series.prototype.init = function(index, gridbw, plot) {
1316 // weed out any null values in the data.
1318 this.gridBorderWidth = gridbw;
1320 var temp = [], i, l;
1321 for (i=0, l=d.length; i<l; i++) {
1322 if (! this.breakOnNull) {
1323 if (d[i] == null || d[i][0] == null || d[i][1] == null) {
1331 // TODO: figure out what to do with null values
1332 // probably involve keeping nulls in data array
1333 // and then updating renderers to break line
1334 // when it hits null value.
1335 // For now, just keep value.
1341 // parse the renderer options and apply default colors if not provided
1342 // Set color even if not shown, so series don't change colors when other
1343 // series on plot shown/hidden.
1345 this.color = plot.colorGenerator.get(this.index);
1347 if (!this.negativeColor) {
1348 this.negativeColor = plot.negativeColorGenerator.get(this.index);
1352 if (!this.fillColor) {
1353 this.fillColor = this.color;
1355 if (this.fillAlpha) {
1356 var comp = $.jqplot.normalize2rgb(this.fillColor);
1357 var comp = $.jqplot.getColorComponents(comp);
1358 this.fillColor = 'rgba('+comp[0]+','+comp[1]+','+comp[2]+','+this.fillAlpha+')';
1360 if ($.isFunction(this.renderer)) {
1361 this.renderer = new this.renderer();
1363 this.renderer.init.call(this, this.rendererOptions, plot);
1364 this.markerRenderer = new this.markerRenderer();
1365 if (!this.markerOptions.color) {
1366 this.markerOptions.color = this.color;
1368 if (this.markerOptions.show == null) {
1369 this.markerOptions.show = this.showMarker;
1371 this.showMarker = this.markerOptions.show;
1372 // the markerRenderer is called within it's own scaope, don't want to overwrite series options!!
1373 this.markerRenderer.init(this.markerOptions);
1376 // data - optional data point array to draw using this series renderer
1377 // gridData - optional grid data point array to draw using this series renderer
1378 // stackData - array of cumulative data for stacked plots.
1379 Series.prototype.draw = function(sctx, opts, plot) {
1380 var options = (opts == undefined) ? {} : opts;
1381 sctx = (sctx == undefined) ? this.canvas._ctx : sctx;
1383 var j, data, gridData;
1385 // hooks get called even if series not shown
1386 // we don't clear canvas here, it would wipe out all other series as well.
1387 for (j=0; j<$.jqplot.preDrawSeriesHooks.length; j++) {
1388 $.jqplot.preDrawSeriesHooks[j].call(this, sctx, options);
1391 this.renderer.setGridData.call(this, plot);
1392 if (!options.preventJqPlotSeriesDrawTrigger) {
1393 $(sctx.canvas).trigger('jqplotSeriesDraw', [this.data, this.gridData]);
1397 data = options.data;
1399 else if (!this._stack) {
1403 data = this._plotData;
1405 gridData = options.gridData || this.renderer.makeGridData.call(this, data, plot);
1407 if (this._type === 'line' && this.renderer.smooth && this.renderer._smoothedData.length) {
1408 gridData = this.renderer._smoothedData;
1411 this.renderer.draw.call(this, sctx, gridData, options, plot);
1414 for (j=0; j<$.jqplot.postDrawSeriesHooks.length; j++) {
1415 $.jqplot.postDrawSeriesHooks[j].call(this, sctx, options, plot);
1418 sctx = opts = plot = j = data = gridData = null;
1421 Series.prototype.drawShadow = function(sctx, opts, plot) {
1422 var options = (opts == undefined) ? {} : opts;
1423 sctx = (sctx == undefined) ? this.shadowCanvas._ctx : sctx;
1425 var j, data, gridData;
1427 // hooks get called even if series not shown
1428 // we don't clear canvas here, it would wipe out all other series as well.
1429 for (j=0; j<$.jqplot.preDrawSeriesShadowHooks.length; j++) {
1430 $.jqplot.preDrawSeriesShadowHooks[j].call(this, sctx, options);
1433 this.renderer.setGridData.call(this, plot);
1437 data = options.data;
1439 else if (!this._stack) {
1443 data = this._plotData;
1445 gridData = options.gridData || this.renderer.makeGridData.call(this, data, plot);
1447 this.renderer.drawShadow.call(this, sctx, gridData, options, plot);
1450 for (j=0; j<$.jqplot.postDrawSeriesShadowHooks.length; j++) {
1451 $.jqplot.postDrawSeriesShadowHooks[j].call(this, sctx, options);
1454 sctx = opts = plot = j = data = gridData = null;
1458 // toggles series display on plot, e.g. show/hide series
1459 Series.prototype.toggleDisplay = function(ev, callback) {
1461 if (ev.data.series) {
1468 if (ev.data.speed) {
1469 speed = ev.data.speed;
1472 // this can be tricky because series may not have a canvas element if replotting.
1473 if (s.canvas._elem.is(':hidden') || !s.show) {
1476 s.canvas._elem.removeClass('jqplot-series-hidden');
1477 if (s.shadowCanvas._elem) {
1478 s.shadowCanvas._elem.fadeIn(speed);
1480 s.canvas._elem.fadeIn(speed, callback);
1481 s.canvas._elem.nextAll('.jqplot-point-label.jqplot-series-'+s.index).fadeIn(speed);
1486 s.canvas._elem.addClass('jqplot-series-hidden');
1487 if (s.shadowCanvas._elem) {
1488 s.shadowCanvas._elem.fadeOut(speed);
1490 s.canvas._elem.fadeOut(speed, callback);
1491 s.canvas._elem.nextAll('.jqplot-point-label.jqplot-series-'+s.index).fadeOut(speed);
1495 // this can be tricky because series may not have a canvas element if replotting.
1496 if (s.canvas._elem.is(':hidden') || !s.show) {
1499 s.canvas._elem.removeClass('jqplot-series-hidden');
1500 if (s.shadowCanvas._elem) {
1501 s.shadowCanvas._elem.show();
1503 s.canvas._elem.show(0, callback);
1504 s.canvas._elem.nextAll('.jqplot-point-label.jqplot-series-'+s.index).show();
1509 s.canvas._elem.addClass('jqplot-series-hidden');
1510 if (s.shadowCanvas._elem) {
1511 s.shadowCanvas._elem.hide();
1513 s.canvas._elem.hide(0, callback);
1514 s.canvas._elem.nextAll('.jqplot-point-label.jqplot-series-'+s.index).hide();
1524 * Object representing the grid on which the plot is drawn. The grid in this
1525 * context is the area bounded by the axes, the area which will contain the series.
1526 * Note, the series are drawn on their own canvas.
1527 * The Grid object cannot be instantiated directly, but is created by the Plot oject.
1528 * Grid properties can be set or overriden by the options passed in from the user.
1531 $.jqplot.ElemContainer.call(this);
1532 // Group: Properties
1534 // prop: drawGridlines
1535 // wether to draw the gridlines on the plot.
1536 this.drawGridlines = true;
1537 // prop: gridLineColor
1538 // color of the grid lines.
1539 this.gridLineColor = '#cccccc';
1540 // prop: gridLineWidth
1541 // width of the grid lines.
1542 this.gridLineWidth = 1.0;
1544 // css spec for the background color.
1545 this.background = '#fffdf6';
1546 // prop: borderColor
1547 // css spec for the color of the grid border.
1548 this.borderColor = '#999999';
1549 // prop: borderWidth
1550 // width of the border in pixels.
1551 this.borderWidth = 2.0;
1553 // True to draw border around grid.
1554 this.drawBorder = true;
1556 // wether to show a shadow behind the grid.
1558 // prop: shadowAngle
1559 // shadow angle in degrees
1560 this.shadowAngle = 45;
1561 // prop: shadowOffset
1562 // Offset of each shadow stroke from the border in pixels
1563 this.shadowOffset = 1.5;
1564 // prop: shadowWidth
1565 // width of the stoke for the shadow
1566 this.shadowWidth = 3;
1567 // prop: shadowDepth
1568 // Number of times shadow is stroked, each stroke offset shadowOffset from the last.
1569 this.shadowDepth = 3;
1570 // prop: shadowColor
1571 // an optional css color spec for the shadow in 'rgba(n, n, n, n)' form
1572 this.shadowColor = null;
1573 // prop: shadowAlpha
1574 // Alpha channel transparency of shadow. 0 = transparent.
1575 this.shadowAlpha = '0.07';
1584 // Instance of a renderer which will actually render the grid,
1585 // see <$.jqplot.CanvasGridRenderer>.
1586 this.renderer = $.jqplot.CanvasGridRenderer;
1587 // prop: rendererOptions
1588 // Options to pass on to the renderer,
1589 // see <$.jqplot.CanvasGridRenderer>.
1590 this.rendererOptions = {};
1591 this._offsets = {top:null, bottom:null, left:null, right:null};
1594 Grid.prototype = new $.jqplot.ElemContainer();
1595 Grid.prototype.constructor = Grid;
1597 Grid.prototype.init = function() {
1598 if ($.isFunction(this.renderer)) {
1599 this.renderer = new this.renderer();
1601 this.renderer.init.call(this, this.rendererOptions);
1604 Grid.prototype.createElement = function(offsets,plot) {
1605 this._offsets = offsets;
1606 return this.renderer.createElement.call(this, plot);
1609 Grid.prototype.draw = function() {
1610 this.renderer.draw.call(this);
1613 $.jqplot.GenericCanvas = function() {
1614 $.jqplot.ElemContainer.call(this);
1618 $.jqplot.GenericCanvas.prototype = new $.jqplot.ElemContainer();
1619 $.jqplot.GenericCanvas.prototype.constructor = $.jqplot.GenericCanvas;
1621 $.jqplot.GenericCanvas.prototype.createElement = function(offsets, clss, plotDimensions, plot) {
1622 this._offsets = offsets;
1623 var klass = 'jqplot';
1624 if (clss != undefined) {
1629 elem = plot.canvasManager.getCanvas();
1631 // if new plotDimensions supplied, use them.
1632 if (plotDimensions != null) {
1633 this._plotDimensions = plotDimensions;
1636 elem.width = this._plotDimensions.width - this._offsets.left - this._offsets.right;
1637 elem.height = this._plotDimensions.height - this._offsets.top - this._offsets.bottom;
1638 this._elem = $(elem);
1639 this._elem.css({ position: 'absolute', left: this._offsets.left, top: this._offsets.top });
1641 this._elem.addClass(klass);
1643 elem = plot.canvasManager.initCanvas(elem);
1649 $.jqplot.GenericCanvas.prototype.setContext = function() {
1650 this._ctx = this._elem.get(0).getContext("2d");
1654 // Memory Leaks patch
1655 $.jqplot.GenericCanvas.prototype.resetCanvas = function() {
1657 if ($.jqplot.use_excanvas && window.G_vmlCanvasManager.uninitElement !== undefined) {
1658 window.G_vmlCanvasManager.uninitElement(this._elem.get(0));
1661 //this._elem.remove();
1662 this._elem.emptyForce();
1668 $.jqplot.HooksManager = function () {
1673 $.jqplot.HooksManager.prototype.addOnce = function(fn, args) {
1675 var havehook = false;
1676 for (var i=0, l=this.hooks.length; i<l; i++) {
1677 if (this.hooks[i] == fn) {
1682 this.hooks.push(fn);
1683 this.args.push(args);
1687 $.jqplot.HooksManager.prototype.add = function(fn, args) {
1689 this.hooks.push(fn);
1690 this.args.push(args);
1693 $.jqplot.EventListenerManager = function () {
1697 $.jqplot.EventListenerManager.prototype.addOnce = function(ev, fn) {
1698 var havehook = false, h, i;
1699 for (var i=0, l=this.hooks.length; i<l; i++) {
1701 if (h[0] == ev && h[1] == fn) {
1706 this.hooks.push([ev, fn]);
1710 $.jqplot.EventListenerManager.prototype.add = function(ev, fn) {
1711 this.hooks.push([ev, fn]);
1715 var _axisNames = ['yMidAxis', 'xaxis', 'yaxis', 'x2axis', 'y2axis', 'y3axis', 'y4axis', 'y5axis', 'y6axis', 'y7axis', 'y8axis', 'y9axis'];
1719 * Plot object returned by call to $.jqplot. Handles parsing user options,
1720 * creating sub objects (Axes, legend, title, series) and rendering the plot.
1723 // Group: Properties
1724 // These properties are specified at the top of the options object
1727 // > axesDefaults:{min:0},
1728 // > series:[{color:'#6633dd'}],
1729 // > title: 'A Plot'
1734 // True to animate the series on initial plot draw (renderer dependent).
1735 // Actual animation functionality must be supported in the renderer.
1736 this.animate = false;
1737 // prop: animateReplot
1738 // True to animate series after a call to the replot() method.
1739 // Use with caution! Replots can happen very frequently under
1740 // certain circumstances (e.g. resizing, dragging points) and
1741 // animation in these situations can cause problems.
1742 this.animateReplot = false;
1744 // up to 4 axes are supported, each with it's own options,
1745 // See <Axis> for axis specific options.
1746 this.axes = {xaxis: new Axis('xaxis'), yaxis: new Axis('yaxis'), x2axis: new Axis('x2axis'), y2axis: new Axis('y2axis'), y3axis: new Axis('y3axis'), y4axis: new Axis('y4axis'), y5axis: new Axis('y5axis'), y6axis: new Axis('y6axis'), y7axis: new Axis('y7axis'), y8axis: new Axis('y8axis'), y9axis: new Axis('y9axis'), yMidAxis: new Axis('yMidAxis')};
1747 this.baseCanvas = new $.jqplot.GenericCanvas();
1748 // true to intercept right click events and fire a 'jqplotRightClick' event.
1749 // this will also block the context menu.
1750 this.captureRightClick = false;
1752 // user's data. Data should *NOT* be specified in the options object,
1753 // but be passed in as the second argument to the $.jqplot() function.
1754 // The data property is described here soley for reference.
1755 // The data should be in the form of an array of 2D or 1D arrays like
1756 // > [ [[x1, y1], [x2, y2],...], [y1, y2, ...] ].
1758 // prop: dataRenderer
1759 // A callable which can be used to preprocess data passed into the plot.
1760 // Will be called with 2 arguments, the plot data and a reference to the plot.
1762 // prop: dataRendererOptions
1763 // Options that will be passed to the dataRenderer.
1764 // Can be of any type.
1765 this.dataRendererOptions;
1767 // prop: axesDefaults
1768 // default options that will be applied to all axes.
1769 // see <Axis> for axes options.
1771 axes: {xaxis:{}, yaxis:{}, x2axis:{}, y2axis:{}, y3axis:{}, y4axis:{}, y5axis:{}, y6axis:{}, y7axis:{}, y8axis:{}, y9axis:{}, yMidAxis:{}},
1772 // prop: seriesDefaults
1773 // default options that will be applied to all series.
1774 // see <Series> for series options.
1778 // prop: defaultAxisStart
1779 // 1-D data series are internally converted into 2-D [x,y] data point arrays
1780 // by jqPlot. This is the default starting value for the missing x or y value.
1781 // The added data will be a monotonically increasing series (e.g. [1, 2, 3, ...])
1782 // starting at this value.
1783 this.defaultAxisStart = 1;
1784 // this.doCustomEventBinding = true;
1785 // prop: drawIfHidden
1786 // True to execute the draw method even if the plot target is hidden.
1787 // Generally, this should be false. Most plot elements will not be sized/
1788 // positioned correclty if renderered into a hidden container. To render into
1789 // a hidden container, call the replot method when the container is shown.
1790 this.drawIfHidden = false;
1791 this.eventCanvas = new $.jqplot.GenericCanvas();
1792 // prop: fillBetween
1793 // Fill between 2 line series in a plot.
1796 // series1: first index (0 based) of series in fill
1797 // series2: second index (0 based) of series in fill
1798 // color: color of fill [default fillColor of series1]
1799 // baseSeries: fill will be drawn below this series (0 based index)
1800 // fill: false to turn off fill [default true].
1802 this.fillBetween = {
1810 // css spec for the font-family attribute. Default for the entire plot.
1813 // css spec for the font-size attribute. Default for the entire plot.
1816 // See <Grid> for grid specific options.
1817 this.grid = new Grid();
1819 // see <$.jqplot.TableLegendRenderer>
1820 this.legend = new Legend();
1821 // prop: noDataIndicator
1822 // Options to set up a mock plot with a data loading indicator if no data is specified.
1823 this.negativeSeriesColors = $.jqplot.config.defaultNegativeColors;
1824 this.noDataIndicator = {
1826 indicator: 'Loading Data...',
1842 // container to hold all of the merged options. Convienence for plugins.
1844 this.previousSeriesStack = [];
1845 // Namespece to hold plugins. Generally non-renderer plugins add themselves to here.
1848 // Array of series object options.
1849 // see <Series> for series specific options.
1851 // array of series indicies. Keep track of order
1852 // which series canvases are displayed, lowest
1853 // to highest, back to front.
1854 this.seriesStack = [];
1855 // prop: seriesColors
1856 // Ann array of CSS color specifications that will be applied, in order,
1857 // to the series in the plot. Colors will wrap around so, if their
1858 // are more series than colors, colors will be reused starting at the
1859 // beginning. For pie charts, this specifies the colors of the slices.
1860 this.seriesColors = $.jqplot.config.defaultColors;
1862 // false to not sort the data passed in by the user.
1863 // Many bar, stakced and other graphs as well as many plugins depend on
1864 // having sorted data.
1865 this.sortData = true;
1866 // prop: stackSeries
1867 // true or false, creates a stack or "mountain" plot.
1868 // Not all series renderers may implement this option.
1869 this.stackSeries = false;
1870 // a shortcut for axis syncTicks options. Not implemented yet.
1871 this.syncXTicks = true;
1872 // a shortcut for axis syncTicks options. Not implemented yet.
1873 this.syncYTicks = true;
1874 // the jquery object for the dom target.
1876 // The id of the dom element to render the plot into
1877 this.targetId = null;
1879 // css spec for the css color attribute. Default for the entire plot.
1882 // Title object. See <Title> for specific options. As a shortcut, you
1883 // can specify the title option as just a string like: title: 'My Plot'
1884 // and this will create a new title object with the specified text.
1885 this.title = new Title();
1886 // Count how many times the draw method has been called while the plot is visible.
1887 // Mostly used to test if plot has never been dran (=0), has been successfully drawn
1888 // into a visible container once (=1) or draw more than once into a visible container.
1889 // Can use this in tests to see if plot has been visibly drawn at least one time.
1890 // After plot has been visibly drawn once, it generally doesn't need redrawn if its
1891 // container is hidden and shown.
1892 this._drawCount = 0;
1893 // sum of y values for all series in plot.
1894 // used in mekko chart.
1897 // array to hold the cumulative stacked series data.
1898 // used to ajust the individual series data, which won't have access to other
1900 this._stackData = [];
1901 // array that holds the data to be plotted. This will be the series data
1902 // merged with the the appropriate data from _stackData according to the stackAxis.
1903 this._plotData = [];
1905 this._height = null;
1906 this._plotDimensions = {height:null, width:null};
1907 this._gridPadding = {top:null, right:null, bottom:null, left:null};
1908 this._defaultGridPadding = {top:10, right:10, bottom:23, left:10};
1910 this._addDomReference = $.jqplot.config.addDomReference;
1912 this.preInitHooks = new $.jqplot.HooksManager();
1913 this.postInitHooks = new $.jqplot.HooksManager();
1914 this.preParseOptionsHooks = new $.jqplot.HooksManager();
1915 this.postParseOptionsHooks = new $.jqplot.HooksManager();
1916 this.preDrawHooks = new $.jqplot.HooksManager();
1917 this.postDrawHooks = new $.jqplot.HooksManager();
1918 this.preDrawSeriesHooks = new $.jqplot.HooksManager();
1919 this.postDrawSeriesHooks = new $.jqplot.HooksManager();
1920 this.preDrawLegendHooks = new $.jqplot.HooksManager();
1921 this.addLegendRowHooks = new $.jqplot.HooksManager();
1922 this.preSeriesInitHooks = new $.jqplot.HooksManager();
1923 this.postSeriesInitHooks = new $.jqplot.HooksManager();
1924 this.preParseSeriesOptionsHooks = new $.jqplot.HooksManager();
1925 this.postParseSeriesOptionsHooks = new $.jqplot.HooksManager();
1926 this.eventListenerHooks = new $.jqplot.EventListenerManager();
1927 this.preDrawSeriesShadowHooks = new $.jqplot.HooksManager();
1928 this.postDrawSeriesShadowHooks = new $.jqplot.HooksManager();
1930 this.colorGenerator = new $.jqplot.ColorGenerator();
1931 this.negativeColorGenerator = new $.jqplot.ColorGenerator();
1933 this.canvasManager = new $.jqplot.CanvasManager();
1935 this.themeEngine = new $.jqplot.ThemeEngine();
1937 var seriesColorsIndex = 0;
1942 // sets the plot target, checks data and applies user
1944 this.init = function(target, data, options) {
1945 options = options || {};
1946 for (var i=0; i<$.jqplot.preInitHooks.length; i++) {
1947 $.jqplot.preInitHooks[i].call(this, target, data, options);
1950 for (var i=0; i<this.preInitHooks.hooks.length; i++) {
1951 this.preInitHooks.hooks[i].call(this, target, data, options);
1954 this.targetId = '#'+target;
1955 this.target = $('#'+target);
1958 // Add a reference to plot
1960 if (this._addDomReference) {
1961 this.target.data('jqplot', this);
1963 // remove any error class that may be stuck on target.
1964 this.target.removeClass('jqplot-error');
1965 if (!this.target.get(0)) {
1966 throw "No plot target specified";
1969 // make sure the target is positioned by some means and set css
1970 if (this.target.css('position') == 'static') {
1971 this.target.css('position', 'relative');
1973 if (!this.target.hasClass('jqplot-target')) {
1974 this.target.addClass('jqplot-target');
1977 // if no height or width specified, use a default.
1978 if (!this.target.height()) {
1980 if (options && options.height) {
1981 h = parseInt(options.height, 10);
1983 else if (this.target.attr('data-height')) {
1984 h = parseInt(this.target.attr('data-height'), 10);
1987 h = parseInt($.jqplot.config.defaultHeight, 10);
1990 this.target.css('height', h+'px');
1993 this._height = h = this.target.height();
1995 if (!this.target.width()) {
1997 if (options && options.width) {
1998 w = parseInt(options.width, 10);
2000 else if (this.target.attr('data-width')) {
2001 w = parseInt(this.target.attr('data-width'), 10);
2004 w = parseInt($.jqplot.config.defaultWidth, 10);
2007 this.target.css('width', w+'px');
2010 this._width = w = this.target.width();
2013 for (var i=0, l=_axisNames.length; i<l; i++) {
2014 this.axes[_axisNames[i]] = new Axis(_axisNames[i]);
2017 this._plotDimensions.height = this._height;
2018 this._plotDimensions.width = this._width;
2019 this.grid._plotDimensions = this._plotDimensions;
2020 this.title._plotDimensions = this._plotDimensions;
2021 this.baseCanvas._plotDimensions = this._plotDimensions;
2022 this.eventCanvas._plotDimensions = this._plotDimensions;
2023 this.legend._plotDimensions = this._plotDimensions;
2024 if (this._height <=0 || this._width <=0 || !this._height || !this._width) {
2025 throw "Canvas dimension not set";
2028 if (options.dataRenderer && $.isFunction(options.dataRenderer)) {
2029 if (options.dataRendererOptions) {
2030 this.dataRendererOptions = options.dataRendererOptions;
2032 this.dataRenderer = options.dataRenderer;
2033 data = this.dataRenderer(data, this, this.dataRendererOptions);
2036 if (options.noDataIndicator && $.isPlainObject(options.noDataIndicator)) {
2037 $.extend(true, this.noDataIndicator, options.noDataIndicator);
2040 if (data == null || $.isArray(data) == false || data.length == 0 || $.isArray(data[0]) == false || data[0].length == 0) {
2042 if (this.noDataIndicator.show == false) {
2047 // have to be descructive here in order for plot to not try and render series.
2048 // This means that $.jqplot() will have to be called again when there is data.
2049 //delete options.series;
2051 for (var ax in this.noDataIndicator.axes) {
2052 for (var prop in this.noDataIndicator.axes[ax]) {
2053 this.axes[ax][prop] = this.noDataIndicator.axes[ax][prop];
2057 this.postDrawHooks.add(function() {
2058 var eh = this.eventCanvas.getHeight();
2059 var ew = this.eventCanvas.getWidth();
2060 var temp = $('<div class="jqplot-noData-container" style="position:absolute;"></div>');
2061 this.target.append(temp);
2064 temp.css('top', this.eventCanvas._offsets.top);
2065 temp.css('left', this.eventCanvas._offsets.left);
2067 var temp2 = $('<div class="jqplot-noData-contents" style="text-align:center; position:relative; margin-left:auto; margin-right:auto;"></div>');
2069 temp2.html(this.noDataIndicator.indicator);
2070 var th = temp2.height();
2071 var tw = temp2.width();
2074 temp2.css('top', (eh - th)/2 + 'px');
2080 // make a copy of the data
2081 this.data = $.extend(true, [], data);
2083 this.parseOptions(options);
2085 if (this.textColor) {
2086 this.target.css('color', this.textColor);
2088 if (this.fontFamily) {
2089 this.target.css('font-family', this.fontFamily);
2091 if (this.fontSize) {
2092 this.target.css('font-size', this.fontSize);
2099 this.computePlotData();
2100 for (var i=0; i<this.series.length; i++) {
2101 // set default stacking order for series canvases
2102 this.seriesStack.push(i);
2103 this.previousSeriesStack.push(i);
2104 this.series[i].shadowCanvas._plotDimensions = this._plotDimensions;
2105 this.series[i].canvas._plotDimensions = this._plotDimensions;
2106 for (var j=0; j<$.jqplot.preSeriesInitHooks.length; j++) {
2107 $.jqplot.preSeriesInitHooks[j].call(this.series[i], target, this.data, this.options.seriesDefaults, this.options.series[i], this);
2109 for (var j=0; j<this.preSeriesInitHooks.hooks.length; j++) {
2110 this.preSeriesInitHooks.hooks[j].call(this.series[i], target, this.data, this.options.seriesDefaults, this.options.series[i], this);
2112 // this.populatePlotData(this.series[i], i);
2113 this.series[i]._plotDimensions = this._plotDimensions;
2114 this.series[i].init(i, this.grid.borderWidth, this);
2115 for (var j=0; j<$.jqplot.postSeriesInitHooks.length; j++) {
2116 $.jqplot.postSeriesInitHooks[j].call(this.series[i], target, this.data, this.options.seriesDefaults, this.options.series[i], this);
2118 for (var j=0; j<this.postSeriesInitHooks.hooks.length; j++) {
2119 this.postSeriesInitHooks.hooks[j].call(this.series[i], target, this.data, this.options.seriesDefaults, this.options.series[i], this);
2121 this._sumy += this.series[i]._sumy;
2122 this._sumx += this.series[i]._sumx;
2127 for (var i=0, l=_axisNames.length; i<l; i++) {
2128 name = _axisNames[i];
2129 axis = this.axes[name];
2130 axis._plotDimensions = this._plotDimensions;
2132 if (this.axes[name].borderColor == null) {
2133 if (name.charAt(0) !== 'x' && axis.useSeriesColor === true && axis.show) {
2134 axis.borderColor = axis._series[0].color;
2137 axis.borderColor = this.grid.borderColor;
2142 if (this.sortData) {
2143 sortData(this.series);
2146 this.grid._axes = this.axes;
2148 this.legend._series = this.series;
2150 for (var i=0; i<$.jqplot.postInitHooks.length; i++) {
2151 $.jqplot.postInitHooks[i].call(this, target, this.data, options);
2154 for (var i=0; i<this.postInitHooks.hooks.length; i++) {
2155 this.postInitHooks.hooks[i].call(this, target, this.data, options);
2159 // method: resetAxesScale
2160 // Reset the specified axes min, max, numberTicks and tickInterval properties to null
2161 // or reset these properties on all axes if no list of axes is provided.
2164 // axes - Boolean to reset or not reset all axes or an array or object of axis names to reset.
2165 this.resetAxesScale = function(axes, options) {
2166 var opts = options || {};
2167 var ax = axes || this.axes;
2171 if ($.isArray(ax)) {
2172 for (var i = 0; i < ax.length; i++) {
2173 this.axes[ax[i]].resetScale(opts[ax[i]]);
2176 else if (typeof(ax) === 'object') {
2177 for (var name in ax) {
2178 this.axes[name].resetScale(opts[name]);
2182 // method: reInitialize
2183 // reinitialize plot for replotting.
2184 // not called directly.
2185 this.reInitialize = function (data, opts) {
2186 // Plot should be visible and have a height and width.
2187 // If plot doesn't have height and width for some
2188 // reason, set it by other means. Plot must not have
2189 // a display:none attribute, however.
2191 var options = $.extend(true, {}, this.options, opts);
2193 var target = this.targetId.substr(1);
2194 var tdata = (data == null) ? this.data : data;
2196 for (var i=0; i<$.jqplot.preInitHooks.length; i++) {
2197 $.jqplot.preInitHooks[i].call(this, target, tdata, options);
2200 for (var i=0; i<this.preInitHooks.hooks.length; i++) {
2201 this.preInitHooks.hooks[i].call(this, target, tdata, options);
2204 this._height = this.target.height();
2205 this._width = this.target.width();
2207 if (this._height <=0 || this._width <=0 || !this._height || !this._width) {
2208 throw "Target dimension not set";
2211 this._plotDimensions.height = this._height;
2212 this._plotDimensions.width = this._width;
2213 this.grid._plotDimensions = this._plotDimensions;
2214 this.title._plotDimensions = this._plotDimensions;
2215 this.baseCanvas._plotDimensions = this._plotDimensions;
2216 this.eventCanvas._plotDimensions = this._plotDimensions;
2217 this.legend._plotDimensions = this._plotDimensions;
2224 for (var i=0, l=_axisNames.length; i<l; i++) {
2225 name = _axisNames[i];
2226 axis = this.axes[name];
2228 // Memory Leaks patch : clear ticks elements
2230 for (var j = 0, tlen = t.length; j < tlen; j++) {
2231 var el = t[j]._elem;
2233 // if canvas renderer
2234 if ($.jqplot.use_excanvas && window.G_vmlCanvasManager.uninitElement !== undefined) {
2235 window.G_vmlCanvasManager.uninitElement(el.get(0));
2246 this.axes[name] = new Axis(name);
2247 this.axes[name]._plotWidth = this._width;
2248 this.axes[name]._plotHeight = this._height;
2252 if (options.dataRenderer && $.isFunction(options.dataRenderer)) {
2253 if (options.dataRendererOptions) {
2254 this.dataRendererOptions = options.dataRendererOptions;
2256 this.dataRenderer = options.dataRenderer;
2257 data = this.dataRenderer(data, this, this.dataRendererOptions);
2260 // make a copy of the data
2261 this.data = $.extend(true, [], data);
2265 this.parseOptions(options);
2268 this.title._plotWidth = this._width;
2270 if (this.textColor) {
2271 this.target.css('color', this.textColor);
2273 if (this.fontFamily) {
2274 this.target.css('font-family', this.fontFamily);
2276 if (this.fontSize) {
2277 this.target.css('font-size', this.fontSize);
2285 this.seriesStack = [];
2286 this.previousSeriesStack = [];
2288 this.computePlotData();
2289 for (var i=0, l=this.series.length; i<l; i++) {
2290 // set default stacking order for series canvases
2291 this.seriesStack.push(i);
2292 this.previousSeriesStack.push(i);
2293 this.series[i].shadowCanvas._plotDimensions = this._plotDimensions;
2294 this.series[i].canvas._plotDimensions = this._plotDimensions;
2295 for (var j=0; j<$.jqplot.preSeriesInitHooks.length; j++) {
2296 $.jqplot.preSeriesInitHooks[j].call(this.series[i], target, this.data, this.options.seriesDefaults, this.options.series[i], this);
2298 for (var j=0; j<this.preSeriesInitHooks.hooks.length; j++) {
2299 this.preSeriesInitHooks.hooks[j].call(this.series[i], target, this.data, this.options.seriesDefaults, this.options.series[i], this);
2301 // this.populatePlotData(this.series[i], i);
2302 this.series[i]._plotDimensions = this._plotDimensions;
2303 this.series[i].init(i, this.grid.borderWidth, this);
2304 for (var j=0; j<$.jqplot.postSeriesInitHooks.length; j++) {
2305 $.jqplot.postSeriesInitHooks[j].call(this.series[i], target, this.data, this.options.seriesDefaults, this.options.series[i], this);
2307 for (var j=0; j<this.postSeriesInitHooks.hooks.length; j++) {
2308 this.postSeriesInitHooks.hooks[j].call(this.series[i], target, this.data, this.options.seriesDefaults, this.options.series[i], this);
2310 this._sumy += this.series[i]._sumy;
2311 this._sumx += this.series[i]._sumx;
2314 for (var i=0, l=_axisNames.length; i<l; i++) {
2315 name = _axisNames[i];
2316 axis = this.axes[name];
2318 axis._plotDimensions = this._plotDimensions;
2320 if (axis.borderColor == null) {
2321 if (name.charAt(0) !== 'x' && axis.useSeriesColor === true && axis.show) {
2322 axis.borderColor = axis._series[0].color;
2325 axis.borderColor = this.grid.borderColor;
2330 if (this.sortData) {
2331 sortData(this.series);
2334 this.grid._axes = this.axes;
2336 this.legend._series = this.series;
2338 for (var i=0, l=$.jqplot.postInitHooks.length; i<l; i++) {
2339 $.jqplot.postInitHooks[i].call(this, target, this.data, options);
2342 for (var i=0, l=this.postInitHooks.hooks.length; i<l; i++) {
2343 this.postInitHooks.hooks[i].call(this, target, this.data, options);
2349 // method: quickInit
2351 // Quick reinitialization plot for replotting.
2352 // Does not parse options ore recreate axes and series.
2353 // not called directly.
2354 this.quickInit = function () {
2355 // Plot should be visible and have a height and width.
2356 // If plot doesn't have height and width for some
2357 // reason, set it by other means. Plot must not have
2358 // a display:none attribute, however.
2360 this._height = this.target.height();
2361 this._width = this.target.width();
2363 if (this._height <=0 || this._width <=0 || !this._height || !this._width) {
2364 throw "Target dimension not set";
2367 this._plotDimensions.height = this._height;
2368 this._plotDimensions.width = this._width;
2369 this.grid._plotDimensions = this._plotDimensions;
2370 this.title._plotDimensions = this._plotDimensions;
2371 this.baseCanvas._plotDimensions = this._plotDimensions;
2372 this.eventCanvas._plotDimensions = this._plotDimensions;
2373 this.legend._plotDimensions = this._plotDimensions;
2375 for (var n in this.axes) {
2376 this.axes[n]._plotWidth = this._width;
2377 this.axes[n]._plotHeight = this._height;
2380 this.title._plotWidth = this._width;
2382 if (this.textColor) {
2383 this.target.css('color', this.textColor);
2385 if (this.fontFamily) {
2386 this.target.css('font-family', this.fontFamily);
2388 if (this.fontSize) {
2389 this.target.css('font-size', this.fontSize);
2394 this.computePlotData();
2395 for (var i=0; i<this.series.length; i++) {
2396 // this.populatePlotData(this.series[i], i);
2397 if (this.series[i]._type === 'line' && this.series[i].renderer.bands.show) {
2398 this.series[i].renderer.initBands.call(this.series[i], this.series[i].renderer.options, this);
2400 this.series[i]._plotDimensions = this._plotDimensions;
2401 this.series[i].canvas._plotDimensions = this._plotDimensions;
2402 //this.series[i].init(i, this.grid.borderWidth);
2403 this._sumy += this.series[i]._sumy;
2404 this._sumx += this.series[i]._sumx;
2409 for (var j=0; j<12; j++) {
2410 name = _axisNames[j];
2411 // Memory Leaks patch : clear ticks elements
2412 var t = this.axes[name]._ticks;
2413 for (var i = 0; i < t.length; i++) {
2414 var el = t[i]._elem;
2416 // if canvas renderer
2417 if ($.jqplot.use_excanvas && window.G_vmlCanvasManager.uninitElement !== undefined) {
2418 window.G_vmlCanvasManager.uninitElement(el.get(0));
2427 this.axes[name]._plotDimensions = this._plotDimensions;
2428 this.axes[name]._ticks = [];
2429 // this.axes[name].renderer.init.call(this.axes[name], {});
2432 if (this.sortData) {
2433 sortData(this.series);
2436 this.grid._axes = this.axes;
2438 this.legend._series = this.series;
2441 // sort the series data in increasing order.
2442 function sortData(series) {
2443 var d, sd, pd, ppd, ret;
2444 for (var i=0; i<series.length; i++) {
2446 var bat = [series[i].data, series[i]._stackData, series[i]._plotData, series[i]._prevPlotData];
2447 for (var n=0; n<4; n++) {
2450 if (series[i]._stackAxis == 'x') {
2451 for (var j = 0; j < d.length; j++) {
2452 if (typeof(d[j][1]) != "number") {
2458 d.sort(function(a,b) { return a[1] - b[1]; });
2462 for (var j = 0; j < d.length; j++) {
2463 if (typeof(d[j][0]) != "number") {
2469 d.sort(function(a,b) { return a[0] - b[0]; });
2477 this.computePlotData = function() {
2478 this._plotData = [];
2479 this._stackData = [];
2485 for (index=0, l=this.series.length; index<l; index++) {
2486 series = this.series[index];
2487 this._plotData.push([]);
2488 this._stackData.push([]);
2489 var cd = series.data;
2490 this._plotData[index] = $.extend(true, [], cd);
2491 this._stackData[index] = $.extend(true, [], cd);
2492 series._plotData = this._plotData[index];
2493 series._stackData = this._stackData[index];
2494 var plotValues = {x:[], y:[]};
2496 if (this.stackSeries && !series.disableStack) {
2497 series._stack = true;
2498 ///////////////////////////
2499 // have to check for nulls
2500 ///////////////////////////
2501 var sidx = (series._stackAxis === 'x') ? 0 : 1;
2503 for (var k=0, cdl=cd.length; k<cdl; k++) {
2504 var temp = cd[k][sidx];
2508 this._plotData[index][k][sidx] = temp;
2509 this._stackData[index][k][sidx] = temp;
2512 for (var j=index; j--;) {
2513 var prevval = this._plotData[j][k][sidx];
2514 // only need to sum up the stack axis column of data
2515 // and only sum if it is of same sign.
2516 // if previous series isn't same sign, keep looking
2517 // at earlier series untill we find one of same sign.
2518 if (temp * prevval >= 0) {
2519 this._plotData[index][k][sidx] += prevval;
2520 this._stackData[index][k][sidx] += prevval;
2529 for (var i=0; i<series.data.length; i++) {
2530 plotValues.x.push(series.data[i][0]);
2531 plotValues.y.push(series.data[i][1]);
2533 this._stackData.push(series.data);
2534 this.series[index]._stackData = series.data;
2535 this._plotData.push(series.data);
2536 series._plotData = series.data;
2537 series._plotValues = plotValues;
2540 series._prevPlotData = this.series[index-1]._plotData;
2544 for (i=series.data.length-1; i>-1; i--) {
2545 series._sumy += series.data[i][1];
2546 series._sumx += series.data[i][0];
2552 // populate the _stackData and _plotData arrays for the plot and the series.
2553 this.populatePlotData = function(series, index) {
2554 // if a stacked chart, compute the stacked data
2555 this._plotData = [];
2556 this._stackData = [];
2557 series._stackData = [];
2558 series._plotData = [];
2559 var plotValues = {x:[], y:[]};
2560 if (this.stackSeries && !series.disableStack) {
2561 series._stack = true;
2562 var sidx = (series._stackAxis === 'x') ? 0 : 1;
2563 // var idx = sidx ? 0 : 1;
2564 // push the current data into stackData
2565 //this._stackData.push(this.series[i].data);
2566 var temp = $.extend(true, [], series.data);
2567 // create the data that will be plotted for this series
2568 var plotdata = $.extend(true, [], series.data);
2569 var tempx, tempy, dval, stackval, comparator;
2570 // for first series, nothing to add to stackData.
2571 for (var j=0; j<index; j++) {
2572 var cd = this.series[j].data;
2573 for (var k=0; k<cd.length; k++) {
2575 tempx = (dval[0] != null) ? dval[0] : 0;
2576 tempy = (dval[1] != null) ? dval[1] : 0;
2577 temp[k][0] += tempx;
2578 temp[k][1] += tempy;
2579 stackval = (sidx) ? tempy : tempx;
2580 // only need to sum up the stack axis column of data
2581 // and only sum if it is of same sign.
2582 if (series.data[k][sidx] * stackval >= 0) {
2583 plotdata[k][sidx] += stackval;
2587 for (var i=0; i<plotdata.length; i++) {
2588 plotValues.x.push(plotdata[i][0]);
2589 plotValues.y.push(plotdata[i][1]);
2591 this._plotData.push(plotdata);
2592 this._stackData.push(temp);
2593 series._stackData = temp;
2594 series._plotData = plotdata;
2595 series._plotValues = plotValues;
2598 for (var i=0; i<series.data.length; i++) {
2599 plotValues.x.push(series.data[i][0]);
2600 plotValues.y.push(series.data[i][1]);
2602 this._stackData.push(series.data);
2603 this.series[index]._stackData = series.data;
2604 this._plotData.push(series.data);
2605 series._plotData = series.data;
2606 series._plotValues = plotValues;
2609 series._prevPlotData = this.series[index-1]._plotData;
2613 for (i=series.data.length-1; i>-1; i--) {
2614 series._sumy += series.data[i][1];
2615 series._sumx += series.data[i][0];
2619 // function to safely return colors from the color array and wrap around at the end.
2620 this.getNextSeriesColor = (function(t) {
2622 var sc = t.seriesColors;
2624 return function () {
2625 if (idx < sc.length) {
2635 this.parseOptions = function(options){
2636 for (var i=0; i<this.preParseOptionsHooks.hooks.length; i++) {
2637 this.preParseOptionsHooks.hooks[i].call(this, options);
2639 for (var i=0; i<$.jqplot.preParseOptionsHooks.length; i++) {
2640 $.jqplot.preParseOptionsHooks[i].call(this, options);
2642 this.options = $.extend(true, {}, this.defaults, options);
2643 var opts = this.options;
2644 this.animate = opts.animate;
2645 this.animateReplot = opts.animateReplot;
2646 this.stackSeries = opts.stackSeries;
2647 if ($.isPlainObject(opts.fillBetween)) {
2649 var temp = ['series1', 'series2', 'color', 'baseSeries', 'fill'],
2652 for (var i=0, l=temp.length; i<l; i++) {
2654 if (opts.fillBetween[tempi] != null) {
2655 this.fillBetween[tempi] = opts.fillBetween[tempi];
2660 if (opts.seriesColors) {
2661 this.seriesColors = opts.seriesColors;
2663 if (opts.negativeSeriesColors) {
2664 this.negativeSeriesColors = opts.negativeSeriesColors;
2666 if (opts.captureRightClick) {
2667 this.captureRightClick = opts.captureRightClick;
2669 this.defaultAxisStart = (options && options.defaultAxisStart != null) ? options.defaultAxisStart : this.defaultAxisStart;
2670 this.colorGenerator.setColors(this.seriesColors);
2671 this.negativeColorGenerator.setColors(this.negativeSeriesColors);
2672 // var cg = new this.colorGenerator(this.seriesColors);
2673 // var ncg = new this.colorGenerator(this.negativeSeriesColors);
2674 // this._gridPadding = this.options.gridPadding;
2675 $.extend(true, this._gridPadding, opts.gridPadding);
2676 this.sortData = (opts.sortData != null) ? opts.sortData : this.sortData;
2677 for (var i=0; i<12; i++) {
2678 var n = _axisNames[i];
2679 var axis = this.axes[n];
2680 axis._options = $.extend(true, {}, opts.axesDefaults, opts.axes[n]);
2681 $.extend(true, axis, opts.axesDefaults, opts.axes[n]);
2682 axis._plotWidth = this._width;
2683 axis._plotHeight = this._height;
2685 // if (this.data.length == 0) {
2687 // for (var i=0; i<this.options.series.length; i++) {
2688 // this.data.push(this.options.series.data);
2692 var normalizeData = function(data, dir, start) {
2693 // return data as an array of point arrays,
2694 // in form [[x1,y1...], [x2,y2...], ...]
2697 dir = dir || 'vertical';
2698 if (!$.isArray(data[0])) {
2699 // we have a series of scalars. One line with just y values.
2700 // turn the scalar list of data into a data array of form:
2701 // [[1, data[0]], [2, data[1]], ...]
2702 for (i=0, l=data.length; i<l; i++) {
2703 if (dir == 'vertical') {
2704 temp.push([start + i, data[i]]);
2707 temp.push([data[i], start+i]);
2712 // we have a properly formatted data series, copy it.
2713 $.extend(true, temp, data);
2720 for (var i=0; i<this.data.length; i++) {
2721 var sopts = $.extend(true, {index: i}, {seriesColors:this.seriesColors, negativeSeriesColors:this.negativeSeriesColors}, this.options.seriesDefaults, this.options.series[i], {rendererOptions:{animation:{show: this.animate}}});
2722 // pass in options in case something needs set prior to initialization.
2723 var temp = new Series(sopts);
2724 for (var j=0; j<$.jqplot.preParseSeriesOptionsHooks.length; j++) {
2725 $.jqplot.preParseSeriesOptionsHooks[j].call(temp, this.options.seriesDefaults, this.options.series[i]);
2727 for (var j=0; j<this.preParseSeriesOptionsHooks.hooks.length; j++) {
2728 this.preParseSeriesOptionsHooks.hooks[j].call(temp, this.options.seriesDefaults, this.options.series[i]);
2730 // Now go back and apply the options to the series. Really should just do this during initializaiton, but don't want to
2731 // mess up preParseSeriesOptionsHooks at this point.
2732 $.extend(true, temp, sopts);
2733 var dir = 'vertical';
2734 if (temp.renderer === $.jqplot.BarRenderer && temp.rendererOptions && temp.rendererOptions.barDirection == 'horizontal') {
2736 temp._stackAxis = 'x';
2737 temp._primaryAxis = '_yaxis';
2739 temp.data = normalizeData(this.data[i], dir, this.defaultAxisStart);
2740 switch (temp.xaxis) {
2742 temp._xaxis = this.axes.xaxis;
2745 temp._xaxis = this.axes.x2axis;
2750 temp._yaxis = this.axes[temp.yaxis];
2751 temp._xaxis._series.push(temp);
2752 temp._yaxis._series.push(temp);
2754 temp._xaxis.show = true;
2755 temp._yaxis.show = true;
2758 if (temp._xaxis.scaleToHiddenSeries) {
2759 temp._xaxis.show = true;
2761 if (temp._yaxis.scaleToHiddenSeries) {
2762 temp._yaxis.show = true;
2766 // // parse the renderer options and apply default colors if not provided
2767 // if (!temp.color && temp.show != false) {
2768 // temp.color = cg.next();
2769 // colorIndex = cg.getIndex() - 1;;
2771 // if (!temp.negativeColor && temp.show != false) {
2772 // temp.negativeColor = ncg.get(colorIndex);
2773 // ncg.setIndex(colorIndex);
2776 temp.label = 'Series '+ (i+1).toString();
2778 // temp.rendererOptions.show = temp.show;
2779 // $.extend(true, temp.renderer, {color:this.seriesColors[i]}, this.rendererOptions);
2780 this.series.push(temp);
2781 for (var j=0; j<$.jqplot.postParseSeriesOptionsHooks.length; j++) {
2782 $.jqplot.postParseSeriesOptionsHooks[j].call(this.series[i], this.options.seriesDefaults, this.options.series[i]);
2784 for (var j=0; j<this.postParseSeriesOptionsHooks.hooks.length; j++) {
2785 this.postParseSeriesOptionsHooks.hooks[j].call(this.series[i], this.options.seriesDefaults, this.options.series[i]);
2789 // copy the grid and title options into this object.
2790 $.extend(true, this.grid, this.options.grid);
2791 // if axis border properties aren't set, set default.
2792 for (var i=0, l=_axisNames.length; i<l; i++) {
2793 var n = _axisNames[i];
2794 var axis = this.axes[n];
2795 if (axis.borderWidth == null) {
2796 axis.borderWidth =this.grid.borderWidth;
2800 if (typeof this.options.title == 'string') {
2801 this.title.text = this.options.title;
2803 else if (typeof this.options.title == 'object') {
2804 $.extend(true, this.title, this.options.title);
2806 this.title._plotWidth = this._width;
2807 this.legend.setOptions(this.options.legend);
2809 for (var i=0; i<$.jqplot.postParseOptionsHooks.length; i++) {
2810 $.jqplot.postParseOptionsHooks[i].call(this, options);
2812 for (var i=0; i<this.postParseOptionsHooks.hooks.length; i++) {
2813 this.postParseOptionsHooks.hooks[i].call(this, options);
2818 // Releases all resources occupied by the plot
2819 this.destroy = function() {
2820 this.canvasManager.freeAllCanvases();
2821 if (this.eventCanvas && this.eventCanvas._elem) {
2822 this.eventCanvas._elem.unbind();
2824 // Couple of posts on Stack Overflow indicate that empty() doesn't
2825 // always cear up the dom and release memory. Sometimes setting
2826 // innerHTML property to null is needed. Particularly on IE, may
2827 // have to directly set it to null, bypassing $.
2828 this.target.empty();
2830 this.target[0].innerHTML = '';
2834 // Does a reinitialization of the plot followed by
2835 // a redraw. Method could be used to interactively
2836 // change plot characteristics and then replot.
2839 // options - Options used for replotting.
2842 // clear - false to not clear (empty) the plot container before replotting (default: true).
2843 // resetAxes - true to reset all axes min, max, numberTicks and tickInterval setting so axes will rescale themselves.
2844 // optionally pass in list of axes to reset (e.g. ['xaxis', 'y2axis']) (default: false).
2845 this.replot = function(options) {
2846 var opts = options || {};
2847 var data = opts.data || null;
2848 var clear = (opts.clear === false) ? false : true;
2849 var resetAxes = opts.resetAxes || false;
2852 delete opts.resetAxes;
2854 this.target.trigger('jqplotPreReplot');
2859 // if have data or other options, full reinit.
2860 // otherwise, quickinit.
2861 if (data || !$.isEmptyObject(opts)) {
2862 this.reInitialize(data, opts);
2869 this.resetAxesScale(resetAxes, opts.axes);
2872 this.target.trigger('jqplotPostReplot');
2876 // Empties the plot target div and redraws the plot.
2877 // This enables plot data and properties to be changed
2878 // and then to comletely clear the plot and redraw.
2879 // redraw *will not* reinitialize any plot elements.
2880 // That is, axes will not be autoscaled and defaults
2881 // will not be reapplied to any plot elements. redraw
2882 // is used primarily with zooming.
2885 // clear - false to not clear (empty) the plot container before redrawing (default: true).
2886 this.redraw = function(clear) {
2887 clear = (clear != null) ? clear : true;
2888 this.target.trigger('jqplotPreRedraw');
2890 this.canvasManager.freeAllCanvases();
2891 this.eventCanvas._elem.unbind();
2892 // Dont think I bind any events to the target, this shouldn't be necessary.
2893 // It will remove user's events.
2894 // this.target.unbind();
2895 this.target.empty();
2897 for (var ax in this.axes) {
2898 this.axes[ax]._ticks = [];
2900 this.computePlotData();
2901 // for (var i=0; i<this.series.length; i++) {
2902 // this.populatePlotData(this.series[i], i);
2906 for (var i=0, tsl = this.series.length; i<tsl; i++) {
2907 this._sumy += this.series[i]._sumy;
2908 this._sumx += this.series[i]._sumx;
2911 this.target.trigger('jqplotPostRedraw');
2915 // Draws all elements of the plot into the container.
2916 // Does not clear the container before drawing.
2917 this.draw = function(){
2918 if (this.drawIfHidden || this.target.is(':visible')) {
2919 this.target.trigger('jqplotPreDraw');
2924 for (i=0, l=$.jqplot.preDrawHooks.length; i<l; i++) {
2925 $.jqplot.preDrawHooks[i].call(this);
2927 for (i=0, l=this.preDrawHooks.length; i<l; i++) {
2928 this.preDrawHooks.hooks[i].apply(this, this.preDrawSeriesHooks.args[i]);
2930 // create an underlying canvas to be used for special features.
2931 this.target.append(this.baseCanvas.createElement({left:0, right:0, top:0, bottom:0}, 'jqplot-base-canvas', null, this));
2932 this.baseCanvas.setContext();
2933 this.target.append(this.title.draw());
2934 this.title.pack({top:0, left:0});
2936 // make room for the legend between the grid and the edge.
2937 // pass a dummy offsets object and a reference to the plot.
2938 var legendElem = this.legend.draw({}, this);
2940 var gridPadding = {top:0, left:0, bottom:0, right:0};
2942 if (this.legend.placement == "outsideGrid") {
2943 // temporarily append the legend to get dimensions
2944 this.target.append(legendElem);
2945 switch (this.legend.location) {
2947 gridPadding.top += this.legend.getHeight();
2950 gridPadding.bottom += this.legend.getHeight();
2955 gridPadding.right += this.legend.getWidth();
2960 gridPadding.left += this.legend.getWidth();
2962 default: // same as 'ne'
2963 gridPadding.right += this.legend.getWidth();
2966 legendElem = legendElem.detach();
2971 // draw the yMidAxis first, so xaxis of pyramid chart can adjust itself if needed.
2972 for (i=0; i<12; i++) {
2973 name = _axisNames[i];
2974 this.target.append(ax[name].draw(this.baseCanvas._ctx, this));
2977 if (ax.yaxis.show) {
2978 gridPadding.left += ax.yaxis.getWidth();
2980 var ra = ['y2axis', 'y3axis', 'y4axis', 'y5axis', 'y6axis', 'y7axis', 'y8axis', 'y9axis'];
2981 var rapad = [0, 0, 0, 0, 0, 0, 0, 0];
2984 for (n=0; n<8; n++) {
2985 if (ax[ra[n]].show) {
2986 gpr += ax[ra[n]].getWidth();
2990 gridPadding.right += gpr;
2991 if (ax.x2axis.show) {
2992 gridPadding.top += ax.x2axis.getHeight();
2994 if (this.title.show) {
2995 gridPadding.top += this.title.getHeight();
2997 if (ax.xaxis.show) {
2998 gridPadding.bottom += ax.xaxis.getHeight();
3001 // end of gridPadding adjustments.
3003 // if user passed in gridDimensions option, check against calculated gridPadding
3004 if (this.options.gridDimensions && $.isPlainObject(this.options.gridDimensions)) {
3005 var gdw = parseInt(this.options.gridDimensions.width, 10) || 0;
3006 var gdh = parseInt(this.options.gridDimensions.height, 10) || 0;
3007 var widthAdj = (this._width - gridPadding.left - gridPadding.right - gdw)/2;
3008 var heightAdj = (this._height - gridPadding.top - gridPadding.bottom - gdh)/2;
3010 if (heightAdj >= 0 && widthAdj >= 0) {
3011 gridPadding.top += heightAdj;
3012 gridPadding.bottom += heightAdj;
3013 gridPadding.left += widthAdj;
3014 gridPadding.right += widthAdj;
3017 var arr = ['top', 'bottom', 'left', 'right'];
3018 for (var n in arr) {
3019 if (this._gridPadding[arr[n]] == null && gridPadding[arr[n]] > 0) {
3020 this._gridPadding[arr[n]] = gridPadding[arr[n]];
3022 else if (this._gridPadding[arr[n]] == null) {
3023 this._gridPadding[arr[n]] = this._defaultGridPadding[arr[n]];
3027 var legendPadding = this._gridPadding;
3029 if (this.legend.placement === 'outsideGrid') {
3030 legendPadding = {top:this.title.getHeight(), left: 0, right: 0, bottom: 0};
3031 if (this.legend.location === 's') {
3032 legendPadding.left = this._gridPadding.left;
3033 legendPadding.right = this._gridPadding.right;
3037 ax.xaxis.pack({position:'absolute', bottom:this._gridPadding.bottom - ax.xaxis.getHeight(), left:0, width:this._width}, {min:this._gridPadding.left, max:this._width - this._gridPadding.right});
3038 ax.yaxis.pack({position:'absolute', top:0, left:this._gridPadding.left - ax.yaxis.getWidth(), height:this._height}, {min:this._height - this._gridPadding.bottom, max: this._gridPadding.top});
3039 ax.x2axis.pack({position:'absolute', top:this._gridPadding.top - ax.x2axis.getHeight(), left:0, width:this._width}, {min:this._gridPadding.left, max:this._width - this._gridPadding.right});
3040 for (i=8; i>0; i--) {
3041 ax[ra[i-1]].pack({position:'absolute', top:0, right:this._gridPadding.right - rapad[i-1]}, {min:this._height - this._gridPadding.bottom, max: this._gridPadding.top});
3043 var ltemp = (this._width - this._gridPadding.left - this._gridPadding.right)/2.0 + this._gridPadding.left - ax.yMidAxis.getWidth()/2.0;
3044 ax.yMidAxis.pack({position:'absolute', top:0, left:ltemp, zIndex:9, textAlign: 'center'}, {min:this._height - this._gridPadding.bottom, max: this._gridPadding.top});
3046 this.target.append(this.grid.createElement(this._gridPadding, this));
3049 var series = this.series;
3050 var seriesLength = series.length;
3051 // put the shadow canvases behind the series canvases so shadows don't overlap on stacked bars.
3052 for (i=0, l=seriesLength; i<l; i++) {
3053 // draw series in order of stacking. This affects only
3054 // order in which canvases are added to dom.
3055 j = this.seriesStack[i];
3056 this.target.append(series[j].shadowCanvas.createElement(this._gridPadding, 'jqplot-series-shadowCanvas', null, this));
3057 series[j].shadowCanvas.setContext();
3058 series[j].shadowCanvas._elem.data('seriesIndex', j);
3061 for (i=0, l=seriesLength; i<l; i++) {
3062 // draw series in order of stacking. This affects only
3063 // order in which canvases are added to dom.
3064 j = this.seriesStack[i];
3065 this.target.append(series[j].canvas.createElement(this._gridPadding, 'jqplot-series-canvas', null, this));
3066 series[j].canvas.setContext();
3067 series[j].canvas._elem.data('seriesIndex', j);
3069 // Need to use filled canvas to capture events in IE.
3070 // Also, canvas seems to block selection of other elements in document on FF.
3071 this.target.append(this.eventCanvas.createElement(this._gridPadding, 'jqplot-event-canvas', null, this));
3072 this.eventCanvas.setContext();
3073 this.eventCanvas._ctx.fillStyle = 'rgba(0,0,0,0)';
3074 this.eventCanvas._ctx.fillRect(0,0,this.eventCanvas._ctx.canvas.width, this.eventCanvas._ctx.canvas.height);
3076 // bind custom event handlers to regular events.
3077 this.bindCustomEvents();
3079 // draw legend before series if the series needs to know the legend dimensions.
3080 if (this.legend.preDraw) {
3081 this.eventCanvas._elem.before(legendElem);
3082 this.legend.pack(legendPadding);
3083 if (this.legend._elem) {
3084 this.drawSeries({legendInfo:{location:this.legend.location, placement:this.legend.placement, width:this.legend.getWidth(), height:this.legend.getHeight(), xoffset:this.legend.xoffset, yoffset:this.legend.yoffset}});
3090 else { // draw series before legend
3093 $(series[seriesLength-1].canvas._elem).after(legendElem);
3095 this.legend.pack(legendPadding);
3098 // register event listeners on the overlay canvas
3099 for (var i=0, l=$.jqplot.eventListenerHooks.length; i<l; i++) {
3100 // in the handler, this will refer to the eventCanvas dom element.
3101 // make sure there are references back into plot objects.
3102 this.eventCanvas._elem.bind($.jqplot.eventListenerHooks[i][0], {plot:this}, $.jqplot.eventListenerHooks[i][1]);
3105 // register event listeners on the overlay canvas
3106 for (var i=0, l=this.eventListenerHooks.hooks.length; i<l; i++) {
3107 // in the handler, this will refer to the eventCanvas dom element.
3108 // make sure there are references back into plot objects.
3109 this.eventCanvas._elem.bind(this.eventListenerHooks.hooks[i][0], {plot:this}, this.eventListenerHooks.hooks[i][1]);
3112 var fb = this.fillBetween;
3113 if (fb.fill && fb.series1 !== fb.series2 && fb.series1 < seriesLength && fb.series2 < seriesLength && series[fb.series1]._type === 'line' && series[fb.series2]._type === 'line') {
3114 this.doFillBetweenLines();
3117 for (var i=0, l=$.jqplot.postDrawHooks.length; i<l; i++) {
3118 $.jqplot.postDrawHooks[i].call(this);
3121 for (var i=0, l=this.postDrawHooks.hooks.length; i<l; i++) {
3122 this.postDrawHooks.hooks[i].apply(this, this.postDrawHooks.args[i]);
3125 if (this.target.is(':visible')) {
3126 this._drawCount += 1;
3133 // ughh. ideally would hide all series then show them.
3134 for (i=0, l=seriesLength; i<l; i++) {
3136 tempr = temps.renderer;
3137 sel = '.jqplot-point-label.jqplot-series-'+i;
3138 if (tempr.animation && tempr.animation._supported && tempr.animation.show && (this._drawCount < 2 || this.animateReplot)) {
3139 _els = this.target.find(sel);
3140 _els.stop(true, true).hide();
3141 temps.canvas._elem.stop(true, true).hide();
3142 temps.shadowCanvas._elem.stop(true, true).hide();
3143 temps.canvas._elem.jqplotEffect('blind', {mode: 'show', direction: tempr.animation.direction}, tempr.animation.speed);
3144 temps.shadowCanvas._elem.jqplotEffect('blind', {mode: 'show', direction: tempr.animation.direction}, tempr.animation.speed);
3145 _els.fadeIn(tempr.animation.speed*0.8);
3150 this.target.trigger('jqplotPostDraw', [this]);
3154 jqPlot.prototype.doFillBetweenLines = function () {
3155 var fb = this.fillBetween;
3156 var sid1 = fb.series1;
3157 var sid2 = fb.series2;
3158 // first series should always be lowest index
3159 var id1 = (sid1 < sid2) ? sid1 : sid2;
3160 var id2 = (sid2 > sid1) ? sid2 : sid1;
3162 var series1 = this.series[id1];
3163 var series2 = this.series[id2];
3165 if (series2.renderer.smooth) {
3166 var tempgd = series2.renderer._smoothedData.slice(0).reverse();
3169 var tempgd = series2.gridData.slice(0).reverse();
3172 if (series1.renderer.smooth) {
3173 var gd = series1.renderer._smoothedData.concat(tempgd);
3176 var gd = series1.gridData.concat(tempgd);
3179 var color = (fb.color !== null) ? fb.color : this.series[sid1].fillColor;
3180 var baseSeries = (fb.baseSeries !== null) ? fb.baseSeries : id1;
3182 // now apply a fill to the shape on the lower series shadow canvas,
3183 // so it is behind both series.
3184 var sr = this.series[baseSeries].renderer.shapeRenderer;
3185 var opts = {fillStyle: color, fill: true, closePath: true};
3186 sr.draw(series1.shadowCanvas._ctx, gd, opts);
3189 this.bindCustomEvents = function() {
3190 this.eventCanvas._elem.bind('click', {plot:this}, this.onClick);
3191 this.eventCanvas._elem.bind('dblclick', {plot:this}, this.onDblClick);
3192 this.eventCanvas._elem.bind('mousedown', {plot:this}, this.onMouseDown);
3193 this.eventCanvas._elem.bind('mousemove', {plot:this}, this.onMouseMove);
3194 this.eventCanvas._elem.bind('mouseenter', {plot:this}, this.onMouseEnter);
3195 this.eventCanvas._elem.bind('mouseleave', {plot:this}, this.onMouseLeave);
3196 if (this.captureRightClick) {
3197 this.eventCanvas._elem.bind('mouseup', {plot:this}, this.onRightClick);
3198 this.eventCanvas._elem.get(0).oncontextmenu = function() {
3203 this.eventCanvas._elem.bind('mouseup', {plot:this}, this.onMouseUp);
3207 function getEventPosition(ev) {
3208 var plot = ev.data.plot;
3209 var go = plot.eventCanvas._elem.offset();
3210 var gridPos = {x:ev.pageX - go.left, y:ev.pageY - go.top};
3211 var dataPos = {xaxis:null, yaxis:null, x2axis:null, y2axis:null, y3axis:null, y4axis:null, y5axis:null, y6axis:null, y7axis:null, y8axis:null, y9axis:null, yMidAxis:null};
3212 var an = ['xaxis', 'yaxis', 'x2axis', 'y2axis', 'y3axis', 'y4axis', 'y5axis', 'y6axis', 'y7axis', 'y8axis', 'y9axis', 'yMidAxis'];
3215 for (n=11; n>0; n--) {
3217 if (ax[axis].show) {
3218 dataPos[axis] = ax[axis].series_p2u(gridPos[axis.charAt(0)]);
3222 return {offsets:go, gridPos:gridPos, dataPos:dataPos};
3226 // function to check if event location is over a area area
3227 function checkIntersection(gridpos, plot) {
3228 var series = plot.series;
3229 var i, j, k, s, r, x, y, theta, sm, sa, minang, maxang;
3230 var d0, d, p, pp, points, bw, hp;
3232 for (k=plot.seriesStack.length-1; k>=0; k--) {
3233 i = plot.seriesStack[k];
3235 hp = s._highlightThreshold;
3236 switch (s.renderer.constructor) {
3237 case $.jqplot.BarRenderer:
3240 for (j=0; j<s._barPoints.length; j++) {
3241 points = s._barPoints[j];
3243 if (x>points[0][0] && x<points[2][0] && y>points[2][1] && y<points[0][1]) {
3244 return {seriesIndex:s.index, pointIndex:j, gridData:p, data:s.data[j], points:s._barPoints[j]};
3248 case $.jqplot.PyramidRenderer:
3251 for (j=0; j<s._barPoints.length; j++) {
3252 points = s._barPoints[j];
3254 if (x > points[0][0] + hp[0][0] && x < points[2][0] + hp[2][0] && y > points[2][1] && y < points[0][1]) {
3255 return {seriesIndex:s.index, pointIndex:j, gridData:p, data:s.data[j], points:s._barPoints[j]};
3260 case $.jqplot.DonutRenderer:
3261 sa = s.startAngle/180*Math.PI;
3262 x = gridpos.x - s._center[0];
3263 y = gridpos.y - s._center[1];
3264 r = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
3265 if (x > 0 && -y >= 0) {
3266 theta = 2*Math.PI - Math.atan(-y/x);
3268 else if (x > 0 && -y < 0) {
3269 theta = -Math.atan(-y/x);
3272 theta = Math.PI - Math.atan(-y/x);
3274 else if (x == 0 && -y > 0) {
3275 theta = 3*Math.PI/2;
3277 else if (x == 0 && -y < 0) {
3280 else if (x == 0 && y == 0) {
3288 else if (theta > 2*Math.PI) {
3293 sm = s.sliceMargin/180*Math.PI;
3294 if (r < s._radius && r > s._innerRadius) {
3295 for (j=0; j<s.gridData.length; j++) {
3296 minang = (j>0) ? s.gridData[j-1][1]+sm : sm;
3297 maxang = s.gridData[j][1];
3298 if (theta > minang && theta < maxang) {
3299 return {seriesIndex:s.index, pointIndex:j, gridData:s.gridData[j], data:s.data[j]};
3305 case $.jqplot.PieRenderer:
3306 sa = s.startAngle/180*Math.PI;
3307 x = gridpos.x - s._center[0];
3308 y = gridpos.y - s._center[1];
3309 r = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
3310 if (x > 0 && -y >= 0) {
3311 theta = 2*Math.PI - Math.atan(-y/x);
3313 else if (x > 0 && -y < 0) {
3314 theta = -Math.atan(-y/x);
3317 theta = Math.PI - Math.atan(-y/x);
3319 else if (x == 0 && -y > 0) {
3320 theta = 3*Math.PI/2;
3322 else if (x == 0 && -y < 0) {
3325 else if (x == 0 && y == 0) {
3333 else if (theta > 2*Math.PI) {
3338 sm = s.sliceMargin/180*Math.PI;
3339 if (r < s._radius) {
3340 for (j=0; j<s.gridData.length; j++) {
3341 minang = (j>0) ? s.gridData[j-1][1]+sm : sm;
3342 maxang = s.gridData[j][1];
3343 if (theta > minang && theta < maxang) {
3344 return {seriesIndex:s.index, pointIndex:j, gridData:s.gridData[j], data:s.data[j]};
3350 case $.jqplot.BubbleRenderer:
3356 for (var j=0; j<s.gridData.length; j++) {
3358 d = Math.sqrt( (x-p[0]) * (x-p[0]) + (y-p[1]) * (y-p[1]) );
3359 if (d <= p[2] && (d <= d0 || d0 == null)) {
3361 ret = {seriesIndex: i, pointIndex:j, gridData:p, data:s.data[j]};
3370 case $.jqplot.FunnelRenderer:
3373 var v = s._vertices,
3375 vlast = v[v.length-1],
3380 // equations of right and left sides, returns x, y values given height of section (y value and 2 points)
3382 function findedge (l, p1 , p2) {
3383 var m = (p1[1] - p2[1])/(p1[0] - p2[0]);
3384 var b = p1[1] - m*p1[0];
3387 return [(y - b)/m, y];
3390 // check each section
3391 lex = findedge(y, vfirst[0], vlast[3]);
3392 rex = findedge(y, vfirst[1], vlast[2]);
3393 for (j=0; j<v.length; j++) {
3395 if (y >= cv[0][1] && y <= cv[3][1] && x >= lex[0] && x <= rex[0]) {
3396 return {seriesIndex:s.index, pointIndex:j, gridData:null, data:s.data[j]};
3401 case $.jqplot.LineRenderer:
3406 if ((s.fill || (s.renderer.bands.show && s.renderer.bands.fill)) && (!plot.plugins.highlighter || !plot.plugins.highlighter.show)) {
3407 // first check if it is in bounding box
3409 if (x>s._boundingBox[0][0] && x<s._boundingBox[1][0] && y>s._boundingBox[1][1] && y<s._boundingBox[0][1]) {
3410 // now check the crossing number
3412 var numPoints = s._areaPoints.length;
3414 var j = numPoints-1;
3416 for(var ii=0; ii < numPoints; ii++) {
3417 var vertex1 = [s._areaPoints[ii][0], s._areaPoints[ii][1]];
3418 var vertex2 = [s._areaPoints[j][0], s._areaPoints[j][1]];
3420 if (vertex1[1] < y && vertex2[1] >= y || vertex2[1] < y && vertex1[1] >= y) {
3421 if (vertex1[0] + (y - vertex1[1]) / (vertex2[1] - vertex1[1]) * (vertex2[0] - vertex1[0]) < x) {
3430 return {seriesIndex:i, pointIndex:null, gridData:s.gridData, data:s.data, points:s._areaPoints};
3437 t = s.markerRenderer.size/2+s.neighborThreshold;
3438 threshold = (t > 0) ? t : 0;
3439 for (var j=0; j<s.gridData.length; j++) {
3441 // neighbor looks different to OHLC chart.
3442 if (r.constructor == $.jqplot.OHLCRenderer) {
3443 if (r.candleStick) {
3444 var yp = s._yaxis.series_u2p;
3445 if (x >= p[0]-r._bodyWidth/2 && x <= p[0]+r._bodyWidth/2 && y >= yp(s.data[j][2]) && y <= yp(s.data[j][3])) {
3446 return {seriesIndex: i, pointIndex:j, gridData:p, data:s.data[j]};
3449 // if an open hi low close chart
3451 var yp = s._yaxis.series_u2p;
3452 if (x >= p[0]-r._tickLength && x <= p[0]+r._tickLength && y >= yp(s.data[j][2]) && y <= yp(s.data[j][3])) {
3453 return {seriesIndex: i, pointIndex:j, gridData:p, data:s.data[j]};
3456 // a hi low close chart
3458 var yp = s._yaxis.series_u2p;
3459 if (x >= p[0]-r._tickLength && x <= p[0]+r._tickLength && y >= yp(s.data[j][1]) && y <= yp(s.data[j][2])) {
3460 return {seriesIndex: i, pointIndex:j, gridData:p, data:s.data[j]};
3465 else if (p[0] != null && p[1] != null){
3466 d = Math.sqrt( (x-p[0]) * (x-p[0]) + (y-p[1]) * (y-p[1]) );
3467 if (d <= threshold && (d <= d0 || d0 == null)) {
3469 return {seriesIndex: i, pointIndex:j, gridData:p, data:s.data[j]};
3482 t = s.markerRenderer.size/2+s.neighborThreshold;
3483 threshold = (t > 0) ? t : 0;
3484 for (var j=0; j<s.gridData.length; j++) {
3486 // neighbor looks different to OHLC chart.
3487 if (r.constructor == $.jqplot.OHLCRenderer) {
3488 if (r.candleStick) {
3489 var yp = s._yaxis.series_u2p;
3490 if (x >= p[0]-r._bodyWidth/2 && x <= p[0]+r._bodyWidth/2 && y >= yp(s.data[j][2]) && y <= yp(s.data[j][3])) {
3491 return {seriesIndex: i, pointIndex:j, gridData:p, data:s.data[j]};
3494 // if an open hi low close chart
3496 var yp = s._yaxis.series_u2p;
3497 if (x >= p[0]-r._tickLength && x <= p[0]+r._tickLength && y >= yp(s.data[j][2]) && y <= yp(s.data[j][3])) {
3498 return {seriesIndex: i, pointIndex:j, gridData:p, data:s.data[j]};
3501 // a hi low close chart
3503 var yp = s._yaxis.series_u2p;
3504 if (x >= p[0]-r._tickLength && x <= p[0]+r._tickLength && y >= yp(s.data[j][1]) && y <= yp(s.data[j][2])) {
3505 return {seriesIndex: i, pointIndex:j, gridData:p, data:s.data[j]};
3511 d = Math.sqrt( (x-p[0]) * (x-p[0]) + (y-p[1]) * (y-p[1]) );
3512 if (d <= threshold && (d <= d0 || d0 == null)) {
3514 return {seriesIndex: i, pointIndex:j, gridData:p, data:s.data[j]};
3528 this.onClick = function(ev) {
3529 // Event passed in is normalized and will have data attribute.
3530 // Event passed out is unnormalized.
3531 var positions = getEventPosition(ev);
3532 var p = ev.data.plot;
3533 var neighbor = checkIntersection(positions.gridPos, p);
3534 var evt = $.Event('jqplotClick');
3535 evt.pageX = ev.pageX;
3536 evt.pageY = ev.pageY;
3537 $(this).trigger(evt, [positions.gridPos, positions.dataPos, neighbor, p]);
3540 this.onDblClick = function(ev) {
3541 // Event passed in is normalized and will have data attribute.
3542 // Event passed out is unnormalized.
3543 var positions = getEventPosition(ev);
3544 var p = ev.data.plot;
3545 var neighbor = checkIntersection(positions.gridPos, p);
3546 var evt = $.Event('jqplotDblClick');
3547 evt.pageX = ev.pageX;
3548 evt.pageY = ev.pageY;
3549 $(this).trigger(evt, [positions.gridPos, positions.dataPos, neighbor, p]);
3552 this.onMouseDown = function(ev) {
3553 var positions = getEventPosition(ev);
3554 var p = ev.data.plot;
3555 var neighbor = checkIntersection(positions.gridPos, p);
3556 var evt = $.Event('jqplotMouseDown');
3557 evt.pageX = ev.pageX;
3558 evt.pageY = ev.pageY;
3559 $(this).trigger(evt, [positions.gridPos, positions.dataPos, neighbor, p]);
3562 this.onMouseUp = function(ev) {
3563 var positions = getEventPosition(ev);
3564 var evt = $.Event('jqplotMouseUp');
3565 evt.pageX = ev.pageX;
3566 evt.pageY = ev.pageY;
3567 $(this).trigger(evt, [positions.gridPos, positions.dataPos, null, ev.data.plot]);
3570 this.onRightClick = function(ev) {
3571 var positions = getEventPosition(ev);
3572 var p = ev.data.plot;
3573 var neighbor = checkIntersection(positions.gridPos, p);
3574 if (p.captureRightClick) {
3575 if (ev.which == 3) {
3576 var evt = $.Event('jqplotRightClick');
3577 evt.pageX = ev.pageX;
3578 evt.pageY = ev.pageY;
3579 $(this).trigger(evt, [positions.gridPos, positions.dataPos, neighbor, p]);
3582 var evt = $.Event('jqplotMouseUp');
3583 evt.pageX = ev.pageX;
3584 evt.pageY = ev.pageY;
3585 $(this).trigger(evt, [positions.gridPos, positions.dataPos, neighbor, p]);
3590 this.onMouseMove = function(ev) {
3591 var positions = getEventPosition(ev);
3592 var p = ev.data.plot;
3593 var neighbor = checkIntersection(positions.gridPos, p);
3594 var evt = $.Event('jqplotMouseMove');
3595 evt.pageX = ev.pageX;
3596 evt.pageY = ev.pageY;
3597 $(this).trigger(evt, [positions.gridPos, positions.dataPos, neighbor, p]);
3600 this.onMouseEnter = function(ev) {
3601 var positions = getEventPosition(ev);
3602 var p = ev.data.plot;
3603 var evt = $.Event('jqplotMouseEnter');
3604 evt.pageX = ev.pageX;
3605 evt.pageY = ev.pageY;
3606 evt.relatedTarget = ev.relatedTarget;
3607 $(this).trigger(evt, [positions.gridPos, positions.dataPos, null, p]);
3610 this.onMouseLeave = function(ev) {
3611 var positions = getEventPosition(ev);
3612 var p = ev.data.plot;
3613 var evt = $.Event('jqplotMouseLeave');
3614 evt.pageX = ev.pageX;
3615 evt.pageY = ev.pageY;
3616 evt.relatedTarget = ev.relatedTarget;
3617 $(this).trigger(evt, [positions.gridPos, positions.dataPos, null, p]);
3620 // method: drawSeries
3621 // Redraws all or just one series on the plot. No axis scaling
3622 // is performed and no other elements on the plot are redrawn.
3623 // options is an options object to pass on to the series renderers.
3624 // It can be an empty object {}. idx is the series index
3625 // to redraw if only one series is to be redrawn.
3626 this.drawSeries = function(options, idx){
3628 // if only one argument passed in and it is a number, use it ad idx.
3629 idx = (typeof(options) === "number" && idx == null) ? options : idx;
3630 options = (typeof(options) === "object") ? options : {};
3631 // draw specified series
3632 if (idx != undefined) {
3633 series = this.series[idx];
3634 ctx = series.shadowCanvas._ctx;
3635 ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
3636 series.drawShadow(ctx, options, this);
3637 ctx = series.canvas._ctx;
3638 ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
3639 series.draw(ctx, options, this);
3640 if (series.renderer.constructor == $.jqplot.BezierCurveRenderer) {
3641 if (idx < this.series.length - 1) {
3642 this.drawSeries(idx+1);
3648 // if call series drawShadow method first, in case all series shadows
3649 // should be drawn before any series. This will ensure, like for
3650 // stacked bar plots, that shadows don't overlap series.
3651 for (i=0; i<this.series.length; i++) {
3652 // first clear the canvas
3653 series = this.series[i];
3654 ctx = series.shadowCanvas._ctx;
3655 ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
3656 series.drawShadow(ctx, options, this);
3657 ctx = series.canvas._ctx;
3658 ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
3659 series.draw(ctx, options, this);
3662 options = idx = i = series = ctx = null;
3665 // method: moveSeriesToFront
3666 // This method requires jQuery 1.4+
3667 // Moves the specified series canvas in front of all other series canvases.
3668 // This effectively "draws" the specified series on top of all other series,
3669 // although it is performed through DOM manipulation, no redrawing is performed.
3672 // idx - 0 based index of the series to move. This will be the index of the series
3673 // as it was first passed into the jqplot function.
3674 this.moveSeriesToFront = function (idx) {
3675 idx = parseInt(idx, 10);
3676 var stackIndex = $.inArray(idx, this.seriesStack);
3677 // if already in front, return
3678 if (stackIndex == -1) {
3681 if (stackIndex == this.seriesStack.length -1) {
3682 this.previousSeriesStack = this.seriesStack.slice(0);
3685 var opidx = this.seriesStack[this.seriesStack.length -1];
3686 var serelem = this.series[idx].canvas._elem.detach();
3687 var shadelem = this.series[idx].shadowCanvas._elem.detach();
3688 this.series[opidx].shadowCanvas._elem.after(shadelem);
3689 this.series[opidx].canvas._elem.after(serelem);
3690 this.previousSeriesStack = this.seriesStack.slice(0);
3691 this.seriesStack.splice(stackIndex, 1);
3692 this.seriesStack.push(idx);
3695 // method: moveSeriesToBack
3696 // This method requires jQuery 1.4+
3697 // Moves the specified series canvas behind all other series canvases.
3700 // idx - 0 based index of the series to move. This will be the index of the series
3701 // as it was first passed into the jqplot function.
3702 this.moveSeriesToBack = function (idx) {
3703 idx = parseInt(idx, 10);
3704 var stackIndex = $.inArray(idx, this.seriesStack);
3705 // if already in back, return
3706 if (stackIndex == 0 || stackIndex == -1) {
3709 var opidx = this.seriesStack[0];
3710 var serelem = this.series[idx].canvas._elem.detach();
3711 var shadelem = this.series[idx].shadowCanvas._elem.detach();
3712 this.series[opidx].shadowCanvas._elem.before(shadelem);
3713 this.series[opidx].canvas._elem.before(serelem);
3714 this.previousSeriesStack = this.seriesStack.slice(0);
3715 this.seriesStack.splice(stackIndex, 1);
3716 this.seriesStack.unshift(idx);
3719 // method: restorePreviousSeriesOrder
3720 // This method requires jQuery 1.4+
3721 // Restore the series canvas order to its previous state.
3722 // Useful to put a series back where it belongs after moving
3724 this.restorePreviousSeriesOrder = function () {
3725 var i, j, serelem, shadelem, temp, move, keep;
3726 // if no change, return.
3727 if (this.seriesStack == this.previousSeriesStack) {
3730 for (i=1; i<this.previousSeriesStack.length; i++) {
3731 move = this.previousSeriesStack[i];
3732 keep = this.previousSeriesStack[i-1];
3733 serelem = this.series[move].canvas._elem.detach();
3734 shadelem = this.series[move].shadowCanvas._elem.detach();
3735 this.series[keep].shadowCanvas._elem.after(shadelem);
3736 this.series[keep].canvas._elem.after(serelem);
3738 temp = this.seriesStack.slice(0);
3739 this.seriesStack = this.previousSeriesStack.slice(0);
3740 this.previousSeriesStack = temp;
3743 // method: restoreOriginalSeriesOrder
3744 // This method requires jQuery 1.4+
3745 // Restore the series canvas order to its original order
3746 // when the plot was created.
3747 this.restoreOriginalSeriesOrder = function () {
3748 var i, j, arr=[], serelem, shadelem;
3749 for (i=0; i<this.series.length; i++) {
3752 if (this.seriesStack == arr) {
3755 this.previousSeriesStack = this.seriesStack.slice(0);
3756 this.seriesStack = arr;
3757 for (i=1; i<this.seriesStack.length; i++) {
3758 serelem = this.series[i].canvas._elem.detach();
3759 shadelem = this.series[i].shadowCanvas._elem.detach();
3760 this.series[i-1].shadowCanvas._elem.after(shadelem);
3761 this.series[i-1].canvas._elem.after(serelem);
3765 this.activateTheme = function (name) {
3766 this.themeEngine.activate(this, name);
3771 // conpute a highlight color or array of highlight colors from given colors.
3772 $.jqplot.computeHighlightColors = function(colors) {
3774 if ($.isArray(colors)) {
3776 for (var i=0; i<colors.length; i++){
3777 var rgba = $.jqplot.getColorComponents(colors[i]);
3778 var newrgb = [rgba[0], rgba[1], rgba[2]];
3779 var sum = newrgb[0] + newrgb[1] + newrgb[2];
3780 for (var j=0; j<3; j++) {
3781 // when darkening, lowest color component can be is 60.
3782 newrgb[j] = (sum > 660) ? newrgb[j] * 0.85 : 0.73 * newrgb[j] + 90;
3783 newrgb[j] = parseInt(newrgb[j], 10);
3784 (newrgb[j] > 255) ? 255 : newrgb[j];
3786 // newrgb[3] = (rgba[3] > 0.4) ? rgba[3] * 0.4 : rgba[3] * 1.5;
3787 // newrgb[3] = (rgba[3] > 0.5) ? 0.8 * rgba[3] - .1 : rgba[3] + 0.2;
3788 newrgb[3] = 0.3 + 0.35 * rgba[3];
3789 ret.push('rgba('+newrgb[0]+','+newrgb[1]+','+newrgb[2]+','+newrgb[3]+')');
3793 var rgba = $.jqplot.getColorComponents(colors);
3794 var newrgb = [rgba[0], rgba[1], rgba[2]];
3795 var sum = newrgb[0] + newrgb[1] + newrgb[2];
3796 for (var j=0; j<3; j++) {
3797 // when darkening, lowest color component can be is 60.
3798 // newrgb[j] = (sum > 570) ? newrgb[j] * 0.8 : newrgb[j] + 0.3 * (255 - newrgb[j]);
3799 // newrgb[j] = parseInt(newrgb[j], 10);
3800 newrgb[j] = (sum > 660) ? newrgb[j] * 0.85 : 0.73 * newrgb[j] + 90;
3801 newrgb[j] = parseInt(newrgb[j], 10);
3802 (newrgb[j] > 255) ? 255 : newrgb[j];
3804 // newrgb[3] = (rgba[3] > 0.4) ? rgba[3] * 0.4 : rgba[3] * 1.5;
3805 // newrgb[3] = (rgba[3] > 0.5) ? 0.8 * rgba[3] - .1 : rgba[3] + 0.2;
3806 newrgb[3] = 0.3 + 0.35 * rgba[3];
3807 ret = 'rgba('+newrgb[0]+','+newrgb[1]+','+newrgb[2]+','+newrgb[3]+')';
3812 $.jqplot.ColorGenerator = function(colors) {
3813 colors = colors || $.jqplot.config.defaultColors;
3816 this.next = function () {
3817 if (idx < colors.length) {
3818 return colors[idx++];
3822 return colors[idx++];
3826 this.previous = function () {
3828 return colors[idx--];
3831 idx = colors.length-1;
3836 // get a color by index without advancing pointer.
3837 this.get = function(i) {
3838 var idx = i - colors.length * Math.floor(i/colors.length);
3842 this.setColors = function(c) {
3846 this.reset = function() {
3850 this.getIndex = function() {
3854 this.setIndex = function(index) {
3859 // convert a hex color string to rgb string.
3860 // h - 3 or 6 character hex string, with or without leading #
3861 // a - optional alpha
3862 $.jqplot.hex2rgb = function(h, a) {
3863 h = h.replace('#', '');
3864 if (h.length == 3) {
3865 h = h.charAt(0)+h.charAt(0)+h.charAt(1)+h.charAt(1)+h.charAt(2)+h.charAt(2);
3868 rgb = 'rgba('+parseInt(h.slice(0,2), 16)+', '+parseInt(h.slice(2,4), 16)+', '+parseInt(h.slice(4,6), 16);
3876 // convert an rgb color spec to a hex spec. ignore any alpha specification.
3877 $.jqplot.rgb2hex = function(s) {
3878 var pat = /rgba?\( *([0-9]{1,3}\.?[0-9]*%?) *, *([0-9]{1,3}\.?[0-9]*%?) *, *([0-9]{1,3}\.?[0-9]*%?) *(?:, *[0-9.]*)?\)/;
3879 var m = s.match(pat);
3881 for (var i=1; i<4; i++) {
3883 if (m[i].search(/%/) != -1) {
3884 temp = parseInt(255*m[i]/100, 10).toString(16);
3885 if (temp.length == 1) {
3890 temp = parseInt(m[i], 10).toString(16);
3891 if (temp.length == 1) {
3900 // given a css color spec, return an rgb css color spec
3901 $.jqplot.normalize2rgb = function(s, a) {
3902 if (s.search(/^ *rgba?\(/) != -1) {
3905 else if (s.search(/^ *#?[0-9a-fA-F]?[0-9a-fA-F]/) != -1) {
3906 return $.jqplot.hex2rgb(s, a);
3909 throw 'invalid color spec';
3913 // extract the r, g, b, a color components out of a css color spec.
3914 $.jqplot.getColorComponents = function(s) {
3915 // check to see if a color keyword.
3916 s = $.jqplot.colorKeywordMap[s] || s;
3917 var rgb = $.jqplot.normalize2rgb(s);
3918 var pat = /rgba?\( *([0-9]{1,3}\.?[0-9]*%?) *, *([0-9]{1,3}\.?[0-9]*%?) *, *([0-9]{1,3}\.?[0-9]*%?) *,? *([0-9.]* *)?\)/;
3919 var m = rgb.match(pat);
3921 for (var i=1; i<4; i++) {
3922 if (m[i].search(/%/) != -1) {
3923 ret[i-1] = parseInt(255*m[i]/100, 10);
3926 ret[i-1] = parseInt(m[i], 10);
3929 ret[3] = parseFloat(m[4]) ? parseFloat(m[4]) : 1.0;
3933 $.jqplot.colorKeywordMap = {
3934 aliceblue: 'rgb(240, 248, 255)',
3935 antiquewhite: 'rgb(250, 235, 215)',
3936 aqua: 'rgb( 0, 255, 255)',
3937 aquamarine: 'rgb(127, 255, 212)',
3938 azure: 'rgb(240, 255, 255)',
3939 beige: 'rgb(245, 245, 220)',
3940 bisque: 'rgb(255, 228, 196)',
3941 black: 'rgb( 0, 0, 0)',
3942 blanchedalmond: 'rgb(255, 235, 205)',
3943 blue: 'rgb( 0, 0, 255)',
3944 blueviolet: 'rgb(138, 43, 226)',
3945 brown: 'rgb(165, 42, 42)',
3946 burlywood: 'rgb(222, 184, 135)',
3947 cadetblue: 'rgb( 95, 158, 160)',
3948 chartreuse: 'rgb(127, 255, 0)',
3949 chocolate: 'rgb(210, 105, 30)',
3950 coral: 'rgb(255, 127, 80)',
3951 cornflowerblue: 'rgb(100, 149, 237)',
3952 cornsilk: 'rgb(255, 248, 220)',
3953 crimson: 'rgb(220, 20, 60)',
3954 cyan: 'rgb( 0, 255, 255)',
3955 darkblue: 'rgb( 0, 0, 139)',
3956 darkcyan: 'rgb( 0, 139, 139)',
3957 darkgoldenrod: 'rgb(184, 134, 11)',
3958 darkgray: 'rgb(169, 169, 169)',
3959 darkgreen: 'rgb( 0, 100, 0)',
3960 darkgrey: 'rgb(169, 169, 169)',
3961 darkkhaki: 'rgb(189, 183, 107)',
3962 darkmagenta: 'rgb(139, 0, 139)',
3963 darkolivegreen: 'rgb( 85, 107, 47)',
3964 darkorange: 'rgb(255, 140, 0)',
3965 darkorchid: 'rgb(153, 50, 204)',
3966 darkred: 'rgb(139, 0, 0)',
3967 darksalmon: 'rgb(233, 150, 122)',
3968 darkseagreen: 'rgb(143, 188, 143)',
3969 darkslateblue: 'rgb( 72, 61, 139)',
3970 darkslategray: 'rgb( 47, 79, 79)',
3971 darkslategrey: 'rgb( 47, 79, 79)',
3972 darkturquoise: 'rgb( 0, 206, 209)',
3973 darkviolet: 'rgb(148, 0, 211)',
3974 deeppink: 'rgb(255, 20, 147)',
3975 deepskyblue: 'rgb( 0, 191, 255)',
3976 dimgray: 'rgb(105, 105, 105)',
3977 dimgrey: 'rgb(105, 105, 105)',
3978 dodgerblue: 'rgb( 30, 144, 255)',
3979 firebrick: 'rgb(178, 34, 34)',
3980 floralwhite: 'rgb(255, 250, 240)',
3981 forestgreen: 'rgb( 34, 139, 34)',
3982 fuchsia: 'rgb(255, 0, 255)',
3983 gainsboro: 'rgb(220, 220, 220)',
3984 ghostwhite: 'rgb(248, 248, 255)',
3985 gold: 'rgb(255, 215, 0)',
3986 goldenrod: 'rgb(218, 165, 32)',
3987 gray: 'rgb(128, 128, 128)',
3988 grey: 'rgb(128, 128, 128)',
3989 green: 'rgb( 0, 128, 0)',
3990 greenyellow: 'rgb(173, 255, 47)',
3991 honeydew: 'rgb(240, 255, 240)',
3992 hotpink: 'rgb(255, 105, 180)',
3993 indianred: 'rgb(205, 92, 92)',
3994 indigo: 'rgb( 75, 0, 130)',
3995 ivory: 'rgb(255, 255, 240)',
3996 khaki: 'rgb(240, 230, 140)',
3997 lavender: 'rgb(230, 230, 250)',
3998 lavenderblush: 'rgb(255, 240, 245)',
3999 lawngreen: 'rgb(124, 252, 0)',
4000 lemonchiffon: 'rgb(255, 250, 205)',
4001 lightblue: 'rgb(173, 216, 230)',
4002 lightcoral: 'rgb(240, 128, 128)',
4003 lightcyan: 'rgb(224, 255, 255)',
4004 lightgoldenrodyellow: 'rgb(250, 250, 210)',
4005 lightgray: 'rgb(211, 211, 211)',
4006 lightgreen: 'rgb(144, 238, 144)',
4007 lightgrey: 'rgb(211, 211, 211)',
4008 lightpink: 'rgb(255, 182, 193)',
4009 lightsalmon: 'rgb(255, 160, 122)',
4010 lightseagreen: 'rgb( 32, 178, 170)',
4011 lightskyblue: 'rgb(135, 206, 250)',
4012 lightslategray: 'rgb(119, 136, 153)',
4013 lightslategrey: 'rgb(119, 136, 153)',
4014 lightsteelblue: 'rgb(176, 196, 222)',
4015 lightyellow: 'rgb(255, 255, 224)',
4016 lime: 'rgb( 0, 255, 0)',
4017 limegreen: 'rgb( 50, 205, 50)',
4018 linen: 'rgb(250, 240, 230)',
4019 magenta: 'rgb(255, 0, 255)',
4020 maroon: 'rgb(128, 0, 0)',
4021 mediumaquamarine: 'rgb(102, 205, 170)',
4022 mediumblue: 'rgb( 0, 0, 205)',
4023 mediumorchid: 'rgb(186, 85, 211)',
4024 mediumpurple: 'rgb(147, 112, 219)',
4025 mediumseagreen: 'rgb( 60, 179, 113)',
4026 mediumslateblue: 'rgb(123, 104, 238)',
4027 mediumspringgreen: 'rgb( 0, 250, 154)',
4028 mediumturquoise: 'rgb( 72, 209, 204)',
4029 mediumvioletred: 'rgb(199, 21, 133)',
4030 midnightblue: 'rgb( 25, 25, 112)',
4031 mintcream: 'rgb(245, 255, 250)',
4032 mistyrose: 'rgb(255, 228, 225)',
4033 moccasin: 'rgb(255, 228, 181)',
4034 navajowhite: 'rgb(255, 222, 173)',
4035 navy: 'rgb( 0, 0, 128)',
4036 oldlace: 'rgb(253, 245, 230)',
4037 olive: 'rgb(128, 128, 0)',
4038 olivedrab: 'rgb(107, 142, 35)',
4039 orange: 'rgb(255, 165, 0)',
4040 orangered: 'rgb(255, 69, 0)',
4041 orchid: 'rgb(218, 112, 214)',
4042 palegoldenrod: 'rgb(238, 232, 170)',
4043 palegreen: 'rgb(152, 251, 152)',
4044 paleturquoise: 'rgb(175, 238, 238)',
4045 palevioletred: 'rgb(219, 112, 147)',
4046 papayawhip: 'rgb(255, 239, 213)',
4047 peachpuff: 'rgb(255, 218, 185)',
4048 peru: 'rgb(205, 133, 63)',
4049 pink: 'rgb(255, 192, 203)',
4050 plum: 'rgb(221, 160, 221)',
4051 powderblue: 'rgb(176, 224, 230)',
4052 purple: 'rgb(128, 0, 128)',
4053 red: 'rgb(255, 0, 0)',
4054 rosybrown: 'rgb(188, 143, 143)',
4055 royalblue: 'rgb( 65, 105, 225)',
4056 saddlebrown: 'rgb(139, 69, 19)',
4057 salmon: 'rgb(250, 128, 114)',
4058 sandybrown: 'rgb(244, 164, 96)',
4059 seagreen: 'rgb( 46, 139, 87)',
4060 seashell: 'rgb(255, 245, 238)',
4061 sienna: 'rgb(160, 82, 45)',
4062 silver: 'rgb(192, 192, 192)',
4063 skyblue: 'rgb(135, 206, 235)',
4064 slateblue: 'rgb(106, 90, 205)',
4065 slategray: 'rgb(112, 128, 144)',
4066 slategrey: 'rgb(112, 128, 144)',
4067 snow: 'rgb(255, 250, 250)',
4068 springgreen: 'rgb( 0, 255, 127)',
4069 steelblue: 'rgb( 70, 130, 180)',
4070 tan: 'rgb(210, 180, 140)',
4071 teal: 'rgb( 0, 128, 128)',
4072 thistle: 'rgb(216, 191, 216)',
4073 tomato: 'rgb(255, 99, 71)',
4074 turquoise: 'rgb( 64, 224, 208)',
4075 violet: 'rgb(238, 130, 238)',
4076 wheat: 'rgb(245, 222, 179)',
4077 white: 'rgb(255, 255, 255)',
4078 whitesmoke: 'rgb(245, 245, 245)',
4079 yellow: 'rgb(255, 255, 0)',
4080 yellowgreen: 'rgb(154, 205, 50)'
4085 // class: $.jqplot.AxisLabelRenderer
4086 // Renderer to place labels on the axes.
4087 $.jqplot.AxisLabelRenderer = function(options) {
4088 // Group: Properties
4089 $.jqplot.ElemContainer.call(this);
4090 // name of the axis associated with this tick
4093 // wether or not to show the tick (mark and label).
4096 // The text or html for the label.
4098 this.fontFamily = null;
4099 this.fontSize = null;
4100 this.textColor = null;
4103 // true to escape HTML entities in the label.
4104 this.escapeHTML = false;
4106 $.extend(true, this, options);
4109 $.jqplot.AxisLabelRenderer.prototype = new $.jqplot.ElemContainer();
4110 $.jqplot.AxisLabelRenderer.prototype.constructor = $.jqplot.AxisLabelRenderer;
4112 $.jqplot.AxisLabelRenderer.prototype.init = function(options) {
4113 $.extend(true, this, options);
4116 $.jqplot.AxisLabelRenderer.prototype.draw = function(ctx, plot) {
4117 // Memory Leaks patch
4119 this._elem.emptyForce();
4123 this._elem = $('<div style="position:absolute;" class="jqplot-'+this.axis+'-label"></div>');
4125 if (Number(this.label)) {
4126 this._elem.css('white-space', 'nowrap');
4129 if (!this.escapeHTML) {
4130 this._elem.html(this.label);
4133 this._elem.text(this.label);
4135 if (this.fontFamily) {
4136 this._elem.css('font-family', this.fontFamily);
4138 if (this.fontSize) {
4139 this._elem.css('font-size', this.fontSize);
4141 if (this.textColor) {
4142 this._elem.css('color', this.textColor);
4148 $.jqplot.AxisLabelRenderer.prototype.pack = function() {
4151 // class: $.jqplot.AxisTickRenderer
4152 // A "tick" object showing the value of a tick/gridline on the plot.
4153 $.jqplot.AxisTickRenderer = function(options) {
4154 // Group: Properties
4155 $.jqplot.ElemContainer.call(this);
4157 // tick mark on the axis. One of 'inside', 'outside', 'cross', '' or null.
4158 this.mark = 'outside';
4159 // name of the axis associated with this tick
4162 // wether or not to show the mark on the axis.
4163 this.showMark = true;
4164 // prop: showGridline
4165 // wether or not to draw the gridline on the grid at this tick.
4166 this.showGridline = true;
4167 // prop: isMinorTick
4168 // if this is a minor tick.
4169 this.isMinorTick = false;
4171 // Length of the tick beyond the grid in pixels.
4172 // DEPRECATED: This has been superceeded by markSize
4175 // Length of the tick marks in pixels. For 'cross' style, length
4176 // will be stoked above and below axis, so total length will be twice this.
4179 // wether or not to show the tick (mark and label).
4180 // Setting this to false requires more testing. It is recommended
4181 // to set showLabel and showMark to false instead.
4184 // wether or not to show the label.
4185 this.showLabel = true;
4190 // A class of a formatter for the tick text. sprintf by default.
4191 this.formatter = $.jqplot.DefaultTickFormatter;
4193 // String to prepend to the tick label.
4194 // Prefix is prepended to the formatted tick label.
4197 // String to append to the tick label.
4198 // Suffix is appended to the formatted tick label.
4200 // prop: formatString
4201 // string passed to the formatter.
4202 this.formatString = '';
4204 // css spec for the font-family css attribute.
4207 // css spec for the font-size css attribute.
4210 // css spec for the color attribute.
4213 // true to escape HTML entities in the label.
4214 this.escapeHTML = false;
4216 this._breakTick = false;
4218 $.extend(true, this, options);
4221 $.jqplot.AxisTickRenderer.prototype.init = function(options) {
4222 $.extend(true, this, options);
4225 $.jqplot.AxisTickRenderer.prototype = new $.jqplot.ElemContainer();
4226 $.jqplot.AxisTickRenderer.prototype.constructor = $.jqplot.AxisTickRenderer;
4228 $.jqplot.AxisTickRenderer.prototype.setTick = function(value, axisName, isMinor) {
4230 this.axis = axisName;
4232 this.isMinorTick = true;
4237 $.jqplot.AxisTickRenderer.prototype.draw = function() {
4238 if (this.label === null) {
4239 this.label = this.prefix + this.formatter(this.formatString, this.value) + this.suffix;
4241 var style = {position: 'absolute'};
4242 if (Number(this.label)) {
4243 style['whitSpace'] = 'nowrap';
4246 // Memory Leaks patch
4248 this._elem.emptyForce();
4252 this._elem = $(document.createElement('div'));
4253 this._elem.addClass("jqplot-"+this.axis+"-tick");
4255 if (!this.escapeHTML) {
4256 this._elem.html(this.label);
4259 this._elem.text(this.label);
4262 this._elem.css(style);
4264 for (var s in this._styles) {
4265 this._elem.css(s, this._styles[s]);
4267 if (this.fontFamily) {
4268 this._elem.css('font-family', this.fontFamily);
4270 if (this.fontSize) {
4271 this._elem.css('font-size', this.fontSize);
4273 if (this.textColor) {
4274 this._elem.css('color', this.textColor);
4276 if (this._breakTick) {
4277 this._elem.addClass('jqplot-breakTick');
4283 $.jqplot.DefaultTickFormatter = function (format, val) {
4284 if (typeof val == 'number') {
4286 format = $.jqplot.config.defaultTickFormatString;
4288 return $.jqplot.sprintf(format, val);
4295 $.jqplot.PercentTickFormatter = function (format, val) {
4296 if (typeof val == 'number') {
4299 format = $.jqplot.config.defaultTickFormatString;
4301 return $.jqplot.sprintf(format, val);
4308 $.jqplot.AxisTickRenderer.prototype.pack = function() {
4311 // Class: $.jqplot.CanvasGridRenderer
4312 // The default jqPlot grid renderer, creating a grid on a canvas element.
4313 // The renderer has no additional options beyond the <Grid> class.
4314 $.jqplot.CanvasGridRenderer = function(){
4315 this.shadowRenderer = new $.jqplot.ShadowRenderer();
4318 // called with context of Grid object
4319 $.jqplot.CanvasGridRenderer.prototype.init = function(options) {
4321 $.extend(true, this, options);
4322 // set the shadow renderer options
4323 var sopts = {lineJoin:'miter', lineCap:'round', fill:false, isarc:false, angle:this.shadowAngle, offset:this.shadowOffset, alpha:this.shadowAlpha, depth:this.shadowDepth, lineWidth:this.shadowWidth, closePath:false, strokeStyle:this.shadowColor};
4324 this.renderer.shadowRenderer.init(sopts);
4327 // called with context of Grid.
4328 $.jqplot.CanvasGridRenderer.prototype.createElement = function(plot) {
4330 // Memory Leaks patch
4332 if ($.jqplot.use_excanvas && window.G_vmlCanvasManager.uninitElement !== undefined) {
4333 elem = this._elem.get(0);
4334 window.G_vmlCanvasManager.uninitElement(elem);
4338 this._elem.emptyForce();
4342 elem = plot.canvasManager.getCanvas();
4344 var w = this._plotDimensions.width;
4345 var h = this._plotDimensions.height;
4348 this._elem = $(elem);
4349 this._elem.addClass('jqplot-grid-canvas');
4350 this._elem.css({ position: 'absolute', left: 0, top: 0 });
4352 elem = plot.canvasManager.initCanvas(elem);
4354 this._top = this._offsets.top;
4355 this._bottom = h - this._offsets.bottom;
4356 this._left = this._offsets.left;
4357 this._right = w - this._offsets.right;
4358 this._width = this._right - this._left;
4359 this._height = this._bottom - this._top;
4360 // avoid memory leak
4365 $.jqplot.CanvasGridRenderer.prototype.draw = function() {
4366 this._ctx = this._elem.get(0).getContext("2d");
4367 var ctx = this._ctx;
4368 var axes = this._axes;
4369 // Add the grid onto the grid canvas. This is the bottom most layer.
4371 ctx.clearRect(0, 0, this._plotDimensions.width, this._plotDimensions.height);
4372 ctx.fillStyle = this.backgroundColor || this.background;
4373 ctx.fillRect(this._left, this._top, this._width, this._height);
4376 ctx.lineJoin = 'miter';
4377 ctx.lineCap = 'butt';
4378 ctx.lineWidth = this.gridLineWidth;
4379 ctx.strokeStyle = this.gridLineColor;
4381 var ax = ['xaxis', 'yaxis', 'x2axis', 'y2axis'];
4382 for (var i=4; i>0; i--) {
4384 var axis = axes[name];
4385 var ticks = axis._ticks;
4386 var numticks = ticks.length;
4388 if (axis.drawBaseline) {
4390 if (axis.baselineWidth !== null) {
4391 bopts.lineWidth = axis.baselineWidth;
4393 if (axis.baselineColor !== null) {
4394 bopts.strokeStyle = axis.baselineColor;
4398 drawLine (this._left, this._bottom, this._right, this._bottom, bopts);
4401 drawLine (this._left, this._bottom, this._left, this._top, bopts);
4404 drawLine (this._left, this._bottom, this._right, this._bottom, bopts);
4407 drawLine (this._right, this._bottom, this._right, this._top, bopts);
4411 for (var j=numticks; j>0; j--) {
4414 var pos = Math.round(axis.u2p(t.value)) + 0.5;
4417 // draw the grid line if we should
4418 if (t.showGridline && this.drawGridlines && ((!t.isMinorTick && axis.drawMajorGridlines) || (t.isMinorTick && axis.drawMinorGridlines)) ) {
4419 drawLine(pos, this._top, pos, this._bottom);
4422 if (t.showMark && t.mark && ((!t.isMinorTick && axis.drawMajorTickMarks) || (t.isMinorTick && axis.drawMinorTickMarks)) ) {
4425 var pos = Math.round(axis.u2p(t.value)) + 0.5;
4446 this.renderer.shadowRenderer.draw(ctx, [[pos,b],[pos,e]], {lineCap:'butt', lineWidth:this.gridLineWidth, offset:this.gridLineWidth*0.75, depth:2, fill:false, closePath:false});
4449 drawLine(pos, b, pos, e);
4453 // draw the grid line
4454 if (t.showGridline && this.drawGridlines && ((!t.isMinorTick && axis.drawMajorGridlines) || (t.isMinorTick && axis.drawMinorGridlines)) ) {
4455 drawLine(this._right, pos, this._left, pos);
4458 if (t.showMark && t.mark && ((!t.isMinorTick && axis.drawMajorTickMarks) || (t.isMinorTick && axis.drawMinorTickMarks)) ) {
4461 var pos = Math.round(axis.u2p(t.value)) + 0.5;
4482 this.renderer.shadowRenderer.draw(ctx, [[b, pos], [e, pos]], {lineCap:'butt', lineWidth:this.gridLineWidth*1.5, offset:this.gridLineWidth*0.75, fill:false, closePath:false});
4484 drawLine(b, pos, e, pos, {strokeStyle:axis.borderColor});
4488 // draw the grid line
4489 if (t.showGridline && this.drawGridlines && ((!t.isMinorTick && axis.drawMajorGridlines) || (t.isMinorTick && axis.drawMinorGridlines)) ) {
4490 drawLine(pos, this._bottom, pos, this._top);
4493 if (t.showMark && t.mark && ((!t.isMinorTick && axis.drawMajorTickMarks) || (t.isMinorTick && axis.drawMinorTickMarks)) ) {
4496 var pos = Math.round(axis.u2p(t.value)) + 0.5;
4517 this.renderer.shadowRenderer.draw(ctx, [[pos,b],[pos,e]], {lineCap:'butt', lineWidth:this.gridLineWidth, offset:this.gridLineWidth*0.75, depth:2, fill:false, closePath:false});
4519 drawLine(pos, b, pos, e);
4523 // draw the grid line
4524 if (t.showGridline && this.drawGridlines && ((!t.isMinorTick && axis.drawMajorGridlines) || (t.isMinorTick && axis.drawMinorGridlines)) ) {
4525 drawLine(this._left, pos, this._right, pos);
4528 if (t.showMark && t.mark && ((!t.isMinorTick && axis.drawMajorTickMarks) || (t.isMinorTick && axis.drawMinorTickMarks)) ) {
4531 var pos = Math.round(axis.u2p(t.value)) + 0.5;
4552 this.renderer.shadowRenderer.draw(ctx, [[b, pos], [e, pos]], {lineCap:'butt', lineWidth:this.gridLineWidth*1.5, offset:this.gridLineWidth*0.75, fill:false, closePath:false});
4554 drawLine(b, pos, e, pos, {strokeStyle:axis.borderColor});
4567 // Now draw grid lines for additional y axes
4569 // TO DO: handle yMidAxis
4571 ax = ['y3axis', 'y4axis', 'y5axis', 'y6axis', 'y7axis', 'y8axis', 'y9axis', 'yMidAxis'];
4572 for (var i=7; i>0; i--) {
4573 var axis = axes[ax[i-1]];
4574 var ticks = axis._ticks;
4576 var tn = ticks[axis.numberTicks-1];
4578 var left = axis.getLeft();
4579 var points = [[left, tn.getTop() + tn.getHeight()/2], [left, t0.getTop() + t0.getHeight()/2 + 1.0]];
4582 this.renderer.shadowRenderer.draw(ctx, points, {lineCap:'butt', fill:false, closePath:false});
4585 drawLine(points[0][0], points[0][1], points[1][0], points[1][1], {lineCap:'butt', strokeStyle:axis.borderColor, lineWidth:axis.borderWidth});
4586 // draw the tick marks
4587 for (var j=ticks.length; j>0; j--) {
4591 var pos = Math.round(axis.u2p(t.value)) + 0.5;
4592 if (t.showMark && t.mark) {
4611 points = [[b,pos], [e,pos]];
4614 this.renderer.shadowRenderer.draw(ctx, points, {lineCap:'butt', lineWidth:this.gridLineWidth*1.5, offset:this.gridLineWidth*0.75, fill:false, closePath:false});
4617 drawLine(b, pos, e, pos, {strokeStyle:axis.borderColor});
4629 function drawLine(bx, by, ex, ey, opts) {
4632 if (opts.lineWidth == null || opts.lineWidth != 0){
4633 $.extend(true, ctx, opts);
4643 var points = [[this._left, this._bottom], [this._right, this._bottom], [this._right, this._top]];
4644 this.renderer.shadowRenderer.draw(ctx, points);
4646 // Now draw border around grid. Use axis border definitions. start at
4647 // upper left and go clockwise.
4648 if (this.borderWidth != 0 && this.drawBorder) {
4649 drawLine (this._left, this._top, this._right, this._top, {lineCap:'round', strokeStyle:axes.x2axis.borderColor, lineWidth:axes.x2axis.borderWidth});
4650 drawLine (this._right, this._top, this._right, this._bottom, {lineCap:'round', strokeStyle:axes.y2axis.borderColor, lineWidth:axes.y2axis.borderWidth});
4651 drawLine (this._right, this._bottom, this._left, this._bottom, {lineCap:'round', strokeStyle:axes.xaxis.borderColor, lineWidth:axes.xaxis.borderWidth});
4652 drawLine (this._left, this._bottom, this._left, this._top, {lineCap:'round', strokeStyle:axes.yaxis.borderColor, lineWidth:axes.yaxis.borderWidth});
4654 // ctx.lineWidth = this.borderWidth;
4655 // ctx.strokeStyle = this.borderColor;
4656 // ctx.strokeRect(this._left, this._top, this._width, this._height);
4663 // Class: $.jqplot.DivTitleRenderer
4664 // The default title renderer for jqPlot. This class has no options beyond the <Title> class.
4665 $.jqplot.DivTitleRenderer = function() {
4668 $.jqplot.DivTitleRenderer.prototype.init = function(options) {
4669 $.extend(true, this, options);
4672 $.jqplot.DivTitleRenderer.prototype.draw = function() {
4673 // Memory Leaks patch
4675 this._elem.emptyForce();
4679 var r = this.renderer;
4680 var elem = document.createElement('div');
4681 this._elem = $(elem);
4682 this._elem.addClass('jqplot-title');
4686 this._elem.height(0);
4687 this._elem.width(0);
4689 else if (this.text) {
4694 else if (this.textColor) {
4695 color = this.textColor;
4698 // don't trust that a stylesheet is present, set the position.
4699 var styles = {position:'absolute', top:'0px', left:'0px'};
4701 if (this._plotWidth) {
4702 styles['width'] = this._plotWidth+'px';
4704 if (this.fontSize) {
4705 styles['fontSize'] = this.fontSize;
4707 if (typeof this.textAlign === 'string') {
4708 styles['textAlign'] = this.textAlign;
4711 styles['textAlign'] = 'center';
4714 styles['color'] = color;
4716 if (this.paddingBottom) {
4717 styles['paddingBottom'] = this.paddingBottom;
4719 if (this.fontFamily) {
4720 styles['fontFamily'] = this.fontFamily;
4723 this._elem.css(styles);
4724 if (this.escapeHtml) {
4725 this._elem.text(this.text);
4728 this._elem.html(this.text);
4732 // styletext += (this._plotWidth) ? 'width:'+this._plotWidth+'px;' : '';
4733 // styletext += (this.fontSize) ? 'font-size:'+this.fontSize+';' : '';
4734 // styletext += (this.textAlign) ? 'text-align:'+this.textAlign+';' : 'text-align:center;';
4735 // styletext += (color) ? 'color:'+color+';' : '';
4736 // styletext += (this.paddingBottom) ? 'padding-bottom:'+this.paddingBottom+';' : '';
4737 // this._elem = $('<div class="jqplot-title" style="'+styletext+'">'+this.text+'</div>');
4738 // if (this.fontFamily) {
4739 // this._elem.css('font-family', this.fontFamily);
4748 $.jqplot.DivTitleRenderer.prototype.pack = function() {
4749 // nothing to do here
4755 $.jqplot.LinePattern = function (ctx, pattern) {
4757 var defaultLinePatterns = {
4758 dotted: [ dotlen, $.jqplot.config.dotGapLength ],
4759 dashed: [ $.jqplot.config.dashLength, $.jqplot.config.gapLength ],
4763 if (typeof pattern === 'string') {
4764 if (pattern[0] === '.' || pattern[0] === '-') {
4767 for (var i=0, imax=s.length; i<imax; i++) {
4769 pattern.push( dotlen );
4771 else if (s[i] === '-') {
4772 pattern.push( $.jqplot.config.dashLength );
4777 pattern.push( $.jqplot.config.gapLength );
4781 pattern = defaultLinePatterns[pattern];
4785 if (!(pattern && pattern.length)) {
4789 var patternIndex = 0;
4790 var patternDistance = pattern[0];
4796 var moveTo = function (x, y) {
4804 var lineTo = function (x, y) {
4805 var scale = ctx.lineWidth;
4808 var dist = Math.sqrt(dx*dx+dy*dy);
4809 if ((dist > 0) && (scale > 0)) {
4813 var dp = scale * patternDistance;
4817 if ((patternIndex & 1) == 0) {
4818 ctx.lineTo( px, py );
4821 ctx.moveTo( px, py );
4825 if (patternIndex >= pattern.length) {
4828 patternDistance = pattern[patternIndex];
4833 if ((patternIndex & 1) == 0) {
4834 ctx.lineTo( px, py );
4837 ctx.moveTo( px, py );
4839 patternDistance -= dist / scale;
4846 var beginPath = function () {
4850 var closePath = function () {
4851 lineTo( pathx0, pathy0 );
4857 beginPath: beginPath,
4858 closePath: closePath
4862 // Class: $.jqplot.LineRenderer
4863 // The default line renderer for jqPlot, this class has no options beyond the <Series> class.
4864 // Draws series as a line.
4865 $.jqplot.LineRenderer = function(){
4866 this.shapeRenderer = new $.jqplot.ShapeRenderer();
4867 this.shadowRenderer = new $.jqplot.ShadowRenderer();
4870 // called with scope of series.
4871 $.jqplot.LineRenderer.prototype.init = function(options, plot) {
4872 // Group: Properties
4874 options = options || {};
4876 this.renderer.animation = {
4883 // True to draw a smoothed (interpolated) line through the data points
4884 // with automatically computed number of smoothing points.
4885 // Set to an integer number > 2 to specify number of smoothing points
4886 // to use between each data point.
4887 this.renderer.smooth = false; // true or a number > 2 for smoothing.
4888 this.renderer.tension = null; // null to auto compute or a number typically > 6. Fewer points requires higher tension.
4889 // prop: constrainSmoothing
4890 // True to use a more accurate smoothing algorithm that will
4891 // not overshoot any data points. False to allow overshoot but
4892 // produce a smoother looking line.
4893 this.renderer.constrainSmoothing = true;
4894 // this is smoothed data in grid coordinates, like gridData
4895 this.renderer._smoothedData = [];
4896 // this is smoothed data in plot units (plot coordinates), like plotData.
4897 this.renderer._smoothedPlotData = [];
4898 this.renderer._hiBandGridData = [];
4899 this.renderer._lowBandGridData = [];
4900 this.renderer._hiBandSmoothedData = [];
4901 this.renderer._lowBandSmoothedData = [];
4904 // Data used to draw error bands or confidence intervals above/below a line.
4906 // bandData can be input in 3 forms. jqPlot will figure out which is the
4907 // low band line and which is the high band line for all forms:
4909 // A 2 dimensional array like [[yl1, yl2, ...], [yu1, yu2, ...]] where
4910 // [yl1, yl2, ...] are y values of the lower line and
4911 // [yu1, yu2, ...] are y values of the upper line.
4912 // In this case there must be the same number of y data points as data points
4913 // in the series and the bands will inherit the x values of the series.
4915 // A 2 dimensional array like [[[xl1, yl1], [xl2, yl2], ...], [[xh1, yh1], [xh2, yh2], ...]]
4916 // where [xl1, yl1] are x,y data points for the lower line and
4917 // [xh1, yh1] are x,y data points for the high line.
4918 // x values do not have to correspond to the x values of the series and can
4919 // be of any arbitrary length.
4921 // Can be of form [[yl1, yu1], [yl2, yu2], [yl3, yu3], ...] where
4922 // there must be 3 or more arrays and there must be the same number of arrays
4923 // as there are data points in the series. In this case,
4924 // [yl1, yu1] specifies the lower and upper y values for the 1st
4925 // data point and so on. The bands will inherit the x
4926 // values from the series.
4927 this.renderer.bandData = [];
4930 // Banding around line, e.g error bands or confidence intervals.
4931 this.renderer.bands = {
4933 // true to show the bands. If bandData or interval is
4934 // supplied, show will be set to true by default.
4939 // color of lines at top and bottom of bands [default: series color].
4942 // True to show lines at top and bottom of bands [default: false].
4945 // True to fill area between bands [default: true].
4948 // css color spec for filled area. [default: series color].
4953 // User specified interval above and below line for bands [default: '3%''].
4954 // Can be a value like 3 or a string like '3%'
4955 // or an upper/lower array like [1, -2] or ['2%', '-1.5%']
4960 var lopts = {highlightMouseOver: options.highlightMouseOver, highlightMouseDown: options.highlightMouseDown, highlightColor: options.highlightColor};
4962 delete (options.highlightMouseOver);
4963 delete (options.highlightMouseDown);
4964 delete (options.highlightColor);
4966 $.extend(true, this.renderer, options);
4968 this.renderer.options = options;
4970 // if we are given some band data, and bands aren't explicity set to false in options, turn them on.
4971 if (this.renderer.bandData.length > 1 && (!options.bands || options.bands.show == null)) {
4972 this.renderer.bands.show = true;
4975 // if we are given an interval, and bands aren't explicity set to false in options, turn them on.
4976 else if (options.bands && options.bands.show == null && options.bands.interval != null) {
4977 this.renderer.bands.show = true;
4980 // if plot is filled, turn off bands.
4982 this.renderer.bands.show = false;
4985 if (this.renderer.bands.show) {
4986 this.renderer.initBands.call(this, this.renderer.options, plot);
4990 // smoothing is not compatible with stacked lines, disable
4992 this.renderer.smooth = false;
4995 // set the shape renderer options
4996 var opts = {lineJoin:this.lineJoin, lineCap:this.lineCap, fill:this.fill, isarc:false, strokeStyle:this.color, fillStyle:this.fillColor, lineWidth:this.lineWidth, linePattern:this.linePattern, closePath:this.fill};
4997 this.renderer.shapeRenderer.init(opts);
4999 var shadow_offset = options.shadowOffset;
5000 // set the shadow renderer options
5001 if (shadow_offset == null) {
5002 // scale the shadowOffset to the width of the line.
5003 if (this.lineWidth > 2.5) {
5004 shadow_offset = 1.25 * (1 + (Math.atan((this.lineWidth/2.5))/0.785398163 - 1)*0.6);
5005 // var shadow_offset = this.shadowOffset;
5007 // for skinny lines, don't make such a big shadow.
5009 shadow_offset = 1.25 * Math.atan((this.lineWidth/2.5))/0.785398163;
5013 var sopts = {lineJoin:this.lineJoin, lineCap:this.lineCap, fill:this.fill, isarc:false, angle:this.shadowAngle, offset:shadow_offset, alpha:this.shadowAlpha, depth:this.shadowDepth, lineWidth:this.lineWidth, linePattern:this.linePattern, closePath:this.fill};
5014 this.renderer.shadowRenderer.init(sopts);
5015 this._areaPoints = [];
5016 this._boundingBox = [[],[]];
5018 if (!this.isTrendline && this.fill || this.renderer.bands.show) {
5019 // Group: Properties
5021 // prop: highlightMouseOver
5022 // True to highlight area on a filled plot when moused over.
5023 // This must be false to enable highlightMouseDown to highlight when clicking on an area on a filled plot.
5024 this.highlightMouseOver = true;
5025 // prop: highlightMouseDown
5026 // True to highlight when a mouse button is pressed over an area on a filled plot.
5027 // This will be disabled if highlightMouseOver is true.
5028 this.highlightMouseDown = false;
5029 // prop: highlightColor
5030 // color to use when highlighting an area on a filled plot.
5031 this.highlightColor = null;
5032 // if user has passed in highlightMouseDown option and not set highlightMouseOver, disable highlightMouseOver
5033 if (lopts.highlightMouseDown && lopts.highlightMouseOver == null) {
5034 lopts.highlightMouseOver = false;
5037 $.extend(true, this, {highlightMouseOver: lopts.highlightMouseOver, highlightMouseDown: lopts.highlightMouseDown, highlightColor: lopts.highlightColor});
5039 if (!this.highlightColor) {
5040 var fc = (this.renderer.bands.show) ? this.renderer.bands.fillColor : this.fillColor;
5041 this.highlightColor = $.jqplot.computeHighlightColors(fc);
5043 // turn off (disable) the highlighter plugin
5044 if (this.highlighter) {
5045 this.highlighter.show = false;
5049 if (!this.isTrendline && plot) {
5050 plot.plugins.lineRenderer = {};
5051 plot.postInitHooks.addOnce(postInit);
5052 plot.postDrawHooks.addOnce(postPlotDraw);
5053 plot.eventListenerHooks.addOnce('jqplotMouseMove', handleMove);
5054 plot.eventListenerHooks.addOnce('jqplotMouseDown', handleMouseDown);
5055 plot.eventListenerHooks.addOnce('jqplotMouseUp', handleMouseUp);
5056 plot.eventListenerHooks.addOnce('jqplotClick', handleClick);
5057 plot.eventListenerHooks.addOnce('jqplotRightClick', handleRightClick);
5062 $.jqplot.LineRenderer.prototype.initBands = function(options, plot) {
5063 // use bandData if no data specified in bands option
5064 //var bd = this.renderer.bandData;
5065 var bd = options.bandData || [];
5066 var bands = this.renderer.bands;
5069 var data = this.data;
5072 // If 2 arrays, and each array greater than 2 elements, assume it is hi and low data bands of y values.
5073 if (bd.length == 2) {
5074 // Do we have an array of x,y values?
5075 // like [[[1,1], [2,4], [3,3]], [[1,3], [2,6], [3,5]]]
5076 if ($.isArray(bd[0][0])) {
5077 // since an arbitrary array of points, spin through all of them to determine max and min lines.
5080 var bdminidx = 0, bdmaxidx = 0;
5081 for (var i = 0, l = bd[0].length; i<l; i++) {
5083 if ((p[1] != null && p[1] > bands._max) || bands._max == null) {
5086 if ((p[1] != null && p[1] < bands._min) || bands._min == null) {
5090 for (var i = 0, l = bd[1].length; i<l; i++) {
5092 if ((p[1] != null && p[1] > bands._max) || bands._max == null) {
5096 if ((p[1] != null && p[1] < bands._min) || bands._min == null) {
5102 if (bdmaxidx === bdminidx) {
5106 bands.hiData = bd[bdmaxidx];
5107 bands.lowData = bd[bdminidx];
5109 // else data is arrays of y values
5110 // like [[1,4,3], [3,6,5]]
5111 // must have same number of band data points as points in series
5112 else if (bd[0].length === data.length && bd[1].length === data.length) {
5113 var hi = (bd[0][0] > bd[1][0]) ? 0 : 1;
5114 var low = (hi) ? 0 : 1;
5115 for (var i=0, l=data.length; i < l; i++) {
5116 bands.hiData.push([data[i][0], bd[hi][i]]);
5117 bands.lowData.push([data[i][0], bd[low][i]]);
5121 // we don't have proper data array, don't show bands.
5127 // if more than 2 arrays, have arrays of [ylow, yhi] values.
5128 // note, can't distinguish case of [[ylow, yhi], [ylow, yhi]] from [[ylow, ylow], [yhi, yhi]]
5129 // this is assumed to be of the latter form.
5130 else if (bd.length > 2 && !$.isArray(bd[0][0])) {
5131 var hi = (bd[0][0] > bd[0][1]) ? 0 : 1;
5132 var low = (hi) ? 0 : 1;
5133 for (var i=0, l=bd.length; i<l; i++) {
5134 bands.hiData.push([data[i][0], bd[i][hi]]);
5135 bands.lowData.push([data[i][0], bd[i][low]]);
5139 // don't have proper data, auto calculate
5141 var intrv = bands.interval;
5147 if ($.isArray(intrv)) {
5157 if (a.charAt(a.length - 1) === '%') {
5159 a = parseFloat(a)/100 + 1;
5168 if (b !== null && isNaN(b)) {
5170 if (b.charAt(b.length - 1) === '%') {
5172 b = parseFloat(b)/100 + 1;
5176 else if (b !== null) {
5185 if (bfunc === 'multiply') {
5190 // make sure a always applies to hi band.
5200 for (var i=0, l = data.length; i < l; i++) {
5203 bands.hiData.push([data[i][0], data[i][1] + a]);
5206 bands.hiData.push([data[i][0], data[i][1] * a]);
5211 bands.lowData.push([data[i][0], data[i][1] + b]);
5214 bands.lowData.push([data[i][0], data[i][1] * b]);
5225 var hd = bands.hiData;
5226 var ld = bands.lowData;
5227 for (var i = 0, l = hd.length; i<l; i++) {
5228 if ((hd[i][1] != null && hd[i][1] > bands._max) || bands._max == null) {
5229 bands._max = hd[i][1];
5232 for (var i = 0, l = ld.length; i<l; i++) {
5233 if ((ld[i][1] != null && ld[i][1] < bands._min) || bands._min == null) {
5234 bands._min = ld[i][1];
5238 // one last check for proper data
5239 // these don't apply any more since allowing arbitrary x,y values
5240 // if (bands.hiData.length != bands.lowData.length) {
5241 // bands.show = false;
5244 // if (bands.hiData.length != this.data.length) {
5245 // bands.show = false;
5248 if (bands.fillColor === null) {
5249 var c = $.jqplot.getColorComponents(bands.color);
5250 // now adjust alpha to differentiate fill
5252 bands.fillColor = 'rgba(' + c[0] +', '+ c[1] +', '+ c[2] +', '+ c[3] + ')';
5256 function getSteps (d, f) {
5257 return (3.4182054+f) * Math.pow(d, -0.3534992);
5260 function computeSteps (d1, d2) {
5261 var s = Math.sqrt(Math.pow((d2[0]- d1[0]), 2) + Math.pow ((d2[1] - d1[1]), 2));
5262 return 5.7648 * Math.log(s) + 7.4456;
5266 var a = (Math.exp(2*x) - 1) / (Math.exp(2*x) + 1);
5271 // computeConstrainedSmoothedData
5272 // An implementation of the constrained cubic spline interpolation
5273 // method as presented in:
5275 // Kruger, CJC, Constrained Cubic Spine Interpolation for Chemical Engineering Applications
5276 // http://www.korf.co.uk/spline.pdf
5278 // The implementation below borrows heavily from the sample Visual Basic
5279 // implementation by CJC Kruger found in http://www.korf.co.uk/spline.xls
5283 // called with scope of series
5284 function computeConstrainedSmoothedData (gd) {
5285 var smooth = this.renderer.smooth;
5286 var dim = this.canvas.getWidth();
5287 var xp = this._xaxis.series_p2u;
5288 var yp = this._yaxis.series_p2u;
5291 var dist = gd.length/dim;
5292 var _smoothedData = [];
5293 var _smoothedPlotData = [];
5295 if (!isNaN(parseFloat(smooth))) {
5296 steps = parseFloat(smooth);
5299 steps = getSteps(dist, 0.5);
5305 for (var i=0, l = gd.length; i<l; i++) {
5310 function dxx(x1, x0) {
5312 return Math.pow(10,10);
5320 // loop through each line segment. Have # points - 1 line segments. Nmber segments starting at 1.
5321 var nmax = gd.length - 1;
5322 for (var num = 1, gdl = gd.length; num<gdl; num++) {
5325 // point at each end of segment.
5326 for (var j = 0; j < 2; j++) {
5327 var i = num - 1 + j; // point number, 0 to # points.
5329 if (i == 0 || i == nmax) {
5330 gxx[j] = Math.pow(10, 10);
5332 else if (yy[i+1] - yy[i] == 0 || yy[i] - yy[i-1] == 0) {
5335 else if (((xx[i+1] - xx[i]) / (yy[i+1] - yy[i]) + (xx[i] - xx[i-1]) / (yy[i] - yy[i-1])) == 0 ) {
5338 else if ( (yy[i+1] - yy[i]) * (yy[i] - yy[i-1]) < 0 ) {
5343 gxx[j] = 2 / (dxx(xx[i + 1], xx[i]) / (yy[i + 1] - yy[i]) + dxx(xx[i], xx[i - 1]) / (yy[i] - yy[i - 1]));
5347 // Reset first derivative (slope) at first and last point
5349 // First point has 0 2nd derivative
5350 gxx[0] = 3 / 2 * (yy[1] - yy[0]) / dxx(xx[1], xx[0]) - gxx[1] / 2;
5352 else if (num == nmax) {
5353 // Last point has 0 2nd derivative
5354 gxx[1] = 3 / 2 * (yy[nmax] - yy[nmax - 1]) / dxx(xx[nmax], xx[nmax - 1]) - gxx[0] / 2;
5357 // Calc second derivative at points
5358 ggxx[0] = -2 * (gxx[1] + 2 * gxx[0]) / dxx(xx[num], xx[num - 1]) + 6 * (yy[num] - yy[num - 1]) / Math.pow(dxx(xx[num], xx[num - 1]), 2);
5359 ggxx[1] = 2 * (2 * gxx[1] + gxx[0]) / dxx(xx[num], xx[num - 1]) - 6 * (yy[num] - yy[num - 1]) / Math.pow(dxx(xx[num], xx[num - 1]), 2);
5361 // Calc constants for cubic interpolation
5362 D = 1 / 6 * (ggxx[1] - ggxx[0]) / dxx(xx[num], xx[num - 1]);
5363 C = 1 / 2 * (xx[num] * ggxx[0] - xx[num - 1] * ggxx[1]) / dxx(xx[num], xx[num - 1]);
5364 B = (yy[num] - yy[num - 1] - C * (Math.pow(xx[num], 2) - Math.pow(xx[num - 1], 2)) - D * (Math.pow(xx[num], 3) - Math.pow(xx[num - 1], 3))) / dxx(xx[num], xx[num - 1]);
5365 A = yy[num - 1] - B * xx[num - 1] - C * Math.pow(xx[num - 1], 2) - D * Math.pow(xx[num - 1], 3);
5367 var increment = (xx[num] - xx[num - 1]) / steps;
5370 for (var j = 0, l = steps; j < l; j++) {
5372 tempx = xx[num - 1] + j * increment;
5374 temp.push(A + B * tempx + C * Math.pow(tempx, 2) + D * Math.pow(tempx, 3));
5375 _smoothedData.push(temp);
5376 _smoothedPlotData.push([xp(temp[0]), yp(temp[1])]);
5380 _smoothedData.push(gd[i]);
5381 _smoothedPlotData.push([xp(gd[i][0]), yp(gd[i][1])]);
5383 return [_smoothedData, _smoothedPlotData];
5387 // computeHermiteSmoothedData
5388 // A hermite spline smoothing of the plot data.
5389 // This implementation is derived from the one posted
5390 // by krypin on the jqplot-users mailing list:
5392 // http://groups.google.com/group/jqplot-users/browse_thread/thread/748be6a445723cea?pli=1
5394 // with a blog post:
5396 // http://blog.statscollector.com/a-plugin-renderer-for-jqplot-to-draw-a-hermite-spline/
5398 // and download of the original plugin:
5400 // http://blog.statscollector.com/wp-content/uploads/2010/02/jqplot.hermiteSplineRenderer.js
5403 // called with scope of series
5404 function computeHermiteSmoothedData (gd) {
5405 var smooth = this.renderer.smooth;
5406 var tension = this.renderer.tension;
5407 var dim = this.canvas.getWidth();
5408 var xp = this._xaxis.series_p2u;
5409 var yp = this._yaxis.series_p2u;
5418 var t, s, h1, h2, h3, h4;
5419 var TiX, TiY, Ti1X, Ti1Y;
5423 var dist = gd.length/dim;
5424 var min, max, stretch, scale, shift;
5425 var _smoothedData = [];
5426 var _smoothedPlotData = [];
5427 if (!isNaN(parseFloat(smooth))) {
5428 steps = parseFloat(smooth);
5431 steps = getSteps(dist, 0.5);
5433 if (!isNaN(parseFloat(tension))) {
5434 tension = parseFloat(tension);
5437 for (var i=0, l = gd.length-1; i < l; i++) {
5439 if (tension === null) {
5440 slope = Math.abs((gd[i+1][1] - gd[i][1]) / (gd[i+1][0] - gd[i][0]));
5444 stretch = (max - min)/2.0;
5448 temp = slope/scale + shift;
5450 a1 = stretch * tanh(temp) - stretch * tanh(shift) + min;
5452 // if have both left and right line segments, will use minimum tension.
5454 slope2 = Math.abs((gd[i][1] - gd[i-1][1]) / (gd[i][0] - gd[i-1][0]));
5456 temp = slope2/scale + shift;
5458 a2 = stretch * tanh(temp) - stretch * tanh(shift) + min;
5466 for (t=0; t < steps; t++) {
5468 h1 = (1 + 2*s)*Math.pow((1-s),2);
5469 h2 = s*Math.pow((1-s),2);
5470 h3 = Math.pow(s,2)*(3-2*s);
5471 h4 = Math.pow(s,2)*(s-1);
5474 TiX = a * (gd[i+1][0] - gd[i-1][0]);
5475 TiY = a * (gd[i+1][1] - gd[i-1][1]);
5477 TiX = a * (gd[i+1][0] - gd[i][0]);
5478 TiY = a * (gd[i+1][1] - gd[i][1]);
5481 Ti1X = a * (gd[i+2][0] - gd[i][0]);
5482 Ti1Y = a * (gd[i+2][1] - gd[i][1]);
5484 Ti1X = a * (gd[i+1][0] - gd[i][0]);
5485 Ti1Y = a * (gd[i+1][1] - gd[i][1]);
5488 pX = h1*gd[i][0] + h3*gd[i+1][0] + h2*TiX + h4*Ti1X;
5489 pY = h1*gd[i][1] + h3*gd[i+1][1] + h2*TiY + h4*Ti1Y;
5492 _smoothedData.push(p);
5493 _smoothedPlotData.push([xp(pX), yp(pY)]);
5496 _smoothedData.push(gd[l]);
5497 _smoothedPlotData.push([xp(gd[l][0]), yp(gd[l][1])]);
5499 return [_smoothedData, _smoothedPlotData];
5503 // converts the user data values to grid coordinates and stores them
5504 // in the gridData array.
5505 // Called with scope of a series.
5506 $.jqplot.LineRenderer.prototype.setGridData = function(plot) {
5507 // recalculate the grid data
5508 var xp = this._xaxis.series_u2p;
5509 var yp = this._yaxis.series_u2p;
5510 var data = this._plotData;
5511 var pdata = this._prevPlotData;
5513 this._prevGridData = [];
5514 this.renderer._smoothedData = [];
5515 this.renderer._smoothedPlotData = [];
5516 this.renderer._hiBandGridData = [];
5517 this.renderer._lowBandGridData = [];
5518 this.renderer._hiBandSmoothedData = [];
5519 this.renderer._lowBandSmoothedData = [];
5520 var bands = this.renderer.bands;
5521 var hasNull = false;
5522 for (var i=0, l=data.length; i < l; i++) {
5523 // if not a line series or if no nulls in data, push the converted point onto the array.
5524 if (data[i][0] != null && data[i][1] != null) {
5525 this.gridData.push([xp.call(this._xaxis, data[i][0]), yp.call(this._yaxis, data[i][1])]);
5527 // else if there is a null, preserve it.
5528 else if (data[i][0] == null) {
5530 this.gridData.push([null, yp.call(this._yaxis, data[i][1])]);
5532 else if (data[i][1] == null) {
5534 this.gridData.push([xp.call(this._xaxis, data[i][0]), null]);
5536 // if not a line series or if no nulls in data, push the converted point onto the array.
5537 if (pdata[i] != null && pdata[i][0] != null && pdata[i][1] != null) {
5538 this._prevGridData.push([xp.call(this._xaxis, pdata[i][0]), yp.call(this._yaxis, pdata[i][1])]);
5540 // else if there is a null, preserve it.
5541 else if (pdata[i] != null && pdata[i][0] == null) {
5542 this._prevGridData.push([null, yp.call(this._yaxis, pdata[i][1])]);
5544 else if (pdata[i] != null && pdata[i][0] != null && pdata[i][1] == null) {
5545 this._prevGridData.push([xp.call(this._xaxis, pdata[i][0]), null]);
5549 // don't do smoothing or bands on broken lines.
5551 this.renderer.smooth = false;
5552 if (this._type === 'line') {
5557 if (this._type === 'line' && bands.show) {
5558 for (var i=0, l=bands.hiData.length; i<l; i++) {
5559 this.renderer._hiBandGridData.push([xp.call(this._xaxis, bands.hiData[i][0]), yp.call(this._yaxis, bands.hiData[i][1])]);
5561 for (var i=0, l=bands.lowData.length; i<l; i++) {
5562 this.renderer._lowBandGridData.push([xp.call(this._xaxis, bands.lowData[i][0]), yp.call(this._yaxis, bands.lowData[i][1])]);
5566 // calculate smoothed data if enough points and no nulls
5567 if (this._type === 'line' && this.renderer.smooth && this.gridData.length > 2) {
5569 if (this.renderer.constrainSmoothing) {
5570 ret = computeConstrainedSmoothedData.call(this, this.gridData);
5571 this.renderer._smoothedData = ret[0];
5572 this.renderer._smoothedPlotData = ret[1];
5575 ret = computeConstrainedSmoothedData.call(this, this.renderer._hiBandGridData);
5576 this.renderer._hiBandSmoothedData = ret[0];
5577 ret = computeConstrainedSmoothedData.call(this, this.renderer._lowBandGridData);
5578 this.renderer._lowBandSmoothedData = ret[0];
5584 ret = computeHermiteSmoothedData.call(this, this.gridData);
5585 this.renderer._smoothedData = ret[0];
5586 this.renderer._smoothedPlotData = ret[1];
5589 ret = computeHermiteSmoothedData.call(this, this.renderer._hiBandGridData);
5590 this.renderer._hiBandSmoothedData = ret[0];
5591 ret = computeHermiteSmoothedData.call(this, this.renderer._lowBandGridData);
5592 this.renderer._lowBandSmoothedData = ret[0];
5601 // converts any arbitrary data values to grid coordinates and
5602 // returns them. This method exists so that plugins can use a series'
5603 // linerenderer to generate grid data points without overwriting the
5604 // grid data associated with that series.
5605 // Called with scope of a series.
5606 $.jqplot.LineRenderer.prototype.makeGridData = function(data, plot) {
5607 // recalculate the grid data
5608 var xp = this._xaxis.series_u2p;
5609 var yp = this._yaxis.series_u2p;
5612 this.renderer._smoothedData = [];
5613 this.renderer._smoothedPlotData = [];
5614 this.renderer._hiBandGridData = [];
5615 this.renderer._lowBandGridData = [];
5616 this.renderer._hiBandSmoothedData = [];
5617 this.renderer._lowBandSmoothedData = [];
5618 var bands = this.renderer.bands;
5619 var hasNull = false;
5620 for (var i=0; i<data.length; i++) {
5621 // if not a line series or if no nulls in data, push the converted point onto the array.
5622 if (data[i][0] != null && data[i][1] != null) {
5623 gd.push([xp.call(this._xaxis, data[i][0]), yp.call(this._yaxis, data[i][1])]);
5625 // else if there is a null, preserve it.
5626 else if (data[i][0] == null) {
5628 gd.push([null, yp.call(this._yaxis, data[i][1])]);
5630 else if (data[i][1] == null) {
5632 gd.push([xp.call(this._xaxis, data[i][0]), null]);
5636 // don't do smoothing or bands on broken lines.
5638 this.renderer.smooth = false;
5639 if (this._type === 'line') {
5644 if (this._type === 'line' && bands.show) {
5645 for (var i=0, l=bands.hiData.length; i<l; i++) {
5646 this.renderer._hiBandGridData.push([xp.call(this._xaxis, bands.hiData[i][0]), yp.call(this._yaxis, bands.hiData[i][1])]);
5648 for (var i=0, l=bands.lowData.length; i<l; i++) {
5649 this.renderer._lowBandGridData.push([xp.call(this._xaxis, bands.lowData[i][0]), yp.call(this._yaxis, bands.lowData[i][1])]);
5653 if (this._type === 'line' && this.renderer.smooth && gd.length > 2) {
5655 if (this.renderer.constrainSmoothing) {
5656 ret = computeConstrainedSmoothedData.call(this, gd);
5657 this.renderer._smoothedData = ret[0];
5658 this.renderer._smoothedPlotData = ret[1];
5661 ret = computeConstrainedSmoothedData.call(this, this.renderer._hiBandGridData);
5662 this.renderer._hiBandSmoothedData = ret[0];
5663 ret = computeConstrainedSmoothedData.call(this, this.renderer._lowBandGridData);
5664 this.renderer._lowBandSmoothedData = ret[0];
5670 ret = computeHermiteSmoothedData.call(this, gd);
5671 this.renderer._smoothedData = ret[0];
5672 this.renderer._smoothedPlotData = ret[1];
5675 ret = computeHermiteSmoothedData.call(this, this.renderer._hiBandGridData);
5676 this.renderer._hiBandSmoothedData = ret[0];
5677 ret = computeHermiteSmoothedData.call(this, this.renderer._lowBandGridData);
5678 this.renderer._lowBandSmoothedData = ret[0];
5688 // called within scope of series.
5689 $.jqplot.LineRenderer.prototype.draw = function(ctx, gd, options, plot) {
5691 // get a copy of the options, so we don't modify the original object.
5692 var opts = $.extend(true, {}, options);
5693 var shadow = (opts.shadow != undefined) ? opts.shadow : this.shadow;
5694 var showLine = (opts.showLine != undefined) ? opts.showLine : this.showLine;
5695 var fill = (opts.fill != undefined) ? opts.fill : this.fill;
5696 var fillAndStroke = (opts.fillAndStroke != undefined) ? opts.fillAndStroke : this.fillAndStroke;
5697 var xmin, ymin, xmax, ymax;
5701 // if we fill, we'll have to add points to close the curve.
5703 if (this.fillToZero) {
5704 // have to break line up into shapes at axis crossings
5705 var negativeColor = this.negativeColor;
5706 if (! this.useNegativeColors) {
5707 negativeColor = opts.fillStyle;
5709 var isnegative = false;
5710 var posfs = opts.fillStyle;
5712 // if stoking line as well as filling, get a copy of line data.
5713 if (fillAndStroke) {
5714 var fasgd = gd.slice(0);
5716 // if not stacked, fill down to axis
5717 if (this.index == 0 || !this._stack) {
5720 var pd = (this.renderer.smooth) ? this.renderer._smoothedPlotData : this._plotData;
5721 this._areaPoints = [];
5722 var pyzero = this._yaxis.series_u2p(this.fillToValue);
5723 var pxzero = this._xaxis.series_u2p(this.fillToValue);
5725 opts.closePath = true;
5727 if (this.fillAxis == 'y') {
5728 tempgd.push([gd[0][0], pyzero]);
5729 this._areaPoints.push([gd[0][0], pyzero]);
5731 for (var i=0; i<gd.length-1; i++) {
5733 this._areaPoints.push(gd[i]);
5734 // do we have an axis crossing?
5735 if (pd[i][1] * pd[i+1][1] < 0) {
5738 opts.fillStyle = negativeColor;
5742 opts.fillStyle = posfs;
5745 var xintercept = gd[i][0] + (gd[i+1][0] - gd[i][0]) * (pyzero-gd[i][1])/(gd[i+1][1] - gd[i][1]);
5746 tempgd.push([xintercept, pyzero]);
5747 this._areaPoints.push([xintercept, pyzero]);
5748 // now draw this shape and shadow.
5750 this.renderer.shadowRenderer.draw(ctx, tempgd, opts);
5752 this.renderer.shapeRenderer.draw(ctx, tempgd, opts);
5753 // now empty temp array and continue
5754 tempgd = [[xintercept, pyzero]];
5755 // this._areaPoints = [[xintercept, pyzero]];
5758 if (pd[gd.length-1][1] < 0) {
5760 opts.fillStyle = negativeColor;
5764 opts.fillStyle = posfs;
5766 tempgd.push(gd[gd.length-1]);
5767 this._areaPoints.push(gd[gd.length-1]);
5768 tempgd.push([gd[gd.length-1][0], pyzero]);
5769 this._areaPoints.push([gd[gd.length-1][0], pyzero]);
5771 // now draw the last area.
5773 this.renderer.shadowRenderer.draw(ctx, tempgd, opts);
5775 this.renderer.shapeRenderer.draw(ctx, tempgd, opts);
5778 // var gridymin = this._yaxis.series_u2p(0);
5779 // // IE doesn't return new length on unshift
5780 // gd.unshift([gd[0][0], gridymin]);
5782 // gd.push([gd[len - 1][0], gridymin]);
5784 // if stacked, fill to line below
5786 var prev = this._prevGridData;
5787 for (var i=prev.length; i>0; i--) {
5789 // this._areaPoints.push(prev[i-1]);
5792 this.renderer.shadowRenderer.draw(ctx, gd, opts);
5794 this._areaPoints = gd;
5795 this.renderer.shapeRenderer.draw(ctx, gd, opts);
5798 /////////////////////////
5799 // Not filled to zero
5800 ////////////////////////
5802 // if stoking line as well as filling, get a copy of line data.
5803 if (fillAndStroke) {
5804 var fasgd = gd.slice(0);
5806 // if not stacked, fill down to axis
5807 if (this.index == 0 || !this._stack) {
5808 // var gridymin = this._yaxis.series_u2p(this._yaxis.min) - this.gridBorderWidth / 2;
5809 var gridymin = ctx.canvas.height;
5810 // IE doesn't return new length on unshift
5811 gd.unshift([gd[0][0], gridymin]);
5812 var len = gd.length;
5813 gd.push([gd[len - 1][0], gridymin]);
5815 // if stacked, fill to line below
5817 var prev = this._prevGridData;
5818 for (var i=prev.length; i>0; i--) {
5822 this._areaPoints = gd;
5825 this.renderer.shadowRenderer.draw(ctx, gd, opts);
5828 this.renderer.shapeRenderer.draw(ctx, gd, opts);
5830 if (fillAndStroke) {
5831 var fasopts = $.extend(true, {}, opts, {fill:false, closePath:false});
5832 this.renderer.shapeRenderer.draw(ctx, fasgd, fasopts);
5834 // TODO: figure out some way to do shadows nicely
5836 // this.renderer.shadowRenderer.draw(ctx, fasgd, fasopts);
5838 // now draw the markers
5839 if (this.markerRenderer.show) {
5840 if (this.renderer.smooth) {
5841 fasgd = this.gridData;
5843 for (i=0; i<fasgd.length; i++) {
5844 this.markerRenderer.draw(fasgd[i][0], fasgd[i][1], ctx, opts.markerOptions);
5851 if (this.renderer.bands.show) {
5853 var bopts = $.extend(true, {}, opts);
5854 if (this.renderer.bands.showLines) {
5855 bdat = (this.renderer.smooth) ? this.renderer._hiBandSmoothedData : this.renderer._hiBandGridData;
5856 this.renderer.shapeRenderer.draw(ctx, bdat, opts);
5857 bdat = (this.renderer.smooth) ? this.renderer._lowBandSmoothedData : this.renderer._lowBandGridData;
5858 this.renderer.shapeRenderer.draw(ctx, bdat, bopts);
5861 if (this.renderer.bands.fill) {
5862 if (this.renderer.smooth) {
5863 bdat = this.renderer._hiBandSmoothedData.concat(this.renderer._lowBandSmoothedData.reverse());
5866 bdat = this.renderer._hiBandGridData.concat(this.renderer._lowBandGridData.reverse());
5868 this._areaPoints = bdat;
5869 bopts.closePath = true;
5871 bopts.fillStyle = this.renderer.bands.fillColor;
5872 this.renderer.shapeRenderer.draw(ctx, bdat, bopts);
5877 this.renderer.shadowRenderer.draw(ctx, gd, opts);
5880 this.renderer.shapeRenderer.draw(ctx, gd, opts);
5883 // calculate the bounding box
5884 var xmin = xmax = ymin = ymax = null;
5885 for (i=0; i<this._areaPoints.length; i++) {
5886 var p = this._areaPoints[i];
5887 if (xmin > p[0] || xmin == null) {
5890 if (ymax < p[1] || ymax == null) {
5893 if (xmax < p[0] || xmax == null) {
5896 if (ymin > p[1] || ymin == null) {
5901 if (this.type === 'line' && this.renderer.bands.show) {
5902 ymax = this._yaxis.series_u2p(this.renderer.bands._min);
5903 ymin = this._yaxis.series_u2p(this.renderer.bands._max);
5906 this._boundingBox = [[xmin, ymax], [xmax, ymin]];
5908 // now draw the markers
5909 if (this.markerRenderer.show && !fill) {
5910 if (this.renderer.smooth) {
5913 for (i=0; i<gd.length; i++) {
5914 if (gd[i][0] != null && gd[i][1] != null) {
5915 this.markerRenderer.draw(gd[i][0], gd[i][1], ctx, opts.markerOptions);
5924 $.jqplot.LineRenderer.prototype.drawShadow = function(ctx, gd, options) {
5925 // This is a no-op, shadows drawn with lines.
5928 // called with scope of plot.
5929 // make sure to not leave anything highlighted.
5930 function postInit(target, data, options) {
5931 for (var i=0; i<this.series.length; i++) {
5932 if (this.series[i].renderer.constructor == $.jqplot.LineRenderer) {
5933 // don't allow mouseover and mousedown at same time.
5934 if (this.series[i].highlightMouseOver) {
5935 this.series[i].highlightMouseDown = false;
5941 // called within context of plot
5942 // create a canvas which we can draw on.
5943 // insert it before the eventCanvas, so eventCanvas will still capture events.
5944 function postPlotDraw() {
5945 // Memory Leaks patch
5946 if (this.plugins.lineRenderer && this.plugins.lineRenderer.highlightCanvas) {
5947 this.plugins.lineRenderer.highlightCanvas.resetCanvas();
5948 this.plugins.lineRenderer.highlightCanvas = null;
5951 this.plugins.lineRenderer.highlightedSeriesIndex = null;
5952 this.plugins.lineRenderer.highlightCanvas = new $.jqplot.GenericCanvas();
5954 this.eventCanvas._elem.before(this.plugins.lineRenderer.highlightCanvas.createElement(this._gridPadding, 'jqplot-lineRenderer-highlight-canvas', this._plotDimensions, this));
5955 this.plugins.lineRenderer.highlightCanvas.setContext();
5956 this.eventCanvas._elem.bind('mouseleave', {plot:this}, function (ev) { unhighlight(ev.data.plot); });
5959 function highlight (plot, sidx, pidx, points) {
5960 var s = plot.series[sidx];
5961 var canvas = plot.plugins.lineRenderer.highlightCanvas;
5962 canvas._ctx.clearRect(0,0,canvas._ctx.canvas.width, canvas._ctx.canvas.height);
5963 s._highlightedPoint = pidx;
5964 plot.plugins.lineRenderer.highlightedSeriesIndex = sidx;
5965 var opts = {fillStyle: s.highlightColor};
5966 if (s.type === 'line' && s.renderer.bands.show) {
5968 opts.closePath = true;
5970 s.renderer.shapeRenderer.draw(canvas._ctx, points, opts);
5974 function unhighlight (plot) {
5975 var canvas = plot.plugins.lineRenderer.highlightCanvas;
5976 canvas._ctx.clearRect(0,0, canvas._ctx.canvas.width, canvas._ctx.canvas.height);
5977 for (var i=0; i<plot.series.length; i++) {
5978 plot.series[i]._highlightedPoint = null;
5980 plot.plugins.lineRenderer.highlightedSeriesIndex = null;
5981 plot.target.trigger('jqplotDataUnhighlight');
5986 function handleMove(ev, gridpos, datapos, neighbor, plot) {
5988 var ins = [neighbor.seriesIndex, neighbor.pointIndex, neighbor.data];
5989 var evt1 = jQuery.Event('jqplotDataMouseOver');
5990 evt1.pageX = ev.pageX;
5991 evt1.pageY = ev.pageY;
5992 plot.target.trigger(evt1, ins);
5993 if (plot.series[ins[0]].highlightMouseOver && !(ins[0] == plot.plugins.lineRenderer.highlightedSeriesIndex)) {
5994 var evt = jQuery.Event('jqplotDataHighlight');
5995 evt.which = ev.which;
5996 evt.pageX = ev.pageX;
5997 evt.pageY = ev.pageY;
5998 plot.target.trigger(evt, ins);
5999 highlight (plot, neighbor.seriesIndex, neighbor.pointIndex, neighbor.points);
6002 else if (neighbor == null) {
6007 function handleMouseDown(ev, gridpos, datapos, neighbor, plot) {
6009 var ins = [neighbor.seriesIndex, neighbor.pointIndex, neighbor.data];
6010 if (plot.series[ins[0]].highlightMouseDown && !(ins[0] == plot.plugins.lineRenderer.highlightedSeriesIndex)) {
6011 var evt = jQuery.Event('jqplotDataHighlight');
6012 evt.which = ev.which;
6013 evt.pageX = ev.pageX;
6014 evt.pageY = ev.pageY;
6015 plot.target.trigger(evt, ins);
6016 highlight (plot, neighbor.seriesIndex, neighbor.pointIndex, neighbor.points);
6019 else if (neighbor == null) {
6024 function handleMouseUp(ev, gridpos, datapos, neighbor, plot) {
6025 var idx = plot.plugins.lineRenderer.highlightedSeriesIndex;
6026 if (idx != null && plot.series[idx].highlightMouseDown) {
6031 function handleClick(ev, gridpos, datapos, neighbor, plot) {
6033 var ins = [neighbor.seriesIndex, neighbor.pointIndex, neighbor.data];
6034 var evt = jQuery.Event('jqplotDataClick');
6035 evt.which = ev.which;
6036 evt.pageX = ev.pageX;
6037 evt.pageY = ev.pageY;
6038 plot.target.trigger(evt, ins);
6042 function handleRightClick(ev, gridpos, datapos, neighbor, plot) {
6044 var ins = [neighbor.seriesIndex, neighbor.pointIndex, neighbor.data];
6045 var idx = plot.plugins.lineRenderer.highlightedSeriesIndex;
6046 if (idx != null && plot.series[idx].highlightMouseDown) {
6049 var evt = jQuery.Event('jqplotDataRightClick');
6050 evt.which = ev.which;
6051 evt.pageX = ev.pageX;
6052 evt.pageY = ev.pageY;
6053 plot.target.trigger(evt, ins);
6058 // class: $.jqplot.LinearAxisRenderer
6059 // The default jqPlot axis renderer, creating a numeric axis.
6060 $.jqplot.LinearAxisRenderer = function() {
6063 // called with scope of axis object.
6064 $.jqplot.LinearAxisRenderer.prototype.init = function(options){
6065 // prop: breakPoints
6066 // EXPERIMENTAL!! Use at your own risk!
6067 // Works only with linear axes and the default tick renderer.
6068 // Array of [start, stop] points to create a broken axis.
6069 // Broken axes have a "jump" in them, which is an immediate
6070 // transition from a smaller value to a larger value.
6071 // Currently, axis ticks MUST be manually assigned if using breakPoints
6072 // by using the axis ticks array option.
6073 this.breakPoints = null;
6074 // prop: breakTickLabel
6075 // Label to use at the axis break if breakPoints are specified.
6076 this.breakTickLabel = "≈";
6077 // prop: drawBaseline
6078 // True to draw the axis baseline.
6079 this.drawBaseline = true;
6080 // prop: baselineWidth
6081 // width of the baseline in pixels.
6082 this.baselineWidth = null;
6083 // prop: baselineColor
6084 // CSS color spec for the baseline.
6085 this.baselineColor = null;
6086 // prop: forceTickAt0
6087 // This will ensure that there is always a tick mark at 0.
6088 // If data range is strictly positive or negative,
6089 // this will force 0 to be inside the axis bounds unless
6090 // the appropriate axis pad (pad, padMin or padMax) is set
6091 // to 0, then this will force an axis min or max value at 0.
6092 // This has know effect when any of the following options
6093 // are set: autoscale, min, max, numberTicks or tickInterval.
6094 this.forceTickAt0 = false;
6095 // prop: forceTickAt100
6096 // This will ensure that there is always a tick mark at 100.
6097 // If data range is strictly above or below 100,
6098 // this will force 100 to be inside the axis bounds unless
6099 // the appropriate axis pad (pad, padMin or padMax) is set
6100 // to 0, then this will force an axis min or max value at 100.
6101 // This has know effect when any of the following options
6102 // are set: autoscale, min, max, numberTicks or tickInterval.
6103 this.forceTickAt100 = false;
6105 // Controls the amount to inset the first and last ticks from
6106 // the edges of the grid, in multiples of the tick interval.
6107 // 0 is no inset, 0.5 is one half a tick interval, 1 is a full
6108 // tick interval, etc.
6111 // Number of ticks to add between "major" ticks.
6112 // Major ticks are ticks supplied by user or auto computed.
6113 // Minor ticks cannot be created by user.
6114 this.minorTicks = 0;
6116 // true to align tick marks across opposed axes
6117 // such as from the y2axis to yaxis.
6118 this.alignTicks = false;
6119 this._autoFormatString = '';
6120 this._overrideFormatString = false;
6121 this._scalefact = 1.0;
6122 $.extend(true, this, options);
6123 if (this.breakPoints) {
6124 if (!$.isArray(this.breakPoints)) {
6125 this.breakPoints = null;
6127 else if (this.breakPoints.length < 2 || this.breakPoints[1] <= this.breakPoints[0]) {
6128 this.breakPoints = null;
6131 if (this.numberTicks != null && this.numberTicks < 2) {
6132 this.numberTicks = 2;
6134 this.resetDataBounds();
6137 // called with scope of axis
6138 $.jqplot.LinearAxisRenderer.prototype.draw = function(ctx, plot) {
6140 // populate the axis label and value properties.
6141 // createTicks is a method on the renderer, but
6142 // call it within the scope of the axis.
6143 this.renderer.createTicks.call(this, plot);
6144 // fill a div with axes labels in the right direction.
6145 // Need to pregenerate each axis to get it's bounds and
6146 // position it and the labels correctly on the plot.
6149 // Added for theming.
6151 // Memory Leaks patch
6152 //this._elem.empty();
6153 this._elem.emptyForce();
6157 this._elem = $(document.createElement('div'));
6158 this._elem.addClass('jqplot-axis jqplot-'+this.name);
6159 this._elem.css('position', 'absolute');
6162 if (this.name == 'xaxis' || this.name == 'x2axis') {
6163 this._elem.width(this._plotDimensions.width);
6166 this._elem.height(this._plotDimensions.height);
6169 // create a _label object.
6170 this.labelOptions.axis = this.name;
6171 this._label = new this.labelRenderer(this.labelOptions);
6172 if (this._label.show) {
6173 var elem = this._label.draw(ctx, plot);
6174 elem.appendTo(this._elem);
6178 var t = this._ticks;
6180 for (var i=0; i<t.length; i++) {
6182 if (tick.show && tick.showLabel && (!tick.isMinorTick || this.showMinorTicks)) {
6183 this._elem.append(tick.draw(ctx, plot));
6192 // called with scope of an axis
6193 $.jqplot.LinearAxisRenderer.prototype.reset = function() {
6194 this.min = this._options.min;
6195 this.max = this._options.max;
6196 this.tickInterval = this._options.tickInterval;
6197 this.numberTicks = this._options.numberTicks;
6198 this._autoFormatString = '';
6199 if (this._overrideFormatString && this.tickOptions && this.tickOptions.formatString) {
6200 this.tickOptions.formatString = '';
6203 // this._ticks = this.__ticks;
6206 // called with scope of axis
6207 $.jqplot.LinearAxisRenderer.prototype.set = function() {
6212 var lshow = (this._label == null) ? false : this._label.show;
6214 var t = this._ticks;
6216 for (var i=0; i<t.length; i++) {
6218 if (!tick._breakTick && tick.show && tick.showLabel && (!tick.isMinorTick || this.showMinorTicks)) {
6219 if (this.name == 'xaxis' || this.name == 'x2axis') {
6220 temp = tick._elem.outerHeight(true);
6223 temp = tick._elem.outerWidth(true);
6234 w = this._label._elem.outerWidth(true);
6235 h = this._label._elem.outerHeight(true);
6237 if (this.name == 'xaxis') {
6239 this._elem.css({'height':dim+'px', left:'0px', bottom:'0px'});
6241 else if (this.name == 'x2axis') {
6243 this._elem.css({'height':dim+'px', left:'0px', top:'0px'});
6245 else if (this.name == 'yaxis') {
6247 this._elem.css({'width':dim+'px', left:'0px', top:'0px'});
6248 if (lshow && this._label.constructor == $.jqplot.AxisLabelRenderer) {
6249 this._label._elem.css('width', w+'px');
6254 this._elem.css({'width':dim+'px', right:'0px', top:'0px'});
6255 if (lshow && this._label.constructor == $.jqplot.AxisLabelRenderer) {
6256 this._label._elem.css('width', w+'px');
6262 // called with scope of axis
6263 $.jqplot.LinearAxisRenderer.prototype.createTicks = function(plot) {
6264 // we're are operating on an axis here
6265 var ticks = this._ticks;
6266 var userTicks = this.ticks;
6267 var name = this.name;
6268 // databounds were set on axis initialization.
6269 var db = this._dataBounds;
6270 var dim = (this.name.charAt(0) === 'x') ? this._plotDimensions.width : this._plotDimensions.height;
6275 // get a copy of user's settings for min/max.
6276 var userMin = this.min;
6277 var userMax = this.max;
6278 var userNT = this.numberTicks;
6279 var userTI = this.tickInterval;
6282 this._scalefact = (Math.max(dim, threshold+1) - threshold)/300.0;
6284 // if we already have ticks, use them.
6285 // ticks must be in order of increasing value.
6287 if (userTicks.length) {
6288 // ticks could be 1D or 2D array of [val, val, ,,,] or [[val, label], [val, label], ...] or mixed
6289 for (i=0; i<userTicks.length; i++){
6290 var ut = userTicks[i];
6291 var t = new this.tickRenderer(this.tickOptions);
6292 if ($.isArray(ut)) {
6294 if (this.breakPoints) {
6295 if (ut[0] == this.breakPoints[0]) {
6296 t.label = this.breakTickLabel;
6297 t._breakTick = true;
6298 t.showGridline = false;
6301 else if (ut[0] > this.breakPoints[0] && ut[0] <= this.breakPoints[1]) {
6303 t.showGridline = false;
6313 t.setTick(ut[0], this.name);
6314 this._ticks.push(t);
6317 else if ($.isPlainObject(ut)) {
6318 $.extend(true, t, ut);
6320 this._ticks.push(t);
6325 if (this.breakPoints) {
6326 if (ut == this.breakPoints[0]) {
6327 t.label = this.breakTickLabel;
6328 t._breakTick = true;
6329 t.showGridline = false;
6332 else if (ut > this.breakPoints[0] && ut <= this.breakPoints[1]) {
6334 t.showGridline = false;
6337 t.setTick(ut, this.name);
6338 this._ticks.push(t);
6341 this.numberTicks = userTicks.length;
6342 this.min = this._ticks[0].value;
6343 this.max = this._ticks[this.numberTicks-1].value;
6344 this.tickInterval = (this.max - this.min) / (this.numberTicks - 1);
6347 // we don't have any ticks yet, let's make some!
6349 if (name == 'xaxis' || name == 'x2axis') {
6350 dim = this._plotDimensions.width;
6353 dim = this._plotDimensions.height;
6356 var _numberTicks = this.numberTicks;
6358 // if aligning this axis, use number of ticks from previous axis.
6359 // Do I need to reset somehow if alignTicks is changed and then graph is replotted??
6360 if (this.alignTicks) {
6361 if (this.name === 'x2axis' && plot.axes.xaxis.show) {
6362 _numberTicks = plot.axes.xaxis.numberTicks;
6364 else if (this.name.charAt(0) === 'y' && this.name !== 'yaxis' && this.name !== 'yMidAxis' && plot.axes.yaxis.show) {
6365 _numberTicks = plot.axes.yaxis.numberTicks;
6369 min = ((this.min != null) ? this.min : db.min);
6370 max = ((this.max != null) ? this.max : db.max);
6372 var range = max - min;
6376 if (this.tickOptions == null || !this.tickOptions.formatString) {
6377 this._overrideFormatString = true;
6380 // Doing complete autoscaling
6381 if (this.min == null || this.max == null && this.tickInterval == null && !this.autoscale) {
6382 // Check if user must have tick at 0 or 100 and ensure they are in range.
6383 // The autoscaling algorithm will always place ticks at 0 and 100 if they are in range.
6384 if (this.forceTickAt0) {
6393 if (this.forceTickAt100) {
6402 var keepMin = false,
6405 if (this.min != null) {
6409 else if (this.max != null) {
6413 // var threshold = 30;
6414 // var tdim = Math.max(dim, threshold+1);
6415 // this._scalefact = (tdim-threshold)/300.0;
6416 var ret = $.jqplot.LinearTickGenerator(min, max, this._scalefact, _numberTicks, keepMin, keepMax);
6417 // calculate a padded max and min, points should be less than these
6418 // so that they aren't too close to the edges of the plot.
6419 // User can adjust how much padding is allowed with pad, padMin and PadMax options.
6420 // If min or max is set, don't pad that end of axis.
6421 var tumin = (this.min != null) ? min : min + range*(this.padMin - 1);
6422 var tumax = (this.max != null) ? max : max - range*(this.padMax - 1);
6424 // if they're equal, we shouldn't have to do anything, right?
6425 // if (min <=tumin || max >= tumax) {
6426 if (min <tumin || max > tumax) {
6427 tumin = (this.min != null) ? min : min - range*(this.padMin - 1);
6428 tumax = (this.max != null) ? max : max + range*(this.padMax - 1);
6429 ret = $.jqplot.LinearTickGenerator(tumin, tumax, this._scalefact, _numberTicks, keepMin, keepMax);
6434 // if numberTicks specified, it should return the same.
6435 this.numberTicks = ret[2];
6436 this._autoFormatString = ret[3];
6437 this.tickInterval = ret[4];
6440 // User has specified some axis scale related option, can use auto algorithm
6443 // if min and max are same, space them out a bit
6447 adj = Math.max(Math.log(min)/Math.LN10, 0.05);
6453 // autoscale. Can't autoscale if min or max is supplied.
6454 // Will use numberTicks and tickInterval if supplied. Ticks
6455 // across multiple axes may not line up depending on how
6456 // bars are to be plotted.
6457 if (this.autoscale && this.min == null && this.max == null) {
6458 var rrange, ti, margin;
6459 var forceMinZero = false;
6460 var forceZeroLine = false;
6461 var intervals = {min:null, max:null, average:null, stddev:null};
6462 // if any series are bars, or if any are fill to zero, and if this
6463 // is the axis to fill toward, check to see if we can start axis at zero.
6464 for (var i=0; i<this._series.length; i++) {
6465 var s = this._series[i];
6466 var faname = (s.fillAxis == 'x') ? s._xaxis.name : s._yaxis.name;
6467 // check to see if this is the fill axis
6468 if (this.name == faname) {
6469 var vals = s._plotValues[s.fillAxis];
6472 for (var j=1; j<vals.length; j++) {
6473 if (vals[j] < vmin) {
6476 else if (vals[j] > vmax) {
6480 var dp = (vmax - vmin) / vmax;
6481 // is this sries a bar?
6482 if (s.renderer.constructor == $.jqplot.BarRenderer) {
6483 // if no negative values and could also check range.
6484 if (vmin >= 0 && (s.fillToZero || dp > 0.1)) {
6485 forceMinZero = true;
6488 forceMinZero = false;
6489 if (s.fill && s.fillToZero && vmin < 0 && vmax > 0) {
6490 forceZeroLine = true;
6493 forceZeroLine = false;
6498 // if not a bar and filling, use appropriate method.
6500 if (vmin >= 0 && (s.fillToZero || dp > 0.1)) {
6501 forceMinZero = true;
6503 else if (vmin < 0 && vmax > 0 && s.fillToZero) {
6504 forceMinZero = false;
6505 forceZeroLine = true;
6508 forceMinZero = false;
6509 forceZeroLine = false;
6513 // if not a bar and not filling, only change existing state
6514 // if it doesn't make sense
6515 else if (vmin < 0) {
6516 forceMinZero = false;
6521 // check if we need make axis min at 0.
6523 // compute number of ticks
6524 this.numberTicks = 2 + Math.ceil((dim-(this.tickSpacing-1))/this.tickSpacing);
6527 // what order is this range?
6528 // what tick interval does that give us?
6529 ti = max/(this.numberTicks-1);
6530 temp = Math.pow(10, Math.abs(Math.floor(Math.log(ti)/Math.LN10)));
6531 if (ti/temp == parseInt(ti/temp, 10)) {
6534 this.tickInterval = Math.ceil(ti/temp) * temp;
6535 this.max = this.tickInterval * (this.numberTicks - 1);
6538 // check if we need to make sure there is a tick at 0.
6539 else if (forceZeroLine) {
6540 // compute number of ticks
6541 this.numberTicks = 2 + Math.ceil((dim-(this.tickSpacing-1))/this.tickSpacing);
6542 var ntmin = Math.ceil(Math.abs(min)/range*(this.numberTicks-1));
6543 var ntmax = this.numberTicks - 1 - ntmin;
6544 ti = Math.max(Math.abs(min/ntmin), Math.abs(max/ntmax));
6545 temp = Math.pow(10, Math.abs(Math.floor(Math.log(ti)/Math.LN10)));
6546 this.tickInterval = Math.ceil(ti/temp) * temp;
6547 this.max = this.tickInterval * ntmax;
6548 this.min = -this.tickInterval * ntmin;
6551 // if nothing else, do autoscaling which will try to line up ticks across axes.
6553 if (this.numberTicks == null){
6554 if (this.tickInterval) {
6555 this.numberTicks = 3 + Math.ceil(range / this.tickInterval);
6558 this.numberTicks = 2 + Math.ceil((dim-(this.tickSpacing-1))/this.tickSpacing);
6562 if (this.tickInterval == null) {
6563 // get a tick interval
6564 ti = range/(this.numberTicks - 1);
6567 temp = Math.pow(10, Math.abs(Math.floor(Math.log(ti)/Math.LN10)));
6572 this.tickInterval = Math.ceil(ti*temp*this.pad)/temp;
6575 temp = 1 / this.tickInterval;
6578 // try to compute a nicer, more even tick interval
6579 // temp = Math.pow(10, Math.floor(Math.log(ti)/Math.LN10));
6580 // this.tickInterval = Math.ceil(ti/temp) * temp;
6581 rrange = this.tickInterval * (this.numberTicks - 1);
6582 margin = (rrange - range)/2;
6584 if (this.min == null) {
6585 this.min = Math.floor(temp*(min-margin))/temp;
6587 if (this.max == null) {
6588 this.max = this.min + rrange;
6592 // Compute a somewhat decent format string if it is needed.
6593 // get precision of interval and determine a format string.
6594 var sf = $.jqplot.getSignificantFigures(this.tickInterval);
6598 // if we have only a whole number, use integer formatting
6599 if (sf.digitsLeft >= sf.significantDigits) {
6604 var temp = Math.max(0, 5 - sf.digitsLeft);
6605 temp = Math.min(temp, sf.digitsRight);
6606 fstr = '%.'+ temp + 'f';
6609 this._autoFormatString = fstr;
6612 // Use the default algorithm which pads each axis to make the chart
6613 // centered nicely on the grid.
6616 rmin = (this.min != null) ? this.min : min - range*(this.padMin - 1);
6617 rmax = (this.max != null) ? this.max : max + range*(this.padMax - 1);
6618 range = rmax - rmin;
6620 if (this.numberTicks == null){
6621 // if tickInterval is specified by user, we will ignore computed maximum.
6622 // max will be equal or greater to fit even # of ticks.
6623 if (this.tickInterval != null) {
6624 this.numberTicks = Math.ceil((rmax - rmin)/this.tickInterval)+1;
6626 else if (dim > 100) {
6627 this.numberTicks = parseInt(3+(dim-100)/75, 10);
6630 this.numberTicks = 2;
6634 if (this.tickInterval == null) {
6635 this.tickInterval = range / (this.numberTicks-1);
6638 if (this.max == null) {
6639 rmax = rmin + this.tickInterval*(this.numberTicks - 1);
6641 if (this.min == null) {
6642 rmin = rmax - this.tickInterval*(this.numberTicks - 1);
6645 // get precision of interval and determine a format string.
6646 var sf = $.jqplot.getSignificantFigures(this.tickInterval);
6650 // if we have only a whole number, use integer formatting
6651 if (sf.digitsLeft >= sf.significantDigits) {
6656 var temp = Math.max(0, 5 - sf.digitsLeft);
6657 temp = Math.min(temp, sf.digitsRight);
6658 fstr = '%.'+ temp + 'f';
6662 this._autoFormatString = fstr;
6668 if (this.renderer.constructor == $.jqplot.LinearAxisRenderer && this._autoFormatString == '') {
6669 // fix for misleading tick display with small range and low precision.
6670 range = this.max - this.min;
6671 // figure out precision
6672 var temptick = new this.tickRenderer(this.tickOptions);
6673 // use the tick formatString or, the default.
6674 var fs = temptick.formatString || $.jqplot.config.defaultTickFormatString;
6675 var fs = fs.match($.jqplot.sprintf.regex)[0];
6678 if (fs.search(/[fFeEgGpP]/) > -1) {
6679 var m = fs.match(/\%\.(\d{0,})?[eEfFgGpP]/);
6681 precision = parseInt(m[1], 10);
6687 else if (fs.search(/[di]/) > -1) {
6690 // fact will be <= 1;
6691 var fact = Math.pow(10, -precision);
6692 if (this.tickInterval < fact) {
6693 // need to correct underrange
6694 if (userNT == null && userTI == null) {
6695 this.tickInterval = fact;
6696 if (userMax == null && userMin == null) {
6697 // this.min = Math.floor((this._dataBounds.min - this.tickInterval)/fact) * fact;
6698 this.min = Math.floor(this._dataBounds.min/fact) * fact;
6699 if (this.min == this._dataBounds.min) {
6700 this.min = this._dataBounds.min - this.tickInterval;
6702 // this.max = Math.ceil((this._dataBounds.max + this.tickInterval)/fact) * fact;
6703 this.max = Math.ceil(this._dataBounds.max/fact) * fact;
6704 if (this.max == this._dataBounds.max) {
6705 this.max = this._dataBounds.max + this.tickInterval;
6707 var n = (this.max - this.min)/this.tickInterval;
6710 this.numberTicks = n + 1;
6712 else if (userMax == null) {
6713 // add one tick for top of range.
6714 var n = (this._dataBounds.max - this.min) / this.tickInterval;
6716 this.numberTicks = Math.ceil(n) + 2;
6717 this.max = this.min + this.tickInterval * (this.numberTicks-1);
6719 else if (userMin == null) {
6720 // add one tick for bottom of range.
6721 var n = (this.max - this._dataBounds.min) / this.tickInterval;
6723 this.numberTicks = Math.ceil(n) + 2;
6724 this.min = this.max - this.tickInterval * (this.numberTicks-1);
6727 // calculate a number of ticks so max is within axis scale
6728 this.numberTicks = Math.ceil((userMax - userMin)/this.tickInterval) + 1;
6729 // if user's min and max don't fit evenly in ticks, adjust.
6730 // This takes care of cases such as user min set to 0, max set to 3.5 but tick
6731 // format string set to %d (integer ticks)
6732 this.min = Math.floor(userMin*Math.pow(10, precision))/Math.pow(10, precision);
6733 this.max = Math.ceil(userMax*Math.pow(10, precision))/Math.pow(10, precision);
6734 // this.max = this.min + this.tickInterval*(this.numberTicks-1);
6735 this.numberTicks = Math.ceil((this.max - this.min)/this.tickInterval) + 1;
6744 if (this._overrideFormatString && this._autoFormatString != '') {
6745 this.tickOptions = this.tickOptions || {};
6746 this.tickOptions.formatString = this._autoFormatString;
6750 for (var i=0; i<this.numberTicks; i++){
6751 tt = this.min + i * this.tickInterval;
6752 t = new this.tickRenderer(this.tickOptions);
6753 // var t = new $.jqplot.AxisTickRenderer(this.tickOptions);
6755 t.setTick(tt, this.name);
6756 this._ticks.push(t);
6758 if (i < this.numberTicks - 1) {
6759 for (var j=0; j<this.minorTicks; j++) {
6760 tt += this.tickInterval/(this.minorTicks+1);
6761 to = $.extend(true, {}, this.tickOptions, {name:this.name, value:tt, label:'', isMinorTick:true});
6762 t = new this.tickRenderer(to);
6763 this._ticks.push(t);
6770 if (this.tickInset) {
6771 this.min = this.min - this.tickInset * this.tickInterval;
6772 this.max = this.max + this.tickInset * this.tickInterval;
6778 // Used to reset just the values of the ticks and then repack, which will
6779 // recalculate the positioning functions. It is assuemd that the
6780 // number of ticks is the same and the values of the new array are at the
6782 // This method needs to be called with the scope of an axis object, like:
6784 // > plot.axes.yaxis.renderer.resetTickValues.call(plot.axes.yaxis, yarr);
6786 $.jqplot.LinearAxisRenderer.prototype.resetTickValues = function(opts) {
6787 if ($.isArray(opts) && opts.length == this._ticks.length) {
6789 for (var i=0; i<opts.length; i++) {
6792 t.label = t.formatter(t.formatString, opts[i]);
6793 t.label = t.prefix + t.label;
6794 t._elem.html(t.label);
6797 this.min = $.jqplot.arrayMin(opts);
6798 this.max = $.jqplot.arrayMax(opts);
6801 // Not implemented yet.
6802 // else if ($.isPlainObject(opts)) {
6807 // called with scope of axis
6808 $.jqplot.LinearAxisRenderer.prototype.pack = function(pos, offsets) {
6809 // Add defaults for repacking from resetTickValues function.
6811 offsets = offsets || this._offsets;
6813 var ticks = this._ticks;
6816 var offmax = offsets.max;
6817 var offmin = offsets.min;
6818 var lshow = (this._label == null) ? false : this._label.show;
6820 for (var p in pos) {
6821 this._elem.css(p, pos[p]);
6824 this._offsets = offsets;
6825 // pixellength will be + for x axes and - for y axes becasue pixels always measured from top left.
6826 var pixellength = offmax - offmin;
6827 var unitlength = max - min;
6829 // point to unit and unit to point conversions references to Plot DOM element top left corner.
6830 if (this.breakPoints) {
6831 unitlength = unitlength - this.breakPoints[1] + this.breakPoints[0];
6833 this.p2u = function(p){
6834 return (p - offmin) * unitlength / pixellength + min;
6837 this.u2p = function(u){
6838 if (u > this.breakPoints[0] && u < this.breakPoints[1]){
6839 u = this.breakPoints[0];
6841 if (u <= this.breakPoints[0]) {
6842 return (u - min) * pixellength / unitlength + offmin;
6845 return (u - this.breakPoints[1] + this.breakPoints[0] - min) * pixellength / unitlength + offmin;
6849 if (this.name.charAt(0) == 'x'){
6850 this.series_u2p = function(u){
6851 if (u > this.breakPoints[0] && u < this.breakPoints[1]){
6852 u = this.breakPoints[0];
6854 if (u <= this.breakPoints[0]) {
6855 return (u - min) * pixellength / unitlength;
6858 return (u - this.breakPoints[1] + this.breakPoints[0] - min) * pixellength / unitlength;
6861 this.series_p2u = function(p){
6862 return p * unitlength / pixellength + min;
6867 this.series_u2p = function(u){
6868 if (u > this.breakPoints[0] && u < this.breakPoints[1]){
6869 u = this.breakPoints[0];
6871 if (u >= this.breakPoints[1]) {
6872 return (u - max) * pixellength / unitlength;
6875 return (u + this.breakPoints[1] - this.breakPoints[0] - max) * pixellength / unitlength;
6878 this.series_p2u = function(p){
6879 return p * unitlength / pixellength + max;
6884 this.p2u = function(p){
6885 return (p - offmin) * unitlength / pixellength + min;
6888 this.u2p = function(u){
6889 return (u - min) * pixellength / unitlength + offmin;
6892 if (this.name == 'xaxis' || this.name == 'x2axis'){
6893 this.series_u2p = function(u){
6894 return (u - min) * pixellength / unitlength;
6896 this.series_p2u = function(p){
6897 return p * unitlength / pixellength + min;
6902 this.series_u2p = function(u){
6903 return (u - max) * pixellength / unitlength;
6905 this.series_p2u = function(p){
6906 return p * unitlength / pixellength + max;
6912 if (this.name == 'xaxis' || this.name == 'x2axis') {
6913 for (var i=0; i<ticks.length; i++) {
6915 if (t.show && t.showLabel) {
6918 if (t.constructor == $.jqplot.CanvasAxisTickRenderer && t.angle) {
6919 // will need to adjust auto positioning based on which axis this is.
6920 var temp = (this.name == 'xaxis') ? 1 : -1;
6921 switch (t.labelPosition) {
6924 if (temp * t.angle < 0) {
6925 shim = -t.getWidth() + t._textRenderer.height * Math.sin(-t._textRenderer.angle) / 2;
6927 // position at start
6929 shim = -t._textRenderer.height * Math.sin(t._textRenderer.angle) / 2;
6933 shim = -t.getWidth() + t._textRenderer.height * Math.sin(-t._textRenderer.angle) / 2;
6936 shim = -t._textRenderer.height * Math.sin(t._textRenderer.angle) / 2;
6939 shim = -t.getWidth()/2 + t._textRenderer.height * Math.sin(-t._textRenderer.angle) / 2;
6942 shim = -t.getWidth()/2 + t._textRenderer.height * Math.sin(-t._textRenderer.angle) / 2;
6947 shim = -t.getWidth()/2;
6949 var val = this.u2p(t.value) + shim + 'px';
6950 t._elem.css('left', val);
6955 var w = this._label._elem.outerWidth(true);
6956 this._label._elem.css('left', offmin + pixellength/2 - w/2 + 'px');
6957 if (this.name == 'xaxis') {
6958 this._label._elem.css('bottom', '0px');
6961 this._label._elem.css('top', '0px');
6967 for (var i=0; i<ticks.length; i++) {
6969 if (t.show && t.showLabel) {
6971 if (t.constructor == $.jqplot.CanvasAxisTickRenderer && t.angle) {
6972 // will need to adjust auto positioning based on which axis this is.
6973 var temp = (this.name == 'yaxis') ? 1 : -1;
6974 switch (t.labelPosition) {
6978 if (temp * t.angle < 0) {
6979 shim = -t._textRenderer.height * Math.cos(-t._textRenderer.angle) / 2;
6982 shim = -t.getHeight() + t._textRenderer.height * Math.cos(t._textRenderer.angle) / 2;
6987 shim = -t._textRenderer.height * Math.cos(-t._textRenderer.angle) / 2;
6990 shim = -t.getHeight() + t._textRenderer.height * Math.cos(t._textRenderer.angle) / 2;
6994 // if (t.angle > 0) {
6995 // shim = -t.getHeight()/2 + t._textRenderer.height * Math.sin(-t._textRenderer.angle) / 2;
6998 // shim = -t.getHeight()/2 - t._textRenderer.height * Math.sin(t._textRenderer.angle) / 2;
7000 shim = -t.getHeight()/2;
7003 shim = -t.getHeight()/2;
7008 shim = -t.getHeight()/2;
7011 var val = this.u2p(t.value) + shim + 'px';
7012 t._elem.css('top', val);
7017 var h = this._label._elem.outerHeight(true);
7018 this._label._elem.css('top', offmax - pixellength/2 - h/2 + 'px');
7019 if (this.name == 'yaxis') {
7020 this._label._elem.css('left', '0px');
7023 this._label._elem.css('right', '0px');
7035 * The following code was generaously given to me a while back by Scott Prahl.
7036 * He did a good job at computing axes min, max and number of ticks for the
7037 * case where the user has not set any scale related parameters (tickInterval,
7038 * numberTicks, min or max). I had ignored this use case for a long time,
7039 * focusing on the more difficult case where user has set some option controlling
7040 * tick generation. Anyway, about time I got this into jqPlot.
7045 * Copyright (c) 2010 Scott Prahl
7046 * The next three routines are currently available for use in all personal
7047 * or commercial projects under both the MIT and GPL version 2.0 licenses.
7048 * This means that you can choose the license that best suits your project
7049 * and use it accordingly.
7052 // A good format string depends on the interval. If the interval is greater
7053 // than 1 then there is no need to show any decimal digits. If it is < 1.0, then
7054 // use the magnitude of the interval to determine the number of digits to show.
7055 function bestFormatString (interval)
7058 interval = Math.abs(interval);
7059 if (interval >= 10) {
7063 else if (interval > 1) {
7064 if (interval === parseInt(interval, 10)) {
7073 var expv = -Math.floor(Math.log(interval)/Math.LN10);
7074 fstr = '%.' + expv + 'f';
7080 var _factors = [0.1, 0.2, 0.3, 0.4, 0.5, 0.8, 1, 2, 3, 4, 5];
7082 var _getLowerFactor = function(f) {
7083 var i = _factors.indexOf(f);
7085 return _factors[i-1];
7088 return _factors[_factors.length - 1] / 100;
7092 var _getHigherFactor = function(f) {
7093 var i = _factors.indexOf(f);
7094 if (i < _factors.length-1) {
7095 return _factors[i+1];
7098 return _factors[0] * 100;
7102 // Given a fixed minimum and maximum and a target number ot ticks
7103 // figure out the best interval and
7104 // return min, max, number ticks, format string and tick interval
7105 function bestConstrainedInterval(min, max, nttarget) {
7106 // run through possible number to ticks and see which interval is best
7107 var low = Math.floor(nttarget/2);
7108 var hi = Math.ceil(nttarget*1.5);
7109 var badness = Number.MAX_VALUE;
7110 var r = (max - min);
7114 var gsf = $.jqplot.getSignificantFigures;
7120 for (var i=0, l=hi-low+1; i<l; i++) {
7121 currentNT = low + i;
7122 temp = r/(currentNT-1);
7125 temp = Math.abs(nttarget - currentNT) + sd.digitsRight;
7126 if (temp < badness) {
7129 bestPrec = sd.digitsRight;
7131 else if (temp === badness) {
7132 // let nicer ticks trump number ot ticks
7133 if (sd.digitsRight < bestPrec) {
7135 bestPrec = sd.digitsRight;
7141 fsd = Math.max(bestPrec, Math.max(gsf(min).digitsRight, gsf(max).digitsRight));
7146 fs = '%.' + fsd + 'f';
7148 temp = r / (bestNT - 1);
7149 // min, max, number ticks, format string, tick interval
7150 return [min, max, bestNT, fs, temp];
7153 // This will return an interval of form 2 * 10^n, 5 * 10^n or 10 * 10^n
7154 // it is based soley on the range and number of ticks. So if user specifies
7155 // number of ticks, use this.
7156 function bestInterval(range, numberTicks) {
7157 numberTicks = numberTicks || 7;
7158 var minimum = range / (numberTicks - 1);
7159 var magnitude = Math.pow(10, Math.floor(Math.log(minimum) / Math.LN10));
7160 var residual = minimum / magnitude;
7162 // "nicest" ranges are 1, 2, 5 or powers of these.
7163 // for magnitudes below 1, only allow these.
7164 if (magnitude < 1) {
7166 interval = 10 * magnitude;
7168 else if (residual > 2) {
7169 interval = 5 * magnitude;
7171 else if (residual > 1) {
7172 interval = 2 * magnitude;
7175 interval = magnitude;
7178 // for large ranges (whole integers), allow intervals like 3, 4 or powers of these.
7179 // this helps a lot with poor choices for number of ticks.
7182 interval = 10 * magnitude;
7184 else if (residual > 4) {
7185 interval = 5 * magnitude;
7187 else if (residual > 3) {
7188 interval = 4 * magnitude;
7190 else if (residual > 2) {
7191 interval = 3 * magnitude;
7193 else if (residual > 1) {
7194 interval = 2 * magnitude;
7197 interval = magnitude;
7204 // This will return an interval of form 2 * 10^n, 5 * 10^n or 10 * 10^n
7205 // it is based soley on the range of data, number of ticks must be computed later.
7206 function bestLinearInterval(range, scalefact) {
7207 scalefact = scalefact || 1;
7208 var expv = Math.floor(Math.log(range)/Math.LN10);
7209 var magnitude = Math.pow(10, expv);
7211 var f = range / magnitude;
7213 // for large plots, scalefact will decrease f and increase number of ticks.
7214 // for small plots, scalefact will increase f and decrease number of ticks.
7217 // for large plots, smaller interval, more ticks.
7230 // for very small plots, larger interval, less ticks in number ticks
7238 return fact*magnitude;
7241 function bestLinearComponents(range, scalefact) {
7242 var expv = Math.floor(Math.log(range)/Math.LN10);
7243 var magnitude = Math.pow(10, expv);
7245 var f = range / magnitude;
7248 // for large plots, scalefact will decrease f and increase number of ticks.
7249 // for small plots, scalefact will increase f and decrease number of ticks.
7252 // for large plots, smaller interval, more ticks.
7265 // for very small plots, larger interval, less ticks in number ticks
7269 // else if (f<=20.0) {
7272 // else if (f<=24.0) {
7279 interval = fact * magnitude;
7281 return [interval, fact, magnitude];
7284 // Given the min and max for a dataset, return suitable endpoints
7285 // for the graphing, a good number for the number of ticks, and a
7286 // format string so that extraneous digits are not displayed.
7287 // returned is an array containing [min, max, nTicks, format]
7288 $.jqplot.LinearTickGenerator = function(axis_min, axis_max, scalefact, numberTicks, keepMin, keepMax) {
7289 // Set to preserve EITHER min OR max.
7290 // If min is preserved, max must be free.
7291 keepMin = (keepMin === null) ? false : keepMin;
7292 keepMax = (keepMax === null || keepMin) ? false : keepMax;
7293 // if endpoints are equal try to include zero otherwise include one
7294 if (axis_min === axis_max) {
7295 axis_max = (axis_max) ? 0 : 1;
7298 scalefact = scalefact || 1.0;
7300 // make sure range is positive
7301 if (axis_max < axis_min) {
7303 axis_max = axis_min;
7308 var ss = bestLinearInterval(axis_max - axis_min, scalefact);
7310 var gsf = $.jqplot.getSignificantFigures;
7312 if (numberTicks == null) {
7314 // Figure out the axis min, max and number of ticks
7315 // the min and max will be some multiple of the tick interval,
7316 // 1*10^n, 2*10^n or 5*10^n. This gaurantees that, if the
7317 // axis min is negative, 0 will be a tick.
7318 if (!keepMin && !keepMax) {
7319 r[0] = Math.floor(axis_min / ss) * ss; // min
7320 r[1] = Math.ceil(axis_max / ss) * ss; // max
7321 r[2] = Math.round((r[1]-r[0])/ss+1.0); // number of ticks
7322 r[3] = bestFormatString(ss); // format string
7323 r[4] = ss; // tick Interval
7327 r[0] = axis_min; // min
7328 r[2] = Math.ceil((axis_max - axis_min) / ss + 1.0); // number of ticks
7329 r[1] = axis_min + (r[2] - 1) * ss; // max
7330 var digitsMin = gsf(axis_min).digitsRight;
7331 var digitsSS = gsf(ss).digitsRight;
7332 if (digitsMin < digitsSS) {
7333 r[3] = bestFormatString(ss); // format string
7336 r[3] = '%.' + digitsMin + 'f';
7338 r[4] = ss; // tick Interval
7342 r[1] = axis_max; // max
7343 r[2] = Math.ceil((axis_max - axis_min) / ss + 1.0); // number of ticks
7344 r[0] = axis_max - (r[2] - 1) * ss; // min
7345 var digitsMax = gsf(axis_max).digitsRight;
7346 var digitsSS = gsf(ss).digitsRight;
7347 if (digitsMax < digitsSS) {
7348 r[3] = bestFormatString(ss); // format string
7351 r[3] = '%.' + digitsMax + 'f';
7353 r[4] = ss; // tick Interval
7360 // Figure out the axis min, max and number of ticks
7361 // the min and max will be some multiple of the tick interval,
7362 // 1*10^n, 2*10^n or 5*10^n. This gaurantees that, if the
7363 // axis min is negative, 0 will be a tick.
7364 tempr[0] = Math.floor(axis_min / ss) * ss; // min
7365 tempr[1] = Math.ceil(axis_max / ss) * ss; // max
7366 tempr[2] = Math.round((tempr[1]-tempr[0])/ss+1.0); // number of ticks
7367 tempr[3] = bestFormatString(ss); // format string
7368 tempr[4] = ss; // tick Interval
7370 // first, see if we happen to get the right number of ticks
7371 if (tempr[2] === numberTicks) {
7377 var newti = bestInterval(tempr[1] - tempr[0], numberTicks);
7379 r[0] = tempr[0]; // min
7380 r[2] = numberTicks; // number of ticks
7381 r[4] = newti; // tick interval
7382 r[3] = bestFormatString(newti); // format string
7383 r[1] = r[0] + (r[2] - 1) * r[4]; // max
7390 $.jqplot.LinearTickGenerator.bestLinearInterval = bestLinearInterval;
7391 $.jqplot.LinearTickGenerator.bestInterval = bestInterval;
7392 $.jqplot.LinearTickGenerator.bestLinearComponents = bestLinearComponents;
7393 $.jqplot.LinearTickGenerator.bestConstrainedInterval = bestConstrainedInterval;
7396 // class: $.jqplot.MarkerRenderer
7397 // The default jqPlot marker renderer, rendering the points on the line.
7398 $.jqplot.MarkerRenderer = function(options){
7399 // Group: Properties
7402 // wether or not to show the marker.
7405 // One of diamond, circle, square, x, plus, dash, filledDiamond, filledCircle, filledSquare
7406 this.style = 'filledCircle';
7408 // size of the line for non-filled markers.
7411 // Size of the marker (diameter or circle, length of edge of square, etc.)
7414 // color of marker. Will be set to color of series by default on init.
7415 this.color = '#666666';
7417 // wether or not to draw a shadow on the line
7419 // prop: shadowAngle
7420 // Shadow angle in degrees
7421 this.shadowAngle = 45;
7422 // prop: shadowOffset
7423 // Shadow offset from line in pixels
7424 this.shadowOffset = 1;
7425 // prop: shadowDepth
7426 // Number of times shadow is stroked, each stroke offset shadowOffset from the last.
7427 this.shadowDepth = 3;
7428 // prop: shadowAlpha
7429 // Alpha channel transparency of shadow. 0 = transparent.
7430 this.shadowAlpha = '0.07';
7431 // prop: shadowRenderer
7432 // Renderer that will draws the shadows on the marker.
7433 this.shadowRenderer = new $.jqplot.ShadowRenderer();
7434 // prop: shapeRenderer
7435 // Renderer that will draw the marker.
7436 this.shapeRenderer = new $.jqplot.ShapeRenderer();
7438 $.extend(true, this, options);
7441 $.jqplot.MarkerRenderer.prototype.init = function(options) {
7442 $.extend(true, this, options);
7443 var sdopt = {angle:this.shadowAngle, offset:this.shadowOffset, alpha:this.shadowAlpha, lineWidth:this.lineWidth, depth:this.shadowDepth, closePath:true};
7444 if (this.style.indexOf('filled') != -1) {
7447 if (this.style.indexOf('ircle') != -1) {
7449 sdopt.closePath = false;
7451 this.shadowRenderer.init(sdopt);
7453 var shopt = {fill:false, isarc:false, strokeStyle:this.color, fillStyle:this.color, lineWidth:this.lineWidth, closePath:true};
7454 if (this.style.indexOf('filled') != -1) {
7457 if (this.style.indexOf('ircle') != -1) {
7459 shopt.closePath = false;
7461 this.shapeRenderer.init(shopt);
7464 $.jqplot.MarkerRenderer.prototype.drawDiamond = function(x, y, ctx, fill, options) {
7466 var dx = this.size/2/stretch;
7467 var dy = this.size/2*stretch;
7468 var points = [[x-dx, y], [x, y+dy], [x+dx, y], [x, y-dy]];
7470 this.shadowRenderer.draw(ctx, points);
7472 this.shapeRenderer.draw(ctx, points, options);
7475 $.jqplot.MarkerRenderer.prototype.drawPlus = function(x, y, ctx, fill, options) {
7477 var dx = this.size/2*stretch;
7478 var dy = this.size/2*stretch;
7479 var points1 = [[x, y-dy], [x, y+dy]];
7480 var points2 = [[x+dx, y], [x-dx, y]];
7481 var opts = $.extend(true, {}, this.options, {closePath:false});
7483 this.shadowRenderer.draw(ctx, points1, {closePath:false});
7484 this.shadowRenderer.draw(ctx, points2, {closePath:false});
7486 this.shapeRenderer.draw(ctx, points1, opts);
7487 this.shapeRenderer.draw(ctx, points2, opts);
7490 $.jqplot.MarkerRenderer.prototype.drawX = function(x, y, ctx, fill, options) {
7492 var dx = this.size/2*stretch;
7493 var dy = this.size/2*stretch;
7494 var opts = $.extend(true, {}, this.options, {closePath:false});
7495 var points1 = [[x-dx, y-dy], [x+dx, y+dy]];
7496 var points2 = [[x-dx, y+dy], [x+dx, y-dy]];
7498 this.shadowRenderer.draw(ctx, points1, {closePath:false});
7499 this.shadowRenderer.draw(ctx, points2, {closePath:false});
7501 this.shapeRenderer.draw(ctx, points1, opts);
7502 this.shapeRenderer.draw(ctx, points2, opts);
7505 $.jqplot.MarkerRenderer.prototype.drawDash = function(x, y, ctx, fill, options) {
7507 var dx = this.size/2*stretch;
7508 var dy = this.size/2*stretch;
7509 var points = [[x-dx, y], [x+dx, y]];
7511 this.shadowRenderer.draw(ctx, points);
7513 this.shapeRenderer.draw(ctx, points, options);
7516 $.jqplot.MarkerRenderer.prototype.drawLine = function(p1, p2, ctx, fill, options) {
7517 var points = [p1, p2];
7519 this.shadowRenderer.draw(ctx, points);
7521 this.shapeRenderer.draw(ctx, points, options);
7524 $.jqplot.MarkerRenderer.prototype.drawSquare = function(x, y, ctx, fill, options) {
7526 var dx = this.size/2/stretch;
7527 var dy = this.size/2*stretch;
7528 var points = [[x-dx, y-dy], [x-dx, y+dy], [x+dx, y+dy], [x+dx, y-dy]];
7530 this.shadowRenderer.draw(ctx, points);
7532 this.shapeRenderer.draw(ctx, points, options);
7535 $.jqplot.MarkerRenderer.prototype.drawCircle = function(x, y, ctx, fill, options) {
7536 var radius = this.size/2;
7537 var end = 2*Math.PI;
7538 var points = [x, y, radius, 0, end, true];
7540 this.shadowRenderer.draw(ctx, points);
7542 this.shapeRenderer.draw(ctx, points, options);
7545 $.jqplot.MarkerRenderer.prototype.draw = function(x, y, ctx, options) {
7546 options = options || {};
7547 // hack here b/c shape renderer uses canvas based color style options
7548 // and marker uses css style names.
7549 if (options.show == null || options.show != false) {
7550 if (options.color && !options.fillStyle) {
7551 options.fillStyle = options.color;
7553 if (options.color && !options.strokeStyle) {
7554 options.strokeStyle = options.color;
7556 switch (this.style) {
7558 this.drawDiamond(x,y,ctx, false, options);
7560 case 'filledDiamond':
7561 this.drawDiamond(x,y,ctx, true, options);
7564 this.drawCircle(x,y,ctx, false, options);
7566 case 'filledCircle':
7567 this.drawCircle(x,y,ctx, true, options);
7570 this.drawSquare(x,y,ctx, false, options);
7572 case 'filledSquare':
7573 this.drawSquare(x,y,ctx, true, options);
7576 this.drawX(x,y,ctx, true, options);
7579 this.drawPlus(x,y,ctx, true, options);
7582 this.drawDash(x,y,ctx, true, options);
7585 this.drawLine(x, y, ctx, false, options);
7588 this.drawDiamond(x,y,ctx, false, options);
7594 // class: $.jqplot.shadowRenderer
7595 // The default jqPlot shadow renderer, rendering shadows behind shapes.
7596 $.jqplot.ShadowRenderer = function(options){
7597 // Group: Properties
7600 // Angle of the shadow in degrees. Measured counter-clockwise from the x axis.
7603 // Pixel offset at the given shadow angle of each shadow stroke from the last stroke.
7606 // alpha transparency of shadow stroke.
7609 // width of the shadow line stroke.
7610 this.lineWidth = 1.5;
7612 // How line segments of the shadow are joined.
7613 this.lineJoin = 'miter';
7615 // how ends of the shadow line are rendered.
7616 this.lineCap = 'round';
7618 // whether line path segment is closed upon itself.
7619 this.closePath = false;
7621 // whether to fill the shape.
7624 // how many times the shadow is stroked. Each stroke will be offset by offset at angle degrees.
7626 this.strokeStyle = 'rgba(0,0,0,0.1)';
7628 // wether the shadow is an arc or not.
7631 $.extend(true, this, options);
7634 $.jqplot.ShadowRenderer.prototype.init = function(options) {
7635 $.extend(true, this, options);
7639 // draws an transparent black (i.e. gray) shadow.
7641 // ctx - canvas drawing context
7642 // points - array of points or [x, y, radius, start angle (rad), end angle (rad)]
7643 $.jqplot.ShadowRenderer.prototype.draw = function(ctx, points, options) {
7645 var opts = (options != null) ? options : {};
7646 var fill = (opts.fill != null) ? opts.fill : this.fill;
7647 var fillRect = (opts.fillRect != null) ? opts.fillRect : this.fillRect;
7648 var closePath = (opts.closePath != null) ? opts.closePath : this.closePath;
7649 var offset = (opts.offset != null) ? opts.offset : this.offset;
7650 var alpha = (opts.alpha != null) ? opts.alpha : this.alpha;
7651 var depth = (opts.depth != null) ? opts.depth : this.depth;
7652 var isarc = (opts.isarc != null) ? opts.isarc : this.isarc;
7653 var linePattern = (opts.linePattern != null) ? opts.linePattern : this.linePattern;
7654 ctx.lineWidth = (opts.lineWidth != null) ? opts.lineWidth : this.lineWidth;
7655 ctx.lineJoin = (opts.lineJoin != null) ? opts.lineJoin : this.lineJoin;
7656 ctx.lineCap = (opts.lineCap != null) ? opts.lineCap : this.lineCap;
7657 ctx.strokeStyle = opts.strokeStyle || this.strokeStyle || 'rgba(0,0,0,'+alpha+')';
7658 ctx.fillStyle = opts.fillStyle || this.fillStyle || 'rgba(0,0,0,'+alpha+')';
7659 for (var j=0; j<depth; j++) {
7660 var ctxPattern = $.jqplot.LinePattern(ctx, linePattern);
7661 ctx.translate(Math.cos(this.angle*Math.PI/180)*offset, Math.sin(this.angle*Math.PI/180)*offset);
7662 ctxPattern.beginPath();
7664 ctx.arc(points[0], points[1], points[2], points[3], points[4], true);
7666 else if (fillRect) {
7668 ctx.fillRect(points[0], points[1], points[2], points[3]);
7671 else if (points && points.length){
7673 for (var i=0; i<points.length; i++) {
7674 // skip to the first non-null point and move to it.
7675 if (points[i][0] != null && points[i][1] != null) {
7677 ctxPattern.moveTo(points[i][0], points[i][1]);
7681 ctxPattern.lineTo(points[i][0], points[i][1]);
7691 ctxPattern.closePath();
7703 // class: $.jqplot.shapeRenderer
7704 // The default jqPlot shape renderer. Given a set of points will
7705 // plot them and either stroke a line (fill = false) or fill them (fill = true).
7706 // If a filled shape is desired, closePath = true must also be set to close
7708 $.jqplot.ShapeRenderer = function(options){
7710 this.lineWidth = 1.5;
7711 // prop: linePattern
7712 // line pattern 'dashed', 'dotted', 'solid', some combination
7713 // of '-' and '.' characters such as '.-.' or a numerical array like
7714 // [draw, skip, draw, skip, ...] such as [1, 10] to draw a dotted line,
7715 // [1, 10, 20, 10] to draw a dot-dash line, and so on.
7716 this.linePattern = 'solid';
7718 // How line segments of the shadow are joined.
7719 this.lineJoin = 'miter';
7721 // how ends of the shadow line are rendered.
7722 this.lineCap = 'round';
7724 // whether line path segment is closed upon itself.
7725 this.closePath = false;
7727 // whether to fill the shape.
7730 // wether the shadow is an arc or not.
7733 // true to draw shape as a filled rectangle.
7734 this.fillRect = false;
7736 // true to draw shape as a stroked rectangle.
7737 this.strokeRect = false;
7739 // true to cear a rectangle.
7740 this.clearRect = false;
7741 // prop: strokeStyle
7742 // css color spec for the stoke style
7743 this.strokeStyle = '#999999';
7745 // css color spec for the fill style.
7746 this.fillStyle = '#999999';
7748 $.extend(true, this, options);
7751 $.jqplot.ShapeRenderer.prototype.init = function(options) {
7752 $.extend(true, this, options);
7758 // ctx - canvas drawing context
7759 // points - array of points for shapes or
7760 // [x, y, width, height] for rectangles or
7761 // [x, y, radius, start angle (rad), end angle (rad)] for circles and arcs.
7762 $.jqplot.ShapeRenderer.prototype.draw = function(ctx, points, options) {
7764 var opts = (options != null) ? options : {};
7765 var fill = (opts.fill != null) ? opts.fill : this.fill;
7766 var closePath = (opts.closePath != null) ? opts.closePath : this.closePath;
7767 var fillRect = (opts.fillRect != null) ? opts.fillRect : this.fillRect;
7768 var strokeRect = (opts.strokeRect != null) ? opts.strokeRect : this.strokeRect;
7769 var clearRect = (opts.clearRect != null) ? opts.clearRect : this.clearRect;
7770 var isarc = (opts.isarc != null) ? opts.isarc : this.isarc;
7771 var linePattern = (opts.linePattern != null) ? opts.linePattern : this.linePattern;
7772 var ctxPattern = $.jqplot.LinePattern(ctx, linePattern);
7773 ctx.lineWidth = opts.lineWidth || this.lineWidth;
7774 ctx.lineJoin = opts.lineJoin || this.lineJoin;
7775 ctx.lineCap = opts.lineCap || this.lineCap;
7776 ctx.strokeStyle = (opts.strokeStyle || opts.color) || this.strokeStyle;
7777 ctx.fillStyle = opts.fillStyle || this.fillStyle;
7780 ctx.arc(points[0], points[1], points[2], points[3], points[4], true);
7793 else if (clearRect) {
7794 ctx.clearRect(points[0], points[1], points[2], points[3]);
7798 else if (fillRect || strokeRect) {
7800 ctx.fillRect(points[0], points[1], points[2], points[3]);
7803 ctx.strokeRect(points[0], points[1], points[2], points[3]);
7808 else if (points && points.length){
7810 for (var i=0; i<points.length; i++) {
7811 // skip to the first non-null point and move to it.
7812 if (points[i][0] != null && points[i][1] != null) {
7814 ctxPattern.moveTo(points[i][0], points[i][1]);
7818 ctxPattern.lineTo(points[i][0], points[i][1]);
7826 ctxPattern.closePath();
7838 // class $.jqplot.TableLegendRenderer
7839 // The default legend renderer for jqPlot.
7840 $.jqplot.TableLegendRenderer = function(){
7844 $.jqplot.TableLegendRenderer.prototype.init = function(options) {
7845 $.extend(true, this, options);
7848 $.jqplot.TableLegendRenderer.prototype.addrow = function (label, color, pad, reverse) {
7849 var rs = (pad) ? this.rowSpacing+'px' : '0px';
7855 elem = document.createElement('tr');
7857 tr.addClass('jqplot-table-legend');
7861 tr.prependTo(this._elem);
7865 tr.appendTo(this._elem);
7868 if (this.showSwatches) {
7869 td = $(document.createElement('td'));
7870 td.addClass('jqplot-table-legend jqplot-table-legend-swatch');
7871 td.css({textAlign: 'center', paddingTop: rs});
7873 div0 = $(document.createElement('div'));
7874 div0.addClass('jqplot-table-legend-swatch-outline');
7875 div1 = $(document.createElement('div'));
7876 div1.addClass('jqplot-table-legend-swatch');
7877 div1.css({backgroundColor: color, borderColor: color});
7879 tr.append(td.append(div0.append(div1)));
7881 // $('<td class="jqplot-table-legend" style="text-align:center;padding-top:'+rs+';">'+
7882 // '<div><div class="jqplot-table-legend-swatch" style="background-color:'+color+';border-color:'+color+';"></div>'+
7883 // '</div></td>').appendTo(tr);
7885 if (this.showLabels) {
7886 td = $(document.createElement('td'));
7887 td.addClass('jqplot-table-legend jqplot-table-legend-label');
7888 td.css('paddingTop', rs);
7891 // elem = $('<td class="jqplot-table-legend" style="padding-top:'+rs+';"></td>');
7892 // elem.appendTo(tr);
7893 if (this.escapeHtml) {
7907 // called with scope of legend
7908 $.jqplot.TableLegendRenderer.prototype.draw = function() {
7910 this._elem.emptyForce();
7915 var series = this._series;
7916 // make a table. one line label per row.
7917 var elem = document.createElement('table');
7918 this._elem = $(elem);
7919 this._elem.addClass('jqplot-table-legend');
7921 var ss = {position:'absolute'};
7922 if (this.background) {
7923 ss['background'] = this.background;
7926 ss['border'] = this.border;
7928 if (this.fontSize) {
7929 ss['fontSize'] = this.fontSize;
7931 if (this.fontFamily) {
7932 ss['fontFamily'] = this.fontFamily;
7934 if (this.textColor) {
7935 ss['textColor'] = this.textColor;
7937 if (this.marginTop != null) {
7938 ss['marginTop'] = this.marginTop;
7940 if (this.marginBottom != null) {
7941 ss['marginBottom'] = this.marginBottom;
7943 if (this.marginLeft != null) {
7944 ss['marginLeft'] = this.marginLeft;
7946 if (this.marginRight != null) {
7947 ss['marginRight'] = this.marginRight;
7954 for (var i = 0; i< series.length; i++) {
7956 if (s._stack || s.renderer.constructor == $.jqplot.BezierCurveRenderer){
7959 if (s.show && s.showLabel) {
7960 var lt = this.labels[i] || s.label.toString();
7962 var color = s.color;
7963 if (reverse && i < series.length - 1){
7966 else if (reverse && i == series.length - 1){
7969 this.renderer.addrow.call(this, lt, color, pad, reverse);
7972 // let plugins add more rows to legend. Used by trend line plugin.
7973 for (var j=0; j<$.jqplot.addLegendRowHooks.length; j++) {
7974 var item = $.jqplot.addLegendRowHooks[j].call(this, s);
7976 this.renderer.addrow.call(this, item.label, item.color, pad);
7987 $.jqplot.TableLegendRenderer.prototype.pack = function(offsets) {
7989 if (this.placement == 'insideGrid') {
7990 switch (this.location) {
7992 var a = offsets.left;
7993 var b = offsets.top;
7994 this._elem.css('left', a);
7995 this._elem.css('top', b);
7998 var a = (offsets.left + (this._plotDimensions.width - offsets.right))/2 - this.getWidth()/2;
7999 var b = offsets.top;
8000 this._elem.css('left', a);
8001 this._elem.css('top', b);
8004 var a = offsets.right;
8005 var b = offsets.top;
8006 this._elem.css({right:a, top:b});
8009 var a = offsets.right;
8010 var b = (offsets.top + (this._plotDimensions.height - offsets.bottom))/2 - this.getHeight()/2;
8011 this._elem.css({right:a, top:b});
8014 var a = offsets.right;
8015 var b = offsets.bottom;
8016 this._elem.css({right:a, bottom:b});
8019 var a = (offsets.left + (this._plotDimensions.width - offsets.right))/2 - this.getWidth()/2;
8020 var b = offsets.bottom;
8021 this._elem.css({left:a, bottom:b});
8024 var a = offsets.left;
8025 var b = offsets.bottom;
8026 this._elem.css({left:a, bottom:b});
8029 var a = offsets.left;
8030 var b = (offsets.top + (this._plotDimensions.height - offsets.bottom))/2 - this.getHeight()/2;
8031 this._elem.css({left:a, top:b});
8033 default: // same as 'se'
8034 var a = offsets.right;
8035 var b = offsets.bottom;
8036 this._elem.css({right:a, bottom:b});
8041 else if (this.placement == 'outside'){
8042 switch (this.location) {
8044 var a = this._plotDimensions.width - offsets.left;
8045 var b = offsets.top;
8046 this._elem.css('right', a);
8047 this._elem.css('top', b);
8050 var a = (offsets.left + (this._plotDimensions.width - offsets.right))/2 - this.getWidth()/2;
8051 var b = this._plotDimensions.height - offsets.top;
8052 this._elem.css('left', a);
8053 this._elem.css('bottom', b);
8056 var a = this._plotDimensions.width - offsets.right;
8057 var b = offsets.top;
8058 this._elem.css({left:a, top:b});
8061 var a = this._plotDimensions.width - offsets.right;
8062 var b = (offsets.top + (this._plotDimensions.height - offsets.bottom))/2 - this.getHeight()/2;
8063 this._elem.css({left:a, top:b});
8066 var a = this._plotDimensions.width - offsets.right;
8067 var b = offsets.bottom;
8068 this._elem.css({left:a, bottom:b});
8071 var a = (offsets.left + (this._plotDimensions.width - offsets.right))/2 - this.getWidth()/2;
8072 var b = this._plotDimensions.height - offsets.bottom;
8073 this._elem.css({left:a, top:b});
8076 var a = this._plotDimensions.width - offsets.left;
8077 var b = offsets.bottom;
8078 this._elem.css({right:a, bottom:b});
8081 var a = this._plotDimensions.width - offsets.left;
8082 var b = (offsets.top + (this._plotDimensions.height - offsets.bottom))/2 - this.getHeight()/2;
8083 this._elem.css({right:a, top:b});
8085 default: // same as 'se'
8086 var a = offsets.right;
8087 var b = offsets.bottom;
8088 this._elem.css({right:a, bottom:b});
8093 switch (this.location) {
8095 this._elem.css({left:0, top:offsets.top});
8098 var a = (offsets.left + (this._plotDimensions.width - offsets.right))/2 - this.getWidth()/2;
8099 this._elem.css({left: a, top:offsets.top});
8102 this._elem.css({right:0, top:offsets.top});
8105 var b = (offsets.top + (this._plotDimensions.height - offsets.bottom))/2 - this.getHeight()/2;
8106 this._elem.css({right:offsets.right, top:b});
8109 this._elem.css({right:offsets.right, bottom:offsets.bottom});
8112 var a = (offsets.left + (this._plotDimensions.width - offsets.right))/2 - this.getWidth()/2;
8113 this._elem.css({left: a, bottom:offsets.bottom});
8116 this._elem.css({left:offsets.left, bottom:offsets.bottom});
8119 var b = (offsets.top + (this._plotDimensions.height - offsets.bottom))/2 - this.getHeight()/2;
8120 this._elem.css({left:offsets.left, top:b});
8122 default: // same as 'se'
8123 this._elem.css({right:offsets.right, bottom:offsets.bottom});
8131 * Class: $.jqplot.ThemeEngine
8132 * Theme Engine provides a programatic way to change some of the more
8133 * common jqplot styling options such as fonts, colors and grid options.
8134 * A theme engine instance is created with each plot. The theme engine
8135 * manages a collection of themes which can be modified, added to, or
8136 * applied to the plot.
8138 * The themeEngine class is not instantiated directly.
8139 * When a plot is initialized, the current plot options are scanned
8140 * an a default theme named "Default" is created. This theme is
8141 * used as the basis for other themes added to the theme engine and
8142 * is always available.
8144 * A theme is a simple javascript object with styling parameters for
8145 * various entities of the plot. A theme has the form:
8149 * > _name:f "Default",
8151 * > backgroundColor: "transparent"
8154 * > textColor: null,
8155 * > fontFamily: null,
8158 * > background: null
8161 * > textColor: "rgb(102, 102, 102)",
8162 * > fontFamily: "'Trebuchet MS',Arial,Helvetica,sans-serif",
8163 * > fontSize: "19.2px",
8164 * > textAlign: "center"
8166 * > seriesStyles: {},
8168 * > color: "#4bb2c5",
8170 * > linePattern: "solid",
8172 * > fillColor: "#4bb2c5",
8173 * > showMarker: true,
8174 * > markerOptions: {
8175 * > color: "#4bb2c5",
8177 * > style: 'filledCircle',
8184 * > drawGridlines: true,
8185 * > gridLineColor: "#cccccc",
8186 * > gridLineWidth: 1,
8187 * > backgroundColor: "#fffdf6",
8188 * > borderColor: "#999999",
8198 * > borderColor: "#999999",
8202 * > showGridline: true,
8203 * > showLabel: true,
8207 * > whiteSpace: "nowrap",
8208 * > fontSize: "12px",
8209 * > fontFamily: "'Trebuchet MS',Arial,Helvetica,sans-serif"
8212 * > textColor: "rgb(102, 102, 102)",
8213 * > whiteSpace: "normal",
8214 * > fontSize: "14.6667px",
8215 * > fontFamily: "'Trebuchet MS',Arial,Helvetica,sans-serif",
8216 * > fontWeight: "400"
8220 * > borderColor: "#999999",
8224 * > showGridline: true,
8225 * > showLabel: true,
8229 * > whiteSpace: "nowrap",
8230 * > fontSize: "12px",
8231 * > fontFamily: "'Trebuchet MS',Arial,Helvetica,sans-serif"
8234 * > textColor: null,
8235 * > whiteSpace: null,
8237 * > fontFamily: null,
8238 * > fontWeight: null
8249 * "seriesStyles" is a style object that will be applied to all series in the plot.
8250 * It will forcibly override any styles applied on the individual series. "axesStyles" is
8251 * a style object that will be applied to all axes in the plot. It will also forcibly
8252 * override any styles on the individual axes.
8254 * The example shown above has series options for a line series. Options for other
8255 * series types are shown below:
8260 * > color: "#4bb2c5",
8261 * > seriesColors: ["#4bb2c5", "#EAA228", "#c5b47f", "#579575", "#839557", "#958c12", "#953579", "#4b5de4", "#d8b83f", "#ff5800", "#0085cc", "#c747a3", "#cddf54", "#FBD178", "#26B4E3", "#bd70c7"],
8266 * > barWidth: 15.09375,
8267 * > highlightColors: ["rgb(129,201,214)", "rgb(129,201,214)", "rgb(129,201,214)", "rgb(129,201,214)", "rgb(129,201,214)", "rgb(129,201,214)", "rgb(129,201,214)", "rgb(129,201,214)"]
8273 * > seriesColors: ["#4bb2c5", "#EAA228", "#c5b47f", "#579575", "#839557", "#958c12", "#953579", "#4b5de4", "#d8b83f", "#ff5800", "#0085cc", "#c747a3", "#cddf54", "#FBD178", "#26B4E3", "#bd70c7"],
8280 * > highlightColors: ["rgb(129,201,214)", "rgb(240,189,104)", "rgb(214,202,165)", "rgb(137,180,158)", "rgb(168,180,137)", "rgb(180,174,89)", "rgb(180,113,161)", "rgb(129,141,236)", "rgb(227,205,120)", "rgb(255,138,76)", "rgb(76,169,219)", "rgb(215,126,190)", "rgb(220,232,135)", "rgb(200,167,96)", "rgb(103,202,235)", "rgb(208,154,215)"]
8286 * > color: "#4bb2c5",
8295 * > sectionMargin: 6,
8296 * > seriesColors: ["#4bb2c5", "#EAA228", "#c5b47f", "#579575", "#839557", "#958c12", "#953579", "#4b5de4", "#d8b83f", "#ff5800", "#0085cc", "#c747a3", "#cddf54", "#FBD178", "#26B4E3", "#bd70c7"],
8297 * > highlightColors: ["rgb(147,208,220)", "rgb(242,199,126)", "rgb(220,210,178)", "rgb(154,191,172)", "rgb(180,191,154)", "rgb(191,186,112)", "rgb(191,133,174)", "rgb(147,157,238)", "rgb(231,212,139)", "rgb(255,154,102)", "rgb(102,181,224)", "rgb(221,144,199)", "rgb(225,235,152)", "rgb(200,167,96)", "rgb(124,210,238)", "rgb(215,169,221)"]
8301 $.jqplot.ThemeEngine = function(){
8302 // Group: Properties
8305 // hash of themes managed by the theme engine.
8306 // Indexed by theme name.
8308 // prop: activeTheme
8309 // Pointer to currently active theme
8310 this.activeTheme=null;
8314 // called with scope of plot
8315 $.jqplot.ThemeEngine.prototype.init = function() {
8316 // get the Default theme from the current plot settings.
8317 var th = new $.jqplot.Theme({_name:'Default'});
8320 for (n in th.target) {
8321 if (n == "textColor") {
8322 th.target[n] = this.target.css('color');
8325 th.target[n] = this.target.css(n);
8329 if (this.title.show && this.title._elem) {
8330 for (n in th.title) {
8331 if (n == "textColor") {
8332 th.title[n] = this.title._elem.css('color');
8335 th.title[n] = this.title._elem.css(n);
8340 for (n in th.grid) {
8341 th.grid[n] = this.grid[n];
8343 if (th.grid.backgroundColor == null && this.grid.background != null) {
8344 th.grid.backgroundColor = this.grid.background;
8346 if (this.legend.show && this.legend._elem) {
8347 for (n in th.legend) {
8348 if (n == 'textColor') {
8349 th.legend[n] = this.legend._elem.css('color');
8352 th.legend[n] = this.legend._elem.css(n);
8358 for (i=0; i<this.series.length; i++) {
8360 if (s.renderer.constructor == $.jqplot.LineRenderer) {
8361 th.series.push(new LineSeriesProperties());
8363 else if (s.renderer.constructor == $.jqplot.BarRenderer) {
8364 th.series.push(new BarSeriesProperties());
8366 else if (s.renderer.constructor == $.jqplot.PieRenderer) {
8367 th.series.push(new PieSeriesProperties());
8369 else if (s.renderer.constructor == $.jqplot.DonutRenderer) {
8370 th.series.push(new DonutSeriesProperties());
8372 else if (s.renderer.constructor == $.jqplot.FunnelRenderer) {
8373 th.series.push(new FunnelSeriesProperties());
8375 else if (s.renderer.constructor == $.jqplot.MeterGaugeRenderer) {
8376 th.series.push(new MeterSeriesProperties());
8381 for (n in th.series[i]) {
8382 th.series[i][n] = s[n];
8386 for (n in this.axes) {
8388 a = th.axes[n] = new AxisProperties();
8389 a.borderColor = ax.borderColor;
8390 a.borderWidth = ax.borderWidth;
8391 if (ax._ticks && ax._ticks[0]) {
8392 for (nn in a.ticks) {
8393 if (ax._ticks[0].hasOwnProperty(nn)) {
8394 a.ticks[nn] = ax._ticks[0][nn];
8396 else if (ax._ticks[0]._elem){
8397 a.ticks[nn] = ax._ticks[0]._elem.css(nn);
8401 if (ax._label && ax._label.show) {
8402 for (nn in a.label) {
8403 // a.label[nn] = ax._label._elem.css(nn);
8404 if (ax._label[nn]) {
8405 a.label[nn] = ax._label[nn];
8407 else if (ax._label._elem){
8408 if (nn == 'textColor') {
8409 a.label[nn] = ax._label._elem.css('color');
8412 a.label[nn] = ax._label._elem.css(nn);
8418 this.themeEngine._add(th);
8419 this.themeEngine.activeTheme = this.themeEngine.themes[th._name];
8426 * Get and return the named theme or the active theme if no name given.
8430 * name - name of theme to get.
8434 * Theme instance of given name.
8436 $.jqplot.ThemeEngine.prototype.get = function(name) {
8438 // return the active theme
8439 return this.activeTheme;
8442 return this.themes[name];
8446 function numericalOrder(a,b) { return a-b; }
8449 * method: getThemeNames
8451 * Return the list of theme names in this manager in alpha-numerical order.
8459 * A the list of theme names in this manager in alpha-numerical order.
8461 $.jqplot.ThemeEngine.prototype.getThemeNames = function() {
8463 for (var n in this.themes) {
8466 return tn.sort(numericalOrder);
8472 * Return a list of themes in alpha-numerical order by name.
8480 * A list of themes in alpha-numerical order by name.
8482 $.jqplot.ThemeEngine.prototype.getThemes = function() {
8485 for (var n in this.themes) {
8488 tn.sort(numericalOrder);
8489 for (var i=0; i<tn.length; i++) {
8490 themes.push(this.themes[tn[i]]);
8495 $.jqplot.ThemeEngine.prototype.activate = function(plot, name) {
8496 // sometimes need to redraw whole plot.
8497 var redrawPlot = false;
8498 if (!name && this.activeTheme && this.activeTheme._name) {
8499 name = this.activeTheme._name;
8501 if (!this.themes.hasOwnProperty(name)) {
8502 throw new Error("No theme of that name");
8505 var th = this.themes[name];
8506 this.activeTheme = th;
8507 var val, checkBorderColor = false, checkBorderWidth = false;
8508 var arr = ['xaxis', 'x2axis', 'yaxis', 'y2axis'];
8510 for (i=0; i<arr.length; i++) {
8512 if (th.axesStyles.borderColor != null) {
8513 plot.axes[ax].borderColor = th.axesStyles.borderColor;
8515 if (th.axesStyles.borderWidth != null) {
8516 plot.axes[ax].borderWidth = th.axesStyles.borderWidth;
8520 for (var axname in plot.axes) {
8521 var axis = plot.axes[axname];
8523 var thaxis = th.axes[axname] || {};
8524 var thaxstyle = th.axesStyles;
8525 var thax = $.jqplot.extend(true, {}, thaxis, thaxstyle);
8526 val = (th.axesStyles.borderColor != null) ? th.axesStyles.borderColor : thax.borderColor;
8527 if (thax.borderColor != null) {
8528 axis.borderColor = thax.borderColor;
8531 val = (th.axesStyles.borderWidth != null) ? th.axesStyles.borderWidth : thax.borderWidth;
8532 if (thax.borderWidth != null) {
8533 axis.borderWidth = thax.borderWidth;
8536 if (axis._ticks && axis._ticks[0]) {
8537 for (var nn in thax.ticks) {
8539 // if (th.axesStyles.ticks && th.axesStyles.ticks[nn] != null) {
8540 // val = th.axesStyles.ticks[nn];
8542 // else if (thax.ticks[nn] != null){
8543 // val = thax.ticks[nn]
8545 val = thax.ticks[nn];
8547 axis.tickOptions[nn] = val;
8553 if (axis._label && axis._label.show) {
8554 for (var nn in thax.label) {
8556 // if (th.axesStyles.label && th.axesStyles.label[nn] != null) {
8557 // val = th.axesStyles.label[nn];
8559 // else if (thax.label && thax.label[nn] != null){
8560 // val = thax.label[nn]
8562 val = thax.label[nn];
8564 axis.labelOptions[nn] = val;
8573 for (var n in th.grid) {
8574 if (th.grid[n] != null) {
8575 plot.grid[n] = th.grid[n];
8582 if (plot.legend.show) {
8583 for (n in th.legend) {
8584 if (th.legend[n] != null) {
8585 plot.legend[n] = th.legend[n];
8589 if (plot.title.show) {
8590 for (n in th.title) {
8591 if (th.title[n] != null) {
8592 plot.title[n] = th.title[n];
8598 for (i=0; i<th.series.length; i++) {
8600 var redrawSeries = false;
8601 for (n in th.series[i]) {
8602 val = (th.seriesStyles[n] != null) ? th.seriesStyles[n] : th.series[i][n];
8606 plot.series[i].renderer.shapeRenderer.fillStyle = val;
8607 plot.series[i].renderer.shapeRenderer.strokeStyle = val;
8608 plot.series[i][n] = val;
8610 else if ((n == 'lineWidth') || (n == 'linePattern')) {
8611 plot.series[i].renderer.shapeRenderer[n] = val;
8612 plot.series[i][n] = val;
8614 else if (n == 'markerOptions') {
8615 merge (plot.series[i].markerOptions, val);
8616 merge (plot.series[i].markerRenderer, val);
8619 plot.series[i][n] = val;
8627 plot.target.empty();
8631 for (n in th.target) {
8632 if (th.target[n] != null) {
8633 plot.target.css(n, th.target[n]);
8640 $.jqplot.ThemeEngine.prototype._add = function(theme, name) {
8645 theme._name = Date.parse(new Date());
8647 if (!this.themes.hasOwnProperty(theme._name)) {
8648 this.themes[theme._name] = theme;
8651 throw new Error("jqplot.ThemeEngine Error: Theme already in use");
8656 // Delete the named theme, return true on success, false on failure.
8662 * Remove the given theme from the themeEngine.
8666 * name - name of the theme to remove.
8670 * true on success, false on failure.
8672 $.jqplot.ThemeEngine.prototype.remove = function(name) {
8673 if (name == 'Default') {
8676 return delete this.themes[name];
8682 * Create a new theme based on the default theme, adding it the themeEngine.
8686 * name - name of the new theme.
8687 * obj - optional object of styles to be applied to this new theme.
8693 $.jqplot.ThemeEngine.prototype.newTheme = function(name, obj) {
8694 if (typeof(name) == 'object') {
8698 if (obj && obj._name) {
8702 name = name || Date.parse(new Date());
8704 // var th = new $.jqplot.Theme(name);
8705 var th = this.copy(this.themes['Default']._name, name);
8706 $.jqplot.extend(th, obj);
8710 // function clone(obj) {
8711 // return eval(obj.toSource());
8714 function clone(obj){
8715 if(obj == null || typeof(obj) != 'object'){
8719 var temp = new obj.constructor();
8720 for(var key in obj){
8721 temp[key] = clone(obj[key]);
8726 $.jqplot.clone = clone;
8728 function merge(obj1, obj2) {
8729 if (obj2 == null || typeof(obj2) != 'object') {
8732 for (var key in obj2) {
8733 if (key == 'highlightColors') {
8734 obj1[key] = clone(obj2[key]);
8736 if (obj2[key] != null && typeof(obj2[key]) == 'object') {
8737 if (!obj1.hasOwnProperty(key)) {
8740 merge(obj1[key], obj2[key]);
8743 obj1[key] = obj2[key];
8748 $.jqplot.merge = merge;
8750 // Use the jQuery 1.3.2 extend function since behaviour in jQuery 1.4 seems problematic
8751 $.jqplot.extend = function() {
8752 // copy reference to target object
8753 var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options;
8755 // Handle a deep copy situation
8756 if ( typeof target === "boolean" ) {
8758 target = arguments[1] || {};
8759 // skip the boolean and the target
8763 // Handle case when target is a string or something (possible in deep copy)
8764 if ( typeof target !== "object" && !toString.call(target) === "[object Function]" ) {
8768 for ( ; i < length; i++ ){
8769 // Only deal with non-null/undefined values
8770 if ( (options = arguments[ i ]) != null ) {
8771 // Extend the base object
8772 for ( var name in options ) {
8773 var src = target[ name ], copy = options[ name ];
8775 // Prevent never-ending loop
8776 if ( target === copy ) {
8780 // Recurse if we're merging object values
8781 if ( deep && copy && typeof copy === "object" && !copy.nodeType ) {
8782 target[ name ] = $.jqplot.extend( deep,
8783 // Never move original objects, clone them
8784 src || ( copy.length != null ? [ ] : { } )
8787 // Don't bring in undefined values
8788 else if ( copy !== undefined ) {
8789 target[ name ] = copy;
8794 // Return the modified object
8805 * oldName - current name of the theme.
8806 * newName - desired name of the theme.
8812 $.jqplot.ThemeEngine.prototype.rename = function (oldName, newName) {
8813 if (oldName == 'Default' || newName == 'Default') {
8814 throw new Error ("jqplot.ThemeEngine Error: Cannot rename from/to Default");
8816 if (this.themes.hasOwnProperty(newName)) {
8817 throw new Error ("jqplot.ThemeEngine Error: New name already in use.");
8819 else if (this.themes.hasOwnProperty(oldName)) {
8820 var th = this.copy (oldName, newName);
8821 this.remove(oldName);
8824 throw new Error("jqplot.ThemeEngine Error: Old name or new name invalid");
8830 * Create a copy of an existing theme in the themeEngine, adding it the themeEngine.
8834 * sourceName - name of the existing theme.
8835 * targetName - name of the copy.
8836 * obj - optional object of style parameter to apply to the new theme.
8842 $.jqplot.ThemeEngine.prototype.copy = function (sourceName, targetName, obj) {
8843 if (targetName == 'Default') {
8844 throw new Error ("jqplot.ThemeEngine Error: Cannot copy over Default theme");
8846 if (!this.themes.hasOwnProperty(sourceName)) {
8847 var s = "jqplot.ThemeEngine Error: Source name invalid";
8850 if (this.themes.hasOwnProperty(targetName)) {
8851 var s = "jqplot.ThemeEngine Error: Target name invalid";
8855 var th = clone(this.themes[sourceName]);
8856 th._name = targetName;
8857 $.jqplot.extend(true, th, obj);
8864 $.jqplot.Theme = function(name, obj) {
8865 if (typeof(name) == 'object') {
8869 name = name || Date.parse(new Date());
8872 backgroundColor: null
8887 this.seriesStyles = {};
8890 drawGridlines: null,
8891 gridLineColor: null,
8892 gridLineWidth: null,
8893 backgroundColor: null,
8898 this.axesStyles = {label:{}, ticks:{}};
8900 if (typeof(obj) == 'string') {
8903 else if(typeof(obj) == 'object') {
8904 $.jqplot.extend(true, this, obj);
8908 var AxisProperties = function() {
8909 this.borderColor = null;
8910 this.borderWidth = null;
8911 this.ticks = new AxisTicks();
8912 this.label = new AxisLabel();
8915 var AxisTicks = function() {
8917 this.showGridline = null;
8918 this.showLabel = null;
8919 this.showMark = null;
8921 this.textColor = null;
8922 this.whiteSpace = null;
8923 this.fontSize = null;
8924 this.fontFamily = null;
8927 var AxisLabel = function() {
8928 this.textColor = null;
8929 this.whiteSpace = null;
8930 this.fontSize = null;
8931 this.fontFamily = null;
8932 this.fontWeight = null;
8935 var LineSeriesProperties = function() {
8937 this.lineWidth=null;
8938 this.linePattern=null;
8940 this.fillColor=null;
8941 this.showMarker=null;
8942 this.markerOptions = new MarkerOptions();
8945 var MarkerOptions = function() {
8948 this.lineWidth = null;
8954 var BarSeriesProperties = function() {
8956 this.seriesColors=null;
8957 this.lineWidth=null;
8959 this.barPadding=null;
8960 this.barMargin=null;
8962 this.highlightColors=null;
8965 var PieSeriesProperties = function() {
8966 this.seriesColors=null;
8968 this.sliceMargin=null;
8971 this.startAngle=null;
8972 this.lineWidth=null;
8973 this.highlightColors=null;
8976 var DonutSeriesProperties = function() {
8977 this.seriesColors=null;
8979 this.sliceMargin=null;
8982 this.startAngle=null;
8983 this.lineWidth=null;
8984 this.innerDiameter=null;
8985 this.thickness=null;
8986 this.ringMargin=null;
8987 this.highlightColors=null;
8990 var FunnelSeriesProperties = function() {
8992 this.lineWidth=null;
8995 this.sectionMargin=null;
8996 this.seriesColors=null;
8997 this.highlightColors=null;
9000 var MeterSeriesProperties = function() {
9002 this.backgroundColor=null;
9003 this.ringColor=null;
9004 this.tickColor=null;
9005 this.ringWidth=null;
9006 this.intervalColors=null;
9007 this.intervalInnerRadius=null;
9008 this.intervalOuterRadius=null;
9009 this.hubRadius=null;
9010 this.needleThickness=null;
9011 this.needlePad=null;
9017 $.fn.jqplotChildText = function() {
9018 return $(this).contents().filter(function() {
9019 return this.nodeType == 3; // Node.TEXT_NODE not defined in I7
9023 // Returns font style as abbreviation for "font" property.
9024 $.fn.jqplotGetComputedFontStyle = function() {
9025 var css = window.getComputedStyle ? window.getComputedStyle(this[0], "") : this[0].currentStyle;
9026 var attrs = css['font-style'] ? ['font-style', 'font-weight', 'font-size', 'font-family'] : ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily'];
9029 for (var i=0 ; i < attrs.length; ++i) {
9030 var attr = String(css[attrs[i]]);
9032 if (attr && attr != 'normal') {
9036 return style.join(' ');
9041 * jQuery namespace to attach functions to jQuery elements.
9045 $.fn.jqplotToImageCanvas = function(options) {
9047 options = options || {};
9048 var x_offset = (options.x_offset == null) ? 0 : options.x_offset;
9049 var y_offset = (options.y_offset == null) ? 0 : options.y_offset;
9050 var backgroundColor = (options.backgroundColor == null) ? 'rgb(255,255,255)' : options.backgroundColor;
9052 if ($(this).width() == 0 || $(this).height() == 0) {
9056 // excanvas and hence IE < 9 do not support toDataURL and cannot export images.
9057 if ($.jqplot.use_excanvas) {
9061 var newCanvas = document.createElement("canvas");
9062 var h = $(this).outerHeight(true);
9063 var w = $(this).outerWidth(true);
9064 var offs = $(this).offset();
9065 var plotleft = offs.left;
9066 var plottop = offs.top;
9067 var transx = 0, transy = 0;
9069 // have to check if any elements are hanging outside of plot area before rendering,
9070 // since changing width of canvas will erase canvas.
9072 var clses = ['jqplot-table-legend', 'jqplot-xaxis-tick', 'jqplot-x2axis-tick', 'jqplot-yaxis-tick', 'jqplot-y2axis-tick', 'jqplot-y3axis-tick',
9073 'jqplot-y4axis-tick', 'jqplot-y5axis-tick', 'jqplot-y6axis-tick', 'jqplot-y7axis-tick', 'jqplot-y8axis-tick', 'jqplot-y9axis-tick',
9074 'jqplot-xaxis-label', 'jqplot-x2axis-label', 'jqplot-yaxis-label', 'jqplot-y2axis-label', 'jqplot-y3axis-label', 'jqplot-y4axis-label',
9075 'jqplot-y5axis-label', 'jqplot-y6axis-label', 'jqplot-y7axis-label', 'jqplot-y8axis-label', 'jqplot-y9axis-label' ];
9077 var temptop, templeft, tempbottom, tempright;
9079 for (var i = 0; i < clses.length; i++) {
9080 $(this).find('.'+clses[i]).each(function() {
9081 temptop = $(this).offset().top - plottop;
9082 templeft = $(this).offset().left - plotleft;
9083 tempright = templeft + $(this).outerWidth(true) + transx;
9084 tempbottom = temptop + $(this).outerHeight(true) + transy;
9085 if (templeft < -transx) {
9086 w = w - transx - templeft;
9089 if (temptop < -transy) {
9090 h = h - transy - temptop;
9093 if (tempright > w) {
9096 if (tempbottom > h) {
9102 newCanvas.width = w + Number(x_offset);
9103 newCanvas.height = h + Number(y_offset);
9105 var newContext = newCanvas.getContext("2d");
9108 newContext.fillStyle = backgroundColor;
9109 newContext.fillRect(0,0, newCanvas.width, newCanvas.height);
9110 newContext.restore();
9112 newContext.translate(transx, transy);
9113 newContext.textAlign = 'left';
9114 newContext.textBaseline = 'top';
9116 function getLineheight(el) {
9117 var lineheight = parseInt($(el).css('line-height'), 10);
9119 if (isNaN(lineheight)) {
9120 lineheight = parseInt($(el).css('font-size'), 10) * 1.2;
9125 function writeWrappedText (el, context, text, left, top, canvasWidth) {
9126 var lineheight = getLineheight(el);
9127 var tagwidth = $(el).innerWidth();
9128 var tagheight = $(el).innerHeight();
9129 var words = text.split(/\s+/);
9130 var wl = words.length;
9134 var templeft = left;
9136 for (var i=0; i<wl; i++) {
9138 if (context.measureText(w).width > tagwidth) {
9144 if (breaks.length === 0) {
9145 // center text if necessary
9146 if ($(el).css('textAlign') === 'center') {
9147 templeft = left + (canvasWidth - context.measureText(w).width)/2 - transx;
9149 context.fillText(text, templeft, top);
9152 w = words.slice(0, breaks[0]).join(' ');
9153 // center text if necessary
9154 if ($(el).css('textAlign') === 'center') {
9155 templeft = left + (canvasWidth - context.measureText(w).width)/2 - transx;
9157 context.fillText(w, templeft, temptop);
9158 temptop += lineheight;
9159 for (var i=1, l=breaks.length; i<l; i++) {
9160 w = words.slice(breaks[i-1], breaks[i]).join(' ');
9161 // center text if necessary
9162 if ($(el).css('textAlign') === 'center') {
9163 templeft = left + (canvasWidth - context.measureText(w).width)/2 - transx;
9165 context.fillText(w, templeft, temptop);
9166 temptop += lineheight;
9168 w = words.slice(breaks[i-1], words.length).join(' ');
9169 // center text if necessary
9170 if ($(el).css('textAlign') === 'center') {
9171 templeft = left + (canvasWidth - context.measureText(w).width)/2 - transx;
9173 context.fillText(w, templeft, temptop);
9178 function _jqpToImage(el, x_offset, y_offset) {
9179 var tagname = el.tagName.toLowerCase();
9180 var p = $(el).position();
9181 var css = window.getComputedStyle ? window.getComputedStyle(el, "") : el.currentStyle; // for IE < 9
9182 var left = x_offset + p.left + parseInt(css.marginLeft, 10) + parseInt(css.borderLeftWidth, 10) + parseInt(css.paddingLeft, 10);
9183 var top = y_offset + p.top + parseInt(css.marginTop, 10) + parseInt(css.borderTopWidth, 10)+ parseInt(css.paddingTop, 10);
9184 var w = newCanvas.width;
9185 // var left = x_offset + p.left + $(el).css('marginLeft') + $(el).css('borderLeftWidth')
9187 // somehow in here, for divs within divs, the width of the inner div should be used instead of the canvas.
9189 if ((tagname == 'div' || tagname == 'span') && !$(el).hasClass('jqplot-highlighter-tooltip')) {
9190 $(el).children().each(function() {
9191 _jqpToImage(this, left, top);
9193 var text = $(el).jqplotChildText();
9196 newContext.font = $(el).jqplotGetComputedFontStyle();
9197 newContext.fillStyle = $(el).css('color');
9199 writeWrappedText(el, newContext, text, left, top, w);
9203 // handle the standard table legend
9205 else if (tagname === 'table' && $(el).hasClass('jqplot-table-legend')) {
9206 newContext.strokeStyle = $(el).css('border-top-color');
9207 newContext.fillStyle = $(el).css('background-color');
9208 newContext.fillRect(left, top, $(el).innerWidth(), $(el).innerHeight());
9209 if (parseInt($(el).css('border-top-width'), 10) > 0) {
9210 newContext.strokeRect(left, top, $(el).innerWidth(), $(el).innerHeight());
9213 // find all the swatches
9214 $(el).find('div.jqplot-table-legend-swatch-outline').each(function() {
9215 // get the first div and stroke it
9217 newContext.strokeStyle = elem.css('border-top-color');
9218 var l = left + elem.position().left;
9219 var t = top + elem.position().top;
9220 newContext.strokeRect(l, t, elem.innerWidth(), elem.innerHeight());
9222 // now fill the swatch
9224 l += parseInt(elem.css('padding-left'), 10);
9225 t += parseInt(elem.css('padding-top'), 10);
9226 var h = elem.innerHeight() - 2 * parseInt(elem.css('padding-top'), 10);
9227 var w = elem.innerWidth() - 2 * parseInt(elem.css('padding-left'), 10);
9229 var swatch = elem.children('div.jqplot-table-legend-swatch');
9230 newContext.fillStyle = swatch.css('background-color');
9231 newContext.fillRect(l, t, w, h);
9236 $(el).find('td.jqplot-table-legend-label').each(function(){
9238 var l = left + elem.position().left;
9239 var t = top + elem.position().top + parseInt(elem.css('padding-top'), 10);
9240 newContext.font = elem.jqplotGetComputedFontStyle();
9241 newContext.fillStyle = elem.css('color');
9242 writeWrappedText(elem, newContext, elem.text(), l, t, w);
9248 else if (tagname == 'canvas') {
9249 newContext.drawImage(el, left, top);
9252 $(this).children().each(function() {
9253 _jqpToImage(this, x_offset, y_offset);
9258 // return the raw image data string.
9259 // Should work on canvas supporting browsers.
9260 $.fn.jqplotToImageStr = function(options) {
9261 var imgCanvas = $(this).jqplotToImageCanvas(options);
9263 return imgCanvas.toDataURL("image/png");
9270 // return a DOM <img> element and return it.
9271 // Should work on canvas supporting browsers.
9272 $.fn.jqplotToImageElem = function(options) {
9273 var elem = document.createElement("img");
9274 var str = $(this).jqplotToImageStr(options);
9279 // return a string for an <img> element and return it.
9280 // Should work on canvas supporting browsers.
9281 $.fn.jqplotToImageElemStr = function(options) {
9282 var str = '<img src='+$(this).jqplotToImageStr(options)+' />';
9286 // Not gauranteed to work, even on canvas supporting browsers due to
9287 // limitations with location.href and browser support.
9288 $.fn.jqplotSaveImage = function() {
9289 var imgData = $(this).jqplotToImageStr({});
9291 window.location.href = imgData.replace("image/png", "image/octet-stream");
9296 // Not gauranteed to work, even on canvas supporting browsers due to
9297 // limitations with window.open and arbitrary data.
9298 $.fn.jqplotViewImage = function() {
9299 var imgStr = $(this).jqplotToImageElemStr({});
9300 var imgData = $(this).jqplotToImageStr({});
9302 var w = window.open('');
9303 w.document.open("image/png");
9304 w.document.write(imgStr);
9315 * <p>Object with extended date parsing and formatting capabilities.
9316 * This library borrows many concepts and ideas from the Date Instance
9317 * Methods by Ken Snyder along with some parts of Ken's actual code.</p>
9319 * <p>jsDate takes a different approach by not extending the built-in
9320 * Date Object, improving date parsing, allowing for multiple formatting
9321 * syntaxes and multiple and more easily expandable localization.</p>
9323 * @author Chris Leonello
9325 * @version #VERSION#
9326 * @copyright (c) 2010 Chris Leonello
9327 * jsDate is currently available for use in all personal or commercial projects
9328 * under both the MIT and GPL version 2.0 licenses. This means that you can
9329 * choose the license that best suits your project and use it accordingly.
9331 * <p>Ken's origianl Date Instance Methods and copyright notice:</p>
9333 * Ken Snyder (ken d snyder at gmail dot com)
9335 * version 2.0.2 (http://kendsnyder.com/sandbox/date/)
9336 * Creative Commons Attribution License 3.0 (http://creativecommons.org/licenses/by/3.0/)
9341 * @param {String | Number | Array | Date Object | Options Object} arguments Optional arguments, either a parsable date/time string,
9342 * a JavaScript timestamp, an array of numbers of form [year, month, day, hours, minutes, seconds, milliseconds],
9343 * a Date object, or an options object of form {syntax: "perl", date:some Date} where all options are optional.
9346 var jsDate = function () {
9348 this.syntax = jsDate.config.syntax;
9349 this._type = "jsDate";
9350 this.proxy = new Date();
9352 this.locale = jsDate.regional.getLocale();
9353 this.formatString = '';
9354 this.defaultCentury = jsDate.config.defaultCentury;
9356 switch ( arguments.length ) {
9360 // other objects either won't have a _type property or,
9361 // if they do, it shouldn't be set to "jsDate", so
9362 // assume it is an options argument.
9363 if (get_type(arguments[0]) == "[object Object]" && arguments[0]._type != "jsDate") {
9364 var opts = this.options = arguments[0];
9365 this.syntax = opts.syntax || this.syntax;
9366 this.defaultCentury = opts.defaultCentury || this.defaultCentury;
9367 this.proxy = jsDate.createDate(opts.date);
9370 this.proxy = jsDate.createDate(arguments[0]);
9375 for ( var i=0; i<arguments.length; i++ ) {
9376 a.push(arguments[i]);
9378 // this should be the current date/time?
9379 this.proxy = new Date();
9380 this.proxy.setFullYear.apply( this.proxy, a.slice(0,3) );
9381 if ( a.slice(3).length ) {
9382 this.proxy.setHours.apply( this.proxy, a.slice(3) );
9389 * @namespace Configuration options that will be used as defaults for all instances on the page.
9390 * @property {String} defaultLocale The default locale to use [en].
9391 * @property {String} syntax The default syntax to use [perl].
9392 * @property {Number} defaultCentury The default centry for 2 digit dates.
9395 defaultLocale: 'en',
9397 defaultCentury: 1900
9401 * Add an arbitrary amount to the currently stored date
9403 * @param {Number} number
9404 * @param {String} unit
9408 jsDate.prototype.add = function(number, unit) {
9409 var factor = multipliers[unit] || multipliers.day;
9410 if (typeof factor == 'number') {
9411 this.proxy.setTime(this.proxy.getTime() + (factor * number));
9413 factor.add(this, number);
9419 * Create a new jqplot.date object with the same date
9424 jsDate.prototype.clone = function() {
9425 return new jsDate(this.proxy.getTime());
9429 * Get the UTC TimeZone Offset of this date in milliseconds.
9434 jsDate.prototype.getUtcOffset = function() {
9435 return this.proxy.getTimezoneOffset() * 60000;
9439 * Find the difference between this jsDate and another date.
9441 * @param {String| Number| Array| jsDate Object| Date Object} dateObj
9442 * @param {String} unit
9443 * @param {Boolean} allowDecimal
9444 * @returns {Number} Number of units difference between dates.
9447 jsDate.prototype.diff = function(dateObj, unit, allowDecimal) {
9448 // ensure we have a Date object
9449 dateObj = new jsDate(dateObj);
9450 if (dateObj === null) {
9453 // get the multiplying factor integer or factor function
9454 var factor = multipliers[unit] || multipliers.day;
9455 if (typeof factor == 'number') {
9457 var unitDiff = (this.proxy.getTime() - dateObj.proxy.getTime()) / factor;
9460 var unitDiff = factor.diff(this.proxy, dateObj.proxy);
9462 // if decimals are not allowed, round toward zero
9463 return (allowDecimal ? unitDiff : Math[unitDiff > 0 ? 'floor' : 'ceil'](unitDiff));
9467 * Get the abbreviated name of the current week day
9472 jsDate.prototype.getAbbrDayName = function() {
9473 return jsDate.regional[this.locale]["dayNamesShort"][this.proxy.getDay()];
9477 * Get the abbreviated name of the current month
9482 jsDate.prototype.getAbbrMonthName = function() {
9483 return jsDate.regional[this.locale]["monthNamesShort"][this.proxy.getMonth()];
9487 * Get UPPER CASE AM or PM for the current time
9492 jsDate.prototype.getAMPM = function() {
9493 return this.proxy.getHours() >= 12 ? 'PM' : 'AM';
9497 * Get lower case am or pm for the current time
9502 jsDate.prototype.getAmPm = function() {
9503 return this.proxy.getHours() >= 12 ? 'pm' : 'am';
9507 * Get the century (19 for 20th Century)
9509 * @returns {Integer} Century (19 for 20th century).
9511 jsDate.prototype.getCentury = function() {
9512 return parseInt(this.proxy.getFullYear()/100, 10);
9516 * Implements Date functionality
9518 jsDate.prototype.getDate = function() {
9519 return this.proxy.getDate();
9523 * Implements Date functionality
9525 jsDate.prototype.getDay = function() {
9526 return this.proxy.getDay();
9530 * Get the Day of week 1 (Monday) thru 7 (Sunday)
9532 * @returns {Integer} Day of week 1 (Monday) thru 7 (Sunday)
9534 jsDate.prototype.getDayOfWeek = function() {
9535 var dow = this.proxy.getDay();
9536 return dow===0?7:dow;
9540 * Get the day of the year
9542 * @returns {Integer} 1 - 366, day of the year
9544 jsDate.prototype.getDayOfYear = function() {
9546 var ms = d - new Date('' + d.getFullYear() + '/1/1 GMT');
9547 ms += d.getTimezoneOffset()*60000;
9549 return parseInt(ms/60000/60/24, 10)+1;
9553 * Get the name of the current week day
9558 jsDate.prototype.getDayName = function() {
9559 return jsDate.regional[this.locale]["dayNames"][this.proxy.getDay()];
9563 * Get the week number of the given year, starting with the first Sunday as the first week
9564 * @returns {Integer} Week number (13 for the 13th full week of the year).
9566 jsDate.prototype.getFullWeekOfYear = function() {
9568 var doy = this.getDayOfYear();
9569 var rdow = 6-d.getDay();
9570 var woy = parseInt((doy+rdow)/7, 10);
9575 * Implements Date functionality
9577 jsDate.prototype.getFullYear = function() {
9578 return this.proxy.getFullYear();
9582 * Get the GMT offset in hours and minutes (e.g. +06:30)
9587 jsDate.prototype.getGmtOffset = function() {
9588 // divide the minutes offset by 60
9589 var hours = this.proxy.getTimezoneOffset() / 60;
9590 // decide if we are ahead of or behind GMT
9591 var prefix = hours < 0 ? '+' : '-';
9592 // remove the negative sign if any
9593 hours = Math.abs(hours);
9594 // add the +/- to the padded number of hours to : to the padded minutes
9595 return prefix + addZeros(Math.floor(hours), 2) + ':' + addZeros((hours % 1) * 60, 2);
9599 * Implements Date functionality
9601 jsDate.prototype.getHours = function() {
9602 return this.proxy.getHours();
9606 * Get the current hour on a 12-hour scheme
9608 * @returns {Integer}
9611 jsDate.prototype.getHours12 = function() {
9612 var hours = this.proxy.getHours();
9613 return hours > 12 ? hours - 12 : (hours == 0 ? 12 : hours);
9617 jsDate.prototype.getIsoWeek = function() {
9619 var woy = d.getWeekOfYear();
9620 var dow1_1 = (new Date('' + d.getFullYear() + '/1/1')).getDay();
9621 // First week is 01 and not 00 as in the case of %U and %W,
9622 // so we add 1 to the final result except if day 1 of the year
9623 // is a Monday (then %W returns 01).
9624 // We also need to subtract 1 if the day 1 of the year is
9625 // Friday-Sunday, so the resulting equation becomes:
9626 var idow = woy + (dow1_1 > 4 || dow1_1 <= 1 ? 0 : 1);
9627 if(idow == 53 && (new Date('' + d.getFullYear() + '/12/31')).getDay() < 4)
9633 d = new jsDate(new Date('' + (d.getFullYear()-1) + '/12/31'));
9634 idow = d.getIsoWeek();
9641 * Implements Date functionality
9643 jsDate.prototype.getMilliseconds = function() {
9644 return this.proxy.getMilliseconds();
9648 * Implements Date functionality
9650 jsDate.prototype.getMinutes = function() {
9651 return this.proxy.getMinutes();
9655 * Implements Date functionality
9657 jsDate.prototype.getMonth = function() {
9658 return this.proxy.getMonth();
9662 * Get the name of the current month
9667 jsDate.prototype.getMonthName = function() {
9668 return jsDate.regional[this.locale]["monthNames"][this.proxy.getMonth()];
9672 * Get the number of the current month, 1-12
9674 * @returns {Integer}
9677 jsDate.prototype.getMonthNumber = function() {
9678 return this.proxy.getMonth() + 1;
9682 * Implements Date functionality
9684 jsDate.prototype.getSeconds = function() {
9685 return this.proxy.getSeconds();
9689 * Return a proper two-digit year integer
9691 * @returns {Integer}
9694 jsDate.prototype.getShortYear = function() {
9695 return this.proxy.getYear() % 100;
9699 * Implements Date functionality
9701 jsDate.prototype.getTime = function() {
9702 return this.proxy.getTime();
9706 * Get the timezone abbreviation
9708 * @returns {String} Abbreviation for the timezone
9710 jsDate.prototype.getTimezoneAbbr = function() {
9711 return this.proxy.toString().replace(/^.*\(([^)]+)\)$/, '$1');
9715 * Get the browser-reported name for the current timezone (e.g. MDT, Mountain Daylight Time)
9719 jsDate.prototype.getTimezoneName = function() {
9720 var match = /(?:\((.+)\)$| ([A-Z]{3}) )/.exec(this.toString());
9721 return match[1] || match[2] || 'GMT' + this.getGmtOffset();
9725 * Implements Date functionality
9727 jsDate.prototype.getTimezoneOffset = function() {
9728 return this.proxy.getTimezoneOffset();
9733 * Get the week number of the given year, starting with the first Monday as the first week
9734 * @returns {Integer} Week number (13 for the 13th week of the year).
9736 jsDate.prototype.getWeekOfYear = function() {
9737 var doy = this.getDayOfYear();
9738 var rdow = 7 - this.getDayOfWeek();
9739 var woy = parseInt((doy+rdow)/7, 10);
9744 * Get the current date as a Unix timestamp
9746 * @returns {Integer}
9749 jsDate.prototype.getUnix = function() {
9750 return Math.round(this.proxy.getTime() / 1000, 0);
9754 * Implements Date functionality
9756 jsDate.prototype.getYear = function() {
9757 return this.proxy.getYear();
9761 * Return a date one day ahead (or any other unit)
9763 * @param {String} unit Optional, year | month | day | week | hour | minute | second | millisecond
9767 jsDate.prototype.next = function(unit) {
9768 unit = unit || 'day';
9769 return this.clone().add(1, unit);
9773 * Set the jsDate instance to a new date.
9775 * @param {String | Number | Array | Date Object | jsDate Object | Options Object} arguments Optional arguments,
9776 * either a parsable date/time string,
9777 * a JavaScript timestamp, an array of numbers of form [year, month, day, hours, minutes, seconds, milliseconds],
9778 * a Date object, jsDate Object or an options object of form {syntax: "perl", date:some Date} where all options are optional.
9780 jsDate.prototype.set = function() {
9781 switch ( arguments.length ) {
9783 this.proxy = new Date();
9786 // other objects either won't have a _type property or,
9787 // if they do, it shouldn't be set to "jsDate", so
9788 // assume it is an options argument.
9789 if (get_type(arguments[0]) == "[object Object]" && arguments[0]._type != "jsDate") {
9790 var opts = this.options = arguments[0];
9791 this.syntax = opts.syntax || this.syntax;
9792 this.defaultCentury = opts.defaultCentury || this.defaultCentury;
9793 this.proxy = jsDate.createDate(opts.date);
9796 this.proxy = jsDate.createDate(arguments[0]);
9801 for ( var i=0; i<arguments.length; i++ ) {
9802 a.push(arguments[i]);
9804 // this should be the current date/time
9805 this.proxy = new Date();
9806 this.proxy.setFullYear.apply( this.proxy, a.slice(0,3) );
9807 if ( a.slice(3).length ) {
9808 this.proxy.setHours.apply( this.proxy, a.slice(3) );
9816 * Sets the day of the month for a specified date according to local time.
9817 * @param {Integer} dayValue An integer from 1 to 31, representing the day of the month.
9819 jsDate.prototype.setDate = function(n) {
9820 this.proxy.setDate(n);
9825 * Sets the full year for a specified date according to local time.
9826 * @param {Integer} yearValue The numeric value of the year, for example, 1995.
9827 * @param {Integer} monthValue Optional, between 0 and 11 representing the months January through December.
9828 * @param {Integer} dayValue Optional, between 1 and 31 representing the day of the month. If you specify the dayValue parameter, you must also specify the monthValue.
9830 jsDate.prototype.setFullYear = function() {
9831 this.proxy.setFullYear.apply(this.proxy, arguments);
9836 * Sets the hours for a specified date according to local time.
9838 * @param {Integer} hoursValue An integer between 0 and 23, representing the hour.
9839 * @param {Integer} minutesValue Optional, An integer between 0 and 59, representing the minutes.
9840 * @param {Integer} secondsValue Optional, An integer between 0 and 59, representing the seconds.
9841 * If you specify the secondsValue parameter, you must also specify the minutesValue.
9842 * @param {Integer} msValue Optional, A number between 0 and 999, representing the milliseconds.
9843 * If you specify the msValue parameter, you must also specify the minutesValue and secondsValue.
9845 jsDate.prototype.setHours = function() {
9846 this.proxy.setHours.apply(this.proxy, arguments);
9851 * Implements Date functionality
9853 jsDate.prototype.setMilliseconds = function(n) {
9854 this.proxy.setMilliseconds(n);
9859 * Implements Date functionality
9861 jsDate.prototype.setMinutes = function() {
9862 this.proxy.setMinutes.apply(this.proxy, arguments);
9867 * Implements Date functionality
9869 jsDate.prototype.setMonth = function() {
9870 this.proxy.setMonth.apply(this.proxy, arguments);
9875 * Implements Date functionality
9877 jsDate.prototype.setSeconds = function() {
9878 this.proxy.setSeconds.apply(this.proxy, arguments);
9883 * Implements Date functionality
9885 jsDate.prototype.setTime = function(n) {
9886 this.proxy.setTime(n);
9891 * Implements Date functionality
9893 jsDate.prototype.setYear = function() {
9894 this.proxy.setYear.apply(this.proxy, arguments);
9899 * Provide a formatted string representation of this date.
9901 * @param {String} formatString A format string.
9902 * See: {@link jsDate.formats}.
9903 * @returns {String} Date String.
9906 jsDate.prototype.strftime = function(formatString) {
9907 formatString = formatString || this.formatString || jsDate.regional[this.locale]['formatString'];
9908 return jsDate.strftime(this, formatString, this.syntax);
9912 * Return a String representation of this jsDate object.
9913 * @returns {String} Date string.
9916 jsDate.prototype.toString = function() {
9917 return this.proxy.toString();
9921 * Convert the current date to an 8-digit integer (%Y%m%d)
9923 * @returns {Integer}
9926 jsDate.prototype.toYmdInt = function() {
9927 return (this.proxy.getFullYear() * 10000) + (this.getMonthNumber() * 100) + this.proxy.getDate();
9931 * @namespace Holds localizations for month/day names.
9932 * <p>jsDate attempts to detect locale when loaded and defaults to 'en'.
9933 * If a localization is detected which is not available, jsDate defaults to 'en'.
9934 * Additional localizations can be added after jsDate loads. After adding a localization,
9935 * call the jsDate.regional.getLocale() method. Currently, en, fr and de are defined.</p>
9937 * <p>Localizations must be an object and have the following properties defined: monthNames, monthNamesShort, dayNames, dayNamesShort and Localizations are added like:</p>
9938 * <pre class="code">
9939 * jsDate.regional['en'] = {
9940 * monthNames : 'January February March April May June July August September October November December'.split(' '),
9941 * monthNamesShort : 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split(' '),
9942 * dayNames : 'Sunday Monday Tuesday Wednesday Thursday Friday Saturday'.split(' '),
9943 * dayNamesShort : 'Sun Mon Tue Wed Thu Fri Sat'.split(' ')
9946 * <p>After adding localizations, call <code>jsDate.regional.getLocale();</code> to update the locale setting with the
9947 * new localizations.</p>
9952 monthNames: ['January','February','March','April','May','June','July','August','September','October','November','December'],
9953 monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun','Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
9954 dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
9955 dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
9956 formatString: '%Y-%m-%d %H:%M:%S'
9960 monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
9961 monthNamesShort: ['Jan','Fév','Mar','Avr','Mai','Jun','Jul','Aoû','Sep','Oct','Nov','Déc'],
9962 dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
9963 dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
9964 formatString: '%Y-%m-%d %H:%M:%S'
9968 monthNames: ['Januar','Februar','März','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'],
9969 monthNamesShort: ['Jan','Feb','Mär','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Dez'],
9970 dayNames: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
9971 dayNamesShort: ['So','Mo','Di','Mi','Do','Fr','Sa'],
9972 formatString: '%Y-%m-%d %H:%M:%S'
9976 monthNames: ['Enero','Febrero','Marzo','Abril','Mayo','Junio', 'Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'],
9977 monthNamesShort: ['Ene','Feb','Mar','Abr','May','Jun', 'Jul','Ago','Sep','Oct','Nov','Dic'],
9978 dayNames: ['Domingo','Lunes','Martes','Miércoles','Jueves','Viernes','Sábado'],
9979 dayNamesShort: ['Dom','Lun','Mar','Mié','Juv','Vie','Sáb'],
9980 formatString: '%Y-%m-%d %H:%M:%S'
9984 monthNames: ['Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'],
9985 monthNamesShort: ['Янв','Фев','Мар','Апр','Май','Июн','Июл','Авг','Сен','Окт','Ноя','Дек'],
9986 dayNames: ['воскресенье','понедельник','вторник','среда','четверг','пятница','суббота'],
9987 dayNamesShort: ['вск','пнд','втр','срд','чтв','птн','сбт'],
9988 formatString: '%Y-%m-%d %H:%M:%S'
9992 monthNames: ['كانون الثاني', 'شباط', 'آذار', 'نيسان', 'آذار', 'حزيران','تموز', 'آب', 'أيلول', 'تشرين الأول', 'تشرين الثاني', 'كانون الأول'],
9993 monthNamesShort: ['1','2','3','4','5','6','7','8','9','10','11','12'],
9994 dayNames: ['السبت', 'الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة'],
9995 dayNamesShort: ['سبت', 'أحد', 'اثنين', 'ثلاثاء', 'أربعاء', 'خميس', 'جمعة'],
9996 formatString: '%Y-%m-%d %H:%M:%S'
10000 monthNames: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
10001 monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'],
10002 dayNames: ['Domingo','Segunda-feira','Terça-feira','Quarta-feira','Quinta-feira','Sexta-feira','Sábado'],
10003 dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','Sáb'],
10004 formatString: '%Y-%m-%d %H:%M:%S'
10008 monthNames: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho', 'Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
10009 monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'],
10010 dayNames: ['Domingo','Segunda-feira','Terça-feira','Quarta-feira','Quinta-feira','Sexta-feira','Sábado'],
10011 dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','Sáb'],
10012 formatString: '%Y-%m-%d %H:%M:%S'
10018 // Set english variants to 'en'
10019 jsDate.regional['en-US'] = jsDate.regional['en-GB'] = jsDate.regional['en'];
10022 * Try to determine the users locale based on the lang attribute of the html page. Defaults to 'en'
10023 * if it cannot figure out a locale of if the locale does not have a localization defined.
10024 * @returns {String} locale
10027 jsDate.regional.getLocale = function () {
10028 var l = jsDate.config.defaultLocale;
10030 if ( document && document.getElementsByTagName('html') && document.getElementsByTagName('html')[0].lang ) {
10031 l = document.getElementsByTagName('html')[0].lang;
10032 if (!jsDate.regional.hasOwnProperty(l)) {
10033 l = jsDate.config.defaultLocale;
10041 var day = 24 * 60 * 60 * 1000;
10043 // padd a number with zeros
10044 var addZeros = function(num, digits) {
10046 var i = digits - num.length;
10047 var s = String(Math.pow(10, i)).slice(1);
10048 return s.concat(num);
10051 // representations used for calculating differences between dates.
10052 // This borrows heavily from Ken Snyder's work.
10053 var multipliers = {
10057 hour: 60 * 60 * 1000,
10061 // add a number of months
10062 add: function(d, number) {
10063 // add any years needed (increments of 12)
10064 multipliers.year.add(d, Math[number > 0 ? 'floor' : 'ceil'](number / 12));
10065 // ensure that we properly wrap betwen December and January
10068 var prevMonth = d.getMonth() + (number % 12);
10069 if (prevMonth == 12) {
10071 d.setYear(d.getFullYear() + 1);
10072 } else if (prevMonth == -1) {
10074 d.setYear(d.getFullYear() - 1);
10076 d.setMonth(prevMonth);
10078 // get the number of months between two Date objects (decimal to the nearest day)
10079 diff: function(d1, d2) {
10080 // get the number of years
10081 var diffYears = d1.getFullYear() - d2.getFullYear();
10082 // get the number of remaining months
10083 var diffMonths = d1.getMonth() - d2.getMonth() + (diffYears * 12);
10084 // get the number of remaining days
10085 var diffDays = d1.getDate() - d2.getDate();
10086 // return the month difference with the days difference as a decimal
10087 return diffMonths + (diffDays / 30);
10091 // add a number of years
10092 add: function(d, number) {
10093 d.setYear(d.getFullYear() + Math[number > 0 ? 'floor' : 'ceil'](number));
10095 // get the number of years between two Date objects (decimal to the nearest day)
10096 diff: function(d1, d2) {
10097 return multipliers.month.diff(d1, d2) / 12;
10102 // Alias each multiplier with an 's' to allow 'year' and 'years' for example.
10103 // This comes from Ken Snyders work.
10105 for (var unit in multipliers) {
10106 if (unit.substring(unit.length - 1) != 's') { // IE will iterate newly added properties :|
10107 multipliers[unit + 's'] = multipliers[unit];
10112 // take a jsDate instance and a format code and return the formatted value.
10113 // This is a somewhat modified version of Ken Snyder's method.
10115 var format = function(d, code, syntax) {
10116 // if shorcut codes are used, recursively expand those.
10117 if (jsDate.formats[syntax]["shortcuts"][code]) {
10118 return jsDate.strftime(d, jsDate.formats[syntax]["shortcuts"][code], syntax);
10120 // get the format code function and addZeros() argument
10121 var getter = (jsDate.formats[syntax]["codes"][code] || '').split('.');
10122 var nbr = d['get' + getter[0]] ? d['get' + getter[0]]() : '';
10124 nbr = addZeros(nbr, getter[1]);
10132 * Static function for convert a date to a string according to a given format. Also acts as namespace for strftime format codes.
10133 * <p>strftime formatting can be accomplished without creating a jsDate object by calling jsDate.strftime():</p>
10134 * <pre class="code">
10135 * var formattedDate = jsDate.strftime('Feb 8, 2006 8:48:32', '%Y-%m-%d %H:%M:%S');
10137 * @param {String | Number | Array | jsDate Object | Date Object} date A parsable date string, JavaScript time stamp, Array of form [year, month, day, hours, minutes, seconds, milliseconds], jsDate Object or Date object.
10138 * @param {String} formatString String with embedded date formatting codes.
10139 * See: {@link jsDate.formats}.
10140 * @param {String} syntax Optional syntax to use [default perl].
10141 * @param {String} locale Optional locale to use.
10142 * @returns {String} Formatted representation of the date.
10145 // Logic as implemented here is very similar to Ken Snyder's Date Instance Methods.
10147 jsDate.strftime = function(d, formatString, syntax, locale) {
10149 var loc = jsDate.regional.getLocale();
10151 // check if syntax and locale are available or reversed
10152 if (syntax && jsDate.formats.hasOwnProperty(syntax)) {
10155 else if (syntax && jsDate.regional.hasOwnProperty(syntax)) {
10159 if (locale && jsDate.formats.hasOwnProperty(locale)) {
10162 else if (locale && jsDate.regional.hasOwnProperty(locale)) {
10166 if (get_type(d) != "[object Object]" || d._type != "jsDate") {
10170 if (!formatString) {
10171 formatString = d.formatString || jsDate.regional[loc]['formatString'];
10173 // default the format string to year-month-day
10174 var source = formatString || '%Y-%m-%d',
10177 // replace each format code
10178 while (source.length > 0) {
10179 if (match = source.match(jsDate.formats[syn].codes.matcher)) {
10180 result += source.slice(0, match.index);
10181 result += (match[1] || '') + format(d, match[2], syn);
10182 source = source.slice(match.index + match[0].length);
10193 * Namespace to hold format codes and format shortcuts. "perl" and "php" format codes
10194 * and shortcuts are defined by default. Additional codes and shortcuts can be
10197 * <pre class="code">
10198 * jsDate.formats["perl"] = {
10200 * matcher: /someregex/,
10201 * Y: "fullYear", // name of "get" method without the "get",
10202 * ..., // more codes
10206 * ..., // more shortcuts
10211 * <p>Additionally, ISO and SQL shortcuts are defined and can be accesses via:
10212 * <code>jsDate.formats.ISO</code> and <code>jsDate.formats.SQL</code>
10216 ISO:'%Y-%m-%dT%H:%M:%S.%N%G',
10217 SQL:'%Y-%m-%d %H:%M:%S'
10221 * Perl format codes and shortcuts for strftime.
10223 * A hash (object) of codes where each code must be an array where the first member is
10224 * the name of a Date.prototype or jsDate.prototype function to call
10225 * and optionally a second member indicating the number to pass to addZeros()
10227 * <p>The following format codes are defined:</p>
10229 * <pre class="code">
10230 * Code Result Description
10232 * %Y 2008 Four-digit year
10233 * %y 08 Two-digit year
10236 * %m 09 Two-digit month
10237 * %#m 9 One or two-digit month
10238 * %B September Full month name
10239 * %b Sep Abbreviated month name
10242 * %d 05 Two-digit day of month
10243 * %#d 5 One or two-digit day of month
10244 * %e 5 One or two-digit day of month
10245 * %A Sunday Full name of the day of the week
10246 * %a Sun Abbreviated name of the day of the week
10247 * %w 0 Number of the day of the week (0 = Sunday, 6 = Saturday)
10250 * %H 23 Hours in 24-hour format (two digits)
10251 * %#H 3 Hours in 24-hour integer format (one or two digits)
10252 * %I 11 Hours in 12-hour format (two digits)
10253 * %#I 3 Hours in 12-hour integer format (one or two digits)
10257 * %M 09 Minutes (two digits)
10258 * %#M 9 Minutes (one or two digits)
10261 * %S 02 Seconds (two digits)
10262 * %#S 2 Seconds (one or two digits)
10263 * %s 1206567625723 Unix timestamp (Seconds past 1970-01-01 00:00:00)
10265 * == Milliseconds ==
10266 * %N 008 Milliseconds (three digits)
10267 * %#N 8 Milliseconds (one to three digits)
10270 * %O 360 difference in minutes between local time and GMT
10271 * %Z Mountain Standard Time Name of timezone as reported by browser
10272 * %G 06:00 Hours and minutes between GMT
10275 * %F 2008-03-26 %Y-%m-%d
10276 * %T 05:06:30 %H:%M:%S
10277 * %X 05:06:30 %H:%M:%S
10278 * %x 03/26/08 %m/%d/%y
10279 * %D 03/26/08 %m/%d/%y
10280 * %#c Wed Mar 26 15:31:00 2008 %a %b %e %H:%M:%S %Y
10281 * %v 3-Sep-2008 %e-%b-%Y
10283 * %r 03:31:00 PM %I:%M:%S %p
10288 * %% % Percent Symbol
10291 * <p>Formatting shortcuts that will be translated into their longer version.
10292 * Be sure that format shortcuts do not refer to themselves: this will cause an infinite loop.</p>
10294 * <p>Format codes and format shortcuts can be redefined after the jsDate
10295 * module is imported.</p>
10297 * <p>Note that if you redefine the whole hash (object), you must supply a "matcher"
10298 * regex for the parser. The default matcher is:</p>
10300 * <code>/()%(#?(%|[a-z]))/i</code>
10302 * <p>which corresponds to the Perl syntax used by default.</p>
10304 * <p>By customizing the matcher and format codes, nearly any strftime functionality is possible.</p>
10307 jsDate.formats.perl = {
10310 // 2-part regex matcher for format codes
10312 // first match must be the character before the code (to account for escaping)
10313 // second match must be the format code character(s)
10315 matcher: /()%(#?(%|[a-z]))/i,
10320 m: 'MonthNumber.2',
10321 '#m': 'MonthNumber',
10323 b: 'AbbrMonthName',
10345 N: 'Milliseconds.3',
10346 '#N': 'Milliseconds',
10348 O: 'TimezoneOffset',
10359 // local format date
10362 // local format extended
10363 '#c': '%a %b %e %H:%M:%S %Y',
10364 // local format short
10376 * PHP format codes and shortcuts for strftime.
10378 * A hash (object) of codes where each code must be an array where the first member is
10379 * the name of a Date.prototype or jsDate.prototype function to call
10380 * and optionally a second member indicating the number to pass to addZeros()
10382 * <p>The following format codes are defined:</p>
10384 * <pre class="code">
10385 * Code Result Description
10387 * %a Sun through Sat An abbreviated textual representation of the day
10388 * %A Sunday - Saturday A full textual representation of the day
10389 * %d 01 to 31 Two-digit day of the month (with leading zeros)
10390 * %e 1 to 31 Day of the month, with a space preceding single digits.
10391 * %j 001 to 366 Day of the year, 3 digits with leading zeros
10392 * %u 1 - 7 (Mon - Sun) ISO-8601 numeric representation of the day of the week
10393 * %w 0 - 6 (Sun - Sat) Numeric representation of the day of the week
10396 * %U 13 Full Week number, starting with the first Sunday as the first week
10397 * %V 01 through 53 ISO-8601:1988 week number, starting with the first week of the year
10398 * with at least 4 weekdays, with Monday being the start of the week
10399 * %W 46 A numeric representation of the week of the year,
10400 * starting with the first Monday as the first week
10402 * %b Jan through Dec Abbreviated month name, based on the locale
10403 * %B January - December Full month name, based on the locale
10404 * %h Jan through Dec Abbreviated month name, based on the locale (an alias of %b)
10405 * %m 01 - 12 (Jan - Dec) Two digit representation of the month
10408 * %C 19 Two digit century (year/100, truncated to an integer)
10409 * %y 09 for 2009 Two digit year
10410 * %Y 2038 Four digit year
10413 * %H 00 through 23 Two digit representation of the hour in 24-hour format
10414 * %I 01 through 12 Two digit representation of the hour in 12-hour format
10415 * %l 1 through 12 Hour in 12-hour format, with a space preceeding single digits
10416 * %M 00 through 59 Two digit representation of the minute
10417 * %p AM/PM UPPER-CASE 'AM' or 'PM' based on the given time
10418 * %P am/pm lower-case 'am' or 'pm' based on the given time
10419 * %r 09:34:17 PM Same as %I:%M:%S %p
10420 * %R 00:35 Same as %H:%M
10421 * %S 00 through 59 Two digit representation of the second
10422 * %T 21:34:17 Same as %H:%M:%S
10423 * %X 03:59:16 Preferred time representation based on locale, without the date
10424 * %z -0500 or EST Either the time zone offset from UTC or the abbreviation
10425 * %Z -0500 or EST The time zone offset/abbreviation option NOT given by %z
10427 * === Time and Date ===
10428 * %D 02/05/09 Same as %m/%d/%y
10429 * %F 2009-02-05 Same as %Y-%m-%d (commonly used in database datestamps)
10430 * %s 305815200 Unix Epoch Time timestamp (same as the time() function)
10431 * %x 02/05/09 Preferred date representation, without the time
10433 * === Miscellaneous ===
10434 * %n --- A newline character (\n)
10435 * %t --- A Tab character (\t)
10436 * %% --- A literal percentage character (%)
10440 jsDate.formats.php = {
10443 // 2-part regex matcher for format codes
10445 // first match must be the character before the code (to account for escaping)
10446 // second match must be the format code character(s)
10448 matcher: /()%((%|[a-z]))/i,
10458 U: 'FullWeekOfYear.2',
10462 b: 'AbbrMonthName',
10464 m: 'MonthNumber.2',
10465 h: 'AbbrMonthName',
10479 O: 'TimezoneOffset',
10498 // Conceptually, the logic implemented here is similar to Ken Snyder's Date Instance Methods.
10499 // I use his idea of a set of parsers which can be regular expressions or functions,
10500 // iterating through those, and then seeing if Date.parse() will create a date.
10501 // The parser expressions and functions are a little different and some bugs have been
10502 // worked out. Also, a lot of "pre-parsing" is done to fix implementation
10503 // variations of Date.parse() between browsers.
10505 jsDate.createDate = function(date) {
10506 // if passing in multiple arguments, try Date constructor
10507 if (date == null) {
10510 // If the passed value is already a date object, return it
10511 if (date instanceof Date) {
10514 // if (typeof date == 'number') return new Date(date * 1000);
10515 // If the passed value is an integer, interpret it as a javascript timestamp
10516 if (typeof date == 'number') {
10517 return new Date(date);
10520 // Before passing strings into Date.parse(), have to normalize them for certain conditions.
10521 // If strings are not formatted staccording to the EcmaScript spec, results from Date parse will be implementation dependent.
10524 // * FF and Opera assume 2 digit dates are pre y2k, Chome assumes <50 is pre y2k, 50+ is 21st century.
10525 // * Chrome will correctly parse '1984-1-25' into localtime, FF and Opera will not parse.
10526 // * Both FF, Chrome and Opera will parse '1984/1/25' into localtime.
10528 // remove leading and trailing spaces
10529 var parsable = String(date).replace(/^\s*(.+)\s*$/g, '$1');
10531 // replace dahses (-) with slashes (/) in dates like n[nnn]/n[n]/n[nnn]
10532 parsable = parsable.replace(/^([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,4})/, "$1/$2/$3");
10535 // Need to check for '15-Dec-09' also.
10536 // FF will not parse, but Chrome will.
10537 // Chrome will set date to 2009 as well.
10540 // first check for 'dd-mmm-yyyy' or 'dd/mmm/yyyy' like '15-Dec-2010'
10541 parsable = parsable.replace(/^(3[01]|[0-2]?\d)[-\/]([a-z]{3,})[-\/](\d{4})/i, "$1 $2 $3");
10543 // Now check for 'dd-mmm-yy' or 'dd/mmm/yy' and normalize years to default century.
10544 var match = parsable.match(/^(3[01]|[0-2]?\d)[-\/]([a-z]{3,})[-\/](\d{2})\D*/i);
10545 if (match && match.length > 3) {
10546 var m3 = parseFloat(match[3]);
10547 var ny = jsDate.config.defaultCentury + m3;
10550 // now replace 2 digit year with 4 digit year
10551 parsable = parsable.replace(/^(3[01]|[0-2]?\d)[-\/]([a-z]{3,})[-\/](\d{2})\D*/i, match[1] +' '+ match[2] +' '+ ny);
10555 // Check for '1/19/70 8:14PM'
10556 // where starts with mm/dd/yy or yy/mm/dd and have something after
10557 // Check if 1st postiion is greater than 31, assume it is year.
10558 // Assme all 2 digit years are 1900's.
10559 // Finally, change them into US style mm/dd/yyyy representations.
10560 match = parsable.match(/^([0-9]{1,2})[-\/]([0-9]{1,2})[-\/]([0-9]{1,2})[^0-9]/);
10562 function h1(parsable, match) {
10563 var m1 = parseFloat(match[1]);
10564 var m2 = parseFloat(match[2]);
10565 var m3 = parseFloat(match[3]);
10566 var cent = jsDate.config.defaultCentury;
10567 var ny, nd, nm, str;
10569 if (m1 > 31) { // first number is a year
10575 else { // last number is the year
10581 str = nm+'/'+nd+'/'+ny;
10583 // now replace 2 digit year with 4 digit year
10584 return parsable.replace(/^([0-9]{1,2})[-\/]([0-9]{1,2})[-\/]([0-9]{1,2})/, str);
10588 if (match && match.length > 3) {
10589 parsable = h1(parsable, match);
10592 // Now check for '1/19/70' with nothing after and do as above
10593 var match = parsable.match(/^([0-9]{1,2})[-\/]([0-9]{1,2})[-\/]([0-9]{1,2})$/);
10595 if (match && match.length > 3) {
10596 parsable = h1(parsable, match);
10601 var length = jsDate.matchers.length;
10604 current = parsable,
10606 while (i < length) {
10607 ms = Date.parse(current);
10609 return new Date(ms);
10611 pattern = jsDate.matchers[i];
10612 if (typeof pattern == 'function') {
10613 obj = pattern.call(jsDate, current);
10614 if (obj instanceof Date) {
10618 current = parsable.replace(pattern[0], pattern[1]);
10628 * Handy static utility function to return the number of days in a given month.
10629 * @param {Integer} year Year
10630 * @param {Integer} month Month (1-12)
10631 * @returns {Integer} Number of days in the month.
10634 // handy utility method Borrowed right from Ken Snyder's Date Instance Mehtods.
10636 jsDate.daysInMonth = function(year, month) {
10638 return new Date(year, 1, 29).getDate() == 29 ? 29 : 28;
10640 return [undefined,31,undefined,31,30,31,30,31,31,30,31,30,31][month];
10645 // An Array of regular expressions or functions that will attempt to match the date string.
10646 // Functions are called with scope of a jsDate instance.
10648 jsDate.matchers = [
10649 // convert dd.mmm.yyyy to mm/dd/yyyy (world date to US date).
10650 [/(3[01]|[0-2]\d)\s*\.\s*(1[0-2]|0\d)\s*\.\s*([1-9]\d{3})/, '$2/$1/$3'],
10651 // convert yyyy-mm-dd to mm/dd/yyyy (ISO date to US date).
10652 [/([1-9]\d{3})\s*-\s*(1[0-2]|0\d)\s*-\s*(3[01]|[0-2]\d)/, '$2/$3/$1'],
10653 // Handle 12 hour or 24 hour time with milliseconds am/pm and optional date part.
10655 var match = str.match(/^(?:(.+)\s+)?([012]?\d)(?:\s*\:\s*(\d\d))?(?:\s*\:\s*(\d\d(\.\d*)?))?\s*(am|pm)?\s*$/i);
10656 // opt. date hour opt. minute opt. second opt. msec opt. am or pm
10659 var d = this.createDate(match[1]);
10664 var d = new Date();
10665 d.setMilliseconds(0);
10667 var hour = parseFloat(match[2]);
10669 hour = match[6].toLowerCase() == 'am' ? (hour == 12 ? 0 : hour) : (hour == 12 ? 12 : hour + 12);
10671 d.setHours(hour, parseInt(match[3] || 0, 10), parseInt(match[4] || 0, 10), ((parseFloat(match[5] || 0)) || 0)*1000);
10678 // Handle ISO timestamp with time zone.
10680 var match = str.match(/^(?:(.+))[T|\s+]([012]\d)(?:\:(\d\d))(?:\:(\d\d))(?:\.\d+)([\+\-]\d\d\:\d\d)$/i);
10683 var d = this.createDate(match[1]);
10688 var d = new Date();
10689 d.setMilliseconds(0);
10691 var hour = parseFloat(match[2]);
10692 d.setHours(hour, parseInt(match[3], 10), parseInt(match[4], 10), parseFloat(match[5])*1000);
10699 // Try to match ambiguous strings like 12/8/22.
10700 // Use FF date assumption that 2 digit years are 20th century (i.e. 1900's).
10701 // This may be redundant with pre processing of date already performed.
10703 var match = str.match(/^([0-3]?\d)\s*[-\/.\s]{1}\s*([a-zA-Z]{3,9})\s*[-\/.\s]{1}\s*([0-3]?\d)$/);
10705 var d = new Date();
10706 var cent = jsDate.config.defaultCentury;
10707 var m1 = parseFloat(match[1]);
10708 var m3 = parseFloat(match[3]);
10710 if (m1 > 31) { // first number is a year
10715 else { // last number is the year
10720 var nm = inArray(match[2], jsDate.regional[jsDate.regional.getLocale()]["monthNamesShort"]);
10723 nm = inArray(match[2], jsDate.regional[jsDate.regional.getLocale()]["monthNames"]);
10726 d.setFullYear(ny, nm, nd);
10727 d.setHours(0,0,0,0);
10738 // I think John Reisig published this method on his blog, ejohn.
10740 function inArray( elem, array ) {
10741 if ( array.indexOf ) {
10742 return array.indexOf( elem );
10745 for ( var i = 0, length = array.length; i < length; i++ ) {
10746 if ( array[ i ] === elem ) {
10755 // Thanks to Kangax, Christian Sciberras and Stack Overflow for this method.
10757 function get_type(thing){
10758 if(thing===null) return "[object Null]"; // special case
10759 return Object.prototype.toString.call(thing);
10766 * JavaScript printf/sprintf functions.
10768 * This code has been adapted from the publicly available sprintf methods
10769 * by Ash Searle. His original header follows:
10771 * This code is unrestricted: you are free to use it however you like.
10773 * The functions should work as expected, performing left or right alignment,
10774 * truncating strings, outputting numbers with a required precision etc.
10776 * For complex cases, these functions follow the Perl implementations of
10777 * (s)printf, allowing arguments to be passed out-of-order, and to set the
10778 * precision or length of the output based on arguments instead of fixed
10781 * See http://perldoc.perl.org/functions/sprintf.html for more information.
10784 * - zero and space-padding
10785 * - right and left-alignment,
10786 * - base X prefix (binary, octal and hex)
10787 * - positive number prefix
10788 * - (minimum) width
10789 * - precision / truncation / maximum width
10790 * - out of order arguments
10792 * Not implemented (yet):
10794 * - size (bytes, words, long-words etc.)
10796 * Will not implement:
10797 * - %n or %p (no pass-by-reference in JavaScript)
10799 * @version 2007.04.27
10800 * @author Ash Searle
10802 * You can see the original work and comments on his blog:
10803 * http://hexmen.com/blog/2007/03/printf-sprintf/
10804 * http://hexmen.com/js/sprintf.js
10808 * @Modifications 2009.05.26
10809 * @author Chris Leonello
10811 * Added %p %P specifier
10812 * Acts like %g or %G but will not add more significant digits to the output than present in the input.
10814 * Format: '%.3p', Input: 0.012, Output: 0.012
10815 * Format: '%.3g', Input: 0.012, Output: 0.0120
10816 * Format: '%.4p', Input: 12.0, Output: 12.0
10817 * Format: '%.4g', Input: 12.0, Output: 12.00
10818 * Format: '%.4p', Input: 4.321e-5, Output: 4.321e-5
10819 * Format: '%.4g', Input: 4.321e-5, Output: 4.3210e-5
10822 * >>> $.jqplot.sprintf('%.2f, %d', 23.3452, 43.23)
10824 * >>> $.jqplot.sprintf("no value: %n, decimal with thousands separator: %'d", 23.3452, 433524)
10825 * "no value: , decimal with thousands separator: 433,524"
10827 $.jqplot.sprintf = function() {
10828 function pad(str, len, chr, leftJustify) {
10829 var padding = (str.length >= len) ? '' : Array(1 + len - str.length >>> 0).join(chr);
10830 return leftJustify ? str + padding : padding + str;
10834 function thousand_separate(value) {
10835 var value_str = new String(value);
10836 for (var i=10; i>0; i--) {
10837 if (value_str == (value_str = value_str.replace(/^(\d+)(\d{3})/, "$1"+$.jqplot.sprintf.thousandsSeparator+"$2"))) break;
10842 function justify(value, prefix, leftJustify, minWidth, zeroPad, htmlSpace) {
10843 var diff = minWidth - value.length;
10846 if (htmlSpace) { spchar = ' '; }
10847 if (leftJustify || !zeroPad) {
10848 value = pad(value, minWidth, spchar, leftJustify);
10850 value = value.slice(0, prefix.length) + pad('', diff, '0', true) + value.slice(prefix.length);
10856 function formatBaseX(value, base, prefix, leftJustify, minWidth, precision, zeroPad, htmlSpace) {
10857 // Note: casts negative numbers to positive ones
10858 var number = value >>> 0;
10859 prefix = prefix && number && {'2': '0b', '8': '0', '16': '0x'}[base] || '';
10860 value = prefix + pad(number.toString(base), precision || 0, '0', false);
10861 return justify(value, prefix, leftJustify, minWidth, zeroPad, htmlSpace);
10864 function formatString(value, leftJustify, minWidth, precision, zeroPad, htmlSpace) {
10865 if (precision != null) {
10866 value = value.slice(0, precision);
10868 return justify(value, '', leftJustify, minWidth, zeroPad, htmlSpace);
10871 var a = arguments, i = 0, format = a[i++];
10873 return format.replace($.jqplot.sprintf.regex, function(substring, valueIndex, flags, minWidth, _, precision, type) {
10874 if (substring == '%%') { return '%'; }
10877 var leftJustify = false, positivePrefix = '', zeroPad = false, prefixBaseX = false, htmlSpace = false, thousandSeparation = false;
10878 for (var j = 0; flags && j < flags.length; j++) switch (flags.charAt(j)) {
10879 case ' ': positivePrefix = ' '; break;
10880 case '+': positivePrefix = '+'; break;
10881 case '-': leftJustify = true; break;
10882 case '0': zeroPad = true; break;
10883 case '#': prefixBaseX = true; break;
10884 case '&': htmlSpace = true; break;
10885 case '\'': thousandSeparation = true; break;
10888 // parameters may be null, undefined, empty-string or real valued
10889 // we want to ignore null, undefined and empty-string values
10894 else if (minWidth == '*') {
10895 minWidth = +a[i++];
10897 else if (minWidth.charAt(0) == '*') {
10898 minWidth = +a[minWidth.slice(1, -1)];
10901 minWidth = +minWidth;
10904 // Note: undocumented perl feature:
10905 if (minWidth < 0) {
10906 minWidth = -minWidth;
10907 leftJustify = true;
10910 if (!isFinite(minWidth)) {
10911 throw new Error('$.jqplot.sprintf: (minimum-)width must be finite');
10915 precision = 'fFeE'.indexOf(type) > -1 ? 6 : (type == 'd') ? 0 : void(0);
10917 else if (precision == '*') {
10918 precision = +a[i++];
10920 else if (precision.charAt(0) == '*') {
10921 precision = +a[precision.slice(1, -1)];
10924 precision = +precision;
10927 // grab value using valueIndex if required?
10928 var value = valueIndex ? a[valueIndex.slice(0, -1)] : a[i++];
10932 if (value == null) {
10935 return formatString(String(value), leftJustify, minWidth, precision, zeroPad, htmlSpace);
10937 case 'c': return formatString(String.fromCharCode(+value), leftJustify, minWidth, precision, zeroPad, htmlSpace);
10938 case 'b': return formatBaseX(value, 2, prefixBaseX, leftJustify, minWidth, precision, zeroPad,htmlSpace);
10939 case 'o': return formatBaseX(value, 8, prefixBaseX, leftJustify, minWidth, precision, zeroPad, htmlSpace);
10940 case 'x': return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad, htmlSpace);
10941 case 'X': return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad, htmlSpace).toUpperCase();
10942 case 'u': return formatBaseX(value, 10, prefixBaseX, leftJustify, minWidth, precision, zeroPad, htmlSpace);
10944 var number = parseInt(+value, 10);
10945 if (isNaN(number)) {
10948 var prefix = number < 0 ? '-' : positivePrefix;
10949 var number_str = thousandSeparation ? thousand_separate(String(Math.abs(number))): String(Math.abs(number));
10950 value = prefix + pad(number_str, precision, '0', false);
10951 //value = prefix + pad(String(Math.abs(number)), precision, '0', false);
10952 return justify(value, prefix, leftJustify, minWidth, zeroPad, htmlSpace);
10955 var number = Math.round(+value);
10956 if (isNaN(number)) {
10959 var prefix = number < 0 ? '-' : positivePrefix;
10960 var number_str = thousandSeparation ? thousand_separate(String(Math.abs(number))): String(Math.abs(number));
10961 value = prefix + pad(number_str, precision, '0', false);
10962 return justify(value, prefix, leftJustify, minWidth, zeroPad, htmlSpace);
10971 var number = +value;
10972 if (isNaN(number)) {
10975 var prefix = number < 0 ? '-' : positivePrefix;
10976 var method = ['toExponential', 'toFixed', 'toPrecision']['efg'.indexOf(type.toLowerCase())];
10977 var textTransform = ['toString', 'toUpperCase']['eEfFgG'.indexOf(type) % 2];
10978 var number_str = Math.abs(number)[method](precision);
10979 number_str = thousandSeparation ? thousand_separate(number_str): number_str;
10980 value = prefix + number_str;
10981 var justified = justify(value, prefix, leftJustify, minWidth, zeroPad, htmlSpace)[textTransform]();
10983 if ($.jqplot.sprintf.decimalMark !== '.' && $.jqplot.sprintf.decimalMark !== $.jqplot.sprintf.thousandsSeparator) {
10984 return justified.replace(/\./, $.jqplot.sprintf.decimalMark);
10992 // make sure number is a number
10993 var number = +value;
10994 if (isNaN(number)) {
10997 var prefix = number < 0 ? '-' : positivePrefix;
10999 var parts = String(Number(Math.abs(number)).toExponential()).split(/e|E/);
11000 var sd = (parts[0].indexOf('.') != -1) ? parts[0].length - 1 : parts[0].length;
11001 var zeros = (parts[1] < 0) ? -parts[1] - 1 : 0;
11003 if (Math.abs(number) < 1) {
11004 if (sd + zeros <= precision) {
11005 value = prefix + Math.abs(number).toPrecision(sd);
11008 if (sd <= precision - 1) {
11009 value = prefix + Math.abs(number).toExponential(sd-1);
11012 value = prefix + Math.abs(number).toExponential(precision-1);
11017 var prec = (sd <= precision) ? sd : precision;
11018 value = prefix + Math.abs(number).toPrecision(prec);
11020 var textTransform = ['toString', 'toUpperCase']['pP'.indexOf(type) % 2];
11021 return justify(value, prefix, leftJustify, minWidth, zeroPad, htmlSpace)[textTransform]();
11023 case 'n': return '';
11024 default: return substring;
11029 $.jqplot.sprintf.thousandsSeparator = ',';
11030 // Specifies the decimal mark for floating point values. By default a period '.'
11031 // is used. If you change this value to for example a comma be sure to also
11032 // change the thousands separator or else this won't work since a simple String
11033 // replace is used (replacing all periods with the mark specified here).
11034 $.jqplot.sprintf.decimalMark = '.';
11036 $.jqplot.sprintf.regex = /%%|%(\d+\$)?([-+#0&\' ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([nAscboxXuidfegpEGP])/g;
11038 $.jqplot.getSignificantFigures = function(number) {
11039 var parts = String(Number(Math.abs(number)).toExponential()).split(/e|E/);
11040 // total significant digits
11041 var sd = (parts[0].indexOf('.') != -1) ? parts[0].length - 1 : parts[0].length;
11042 var zeros = (parts[1] < 0) ? -parts[1] - 1 : 0;
11044 var expn = parseInt(parts[1], 10);
11045 // digits to the left of the decimal place
11046 var dleft = (expn + 1 > 0) ? expn + 1 : 0;
11047 // digits to the right of the decimal place
11048 var dright = (sd <= dleft) ? 0 : sd - expn - 1;
11049 return {significantDigits: sd, digitsLeft: dleft, digitsRight: dright, zeros: zeros, exponent: expn} ;
11052 $.jqplot.getPrecision = function(number) {
11053 return $.jqplot.getSignificantFigures(number).digitsRight;
11059 var backCompat = $.uiBackCompat !== false;
11061 $.jqplot.effects = {
11065 // prefix used for storing data on .data()
11066 var dataSpace = "jqplot.storage.";
11068 /******************************************************************************/
11069 /*********************************** EFFECTS **********************************/
11070 /******************************************************************************/
11072 $.extend( $.jqplot.effects, {
11075 // Saves a set of properties in a data storage
11076 save: function( element, set ) {
11077 for( var i=0; i < set.length; i++ ) {
11078 if ( set[ i ] !== null ) {
11079 element.data( dataSpace + set[ i ], element[ 0 ].style[ set[ i ] ] );
11084 // Restores a set of previously saved properties from a data storage
11085 restore: function( element, set ) {
11086 for( var i=0; i < set.length; i++ ) {
11087 if ( set[ i ] !== null ) {
11088 element.css( set[ i ], element.data( dataSpace + set[ i ] ) );
11093 setMode: function( el, mode ) {
11094 if (mode === "toggle") {
11095 mode = el.is( ":hidden" ) ? "show" : "hide";
11100 // Wraps the element around a wrapper that copies position properties
11101 createWrapper: function( element ) {
11103 // if the element is already wrapped, return it
11104 if ( element.parent().is( ".ui-effects-wrapper" )) {
11105 return element.parent();
11108 // wrap the element
11110 width: element.outerWidth(true),
11111 height: element.outerHeight(true),
11112 "float": element.css( "float" )
11114 wrapper = $( "<div></div>" )
11115 .addClass( "ui-effects-wrapper" )
11118 background: "transparent",
11123 // Store the size in case width/height are defined in % - Fixes #5245
11125 width: element.width(),
11126 height: element.height()
11128 active = document.activeElement;
11130 element.wrap( wrapper );
11132 // Fixes #7595 - Elements lose focus when wrapped.
11133 if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) {
11134 $( active ).focus();
11137 wrapper = element.parent(); //Hotfix for jQuery 1.4 since some change in wrap() seems to actually loose the reference to the wrapped element
11139 // transfer positioning properties to the wrapper
11140 if ( element.css( "position" ) === "static" ) {
11141 wrapper.css({ position: "relative" });
11142 element.css({ position: "relative" });
11145 position: element.css( "position" ),
11146 zIndex: element.css( "z-index" )
11148 $.each([ "top", "left", "bottom", "right" ], function(i, pos) {
11149 props[ pos ] = element.css( pos );
11150 if ( isNaN( parseInt( props[ pos ], 10 ) ) ) {
11151 props[ pos ] = "auto";
11155 position: "relative",
11164 return wrapper.css( props ).show();
11167 removeWrapper: function( element ) {
11168 var active = document.activeElement;
11170 if ( element.parent().is( ".ui-effects-wrapper" ) ) {
11171 element.parent().replaceWith( element );
11173 // Fixes #7595 - Elements lose focus when wrapped.
11174 if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) {
11175 $( active ).focus();
11184 // return an effect options object for the given parameters:
11185 function _normalizeArguments( effect, options, speed, callback ) {
11187 // short path for passing an effect options object:
11188 if ( $.isPlainObject( effect ) ) {
11192 // convert to an object
11193 effect = { effect: effect };
11196 if ( options === undefined ) {
11200 // catch (effect, callback)
11201 if ( $.isFunction( options ) ) {
11202 callback = options;
11207 // catch (effect, speed, ?)
11208 if ( $.type( options ) === "number" || $.fx.speeds[ options ]) {
11214 // catch (effect, options, callback)
11215 if ( $.isFunction( speed ) ) {
11220 // add options to effect
11222 $.extend( effect, options );
11225 speed = speed || options.duration;
11226 effect.duration = $.fx.off ? 0 : typeof speed === "number"
11227 ? speed : speed in $.fx.speeds ? $.fx.speeds[ speed ] : $.fx.speeds._default;
11229 effect.complete = callback || options.complete;
11234 function standardSpeed( speed ) {
11235 // valid standard speeds
11236 if ( !speed || typeof speed === "number" || $.fx.speeds[ speed ] ) {
11240 // invalid strings - treat as "normal" speed
11241 if ( typeof speed === "string" && !$.jqplot.effects.effect[ speed ] ) {
11242 // TODO: remove in 2.0 (#7115)
11243 if ( backCompat && $.jqplot.effects[ speed ] ) {
11253 jqplotEffect: function( effect, options, speed, callback ) {
11254 var args = _normalizeArguments.apply( this, arguments ),
11256 queue = args.queue,
11257 effectMethod = $.jqplot.effects.effect[ args.effect ],
11259 // DEPRECATED: remove in 2.0 (#7115)
11260 oldEffectMethod = !effectMethod && backCompat && $.jqplot.effects[ args.effect ];
11262 if ( $.fx.off || !( effectMethod || oldEffectMethod ) ) {
11263 // delegate to the original method (e.g., .show()) if possible
11265 return this[ mode ]( args.duration, args.complete );
11267 return this.each( function() {
11268 if ( args.complete ) {
11269 args.complete.call( this );
11275 function run( next ) {
11276 var elem = $( this ),
11277 complete = args.complete,
11281 if ( $.isFunction( complete ) ) {
11282 complete.call( elem[0] );
11284 if ( $.isFunction( next ) ) {
11289 // if the element is hiddden and mode is hide,
11290 // or element is visible and mode is show
11291 if ( elem.is( ":hidden" ) ? mode === "hide" : mode === "show" ) {
11294 effectMethod.call( elem[0], args, done );
11298 // TODO: remove this check in 2.0, effectMethod will always be true
11299 if ( effectMethod ) {
11300 return queue === false ? this.each( run ) : this.queue( queue || "fx", run );
11302 // DEPRECATED: remove in 2.0 (#7115)
11303 return oldEffectMethod.call(this, {
11305 duration: args.duration,
11306 callback: args.complete,
11316 var rvertical = /up|down|vertical/,
11317 rpositivemotion = /up|left|vertical|horizontal/;
11319 $.jqplot.effects.effect.blind = function( o, done ) {
11321 var el = $( this ),
11322 props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
11323 mode = $.jqplot.effects.setMode( el, o.mode || "hide" ),
11324 direction = o.direction || "up",
11325 vertical = rvertical.test( direction ),
11326 ref = vertical ? "height" : "width",
11327 ref2 = vertical ? "top" : "left",
11328 motion = rpositivemotion.test( direction ),
11330 show = mode === "show",
11331 wrapper, distance, top;
11333 // // if already wrapped, the wrapper's properties are my property. #6245
11334 if ( el.parent().is( ".ui-effects-wrapper" ) ) {
11335 $.jqplot.effects.save( el.parent(), props );
11337 $.jqplot.effects.save( el, props );
11340 top = parseInt(el.css('top'), 10);
11341 wrapper = $.jqplot.effects.createWrapper( el ).css({
11345 distance = vertical ? wrapper[ ref ]() + top : wrapper[ ref ]();
11347 animation[ ref ] = show ? String(distance) : '0';
11350 .css( vertical ? "bottom" : "right", 0 )
11351 .css( vertical ? "top" : "left", "" )
11352 .css({ position: "absolute" });
11353 animation[ ref2 ] = show ? '0' : String(distance);
11356 // // start at 0 if we are showing
11358 wrapper.css( ref, 0 );
11360 wrapper.css( ref2, distance );
11365 wrapper.animate( animation, {
11366 duration: o.duration,
11369 complete: function() {
11370 if ( mode === "hide" ) {
11373 $.jqplot.effects.restore( el, props );
11374 $.jqplot.effects.removeWrapper( el );