first commit
[wnstats.git] / public / javascripts / jqplot / jquery.jqplot.js
blobcded47ab72313ce0f724a276ef6596aa201623e2
1 /**
2  * Title: jqPlot Charts
3  * 
4  * Pure JavaScript plotting plugin for jQuery.
5  * 
6  * About: Version
7  * 
8  * version: 1.0.4 
9  * revision: 1121
10  * 
11  * About: Copyright & License
12  * 
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.
17  * 
18  * See <GPL Version 2> and <MIT License> contained within this distribution for further information. 
19  *
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.
23  *
24  * If you are feeling kind and generous, consider supporting the project by
25  * making a donation at: http://www.jqplot.com/donate.php.
26  *
27  * sprintf functions contained in jqplot.sprintf.js by Ash Searle:
28  * 
29  *     version 2007.04.27
30  *     author 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."
35  * 
36  * 
37  * About: Introduction
38  * 
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:
42  * 
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" />
47  * 
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:
50  * 
51  * > chart = $.jqplot('targetElemId', [dataArray,...], {optionsObject});
52  * 
53  * The options available to jqplot are detailed in <jqPlot Options> in the jqPlotOptions.txt file.
54  * 
55  * An actual call to $.jqplot() may look like the 
56  * examples below:
57  * 
58  * > chart = $.jqplot('chartdiv',  [[[1, 2],[3,5.12],[5,13.1],[7,33.6],[9,85.9],[11,219.9]]]);
59  * 
60  * or
61  * 
62  * > dataArray = [34,12,43,55,77];
63  * > chart = $.jqplot('targetElemId', [dataArray, ...], {title:'My Plot', axes:{yaxis:{min:20, max:100}}});
64  * 
65  * For more inforrmation, see <jqPlot Usage>.
66  * 
67  * About: Usage
68  * 
69  * See <jqPlot Usage>
70  * 
71  * About: Available Options 
72  * 
73  * See <jqPlot Options> for a list of options available thorugh the options object (not complete yet!)
74  * 
75  * About: Options Usage
76  * 
77  * See <Options Tutorial>
78  * 
79  * About: Changes
80  * 
81  * See <Change Log>
82  * 
83  */
85 (function($) {
86     // make sure undefined is undefined
87     var undefined;
88     
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("*") );
94         }
95   
96         // Remove any remaining nodes
97         if ($.jqplot.use_excanvas) {
98           elem.outerHTML = "";
99         }
100         else {
101           while ( elem.firstChild ) {
102             elem.removeChild( elem.firstChild );
103           }
104         }
106         elem = null;
107       }
108   
109       return $(this);
110     };
111   
112     $.fn.removeChildForce = function(parent) {
113       while ( parent.firstChild ) {
114         this.removeChildForce( parent.firstChild );
115         parent.removeChild( parent.firstChild );
116       }
117     };
119     $.fn.jqplot = function() {
120         var datas = [];
121         var options = [];
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]);
126             }
127             else if ($.isPlainObject(arguments[i])) {
128                 options.push(arguments[i]);
129             }
130         }
132         return this.each(function(index) {
133             var tid, 
134                 plot, 
135                 $this = $(this),
136                 dl = datas.length,
137                 ol = options.length,
138                 data, 
139                 opts;
141             if (index < dl) {
142                 data = datas[index];
143             }
144             else {
145                 data = dl ? datas[dl-1] : null;
146             }
148             if (index < ol) {
149                 opts = options[index];
150             }
151             else {
152                 opts = ol ? options[ol-1] : null;
153             }
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);
161             }
163             plot = $.jqplot(tid, data, opts);
165             $this.data('jqplot', plot);
166         });
167     };
170     /**
171      * Namespace: $.jqplot
172      * jQuery function called by the user to create a plot.
173      *  
174      * Parameters:
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.
178      * 
179      * Properties:
180      * config - object to hold configuration information for jqPlot plot object.
181      * 
182      * attributes:
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.
192      */
194     $.jqplot = function(target, data, options) {
195         var _data = null, _options = null;
197         if (arguments.length === 3) {
198             _data = data;
199             _options = options;
200         }
202         else if (arguments.length === 2) {
203             if ($.isArray(data)) {
204                 _data = data;
205             }
207             else if ($.isPlainObject(data)) {
208                 _options = data;
209             }
210         }
212         if (_data === null && _options !== null && _options.data) {
213             _data = _options.data;
214         }
216         var plot = new jqPlot();
217         // remove any error class that may be stuck on target.
218         $('#'+target).removeClass('jqplot-error');
219         
220         if ($.jqplot.config.catchErrors) {
221             try {
222                 plot.init(target, _data, _options);
223                 plot.draw();
224                 plot.themeEngine.init.call(plot);
225                 return plot;
226             }
227             catch(e) {
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;
237             }
238         }
239         else {        
240             plot.init(target, _data, _options);
241             plot.draw();
242             plot.themeEngine.init.call(plot);
243             return plot;
244         }
245     };
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 = [];
261         }
262         
263         var myCanvases = [];
264         
265         this.getCanvas = function() {
266             var canvas;
267             var makeNew = true;
268             
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) {
272                         makeNew = false;
273                         canvas = $.jqplot.CanvasManager.canvases[i];
274                         // $(canvas).removeClass('jqplot-canvasManager-free').addClass('jqplot-canvasManager-inuse');
275                         $.jqplot.CanvasManager.free[i] = false;
276                         myCanvases.push(i);
277                         break;
278                     }
279                 }
280             }
282             if (makeNew) {
283                 canvas = document.createElement('canvas');
284                 myCanvases.push($.jqplot.CanvasManager.canvases.length);
285                 $.jqplot.CanvasManager.canvases.push(canvas);
286                 $.jqplot.CanvasManager.free.push(false);
287             }   
288             
289             return canvas;
290         };
291         
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);
297             }
298             return canvas;
299         };
301         this.freeAllCanvases = function() {
302             for (var i = 0, l=myCanvases.length; i < l; i++) {
303                 this.freeCanvas(myCanvases[i]);
304             }
305             myCanvases = [];
306         };
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;
313             } 
314             else {
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?
322                 canvas.width = 0;
323                 canvas.height = 0;
324                 $.jqplot.CanvasManager.free[idx] = true;
325             }
326         };
327         
328     };
330             
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);
335         }
336     };
337         
338     $.jqplot.config = {
339         addDomReference: false,
340         enablePlugins:false,
341         defaultHeight:300,
342         defaultWidth:400,
343         UTCAdjust:false,
344         timezoneOffset: new Date(new Date().getTimezoneOffset() * 60000),
345         errorMessage: '',
346         errorBackground: '',
347         errorBorder: '',
348         errorFontFamily: '',
349         errorFontSize: '',
350         errorFontStyle: '',
351         errorFontWeight: '',
352         catchErrors: false,
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"],
356         dashLength: 4,
357         gapLength: 4,
358         dotGapLength: 2.5,
359         srcLocation: 'jqplot/src/',
360         pluginLocation: 'jqplot/src/plugins/'
361     };
362     
363     
364     $.jqplot.arrayMax = function( array ){
365         return Math.max.apply( Math, array );
366     };
367     
368     $.jqplot.arrayMin = function( array ){
369         return Math.min.apply( Math, array );
370     };
371     
372     $.jqplot.enablePlugins = $.jqplot.config.enablePlugins;
373     
374     // canvas related tests taken from modernizer:
375     // Copyright (c) 2009 - 2010 Faruk Ates.
376     // http://www.modernizr.com
377     
378     $.jqplot.support_canvas = function() {
379         if (typeof $.jqplot.support_canvas.result == 'undefined') {
380             $.jqplot.support_canvas.result = !!document.createElement('canvas').getContext; 
381         }
382         return $.jqplot.support_canvas.result;
383     };
384             
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;
389             }
390             else {
391                 $.jqplot.support_canvas_text.result = !!(document.createElement('canvas').getContext && typeof document.createElement('canvas').getContext('2d').fillText == 'function');
392             }
393              
394         }
395         return $.jqplot.support_canvas_text.result;
396     };
397     
398     $.jqplot.use_excanvas = ($.browser.msie && !$.jqplot.support_canvas()) ? true : false;
399     
400     /**
401      * 
402      * Hooks: jqPlot Pugin Hooks
403      * 
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
418      *     are parsed.
419      * $.jqplot.postParseSeriesOptionsHooks - called after series related options
420      *     are parsed.
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.
425      * 
426      */
427     
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() {
448         this._elem;
449         this._plotWidth;
450         this._plotHeight;
451         this._plotDimensions = {height:null, width:null};
452     };
453     
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;
463         elem = null;
464         return this._elem;
465     };
466     
467     $.jqplot.ElemContainer.prototype.getWidth = function() {
468         if (this._elem) {
469             return this._elem.outerWidth(true);
470         }
471         else {
472             return null;
473         }
474     };
475     
476     $.jqplot.ElemContainer.prototype.getHeight = function() {
477         if (this._elem) {
478             return this._elem.outerHeight(true);
479         }
480         else {
481             return null;
482         }
483     };
484     
485     $.jqplot.ElemContainer.prototype.getPosition = function() {
486         if (this._elem) {
487             return this._elem.position();
488         }
489         else {
490             return {top:null, left:null, bottom:null, right:null};
491         }
492     };
493     
494     $.jqplot.ElemContainer.prototype.getTop = function() {
495         return this.getPosition().top;
496     };
497     
498     $.jqplot.ElemContainer.prototype.getLeft = function() {
499         return this.getPosition().left;
500     };
501     
502     $.jqplot.ElemContainer.prototype.getBottom = function() {
503         return this._elem.css('bottom');
504     };
505     
506     $.jqplot.ElemContainer.prototype.getRight = function() {
507         return this._elem.css('right');
508     };
509     
511     /**
512      * Class: Axis
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.
516      * 
517      */
518     function Axis(name) {
519         $.jqplot.ElemContainer.call(this);
520         // Group: Properties
521         //
522         // Axes options are specified within an axes object at the top level of the 
523         // plot options like so:
524         // > {
525         // >    axes: {
526         // >        xaxis: {min: 5},
527         // >        yaxis: {min: 2, max: 8, numberTicks:4},
528         // >        x2axis: {pad: 1.5},
529         // >        y2axis: {ticks:[22, 44, 66, 88]}
530         // >        }
531         // > }
532         // There are 2 x axes, 'xaxis' and 'x2axis', and 
533         // 9 yaxes, 'yaxis', 'y2axis'. 'y3axis', ...  Any or all of which may be specified.
534         this.name = name;
535         this._series = [];
536         // prop: show
537         // Wether to display the axis on the graph.
538         this.show = false;
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;
543         // prop: tickOptions
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 = {};
552         // prop: label
553         // Label for the axis
554         this.label = null;
555         // prop: showLabel
556         // true to show the axis label.
557         this.showLabel = true;
558         // prop: min
559         // minimum value of the axis (in data units, not pixels).
560         this.min = null;
561         // prop: max
562         // maximum value of the axis (in data units, not pixels).
563         this.max = null;
564         // prop: autoscale
565         // DEPRECATED
566         // the default scaling algorithm produces superior results.
567         this.autoscale = false;
568         // prop: pad
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.
572         this.pad = 1.2;
573         // prop: padMax
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.
577         this.padMax = null;
578         // prop: padMin
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.
582         this.padMin = null;
583         // prop: ticks
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.
586         this.ticks = [];
587         // prop: numberTicks
588         // Desired number of ticks.  Default is to compute automatically.
589         this.numberTicks;
590         // prop: tickInterval
591         // number of units between ticks.  Mutually exclusive with numberTicks.
592         this.tickInterval;
593         // prop: renderer
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 = {};
600         // prop: showTicks
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;
627         // prop: borderWidth
628         // width of line stroked at the border of the axis.  Defaults
629         // to the width of the grid boarder.
630         this.borderWidth = null;
631         // prop: borderColor
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};
644         this._ticks=[];
645         this._label = null;
646         // prop: syncTicks
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;
652         // prop: tickSpacing
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.
658         this._min = null;
659         this._max = null;
660         this._tickInterval = null;
661         this._numberTicks = null;
662         this.__ticks = null;
663         // hold original user options.
664         this._options = {};
665     }
666     
667     Axis.prototype = new $.jqplot.ElemContainer();
668     Axis.prototype.constructor = Axis;
669     
670     Axis.prototype.init = function() {
671         if ($.isFunction(this.renderer)) {
672             this.renderer = new this.renderer();  
673         }
674         // set the axis name
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;
680         }
681         if (this.tickOptions.showMark == null) {
682             this.tickOptions.showMark = this.showTickMarks;
683         }
684         if (this.tickOptions.showLabel == null) {
685             this.tickOptions.showLabel = this.showTicks;
686         }
687         
688         if (this.label == null || this.label == '') {
689             this.showLabel = false;
690         }
691         else {
692             this.labelOptions.label = this.label;
693         }
694         if (this.showLabel == false) {
695             this.labelOptions.show = false;
696         }
697         // set the default padMax, padMin if not specified
698         // special check, if no padding desired, padding
699         // should be set to 1.0
700         if (this.pad == 0) {
701             this.pad = 1.0;
702         }
703         if (this.padMax == 0) {
704             this.padMax = 1.0;
705         }
706         if (this.padMin == 0) {
707             this.padMin = 1.0;
708         }
709         if (this.padMax == null) {
710             this.padMax = (this.pad-1)/2 + 1;
711         }
712         if (this.padMin == null) {
713             this.padMin = (this.pad-1)/2 + 1;
714         }
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;
720         }
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;
724         }
725         else if (this.syncTicks == null){
726             this.syncTicks = false;
727         }
728         this.renderer.init.call(this, this.rendererOptions);
729         
730     };
731     
732     Axis.prototype.draw = function(ctx, plot) {
733         // Memory Leaks patch
734         if (this.__ticks) {
735           this.__ticks = null;
736         }
738         return this.renderer.draw.call(this, ctx, plot);
739         
740     };
741     
742     Axis.prototype.set = function() {
743         this.renderer.set.call(this);
744     };
745     
746     Axis.prototype.pack = function(pos, offsets) {
747         if (this.show) {
748             this.renderer.pack.call(this, pos, offsets);
749         }
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;
757         }
758     };
759     
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);
763     };
764     
765     Axis.prototype.resetScale = function(opts) {
766         $.extend(true, this, {min: null, max: null, numberTicks: null, tickInterval: null, _ticks: [], ticks: []}, opts);
767         this.resetDataBounds();
768     };
769     
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;
774         db.min = null;
775         db.max = null;
776         var l, s, d;
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++) {
780             s = this._series[i];
781             if (s.show || this.scaleToHiddenSeries) {
782                 d = s._plotData;
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]];
785                 }
787                 var minyidx = 1, maxyidx = 1;
789                 if (s._type != null && s._type == 'ohlc') {
790                     minyidx = 3;
791                     maxyidx = 2;
792                 }
793                 
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) {
797                             db.min = d[j][0];
798                         }
799                         if ((d[j][0] != null && d[j][0] > db.max) || db.max == null) {
800                             db.max = d[j][0];
801                         }
802                     }              
803                     else {
804                         if ((d[j][minyidx] != null && d[j][minyidx] < db.min) || db.min == null) {
805                             db.min = d[j][minyidx];
806                         }
807                         if ((d[j][maxyidx] != null && d[j][maxyidx] > db.max) || db.max == null) {
808                             db.max = d[j][maxyidx];
809                         }
810                     }              
811                 }
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) {
818                     doforce = false;
819                 }
821                 else if (doforce && this._options.hasOwnProperty('forceTickAt0') && this._options.forceTickAt0 == false) {
822                     doforce = false;
823                 }
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) {
828                             doforce = false;
829                         }
830                     }
832                     else if (s.barDirection == 'horizontal' && (this.name == 'xaxis' || this.name == 'x2axis')) {
833                         if (this._options.pad != null || this._options.padMin != null) {
834                             doforce = false;
835                         }
836                     }
838                 }
839             }
840         }
842         if (doforce && this.renderer.constructor === $.jqplot.LinearAxisRenderer && db.min >= 0) {
843             this.padMin = 1.0;
844             this.forceTickAt0 = true;
845         }
846     };
848     /**
849      * Class: Legend
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.
853      */
854     function Legend(options) {
855         $.jqplot.ElemContainer.call(this);
856         // Group: Properties
857         
858         // prop: show
859         // Wether to display the legend on the graph.
860         this.show = false;
861         // prop: location
862         // Placement of the legend.  one of the compass directions: nw, n, ne, e, se, s, sw, w
863         this.location = 'ne';
864         // prop: labels
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.
867         this.labels = [];
868         // prop: showLabels
869         // true to show the label text on the  legend.
870         this.showLabels = true;
871         // prop: showSwatch
872         // true to show the color swatches on the legend.
873         this.showSwatches = true;
874         // prop: placement
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";
882         // prop: xoffset
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.
885         this.xoffset = 0;
886         // prop: yoffset
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.
889         this.yoffset = 0;
890         // prop: border
891         // css spec for the border around the legend box.
892         this.border;
893         // prop: background
894         // css spec for the background of the legend box.
895         this.background;
896         // prop: textColor
897         // css color spec for the legend text.
898         this.textColor;
899         // prop: fontFamily
900         // css font-family spec for the legend text.
901         this.fontFamily; 
902         // prop: fontSize
903         // css font-size spec for the legend text.
904         this.fontSize ;
905         // prop: rowSpacing
906         // css padding-top spec for the rows in the legend.
907         this.rowSpacing = '0.5em';
908         // renderer
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 = {};
915         // prop: predraw
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;
919         // prop: marginTop
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;
924         // prop: marginRight
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;
934         // prop: marginLeft
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;
939         // prop: escapeHtml
940         // True to escape special characters with their html entity equivalents
941         // in legend text.  "<" becomes &lt; and so on, so html tags are not rendered.
942         this.escapeHtml = false;
943         this._series = [];
944         
945         $.extend(true, this, options);
946     }
947     
948     Legend.prototype = new $.jqplot.ElemContainer();
949     Legend.prototype.constructor = Legend;
950     
951     Legend.prototype.setOptions = function(options) {
952         $.extend(true, this, options);
953         
954         // Try to emulate deprecated behaviour
955         // if user has specified xoffset or yoffset, copy these to
956         // the margin properties.
957         
958         if (this.placement ==  'inside') {
959             this.placement = 'insideGrid';
960         }
961         
962         if (this.xoffset >0) {
963             if (this.placement == 'insideGrid') {
964                 switch (this.location) {
965                     case 'nw':
966                     case 'w':
967                     case 'sw':
968                         if (this.marginLeft == null) {
969                             this.marginLeft = this.xoffset + 'px';
970                         }
971                         this.marginRight = '0px';
972                         break;
973                     case 'ne':
974                     case 'e':
975                     case 'se':
976                     default:
977                         if (this.marginRight == null) {
978                             this.marginRight = this.xoffset + 'px';
979                         }
980                         this.marginLeft = '0px';
981                         break;
982                 }
983             }
984             else if (this.placement == 'outside') {
985                 switch (this.location) {
986                     case 'nw':
987                     case 'w':
988                     case 'sw':
989                         if (this.marginRight == null) {
990                             this.marginRight = this.xoffset + 'px';
991                         }
992                         this.marginLeft = '0px';
993                         break;
994                     case 'ne':
995                     case 'e':
996                     case 'se':
997                     default:
998                         if (this.marginLeft == null) {
999                             this.marginLeft = this.xoffset + 'px';
1000                         }
1001                         this.marginRight = '0px';
1002                         break;
1003                 }
1004             }
1005             this.xoffset = 0;
1006         }
1007         
1008         if (this.yoffset >0) {
1009             if (this.placement == 'outside') {
1010                 switch (this.location) {
1011                     case 'sw':
1012                     case 's':
1013                     case 'se':
1014                         if (this.marginTop == null) {
1015                             this.marginTop = this.yoffset + 'px';
1016                         }
1017                         this.marginBottom = '0px';
1018                         break;
1019                     case 'ne':
1020                     case 'n':
1021                     case 'nw':
1022                     default:
1023                         if (this.marginBottom == null) {
1024                             this.marginBottom = this.yoffset + 'px';
1025                         }
1026                         this.marginTop = '0px';
1027                         break;
1028                 }
1029             }
1030             else if (this.placement == 'insideGrid') {
1031                 switch (this.location) {
1032                     case 'sw':
1033                     case 's':
1034                     case 'se':
1035                         if (this.marginBottom == null) {
1036                             this.marginBottom = this.yoffset + 'px';
1037                         }
1038                         this.marginTop = '0px';
1039                         break;
1040                     case 'ne':
1041                     case 'n':
1042                     case 'nw':
1043                     default:
1044                         if (this.marginTop == null) {
1045                             this.marginTop = this.yoffset + 'px';
1046                         }
1047                         this.marginBottom = '0px';
1048                         break;
1049                 }
1050             }
1051             this.yoffset = 0;
1052         }
1053         
1054         // TO-DO:
1055         // Handle case where offsets are < 0.
1056         //
1057     };
1058     
1059     Legend.prototype.init = function() {
1060         if ($.isFunction(this.renderer)) {
1061             this.renderer = new this.renderer();  
1062         }
1063         this.renderer.init.call(this, this.rendererOptions);
1064     };
1065     
1066     Legend.prototype.draw = function(offsets, plot) {
1067         for (var i=0; i<$.jqplot.preDrawLegendHooks.length; i++){
1068             $.jqplot.preDrawLegendHooks[i].call(this, offsets);
1069         }
1070         return this.renderer.draw.call(this, offsets, plot);
1071     };
1072     
1073     Legend.prototype.pack = function(offsets) {
1074         this.renderer.pack.call(this, offsets);
1075     };
1077     /**
1078      * Class: Title
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.
1082      * 
1083      * Parameters:
1084      * text - text of the title.
1085      */
1086     function Title(text) {
1087         $.jqplot.ElemContainer.call(this);
1088         // Group: Properties
1089         
1090         // prop: text
1091         // text of the title;
1092         this.text = text;
1093         // prop: show
1094         // wether or not to show the title
1095         this.show = true;
1096         // prop: fontFamily
1097         // css font-family spec for the text.
1098         this.fontFamily;
1099         // prop: fontSize
1100         // css font-size spec for the text.
1101         this.fontSize ;
1102         // prop: textAlign
1103         // css text-align spec for the text.
1104         this.textAlign;
1105         // prop: textColor
1106         // css color spec for the text.
1107         this.textColor;
1108         // prop: renderer
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 = {};   
1115         // prop: escapeHtml
1116         // True to escape special characters with their html entity equivalents
1117         // in title text.  "<" becomes &lt; and so on, so html tags are not rendered.
1118         this.escapeHtml = false;
1119     }
1120     
1121     Title.prototype = new $.jqplot.ElemContainer();
1122     Title.prototype.constructor = Title;
1123     
1124     Title.prototype.init = function() {
1125         if ($.isFunction(this.renderer)) {
1126             this.renderer = new this.renderer();  
1127         }
1128         this.renderer.init.call(this, this.rendererOptions);
1129     };
1130     
1131     Title.prototype.draw = function(width) {
1132         return this.renderer.draw.call(this, width);
1133     };
1134     
1135     Title.prototype.pack = function() {
1136         this.renderer.pack.call(this);
1137     };
1140     /**
1141      * Class: Series
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.
1145      */
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:
1154         // > {
1155         // >    series:[
1156         // >        {color: '#ff4466', lineWidth: 5, label:'good line'},
1157         // >        {yaxis: 'y2axis', shadow: false, label:'bad line'}
1158         // >    ]
1159         // > }
1161         // prop: show
1162         // wether or not to draw the series.
1163         this.show = true;
1164         // prop: xaxis
1165         // which x axis to use with this series, either 'xaxis' or 'x2axis'.
1166         this.xaxis = 'xaxis';
1167         this._xaxis;
1168         // prop: yaxis
1169         // which y axis to use with this series, either 'yaxis' or 'y2axis'.
1170         this.yaxis = 'yaxis';
1171         this._yaxis;
1172         this.gridBorderWidth = 2.0;
1173         // prop: renderer
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 = {};
1180         this.data = [];
1181         this.gridData = [];
1182         // prop: label
1183         // Line label to use in the legend.
1184         this.label = '';
1185         // prop: showLabel
1186         // true to show label for this series in the legend.
1187         this.showLabel = true;
1188         // prop: color
1189         // css color spec for the series
1190         this.color;
1191         // prop: negativeColor
1192         // css color spec used for filled (area) plots that are filled to zero and
1193         // the "useNegativeColors" option is true.
1194         this.negativeColor;
1195         // prop: lineWidth
1196         // width of the line in pixels.  May have different meanings depending on renderer.
1197         this.lineWidth = 2.5;
1198         // prop: lineJoin
1199         // Canvas lineJoin style between segments of series.
1200         this.lineJoin = 'round';
1201         // prop: lineCap
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';
1210         this.shadow = true;
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 = {};
1235         // prop: showLine
1236         // wether to actually draw the line or not.  Series will still be renderered, even if no line is drawn.
1237         this.showLine = true;
1238         // prop: showMarker
1239         // wether or not to show the markers at the data points.
1240         this.showMarker = true;
1241         // prop: index
1242         // 0 based index of this series in the plot series array.
1243         this.index;
1244         // prop: fill
1245         // true or false, wether to fill under lines or in bars.
1246         // May not be implemented in all renderers.
1247         this.fill = false;
1248         // prop: fillColor
1249         // CSS color spec to use for fill under line.  Defaults to line color.
1250         this.fillColor;
1251         // prop: fillAlpha
1252         // Alpha transparency to apply to the fill under the line.
1253         // Use this to adjust alpha separate from fill color.
1254         this.fillAlpha;
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;
1275         // prop: fillToZero
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;
1282         // prop: fillAxis
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();
1305         this.plugins = {};
1306         // sum of y values in this series.
1307         this._sumy = 0;
1308         this._sumx = 0;
1309         this._type = '';
1310     }
1311     
1312     Series.prototype = new $.jqplot.ElemContainer();
1313     Series.prototype.constructor = Series;
1314     
1315     Series.prototype.init = function(index, gridbw, plot) {
1316         // weed out any null values in the data.
1317         this.index = index;
1318         this.gridBorderWidth = gridbw;
1319         var d = this.data;
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) {
1324                     continue;
1325                 }
1326                 else {
1327                     temp.push(d[i]);
1328                 }
1329             }
1330             else {
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.
1336                 temp.push(d[i]);
1337             }
1338         }
1339         this.data = temp;
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.
1344         if (!this.color) {
1345             this.color = plot.colorGenerator.get(this.index);
1346         }
1347         if (!this.negativeColor) {
1348             this.negativeColor = plot.negativeColorGenerator.get(this.index);
1349         }
1352         if (!this.fillColor) {
1353             this.fillColor = this.color;
1354         }
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+')';
1359         }
1360         if ($.isFunction(this.renderer)) {
1361             this.renderer = new this.renderer();  
1362         }
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;
1367         }
1368         if (this.markerOptions.show == null) {
1369             this.markerOptions.show = this.showMarker;
1370         }
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);
1374     };
1375     
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;
1382         
1383         var j, data, gridData;
1384         
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);
1389         }
1390         if (this.show) {
1391             this.renderer.setGridData.call(this, plot);
1392             if (!options.preventJqPlotSeriesDrawTrigger) {
1393                 $(sctx.canvas).trigger('jqplotSeriesDraw', [this.data, this.gridData]);
1394             }
1395             data = [];
1396             if (options.data) {
1397                 data = options.data;
1398             }
1399             else if (!this._stack) {
1400                 data = this.data;
1401             }
1402             else {
1403                 data = this._plotData;
1404             }
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;
1409             }
1411             this.renderer.draw.call(this, sctx, gridData, options, plot);
1412         }
1413         
1414         for (j=0; j<$.jqplot.postDrawSeriesHooks.length; j++) {
1415             $.jqplot.postDrawSeriesHooks[j].call(this, sctx, options, plot);
1416         }
1417         
1418         sctx = opts = plot = j = data = gridData = null;
1419     };
1420     
1421     Series.prototype.drawShadow = function(sctx, opts, plot) {
1422         var options = (opts == undefined) ? {} : opts;
1423         sctx = (sctx == undefined) ? this.shadowCanvas._ctx : sctx;
1424         
1425         var j, data, gridData;
1426         
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);
1431         }
1432         if (this.shadow) {
1433             this.renderer.setGridData.call(this, plot);
1435             data = [];
1436             if (options.data) {
1437                 data = options.data;
1438             }
1439             else if (!this._stack) {
1440                 data = this.data;
1441             }
1442             else {
1443                 data = this._plotData;
1444             }
1445             gridData = options.gridData || this.renderer.makeGridData.call(this, data, plot);
1446         
1447             this.renderer.drawShadow.call(this, sctx, gridData, options, plot);
1448         }
1449         
1450         for (j=0; j<$.jqplot.postDrawSeriesShadowHooks.length; j++) {
1451             $.jqplot.postDrawSeriesShadowHooks[j].call(this, sctx, options);
1452         }
1453         
1454         sctx = opts = plot = j = data = gridData = null;
1455         
1456     };
1457     
1458     // toggles series display on plot, e.g. show/hide series
1459     Series.prototype.toggleDisplay = function(ev, callback) {
1460         var s, speed;
1461         if (ev.data.series) {
1462             s = ev.data.series;
1463         }
1464         else {
1465             s = this;
1466         }
1468         if (ev.data.speed) {
1469             speed = ev.data.speed;
1470         }
1471         if (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) {
1474                 s.show = true;
1476                 s.canvas._elem.removeClass('jqplot-series-hidden');
1477                 if (s.shadowCanvas._elem) {
1478                     s.shadowCanvas._elem.fadeIn(speed);
1479                 }
1480                 s.canvas._elem.fadeIn(speed, callback);
1481                 s.canvas._elem.nextAll('.jqplot-point-label.jqplot-series-'+s.index).fadeIn(speed);
1482             }
1483             else {
1484                 s.show = false;
1486                 s.canvas._elem.addClass('jqplot-series-hidden');
1487                 if (s.shadowCanvas._elem) {
1488                     s.shadowCanvas._elem.fadeOut(speed);
1489                 }
1490                 s.canvas._elem.fadeOut(speed, callback);
1491                 s.canvas._elem.nextAll('.jqplot-point-label.jqplot-series-'+s.index).fadeOut(speed);
1492             }
1493         }
1494         else {
1495             // this can be tricky because series may not have a canvas element if replotting.
1496             if (s.canvas._elem.is(':hidden') || !s.show) {
1497                 s.show = true;
1499                 s.canvas._elem.removeClass('jqplot-series-hidden');
1500                 if (s.shadowCanvas._elem) {
1501                     s.shadowCanvas._elem.show();
1502                 }
1503                 s.canvas._elem.show(0, callback);
1504                 s.canvas._elem.nextAll('.jqplot-point-label.jqplot-series-'+s.index).show();
1505             }
1506             else {
1507                 s.show = false;
1509                 s.canvas._elem.addClass('jqplot-series-hidden');
1510                 if (s.shadowCanvas._elem) {
1511                     s.shadowCanvas._elem.hide();
1512                 }
1513                 s.canvas._elem.hide(0, callback);
1514                 s.canvas._elem.nextAll('.jqplot-point-label.jqplot-series-'+s.index).hide();
1515             }
1516         }
1517     };
1518     
1521     /**
1522      * Class: Grid
1523      * 
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.
1529      */
1530     function Grid() {
1531         $.jqplot.ElemContainer.call(this);
1532         // Group: Properties
1533         
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;
1543         // prop: background
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;
1552         // prop: drawBorder
1553         // True to draw border around grid.
1554         this.drawBorder = true;
1555         // prop: shadow
1556         // wether to show a shadow behind the grid.
1557         this.shadow = true;
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';
1576         this._left;
1577         this._top;
1578         this._right;
1579         this._bottom;
1580         this._width;
1581         this._height;
1582         this._axes = [];
1583         // prop: renderer
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};
1592     }
1593     
1594     Grid.prototype = new $.jqplot.ElemContainer();
1595     Grid.prototype.constructor = Grid;
1596     
1597     Grid.prototype.init = function() {
1598         if ($.isFunction(this.renderer)) {
1599             this.renderer = new this.renderer();  
1600         }
1601         this.renderer.init.call(this, this.rendererOptions);
1602     };
1603     
1604     Grid.prototype.createElement = function(offsets,plot) {
1605         this._offsets = offsets;
1606         return this.renderer.createElement.call(this, plot);
1607     };
1608     
1609     Grid.prototype.draw = function() {
1610         this.renderer.draw.call(this);
1611     };
1612     
1613     $.jqplot.GenericCanvas = function() {
1614         $.jqplot.ElemContainer.call(this);
1615         this._ctx;  
1616     };
1617     
1618     $.jqplot.GenericCanvas.prototype = new $.jqplot.ElemContainer();
1619     $.jqplot.GenericCanvas.prototype.constructor = $.jqplot.GenericCanvas;
1620     
1621     $.jqplot.GenericCanvas.prototype.createElement = function(offsets, clss, plotDimensions, plot) {
1622         this._offsets = offsets;
1623         var klass = 'jqplot';
1624         if (clss != undefined) {
1625             klass = clss;
1626         }
1627         var elem;
1629         elem = plot.canvasManager.getCanvas();
1630         
1631         // if new plotDimensions supplied, use them.
1632         if (plotDimensions != null) {
1633             this._plotDimensions = plotDimensions;
1634         }
1635         
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 });
1640         
1641         this._elem.addClass(klass);
1642         
1643         elem = plot.canvasManager.initCanvas(elem);
1644         
1645         elem = null;
1646         return this._elem;
1647     };
1648     
1649     $.jqplot.GenericCanvas.prototype.setContext = function() {
1650         this._ctx = this._elem.get(0).getContext("2d");
1651         return this._ctx;
1652     };
1653     
1654     // Memory Leaks patch
1655     $.jqplot.GenericCanvas.prototype.resetCanvas = function() {
1656       if (this._elem) {
1657         if ($.jqplot.use_excanvas && window.G_vmlCanvasManager.uninitElement !== undefined) {
1658            window.G_vmlCanvasManager.uninitElement(this._elem.get(0));
1659         }
1660         
1661         //this._elem.remove();
1662         this._elem.emptyForce();
1663       }
1664       
1665       this._ctx = null;
1666     };
1667     
1668     $.jqplot.HooksManager = function () {
1669         this.hooks =[];
1670         this.args = [];
1671     };
1672     
1673     $.jqplot.HooksManager.prototype.addOnce = function(fn, args) {
1674         args = args || [];
1675         var havehook = false;
1676         for (var i=0, l=this.hooks.length; i<l; i++) {
1677             if (this.hooks[i] == fn) {
1678                 havehook = true;
1679             }
1680         }
1681         if (!havehook) {
1682             this.hooks.push(fn);
1683             this.args.push(args);
1684         }
1685     };
1686     
1687     $.jqplot.HooksManager.prototype.add = function(fn, args) {
1688         args = args || [];
1689         this.hooks.push(fn);
1690         this.args.push(args);
1691     };
1692     
1693     $.jqplot.EventListenerManager = function () {
1694         this.hooks =[];
1695     };
1696     
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++) {
1700             h = this.hooks[i];
1701             if (h[0] == ev && h[1] == fn) {
1702                 havehook = true;
1703             }
1704         }
1705         if (!havehook) {
1706             this.hooks.push([ev, fn]);
1707         }
1708     };
1709     
1710     $.jqplot.EventListenerManager.prototype.add = function(ev, fn) {
1711         this.hooks.push([ev, fn]);
1712     };
1715     var _axisNames = ['yMidAxis', 'xaxis', 'yaxis', 'x2axis', 'y2axis', 'y3axis', 'y4axis', 'y5axis', 'y6axis', 'y7axis', 'y8axis', 'y9axis'];
1717     /**
1718      * Class: jqPlot
1719      * Plot object returned by call to $.jqplot.  Handles parsing user options,
1720      * creating sub objects (Axes, legend, title, series) and rendering the plot.
1721      */
1722     function jqPlot() {
1723         // Group: Properties
1724         // These properties are specified at the top of the options object
1725         // like so:
1726         // > {
1727         // >     axesDefaults:{min:0},
1728         // >     series:[{color:'#6633dd'}],
1729         // >     title: 'A Plot'
1730         // > }
1731         //
1733         // prop: animate
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;
1743         // prop: axes
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;
1751         // prop: data
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, ...] ].
1757         this.data = [];
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.
1761         this.dataRenderer;
1762         // prop: dataRendererOptions
1763         // Options that will be passed to the dataRenderer.
1764         // Can be of any type.
1765         this.dataRendererOptions;
1766         this.defaults = {
1767             // prop: axesDefaults
1768             // default options that will be applied to all axes.
1769             // see <Axis> for axes options.
1770             axesDefaults: {},
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.
1775             seriesDefaults: {},
1776             series:[]
1777         };
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.
1794         // Options object:
1795         // {
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].
1801         //  }
1802         this.fillBetween = {
1803             series1: null,
1804             series2: null,
1805             color: null,
1806             baseSeries: 0,
1807             fill: true
1808         };
1809         // prop; fontFamily
1810         // css spec for the font-family attribute.  Default for the entire plot.
1811         this.fontFamily;
1812         // prop: fontSize
1813         // css spec for the font-size attribute.  Default for the entire plot.
1814         this.fontSize;
1815         // prop: grid
1816         // See <Grid> for grid specific options.
1817         this.grid = new Grid();
1818         // prop: legend
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 = {    
1825             show: false,
1826             indicator: 'Loading Data...',
1827             axes: {
1828                 xaxis: {
1829                     min: 0,
1830                     max: 10,
1831                     tickInterval: 2,
1832                     show: true
1833                 },
1834                 yaxis: {
1835                     min: 0,
1836                     max: 12,
1837                     tickInterval: 3,
1838                     show: true
1839                 }
1840             }
1841         };
1842         // container to hold all of the merged options.  Convienence for plugins.
1843         this.options = {};
1844         this.previousSeriesStack = [];
1845         // Namespece to hold plugins.  Generally non-renderer plugins add themselves to here.
1846         this.plugins = {};
1847         // prop: series
1848         // Array of series object options.
1849         // see <Series> for series specific options.
1850         this.series = [];
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;
1861         // prop: sortData
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.
1875         this.target = null; 
1876         // The id of the dom element to render the plot into
1877         this.targetId = null;
1878         // prop textColor
1879         // css spec for the css color attribute.  Default for the entire plot.
1880         this.textColor;
1881         // prop: title
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.
1895         this._sumy = 0;
1896         this._sumx = 0;
1897         // array to hold the cumulative stacked series data.
1898         // used to ajust the individual series data, which won't have access to other
1899         // series data.
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 = [];
1904         this._width = null;
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();
1929         
1930         this.colorGenerator = new $.jqplot.ColorGenerator();
1931         this.negativeColorGenerator = new $.jqplot.ColorGenerator();
1933         this.canvasManager = new $.jqplot.CanvasManager();
1935         this.themeEngine = new $.jqplot.ThemeEngine();
1936         
1937         var seriesColorsIndex = 0;
1939         // Group: methods
1940         //
1941         // method: init
1942         // sets the plot target, checks data and applies user
1943         // options to plot.
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);
1948             }
1950             for (var i=0; i<this.preInitHooks.hooks.length; i++) {
1951                 this.preInitHooks.hooks[i].call(this, target, data, options);
1952             }
1953             
1954             this.targetId = '#'+target;
1955             this.target = $('#'+target);
1957             //////
1958             // Add a reference to plot
1959             //////
1960             if (this._addDomReference) {
1961                 this.target.data('jqplot', this);
1962             }
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";
1967             }
1968             
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');
1972             }
1973             if (!this.target.hasClass('jqplot-target')) {
1974                 this.target.addClass('jqplot-target');
1975             }
1976             
1977             // if no height or width specified, use a default.
1978             if (!this.target.height()) {
1979                 var h;
1980                 if (options && options.height) {
1981                     h = parseInt(options.height, 10);
1982                 }
1983                 else if (this.target.attr('data-height')) {
1984                     h = parseInt(this.target.attr('data-height'), 10);
1985                 }
1986                 else {
1987                     h = parseInt($.jqplot.config.defaultHeight, 10);
1988                 }
1989                 this._height = h;
1990                 this.target.css('height', h+'px');
1991             }
1992             else {
1993                 this._height = h = this.target.height();
1994             }
1995             if (!this.target.width()) {
1996                 var w;
1997                 if (options && options.width) {
1998                     w = parseInt(options.width, 10);
1999                 }
2000                 else if (this.target.attr('data-width')) {
2001                     w = parseInt(this.target.attr('data-width'), 10);
2002                 }
2003                 else {
2004                     w = parseInt($.jqplot.config.defaultWidth, 10);
2005                 }
2006                 this._width = w;
2007                 this.target.css('width', w+'px');
2008             }
2009             else {
2010                 this._width = w = this.target.width();
2011             }
2013             for (var i=0, l=_axisNames.length; i<l; i++) {
2014                 this.axes[_axisNames[i]] = new Axis(_axisNames[i]);
2015             }
2016             
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";
2026             }
2027             
2028             if (options.dataRenderer && $.isFunction(options.dataRenderer)) {
2029                 if (options.dataRendererOptions) {
2030                     this.dataRendererOptions = options.dataRendererOptions;
2031                 }
2032                 this.dataRenderer = options.dataRenderer;
2033                 data = this.dataRenderer(data, this, this.dataRendererOptions);
2034             }
2035             
2036             if (options.noDataIndicator && $.isPlainObject(options.noDataIndicator)) {
2037                 $.extend(true, this.noDataIndicator, options.noDataIndicator);
2038             }
2039             
2040             if (data == null || $.isArray(data) == false || data.length == 0 || $.isArray(data[0]) == false || data[0].length == 0) {
2041                 
2042                 if (this.noDataIndicator.show == false) {
2043                     throw "No Data";
2044                 }
2045                 
2046                 else {
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;
2050                     
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];
2054                         }
2055                     }
2056                     
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);
2062                         temp.height(eh);
2063                         temp.width(ew);
2064                         temp.css('top', this.eventCanvas._offsets.top);
2065                         temp.css('left', this.eventCanvas._offsets.left);
2066                         
2067                         var temp2 = $('<div class="jqplot-noData-contents" style="text-align:center; position:relative; margin-left:auto; margin-right:auto;"></div>');
2068                         temp.append(temp2);
2069                         temp2.html(this.noDataIndicator.indicator);
2070                         var th = temp2.height();
2071                         var tw = temp2.width();
2072                         temp2.height(th);
2073                         temp2.width(tw);
2074                         temp2.css('top', (eh - th)/2 + 'px');
2075                     });
2077                 }
2078             }
2079             
2080             // make a copy of the data
2081             this.data = $.extend(true, [], data);
2082             
2083             this.parseOptions(options);
2084             
2085             if (this.textColor) {
2086                 this.target.css('color', this.textColor);
2087             }
2088             if (this.fontFamily) {
2089                 this.target.css('font-family', this.fontFamily);
2090             }
2091             if (this.fontSize) {
2092                 this.target.css('font-size', this.fontSize);
2093             }
2094             
2095             this.title.init();
2096             this.legend.init();
2097             this._sumy = 0;
2098             this._sumx = 0;
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);
2108                 }
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);
2111                 }
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);
2117                 }
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);
2120                 }
2121                 this._sumy += this.series[i]._sumy;
2122                 this._sumx += this.series[i]._sumx;
2123             }
2125             var name,
2126                 axis;
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;
2131                 axis.init();
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;
2135                     }
2136                     else {
2137                         axis.borderColor = this.grid.borderColor;
2138                     }
2139                 }
2140             }
2141             
2142             if (this.sortData) {
2143                 sortData(this.series);
2144             }
2145             this.grid.init();
2146             this.grid._axes = this.axes;
2147             
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);
2152             }
2154             for (var i=0; i<this.postInitHooks.hooks.length; i++) {
2155                 this.postInitHooks.hooks[i].call(this, target, this.data, options);
2156             }
2157         };  
2158         
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.
2162         //
2163         // Parameters:
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;
2168             if (ax === true) {
2169                 ax = this.axes;
2170             }
2171             if ($.isArray(ax)) {
2172                 for (var i = 0; i < ax.length; i++) {
2173                     this.axes[ax[i]].resetScale(opts[ax[i]]);
2174                 }
2175             }
2176             else if (typeof(ax) === 'object') {
2177                 for (var name in ax) {
2178                     this.axes[name].resetScale(opts[name]);
2179                 }
2180             }
2181         };
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);
2198             }
2200             for (var i=0; i<this.preInitHooks.hooks.length; i++) {
2201                 this.preInitHooks.hooks[i].call(this, target, tdata, options);
2202             }
2203             
2204             this._height = this.target.height();
2205             this._width = this.target.width();
2206             
2207             if (this._height <=0 || this._width <=0 || !this._height || !this._width) {
2208                 throw "Target dimension not set";
2209             }
2210             
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;
2219             var name,
2220                 t, 
2221                 j, 
2222                 axis;
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
2229                 t = axis._ticks;
2230                 for (var j = 0, tlen = t.length; j < tlen; j++) {
2231                   var el = t[j]._elem;
2232                   if (el) {
2233                     // if canvas renderer
2234                     if ($.jqplot.use_excanvas && window.G_vmlCanvasManager.uninitElement !== undefined) {
2235                       window.G_vmlCanvasManager.uninitElement(el.get(0));
2236                     }
2237                     el.emptyForce();
2238                     el = null;
2239                     t._elem = null;
2240                   }
2241                 }
2242                 t = null;
2244                 delete axis.ticks;
2245                 delete axis._ticks;
2246                 this.axes[name] = new Axis(name);
2247                 this.axes[name]._plotWidth = this._width;
2248                 this.axes[name]._plotHeight = this._height;
2249             }
2250             
2251             if (data) {
2252                 if (options.dataRenderer && $.isFunction(options.dataRenderer)) {
2253                     if (options.dataRendererOptions) {
2254                         this.dataRendererOptions = options.dataRendererOptions;
2255                     }
2256                     this.dataRenderer = options.dataRenderer;
2257                     data = this.dataRenderer(data, this, this.dataRendererOptions);
2258                 }
2259                 
2260                 // make a copy of the data
2261                 this.data = $.extend(true, [], data);
2262             }
2264             if (opts) {
2265                 this.parseOptions(options);
2266             }
2267             
2268             this.title._plotWidth = this._width;
2269             
2270             if (this.textColor) {
2271                 this.target.css('color', this.textColor);
2272             }
2273             if (this.fontFamily) {
2274                 this.target.css('font-family', this.fontFamily);
2275             }
2276             if (this.fontSize) {
2277                 this.target.css('font-size', this.fontSize);
2278             }
2280             this.title.init();
2281             this.legend.init();
2282             this._sumy = 0;
2283             this._sumx = 0;
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);
2297                 }
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);
2300                 }
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);
2306                 }
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);
2309                 }
2310                 this._sumy += this.series[i]._sumy;
2311                 this._sumx += this.series[i]._sumx;
2312             }
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;
2319                 axis.init();
2320                 if (axis.borderColor == null) {
2321                     if (name.charAt(0) !== 'x' && axis.useSeriesColor === true && axis.show) {
2322                         axis.borderColor = axis._series[0].color;
2323                     }
2324                     else {
2325                         axis.borderColor = this.grid.borderColor;
2326                     }
2327                 }
2328             }
2329             
2330             if (this.sortData) {
2331                 sortData(this.series);
2332             }
2333             this.grid.init();
2334             this.grid._axes = this.axes;
2335             
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);
2340             }
2342             for (var i=0, l=this.postInitHooks.hooks.length; i<l; i++) {
2343                 this.postInitHooks.hooks[i].call(this, target, this.data, options);
2344             }
2345         };
2349         // method: quickInit
2350         // 
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.
2359             
2360             this._height = this.target.height();
2361             this._width = this.target.width();
2362             
2363             if (this._height <=0 || this._width <=0 || !this._height || !this._width) {
2364                 throw "Target dimension not set";
2365             }
2366             
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;
2374             
2375             for (var n in this.axes) {
2376                 this.axes[n]._plotWidth = this._width;
2377                 this.axes[n]._plotHeight = this._height;
2378             }
2379             
2380             this.title._plotWidth = this._width;
2381             
2382             if (this.textColor) {
2383                 this.target.css('color', this.textColor);
2384             }
2385             if (this.fontFamily) {
2386                 this.target.css('font-family', this.fontFamily);
2387             }
2388             if (this.fontSize) {
2389                 this.target.css('font-size', this.fontSize);
2390             }
2391             
2392             this._sumy = 0;
2393             this._sumx = 0;
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);
2399                 }
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;
2405             }
2407             var name;
2408             
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;
2415                   if (el) {
2416                     // if canvas renderer
2417                     if ($.jqplot.use_excanvas && window.G_vmlCanvasManager.uninitElement !== undefined) {
2418                       window.G_vmlCanvasManager.uninitElement(el.get(0));
2419                     }
2420                     el.emptyForce();
2421                     el = null;
2422                     t._elem = null;
2423                   }
2424                 }
2425                 t = null;
2426                 
2427                 this.axes[name]._plotDimensions = this._plotDimensions;
2428                 this.axes[name]._ticks = [];
2429                 // this.axes[name].renderer.init.call(this.axes[name], {});
2430             }
2431             
2432             if (this.sortData) {
2433                 sortData(this.series);
2434             }
2435             
2436             this.grid._axes = this.axes;
2437             
2438             this.legend._series = this.series;
2439         };
2440         
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++) {
2445                 var check;
2446                 var bat = [series[i].data, series[i]._stackData, series[i]._plotData, series[i]._prevPlotData];
2447                 for (var n=0; n<4; n++) {
2448                     check = true;
2449                     d = bat[n];
2450                     if (series[i]._stackAxis == 'x') {
2451                         for (var j = 0; j < d.length; j++) {
2452                             if (typeof(d[j][1]) != "number") {
2453                                 check = false;
2454                                 break;
2455                             }
2456                         }
2457                         if (check) {
2458                             d.sort(function(a,b) { return a[1] - b[1]; });
2459                         }
2460                     }
2461                     else {
2462                         for (var j = 0; j < d.length; j++) {
2463                             if (typeof(d[j][0]) != "number") {
2464                                 check = false;
2465                                 break;
2466                             }
2467                         }
2468                         if (check) {
2469                             d.sort(function(a,b) { return a[0] - b[0]; });
2470                         }
2471                     }
2472                 }
2473                
2474             }
2475         }
2477         this.computePlotData = function() {
2478             this._plotData = [];
2479             this._stackData = [];
2480             var series,
2481                 index,
2482                 l;
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];
2505                         if (temp == null) {
2506                             temp = 0;
2507                         }
2508                         this._plotData[index][k][sidx] = temp;
2509                         this._stackData[index][k][sidx] = temp;
2511                         if (index > 0) {
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;
2521                                     break;
2522                                 } 
2523                             }
2524                         }
2525                     }
2527                 }
2528                 else {
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]);
2532                     }
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;
2538                 }
2539                 if (index>0) {
2540                     series._prevPlotData = this.series[index-1]._plotData;
2541                 }
2542                 series._sumy = 0;
2543                 series._sumx = 0;
2544                 for (i=series.data.length-1; i>-1; i--) {
2545                     series._sumy += series.data[i][1];
2546                     series._sumx += series.data[i][0];
2547                 }
2548             }
2550         };
2551         
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++) {
2574                         dval = cd[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;
2584                         }
2585                     }
2586                 }
2587                 for (var i=0; i<plotdata.length; i++) {
2588                     plotValues.x.push(plotdata[i][0]);
2589                     plotValues.y.push(plotdata[i][1]);
2590                 }
2591                 this._plotData.push(plotdata);
2592                 this._stackData.push(temp);
2593                 series._stackData = temp;
2594                 series._plotData = plotdata;
2595                 series._plotValues = plotValues;
2596             }
2597             else {
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]);
2601                 }
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;
2607             }
2608             if (index>0) {
2609                 series._prevPlotData = this.series[index-1]._plotData;
2610             }
2611             series._sumy = 0;
2612             series._sumx = 0;
2613             for (i=series.data.length-1; i>-1; i--) {
2614                 series._sumy += series.data[i][1];
2615                 series._sumx += series.data[i][0];
2616             }
2617         };
2618         
2619         // function to safely return colors from the color array and wrap around at the end.
2620         this.getNextSeriesColor = (function(t) {
2621             var idx = 0;
2622             var sc = t.seriesColors;
2623             
2624             return function () { 
2625                 if (idx < sc.length) {
2626                     return sc[idx++];
2627                 }
2628                 else {
2629                     idx = 0;
2630                     return sc[idx++];
2631                 }
2632             };
2633         })(this);
2634     
2635         this.parseOptions = function(options){
2636             for (var i=0; i<this.preParseOptionsHooks.hooks.length; i++) {
2637                 this.preParseOptionsHooks.hooks[i].call(this, options);
2638             }
2639             for (var i=0; i<$.jqplot.preParseOptionsHooks.length; i++) {
2640                 $.jqplot.preParseOptionsHooks[i].call(this, options);
2641             }
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'], 
2650                     tempi;
2652                 for (var i=0, l=temp.length; i<l; i++) {
2653                     tempi = temp[i];
2654                     if (opts.fillBetween[tempi] != null) {
2655                         this.fillBetween[tempi] = opts.fillBetween[tempi];
2656                     }
2657                 }
2658             }
2660             if (opts.seriesColors) {
2661                 this.seriesColors = opts.seriesColors;
2662             }
2663             if (opts.negativeSeriesColors) {
2664                 this.negativeSeriesColors = opts.negativeSeriesColors;
2665             }
2666             if (opts.captureRightClick) {
2667                 this.captureRightClick = opts.captureRightClick;
2668             }
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;
2684             }
2685             // if (this.data.length == 0) {
2686             //     this.data = [];
2687             //     for (var i=0; i<this.options.series.length; i++) {
2688             //         this.data.push(this.options.series.data);
2689             //     }    
2690             // }
2691                 
2692             var normalizeData = function(data, dir, start) {
2693                 // return data as an array of point arrays,
2694                 // in form [[x1,y1...], [x2,y2...], ...]
2695                 var temp = [];
2696                 var i, l;
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]]);   
2705                         }
2706                         else {
2707                             temp.push([data[i], start+i]);
2708                         }
2709                     }
2710                 }            
2711                 else {
2712                     // we have a properly formatted data series, copy it.
2713                     $.extend(true, temp, data);
2714                 }
2715                 return temp;
2716             };
2718             var colorIndex = 0;
2719             this.series = [];
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]);
2726                 }
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]);
2729                 }
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') {
2735                     dir = 'horizontal';
2736                     temp._stackAxis = 'x';
2737                     temp._primaryAxis = '_yaxis';
2738                 }
2739                 temp.data = normalizeData(this.data[i], dir, this.defaultAxisStart);
2740                 switch (temp.xaxis) {
2741                     case 'xaxis':
2742                         temp._xaxis = this.axes.xaxis;
2743                         break;
2744                     case 'x2axis':
2745                         temp._xaxis = this.axes.x2axis;
2746                         break;
2747                     default:
2748                         break;
2749                 }
2750                 temp._yaxis = this.axes[temp.yaxis];
2751                 temp._xaxis._series.push(temp);
2752                 temp._yaxis._series.push(temp);
2753                 if (temp.show) {
2754                     temp._xaxis.show = true;
2755                     temp._yaxis.show = true;
2756                 }
2757                 else {
2758                     if (temp._xaxis.scaleToHiddenSeries) {
2759                         temp._xaxis.show = true;
2760                     }
2761                     if (temp._yaxis.scaleToHiddenSeries) {
2762                         temp._yaxis.show = true;
2763                     }
2764                 }
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;;
2770                 // }
2771                 // if (!temp.negativeColor && temp.show != false) {
2772                 //     temp.negativeColor = ncg.get(colorIndex);
2773                 //     ncg.setIndex(colorIndex);
2774                 // }
2775                 if (!temp.label) {
2776                     temp.label = 'Series '+ (i+1).toString();
2777                 }
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]);
2783                 }
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]);
2786                 }
2787             }
2788             
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;
2797                 }
2798             }
2799             
2800             if (typeof this.options.title == 'string') {
2801                 this.title.text = this.options.title;
2802             }
2803             else if (typeof this.options.title == 'object') {
2804                 $.extend(true, this.title, this.options.title);
2805             }
2806             this.title._plotWidth = this._width;
2807             this.legend.setOptions(this.options.legend);
2808             
2809             for (var i=0; i<$.jqplot.postParseOptionsHooks.length; i++) {
2810                 $.jqplot.postParseOptionsHooks[i].call(this, options);
2811             }
2812             for (var i=0; i<this.postParseOptionsHooks.hooks.length; i++) {
2813                 this.postParseOptionsHooks.hooks[i].call(this, options);
2814             }
2815         };
2816         
2817         // method: destroy
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();
2823             }
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 = '';
2831         };
2832         
2833         // method: replot
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.
2837         //
2838         // Parameters:
2839         // options - Options used for replotting.
2840         //
2841         // Properties:
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;
2850             delete opts.data;
2851             delete opts.clear;
2852             delete opts.resetAxes;
2854             this.target.trigger('jqplotPreReplot');
2855             
2856             if (clear) {
2857                 this.destroy();
2858             }
2859             // if have data or other options, full reinit.
2860             // otherwise, quickinit.
2861             if (data || !$.isEmptyObject(opts)) {
2862                 this.reInitialize(data, opts);
2863             }
2864             else {
2865                 this.quickInit();
2866             }
2868             if (resetAxes) {
2869                 this.resetAxesScale(resetAxes, opts.axes);
2870             }
2871             this.draw();
2872             this.target.trigger('jqplotPostReplot');
2873         };
2874         
2875         // method: redraw
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. 
2883         //
2884         // Parameters:
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');
2889             if (clear) {
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();
2896             }
2897              for (var ax in this.axes) {
2898                 this.axes[ax]._ticks = [];
2899             }
2900             this.computePlotData();
2901             // for (var i=0; i<this.series.length; i++) {
2902             //     this.populatePlotData(this.series[i], i);
2903             // }
2904             this._sumy = 0;
2905             this._sumx = 0;
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;
2909             }
2910             this.draw();
2911             this.target.trigger('jqplotPostRedraw');
2912         };
2913         
2914         // method: draw
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');
2920                 var i,
2921                     j,
2922                     l,
2923                     tempseries;
2924                 for (i=0, l=$.jqplot.preDrawHooks.length; i<l; i++) {
2925                     $.jqplot.preDrawHooks[i].call(this);
2926                 }
2927                 for (i=0, l=this.preDrawHooks.length; i<l; i++) {
2928                     this.preDrawHooks.hooks[i].apply(this, this.preDrawSeriesHooks.args[i]);
2929                 }
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});
2935                 
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);
2939                 
2940                 var gridPadding = {top:0, left:0, bottom:0, right:0};
2941                 
2942                 if (this.legend.placement == "outsideGrid") {
2943                     // temporarily append the legend to get dimensions
2944                     this.target.append(legendElem);
2945                     switch (this.legend.location) {
2946                         case 'n':
2947                             gridPadding.top += this.legend.getHeight();
2948                             break;
2949                         case 's':
2950                             gridPadding.bottom += this.legend.getHeight();
2951                             break;
2952                         case 'ne':
2953                         case 'e':
2954                         case 'se':
2955                             gridPadding.right += this.legend.getWidth();
2956                             break;
2957                         case 'nw':
2958                         case 'w':
2959                         case 'sw':
2960                             gridPadding.left += this.legend.getWidth();
2961                             break;
2962                         default:  // same as 'ne'
2963                             gridPadding.right += this.legend.getWidth();
2964                             break;
2965                     }
2966                     legendElem = legendElem.detach();
2967                 }
2968                 
2969                 var ax = this.axes;
2970                 var name;
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));
2975                     ax[name].set();
2976                 }
2977                 if (ax.yaxis.show) {
2978                     gridPadding.left += ax.yaxis.getWidth();
2979                 }
2980                 var ra = ['y2axis', 'y3axis', 'y4axis', 'y5axis', 'y6axis', 'y7axis', 'y8axis', 'y9axis'];
2981                 var rapad = [0, 0, 0, 0, 0, 0, 0, 0];
2982                 var gpr = 0;
2983                 var n;
2984                 for (n=0; n<8; n++) {
2985                     if (ax[ra[n]].show) {
2986                         gpr += ax[ra[n]].getWidth();
2987                         rapad[n] = gpr;
2988                     }
2989                 }
2990                 gridPadding.right += gpr;
2991                 if (ax.x2axis.show) {
2992                     gridPadding.top += ax.x2axis.getHeight();
2993                 }
2994                 if (this.title.show) {
2995                     gridPadding.top += this.title.getHeight();
2996                 }
2997                 if (ax.xaxis.show) {
2998                     gridPadding.bottom += ax.xaxis.getHeight();
2999                 }
3000                 
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;
3015                     }
3016                 }
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]];
3021                     }
3022                     else if (this._gridPadding[arr[n]] == null) {
3023                         this._gridPadding[arr[n]] = this._defaultGridPadding[arr[n]];
3024                     }
3025                 }
3026                 
3027                 var legendPadding = this._gridPadding;
3028                 
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;
3034                     }
3035                 }
3036                 
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});
3042                 }
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});
3045             
3046                 this.target.append(this.grid.createElement(this._gridPadding, this));
3047                 this.grid.draw();
3048                 
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);
3059                 }
3060                 
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);
3068                 }
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);
3075             
3076                 // bind custom event handlers to regular events.
3077                 this.bindCustomEvents();
3078             
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}});
3085                     }
3086                     else {
3087                         this.drawSeries();
3088                     }
3089                 }
3090                 else {  // draw series before legend
3091                     this.drawSeries();
3092                     if (seriesLength) {
3093                         $(series[seriesLength-1].canvas._elem).after(legendElem);
3094                     }
3095                     this.legend.pack(legendPadding);                
3096                 }
3097             
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]);
3103                 }
3104             
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]);
3110                 }
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();
3115                 }
3117                 for (var i=0, l=$.jqplot.postDrawHooks.length; i<l; i++) {
3118                     $.jqplot.postDrawHooks[i].call(this);
3119                 }
3121                 for (var i=0, l=this.postDrawHooks.hooks.length; i<l; i++) {
3122                     this.postDrawHooks.hooks[i].apply(this, this.postDrawHooks.args[i]);
3123                 }
3124             
3125                 if (this.target.is(':visible')) {
3126                     this._drawCount += 1;
3127                 }
3129                 var temps, 
3130                     tempr,
3131                     sel,
3132                     _els;
3133                 // ughh.  ideally would hide all series then show them.
3134                 for (i=0, l=seriesLength; i<l; i++) {
3135                     temps = series[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);
3146                     }
3147                 }
3148                 _els = null;
3149             
3150                 this.target.trigger('jqplotPostDraw', [this]);
3151             }
3152         };
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();
3167             }
3168             else {
3169                 var tempgd = series2.gridData.slice(0).reverse();
3170             }
3172             if (series1.renderer.smooth) {
3173                 var gd = series1.renderer._smoothedData.concat(tempgd);
3174             }
3175             else {
3176                 var gd = series1.gridData.concat(tempgd);
3177             }
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);
3187         };
3188         
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() {
3199                     return false;
3200                 };
3201             }
3202             else {
3203                 this.eventCanvas._elem.bind('mouseup', {plot:this}, this.onMouseUp);
3204             }
3205         };
3206         
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'];
3213             var ax = plot.axes;
3214             var n, axis;
3215             for (n=11; n>0; n--) {
3216                 axis = an[n-1];
3217                 if (ax[axis].show) {
3218                     dataPos[axis] = ax[axis].series_p2u(gridPos[axis.charAt(0)]);
3219                 }
3220             }
3222             return {offsets:go, gridPos:gridPos, dataPos:dataPos};
3223         }
3224         
3225         
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;
3231             var threshold, t;
3232             for (k=plot.seriesStack.length-1; k>=0; k--) {
3233                 i = plot.seriesStack[k];
3234                 s = series[i];
3235                 hp = s._highlightThreshold;
3236                 switch (s.renderer.constructor) {
3237                     case $.jqplot.BarRenderer:
3238                         x = gridpos.x;
3239                         y = gridpos.y;
3240                         for (j=0; j<s._barPoints.length; j++) {
3241                             points = s._barPoints[j];
3242                             p = s.gridData[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]};
3245                             }
3246                         }
3247                         break;
3248                     case $.jqplot.PyramidRenderer:
3249                         x = gridpos.x;
3250                         y = gridpos.y;
3251                         for (j=0; j<s._barPoints.length; j++) {
3252                             points = s._barPoints[j];
3253                             p = s.gridData[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]};
3256                             }
3257                         }
3258                         break;
3259                     
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);
3267                         }
3268                         else if (x > 0 && -y < 0) {
3269                             theta = -Math.atan(-y/x);
3270                         }
3271                         else if (x < 0) {
3272                             theta = Math.PI - Math.atan(-y/x);
3273                         }
3274                         else if (x == 0 && -y > 0) {
3275                             theta = 3*Math.PI/2;
3276                         }
3277                         else if (x == 0 && -y < 0) {
3278                             theta = Math.PI/2;
3279                         }
3280                         else if (x == 0 && y == 0) {
3281                             theta = 0;
3282                         }
3283                         if (sa) {
3284                             theta -= sa;
3285                             if (theta < 0) {
3286                                 theta += 2*Math.PI;
3287                             }
3288                             else if (theta > 2*Math.PI) {
3289                                 theta -= 2*Math.PI;
3290                             }
3291                         }
3292             
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]};
3300                                 }
3301                             }
3302                         }
3303                         break;
3304                         
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);
3312                         }
3313                         else if (x > 0 && -y < 0) {
3314                             theta = -Math.atan(-y/x);
3315                         }
3316                         else if (x < 0) {
3317                             theta = Math.PI - Math.atan(-y/x);
3318                         }
3319                         else if (x == 0 && -y > 0) {
3320                             theta = 3*Math.PI/2;
3321                         }
3322                         else if (x == 0 && -y < 0) {
3323                             theta = Math.PI/2;
3324                         }
3325                         else if (x == 0 && y == 0) {
3326                             theta = 0;
3327                         }
3328                         if (sa) {
3329                             theta -= sa;
3330                             if (theta < 0) {
3331                                 theta += 2*Math.PI;
3332                             }
3333                             else if (theta > 2*Math.PI) {
3334                                 theta -= 2*Math.PI;
3335                             }
3336                         }
3337             
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]};
3345                                 }
3346                             }
3347                         }
3348                         break;
3349                         
3350                     case $.jqplot.BubbleRenderer:
3351                         x = gridpos.x;
3352                         y = gridpos.y;
3353                         var ret = null;
3354                         
3355                         if (s.show) {
3356                             for (var j=0; j<s.gridData.length; j++) {
3357                                 p = s.gridData[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)) {
3360                                    d0 = d;
3361                                    ret = {seriesIndex: i, pointIndex:j, gridData:p, data:s.data[j]};
3362                                 }
3363                             }
3364                             if (ret != null) {
3365                                 return ret;
3366                             }
3367                         }
3368                         break;
3369                         
3370                     case $.jqplot.FunnelRenderer:
3371                         x = gridpos.x;
3372                         y = gridpos.y;
3373                         var v = s._vertices,
3374                             vfirst = v[0],
3375                             vlast = v[v.length-1],
3376                             lex,
3377                             rex,
3378                             cv;
3379     
3380                         // equations of right and left sides, returns x, y values given height of section (y value and 2 points)
3381     
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];
3385                             var y = l + p1[1];
3386         
3387                             return [(y - b)/m, y];
3388                         }
3389     
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++) {
3394                             cv = v[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]};
3397                             }
3398                         }         
3399                         break;           
3400                     
3401                     case $.jqplot.LineRenderer:
3402                         x = gridpos.x;
3403                         y = gridpos.y;
3404                         r = s.renderer;
3405                         if (s.show) {
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
3408                                 var inside = false;
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   
3411                                     
3412                                     var numPoints = s._areaPoints.length;
3413                                     var ii;
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) {
3422                                                 inside = !inside;
3423                                             }
3424                                         }
3426                                         j = ii;
3427                                     }        
3428                                 }
3429                                 if (inside) {
3430                                     return {seriesIndex:i, pointIndex:null, gridData:s.gridData, data:s.data, points:s._areaPoints};
3431                                 }
3432                                 break;
3433                                 
3434                             }
3436                             else {
3437                                 t = s.markerRenderer.size/2+s.neighborThreshold;
3438                                 threshold = (t > 0) ? t : 0;
3439                                 for (var j=0; j<s.gridData.length; j++) {
3440                                     p = s.gridData[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]};
3447                                             }
3448                                         }
3449                                         // if an open hi low close chart
3450                                         else if (!r.hlc){
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]};
3454                                             }
3455                                         }
3456                                         // a hi low close chart
3457                                         else {
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]};
3461                                             }
3462                                         }
3463                             
3464                                     }
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)) {
3468                                            d0 = d;
3469                                            return {seriesIndex: i, pointIndex:j, gridData:p, data:s.data[j]};
3470                                         }
3471                                     }
3472                                 } 
3473                             }
3474                         }
3475                         break;
3476                         
3477                     default:
3478                         x = gridpos.x;
3479                         y = gridpos.y;
3480                         r = s.renderer;
3481                         if (s.show) {
3482                             t = s.markerRenderer.size/2+s.neighborThreshold;
3483                             threshold = (t > 0) ? t : 0;
3484                             for (var j=0; j<s.gridData.length; j++) {
3485                                 p = s.gridData[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]};
3492                                         }
3493                                     }
3494                                     // if an open hi low close chart
3495                                     else if (!r.hlc){
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]};
3499                                         }
3500                                     }
3501                                     // a hi low close chart
3502                                     else {
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]};
3506                                         }
3507                                     }
3508                             
3509                                 }
3510                                 else {
3511                                     d = Math.sqrt( (x-p[0]) * (x-p[0]) + (y-p[1]) * (y-p[1]) );
3512                                     if (d <= threshold && (d <= d0 || d0 == null)) {
3513                                        d0 = d;
3514                                        return {seriesIndex: i, pointIndex:j, gridData:p, data:s.data[j]};
3515                                     }
3516                                 }
3517                             } 
3518                         }
3519                         break;
3520                 }
3521             }
3522             
3523             return null;
3524         }
3525         
3526         
3527         
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]);
3538         };
3539         
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]);
3550         };
3551         
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]);
3560         };
3561         
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]);
3568         };
3569         
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]);
3580                 }
3581                 else {
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]);
3586                 }
3587             }
3588         };
3589         
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]);
3598         };
3599         
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]);
3608         };
3609         
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]);
3618         };
3619         
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){
3627             var i, series, ctx;
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); 
3643                     }
3644                 }
3645             }
3646             
3647             else {
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);
3660                 }
3661             }
3662             options = idx = i = series = ctx = null;
3663         };
3664         
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.
3670         //
3671         // Parameters:
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) {
3679                 return;
3680             }
3681             if (stackIndex == this.seriesStack.length -1) {
3682                 this.previousSeriesStack = this.seriesStack.slice(0);
3683                 return;
3684             }
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);
3693         };
3694         
3695         // method: moveSeriesToBack
3696         // This method requires jQuery 1.4+
3697         // Moves the specified series canvas behind all other series canvases.
3698         //
3699         // Parameters:
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) {
3707                 return;
3708             }
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);
3717         };
3718         
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
3723         // it to the front.
3724         this.restorePreviousSeriesOrder = function () {
3725             var i, j, serelem, shadelem, temp, move, keep;
3726             // if no change, return.
3727             if (this.seriesStack == this.previousSeriesStack) {
3728                 return;
3729             }
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);
3737             }
3738             temp = this.seriesStack.slice(0);
3739             this.seriesStack = this.previousSeriesStack.slice(0);
3740             this.previousSeriesStack = temp;
3741         };
3742         
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++) {
3750                 arr.push(i);
3751             }
3752             if (this.seriesStack == arr) {
3753                 return;
3754             }
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);
3762             }
3763         };
3764         
3765         this.activateTheme = function (name) {
3766             this.themeEngine.activate(this, name);
3767         };
3768     }
3769     
3770     
3771     // conpute a highlight color or array of highlight colors from given colors.
3772     $.jqplot.computeHighlightColors  = function(colors) {
3773         var ret;
3774         if ($.isArray(colors)) {
3775             ret = [];
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];
3785                 }
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]+')');
3790             }
3791         }
3792         else {
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];
3803             }
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]+')';
3808         }
3809         return ret;
3810     };
3811         
3812    $.jqplot.ColorGenerator = function(colors) {
3813         colors = colors || $.jqplot.config.defaultColors;
3814         var idx = 0;
3815         
3816         this.next = function () { 
3817             if (idx < colors.length) {
3818                 return colors[idx++];
3819             }
3820             else {
3821                 idx = 0;
3822                 return colors[idx++];
3823             }
3824         };
3825         
3826         this.previous = function () { 
3827             if (idx > 0) {
3828                 return colors[idx--];
3829             }
3830             else {
3831                 idx = colors.length-1;
3832                 return colors[idx];
3833             }
3834         };
3835         
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);
3839             return colors[idx];
3840         };
3841         
3842         this.setColors = function(c) {
3843             colors = c;
3844         };
3845         
3846         this.reset = function() {
3847             idx = 0;
3848         };
3850         this.getIndex = function() {
3851             return idx;
3852         };
3854         this.setIndex = function(index) {
3855             idx = index;
3856         };
3857     };
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);
3866         }
3867         var rgb;
3868         rgb = 'rgba('+parseInt(h.slice(0,2), 16)+', '+parseInt(h.slice(2,4), 16)+', '+parseInt(h.slice(4,6), 16);
3869         if (a) {
3870             rgb += ', '+a;
3871         }
3872         rgb += ')';
3873         return rgb;
3874     };
3875     
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);
3880         var h = '#';
3881         for (var i=1; i<4; i++) {
3882             var temp;
3883             if (m[i].search(/%/) != -1) {
3884                 temp = parseInt(255*m[i]/100, 10).toString(16);
3885                 if (temp.length == 1) {
3886                     temp = '0'+temp;
3887                 }
3888             }
3889             else {
3890                 temp = parseInt(m[i], 10).toString(16);
3891                 if (temp.length == 1) {
3892                     temp = '0'+temp;
3893                 }
3894             }
3895             h += temp;
3896         }
3897         return h;
3898     };
3899     
3900     // given a css color spec, return an rgb css color spec
3901     $.jqplot.normalize2rgb = function(s, a) {
3902         if (s.search(/^ *rgba?\(/) != -1) {
3903             return s; 
3904         }
3905         else if (s.search(/^ *#?[0-9a-fA-F]?[0-9a-fA-F]/) != -1) {
3906             return $.jqplot.hex2rgb(s, a);
3907         }
3908         else {
3909             throw 'invalid color spec';
3910         }
3911     };
3912     
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);
3920         var ret = [];
3921         for (var i=1; i<4; i++) {
3922             if (m[i].search(/%/) != -1) {
3923                 ret[i-1] = parseInt(255*m[i]/100, 10);
3924             }
3925             else {
3926                 ret[i-1] = parseInt(m[i], 10);
3927             }
3928         }
3929         ret[3] = parseFloat(m[4]) ? parseFloat(m[4]) : 1.0;
3930         return ret;
3931     };
3932     
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)'
4081     };
4083     
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
4091         this.axis;
4092         // prop: show
4093         // wether or not to show the tick (mark and label).
4094         this.show = true;
4095         // prop: label
4096         // The text or html for the label.
4097         this.label = '';
4098         this.fontFamily = null;
4099         this.fontSize = null;
4100         this.textColor = null;
4101         this._elem;
4102         // prop: escapeHTML
4103         // true to escape HTML entities in the label.
4104         this.escapeHTML = false;
4105         
4106         $.extend(true, this, options);
4107     };
4108     
4109     $.jqplot.AxisLabelRenderer.prototype = new $.jqplot.ElemContainer();
4110     $.jqplot.AxisLabelRenderer.prototype.constructor = $.jqplot.AxisLabelRenderer;
4111     
4112     $.jqplot.AxisLabelRenderer.prototype.init = function(options) {
4113         $.extend(true, this, options);
4114     };
4115     
4116     $.jqplot.AxisLabelRenderer.prototype.draw = function(ctx, plot) {
4117         // Memory Leaks patch
4118         if (this._elem) {
4119             this._elem.emptyForce();
4120             this._elem = null;
4121         }
4123         this._elem = $('<div style="position:absolute;" class="jqplot-'+this.axis+'-label"></div>');
4124         
4125         if (Number(this.label)) {
4126             this._elem.css('white-space', 'nowrap');
4127         }
4128         
4129         if (!this.escapeHTML) {
4130             this._elem.html(this.label);
4131         }
4132         else {
4133             this._elem.text(this.label);
4134         }
4135         if (this.fontFamily) {
4136             this._elem.css('font-family', this.fontFamily);
4137         }
4138         if (this.fontSize) {
4139             this._elem.css('font-size', this.fontSize);
4140         }
4141         if (this.textColor) {
4142             this._elem.css('color', this.textColor);
4143         }
4144         
4145         return this._elem;
4146     };
4147     
4148     $.jqplot.AxisLabelRenderer.prototype.pack = function() {
4149     };
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);
4156         // prop: mark
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
4160         this.axis;
4161         // prop: showMark
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;
4170         // prop: size
4171         // Length of the tick beyond the grid in pixels.
4172         // DEPRECATED: This has been superceeded by markSize
4173         this.size = 4;
4174         // prop:  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.
4177         this.markSize = 6;
4178         // prop: show
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.
4182         this.show = true;
4183         // prop: showLabel
4184         // wether or not to show the label.
4185         this.showLabel = true;
4186         this.label = null;
4187         this.value = null;
4188         this._styles = {};
4189         // prop: formatter
4190         // A class of a formatter for the tick text.  sprintf by default.
4191         this.formatter = $.jqplot.DefaultTickFormatter;
4192         // prop: prefix
4193         // String to prepend to the tick label.
4194         // Prefix is prepended to the formatted tick label.
4195         this.prefix = '';
4196         // prop: suffix
4197         // String to append to the tick label.
4198         // Suffix is appended to the formatted tick label.
4199         this.suffix = '';
4200         // prop: formatString
4201         // string passed to the formatter.
4202         this.formatString = '';
4203         // prop: fontFamily
4204         // css spec for the font-family css attribute.
4205         this.fontFamily;
4206         // prop: fontSize
4207         // css spec for the font-size css attribute.
4208         this.fontSize;
4209         // prop: textColor
4210         // css spec for the color attribute.
4211         this.textColor;
4212         // prop: escapeHTML
4213         // true to escape HTML entities in the label.
4214         this.escapeHTML = false;
4215         this._elem;
4216                 this._breakTick = false;
4217         
4218         $.extend(true, this, options);
4219     };
4220     
4221     $.jqplot.AxisTickRenderer.prototype.init = function(options) {
4222         $.extend(true, this, options);
4223     };
4224     
4225     $.jqplot.AxisTickRenderer.prototype = new $.jqplot.ElemContainer();
4226     $.jqplot.AxisTickRenderer.prototype.constructor = $.jqplot.AxisTickRenderer;
4227     
4228     $.jqplot.AxisTickRenderer.prototype.setTick = function(value, axisName, isMinor) {
4229         this.value = value;
4230         this.axis = axisName;
4231         if (isMinor) {
4232             this.isMinorTick = true;
4233         }
4234         return this;
4235     };
4236     
4237     $.jqplot.AxisTickRenderer.prototype.draw = function() {
4238         if (this.label === null) {
4239             this.label = this.prefix + this.formatter(this.formatString, this.value) + this.suffix;
4240         }
4241         var style = {position: 'absolute'};
4242         if (Number(this.label)) {
4243             style['whitSpace'] = 'nowrap';
4244         }
4245         
4246         // Memory Leaks patch
4247         if (this._elem) {
4248             this._elem.emptyForce();
4249             this._elem = null;
4250         }
4252         this._elem = $(document.createElement('div'));
4253         this._elem.addClass("jqplot-"+this.axis+"-tick");
4254         
4255         if (!this.escapeHTML) {
4256             this._elem.html(this.label);
4257         }
4258         else {
4259             this._elem.text(this.label);
4260         }
4261         
4262         this._elem.css(style);
4264         for (var s in this._styles) {
4265             this._elem.css(s, this._styles[s]);
4266         }
4267         if (this.fontFamily) {
4268             this._elem.css('font-family', this.fontFamily);
4269         }
4270         if (this.fontSize) {
4271             this._elem.css('font-size', this.fontSize);
4272         }
4273         if (this.textColor) {
4274             this._elem.css('color', this.textColor);
4275         }
4276                 if (this._breakTick) {
4277                         this._elem.addClass('jqplot-breakTick');
4278                 }
4279         
4280         return this._elem;
4281     };
4282         
4283     $.jqplot.DefaultTickFormatter = function (format, val) {
4284         if (typeof val == 'number') {
4285             if (!format) {
4286                 format = $.jqplot.config.defaultTickFormatString;
4287             }
4288             return $.jqplot.sprintf(format, val);
4289         }
4290         else {
4291             return String(val);
4292         }
4293     };
4294         
4295     $.jqplot.PercentTickFormatter = function (format, val) {
4296         if (typeof val == 'number') {
4297             val = 100 * val;
4298             if (!format) {
4299                 format = $.jqplot.config.defaultTickFormatString;
4300             }
4301             return $.jqplot.sprintf(format, val);
4302         }
4303         else {
4304             return String(val);
4305         }
4306     };
4307     
4308     $.jqplot.AxisTickRenderer.prototype.pack = function() {
4309     };
4310      
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();
4316     };
4317     
4318     // called with context of Grid object
4319     $.jqplot.CanvasGridRenderer.prototype.init = function(options) {
4320         this._ctx;
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);
4325     };
4326     
4327     // called with context of Grid.
4328     $.jqplot.CanvasGridRenderer.prototype.createElement = function(plot) {
4329         var elem;
4330         // Memory Leaks patch
4331         if (this._elem) {
4332           if ($.jqplot.use_excanvas && window.G_vmlCanvasManager.uninitElement !== undefined) {
4333             elem = this._elem.get(0);
4334             window.G_vmlCanvasManager.uninitElement(elem);
4335             elem = null;
4336           }
4337           
4338           this._elem.emptyForce();
4339           this._elem = null;
4340         }
4341       
4342         elem = plot.canvasManager.getCanvas();
4344         var w = this._plotDimensions.width;
4345         var h = this._plotDimensions.height;
4346         elem.width = w;
4347         elem.height = h;
4348         this._elem = $(elem);
4349         this._elem.addClass('jqplot-grid-canvas');
4350         this._elem.css({ position: 'absolute', left: 0, top: 0 });
4351         
4352                 elem = plot.canvasManager.initCanvas(elem);
4353                 
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
4361         elem = null;
4362         return this._elem;
4363     };
4364     
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.
4370         ctx.save();
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);
4374         
4375         ctx.save();
4376         ctx.lineJoin = 'miter';
4377         ctx.lineCap = 'butt';
4378         ctx.lineWidth = this.gridLineWidth;
4379         ctx.strokeStyle = this.gridLineColor;
4380         var b, e, s, m;
4381         var ax = ['xaxis', 'yaxis', 'x2axis', 'y2axis'];
4382         for (var i=4; i>0; i--) {
4383             var name = ax[i-1];
4384             var axis = axes[name];
4385             var ticks = axis._ticks;
4386             var numticks = ticks.length;
4387             if (axis.show) {
4388                 if (axis.drawBaseline) {
4389                     var bopts = {};
4390                     if (axis.baselineWidth !== null) {
4391                         bopts.lineWidth = axis.baselineWidth;
4392                     }
4393                     if (axis.baselineColor !== null) {
4394                         bopts.strokeStyle = axis.baselineColor;
4395                     }
4396                     switch (name) {
4397                         case 'xaxis':
4398                             drawLine (this._left, this._bottom, this._right, this._bottom, bopts);
4399                             break;
4400                         case 'yaxis':
4401                             drawLine (this._left, this._bottom, this._left, this._top, bopts);
4402                             break;
4403                         case 'x2axis':
4404                             drawLine (this._left, this._bottom, this._right, this._bottom, bopts);
4405                             break;
4406                         case 'y2axis':
4407                             drawLine (this._right, this._bottom, this._right, this._top, bopts);
4408                             break;
4409                     }
4410                 }
4411                 for (var j=numticks; j>0; j--) {
4412                     var t = ticks[j-1];
4413                     if (t.show) {
4414                         var pos = Math.round(axis.u2p(t.value)) + 0.5;
4415                         switch (name) {
4416                             case 'xaxis':
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);
4420                                 }
4421                                 // draw the mark
4422                                 if (t.showMark && t.mark && ((!t.isMinorTick && axis.drawMajorTickMarks) || (t.isMinorTick && axis.drawMinorTickMarks)) ) {
4423                                     s = t.markSize;
4424                                     m = t.mark;
4425                                     var pos = Math.round(axis.u2p(t.value)) + 0.5;
4426                                     switch (m) {
4427                                         case 'outside':
4428                                             b = this._bottom;
4429                                             e = this._bottom+s;
4430                                             break;
4431                                         case 'inside':
4432                                             b = this._bottom-s;
4433                                             e = this._bottom;
4434                                             break;
4435                                         case 'cross':
4436                                             b = this._bottom-s;
4437                                             e = this._bottom+s;
4438                                             break;
4439                                         default:
4440                                             b = this._bottom;
4441                                             e = this._bottom+s;
4442                                             break;
4443                                     }
4444                                     // draw the shadow
4445                                     if (this.shadow) {
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});
4447                                     }
4448                                     // draw the line
4449                                     drawLine(pos, b, pos, e);
4450                                 }
4451                                 break;
4452                             case 'yaxis':
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);
4456                                 }
4457                                 // draw the mark
4458                                 if (t.showMark && t.mark && ((!t.isMinorTick && axis.drawMajorTickMarks) || (t.isMinorTick && axis.drawMinorTickMarks)) ) {
4459                                     s = t.markSize;
4460                                     m = t.mark;
4461                                     var pos = Math.round(axis.u2p(t.value)) + 0.5;
4462                                     switch (m) {
4463                                         case 'outside':
4464                                             b = this._left-s;
4465                                             e = this._left;
4466                                             break;
4467                                         case 'inside':
4468                                             b = this._left;
4469                                             e = this._left+s;
4470                                             break;
4471                                         case 'cross':
4472                                             b = this._left-s;
4473                                             e = this._left+s;
4474                                             break;
4475                                         default:
4476                                             b = this._left-s;
4477                                             e = this._left;
4478                                             break;
4479                                             }
4480                                     // draw the shadow
4481                                     if (this.shadow) {
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});
4483                                     }
4484                                     drawLine(b, pos, e, pos, {strokeStyle:axis.borderColor});
4485                                 }
4486                                 break;
4487                             case 'x2axis':
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);
4491                                 }
4492                                 // draw the mark
4493                                 if (t.showMark && t.mark && ((!t.isMinorTick && axis.drawMajorTickMarks) || (t.isMinorTick && axis.drawMinorTickMarks)) ) {
4494                                     s = t.markSize;
4495                                     m = t.mark;
4496                                     var pos = Math.round(axis.u2p(t.value)) + 0.5;
4497                                     switch (m) {
4498                                         case 'outside':
4499                                             b = this._top-s;
4500                                             e = this._top;
4501                                             break;
4502                                         case 'inside':
4503                                             b = this._top;
4504                                             e = this._top+s;
4505                                             break;
4506                                         case 'cross':
4507                                             b = this._top-s;
4508                                             e = this._top+s;
4509                                             break;
4510                                         default:
4511                                             b = this._top-s;
4512                                             e = this._top;
4513                                             break;
4514                                             }
4515                                     // draw the shadow
4516                                     if (this.shadow) {
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});
4518                                     }
4519                                     drawLine(pos, b, pos, e);
4520                                 }
4521                                 break;
4522                             case 'y2axis':
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);
4526                                 }
4527                                 // draw the mark
4528                                 if (t.showMark && t.mark && ((!t.isMinorTick && axis.drawMajorTickMarks) || (t.isMinorTick && axis.drawMinorTickMarks)) ) {
4529                                     s = t.markSize;
4530                                     m = t.mark;
4531                                     var pos = Math.round(axis.u2p(t.value)) + 0.5;
4532                                     switch (m) {
4533                                         case 'outside':
4534                                             b = this._right;
4535                                             e = this._right+s;
4536                                             break;
4537                                         case 'inside':
4538                                             b = this._right-s;
4539                                             e = this._right;
4540                                             break;
4541                                         case 'cross':
4542                                             b = this._right-s;
4543                                             e = this._right+s;
4544                                             break;
4545                                         default:
4546                                             b = this._right;
4547                                             e = this._right+s;
4548                                             break;
4549                                             }
4550                                     // draw the shadow
4551                                     if (this.shadow) {
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});
4553                                     }
4554                                     drawLine(b, pos, e, pos, {strokeStyle:axis.borderColor});
4555                                 }
4556                                 break;
4557                             default:
4558                                 break;
4559                         }
4560                     }
4561                 }
4562                 t = null;
4563             }
4564             axis = null;
4565             ticks = null;
4566         }
4567         // Now draw grid lines for additional y axes
4568         //////
4569         // TO DO: handle yMidAxis
4570         //////
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;
4575             if (axis.show) {
4576                 var tn = ticks[axis.numberTicks-1];
4577                 var t0 = ticks[0];
4578                 var left = axis.getLeft();
4579                 var points = [[left, tn.getTop() + tn.getHeight()/2], [left, t0.getTop() + t0.getHeight()/2 + 1.0]];
4580                 // draw the shadow
4581                 if (this.shadow) {
4582                     this.renderer.shadowRenderer.draw(ctx, points, {lineCap:'butt', fill:false, closePath:false});
4583                 }
4584                 // draw the line
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--) {
4588                     var t = ticks[j-1];
4589                     s = t.markSize;
4590                     m = t.mark;
4591                     var pos = Math.round(axis.u2p(t.value)) + 0.5;
4592                     if (t.showMark && t.mark) {
4593                         switch (m) {
4594                             case 'outside':
4595                                 b = left;
4596                                 e = left+s;
4597                                 break;
4598                             case 'inside':
4599                                 b = left-s;
4600                                 e = left;
4601                                 break;
4602                             case 'cross':
4603                                 b = left-s;
4604                                 e = left+s;
4605                                 break;
4606                             default:
4607                                 b = left;
4608                                 e = left+s;
4609                                 break;
4610                         }
4611                         points = [[b,pos], [e,pos]];
4612                         // draw the shadow
4613                         if (this.shadow) {
4614                             this.renderer.shadowRenderer.draw(ctx, points, {lineCap:'butt', lineWidth:this.gridLineWidth*1.5, offset:this.gridLineWidth*0.75, fill:false, closePath:false});
4615                         }
4616                         // draw the line
4617                         drawLine(b, pos, e, pos, {strokeStyle:axis.borderColor});
4618                     }
4619                     t = null;
4620                 }
4621                 t0 = null;
4622             }
4623             axis = null;
4624             ticks =  null;
4625         }
4626         
4627         ctx.restore();
4628         
4629         function drawLine(bx, by, ex, ey, opts) {
4630             ctx.save();
4631             opts = opts || {};
4632             if (opts.lineWidth == null || opts.lineWidth != 0){
4633                 $.extend(true, ctx, opts);
4634                 ctx.beginPath();
4635                 ctx.moveTo(bx, by);
4636                 ctx.lineTo(ex, ey);
4637                 ctx.stroke();
4638                 ctx.restore();
4639             }
4640         }
4641         
4642         if (this.shadow) {
4643             var points = [[this._left, this._bottom], [this._right, this._bottom], [this._right, this._top]];
4644             this.renderer.shadowRenderer.draw(ctx, points);
4645         }
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});
4653         }
4654         // ctx.lineWidth = this.borderWidth;
4655         // ctx.strokeStyle = this.borderColor;
4656         // ctx.strokeRect(this._left, this._top, this._width, this._height);
4657         
4658         ctx.restore();
4659         ctx =  null;
4660         axes = null;
4661     };
4663     // Class: $.jqplot.DivTitleRenderer
4664     // The default title renderer for jqPlot.  This class has no options beyond the <Title> class. 
4665     $.jqplot.DivTitleRenderer = function() {
4666     };
4667     
4668     $.jqplot.DivTitleRenderer.prototype.init = function(options) {
4669         $.extend(true, this, options);
4670     };
4671     
4672     $.jqplot.DivTitleRenderer.prototype.draw = function() {
4673         // Memory Leaks patch
4674         if (this._elem) {
4675             this._elem.emptyForce();
4676             this._elem = null;
4677         }
4679         var r = this.renderer;
4680         var elem = document.createElement('div');
4681         this._elem = $(elem);
4682         this._elem.addClass('jqplot-title');
4684         if (!this.text) {
4685             this.show = false;
4686             this._elem.height(0);
4687             this._elem.width(0);
4688         }
4689         else if (this.text) {
4690             var color;
4691             if (this.color) {
4692                 color = this.color;
4693             }
4694             else if (this.textColor) {
4695                 color = this.textColor;
4696             }
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';
4703             }
4704             if (this.fontSize) {
4705                 styles['fontSize'] = this.fontSize;
4706             }
4707             if (typeof this.textAlign === 'string') {
4708                 styles['textAlign'] = this.textAlign;
4709             }
4710             else {
4711                 styles['textAlign'] = 'center';
4712             }
4713             if (color) {
4714                 styles['color'] = color;
4715             }
4716             if (this.paddingBottom) {
4717                 styles['paddingBottom'] = this.paddingBottom;
4718             }
4719             if (this.fontFamily) {
4720                 styles['fontFamily'] = this.fontFamily;
4721             }
4723             this._elem.css(styles);
4724             if (this.escapeHtml) {
4725                 this._elem.text(this.text);
4726             }
4727             else {
4728                 this._elem.html(this.text);
4729             }
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);
4740             // }
4741         }
4743         elem = null;
4744         
4745         return this._elem;
4746     };
4747     
4748     $.jqplot.DivTitleRenderer.prototype.pack = function() {
4749         // nothing to do here
4750     };
4751   
4753     var dotlen = 0.1;
4755     $.jqplot.LinePattern = function (ctx, pattern) {
4757                 var defaultLinePatterns = {
4758                         dotted: [ dotlen, $.jqplot.config.dotGapLength ],
4759                         dashed: [ $.jqplot.config.dashLength, $.jqplot.config.gapLength ],
4760                         solid: null
4761                 };      
4763         if (typeof pattern === 'string') {
4764             if (pattern[0] === '.' || pattern[0] === '-') {
4765                 var s = pattern;
4766                 pattern = [];
4767                 for (var i=0, imax=s.length; i<imax; i++) {
4768                     if (s[i] === '.') {
4769                         pattern.push( dotlen );
4770                     }
4771                     else if (s[i] === '-') {
4772                         pattern.push( $.jqplot.config.dashLength );
4773                     }
4774                     else {
4775                         continue;
4776                     }
4777                     pattern.push( $.jqplot.config.gapLength );
4778                 }
4779             }
4780             else {
4781                 pattern = defaultLinePatterns[pattern];
4782             }
4783         }
4785         if (!(pattern && pattern.length)) {
4786             return ctx;
4787         }
4789         var patternIndex = 0;
4790         var patternDistance = pattern[0];
4791         var px = 0;
4792         var py = 0;
4793         var pathx0 = 0;
4794         var pathy0 = 0;
4796         var moveTo = function (x, y) {
4797             ctx.moveTo( x, y );
4798             px = x;
4799             py = y;
4800             pathx0 = x;
4801             pathy0 = y;
4802         };
4804         var lineTo = function (x, y) {
4805             var scale = ctx.lineWidth;
4806             var dx = x - px;
4807             var dy = y - py;
4808             var dist = Math.sqrt(dx*dx+dy*dy);
4809             if ((dist > 0) && (scale > 0)) {
4810                 dx /= dist;
4811                 dy /= dist;
4812                 while (true) {
4813                     var dp = scale * patternDistance;
4814                     if (dp < dist) {
4815                         px += dp * dx;
4816                         py += dp * dy;
4817                         if ((patternIndex & 1) == 0) {
4818                             ctx.lineTo( px, py );
4819                         }
4820                         else {
4821                             ctx.moveTo( px, py );
4822                         }
4823                         dist -= dp;
4824                         patternIndex++;
4825                         if (patternIndex >= pattern.length) {
4826                             patternIndex = 0;
4827                         }
4828                         patternDistance = pattern[patternIndex];
4829                     }
4830                     else {
4831                         px = x;
4832                         py = y;
4833                         if ((patternIndex & 1) == 0) {
4834                             ctx.lineTo( px, py );
4835                         }
4836                         else {
4837                             ctx.moveTo( px, py );
4838                         }
4839                         patternDistance -= dist / scale;
4840                         break;
4841                     }
4842                 }
4843             }
4844         };
4846         var beginPath = function () {
4847             ctx.beginPath();
4848         };
4850         var closePath = function () {
4851             lineTo( pathx0, pathy0 );
4852         };
4854         return {
4855             moveTo: moveTo,
4856             lineTo: lineTo,
4857             beginPath: beginPath,
4858             closePath: closePath
4859         };
4860     };
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();
4868     };
4869     
4870     // called with scope of series.
4871     $.jqplot.LineRenderer.prototype.init = function(options, plot) {
4872         // Group: Properties
4873         //
4874         options = options || {};
4875         this._type='line';
4876         this.renderer.animation = {
4877             show: false,
4878             direction: 'left',
4879             speed: 2500,
4880             _supported: true
4881         };
4882         // prop: smooth
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 = [];
4903         // prop: bandData
4904         // Data used to draw error bands or confidence intervals above/below a line.
4905         //
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:
4908         // 
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.
4914         //
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.
4920         //
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 = [];
4929         // Group: bands
4930         // Banding around line, e.g error bands or confidence intervals.
4931         this.renderer.bands = {
4932             // prop: show
4933             // true to show the bands.  If bandData or interval is
4934             // supplied, show will be set to true by default.
4935             show: false,
4936             hiData: [],
4937             lowData: [],
4938             // prop: color
4939             // color of lines at top and bottom of bands [default: series color].
4940             color: this.color,
4941             // prop: showLines
4942             // True to show lines at top and bottom of bands [default: false].
4943             showLines: false,
4944             // prop: fill
4945             // True to fill area between bands [default: true].
4946             fill: true,
4947             // prop: fillColor
4948             // css color spec for filled area.  [default: series color].
4949             fillColor: null,
4950             _min: null,
4951             _max: null,
4952             // prop: interval
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%']
4956             interval: '3%'
4957         };
4960         var lopts = {highlightMouseOver: options.highlightMouseOver, highlightMouseDown: options.highlightMouseDown, highlightColor: options.highlightColor};
4961         
4962         delete (options.highlightMouseOver);
4963         delete (options.highlightMouseDown);
4964         delete (options.highlightColor);
4965         
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;
4973         }
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;
4978         }
4980         // if plot is filled, turn off bands.
4981         if (this.fill) {
4982             this.renderer.bands.show = false;
4983         }
4985         if (this.renderer.bands.show) {
4986             this.renderer.initBands.call(this, this.renderer.options, plot);
4987         }
4990         // smoothing is not compatible with stacked lines, disable
4991         if (this._stack) {
4992             this.renderer.smooth = false;
4993         }
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;
5006             }
5007             // for skinny lines, don't make such a big shadow.
5008             else {
5009                 shadow_offset = 1.25 * Math.atan((this.lineWidth/2.5))/0.785398163;
5010             }
5011         }
5012         
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 = [[],[]];
5017         
5018         if (!this.isTrendline && this.fill || this.renderer.bands.show) {
5019             // Group: Properties
5020             //        
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;
5035             }
5036         
5037             $.extend(true, this, {highlightMouseOver: lopts.highlightMouseOver, highlightMouseDown: lopts.highlightMouseDown, highlightColor: lopts.highlightColor});
5038             
5039             if (!this.highlightColor) {
5040                 var fc = (this.renderer.bands.show) ? this.renderer.bands.fillColor : this.fillColor;
5041                 this.highlightColor = $.jqplot.computeHighlightColors(fc);
5042             }
5043             // turn off (disable) the highlighter plugin
5044             if (this.highlighter) {
5045                 this.highlighter.show = false;
5046             }
5047         }
5048         
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);
5058         }
5060     };
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;
5067         bands.hiData = [];
5068         bands.lowData = [];
5069         var data = this.data;
5070         bands._max = null;
5071         bands._min = null;
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.
5079                 var p;
5080                 var bdminidx = 0, bdmaxidx = 0;
5081                 for (var i = 0, l = bd[0].length; i<l; i++) {
5082                     p = bd[0][i];
5083                     if ((p[1] != null && p[1] > bands._max) || bands._max == null) {
5084                         bands._max = p[1];
5085                     }
5086                     if ((p[1] != null && p[1] < bands._min) || bands._min == null) {
5087                         bands._min = p[1];
5088                     }
5089                 }
5090                 for (var i = 0, l = bd[1].length; i<l; i++) {
5091                     p = bd[1][i];
5092                     if ((p[1] != null && p[1] > bands._max) || bands._max == null) {
5093                         bands._max = p[1];
5094                         bdmaxidx = 1;
5095                     }
5096                     if ((p[1] != null && p[1] < bands._min) || bands._min == null) {
5097                         bands._min = p[1];
5098                         bdminidx = 1;
5099                     }
5100                 }
5102                 if (bdmaxidx === bdminidx) {
5103                     bands.show = false;
5104                 }
5106                 bands.hiData = bd[bdmaxidx];
5107                 bands.lowData = bd[bdminidx];
5108             }
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]]);
5118                 }
5119             }
5121             // we don't have proper data array, don't show bands.
5122             else {
5123                 bands.show = false;
5124             }
5125         }
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]]);
5136             }
5137         }
5139         // don't have proper data, auto calculate
5140         else {
5141             var intrv = bands.interval;
5142             var a = null;
5143             var b = null;
5144             var afunc = null;
5145             var bfunc = null;
5147             if ($.isArray(intrv)) {
5148                 a = intrv[0];
5149                 b = intrv[1];
5150             }
5151             else {
5152                 a = intrv;
5153             }
5155             if (isNaN(a)) {
5156                 // we have a string
5157                 if (a.charAt(a.length - 1) === '%') {
5158                     afunc = 'multiply';
5159                     a = parseFloat(a)/100 + 1;
5160                 }
5161             }
5163             else {
5164                 a = parseFloat(a);
5165                 afunc = 'add';
5166             }
5168             if (b !== null && isNaN(b)) {
5169                 // we have a string
5170                 if (b.charAt(b.length - 1) === '%') {
5171                     bfunc = 'multiply';
5172                     b = parseFloat(b)/100 + 1;
5173                 }
5174             }
5176             else if (b !== null) {
5177                 b = parseFloat(b);
5178                 bfunc = 'add';
5179             }
5181             if (a !== null) {
5182                 if (b === null) {
5183                     b = -a;
5184                     bfunc = afunc;
5185                     if (bfunc === 'multiply') {
5186                         b += 2;
5187                     }
5188                 }
5190                 // make sure a always applies to hi band.
5191                 if (a < b) {
5192                     var temp = a;
5193                     a = b;
5194                     b = temp;
5195                     temp = afunc;
5196                     afunc = bfunc;
5197                     bfunc = temp;
5198                 }
5200                 for (var i=0, l = data.length; i < l; i++) {
5201                     switch (afunc) {
5202                         case 'add':
5203                             bands.hiData.push([data[i][0], data[i][1] + a]);
5204                             break;
5205                         case 'multiply':
5206                             bands.hiData.push([data[i][0], data[i][1] * a]);
5207                             break;
5208                     }
5209                     switch (bfunc) {
5210                         case 'add':
5211                             bands.lowData.push([data[i][0], data[i][1] + b]);
5212                             break;
5213                         case 'multiply':
5214                             bands.lowData.push([data[i][0], data[i][1] * b]);
5215                             break;
5216                     }
5217                 }
5218             }
5220             else {
5221                 bands.show = false;
5222             }
5223         }
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];
5230             }
5231         }
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];
5235             }
5236         }
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;
5242         // }
5244         // if (bands.hiData.length != this.data.length) {
5245         //     bands.show = false;
5246         // }
5248         if (bands.fillColor === null) {
5249             var c = $.jqplot.getColorComponents(bands.color);
5250             // now adjust alpha to differentiate fill
5251             c[3] = c[3] * 0.5;
5252             bands.fillColor = 'rgba(' + c[0] +', '+ c[1] +', '+ c[2] +', '+ c[3] + ')';
5253         }
5254     };
5256     function getSteps (d, f) {
5257         return (3.4182054+f) * Math.pow(d, -0.3534992);
5258     }
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;
5263     }
5265     function tanh (x) {
5266         var a = (Math.exp(2*x) - 1) / (Math.exp(2*x) + 1);
5267         return a;
5268     }
5270     //////////
5271     // computeConstrainedSmoothedData
5272     // An implementation of the constrained cubic spline interpolation
5273     // method as presented in:
5274     //
5275     // Kruger, CJC, Constrained Cubic Spine Interpolation for Chemical Engineering Applications
5276     // http://www.korf.co.uk/spline.pdf
5277     //
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
5280     //
5281     /////////
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; 
5289         var steps =null;
5290         var _steps = null;
5291         var dist = gd.length/dim;
5292         var _smoothedData = [];
5293         var _smoothedPlotData = [];
5295         if (!isNaN(parseFloat(smooth))) {
5296             steps = parseFloat(smooth);
5297         }
5298         else {
5299             steps = getSteps(dist, 0.5);
5300         }
5302         var yy = [];
5303         var xx = [];
5305         for (var i=0, l = gd.length; i<l; i++) {
5306             yy.push(gd[i][1]);
5307             xx.push(gd[i][0]);
5308         }
5310         function dxx(x1, x0) {
5311             if (x1 - x0 == 0) {
5312                 return Math.pow(10,10);
5313             }
5314             else {
5315                 return x1 - x0;
5316             }
5317         }
5319         var A, B, C, D;
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++) {
5323             var gxx = [];
5324             var ggxx = [];
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);
5331                 }
5332                 else if (yy[i+1] - yy[i] == 0 || yy[i] - yy[i-1] == 0) {
5333                     gxx[j] = 0;
5334                 }
5335                 else if (((xx[i+1] - xx[i]) / (yy[i+1] - yy[i]) + (xx[i] - xx[i-1]) / (yy[i] - yy[i-1])) == 0 ) {
5336                     gxx[j] = 0;
5337                 }
5338                 else if ( (yy[i+1] - yy[i]) * (yy[i] - yy[i-1]) < 0 ) {
5339                     gxx[j] = 0;
5340                 }
5342                 else {
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]));
5344                 }
5345             }
5347             // Reset first derivative (slope) at first and last point
5348             if (num == 1) {
5349                 // First point has 0 2nd derivative
5350                 gxx[0] = 3 / 2 * (yy[1] - yy[0]) / dxx(xx[1], xx[0]) - gxx[1] / 2;
5351             }
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;
5355             }   
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;
5368             var temp, tempx;
5370             for (var j = 0, l = steps; j < l; j++) {
5371                 temp = [];
5372                 tempx = xx[num - 1] + j * increment;
5373                 temp.push(tempx);
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])]);
5377             }
5378         }
5380         _smoothedData.push(gd[i]);
5381         _smoothedPlotData.push([xp(gd[i][0]), yp(gd[i][1])]);
5383         return [_smoothedData, _smoothedPlotData];
5384     }
5386     ///////
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:
5391     //
5392     // http://groups.google.com/group/jqplot-users/browse_thread/thread/748be6a445723cea?pli=1
5393     //
5394     // with a blog post:
5395     //
5396     // http://blog.statscollector.com/a-plugin-renderer-for-jqplot-to-draw-a-hermite-spline/
5397     //
5398     // and download of the original plugin:
5399     //
5400     // http://blog.statscollector.com/wp-content/uploads/2010/02/jqplot.hermiteSplineRenderer.js
5401     //////////
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; 
5410         var steps =null;
5411         var _steps = null;
5412         var a = null;
5413         var a1 = null;
5414         var a2 = null;
5415         var slope = null;
5416         var slope2 = null;
5417         var temp = null;
5418         var t, s, h1, h2, h3, h4;
5419         var TiX, TiY, Ti1X, Ti1Y;
5420         var pX, pY, p;
5421         var sd = [];
5422         var spd = [];
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);
5429         }
5430         else {
5431             steps = getSteps(dist, 0.5);
5432         }
5433         if (!isNaN(parseFloat(tension))) {
5434             tension = parseFloat(tension);
5435         }
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]));
5442                 min = 0.3;
5443                 max = 0.6;
5444                 stretch = (max - min)/2.0;
5445                 scale = 2.5;
5446                 shift = -1.4;
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. 
5453                 if (i > 0) {
5454                     slope2 = Math.abs((gd[i][1] - gd[i-1][1]) / (gd[i][0] - gd[i-1][0]));
5455                 }
5456                 temp = slope2/scale + shift;
5458                 a2 = stretch * tanh(temp) - stretch * tanh(shift) + min;
5460                 a = (a1 + a2)/2.0;
5462             }
5463             else {
5464                 a = tension;
5465             }
5466             for (t=0; t < steps; t++) {
5467                 s = t / steps;
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);     
5472                 
5473                 if (gd[i-1]) {  
5474                     TiX = a * (gd[i+1][0] - gd[i-1][0]); 
5475                     TiY = a * (gd[i+1][1] - gd[i-1][1]);
5476                 } else {
5477                     TiX = a * (gd[i+1][0] - gd[i][0]); 
5478                     TiY = a * (gd[i+1][1] - gd[i][1]);                                  
5479                 }
5480                 if (gd[i+2]) {  
5481                     Ti1X = a * (gd[i+2][0] - gd[i][0]); 
5482                     Ti1Y = a * (gd[i+2][1] - gd[i][1]);
5483                 } else {
5484                     Ti1X = a * (gd[i+1][0] - gd[i][0]); 
5485                     Ti1Y = a * (gd[i+1][1] - gd[i][1]);                                 
5486                 }
5487                 
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;
5490                 p = [pX, pY];
5492                 _smoothedData.push(p);
5493                 _smoothedPlotData.push([xp(pX), yp(pY)]);
5494             }
5495         }
5496         _smoothedData.push(gd[l]);
5497         _smoothedPlotData.push([xp(gd[l][0]), yp(gd[l][1])]);
5499         return [_smoothedData, _smoothedPlotData];
5500     }
5501     
5502     // setGridData
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;
5512         this.gridData = [];
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])]);
5526             }
5527             // else if there is a null, preserve it.
5528             else if (data[i][0] == null) {
5529                 hasNull = true;
5530                 this.gridData.push([null, yp.call(this._yaxis, data[i][1])]);
5531             }
5532             else if (data[i][1] == null) {
5533                 hasNull = true;
5534                 this.gridData.push([xp.call(this._xaxis, data[i][0]), null]);
5535             }
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])]);
5539             }
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])]);
5543             }  
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]);
5546             }
5547         }
5549         // don't do smoothing or bands on broken lines.
5550         if (hasNull) {
5551             this.renderer.smooth = false;
5552             if (this._type === 'line') {
5553                 bands.show = false;
5554             }
5555         }
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])]);
5560             }
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])]);
5563             }
5564         }
5566         // calculate smoothed data if enough points and no nulls
5567         if (this._type === 'line' && this.renderer.smooth && this.gridData.length > 2) {
5568             var ret;
5569             if (this.renderer.constrainSmoothing) {
5570                 ret = computeConstrainedSmoothedData.call(this, this.gridData);
5571                 this.renderer._smoothedData = ret[0];
5572                 this.renderer._smoothedPlotData = ret[1];
5574                 if (bands.show) {
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];
5579                 }
5581                 ret = null;
5582             }
5583             else {
5584                 ret = computeHermiteSmoothedData.call(this, this.gridData);
5585                 this.renderer._smoothedData = ret[0];
5586                 this.renderer._smoothedPlotData = ret[1];
5588                 if (bands.show) {
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];
5593                 }
5595                 ret = null;
5596             }
5597         }
5598     };
5599     
5600     // makeGridData
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;
5610         var gd = [];
5611         var pgd = [];
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])]);
5624             }
5625             // else if there is a null, preserve it.
5626             else if (data[i][0] == null) {
5627                 hasNull = true;
5628                 gd.push([null, yp.call(this._yaxis, data[i][1])]);
5629             }
5630             else if (data[i][1] == null) {
5631                 hasNull = true;
5632                 gd.push([xp.call(this._xaxis, data[i][0]), null]);
5633             }
5634         }
5636         // don't do smoothing or bands on broken lines.
5637         if (hasNull) {
5638             this.renderer.smooth = false;
5639             if (this._type === 'line') {
5640                 bands.show = false;
5641             }
5642         }
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])]);
5647             }
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])]);
5650             }
5651         }
5653         if (this._type === 'line' && this.renderer.smooth && gd.length > 2) {
5654             var ret;
5655             if (this.renderer.constrainSmoothing) {
5656                 ret = computeConstrainedSmoothedData.call(this, gd);
5657                 this.renderer._smoothedData = ret[0];
5658                 this.renderer._smoothedPlotData = ret[1];
5660                 if (bands.show) {
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];
5665                 }
5667                 ret = null;
5668             }
5669             else {
5670                 ret = computeHermiteSmoothedData.call(this, gd);
5671                 this.renderer._smoothedData = ret[0];
5672                 this.renderer._smoothedPlotData = ret[1];
5674                 if (bands.show) {
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];
5679                 }
5681                 ret = null;
5682             }
5683         }
5684         return gd;
5685     };
5686     
5688     // called within scope of series.
5689     $.jqplot.LineRenderer.prototype.draw = function(ctx, gd, options, plot) {
5690         var i;
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;
5698         ctx.save();
5699         if (gd.length) {
5700             if (showLine) {
5701                 // if we fill, we'll have to add points to close the curve.
5702                 if (fill) {
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;
5708                         }
5709                         var isnegative = false;
5710                         var posfs = opts.fillStyle;
5711                     
5712                         // if stoking line as well as filling, get a copy of line data.
5713                         if (fillAndStroke) {
5714                             var fasgd = gd.slice(0);
5715                         }
5716                         // if not stacked, fill down to axis
5717                         if (this.index == 0 || !this._stack) {
5718                         
5719                             var tempgd = [];
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;
5726                             
5727                             if (this.fillAxis == 'y') {
5728                                 tempgd.push([gd[0][0], pyzero]);
5729                                 this._areaPoints.push([gd[0][0], pyzero]);
5730                                 
5731                                 for (var i=0; i<gd.length-1; i++) {
5732                                     tempgd.push(gd[i]);
5733                                     this._areaPoints.push(gd[i]);
5734                                     // do we have an axis crossing?
5735                                     if (pd[i][1] * pd[i+1][1] < 0) {
5736                                         if (pd[i][1] < 0) {
5737                                             isnegative = true;
5738                                             opts.fillStyle = negativeColor;
5739                                         }
5740                                         else {
5741                                             isnegative = false;
5742                                             opts.fillStyle = posfs;
5743                                         }
5744                                         
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.
5749                                         if (shadow) {
5750                                             this.renderer.shadowRenderer.draw(ctx, tempgd, opts);
5751                                         }
5752                                         this.renderer.shapeRenderer.draw(ctx, tempgd, opts);
5753                                         // now empty temp array and continue
5754                                         tempgd = [[xintercept, pyzero]];
5755                                         // this._areaPoints = [[xintercept, pyzero]];
5756                                     }   
5757                                 }
5758                                 if (pd[gd.length-1][1] < 0) {
5759                                     isnegative = true;
5760                                     opts.fillStyle = negativeColor;
5761                                 }
5762                                 else {
5763                                     isnegative = false;
5764                                     opts.fillStyle = posfs;
5765                                 }
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]); 
5770                             }
5771                             // now draw the last area.
5772                             if (shadow) {
5773                                 this.renderer.shadowRenderer.draw(ctx, tempgd, opts);
5774                             }
5775                             this.renderer.shapeRenderer.draw(ctx, tempgd, opts);
5776                             
5777                             
5778                             // var gridymin = this._yaxis.series_u2p(0);
5779                             // // IE doesn't return new length on unshift
5780                             // gd.unshift([gd[0][0], gridymin]);
5781                             // len = gd.length;
5782                             // gd.push([gd[len - 1][0], gridymin]);                   
5783                         }
5784                         // if stacked, fill to line below 
5785                         else {
5786                             var prev = this._prevGridData;
5787                             for (var i=prev.length; i>0; i--) {
5788                                 gd.push(prev[i-1]);
5789                                 // this._areaPoints.push(prev[i-1]);
5790                             }
5791                             if (shadow) {
5792                                 this.renderer.shadowRenderer.draw(ctx, gd, opts);
5793                             }
5794                             this._areaPoints = gd;
5795                             this.renderer.shapeRenderer.draw(ctx, gd, opts);
5796                         }
5797                     }
5798                     /////////////////////////
5799                     // Not filled to zero
5800                     ////////////////////////
5801                     else {                    
5802                         // if stoking line as well as filling, get a copy of line data.
5803                         if (fillAndStroke) {
5804                             var fasgd = gd.slice(0);
5805                         }
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]);                   
5814                         }
5815                         // if stacked, fill to line below 
5816                         else {
5817                             var prev = this._prevGridData;
5818                             for (var i=prev.length; i>0; i--) {
5819                                 gd.push(prev[i-1]);
5820                             }
5821                         }
5822                         this._areaPoints = gd;
5823                         
5824                         if (shadow) {
5825                             this.renderer.shadowRenderer.draw(ctx, gd, opts);
5826                         }
5827             
5828                         this.renderer.shapeRenderer.draw(ctx, gd, opts);                        
5829                     }
5830                     if (fillAndStroke) {
5831                         var fasopts = $.extend(true, {}, opts, {fill:false, closePath:false});
5832                         this.renderer.shapeRenderer.draw(ctx, fasgd, fasopts);
5833                         //////////
5834                         // TODO: figure out some way to do shadows nicely
5835                         // if (shadow) {
5836                         //     this.renderer.shadowRenderer.draw(ctx, fasgd, fasopts);
5837                         // }
5838                         // now draw the markers
5839                         if (this.markerRenderer.show) {
5840                             if (this.renderer.smooth) {
5841                                 fasgd = this.gridData;
5842                             }
5843                             for (i=0; i<fasgd.length; i++) {
5844                                 this.markerRenderer.draw(fasgd[i][0], fasgd[i][1], ctx, opts.markerOptions);
5845                             }
5846                         }
5847                     }
5848                 }
5849                 else {
5851                     if (this.renderer.bands.show) {
5852                         var bdat;
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);
5859                         }
5861                         if (this.renderer.bands.fill) {
5862                             if (this.renderer.smooth) {
5863                                 bdat = this.renderer._hiBandSmoothedData.concat(this.renderer._lowBandSmoothedData.reverse());
5864                             }
5865                             else {
5866                                 bdat = this.renderer._hiBandGridData.concat(this.renderer._lowBandGridData.reverse());
5867                             }
5868                             this._areaPoints = bdat;
5869                             bopts.closePath = true;
5870                             bopts.fill = true;
5871                             bopts.fillStyle = this.renderer.bands.fillColor;
5872                             this.renderer.shapeRenderer.draw(ctx, bdat, bopts);
5873                         }
5874                     }
5876                     if (shadow) {
5877                         this.renderer.shadowRenderer.draw(ctx, gd, opts);
5878                     }
5879     
5880                     this.renderer.shapeRenderer.draw(ctx, gd, opts);
5881                 }
5882             }
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) {
5888                     xmin = p[0];
5889                 }
5890                 if (ymax < p[1] || ymax == null) {
5891                     ymax = p[1];
5892                 }
5893                 if (xmax < p[0] || xmax == null) {
5894                     xmax = p[0];
5895                 }
5896                 if (ymin > p[1] || ymin == null) {
5897                     ymin = p[1];
5898                 }
5899             }
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);
5904             }
5906             this._boundingBox = [[xmin, ymax], [xmax, ymin]];
5907         
5908             // now draw the markers
5909             if (this.markerRenderer.show && !fill) {
5910                 if (this.renderer.smooth) {
5911                     gd = this.gridData;
5912                 }
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);
5916                     }
5917                 }
5918             }
5919         }
5920         
5921         ctx.restore();
5922     };  
5923     
5924     $.jqplot.LineRenderer.prototype.drawShadow = function(ctx, gd, options) {
5925         // This is a no-op, shadows drawn with lines.
5926     };
5927     
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;
5936                 }
5937             }
5938         }
5939     }  
5940     
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;
5949         }
5950         
5951         this.plugins.lineRenderer.highlightedSeriesIndex = null;
5952         this.plugins.lineRenderer.highlightCanvas = new $.jqplot.GenericCanvas();
5953         
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); });
5957     } 
5958     
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) {
5967             opts.fill = true;
5968             opts.closePath = true;
5969         }
5970         s.renderer.shapeRenderer.draw(canvas._ctx, points, opts);
5971         canvas = null;
5972     }
5973     
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;
5979         }
5980         plot.plugins.lineRenderer.highlightedSeriesIndex = null;
5981         plot.target.trigger('jqplotDataUnhighlight');
5982         canvas = null;
5983     }
5984     
5985     
5986     function handleMove(ev, gridpos, datapos, neighbor, plot) {
5987         if (neighbor) {
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);
6000             }
6001         }
6002         else if (neighbor == null) {
6003             unhighlight (plot);
6004         }
6005     }
6006     
6007     function handleMouseDown(ev, gridpos, datapos, neighbor, plot) {
6008         if (neighbor) {
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);
6017             }
6018         }
6019         else if (neighbor == null) {
6020             unhighlight (plot);
6021         }
6022     }
6023     
6024     function handleMouseUp(ev, gridpos, datapos, neighbor, plot) {
6025         var idx = plot.plugins.lineRenderer.highlightedSeriesIndex;
6026         if (idx != null && plot.series[idx].highlightMouseDown) {
6027             unhighlight(plot);
6028         }
6029     }
6030     
6031     function handleClick(ev, gridpos, datapos, neighbor, plot) {
6032         if (neighbor) {
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);
6039         }
6040     }
6041     
6042     function handleRightClick(ev, gridpos, datapos, neighbor, plot) {
6043         if (neighbor) {
6044             var ins = [neighbor.seriesIndex, neighbor.pointIndex, neighbor.data];
6045             var idx = plot.plugins.lineRenderer.highlightedSeriesIndex;
6046             if (idx != null && plot.series[idx].highlightMouseDown) {
6047                 unhighlight(plot);
6048             }
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);
6054         }
6055     }
6056     
6057     
6058     // class: $.jqplot.LinearAxisRenderer
6059     // The default jqPlot axis renderer, creating a numeric axis.
6060     $.jqplot.LinearAxisRenderer = function() {
6061     };
6062     
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 = "&asymp;";
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;
6104         // prop: tickInset
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.
6109         this.tickInset = 0;
6110         // prop: minorTicks
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;
6115         // prop: alignTicks
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;
6126             }
6127             else if (this.breakPoints.length < 2 || this.breakPoints[1] <= this.breakPoints[0]) {
6128                 this.breakPoints = null;
6129             }
6130         }
6131         if (this.numberTicks != null && this.numberTicks < 2) {
6132             this.numberTicks = 2;
6133         }
6134         this.resetDataBounds();
6135     };
6136     
6137     // called with scope of axis
6138     $.jqplot.LinearAxisRenderer.prototype.draw = function(ctx, plot) {
6139         if (this.show) {
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.
6147             var dim=0;
6148             var temp;
6149             // Added for theming.
6150             if (this._elem) {
6151                 // Memory Leaks patch
6152                 //this._elem.empty();
6153                 this._elem.emptyForce();
6154                 this._elem = null;
6155             }
6156             
6157             this._elem = $(document.createElement('div'));
6158             this._elem.addClass('jqplot-axis jqplot-'+this.name);
6159             this._elem.css('position', 'absolute');
6161             
6162             if (this.name == 'xaxis' || this.name == 'x2axis') {
6163                 this._elem.width(this._plotDimensions.width);
6164             }
6165             else {
6166                 this._elem.height(this._plotDimensions.height);
6167             }
6168             
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);
6175                 elem = null;
6176             }
6177     
6178             var t = this._ticks;
6179             var tick;
6180             for (var i=0; i<t.length; i++) {
6181                 tick = t[i];
6182                 if (tick.show && tick.showLabel && (!tick.isMinorTick || this.showMinorTicks)) {
6183                     this._elem.append(tick.draw(ctx, plot));
6184                 }
6185             }
6186             tick = null;
6187             t = null;
6188         }
6189         return this._elem;
6190     };
6191     
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 = '';
6201         }
6203         // this._ticks = this.__ticks;
6204     };
6205     
6206     // called with scope of axis
6207     $.jqplot.LinearAxisRenderer.prototype.set = function() { 
6208         var dim = 0;
6209         var temp;
6210         var w = 0;
6211         var h = 0;
6212         var lshow = (this._label == null) ? false : this._label.show;
6213         if (this.show) {
6214             var t = this._ticks;
6215             var tick;
6216             for (var i=0; i<t.length; i++) {
6217                 tick = t[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);
6221                     }
6222                     else {
6223                         temp = tick._elem.outerWidth(true);
6224                     }
6225                     if (temp > dim) {
6226                         dim = temp;
6227                     }
6228                 }
6229             }
6230             tick = null;
6231             t = null;
6232             
6233             if (lshow) {
6234                 w = this._label._elem.outerWidth(true);
6235                 h = this._label._elem.outerHeight(true); 
6236             }
6237             if (this.name == 'xaxis') {
6238                 dim = dim + h;
6239                 this._elem.css({'height':dim+'px', left:'0px', bottom:'0px'});
6240             }
6241             else if (this.name == 'x2axis') {
6242                 dim = dim + h;
6243                 this._elem.css({'height':dim+'px', left:'0px', top:'0px'});
6244             }
6245             else if (this.name == 'yaxis') {
6246                 dim = dim + w;
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');
6250                 }
6251             }
6252             else {
6253                 dim = dim + w;
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');
6257                 }
6258             }
6259         }  
6260     };    
6261     
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;
6271         var interval;
6272         var min, max;
6273         var pos1, pos2;
6274         var tt, i;
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;
6281         var threshold = 30;
6282         this._scalefact =  (Math.max(dim, threshold+1) - threshold)/300.0;
6283         
6284         // if we already have ticks, use them.
6285         // ticks must be in order of increasing value.
6286         
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)) {
6293                     t.value = ut[0];
6294                     if (this.breakPoints) {
6295                         if (ut[0] == this.breakPoints[0]) {
6296                             t.label = this.breakTickLabel;
6297                             t._breakTick = true;
6298                             t.showGridline = false;
6299                             t.showMark = false;
6300                         }
6301                         else if (ut[0] > this.breakPoints[0] && ut[0] <= this.breakPoints[1]) {
6302                             t.show = false;
6303                             t.showGridline = false;
6304                             t.label = ut[1];
6305                         }
6306                         else {
6307                             t.label = ut[1];
6308                         }
6309                     }
6310                     else {
6311                         t.label = ut[1];
6312                     }
6313                     t.setTick(ut[0], this.name);
6314                     this._ticks.push(t);
6315                 }
6317                 else if ($.isPlainObject(ut)) {
6318                     $.extend(true, t, ut);
6319                     t.axis = this.name;
6320                     this._ticks.push(t);
6321                 }
6322                 
6323                 else {
6324                     t.value = ut;
6325                     if (this.breakPoints) {
6326                         if (ut == this.breakPoints[0]) {
6327                             t.label = this.breakTickLabel;
6328                             t._breakTick = true;
6329                             t.showGridline = false;
6330                             t.showMark = false;
6331                         }
6332                         else if (ut > this.breakPoints[0] && ut <= this.breakPoints[1]) {
6333                             t.show = false;
6334                             t.showGridline = false;
6335                         }
6336                     }
6337                     t.setTick(ut, this.name);
6338                     this._ticks.push(t);
6339                 }
6340             }
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);
6345         }
6346         
6347         // we don't have any ticks yet, let's make some!
6348         else {
6349             if (name == 'xaxis' || name == 'x2axis') {
6350                 dim = this._plotDimensions.width;
6351             }
6352             else {
6353                 dim = this._plotDimensions.height;
6354             }
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;
6363                 }
6364                 else if (this.name.charAt(0) === 'y' && this.name !== 'yaxis' && this.name !== 'yMidAxis' && plot.axes.yaxis.show) {
6365                     _numberTicks = plot.axes.yaxis.numberTicks;
6366                 }
6367             }
6368         
6369             min = ((this.min != null) ? this.min : db.min);
6370             max = ((this.max != null) ? this.max : db.max);
6372             var range = max - min;
6373             var rmin, rmax;
6374             var temp;
6376             if (this.tickOptions == null || !this.tickOptions.formatString) {
6377                 this._overrideFormatString = true;
6378             }
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) {
6385                     if (min > 0) {
6386                         min = 0;
6387                     }
6388                     if (max < 0) {
6389                         max = 0;
6390                     }
6391                 }
6393                 if (this.forceTickAt100) {
6394                     if (min > 100) {
6395                         min = 100;
6396                     }
6397                     if (max < 100) {
6398                         max = 100;
6399                     }
6400                 }
6402                 var keepMin = false,
6403                     keepMax = false;
6405                 if (this.min != null) {
6406                     keepMin = true;
6407                 }
6409                 else if (this.max != null) {
6410                     keepMax = true;
6411                 }
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);
6430                 }
6432                 this.min = ret[0];
6433                 this.max = ret[1];
6434                 // if numberTicks specified, it should return the same.
6435                 this.numberTicks = ret[2];
6436                 this._autoFormatString = ret[3];
6437                 this.tickInterval = ret[4];
6438             }
6440             // User has specified some axis scale related option, can use auto algorithm
6441             else {
6442                 
6443                 // if min and max are same, space them out a bit
6444                 if (min == max) {
6445                     var adj = 0.05;
6446                     if (min > 0) {
6447                         adj = Math.max(Math.log(min)/Math.LN10, 0.05);
6448                     }
6449                     min -= adj;
6450                     max += adj;
6451                 }
6452                 
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];
6470                             var vmin = vals[0];
6471                             var vmax = vals[0];
6472                             for (var j=1; j<vals.length; j++) {
6473                                 if (vals[j] < vmin) {
6474                                     vmin = vals[j];
6475                                 }
6476                                 else if (vals[j] > vmax) {
6477                                     vmax = vals[j];
6478                                 }
6479                             }
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;
6486                                 }
6487                                 else {
6488                                     forceMinZero = false;
6489                                     if (s.fill && s.fillToZero && vmin < 0 && vmax > 0) {
6490                                         forceZeroLine = true;
6491                                     }
6492                                     else {
6493                                         forceZeroLine = false;
6494                                     }
6495                                 }
6496                             }
6497                             
6498                             // if not a bar and filling, use appropriate method.
6499                             else if (s.fill) {
6500                                 if (vmin >= 0 && (s.fillToZero || dp > 0.1)) {
6501                                     forceMinZero = true;
6502                                 }
6503                                 else if (vmin < 0 && vmax > 0 && s.fillToZero) {
6504                                     forceMinZero = false;
6505                                     forceZeroLine = true;
6506                                 }
6507                                 else {
6508                                     forceMinZero = false;
6509                                     forceZeroLine = false;
6510                                 }
6511                             }
6512                             
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;
6517                             }
6518                         }
6519                     }
6520                     
6521                     // check if we need make axis min at 0.
6522                     if (forceMinZero) {
6523                         // compute number of ticks
6524                         this.numberTicks = 2 + Math.ceil((dim-(this.tickSpacing-1))/this.tickSpacing);
6525                         this.min = 0;
6526                         userMin = 0;
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)) {
6532                             ti += temp;
6533                         }
6534                         this.tickInterval = Math.ceil(ti/temp) * temp;
6535                         this.max = this.tickInterval * (this.numberTicks - 1);
6536                     }
6537                     
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;
6549                     }
6550                     
6551                     // if nothing else, do autoscaling which will try to line up ticks across axes.
6552                     else {  
6553                         if (this.numberTicks == null){
6554                             if (this.tickInterval) {
6555                                 this.numberTicks = 3 + Math.ceil(range / this.tickInterval);
6556                             }
6557                             else {
6558                                 this.numberTicks = 2 + Math.ceil((dim-(this.tickSpacing-1))/this.tickSpacing);
6559                             }
6560                         }
6561                 
6562                         if (this.tickInterval == null) {
6563                             // get a tick interval
6564                             ti = range/(this.numberTicks - 1);
6566                             if (ti < 1) {
6567                                 temp = Math.pow(10, Math.abs(Math.floor(Math.log(ti)/Math.LN10)));
6568                             }
6569                             else {
6570                                 temp = 1;
6571                             }
6572                             this.tickInterval = Math.ceil(ti*temp*this.pad)/temp;
6573                         }
6574                         else {
6575                             temp = 1 / this.tickInterval;
6576                         }
6577                         
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;
6583            
6584                         if (this.min == null) {
6585                             this.min = Math.floor(temp*(min-margin))/temp;
6586                         }
6587                         if (this.max == null) {
6588                             this.max = this.min + rrange;
6589                         }
6590                     }
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);
6596                     var fstr;
6598                     // if we have only a whole number, use integer formatting
6599                     if (sf.digitsLeft >= sf.significantDigits) {
6600                         fstr = '%d';
6601                     }
6603                     else {
6604                         var temp = Math.max(0, 5 - sf.digitsLeft);
6605                         temp = Math.min(temp, sf.digitsRight);
6606                         fstr = '%.'+ temp + 'f';
6607                     }
6609                     this._autoFormatString = fstr;
6610                 }
6611                 
6612                 // Use the default algorithm which pads each axis to make the chart
6613                 // centered nicely on the grid.
6614                 else {
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;
6619         
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;
6625                         }
6626                         else if (dim > 100) {
6627                             this.numberTicks = parseInt(3+(dim-100)/75, 10);
6628                         }
6629                         else {
6630                             this.numberTicks = 2;
6631                         }
6632                     }
6633                 
6634                     if (this.tickInterval == null) {
6635                         this.tickInterval = range / (this.numberTicks-1);
6636                     }
6637                     
6638                     if (this.max == null) {
6639                         rmax = rmin + this.tickInterval*(this.numberTicks - 1);
6640                     }        
6641                     if (this.min == null) {
6642                         rmin = rmax - this.tickInterval*(this.numberTicks - 1);
6643                     }
6645                     // get precision of interval and determine a format string.
6646                     var sf = $.jqplot.getSignificantFigures(this.tickInterval);
6648                     var fstr;
6650                     // if we have only a whole number, use integer formatting
6651                     if (sf.digitsLeft >= sf.significantDigits) {
6652                         fstr = '%d';
6653                     }
6655                     else {
6656                         var temp = Math.max(0, 5 - sf.digitsLeft);
6657                         temp = Math.min(temp, sf.digitsRight);
6658                         fstr = '%.'+ temp + 'f';
6659                     }
6662                     this._autoFormatString = fstr;
6664                     this.min = rmin;
6665                     this.max = rmax;
6666                 }
6667                 
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];
6676                     var precision = 0;
6677                     if (fs) {
6678                         if (fs.search(/[fFeEgGpP]/) > -1) {
6679                             var m = fs.match(/\%\.(\d{0,})?[eEfFgGpP]/);
6680                             if (m) {
6681                                 precision = parseInt(m[1], 10);
6682                             }
6683                             else {
6684                                 precision = 6;
6685                             }
6686                         }
6687                         else if (fs.search(/[di]/) > -1) {
6688                             precision = 0;
6689                         }
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;
6701                                     }
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;
6706                                     }
6707                                     var n = (this.max - this.min)/this.tickInterval;
6708                                     n = n.toFixed(11);
6709                                     n = Math.ceil(n);
6710                                     this.numberTicks = n + 1;
6711                                 }
6712                                 else if (userMax == null) {
6713                                     // add one tick for top of range.
6714                                     var n = (this._dataBounds.max - this.min) / this.tickInterval;
6715                                     n = n.toFixed(11);
6716                                     this.numberTicks = Math.ceil(n) + 2;
6717                                     this.max = this.min + this.tickInterval * (this.numberTicks-1);
6718                                 }
6719                                 else if (userMin == null) {
6720                                     // add one tick for bottom of range.
6721                                     var n = (this.max - this._dataBounds.min) / this.tickInterval;
6722                                     n = n.toFixed(11);
6723                                     this.numberTicks = Math.ceil(n) + 2;
6724                                     this.min = this.max - this.tickInterval * (this.numberTicks-1);
6725                                 }
6726                                 else {
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;
6736                                 }
6737                             }
6738                         }
6739                     }
6740                 }
6741                 
6742             }
6743             
6744             if (this._overrideFormatString && this._autoFormatString != '') {
6745                 this.tickOptions = this.tickOptions || {};
6746                 this.tickOptions.formatString = this._autoFormatString;
6747             }
6749             var t, to;
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);
6764                     }
6765                 }
6766                 t = null;
6767             }
6768         }
6770         if (this.tickInset) {
6771             this.min = this.min - this.tickInset * this.tickInterval;
6772             this.max = this.max + this.tickInset * this.tickInterval;
6773         }
6775         ticks = null;
6776     };
6777     
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
6781     // proper interval.
6782     // This method needs to be called with the scope of an axis object, like:
6783     //
6784     // > plot.axes.yaxis.renderer.resetTickValues.call(plot.axes.yaxis, yarr);
6785     //
6786     $.jqplot.LinearAxisRenderer.prototype.resetTickValues = function(opts) {
6787         if ($.isArray(opts) && opts.length == this._ticks.length) {
6788             var t;
6789             for (var i=0; i<opts.length; i++) {
6790                 t = this._ticks[i];
6791                 t.value = opts[i];
6792                 t.label = t.formatter(t.formatString, opts[i]);
6793                 t.label = t.prefix + t.label;
6794                 t._elem.html(t.label);
6795             }
6796             t = null;
6797             this.min = $.jqplot.arrayMin(opts);
6798             this.max = $.jqplot.arrayMax(opts);
6799             this.pack();
6800         }
6801         // Not implemented yet.
6802         // else if ($.isPlainObject(opts)) {
6803         // 
6804         // }
6805     };
6806     
6807     // called with scope of axis
6808     $.jqplot.LinearAxisRenderer.prototype.pack = function(pos, offsets) {
6809         // Add defaults for repacking from resetTickValues function.
6810         pos = pos || {};
6811         offsets = offsets || this._offsets;
6812         
6813         var ticks = this._ticks;
6814         var max = this.max;
6815         var min = this.min;
6816         var offmax = offsets.max;
6817         var offmin = offsets.min;
6818         var lshow = (this._label == null) ? false : this._label.show;
6819         
6820         for (var p in pos) {
6821             this._elem.css(p, pos[p]);
6822         }
6823         
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;
6828         
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];
6832             
6833             this.p2u = function(p){
6834                 return (p - offmin) * unitlength / pixellength + min;
6835             };
6836         
6837             this.u2p = function(u){
6838                 if (u > this.breakPoints[0] && u < this.breakPoints[1]){
6839                     u = this.breakPoints[0];
6840                 }
6841                 if (u <= this.breakPoints[0]) {
6842                     return (u - min) * pixellength / unitlength + offmin;
6843                 }
6844                 else {
6845                     return (u - this.breakPoints[1] + this.breakPoints[0] - min) * pixellength / unitlength + offmin;
6846                 }
6847             };
6848                 
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];
6853                     }
6854                     if (u <= this.breakPoints[0]) {
6855                         return (u - min) * pixellength / unitlength;
6856                     }
6857                     else {
6858                         return (u - this.breakPoints[1] + this.breakPoints[0] - min) * pixellength / unitlength;
6859                     }
6860                 };
6861                 this.series_p2u = function(p){
6862                     return p * unitlength / pixellength + min;
6863                 };
6864             }
6865         
6866             else {
6867                 this.series_u2p = function(u){
6868                     if (u > this.breakPoints[0] && u < this.breakPoints[1]){
6869                         u = this.breakPoints[0];
6870                     }
6871                     if (u >= this.breakPoints[1]) {
6872                         return (u - max) * pixellength / unitlength;
6873                     }
6874                     else {
6875                         return (u + this.breakPoints[1] - this.breakPoints[0] - max) * pixellength / unitlength;
6876                     }
6877                 };
6878                 this.series_p2u = function(p){
6879                     return p * unitlength / pixellength + max;
6880                 };
6881             }
6882         }
6883         else {
6884             this.p2u = function(p){
6885                 return (p - offmin) * unitlength / pixellength + min;
6886             };
6887         
6888             this.u2p = function(u){
6889                 return (u - min) * pixellength / unitlength + offmin;
6890             };
6891                 
6892             if (this.name == 'xaxis' || this.name == 'x2axis'){
6893                 this.series_u2p = function(u){
6894                     return (u - min) * pixellength / unitlength;
6895                 };
6896                 this.series_p2u = function(p){
6897                     return p * unitlength / pixellength + min;
6898                 };
6899             }
6900         
6901             else {
6902                 this.series_u2p = function(u){
6903                     return (u - max) * pixellength / unitlength;
6904                 };
6905                 this.series_p2u = function(p){
6906                     return p * unitlength / pixellength + max;
6907                 };
6908             }
6909         }
6910         
6911         if (this.show) {
6912             if (this.name == 'xaxis' || this.name == 'x2axis') {
6913                 for (var i=0; i<ticks.length; i++) {
6914                     var t = ticks[i];
6915                     if (t.show && t.showLabel) {
6916                         var shim;
6917                         
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) {
6922                                 case 'auto':
6923                                     // position at end
6924                                     if (temp * t.angle < 0) {
6925                                         shim = -t.getWidth() + t._textRenderer.height * Math.sin(-t._textRenderer.angle) / 2;
6926                                     }
6927                                     // position at start
6928                                     else {
6929                                         shim = -t._textRenderer.height * Math.sin(t._textRenderer.angle) / 2;
6930                                     }
6931                                     break;
6932                                 case 'end':
6933                                     shim = -t.getWidth() + t._textRenderer.height * Math.sin(-t._textRenderer.angle) / 2;
6934                                     break;
6935                                 case 'start':
6936                                     shim = -t._textRenderer.height * Math.sin(t._textRenderer.angle) / 2;
6937                                     break;
6938                                 case 'middle':
6939                                     shim = -t.getWidth()/2 + t._textRenderer.height * Math.sin(-t._textRenderer.angle) / 2;
6940                                     break;
6941                                 default:
6942                                     shim = -t.getWidth()/2 + t._textRenderer.height * Math.sin(-t._textRenderer.angle) / 2;
6943                                     break;
6944                             }
6945                         }
6946                         else {
6947                             shim = -t.getWidth()/2;
6948                         }
6949                         var val = this.u2p(t.value) + shim + 'px';
6950                         t._elem.css('left', val);
6951                         t.pack();
6952                     }
6953                 }
6954                 if (lshow) {
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');
6959                     }
6960                     else {
6961                         this._label._elem.css('top', '0px');
6962                     }
6963                     this._label.pack();
6964                 }
6965             }
6966             else {
6967                 for (var i=0; i<ticks.length; i++) {
6968                     var t = ticks[i];
6969                     if (t.show && t.showLabel) {                        
6970                         var shim;
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) {
6975                                 case 'auto':
6976                                     // position at end
6977                                 case 'end':
6978                                     if (temp * t.angle < 0) {
6979                                         shim = -t._textRenderer.height * Math.cos(-t._textRenderer.angle) / 2;
6980                                     }
6981                                     else {
6982                                         shim = -t.getHeight() + t._textRenderer.height * Math.cos(t._textRenderer.angle) / 2;
6983                                     }
6984                                     break;
6985                                 case 'start':
6986                                     if (t.angle > 0) {
6987                                         shim = -t._textRenderer.height * Math.cos(-t._textRenderer.angle) / 2;
6988                                     }
6989                                     else {
6990                                         shim = -t.getHeight() + t._textRenderer.height * Math.cos(t._textRenderer.angle) / 2;
6991                                     }
6992                                     break;
6993                                 case 'middle':
6994                                     // if (t.angle > 0) {
6995                                     //     shim = -t.getHeight()/2 + t._textRenderer.height * Math.sin(-t._textRenderer.angle) / 2;
6996                                     // }
6997                                     // else {
6998                                     //     shim = -t.getHeight()/2 - t._textRenderer.height * Math.sin(t._textRenderer.angle) / 2;
6999                                     // }
7000                                     shim = -t.getHeight()/2;
7001                                     break;
7002                                 default:
7003                                     shim = -t.getHeight()/2;
7004                                     break;
7005                             }
7006                         }
7007                         else {
7008                             shim = -t.getHeight()/2;
7009                         }
7010                         
7011                         var val = this.u2p(t.value) + shim + 'px';
7012                         t._elem.css('top', val);
7013                         t.pack();
7014                     }
7015                 }
7016                 if (lshow) {
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');
7021                     }
7022                     else {
7023                         this._label._elem.css('right', '0px');
7024                     }   
7025                     this._label.pack();
7026                 }
7027             }
7028         }
7030         ticks = null;
7031     };
7034     /**
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.
7041     * Thanks Scott!!
7042     */
7043     
7044     /**
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. 
7050     */
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)
7056     {
7057         var fstr;
7058         interval = Math.abs(interval);
7059         if (interval >= 10) {
7060             fstr = '%d';
7061         }
7063         else if (interval > 1) {
7064             if (interval === parseInt(interval, 10)) {
7065                 fstr = '%d';
7066             }
7067             else {
7068                 fstr = '%.1f';
7069             }
7070         }
7072         else {
7073             var expv = -Math.floor(Math.log(interval)/Math.LN10);
7074             fstr = '%.' + expv + 'f';
7075         }
7076         
7077         return fstr; 
7078     }
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);
7084         if (i > 0) {
7085             return _factors[i-1];
7086         }
7087         else {
7088             return _factors[_factors.length - 1] / 100;
7089         }
7090     };
7092     var _getHigherFactor = function(f) {
7093         var i = _factors.indexOf(f);
7094         if (i < _factors.length-1) {
7095             return _factors[i+1];
7096         }
7097         else {
7098             return _factors[0] * 100;
7099         }
7100     };
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);
7111         var temp;
7112         var sd;
7113         var bestNT;
7114         var gsf = $.jqplot.getSignificantFigures;
7115         var fsd;
7116         var fs;
7117         var currentNT;
7118         var bestPrec;
7120         for (var i=0, l=hi-low+1; i<l; i++) {
7121             currentNT = low + i;
7122             temp = r/(currentNT-1);
7123             sd = gsf(temp);
7125             temp = Math.abs(nttarget - currentNT) + sd.digitsRight;
7126             if (temp < badness) {
7127                 badness = temp;
7128                 bestNT = currentNT;
7129                 bestPrec = sd.digitsRight;
7130             }
7131             else if (temp === badness) {
7132                 // let nicer ticks trump number ot ticks
7133                 if (sd.digitsRight < bestPrec) {
7134                     bestNT = currentNT;
7135                     bestPrec = sd.digitsRight;
7136                 }
7137             }
7139         }
7141         fsd = Math.max(bestPrec, Math.max(gsf(min).digitsRight, gsf(max).digitsRight));
7142         if (fsd === 0) {
7143             fs = '%d';
7144         }
7145         else {
7146             fs = '%.' + fsd + 'f';
7147         }
7148         temp = r / (bestNT - 1);
7149         // min, max, number ticks, format string, tick interval
7150         return [min, max, bestNT, fs, temp];
7151     }
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;
7161         var interval;
7162         // "nicest" ranges are 1, 2, 5 or powers of these.
7163         // for magnitudes below 1, only allow these. 
7164         if (magnitude < 1) {
7165             if (residual > 5) {
7166                 interval = 10 * magnitude;
7167             }
7168             else if (residual > 2) {
7169                 interval = 5 * magnitude;
7170             }
7171             else if (residual > 1) {
7172                 interval = 2 * magnitude;
7173             }
7174             else {
7175                 interval = magnitude;
7176             }
7177         }
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. 
7180         else {
7181             if (residual > 5) {
7182                 interval = 10 * magnitude;
7183             }
7184             else if (residual > 4) {
7185                 interval = 5 * magnitude;
7186             }
7187             else if (residual > 3) {
7188                 interval = 4 * magnitude;
7189             }
7190             else if (residual > 2) {
7191                 interval = 3 * magnitude;
7192             }
7193             else if (residual > 1) {
7194                 interval = 2 * magnitude;
7195             }
7196             else {
7197                 interval = magnitude;
7198             }
7199         }
7201         return interval;
7202     }
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);
7210         // 0 < f < 10
7211         var f = range / magnitude;
7212         var fact;
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.
7215         f = f/scalefact;
7217         // for large plots, smaller interval, more ticks.
7218         if (f<=0.38) {
7219             fact = 0.1;
7220         }
7221         else if (f<=1.6) {
7222             fact = 0.2;
7223         }
7224         else if (f<=4.0) {
7225             fact = 0.5;
7226         }
7227         else if (f<=8.0) {
7228             fact = 1.0;
7229         }
7230         // for very small plots, larger interval, less ticks in number ticks
7231         else if (f<=16.0) {
7232             fact = 2;
7233         }
7234         else {
7235             fact = 5;
7236         } 
7238         return fact*magnitude; 
7239     }
7241     function bestLinearComponents(range, scalefact) {
7242         var expv = Math.floor(Math.log(range)/Math.LN10);
7243         var magnitude = Math.pow(10, expv);
7244         // 0 < f < 10
7245         var f = range / magnitude;
7246         var interval;
7247         var fact;
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.
7250         f = f/scalefact;
7252         // for large plots, smaller interval, more ticks.
7253         if (f<=0.38) {
7254             fact = 0.1;
7255         }
7256         else if (f<=1.6) {
7257             fact = 0.2;
7258         }
7259         else if (f<=4.0) {
7260             fact = 0.5;
7261         }
7262         else if (f<=8.0) {
7263             fact = 1.0;
7264         }
7265         // for very small plots, larger interval, less ticks in number ticks
7266         else if (f<=16.0) {
7267             fact = 2;
7268         }
7269         // else if (f<=20.0) {
7270         //     fact = 3;
7271         // }
7272         // else if (f<=24.0) {
7273         //     fact = 4;
7274         // }
7275         else {
7276             fact = 5;
7277         } 
7279         interval = fact * magnitude;
7281         return [interval, fact, magnitude];
7282     }
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;
7296         }
7298         scalefact = scalefact || 1.0;
7300         // make sure range is positive
7301         if (axis_max < axis_min) {
7302             var a = axis_max;
7303             axis_max = axis_min;
7304             axis_min = a;
7305         }
7307         var r = [];
7308         var ss = bestLinearInterval(axis_max - axis_min, scalefact);
7310         var gsf = $.jqplot.getSignificantFigures;
7311         
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
7324             }
7326             else if (keepMin) {
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
7334                 }
7335                 else {
7336                     r[3] = '%.' + digitsMin + 'f';
7337                 }
7338                 r[4] = ss;                                              // tick Interval
7339             }
7341             else if (keepMax) {
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
7349                 }
7350                 else {
7351                     r[3] = '%.' + digitsMax + 'f';
7352                 }
7353                 r[4] = ss;                                              // tick Interval
7354             }
7355         }
7357         else {
7358             var tempr = [];
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) {
7372                 r = tempr;
7373             }
7375             else {
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
7384             }
7385         }
7387         return r;
7388     };
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
7400         
7401         // prop: show
7402         // wether or not to show the marker.
7403         this.show = true;
7404         // prop: style
7405         // One of diamond, circle, square, x, plus, dash, filledDiamond, filledCircle, filledSquare
7406         this.style = 'filledCircle';
7407         // prop: lineWidth
7408         // size of the line for non-filled markers.
7409         this.lineWidth = 2;
7410         // prop: size
7411         // Size of the marker (diameter or circle, length of edge of square, etc.)
7412         this.size = 9.0;
7413         // prop: color
7414         // color of marker.  Will be set to color of series by default on init.
7415         this.color = '#666666';
7416         // prop: shadow
7417         // wether or not to draw a shadow on the line
7418         this.shadow = true;
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();
7437         
7438         $.extend(true, this, options);
7439     };
7440     
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) {
7445             sdopt.fill = true;
7446         }
7447         if (this.style.indexOf('ircle') != -1) {
7448             sdopt.isarc = true;
7449             sdopt.closePath = false;
7450         }
7451         this.shadowRenderer.init(sdopt);
7452         
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) {
7455             shopt.fill = true;
7456         }
7457         if (this.style.indexOf('ircle') != -1) {
7458             shopt.isarc = true;
7459             shopt.closePath = false;
7460         }
7461         this.shapeRenderer.init(shopt);
7462     };
7463     
7464     $.jqplot.MarkerRenderer.prototype.drawDiamond = function(x, y, ctx, fill, options) {
7465         var stretch = 1.2;
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]];
7469         if (this.shadow) {
7470             this.shadowRenderer.draw(ctx, points);
7471         }
7472         this.shapeRenderer.draw(ctx, points, options);
7473     };
7474     
7475     $.jqplot.MarkerRenderer.prototype.drawPlus = function(x, y, ctx, fill, options) {
7476         var stretch = 1.0;
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});
7482         if (this.shadow) {
7483             this.shadowRenderer.draw(ctx, points1, {closePath:false});
7484             this.shadowRenderer.draw(ctx, points2, {closePath:false});
7485         }
7486         this.shapeRenderer.draw(ctx, points1, opts);
7487         this.shapeRenderer.draw(ctx, points2, opts);
7488     };
7489     
7490     $.jqplot.MarkerRenderer.prototype.drawX = function(x, y, ctx, fill, options) {
7491         var stretch = 1.0;
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]];
7497         if (this.shadow) {
7498             this.shadowRenderer.draw(ctx, points1, {closePath:false});
7499             this.shadowRenderer.draw(ctx, points2, {closePath:false});
7500         }
7501         this.shapeRenderer.draw(ctx, points1, opts);
7502         this.shapeRenderer.draw(ctx, points2, opts);
7503     };
7504     
7505     $.jqplot.MarkerRenderer.prototype.drawDash = function(x, y, ctx, fill, options) {
7506         var stretch = 1.0;
7507         var dx = this.size/2*stretch;
7508         var dy = this.size/2*stretch;
7509         var points = [[x-dx, y], [x+dx, y]];
7510         if (this.shadow) {
7511             this.shadowRenderer.draw(ctx, points);
7512         }
7513         this.shapeRenderer.draw(ctx, points, options);
7514     };
7515     
7516     $.jqplot.MarkerRenderer.prototype.drawLine = function(p1, p2, ctx, fill, options) {
7517         var points = [p1, p2];
7518         if (this.shadow) {
7519             this.shadowRenderer.draw(ctx, points);
7520         }
7521         this.shapeRenderer.draw(ctx, points, options);
7522     };
7523     
7524     $.jqplot.MarkerRenderer.prototype.drawSquare = function(x, y, ctx, fill, options) {
7525         var stretch = 1.0;
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]];
7529         if (this.shadow) {
7530             this.shadowRenderer.draw(ctx, points);
7531         }
7532         this.shapeRenderer.draw(ctx, points, options);
7533     };
7534     
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];
7539         if (this.shadow) {
7540             this.shadowRenderer.draw(ctx, points);
7541         }
7542         this.shapeRenderer.draw(ctx, points, options);
7543     };
7544     
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;
7552             }
7553             if (options.color && !options.strokeStyle) {
7554                 options.strokeStyle = options.color;
7555             }
7556             switch (this.style) {
7557                 case 'diamond':
7558                     this.drawDiamond(x,y,ctx, false, options);
7559                     break;
7560                 case 'filledDiamond':
7561                     this.drawDiamond(x,y,ctx, true, options);
7562                     break;
7563                 case 'circle':
7564                     this.drawCircle(x,y,ctx, false, options);
7565                     break;
7566                 case 'filledCircle':
7567                     this.drawCircle(x,y,ctx, true, options);
7568                     break;
7569                 case 'square':
7570                     this.drawSquare(x,y,ctx, false, options);
7571                     break;
7572                 case 'filledSquare':
7573                     this.drawSquare(x,y,ctx, true, options);
7574                     break;
7575                 case 'x':
7576                     this.drawX(x,y,ctx, true, options);
7577                     break;
7578                 case 'plus':
7579                     this.drawPlus(x,y,ctx, true, options);
7580                     break;
7581                 case 'dash':
7582                     this.drawDash(x,y,ctx, true, options);
7583                     break;
7584                 case 'line':
7585                     this.drawLine(x, y, ctx, false, options);
7586                     break;
7587                 default:
7588                     this.drawDiamond(x,y,ctx, false, options);
7589                     break;
7590             }
7591         }
7592     };
7593     
7594     // class: $.jqplot.shadowRenderer
7595     // The default jqPlot shadow renderer, rendering shadows behind shapes.
7596     $.jqplot.ShadowRenderer = function(options){ 
7597         // Group: Properties
7598         
7599         // prop: angle
7600         // Angle of the shadow in degrees.  Measured counter-clockwise from the x axis.
7601         this.angle = 45;
7602         // prop: offset
7603         // Pixel offset at the given shadow angle of each shadow stroke from the last stroke.
7604         this.offset = 1;
7605         // prop: alpha
7606         // alpha transparency of shadow stroke.
7607         this.alpha = 0.07;
7608         // prop: lineWidth
7609         // width of the shadow line stroke.
7610         this.lineWidth = 1.5;
7611         // prop: lineJoin
7612         // How line segments of the shadow are joined.
7613         this.lineJoin = 'miter';
7614         // prop: lineCap
7615         // how ends of the shadow line are rendered.
7616         this.lineCap = 'round';
7617         // prop; closePath
7618         // whether line path segment is closed upon itself.
7619         this.closePath = false;
7620         // prop: fill
7621         // whether to fill the shape.
7622         this.fill = false;
7623         // prop: depth
7624         // how many times the shadow is stroked.  Each stroke will be offset by offset at angle degrees.
7625         this.depth = 3;
7626         this.strokeStyle = 'rgba(0,0,0,0.1)';
7627         // prop: isarc
7628         // wether the shadow is an arc or not.
7629         this.isarc = false;
7630         
7631         $.extend(true, this, options);
7632     };
7633     
7634     $.jqplot.ShadowRenderer.prototype.init = function(options) {
7635         $.extend(true, this, options);
7636     };
7637     
7638     // function: draw
7639     // draws an transparent black (i.e. gray) shadow.
7640     //
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) {
7644         ctx.save();
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();
7663             if (isarc) {
7664                 ctx.arc(points[0], points[1], points[2], points[3], points[4], true);                
7665             }
7666             else if (fillRect) {
7667                 if (fillRect) {
7668                     ctx.fillRect(points[0], points[1], points[2], points[3]);
7669                 }
7670             }
7671             else if (points && points.length){
7672                 var move = true;
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) {
7676                         if (move) {
7677                             ctxPattern.moveTo(points[i][0], points[i][1]);
7678                             move = false;
7679                         }
7680                         else {
7681                             ctxPattern.lineTo(points[i][0], points[i][1]);
7682                         }
7683                     }
7684                     else {
7685                         move = true;
7686                     }
7687                 }
7688                 
7689             }
7690             if (closePath) {
7691                 ctxPattern.closePath();
7692             }
7693             if (fill) {
7694                 ctx.fill();
7695             }
7696             else {
7697                 ctx.stroke();
7698             }
7699         }
7700         ctx.restore();
7701     };
7702     
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
7707     // the shape.
7708     $.jqplot.ShapeRenderer = function(options){
7709         
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';
7717         // prop: lineJoin
7718         // How line segments of the shadow are joined.
7719         this.lineJoin = 'miter';
7720         // prop: lineCap
7721         // how ends of the shadow line are rendered.
7722         this.lineCap = 'round';
7723         // prop; closePath
7724         // whether line path segment is closed upon itself.
7725         this.closePath = false;
7726         // prop: fill
7727         // whether to fill the shape.
7728         this.fill = false;
7729         // prop: isarc
7730         // wether the shadow is an arc or not.
7731         this.isarc = false;
7732         // prop: fillRect
7733         // true to draw shape as a filled rectangle.
7734         this.fillRect = false;
7735         // prop: strokeRect
7736         // true to draw shape as a stroked rectangle.
7737         this.strokeRect = false;
7738         // prop: clearRect
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';
7744         // prop: fillStyle
7745         // css color spec for the fill style.
7746         this.fillStyle = '#999999'; 
7747         
7748         $.extend(true, this, options);
7749     };
7750     
7751     $.jqplot.ShapeRenderer.prototype.init = function(options) {
7752         $.extend(true, this, options);
7753     };
7754     
7755     // function: draw
7756     // draws the shape.
7757     //
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) {
7763         ctx.save();
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;
7778         ctx.beginPath();
7779         if (isarc) {
7780             ctx.arc(points[0], points[1], points[2], points[3], points[4], true);   
7781             if (closePath) {
7782                 ctx.closePath();
7783             }
7784             if (fill) {
7785                 ctx.fill();
7786             }
7787             else {
7788                 ctx.stroke();
7789             }
7790             ctx.restore();
7791             return;
7792         }
7793         else if (clearRect) {
7794             ctx.clearRect(points[0], points[1], points[2], points[3]);
7795             ctx.restore();
7796             return;
7797         }
7798         else if (fillRect || strokeRect) {
7799             if (fillRect) {
7800                 ctx.fillRect(points[0], points[1], points[2], points[3]);
7801             }
7802             if (strokeRect) {
7803                 ctx.strokeRect(points[0], points[1], points[2], points[3]);
7804                 ctx.restore();
7805                 return;
7806             }
7807         }
7808         else if (points && points.length){
7809             var move = true;
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) {
7813                     if (move) {
7814                         ctxPattern.moveTo(points[i][0], points[i][1]);
7815                         move = false;
7816                     }
7817                     else {
7818                         ctxPattern.lineTo(points[i][0], points[i][1]);
7819                     }
7820                 }
7821                 else {
7822                     move = true;
7823                 }
7824             }
7825             if (closePath) {
7826                 ctxPattern.closePath();
7827             }
7828             if (fill) {
7829                 ctx.fill();
7830             }
7831             else {
7832                 ctx.stroke();
7833             }
7834         }
7835         ctx.restore();
7836     };
7837     
7838     // class $.jqplot.TableLegendRenderer
7839     // The default legend renderer for jqPlot.
7840     $.jqplot.TableLegendRenderer = function(){
7841         //
7842     };
7843     
7844     $.jqplot.TableLegendRenderer.prototype.init = function(options) {
7845         $.extend(true, this, options);
7846     };
7847         
7848     $.jqplot.TableLegendRenderer.prototype.addrow = function (label, color, pad, reverse) {
7849         var rs = (pad) ? this.rowSpacing+'px' : '0px';
7850         var tr;
7851         var td;
7852         var elem;
7853         var div0;
7854         var div1;
7855         elem = document.createElement('tr');
7856         tr = $(elem);
7857         tr.addClass('jqplot-table-legend');
7858         elem = null;
7860         if (reverse){
7861             tr.prependTo(this._elem);
7862         }
7864         else{
7865             tr.appendTo(this._elem);
7866         }
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);
7884         }
7885         if (this.showLabels) {
7886             td = $(document.createElement('td'));
7887             td.addClass('jqplot-table-legend jqplot-table-legend-label');
7888             td.css('paddingTop', rs);
7889             tr.append(td);
7891             // elem = $('<td class="jqplot-table-legend" style="padding-top:'+rs+';"></td>');
7892             // elem.appendTo(tr);
7893             if (this.escapeHtml) {
7894                 td.text(label);
7895             }
7896             else {
7897                 td.html(label);
7898             }
7899         }
7900         td = null;
7901         div0 = null;
7902         div1 = null;
7903         tr = null;
7904         elem = null;
7905     };
7906     
7907     // called with scope of legend
7908     $.jqplot.TableLegendRenderer.prototype.draw = function() {
7909         if (this._elem) {
7910             this._elem.emptyForce();
7911             this._elem = null;
7912         }
7914         if (this.show) {
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;
7924             }
7925             if (this.border) {
7926                 ss['border'] = this.border;
7927             }
7928             if (this.fontSize) {
7929                 ss['fontSize'] = this.fontSize;
7930             }
7931             if (this.fontFamily) {
7932                 ss['fontFamily'] = this.fontFamily;
7933             }
7934             if (this.textColor) {
7935                 ss['textColor'] = this.textColor;
7936             }
7937             if (this.marginTop != null) {
7938                 ss['marginTop'] = this.marginTop;
7939             }
7940             if (this.marginBottom != null) {
7941                 ss['marginBottom'] = this.marginBottom;
7942             }
7943             if (this.marginLeft != null) {
7944                 ss['marginLeft'] = this.marginLeft;
7945             }
7946             if (this.marginRight != null) {
7947                 ss['marginRight'] = this.marginRight;
7948             }
7949             
7950         
7951             var pad = false, 
7952                 reverse = false,
7953                                 s;
7954             for (var i = 0; i< series.length; i++) {
7955                 s = series[i];
7956                 if (s._stack || s.renderer.constructor == $.jqplot.BezierCurveRenderer){
7957                     reverse = true;
7958                 }
7959                 if (s.show && s.showLabel) {
7960                     var lt = this.labels[i] || s.label.toString();
7961                     if (lt) {
7962                         var color = s.color;
7963                         if (reverse && i < series.length - 1){
7964                             pad = true;
7965                         }
7966                         else if (reverse && i == series.length - 1){
7967                             pad = false;
7968                         }
7969                         this.renderer.addrow.call(this, lt, color, pad, reverse);
7970                         pad = true;
7971                     }
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);
7975                         if (item) {
7976                             this.renderer.addrow.call(this, item.label, item.color, pad);
7977                             pad = true;
7978                         } 
7979                     }
7980                     lt = null;
7981                 }
7982             }
7983         }
7984         return this._elem;
7985     };
7986     
7987     $.jqplot.TableLegendRenderer.prototype.pack = function(offsets) {
7988         if (this.show) {       
7989             if (this.placement == 'insideGrid') {
7990                 switch (this.location) {
7991                     case 'nw':
7992                         var a = offsets.left;
7993                         var b = offsets.top;
7994                         this._elem.css('left', a);
7995                         this._elem.css('top', b);
7996                         break;
7997                     case 'n':
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);
8002                         break;
8003                     case 'ne':
8004                         var a = offsets.right;
8005                         var b = offsets.top;
8006                         this._elem.css({right:a, top:b});
8007                         break;
8008                     case 'e':
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});
8012                         break;
8013                     case 'se':
8014                         var a = offsets.right;
8015                         var b = offsets.bottom;
8016                         this._elem.css({right:a, bottom:b});
8017                         break;
8018                     case 's':
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});
8022                         break;
8023                     case 'sw':
8024                         var a = offsets.left;
8025                         var b = offsets.bottom;
8026                         this._elem.css({left:a, bottom:b});
8027                         break;
8028                     case 'w':
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});
8032                         break;
8033                     default:  // same as 'se'
8034                         var a = offsets.right;
8035                         var b = offsets.bottom;
8036                         this._elem.css({right:a, bottom:b});
8037                         break;
8038                 }
8039                 
8040             }
8041             else if (this.placement == 'outside'){
8042                 switch (this.location) {
8043                     case 'nw':
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);
8048                         break;
8049                     case 'n':
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);
8054                         break;
8055                     case 'ne':
8056                         var a = this._plotDimensions.width - offsets.right;
8057                         var b = offsets.top;
8058                         this._elem.css({left:a, top:b});
8059                         break;
8060                     case 'e':
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});
8064                         break;
8065                     case 'se':
8066                         var a = this._plotDimensions.width - offsets.right;
8067                         var b = offsets.bottom;
8068                         this._elem.css({left:a, bottom:b});
8069                         break;
8070                     case 's':
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});
8074                         break;
8075                     case 'sw':
8076                         var a = this._plotDimensions.width - offsets.left;
8077                         var b = offsets.bottom;
8078                         this._elem.css({right:a, bottom:b});
8079                         break;
8080                     case 'w':
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});
8084                         break;
8085                     default:  // same as 'se'
8086                         var a = offsets.right;
8087                         var b = offsets.bottom;
8088                         this._elem.css({right:a, bottom:b});
8089                         break;
8090                 }
8091             }
8092             else {
8093                 switch (this.location) {
8094                     case 'nw':
8095                         this._elem.css({left:0, top:offsets.top});
8096                         break;
8097                     case 'n':
8098                         var a = (offsets.left + (this._plotDimensions.width - offsets.right))/2 - this.getWidth()/2;
8099                         this._elem.css({left: a, top:offsets.top});
8100                         break;
8101                     case 'ne':
8102                         this._elem.css({right:0, top:offsets.top});
8103                         break;
8104                     case 'e':
8105                         var b = (offsets.top + (this._plotDimensions.height - offsets.bottom))/2 - this.getHeight()/2;
8106                         this._elem.css({right:offsets.right, top:b});
8107                         break;
8108                     case 'se':
8109                         this._elem.css({right:offsets.right, bottom:offsets.bottom});
8110                         break;
8111                     case 's':
8112                         var a = (offsets.left + (this._plotDimensions.width - offsets.right))/2 - this.getWidth()/2;
8113                         this._elem.css({left: a, bottom:offsets.bottom});
8114                         break;
8115                     case 'sw':
8116                         this._elem.css({left:offsets.left, bottom:offsets.bottom});
8117                         break;
8118                     case 'w':
8119                         var b = (offsets.top + (this._plotDimensions.height - offsets.bottom))/2 - this.getHeight()/2;
8120                         this._elem.css({left:offsets.left, top:b});
8121                         break;
8122                     default:  // same as 'se'
8123                         this._elem.css({right:offsets.right, bottom:offsets.bottom});
8124                         break;
8125                 }
8126             }
8127         } 
8128     };
8130     /**
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.
8137      * 
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.
8143      * 
8144      * A theme is a simple javascript object with styling parameters for
8145      * various entities of the plot.  A theme has the form:
8146      * 
8147      * 
8148      * > {
8149      * >     _name:f "Default",
8150      * >     target: {
8151      * >         backgroundColor: "transparent"
8152      * >     },
8153      * >     legend: {
8154      * >         textColor: null,
8155      * >         fontFamily: null,
8156      * >         fontSize: null,
8157      * >         border: null,
8158      * >         background: null
8159      * >     },
8160      * >     title: {
8161      * >         textColor: "rgb(102, 102, 102)",
8162      * >         fontFamily: "'Trebuchet MS',Arial,Helvetica,sans-serif",
8163      * >         fontSize: "19.2px",
8164      * >         textAlign: "center"
8165      * >     },
8166      * >     seriesStyles: {},
8167      * >     series: [{
8168      * >         color: "#4bb2c5",
8169      * >         lineWidth: 2.5,
8170      * >         linePattern: "solid",
8171      * >         shadow: true,
8172      * >         fillColor: "#4bb2c5",
8173      * >         showMarker: true,
8174      * >         markerOptions: {
8175      * >             color: "#4bb2c5",
8176      * >             show: true,
8177      * >             style: 'filledCircle',
8178      * >             lineWidth: 1.5,
8179      * >             size: 4,
8180      * >             shadow: true
8181      * >         }
8182      * >     }],
8183      * >     grid: {
8184      * >         drawGridlines: true,
8185      * >         gridLineColor: "#cccccc",
8186      * >         gridLineWidth: 1,
8187      * >         backgroundColor: "#fffdf6",
8188      * >         borderColor: "#999999",
8189      * >         borderWidth: 2,
8190      * >         shadow: true
8191      * >     },
8192      * >     axesStyles: {
8193      * >         label: {},
8194      * >         ticks: {}
8195      * >     },
8196      * >     axes: {
8197      * >         xaxis: {
8198      * >             borderColor: "#999999",
8199      * >             borderWidth: 2,
8200      * >             ticks: {
8201      * >                 show: true,
8202      * >                 showGridline: true,
8203      * >                 showLabel: true,
8204      * >                 showMark: true,
8205      * >                 size: 4,
8206      * >                 textColor: "",
8207      * >                 whiteSpace: "nowrap",
8208      * >                 fontSize: "12px",
8209      * >                 fontFamily: "'Trebuchet MS',Arial,Helvetica,sans-serif"
8210      * >             },
8211      * >             label: {
8212      * >                 textColor: "rgb(102, 102, 102)",
8213      * >                 whiteSpace: "normal",
8214      * >                 fontSize: "14.6667px",
8215      * >                 fontFamily: "'Trebuchet MS',Arial,Helvetica,sans-serif",
8216      * >                 fontWeight: "400"
8217      * >             }
8218      * >         },
8219      * >         yaxis: {
8220      * >             borderColor: "#999999",
8221      * >             borderWidth: 2,
8222      * >             ticks: {
8223      * >                 show: true,
8224      * >                 showGridline: true,
8225      * >                 showLabel: true,
8226      * >                 showMark: true,
8227      * >                 size: 4,
8228      * >                 textColor: "",
8229      * >                 whiteSpace: "nowrap",
8230      * >                 fontSize: "12px",
8231      * >                 fontFamily: "'Trebuchet MS',Arial,Helvetica,sans-serif"
8232      * >             },
8233      * >             label: {
8234      * >                 textColor: null,
8235      * >                 whiteSpace: null,
8236      * >                 fontSize: null,
8237      * >                 fontFamily: null,
8238      * >                 fontWeight: null
8239      * >             }
8240      * >         },
8241      * >         x2axis: {...
8242      * >         },
8243      * >         ...
8244      * >         y9axis: {...
8245      * >         }
8246      * >     }
8247      * > }
8248      * 
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.
8253      * 
8254      * The example shown above has series options for a line series.  Options for other
8255      * series types are shown below:
8256      * 
8257      * Bar Series:
8258      * 
8259      * > {
8260      * >     color: "#4bb2c5",
8261      * >     seriesColors: ["#4bb2c5", "#EAA228", "#c5b47f", "#579575", "#839557", "#958c12", "#953579", "#4b5de4", "#d8b83f", "#ff5800", "#0085cc", "#c747a3", "#cddf54", "#FBD178", "#26B4E3", "#bd70c7"],
8262      * >     lineWidth: 2.5,
8263      * >     shadow: true,
8264      * >     barPadding: 2,
8265      * >     barMargin: 10,
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)"]
8268      * > }
8269      * 
8270      * Pie Series:
8271      * 
8272      * > {
8273      * >     seriesColors: ["#4bb2c5", "#EAA228", "#c5b47f", "#579575", "#839557", "#958c12", "#953579", "#4b5de4", "#d8b83f", "#ff5800", "#0085cc", "#c747a3", "#cddf54", "#FBD178", "#26B4E3", "#bd70c7"],
8274      * >     padding: 20,
8275      * >     sliceMargin: 0,
8276      * >     fill: true,
8277      * >     shadow: true,
8278      * >     startAngle: 0,
8279      * >     lineWidth: 2.5,
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)"]
8281      * > }
8282      * 
8283      * Funnel Series:
8284      * 
8285      * > {
8286      * >     color: "#4bb2c5",
8287      * >     lineWidth: 2,
8288      * >     shadow: true,
8289      * >     padding: {
8290      * >         top: 20,
8291      * >         right: 20,
8292      * >         bottom: 20,
8293      * >         left: 20
8294      * >     },
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)"]
8298      * > }
8299      * 
8300      */
8301     $.jqplot.ThemeEngine = function(){
8302         // Group: Properties
8303         //
8304         // prop: themes
8305         // hash of themes managed by the theme engine.  
8306         // Indexed by theme name.
8307         this.themes = {};
8308         // prop: activeTheme
8309         // Pointer to currently active theme
8310         this.activeTheme=null;
8311         
8312     };
8313     
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'});
8318         var n, i, nn;
8319         
8320         for (n in th.target) {
8321             if (n == "textColor") {
8322                 th.target[n] = this.target.css('color');
8323             }
8324             else {
8325                 th.target[n] = this.target.css(n);
8326             }
8327         }
8328         
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');
8333                 }
8334                 else {
8335                     th.title[n] = this.title._elem.css(n);
8336                 }
8337             }
8338         }
8339         
8340         for (n in th.grid) {
8341             th.grid[n] = this.grid[n];
8342         }
8343         if (th.grid.backgroundColor == null && this.grid.background != null) {
8344             th.grid.backgroundColor = this.grid.background;
8345         }
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');
8350                 }
8351                 else {
8352                     th.legend[n] = this.legend._elem.css(n);
8353                 }
8354             }
8355         }
8356         var s;
8357         
8358         for (i=0; i<this.series.length; i++) {
8359             s = this.series[i];
8360             if (s.renderer.constructor == $.jqplot.LineRenderer) {
8361                 th.series.push(new LineSeriesProperties());
8362             }
8363             else if (s.renderer.constructor == $.jqplot.BarRenderer) {
8364                 th.series.push(new BarSeriesProperties());
8365             }
8366             else if (s.renderer.constructor == $.jqplot.PieRenderer) {
8367                 th.series.push(new PieSeriesProperties());
8368             }
8369             else if (s.renderer.constructor == $.jqplot.DonutRenderer) {
8370                 th.series.push(new DonutSeriesProperties());
8371             }
8372             else if (s.renderer.constructor == $.jqplot.FunnelRenderer) {
8373                 th.series.push(new FunnelSeriesProperties());
8374             }
8375             else if (s.renderer.constructor == $.jqplot.MeterGaugeRenderer) {
8376                 th.series.push(new MeterSeriesProperties());
8377             }
8378             else {
8379                 th.series.push({});
8380             }
8381             for (n in th.series[i]) {
8382                 th.series[i][n] = s[n];
8383             }
8384         }
8385         var a, ax;
8386         for (n in this.axes) {
8387             ax = this.axes[n];
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];
8395                     }
8396                     else if (ax._ticks[0]._elem){
8397                         a.ticks[nn] = ax._ticks[0]._elem.css(nn);
8398                     }
8399                 }
8400             }
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];
8406                     }
8407                     else if (ax._label._elem){
8408                         if (nn == 'textColor') {
8409                             a.label[nn] = ax._label._elem.css('color');
8410                         }
8411                         else {
8412                             a.label[nn] = ax._label._elem.css(nn);
8413                         }
8414                     }
8415                 }
8416             }
8417         }
8418         this.themeEngine._add(th);
8419         this.themeEngine.activeTheme  = this.themeEngine.themes[th._name];
8420     };
8421     /**
8422      * Group: methods
8423      * 
8424      * method: get
8425      * 
8426      * Get and return the named theme or the active theme if no name given.
8427      * 
8428      * parameter:
8429      * 
8430      * name - name of theme to get.
8431      * 
8432      * returns:
8433      * 
8434      * Theme instance of given name.
8435      */   
8436     $.jqplot.ThemeEngine.prototype.get = function(name) {
8437         if (!name) {
8438             // return the active theme
8439             return this.activeTheme;
8440         }
8441         else {
8442             return this.themes[name];
8443         }
8444     };
8445     
8446     function numericalOrder(a,b) { return a-b; }
8447     
8448     /**
8449      * method: getThemeNames
8450      * 
8451      * Return the list of theme names in this manager in alpha-numerical order.
8452      * 
8453      * parameter:
8454      * 
8455      * None
8456      * 
8457      * returns:
8458      * 
8459      * A the list of theme names in this manager in alpha-numerical order.
8460      */       
8461     $.jqplot.ThemeEngine.prototype.getThemeNames = function() {
8462         var tn = [];
8463         for (var n in this.themes) {
8464             tn.push(n);
8465         }
8466         return tn.sort(numericalOrder);
8467     };
8469     /**
8470      * method: getThemes
8471      * 
8472      * Return a list of themes in alpha-numerical order by name.
8473      * 
8474      * parameter:
8475      * 
8476      * None
8477      * 
8478      * returns:
8479      * 
8480      * A list of themes in alpha-numerical order by name.
8481      */ 
8482     $.jqplot.ThemeEngine.prototype.getThemes = function() {
8483         var tn = [];
8484         var themes = [];
8485         for (var n in this.themes) {
8486             tn.push(n);
8487         }
8488         tn.sort(numericalOrder);
8489         for (var i=0; i<tn.length; i++) {
8490             themes.push(this.themes[tn[i]]);
8491         }
8492         return themes;
8493     };
8494     
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;
8500         }
8501         if (!this.themes.hasOwnProperty(name)) {
8502             throw new Error("No theme of that name");
8503         }
8504         else {
8505             var th = this.themes[name];
8506             this.activeTheme = th;
8507             var val, checkBorderColor = false, checkBorderWidth = false;
8508             var arr = ['xaxis', 'x2axis', 'yaxis', 'y2axis'];
8509             
8510             for (i=0; i<arr.length; i++) {
8511                 var ax = arr[i];
8512                 if (th.axesStyles.borderColor != null) {
8513                     plot.axes[ax].borderColor = th.axesStyles.borderColor;
8514                 }
8515                 if (th.axesStyles.borderWidth != null) {
8516                     plot.axes[ax].borderWidth = th.axesStyles.borderWidth;
8517                 }
8518             }
8519             
8520             for (var axname in plot.axes) {
8521                 var axis = plot.axes[axname];
8522                 if (axis.show) {
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;
8529                         redrawPlot = true;
8530                     }
8531                     val = (th.axesStyles.borderWidth != null) ? th.axesStyles.borderWidth : thax.borderWidth;
8532                     if (thax.borderWidth != null) {
8533                         axis.borderWidth = thax.borderWidth;
8534                         redrawPlot = true;
8535                     }
8536                     if (axis._ticks && axis._ticks[0]) {
8537                         for (var nn in thax.ticks) {
8538                             // val = null;
8539                             // if (th.axesStyles.ticks && th.axesStyles.ticks[nn] != null) {
8540                             //     val = th.axesStyles.ticks[nn];
8541                             // }
8542                             // else if (thax.ticks[nn] != null){
8543                             //     val = thax.ticks[nn]
8544                             // }
8545                             val = thax.ticks[nn];
8546                             if (val != null) {
8547                                 axis.tickOptions[nn] = val;
8548                                 axis._ticks = [];
8549                                 redrawPlot = true;
8550                             }
8551                         }
8552                     }
8553                     if (axis._label && axis._label.show) {
8554                         for (var nn in thax.label) {
8555                             // val = null;
8556                             // if (th.axesStyles.label && th.axesStyles.label[nn] != null) {
8557                             //     val = th.axesStyles.label[nn];
8558                             // }
8559                             // else if (thax.label && thax.label[nn] != null){
8560                             //     val = thax.label[nn]
8561                             // }
8562                             val = thax.label[nn];
8563                             if (val != null) {
8564                                 axis.labelOptions[nn] = val;
8565                                 redrawPlot = true;
8566                             }
8567                         }
8568                     }
8569                     
8570                 }
8571             }            
8572             
8573             for (var n in th.grid) {
8574                 if (th.grid[n] != null) {
8575                     plot.grid[n] = th.grid[n];
8576                 }
8577             }
8578             if (!redrawPlot) {
8579                 plot.grid.draw();
8580             }
8581             
8582             if (plot.legend.show) { 
8583                 for (n in th.legend) {
8584                     if (th.legend[n] != null) {
8585                         plot.legend[n] = th.legend[n];
8586                     }
8587                 }
8588             }
8589             if (plot.title.show) {
8590                 for (n in th.title) {
8591                     if (th.title[n] != null) {
8592                         plot.title[n] = th.title[n];
8593                     }
8594                 }
8595             }
8596             
8597             var i;
8598             for (i=0; i<th.series.length; i++) {
8599                 var opts = {};
8600                 var redrawSeries = false;
8601                 for (n in th.series[i]) {
8602                     val = (th.seriesStyles[n] != null) ? th.seriesStyles[n] : th.series[i][n];
8603                     if (val != null) {
8604                         opts[n] = val;
8605                         if (n == 'color') {
8606                             plot.series[i].renderer.shapeRenderer.fillStyle = val;
8607                             plot.series[i].renderer.shapeRenderer.strokeStyle = val;
8608                             plot.series[i][n] = val;
8609                         }
8610                         else if ((n == 'lineWidth') || (n == 'linePattern')) {
8611                             plot.series[i].renderer.shapeRenderer[n] = val;
8612                             plot.series[i][n] = val;
8613                         }
8614                         else if (n == 'markerOptions') {
8615                             merge (plot.series[i].markerOptions, val);
8616                             merge (plot.series[i].markerRenderer, val);
8617                         }
8618                         else {
8619                             plot.series[i][n] = val;
8620                         }
8621                         redrawPlot = true;
8622                     }
8623                 }
8624             }
8625             
8626             if (redrawPlot) {
8627                 plot.target.empty();
8628                 plot.draw();
8629             }
8630             
8631             for (n in th.target) {
8632                 if (th.target[n] != null) {
8633                     plot.target.css(n, th.target[n]);
8634                 }
8635             }
8636         }
8637         
8638     };
8639     
8640     $.jqplot.ThemeEngine.prototype._add = function(theme, name) {
8641         if (name) {
8642             theme._name = name;
8643         }
8644         if (!theme._name) {
8645             theme._name = Date.parse(new Date());
8646         }
8647         if (!this.themes.hasOwnProperty(theme._name)) {
8648             this.themes[theme._name] = theme;
8649         }
8650         else {
8651             throw new Error("jqplot.ThemeEngine Error: Theme already in use");
8652         }
8653     };
8654     
8655     // method remove
8656     // Delete the named theme, return true on success, false on failure.
8657     
8659     /**
8660      * method: remove
8661      * 
8662      * Remove the given theme from the themeEngine.
8663      * 
8664      * parameters:
8665      * 
8666      * name - name of the theme to remove.
8667      * 
8668      * returns:
8669      * 
8670      * true on success, false on failure.
8671      */
8672     $.jqplot.ThemeEngine.prototype.remove = function(name) {
8673         if (name == 'Default') {
8674             return false;
8675         }
8676         return delete this.themes[name];
8677     };
8679     /**
8680      * method: newTheme
8681      * 
8682      * Create a new theme based on the default theme, adding it the themeEngine.
8683      * 
8684      * parameters:
8685      * 
8686      * name - name of the new theme.
8687      * obj - optional object of styles to be applied to this new theme.
8688      * 
8689      * returns:
8690      * 
8691      * new Theme object.
8692      */
8693     $.jqplot.ThemeEngine.prototype.newTheme = function(name, obj) {
8694         if (typeof(name) == 'object') {
8695             obj = obj || name;
8696             name = null;
8697         }
8698         if (obj && obj._name) {
8699             name = obj._name;
8700         }
8701         else {
8702             name = name || Date.parse(new Date());
8703         }
8704         // var th = new $.jqplot.Theme(name);
8705         var th = this.copy(this.themes['Default']._name, name);
8706         $.jqplot.extend(th, obj);
8707         return th;
8708     };
8709     
8710     // function clone(obj) {
8711     //     return eval(obj.toSource());
8712     // }
8713     
8714     function clone(obj){
8715         if(obj == null || typeof(obj) != 'object'){
8716             return obj;
8717         }
8718     
8719         var temp = new obj.constructor();
8720         for(var key in obj){
8721             temp[key] = clone(obj[key]);
8722         }   
8723         return temp;
8724     }
8725     
8726     $.jqplot.clone = clone;
8727     
8728     function merge(obj1, obj2) {
8729         if (obj2 ==  null || typeof(obj2) != 'object') {
8730             return;
8731         }
8732         for (var key in obj2) {
8733             if (key == 'highlightColors') {
8734                 obj1[key] = clone(obj2[key]);
8735             }
8736             if (obj2[key] != null && typeof(obj2[key]) == 'object') {
8737                 if (!obj1.hasOwnProperty(key)) {
8738                     obj1[key] = {};
8739                 }
8740                 merge(obj1[key], obj2[key]);
8741             }
8742             else {
8743                 obj1[key] = obj2[key];
8744             }
8745         }
8746     }
8747     
8748     $.jqplot.merge = merge;
8749     
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" ) {
8757             deep = target;
8758             target = arguments[1] || {};
8759             // skip the boolean and the target
8760             i = 2;
8761         }
8763         // Handle case when target is a string or something (possible in deep copy)
8764         if ( typeof target !== "object" && !toString.call(target) === "[object Function]" ) {
8765             target = {};
8766         }
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 ) {
8777                         continue;
8778                     }
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 ? [ ] : { } )
8785                         , copy );
8786                     }
8787                     // Don't bring in undefined values
8788                     else if ( copy !== undefined ) {
8789                         target[ name ] = copy;
8790                     }
8791                 }
8792             }
8793         }
8794         // Return the modified object
8795         return target;
8796     };
8798     /**
8799      * method: rename
8800      * 
8801      * Rename a theme.
8802      * 
8803      * parameters:
8804      * 
8805      * oldName - current name of the theme.
8806      * newName - desired name of the theme.
8807      * 
8808      * returns:
8809      * 
8810      * new Theme object.
8811      */
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");
8815         }
8816         if (this.themes.hasOwnProperty(newName)) {
8817             throw new Error ("jqplot.ThemeEngine Error: New name already in use.");
8818         }
8819         else if (this.themes.hasOwnProperty(oldName)) {
8820             var th = this.copy (oldName, newName);
8821             this.remove(oldName);
8822             return th;
8823         }
8824         throw new Error("jqplot.ThemeEngine Error: Old name or new name invalid");
8825     };
8827     /**
8828      * method: copy
8829      * 
8830      * Create a copy of an existing theme in the themeEngine, adding it the themeEngine.
8831      * 
8832      * parameters:
8833      * 
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.
8837      * 
8838      * returns:
8839      * 
8840      * new Theme object.
8841      */
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");
8845         }
8846         if (!this.themes.hasOwnProperty(sourceName)) {
8847             var s = "jqplot.ThemeEngine Error: Source name invalid";
8848             throw new Error(s);
8849         }
8850         if (this.themes.hasOwnProperty(targetName)) {
8851             var s = "jqplot.ThemeEngine Error: Target name invalid";
8852             throw new Error(s);
8853         }
8854         else {
8855             var th = clone(this.themes[sourceName]);
8856             th._name = targetName;
8857             $.jqplot.extend(true, th, obj);
8858             this._add(th);
8859             return th;
8860         }
8861     };
8862     
8863     
8864     $.jqplot.Theme = function(name, obj) {
8865         if (typeof(name) == 'object') {
8866             obj = obj || name;
8867             name = null;
8868         }
8869         name = name || Date.parse(new Date());
8870         this._name = name;
8871         this.target = {
8872             backgroundColor: null
8873         };
8874         this.legend = {
8875             textColor: null,
8876             fontFamily: null,
8877             fontSize: null,
8878             border: null,
8879             background: null
8880         };
8881         this.title = {
8882             textColor: null,
8883             fontFamily: null,
8884             fontSize: null,
8885             textAlign: null
8886         };
8887         this.seriesStyles = {};
8888         this.series = [];
8889         this.grid = {
8890             drawGridlines: null,
8891             gridLineColor: null,
8892             gridLineWidth: null,
8893             backgroundColor: null,
8894             borderColor: null,
8895             borderWidth: null,
8896             shadow: null
8897         };
8898         this.axesStyles = {label:{}, ticks:{}};
8899         this.axes = {};
8900         if (typeof(obj) == 'string') {
8901             this._name = obj;
8902         }
8903         else if(typeof(obj) == 'object') {
8904             $.jqplot.extend(true, this, obj);
8905         }
8906     };
8907     
8908     var AxisProperties = function() {
8909         this.borderColor = null;
8910         this.borderWidth = null;
8911         this.ticks = new AxisTicks();
8912         this.label = new AxisLabel();
8913     };
8914     
8915     var AxisTicks = function() {
8916         this.show = null;
8917         this.showGridline = null;
8918         this.showLabel = null;
8919         this.showMark = null;
8920         this.size = null;
8921         this.textColor = null;
8922         this.whiteSpace = null;
8923         this.fontSize = null;
8924         this.fontFamily = null;
8925     };
8926     
8927     var AxisLabel = function() {
8928         this.textColor = null;
8929         this.whiteSpace = null;
8930         this.fontSize = null;
8931         this.fontFamily = null;
8932         this.fontWeight = null;
8933     };
8934     
8935     var LineSeriesProperties = function() {
8936         this.color=null;
8937         this.lineWidth=null;
8938         this.linePattern=null;
8939         this.shadow=null;
8940         this.fillColor=null;
8941         this.showMarker=null;
8942         this.markerOptions = new MarkerOptions();
8943     };
8944     
8945     var MarkerOptions = function() {
8946         this.show = null;
8947         this.style = null;
8948         this.lineWidth = null;
8949         this.size = null;
8950         this.color = null;
8951         this.shadow = null;
8952     };
8953     
8954     var BarSeriesProperties = function() {
8955         this.color=null;
8956         this.seriesColors=null;
8957         this.lineWidth=null;
8958         this.shadow=null;
8959         this.barPadding=null;
8960         this.barMargin=null;
8961         this.barWidth=null;
8962         this.highlightColors=null;
8963     };
8964     
8965     var PieSeriesProperties = function() {
8966         this.seriesColors=null;
8967         this.padding=null;
8968         this.sliceMargin=null;
8969         this.fill=null;
8970         this.shadow=null;
8971         this.startAngle=null;
8972         this.lineWidth=null;
8973         this.highlightColors=null;
8974     };
8975     
8976     var DonutSeriesProperties = function() {
8977         this.seriesColors=null;
8978         this.padding=null;
8979         this.sliceMargin=null;
8980         this.fill=null;
8981         this.shadow=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;
8988     };
8989     
8990     var FunnelSeriesProperties = function() {
8991         this.color=null;
8992         this.lineWidth=null;
8993         this.shadow=null;
8994         this.padding=null;
8995         this.sectionMargin=null;
8996         this.seriesColors=null;
8997         this.highlightColors=null;
8998     };
8999     
9000     var MeterSeriesProperties = function() {
9001         this.padding=null;
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;
9012     };
9013         
9017     $.fn.jqplotChildText = function() {
9018         return $(this).contents().filter(function() {
9019             return this.nodeType == 3;  // Node.TEXT_NODE not defined in I7
9020         }).text();
9021     };
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'];
9027         var style = [];
9029         for (var i=0 ; i < attrs.length; ++i) {
9030             var attr = String(css[attrs[i]]);
9032             if (attr && attr != 'normal') {
9033                 style.push(attr);
9034             }
9035         }
9036         return style.join(' ');
9037     };
9039     /**
9040      * Namespace: $.fn
9041      * jQuery namespace to attach functions to jQuery elements.
9042      *  
9043      */
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) {
9053             return null;
9054         }
9056         // excanvas and hence IE < 9 do not support toDataURL and cannot export images.
9057         if ($.jqplot.use_excanvas) {
9058             return null;
9059         }
9060         
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;
9087                     transx = -templeft;
9088                 }
9089                 if (temptop < -transy) {
9090                     h = h - transy - temptop;
9091                     transy = - temptop;
9092                 }
9093                 if (tempright > w) {
9094                     w = tempright;
9095                 }
9096                 if (tempbottom > h) {
9097                     h =  tempbottom;
9098                 }
9099             });
9100         }
9102         newCanvas.width = w + Number(x_offset);
9103         newCanvas.height = h + Number(y_offset);
9105         var newContext = newCanvas.getContext("2d"); 
9107         newContext.save();
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;
9121             }
9122             return lineheight;
9123         }
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;
9131             var w = '';
9132             var breaks = [];
9133             var temptop = top;
9134             var templeft = left;
9136             for (var i=0; i<wl; i++) {
9137                 w += words[i];
9138                 if (context.measureText(w).width > tagwidth) {
9139                     breaks.push(i);
9140                     w = '';
9141                     i--;
9142                 }   
9143             }
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;
9148                 }
9149                 context.fillText(text, templeft, top);
9150             }
9151             else {
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;
9156                 }
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;
9164                     }
9165                     context.fillText(w, templeft, temptop);
9166                     temptop += lineheight;
9167                 }
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;
9172                 }
9173                 context.fillText(w, templeft, temptop);
9174             }
9176         }
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);
9192                 });
9193                 var text = $(el).jqplotChildText();
9195                 if (text) {
9196                     newContext.font = $(el).jqplotGetComputedFontStyle();
9197                     newContext.fillStyle = $(el).css('color');
9199                     writeWrappedText(el, newContext, text, left, top, w);
9200                 }
9201             }
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());
9211                 }
9213                 // find all the swatches
9214                 $(el).find('div.jqplot-table-legend-swatch-outline').each(function() {
9215                     // get the first div and stroke it
9216                     var elem = $(this);
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
9223                     
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);
9232                 });
9234                 // now add text
9236                 $(el).find('td.jqplot-table-legend-label').each(function(){
9237                     var elem = $(this);
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);
9243                 });
9245                 var elem = null;
9246             }
9248             else if (tagname == 'canvas') {
9249                 newContext.drawImage(el, left, top);
9250             }
9251         }
9252         $(this).children().each(function() {
9253             _jqpToImage(this, x_offset, y_offset);
9254         });
9255         return newCanvas;
9256     };
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);
9262         if (imgCanvas) {
9263             return imgCanvas.toDataURL("image/png");
9264         }
9265         else {
9266             return null;
9267         }
9268     };
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);
9275         elem.src = str;
9276         return elem;
9277     };
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)+' />';
9283         return str;
9284     };
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({});
9290         if (imgData) {
9291             window.location.href = imgData.replace("image/png", "image/octet-stream");
9292         }
9294     };
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({});
9301         if (imgStr) {
9302             var w = window.open('');
9303             w.document.open("image/png");
9304             w.document.write(imgStr);
9305             w.document.close();
9306             w = null;
9307         }
9308     };
9309     
9313     /** 
9314      * @description
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>
9318      *
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>
9322      * 
9323      * @author Chris Leonello
9324      * @date #date#
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.
9330      * 
9331      * <p>Ken's origianl Date Instance Methods and copyright notice:</p>
9332      * <pre>
9333      * Ken Snyder (ken d snyder at gmail dot com)
9334      * 2008-09-10
9335      * version 2.0.2 (http://kendsnyder.com/sandbox/date/)     
9336      * Creative Commons Attribution License 3.0 (http://creativecommons.org/licenses/by/3.0/)
9337      * </pre>
9338      * 
9339      * @class
9340      * @name jsDate
9341      * @param  {String | Number | Array | Date&nbsp;Object | Options&nbsp;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.
9344      */
9345      
9346     var jsDate = function () {
9347     
9348         this.syntax = jsDate.config.syntax;
9349         this._type = "jsDate";
9350         this.proxy = new Date();
9351         this.options = {};
9352         this.locale = jsDate.regional.getLocale();
9353         this.formatString = '';
9354         this.defaultCentury = jsDate.config.defaultCentury;
9356         switch ( arguments.length ) {
9357             case 0:
9358                 break;
9359             case 1:
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);
9368                 }
9369                 else {
9370                     this.proxy = jsDate.createDate(arguments[0]);
9371                 }
9372                 break;
9373             default:
9374                 var a = [];
9375                 for ( var i=0; i<arguments.length; i++ ) {
9376                     a.push(arguments[i]);
9377                 }
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) );
9383                 }
9384                 break;
9385         }
9386     };
9387     
9388     /**
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.
9393      */
9394     jsDate.config = {
9395         defaultLocale: 'en',
9396         syntax: 'perl',
9397         defaultCentury: 1900
9398     };
9399         
9400     /**
9401      * Add an arbitrary amount to the currently stored date
9402      * 
9403      * @param {Number} number      
9404      * @param {String} unit
9405      * @returns {jsDate}       
9406      */
9407      
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));
9412         } else {
9413             factor.add(this, number);
9414         }
9415         return this;
9416     };
9417         
9418     /**
9419      * Create a new jqplot.date object with the same date
9420      * 
9421      * @returns {jsDate}
9422      */  
9423      
9424     jsDate.prototype.clone = function() {
9425             return new jsDate(this.proxy.getTime());
9426     };
9428     /**
9429      * Get the UTC TimeZone Offset of this date in milliseconds.
9430      *
9431      * @returns {Number}
9432      */
9434     jsDate.prototype.getUtcOffset = function() {
9435         return this.proxy.getTimezoneOffset() * 60000;
9436     };
9438     /**
9439      * Find the difference between this jsDate and another date.
9440      * 
9441      * @param {String| Number| Array| jsDate&nbsp;Object| Date&nbsp;Object} dateObj
9442      * @param {String} unit
9443      * @param {Boolean} allowDecimal
9444      * @returns {Number} Number of units difference between dates.
9445      */
9446      
9447     jsDate.prototype.diff = function(dateObj, unit, allowDecimal) {
9448         // ensure we have a Date object
9449         dateObj = new jsDate(dateObj);
9450         if (dateObj === null) {
9451             return null;
9452         }
9453         // get the multiplying factor integer or factor function
9454         var factor = multipliers[unit] || multipliers.day;
9455         if (typeof factor == 'number') {
9456             // multiply
9457             var unitDiff = (this.proxy.getTime() - dateObj.proxy.getTime()) / factor;
9458         } else {
9459             // run function
9460             var unitDiff = factor.diff(this.proxy, dateObj.proxy);
9461         }
9462         // if decimals are not allowed, round toward zero
9463         return (allowDecimal ? unitDiff : Math[unitDiff > 0 ? 'floor' : 'ceil'](unitDiff));          
9464     };
9465     
9466     /**
9467      * Get the abbreviated name of the current week day
9468      * 
9469      * @returns {String}
9470      */   
9471      
9472     jsDate.prototype.getAbbrDayName = function() {
9473         return jsDate.regional[this.locale]["dayNamesShort"][this.proxy.getDay()];
9474     };
9475     
9476     /**
9477      * Get the abbreviated name of the current month
9478      * 
9479      * @returns {String}
9480      */
9481      
9482     jsDate.prototype.getAbbrMonthName = function() {
9483         return jsDate.regional[this.locale]["monthNamesShort"][this.proxy.getMonth()];
9484     };
9485     
9486     /**
9487      * Get UPPER CASE AM or PM for the current time
9488      * 
9489      * @returns {String}
9490      */
9491      
9492     jsDate.prototype.getAMPM = function() {
9493         return this.proxy.getHours() >= 12 ? 'PM' : 'AM';
9494     };
9495     
9496     /**
9497      * Get lower case am or pm for the current time
9498      * 
9499      * @returns {String}
9500      */
9501      
9502     jsDate.prototype.getAmPm = function() {
9503         return this.proxy.getHours() >= 12 ? 'pm' : 'am';
9504     };
9505     
9506     /**
9507      * Get the century (19 for 20th Century)
9508      *
9509      * @returns {Integer} Century (19 for 20th century).
9510      */
9511     jsDate.prototype.getCentury = function() { 
9512         return parseInt(this.proxy.getFullYear()/100, 10);
9513     };
9514     
9515     /**
9516      * Implements Date functionality
9517      */
9518     jsDate.prototype.getDate = function() {
9519         return this.proxy.getDate();
9520     };
9521     
9522     /**
9523      * Implements Date functionality
9524      */
9525     jsDate.prototype.getDay = function() {
9526         return this.proxy.getDay();
9527     };
9528     
9529     /**
9530      * Get the Day of week 1 (Monday) thru 7 (Sunday)
9531      * 
9532      * @returns {Integer} Day of week 1 (Monday) thru 7 (Sunday)
9533      */
9534     jsDate.prototype.getDayOfWeek = function() { 
9535         var dow = this.proxy.getDay(); 
9536         return dow===0?7:dow; 
9537     };
9538     
9539     /**
9540      * Get the day of the year
9541      * 
9542      * @returns {Integer} 1 - 366, day of the year
9543      */
9544     jsDate.prototype.getDayOfYear = function() {
9545         var d = this.proxy;
9546         var ms = d - new Date('' + d.getFullYear() + '/1/1 GMT');
9547         ms += d.getTimezoneOffset()*60000;
9548         d = null;
9549         return parseInt(ms/60000/60/24, 10)+1;
9550     };
9551     
9552     /**
9553      * Get the name of the current week day
9554      * 
9555      * @returns {String}
9556      */  
9557      
9558     jsDate.prototype.getDayName = function() {
9559         return jsDate.regional[this.locale]["dayNames"][this.proxy.getDay()];
9560     };
9561     
9562     /**
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).
9565      */
9566     jsDate.prototype.getFullWeekOfYear = function() {
9567         var d = this.proxy;
9568         var doy = this.getDayOfYear();
9569         var rdow = 6-d.getDay();
9570         var woy = parseInt((doy+rdow)/7, 10);
9571         return woy;
9572     };
9573     
9574     /**
9575      * Implements Date functionality
9576      */
9577     jsDate.prototype.getFullYear = function() {
9578         return this.proxy.getFullYear();
9579     };
9580     
9581     /**
9582      * Get the GMT offset in hours and minutes (e.g. +06:30)
9583      * 
9584      * @returns {String}
9585      */
9586      
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);
9596     };
9597     
9598     /**
9599      * Implements Date functionality
9600      */
9601     jsDate.prototype.getHours = function() {
9602         return this.proxy.getHours();
9603     };
9604     
9605     /**
9606      * Get the current hour on a 12-hour scheme
9607      * 
9608      * @returns {Integer}
9609      */
9610      
9611     jsDate.prototype.getHours12  = function() {
9612         var hours = this.proxy.getHours();
9613         return hours > 12 ? hours - 12 : (hours == 0 ? 12 : hours);
9614     };
9615     
9616     
9617     jsDate.prototype.getIsoWeek = function() {
9618         var d = this.proxy;
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)
9628         {
9629             idow = 1;
9630         }
9631         else if(idow === 0)
9632         {
9633             d = new jsDate(new Date('' + (d.getFullYear()-1) + '/12/31'));
9634             idow = d.getIsoWeek();
9635         }
9636         d = null;
9637         return idow;
9638     };
9639     
9640     /**
9641      * Implements Date functionality
9642      */
9643     jsDate.prototype.getMilliseconds = function() {
9644         return this.proxy.getMilliseconds();
9645     };
9646     
9647     /**
9648      * Implements Date functionality
9649      */
9650     jsDate.prototype.getMinutes = function() {
9651         return this.proxy.getMinutes();
9652     };
9653     
9654     /**
9655      * Implements Date functionality
9656      */
9657     jsDate.prototype.getMonth = function() {
9658         return this.proxy.getMonth();
9659     };
9660     
9661     /**
9662      * Get the name of the current month
9663      * 
9664      * @returns {String}
9665      */
9666      
9667     jsDate.prototype.getMonthName = function() {
9668         return jsDate.regional[this.locale]["monthNames"][this.proxy.getMonth()];
9669     };
9670     
9671     /**
9672      * Get the number of the current month, 1-12
9673      * 
9674      * @returns {Integer}
9675      */
9676      
9677     jsDate.prototype.getMonthNumber = function() {
9678         return this.proxy.getMonth() + 1;
9679     };
9680     
9681     /**
9682      * Implements Date functionality
9683      */
9684     jsDate.prototype.getSeconds = function() {
9685         return this.proxy.getSeconds();
9686     };
9687     
9688     /**
9689      * Return a proper two-digit year integer
9690      * 
9691      * @returns {Integer}
9692      */
9693      
9694     jsDate.prototype.getShortYear = function() {
9695         return this.proxy.getYear() % 100;
9696     };
9697     
9698     /**
9699      * Implements Date functionality
9700      */
9701     jsDate.prototype.getTime = function() {
9702         return this.proxy.getTime();
9703     };
9704     
9705     /**
9706      * Get the timezone abbreviation
9707      *
9708      * @returns {String} Abbreviation for the timezone
9709      */
9710     jsDate.prototype.getTimezoneAbbr = function() {
9711         return this.proxy.toString().replace(/^.*\(([^)]+)\)$/, '$1'); 
9712     };
9713     
9714     /**
9715      * Get the browser-reported name for the current timezone (e.g. MDT, Mountain Daylight Time)
9716      * 
9717      * @returns {String}
9718      */
9719     jsDate.prototype.getTimezoneName = function() {
9720         var match = /(?:\((.+)\)$| ([A-Z]{3}) )/.exec(this.toString());
9721         return match[1] || match[2] || 'GMT' + this.getGmtOffset();
9722     }; 
9723     
9724     /**
9725      * Implements Date functionality
9726      */
9727     jsDate.prototype.getTimezoneOffset = function() {
9728         return this.proxy.getTimezoneOffset();
9729     };
9730     
9731     
9732     /**
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).
9735      */
9736     jsDate.prototype.getWeekOfYear = function() {
9737         var doy = this.getDayOfYear();
9738         var rdow = 7 - this.getDayOfWeek();
9739         var woy = parseInt((doy+rdow)/7, 10);
9740         return woy;
9741     };
9742     
9743     /**
9744      * Get the current date as a Unix timestamp
9745      * 
9746      * @returns {Integer}
9747      */
9748      
9749     jsDate.prototype.getUnix = function() {
9750         return Math.round(this.proxy.getTime() / 1000, 0);
9751     }; 
9752     
9753     /**
9754      * Implements Date functionality
9755      */
9756     jsDate.prototype.getYear = function() {
9757         return this.proxy.getYear();
9758     };
9759     
9760     /**
9761      * Return a date one day ahead (or any other unit)
9762      * 
9763      * @param {String} unit Optional, year | month | day | week | hour | minute | second | millisecond
9764      * @returns {jsDate}
9765      */
9766      
9767     jsDate.prototype.next = function(unit) {
9768         unit = unit || 'day';
9769         return this.clone().add(1, unit);
9770     };
9771     
9772     /**
9773      * Set the jsDate instance to a new date.
9774      *
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.
9779      */
9780     jsDate.prototype.set = function() {
9781         switch ( arguments.length ) {
9782             case 0:
9783                 this.proxy = new Date();
9784                 break;
9785             case 1:
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);
9794                 }
9795                 else {
9796                     this.proxy = jsDate.createDate(arguments[0]);
9797                 }
9798                 break;
9799             default:
9800                 var a = [];
9801                 for ( var i=0; i<arguments.length; i++ ) {
9802                     a.push(arguments[i]);
9803                 }
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) );
9809                 }
9810                 break;
9811         }
9812         return this;
9813     };
9814     
9815     /**
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. 
9818      */
9819     jsDate.prototype.setDate = function(n) {
9820         this.proxy.setDate(n);
9821         return this;
9822     };
9823     
9824     /**
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. 
9829      */
9830     jsDate.prototype.setFullYear = function() {
9831         this.proxy.setFullYear.apply(this.proxy, arguments);
9832         return this;
9833     };
9834     
9835     /**
9836      * Sets the hours for a specified date according to local time.
9837      * 
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. 
9844      */
9845     jsDate.prototype.setHours = function() {
9846         this.proxy.setHours.apply(this.proxy, arguments);
9847         return this;
9848     };
9849     
9850     /**
9851      * Implements Date functionality
9852      */ 
9853     jsDate.prototype.setMilliseconds = function(n) {
9854         this.proxy.setMilliseconds(n);
9855         return this;
9856     };
9857     
9858     /**
9859      * Implements Date functionality
9860      */ 
9861     jsDate.prototype.setMinutes = function() {
9862         this.proxy.setMinutes.apply(this.proxy, arguments);
9863         return this;
9864     };
9865     
9866     /**
9867      * Implements Date functionality
9868      */ 
9869     jsDate.prototype.setMonth = function() {
9870         this.proxy.setMonth.apply(this.proxy, arguments);
9871         return this;
9872     };
9873     
9874     /**
9875      * Implements Date functionality
9876      */ 
9877     jsDate.prototype.setSeconds = function() {
9878         this.proxy.setSeconds.apply(this.proxy, arguments);
9879         return this;
9880     };
9881     
9882     /**
9883      * Implements Date functionality
9884      */ 
9885     jsDate.prototype.setTime = function(n) {
9886         this.proxy.setTime(n);
9887         return this;
9888     };
9889     
9890     /**
9891      * Implements Date functionality
9892      */ 
9893     jsDate.prototype.setYear = function() {
9894         this.proxy.setYear.apply(this.proxy, arguments);
9895         return this;
9896     };
9897     
9898     /**
9899      * Provide a formatted string representation of this date.
9900      * 
9901      * @param {String} formatString A format string.  
9902      * See: {@link jsDate.formats}.
9903      * @returns {String} Date String.
9904      */
9905             
9906     jsDate.prototype.strftime = function(formatString) {
9907         formatString = formatString || this.formatString || jsDate.regional[this.locale]['formatString'];
9908         return jsDate.strftime(this, formatString, this.syntax);
9909     };
9910         
9911     /**
9912      * Return a String representation of this jsDate object.
9913      * @returns {String} Date string.
9914      */
9915     
9916     jsDate.prototype.toString = function() {
9917         return this.proxy.toString();
9918     };
9919         
9920     /**
9921      * Convert the current date to an 8-digit integer (%Y%m%d)
9922      * 
9923      * @returns {Integer}
9924      */
9925      
9926     jsDate.prototype.toYmdInt = function() {
9927         return (this.proxy.getFullYear() * 10000) + (this.getMonthNumber() * 100) + this.proxy.getDate();
9928     };
9929     
9930     /**
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>
9936      * 
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(' ')
9944      * };
9945      * </pre>
9946      * <p>After adding localizations, call <code>jsDate.regional.getLocale();</code> to update the locale setting with the
9947      * new localizations.</p>
9948      */
9949      
9950     jsDate.regional = {
9951         'en': {
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'
9957         },
9958         
9959         'fr': {
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'
9965         },
9966         
9967         'de': {
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'
9973         },
9974         
9975         'es': {
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&eacute;rcoles','Jueves','Viernes','S&aacute;bado'],
9979             dayNamesShort: ['Dom','Lun','Mar','Mi&eacute;','Juv','Vie','S&aacute;b'],
9980             formatString: '%Y-%m-%d %H:%M:%S'
9981         },
9982         
9983         'ru': {
9984             monthNames: ['Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'],
9985             monthNamesShort: ['Янв','Фев','Мар','Апр','Май','Июн','Июл','Авг','Сен','Окт','Ноя','Дек'],
9986             dayNames: ['воскресенье','понедельник','вторник','среда','четверг','пятница','суббота'],
9987             dayNamesShort: ['вск','пнд','втр','срд','чтв','птн','сбт'],
9988             formatString: '%Y-%m-%d %H:%M:%S'
9989         },
9990         
9991         'ar': {
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'
9997         },
9998         
9999         'pt': {
10000             monthNames: ['Janeiro','Fevereiro','Mar&ccedil;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&ccedil;a-feira','Quarta-feira','Quinta-feira','Sexta-feira','S&aacute;bado'],
10003             dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','S&aacute;b'],
10004             formatString: '%Y-%m-%d %H:%M:%S'   
10005         },
10006         
10007         'pt-BR': {
10008             monthNames: ['Janeiro','Fevereiro','Mar&ccedil;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&ccedil;a-feira','Quarta-feira','Quinta-feira','Sexta-feira','S&aacute;bado'],
10011             dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','S&aacute;b'],
10012             formatString: '%Y-%m-%d %H:%M:%S'
10013         }
10014         
10015     
10016     };
10017     
10018     // Set english variants to 'en'
10019     jsDate.regional['en-US'] = jsDate.regional['en-GB'] = jsDate.regional['en'];
10020     
10021     /**
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
10025      */
10026      
10027     jsDate.regional.getLocale = function () {
10028         var l = jsDate.config.defaultLocale;
10029         
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;
10034             }
10035         }
10036         
10037         return l;
10038     };
10039     
10040     // ms in day
10041     var day = 24 * 60 * 60 * 1000;
10042     
10043     // padd a number with zeros
10044     var addZeros = function(num, digits) {
10045         num = String(num);
10046         var i = digits - num.length;
10047         var s = String(Math.pow(10, i)).slice(1);
10048         return s.concat(num);
10049     };
10051     // representations used for calculating differences between dates.
10052     // This borrows heavily from Ken Snyder's work.
10053     var multipliers = {
10054         millisecond: 1,
10055         second: 1000,
10056         minute: 60 * 1000,
10057         hour: 60 * 60 * 1000,
10058         day: day,
10059         week: 7 * day,
10060         month: {
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
10066                 // 11 % 12 = 11
10067                 // 12 % 12 = 0
10068                 var prevMonth = d.getMonth() + (number % 12);
10069                 if (prevMonth == 12) {
10070                     prevMonth = 0;
10071                     d.setYear(d.getFullYear() + 1);
10072                 } else if (prevMonth == -1) {
10073                     prevMonth = 11;
10074                     d.setYear(d.getFullYear() - 1);
10075                 }
10076                 d.setMonth(prevMonth);
10077             },
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);
10088             }
10089         },
10090         year: {
10091             // add a number of years
10092             add: function(d, number) {
10093                 d.setYear(d.getFullYear() + Math[number > 0 ? 'floor' : 'ceil'](number));
10094             },
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;
10098             }
10099         }        
10100     };
10101     //
10102     // Alias each multiplier with an 's' to allow 'year' and 'years' for example.
10103     // This comes from Ken Snyders work.
10104     //
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];
10108         }
10109     }
10110     
10111     //
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.
10114     //
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);
10119         } else {
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]]() : '';
10123             if (getter[1]) {
10124                 nbr = addZeros(nbr, getter[1]);
10125             }
10126             return nbr;
10127         }       
10128     };
10129     
10130     /**
10131      * @static
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');
10136      * </pre>
10137      * @param {String | Number | Array | jsDate&nbsp;Object | Date&nbsp;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.
10143     */
10144     //
10145     // Logic as implemented here is very similar to Ken Snyder's Date Instance Methods.
10146     //
10147     jsDate.strftime = function(d, formatString, syntax, locale) {
10148         var syn = 'perl';
10149         var loc = jsDate.regional.getLocale();
10150         
10151         // check if syntax and locale are available or reversed
10152         if (syntax && jsDate.formats.hasOwnProperty(syntax)) {
10153             syn = syntax;
10154         }
10155         else if (syntax && jsDate.regional.hasOwnProperty(syntax)) {
10156             loc = syntax;
10157         }
10158         
10159         if (locale && jsDate.formats.hasOwnProperty(locale)) {
10160             syn = locale;
10161         }
10162         else if (locale && jsDate.regional.hasOwnProperty(locale)) {
10163             loc = locale;
10164         }
10165         
10166         if (get_type(d) != "[object Object]" || d._type != "jsDate") {
10167             d = new jsDate(d);
10168             d.locale = loc;
10169         }
10170         if (!formatString) {
10171             formatString = d.formatString || jsDate.regional[loc]['formatString'];
10172         }
10173         // default the format string to year-month-day
10174         var source = formatString || '%Y-%m-%d', 
10175             result = '', 
10176             match;
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);
10183             } else {
10184                 result += source;
10185                 source = '';
10186             }
10187         }
10188         return result;
10189     };
10190     
10191     /**
10192      * @namespace
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
10195      * added like:
10196      * 
10197      * <pre class="code">
10198      * jsDate.formats["perl"] = {
10199      *     "codes": {
10200      *         matcher: /someregex/,
10201      *         Y: "fullYear",  // name of "get" method without the "get",
10202      *         ...,            // more codes
10203      *     },
10204      *     "shortcuts": {
10205      *         F: '%Y-%m-%d',
10206      *         ...,            // more shortcuts
10207      *     }
10208      * };
10209      * </pre>
10210      * 
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>
10213      */
10214     
10215     jsDate.formats = {
10216         ISO:'%Y-%m-%dT%H:%M:%S.%N%G',
10217         SQL:'%Y-%m-%d %H:%M:%S'
10218     };
10219     
10220     /**
10221      * Perl format codes and shortcuts for strftime.
10222      * 
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()
10226      * 
10227      * <p>The following format codes are defined:</p>
10228      * 
10229      * <pre class="code">
10230      * Code    Result                    Description
10231      * == Years ==           
10232      * %Y      2008                      Four-digit year
10233      * %y      08                        Two-digit year
10234      * 
10235      * == Months ==          
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
10240      * 
10241      * == Days ==            
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)
10248      * 
10249      * == Hours ==           
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)
10254      * %p      PM                        AM or PM
10255      * 
10256      * == Minutes ==         
10257      * %M      09                        Minutes (two digits)
10258      * %#M     9                         Minutes (one or two digits)
10259      * 
10260      * == Seconds ==         
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)
10264      * 
10265      * == Milliseconds ==    
10266      * %N      008                       Milliseconds (three digits)
10267      * %#N     8                         Milliseconds (one to three digits)
10268      * 
10269      * == Timezone ==        
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
10273      * 
10274      * == Shortcuts ==       
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
10282      * %R      15:31                     %H:%M
10283      * %r      03:31:00 PM               %I:%M:%S %p
10284      * 
10285      * == Characters ==      
10286      * %n      \n                        Newline
10287      * %t      \t                        Tab
10288      * %%      %                         Percent Symbol
10289      * </pre>
10290      * 
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>
10293      * 
10294      * <p>Format codes and format shortcuts can be redefined after the jsDate
10295      * module is imported.</p>
10296      * 
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>
10299      * 
10300      * <code>/()%(#?(%|[a-z]))/i</code>
10301      * 
10302      * <p>which corresponds to the Perl syntax used by default.</p>
10303      * 
10304      * <p>By customizing the matcher and format codes, nearly any strftime functionality is possible.</p>
10305      */
10306      
10307     jsDate.formats.perl = {
10308         codes: {
10309             //
10310             // 2-part regex matcher for format codes
10311             //
10312             // first match must be the character before the code (to account for escaping)
10313             // second match must be the format code character(s)
10314             //
10315             matcher: /()%(#?(%|[a-z]))/i,
10316             // year
10317             Y: 'FullYear',
10318             y: 'ShortYear.2',
10319             // month
10320             m: 'MonthNumber.2',
10321             '#m': 'MonthNumber',
10322             B: 'MonthName',
10323             b: 'AbbrMonthName',
10324             // day
10325             d: 'Date.2',
10326             '#d': 'Date',
10327             e: 'Date',
10328             A: 'DayName',
10329             a: 'AbbrDayName',
10330             w: 'Day',
10331             // hours
10332             H: 'Hours.2',
10333             '#H': 'Hours',
10334             I: 'Hours12.2',
10335             '#I': 'Hours12',
10336             p: 'AMPM',
10337             // minutes
10338             M: 'Minutes.2',
10339             '#M': 'Minutes',
10340             // seconds
10341             S: 'Seconds.2',
10342             '#S': 'Seconds',
10343             s: 'Unix',
10344             // milliseconds
10345             N: 'Milliseconds.3',
10346             '#N': 'Milliseconds',
10347             // timezone
10348             O: 'TimezoneOffset',
10349             Z: 'TimezoneName',
10350             G: 'GmtOffset'  
10351         },
10352         
10353         shortcuts: {
10354             // date
10355             F: '%Y-%m-%d',
10356             // time
10357             T: '%H:%M:%S',
10358             X: '%H:%M:%S',
10359             // local format date
10360             x: '%m/%d/%y',
10361             D: '%m/%d/%y',
10362             // local format extended
10363             '#c': '%a %b %e %H:%M:%S %Y',
10364             // local format short
10365             v: '%e-%b-%Y',
10366             R: '%H:%M',
10367             r: '%I:%M:%S %p',
10368             // tab and newline
10369             t: '\t',
10370             n: '\n',
10371             '%': '%'
10372         }
10373     };
10374     
10375     /**
10376      * PHP format codes and shortcuts for strftime.
10377      * 
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()
10381      * 
10382      * <p>The following format codes are defined:</p>
10383      * 
10384      * <pre class="code">
10385      * Code    Result                    Description
10386      * === Days ===        
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
10394      *                                  
10395      * === 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
10401      * === Month ===                    
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
10406      * 
10407      * === Year ===                     
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
10411      * 
10412      * === Time ===                     
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
10426      * 
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
10432      * 
10433      * === Miscellaneous ===            
10434      * %n        ---                     A newline character (\n)
10435      * %t        ---                     A Tab character (\t)
10436      * %%        ---                     A literal percentage character (%)
10437      * </pre>
10438      */
10440     jsDate.formats.php = {
10441         codes: {
10442             //
10443             // 2-part regex matcher for format codes
10444             //
10445             // first match must be the character before the code (to account for escaping)
10446             // second match must be the format code character(s)
10447             //
10448             matcher: /()%((%|[a-z]))/i,
10449             // day
10450             a: 'AbbrDayName',
10451             A: 'DayName',
10452             d: 'Date.2',
10453             e: 'Date',
10454             j: 'DayOfYear.3',
10455             u: 'DayOfWeek',
10456             w: 'Day',
10457             // week
10458             U: 'FullWeekOfYear.2',
10459             V: 'IsoWeek.2',
10460             W: 'WeekOfYear.2',
10461             // month
10462             b: 'AbbrMonthName',
10463             B: 'MonthName',
10464             m: 'MonthNumber.2',
10465             h: 'AbbrMonthName',
10466             // year
10467             C: 'Century.2',
10468             y: 'ShortYear.2',
10469             Y: 'FullYear',
10470             // time
10471             H: 'Hours.2',
10472             I: 'Hours12.2',
10473             l: 'Hours12',
10474             p: 'AMPM',
10475             P: 'AmPm',
10476             M: 'Minutes.2',
10477             S: 'Seconds.2',
10478             s: 'Unix',
10479             O: 'TimezoneOffset',
10480             z: 'GmtOffset',
10481             Z: 'TimezoneAbbr'
10482         },
10483         
10484         shortcuts: {
10485             D: '%m/%d/%y',
10486             F: '%Y-%m-%d',
10487             T: '%H:%M:%S',
10488             X: '%H:%M:%S',
10489             x: '%m/%d/%y',
10490             R: '%H:%M',
10491             r: '%I:%M:%S %p',
10492             t: '\t',
10493             n: '\n',
10494             '%': '%'
10495         }
10496     };   
10497     //
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.
10504     //
10505     jsDate.createDate = function(date) {
10506         // if passing in multiple arguments, try Date constructor
10507         if (date == null) {
10508             return new Date();
10509         }
10510         // If the passed value is already a date object, return it
10511         if (date instanceof Date) {
10512             return date;
10513         }
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);
10518         }
10519         
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.  
10522         // 
10523         // For example: 
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.
10527         
10528         // remove leading and trailing spaces
10529         var parsable = String(date).replace(/^\s*(.+)\s*$/g, '$1');
10530         
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");
10533         
10534         /////////
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.
10538         /////////
10539         
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");
10542         
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;
10548             ny = String(ny);
10549             
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);
10552             
10553         }
10554         
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]/);
10561         
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;
10568             
10569             if (m1 > 31) { // first number is a year
10570                 nd = m3;
10571                 nm = m2;
10572                 ny = cent + m1;
10573             }
10574             
10575             else { // last number is the year
10576                 nd = m2;
10577                 nm = m1;
10578                 ny = cent + m3;
10579             }
10580             
10581             str = nm+'/'+nd+'/'+ny;
10582             
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);
10585         
10586         }
10587         
10588         if (match && match.length > 3) {
10589             parsable = h1(parsable, match);
10590         }
10591         
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})$/);
10594         
10595         if (match && match.length > 3) {
10596             parsable = h1(parsable, match);
10597         }
10598                 
10599         
10600         var i = 0;
10601         var length = jsDate.matchers.length;
10602         var pattern,
10603             ms,
10604             current = parsable,
10605             obj;
10606         while (i < length) {
10607             ms = Date.parse(current);
10608             if (!isNaN(ms)) {
10609                 return new Date(ms);
10610             }
10611             pattern = jsDate.matchers[i];
10612             if (typeof pattern == 'function') {
10613                 obj = pattern.call(jsDate, current);
10614                 if (obj instanceof Date) {
10615                     return obj;
10616                 }
10617             } else {
10618                 current = parsable.replace(pattern[0], pattern[1]);
10619             }
10620             i++;
10621         }
10622         return NaN;
10623     };
10624     
10626     /**
10627      * @static
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.
10632     */
10633     //
10634     // handy utility method Borrowed right from Ken Snyder's Date Instance Mehtods.
10635     // 
10636     jsDate.daysInMonth = function(year, month) {
10637         if (month == 2) {
10638             return new Date(year, 1, 29).getDate() == 29 ? 29 : 28;
10639         }
10640         return [undefined,31,undefined,31,30,31,30,31,31,30,31,30,31][month];
10641     };
10644     //
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.
10647     //
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.
10654         function(str) { 
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
10657             if (match) {
10658                 if (match[1]) {
10659                     var d = this.createDate(match[1]);
10660                     if (isNaN(d)) {
10661                         return;
10662                     }
10663                 } else {
10664                     var d = new Date();
10665                     d.setMilliseconds(0);
10666                 }
10667                 var hour = parseFloat(match[2]);
10668                 if (match[6]) {
10669                     hour = match[6].toLowerCase() == 'am' ? (hour == 12 ? 0 : hour) : (hour == 12 ? 12 : hour + 12);
10670                 }
10671                 d.setHours(hour, parseInt(match[3] || 0, 10), parseInt(match[4] || 0, 10), ((parseFloat(match[5] || 0)) || 0)*1000);
10672                 return d;
10673             }
10674             else {
10675                 return str;
10676             }
10677         },
10678         // Handle ISO timestamp with time zone.
10679         function(str) {
10680             var match = str.match(/^(?:(.+))[T|\s+]([012]\d)(?:\:(\d\d))(?:\:(\d\d))(?:\.\d+)([\+\-]\d\d\:\d\d)$/i);
10681             if (match) {
10682                 if (match[1]) {
10683                     var d = this.createDate(match[1]);
10684                     if (isNaN(d)) {
10685                         return;
10686                     }
10687                 } else {
10688                     var d = new Date();
10689                     d.setMilliseconds(0);
10690                 }
10691                 var hour = parseFloat(match[2]);
10692                 d.setHours(hour, parseInt(match[3], 10), parseInt(match[4], 10), parseFloat(match[5])*1000);
10693                 return d;
10694             }
10695             else {
10696                     return str;
10697             }
10698         },
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.
10702         function(str) {
10703             var match = str.match(/^([0-3]?\d)\s*[-\/.\s]{1}\s*([a-zA-Z]{3,9})\s*[-\/.\s]{1}\s*([0-3]?\d)$/);
10704             if (match) {
10705                 var d = new Date();
10706                 var cent = jsDate.config.defaultCentury;
10707                 var m1 = parseFloat(match[1]);
10708                 var m3 = parseFloat(match[3]);
10709                 var ny, nd, nm;
10710                 if (m1 > 31) { // first number is a year
10711                     nd = m3;
10712                     ny = cent + m1;
10713                 }
10714                 
10715                 else { // last number is the year
10716                     nd = m1;
10717                     ny = cent + m3;
10718                 }
10719                 
10720                 var nm = inArray(match[2], jsDate.regional[jsDate.regional.getLocale()]["monthNamesShort"]);
10721                 
10722                 if (nm == -1) {
10723                     nm = inArray(match[2], jsDate.regional[jsDate.regional.getLocale()]["monthNames"]);
10724                 }
10725             
10726                 d.setFullYear(ny, nm, nd);
10727                 d.setHours(0,0,0,0);
10728                 return d;
10729             }
10730             
10731             else {
10732                 return str;
10733             }
10734         }      
10735     ];
10737     //
10738     // I think John Reisig published this method on his blog, ejohn.
10739     //
10740     function inArray( elem, array ) {
10741         if ( array.indexOf ) {
10742             return array.indexOf( elem );
10743         }
10745         for ( var i = 0, length = array.length; i < length; i++ ) {
10746             if ( array[ i ] === elem ) {
10747                 return i;
10748             }
10749         }
10751         return -1;
10752     }
10753     
10754     //
10755     // Thanks to Kangax, Christian Sciberras and Stack Overflow for this method.
10756     //
10757     function get_type(thing){
10758         if(thing===null) return "[object Null]"; // special case
10759         return Object.prototype.toString.call(thing);
10760     }
10761     
10762     $.jsDate = jsDate;
10764       
10765     /**
10766      * JavaScript printf/sprintf functions.
10767      * 
10768      * This code has been adapted from the publicly available sprintf methods
10769      * by Ash Searle. His original header follows:
10770      *
10771      *     This code is unrestricted: you are free to use it however you like.
10772      *     
10773      *     The functions should work as expected, performing left or right alignment,
10774      *     truncating strings, outputting numbers with a required precision etc.
10775      *
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
10779      *     numbers.
10780      *
10781      *     See http://perldoc.perl.org/functions/sprintf.html for more information.
10782      *
10783      *     Implemented:
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
10791      *
10792      *     Not implemented (yet):
10793      *     - vector flag
10794      *     - size (bytes, words, long-words etc.)
10795      *     
10796      *     Will not implement:
10797      *     - %n or %p (no pass-by-reference in JavaScript)
10798      *
10799      *     @version 2007.04.27
10800      *     @author Ash Searle 
10801      * 
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
10805      */
10806      
10807      /**
10808       * @Modifications 2009.05.26
10809       * @author Chris Leonello
10810       * 
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.
10813       * Example:
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
10820       * 
10821       * Example:
10822       * >>> $.jqplot.sprintf('%.2f, %d', 23.3452, 43.23)
10823       * "23.35, 43"
10824       * >>> $.jqplot.sprintf("no value: %n, decimal with thousands separator: %'d", 23.3452, 433524)
10825       * "no value: , decimal with thousands separator: 433,524"
10826       */
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;
10832         }
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;
10838             }
10839             return value_str; 
10840         }
10842         function justify(value, prefix, leftJustify, minWidth, zeroPad, htmlSpace) {
10843             var diff = minWidth - value.length;
10844             if (diff > 0) {
10845                 var spchar = ' ';
10846                 if (htmlSpace) { spchar = '&nbsp;'; }
10847                 if (leftJustify || !zeroPad) {
10848                     value = pad(value, minWidth, spchar, leftJustify);
10849                 } else {
10850                     value = value.slice(0, prefix.length) + pad('', diff, '0', true) + value.slice(prefix.length);
10851                 }
10852             }
10853             return value;
10854         }
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);
10862         }
10864         function formatString(value, leftJustify, minWidth, precision, zeroPad, htmlSpace) {
10865             if (precision != null) {
10866                 value = value.slice(0, precision);
10867             }
10868             return justify(value, '', leftJustify, minWidth, zeroPad, htmlSpace);
10869         }
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 '%'; }
10876             // parse flags
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;
10886             }
10888             // parameters may be null, undefined, empty-string or real valued
10889             // we want to ignore null, undefined and empty-string values
10891             if (!minWidth) {
10892                 minWidth = 0;
10893             } 
10894             else if (minWidth == '*') {
10895                 minWidth = +a[i++];
10896             } 
10897             else if (minWidth.charAt(0) == '*') {
10898                 minWidth = +a[minWidth.slice(1, -1)];
10899             } 
10900             else {
10901                 minWidth = +minWidth;
10902             }
10904             // Note: undocumented perl feature:
10905             if (minWidth < 0) {
10906                 minWidth = -minWidth;
10907                 leftJustify = true;
10908             }
10910             if (!isFinite(minWidth)) {
10911                 throw new Error('$.jqplot.sprintf: (minimum-)width must be finite');
10912             }
10914             if (!precision) {
10915                 precision = 'fFeE'.indexOf(type) > -1 ? 6 : (type == 'd') ? 0 : void(0);
10916             } 
10917             else if (precision == '*') {
10918                 precision = +a[i++];
10919             } 
10920             else if (precision.charAt(0) == '*') {
10921                 precision = +a[precision.slice(1, -1)];
10922             } 
10923             else {
10924                 precision = +precision;
10925             }
10927             // grab value using valueIndex if required?
10928             var value = valueIndex ? a[valueIndex.slice(0, -1)] : a[i++];
10930             switch (type) {
10931             case 's': {
10932                 if (value == null) {
10933                     return '';
10934                 }
10935                 return formatString(String(value), leftJustify, minWidth, precision, zeroPad, htmlSpace);
10936             }
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);
10943             case 'i': {
10944               var number = parseInt(+value, 10);
10945               if (isNaN(number)) {
10946                 return '';
10947               }
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);
10953                   }
10954             case 'd': {
10955               var number = Math.round(+value);
10956               if (isNaN(number)) {
10957                 return '';
10958               }
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);
10963                   }
10964             case 'e':
10965             case 'E':
10966             case 'f':
10967             case 'F':
10968             case 'g':
10969             case 'G':
10970                       {
10971                       var number = +value;
10972                       if (isNaN(number)) {
10973                           return '';
10974                       }
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);
10985                       } else {
10986                           return justified;
10987                       }
10988                   }
10989             case 'p':
10990             case 'P':
10991             {
10992                 // make sure number is a number
10993                 var number = +value;
10994                 if (isNaN(number)) {
10995                     return '';
10996                 }
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;
11002                 
11003                 if (Math.abs(number) < 1) {
11004                     if (sd + zeros  <= precision) {
11005                         value = prefix + Math.abs(number).toPrecision(sd);
11006                     }
11007                     else {
11008                         if (sd  <= precision - 1) {
11009                             value = prefix + Math.abs(number).toExponential(sd-1);
11010                         }
11011                         else {
11012                             value = prefix + Math.abs(number).toExponential(precision-1);
11013                         }
11014                     }
11015                 }
11016                 else {
11017                     var prec = (sd <= precision) ? sd : precision;
11018                     value = prefix + Math.abs(number).toPrecision(prec);
11019                 }
11020                 var textTransform = ['toString', 'toUpperCase']['pP'.indexOf(type) % 2];
11021                 return justify(value, prefix, leftJustify, minWidth, zeroPad, htmlSpace)[textTransform]();
11022             }
11023             case 'n': return '';
11024             default: return substring;
11025             }
11026         });
11027     };
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 = '.';
11035     
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;
11043         // exponent
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} ;
11050     };
11052     $.jqplot.getPrecision = function(number) {
11053         return $.jqplot.getSignificantFigures(number).digitsRight;
11054     };
11056 })(jQuery);  
11059     var backCompat = $.uiBackCompat !== false;
11061     $.jqplot.effects = {
11062         effect: {}
11063     };
11065     // prefix used for storing data on .data()
11066     var dataSpace = "jqplot.storage.";
11068     /******************************************************************************/
11069     /*********************************** EFFECTS **********************************/
11070     /******************************************************************************/
11072     $.extend( $.jqplot.effects, {
11073         version: "1.9pre",
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 ] ] );
11080                 }
11081             }
11082         },
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 ] ) );
11089                 }
11090             }
11091         },
11093         setMode: function( el, mode ) {
11094             if (mode === "toggle") {
11095                 mode = el.is( ":hidden" ) ? "show" : "hide";
11096             }
11097             return mode;
11098         },
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();
11106             }
11108             // wrap the element
11109             var props = {
11110                     width: element.outerWidth(true),
11111                     height: element.outerHeight(true),
11112                     "float": element.css( "float" )
11113                 },
11114                 wrapper = $( "<div></div>" )
11115                     .addClass( "ui-effects-wrapper" )
11116                     .css({
11117                         fontSize: "100%",
11118                         background: "transparent",
11119                         border: "none",
11120                         margin: 0,
11121                         padding: 0
11122                     }),
11123                 // Store the size in case width/height are defined in % - Fixes #5245
11124                 size = {
11125                     width: element.width(),
11126                     height: element.height()
11127                 },
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();
11135             }
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" });
11143             } else {
11144                 $.extend( props, {
11145                     position: element.css( "position" ),
11146                     zIndex: element.css( "z-index" )
11147                 });
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";
11152                     }
11153                 });
11154                 element.css({
11155                     position: "relative",
11156                     top: 0,
11157                     left: 0,
11158                     right: "auto",
11159                     bottom: "auto"
11160                 });
11161             }
11162             element.css(size);
11164             return wrapper.css( props ).show();
11165         },
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();
11176                 }
11177             }
11180             return element;
11181         }
11182     });
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 ) ) {
11189             return effect;
11190         }
11192         // convert to an object
11193         effect = { effect: effect };
11195         // catch (effect)
11196         if ( options === undefined ) {
11197             options = {};
11198         }
11200         // catch (effect, callback)
11201         if ( $.isFunction( options ) ) {
11202             callback = options;
11203             speed = null;
11204             options = {};
11205         }
11207         // catch (effect, speed, ?)
11208         if ( $.type( options ) === "number" || $.fx.speeds[ options ]) {
11209             callback = speed;
11210             speed = options;
11211             options = {};
11212         }
11214         // catch (effect, options, callback)
11215         if ( $.isFunction( speed ) ) {
11216             callback = speed;
11217             speed = null;
11218         }
11220         // add options to effect
11221         if ( options ) {
11222             $.extend( effect, options );
11223         }
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;
11231         return effect;
11232     }
11234     function standardSpeed( speed ) {
11235         // valid standard speeds
11236         if ( !speed || typeof speed === "number" || $.fx.speeds[ speed ] ) {
11237             return true;
11238         }
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 ] ) {
11244                 return false;
11245             }
11246             return true;
11247         }
11249         return false;
11250     }
11252     $.fn.extend({
11253         jqplotEffect: function( effect, options, speed, callback ) {
11254             var args = _normalizeArguments.apply( this, arguments ),
11255                 mode = args.mode,
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
11264                 if ( mode ) {
11265                     return this[ mode ]( args.duration, args.complete );
11266                 } else {
11267                     return this.each( function() {
11268                         if ( args.complete ) {
11269                             args.complete.call( this );
11270                         }
11271                     });
11272                 }
11273             }
11275             function run( next ) {
11276                 var elem = $( this ),
11277                     complete = args.complete,
11278                     mode = args.mode;
11280                 function done() {
11281                     if ( $.isFunction( complete ) ) {
11282                         complete.call( elem[0] );
11283                     }
11284                     if ( $.isFunction( next ) ) {
11285                         next();
11286                     }
11287                 }
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" ) {
11292                     done();
11293                 } else {
11294                     effectMethod.call( elem[0], args, done );
11295                 }
11296             }
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 );
11301             } else {
11302                 // DEPRECATED: remove in 2.0 (#7115)
11303                 return oldEffectMethod.call(this, {
11304                     options: args,
11305                     duration: args.duration,
11306                     callback: args.complete,
11307                     mode: args.mode
11308                 });
11309             }
11310         }
11311     });
11316     var rvertical = /up|down|vertical/,
11317         rpositivemotion = /up|left|vertical|horizontal/;
11319     $.jqplot.effects.effect.blind = function( o, done ) {
11320         // Create element
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 ),
11329             animation = {},
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 );
11336         } else {
11337             $.jqplot.effects.save( el, props );
11338         }
11339         el.show();
11340         top = parseInt(el.css('top'), 10);
11341         wrapper = $.jqplot.effects.createWrapper( el ).css({
11342             overflow: "hidden"
11343         });
11345         distance = vertical ? wrapper[ ref ]() + top : wrapper[ ref ]();
11347         animation[ ref ] = show ? String(distance) : '0';
11348         if ( !motion ) {
11349             el
11350                 .css( vertical ? "bottom" : "right", 0 )
11351                 .css( vertical ? "top" : "left", "" )
11352                 .css({ position: "absolute" });
11353             animation[ ref2 ] = show ? '0' : String(distance);
11354         }
11356         // // start at 0 if we are showing
11357         if ( show ) {
11358             wrapper.css( ref, 0 );
11359             if ( ! motion ) {
11360                 wrapper.css( ref2, distance );
11361             }
11362         }
11364         // // Animate
11365         wrapper.animate( animation, {
11366             duration: o.duration,
11367             easing: o.easing,
11368             queue: false,
11369             complete: function() {
11370                 if ( mode === "hide" ) {
11371                     el.hide();
11372                 }
11373                 $.jqplot.effects.restore( el, props );
11374                 $.jqplot.effects.removeWrapper( el );
11375                 done();
11376             }
11377         });
11379     };