/**
* Title: jqPlot Charts
*
* Pure JavaScript plotting plugin for jQuery.
*
* About: Version
*
* 1.0.0a_r701
*
* About: Copyright & License
*
* Copyright (c) 2009-2011 Chris Leonello
* jqPlot is currently available for use in all personal or commercial projects
* under both the MIT and GPL version 2.0 licenses. This means that you can
* choose the license that best suits your project and use it accordingly.
*
* See and contained within this distribution for further information.
*
* The author would appreciate an email letting him know of any substantial
* use of jqPlot. You can reach the author at: chris at jqplot dot com
* or see http://www.jqplot.com/info.php. This is, of course, not required.
*
* If you are feeling kind and generous, consider supporting the project by
* making a donation at: http://www.jqplot.com/donate.php.
*
* sprintf functions contained in jqplot.sprintf.js by Ash Searle:
*
* version 2007.04.27
* author Ash Searle
* http://hexmen.com/blog/2007/03/printf-sprintf/
* http://hexmen.com/js/sprintf.js
* The author (Ash Searle) has placed this code in the public domain:
* "This code is unrestricted: you are free to use it however you like."
*
*
* About: Introduction
*
* jqPlot requires jQuery (1.4+ required for certain features). jQuery 1.4.2 is included in the distribution.
* To use jqPlot include jQuery, the jqPlot jQuery plugin, the jqPlot css file and optionally
* the excanvas script for IE support in your web page:
*
* >
* >
* >
* >
*
* jqPlot can be customized by overriding the defaults of any of the objects which make
* up the plot. The general usage of jqplot is:
*
* > chart = $.jqplot('targetElemId', [dataArray,...], {optionsObject});
*
* The options available to jqplot are detailed in in the jqPlotOptions.txt file.
*
* An actual call to $.jqplot() may look like the
* examples below:
*
* > chart = $.jqplot('chartdiv', [[[1, 2],[3,5.12],[5,13.1],[7,33.6],[9,85.9],[11,219.9]]]);
*
* or
*
* > dataArray = [34,12,43,55,77];
* > chart = $.jqplot('targetElemId', [dataArray, ...], {title:'My Plot', axes:{yaxis:{min:20, max:100}}});
*
* For more inforrmation, see .
*
* About: Usage
*
* See
*
* About: Available Options
*
* See for a list of options available thorugh the options object (not complete yet!)
*
* About: Options Usage
*
* See
*
* About: Changes
*
* See
*
*/
(function($) {
// make sure undefined is undefined
var undefined;
/**
* Class: $.jqplot
* jQuery function called by the user to create a plot.
*
* Parameters:
* target - ID of target element to render the plot into.
* data - an array of data series.
* options - user defined options object. See the individual classes for available options.
*
* Properties:
* config - object to hold configuration information for jqPlot plot object.
*
* attributes:
* enablePlugins - False to disable plugins by default. Plugins must then be explicitly
* enabled in the individual plot options. Default: false.
* This property sets the "show" property of certain plugins to true or false.
* Only plugins that can be immediately active upon loading are affected. This includes
* non-renderer plugins like cursor, dragable, highlighter, and trendline.
* defaultHeight - Default height for plots where no css height specification exists. This
* is a jqplot wide default.
* defaultWidth - Default height for plots where no css height specification exists. This
* is a jqplot wide default.
*/
$.jqplot = function(target, data, options) {
var _data, _options;
if (options == null) {
if (jQuery.isArray(data)) {
_data = data;
_options = null;
}
else if (typeof(data) === 'object') {
_data = null;
_options = data;
}
}
else {
_data = data;
_options = options;
}
var plot = new jqPlot();
// remove any error class that may be stuck on target.
$('#'+target).removeClass('jqplot-error');
if ($.jqplot.config.catchErrors) {
try {
plot.init(target, _data, _options);
plot.draw();
plot.themeEngine.init.call(plot);
return plot;
}
catch(e) {
var msg = $.jqplot.config.errorMessage || e.message;
$('#'+target).append('
');
for (var s in this._styles) {
this._elem.css(s, this._styles[s]);
}
if (this.fontFamily) {
this._elem.css('font-family', this.fontFamily);
}
if (this.fontSize) {
this._elem.css('font-size', this.fontSize);
}
if (this.textColor) {
this._elem.css('color', this.textColor);
}
if (this._breakTick) {
this._elem.addClass('jqplot-breakTick');
}
return this._elem;
};
$.jqplot.DefaultTickFormatter = function (format, val) {
if (typeof val == 'number') {
if (!format) {
format = $.jqplot.config.defaultTickFormatString;
}
return $.jqplot.sprintf(format, val);
}
else {
return String(val);
}
};
$.jqplot.AxisTickRenderer.prototype.pack = function() {
};
// Class: $.jqplot.CanvasGridRenderer
// The default jqPlot grid renderer, creating a grid on a canvas element.
// The renderer has no additional options beyond the class.
$.jqplot.CanvasGridRenderer = function(){
this.shadowRenderer = new $.jqplot.ShadowRenderer();
};
// called with context of Grid object
$.jqplot.CanvasGridRenderer.prototype.init = function(options) {
this._ctx;
$.extend(true, this, options);
// set the shadow renderer options
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};
this.renderer.shadowRenderer.init(sopts);
};
// called with context of Grid.
$.jqplot.CanvasGridRenderer.prototype.createElement = function() {
var elem = document.createElement('canvas');
var w = this._plotDimensions.width;
var h = this._plotDimensions.height;
elem.width = w;
elem.height = h;
this._elem = $(elem);
this._elem.addClass('jqplot-grid-canvas');
this._elem.css({ position: 'absolute', left: 0, top: 0 });
if ($.jqplot.use_excanvas) {
window.G_vmlCanvasManager.init_(document);
}
if ($.jqplot.use_excanvas) {
elem = window.G_vmlCanvasManager.initElement(elem);
}
this._top = this._offsets.top;
this._bottom = h - this._offsets.bottom;
this._left = this._offsets.left;
this._right = w - this._offsets.right;
this._width = this._right - this._left;
this._height = this._bottom - this._top;
// avoid memory leak
elem = null;
return this._elem;
};
$.jqplot.CanvasGridRenderer.prototype.draw = function() {
this._ctx = this._elem.get(0).getContext("2d");
var ctx = this._ctx;
var axes = this._axes;
// Add the grid onto the grid canvas. This is the bottom most layer.
ctx.save();
ctx.clearRect(0, 0, this._plotDimensions.width, this._plotDimensions.height);
ctx.fillStyle = this.backgroundColor || this.background;
ctx.fillRect(this._left, this._top, this._width, this._height);
if (true) {
ctx.save();
ctx.lineJoin = 'miter';
ctx.lineCap = 'butt';
ctx.lineWidth = this.gridLineWidth;
ctx.strokeStyle = this.gridLineColor;
var b, e;
var ax = ['xaxis', 'yaxis', 'x2axis', 'y2axis'];
for (var i=4; i>0; i--) {
var name = ax[i-1];
var axis = axes[name];
var ticks = axis._ticks;
if (axis.show) {
for (var j=ticks.length; j>0; j--) {
var t = ticks[j-1];
if (t.show) {
var pos = Math.round(axis.u2p(t.value)) + 0.5;
switch (name) {
case 'xaxis':
// draw the grid line
if (t.showGridline && this.drawGridlines) {
drawLine(pos, this._top, pos, this._bottom);
}
// draw the mark
if (t.showMark && t.mark) {
s = t.markSize;
m = t.mark;
var pos = Math.round(axis.u2p(t.value)) + 0.5;
switch (m) {
case 'outside':
b = this._bottom;
e = this._bottom+s;
break;
case 'inside':
b = this._bottom-s;
e = this._bottom;
break;
case 'cross':
b = this._bottom-s;
e = this._bottom+s;
break;
default:
b = this._bottom;
e = this._bottom+s;
break;
}
// draw the shadow
if (this.shadow) {
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});
}
// draw the line
drawLine(pos, b, pos, e);
}
break;
case 'yaxis':
// draw the grid line
if (t.showGridline && this.drawGridlines) {
drawLine(this._right, pos, this._left, pos);
}
// draw the mark
if (t.showMark && t.mark) {
s = t.markSize;
m = t.mark;
var pos = Math.round(axis.u2p(t.value)) + 0.5;
switch (m) {
case 'outside':
b = this._left-s;
e = this._left;
break;
case 'inside':
b = this._left;
e = this._left+s;
break;
case 'cross':
b = this._left-s;
e = this._left+s;
break;
default:
b = this._left-s;
e = this._left;
break;
}
// draw the shadow
if (this.shadow) {
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});
}
drawLine(b, pos, e, pos, {strokeStyle:axis.borderColor});
}
break;
case 'x2axis':
// draw the grid line
if (t.showGridline && this.drawGridlines) {
drawLine(pos, this._bottom, pos, this._top);
}
// draw the mark
if (t.showMark && t.mark) {
s = t.markSize;
m = t.mark;
var pos = Math.round(axis.u2p(t.value)) + 0.5;
switch (m) {
case 'outside':
b = this._top-s;
e = this._top;
break;
case 'inside':
b = this._top;
e = this._top+s;
break;
case 'cross':
b = this._top-s;
e = this._top+s;
break;
default:
b = this._top-s;
e = this._top;
break;
}
// draw the shadow
if (this.shadow) {
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});
}
drawLine(pos, b, pos, e);
}
break;
case 'y2axis':
// draw the grid line
if (t.showGridline && this.drawGridlines) {
drawLine(this._left, pos, this._right, pos);
}
// draw the mark
if (t.showMark && t.mark) {
s = t.markSize;
m = t.mark;
var pos = Math.round(axis.u2p(t.value)) + 0.5;
switch (m) {
case 'outside':
b = this._right;
e = this._right+s;
break;
case 'inside':
b = this._right-s;
e = this._right;
break;
case 'cross':
b = this._right-s;
e = this._right+s;
break;
default:
b = this._right;
e = this._right+s;
break;
}
// draw the shadow
if (this.shadow) {
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});
}
drawLine(b, pos, e, pos, {strokeStyle:axis.borderColor});
}
break;
default:
break;
}
}
}
t = null;
}
axis = null;
ticks = null;
}
// Now draw grid lines for additional y axes
ax = ['y3axis', 'y4axis', 'y5axis', 'y6axis', 'y7axis', 'y8axis', 'y9axis'];
for (var i=7; i>0; i--) {
var axis = axes[ax[i-1]];
var ticks = axis._ticks;
if (axis.show) {
var tn = ticks[axis.numberTicks-1];
var t0 = ticks[0];
var left = axis.getLeft();
var points = [[left, tn.getTop() + tn.getHeight()/2], [left, t0.getTop() + t0.getHeight()/2 + 1.0]];
// draw the shadow
if (this.shadow) {
this.renderer.shadowRenderer.draw(ctx, points, {lineCap:'butt', fill:false, closePath:false});
}
// draw the line
drawLine(points[0][0], points[0][1], points[1][0], points[1][1], {lineCap:'butt', strokeStyle:axis.borderColor, lineWidth:axis.borderWidth});
// draw the tick marks
for (var j=ticks.length; j>0; j--) {
var t = ticks[j-1];
s = t.markSize;
m = t.mark;
var pos = Math.round(axis.u2p(t.value)) + 0.5;
if (t.showMark && t.mark) {
switch (m) {
case 'outside':
b = left;
e = left+s;
break;
case 'inside':
b = left-s;
e = left;
break;
case 'cross':
b = left-s;
e = left+s;
break;
default:
b = left;
e = left+s;
break;
}
points = [[b,pos], [e,pos]];
// draw the shadow
if (this.shadow) {
this.renderer.shadowRenderer.draw(ctx, points, {lineCap:'butt', lineWidth:this.gridLineWidth*1.5, offset:this.gridLineWidth*0.75, fill:false, closePath:false});
}
// draw the line
drawLine(b, pos, e, pos, {strokeStyle:axis.borderColor});
}
t = null;
}
t0 = null;
}
axis = null;
ticks = null;
}
ctx.restore();
}
function drawLine(bx, by, ex, ey, opts) {
ctx.save();
opts = opts || {};
if (opts.lineWidth == null || opts.lineWidth != 0){
$.extend(true, ctx, opts);
ctx.beginPath();
ctx.moveTo(bx, by);
ctx.lineTo(ex, ey);
ctx.stroke();
ctx.restore();
}
}
if (this.shadow) {
var points = [[this._left, this._bottom], [this._right, this._bottom], [this._right, this._top]];
this.renderer.shadowRenderer.draw(ctx, points);
}
// Now draw border around grid. Use axis border definitions. start at
// upper left and go clockwise.
if (this.borderWidth != 0 && this.drawBorder) {
drawLine (this._left, this._top, this._right, this._top, {lineCap:'round', strokeStyle:axes.x2axis.borderColor, lineWidth:axes.x2axis.borderWidth});
drawLine (this._right, this._top, this._right, this._bottom, {lineCap:'round', strokeStyle:axes.y2axis.borderColor, lineWidth:axes.y2axis.borderWidth});
drawLine (this._right, this._bottom, this._left, this._bottom, {lineCap:'round', strokeStyle:axes.xaxis.borderColor, lineWidth:axes.xaxis.borderWidth});
drawLine (this._left, this._bottom, this._left, this._top, {lineCap:'round', strokeStyle:axes.yaxis.borderColor, lineWidth:axes.yaxis.borderWidth});
}
// ctx.lineWidth = this.borderWidth;
// ctx.strokeStyle = this.borderColor;
// ctx.strokeRect(this._left, this._top, this._width, this._height);
ctx.restore();
ctx = null;
axes = null;
};
// Class: $.jqplot.DivTitleRenderer
// The default title renderer for jqPlot. This class has no options beyond the class.
$.jqplot.DivTitleRenderer = function() {
};
$.jqplot.DivTitleRenderer.prototype.init = function(options) {
$.extend(true, this, options);
};
$.jqplot.DivTitleRenderer.prototype.draw = function() {
var r = this.renderer;
if (!this.text) {
this.show = false;
this._elem = $('');
}
else if (this.text) {
var color;
if (this.color) {
color = this.color;
}
else if (this.textColor) {
color = this.textColor;
}
// don't trust that a stylesheet is present, set the position.
var styletext = 'position:absolute;top:0px;left:0px;';
styletext += (this._plotWidth) ? 'width:'+this._plotWidth+'px;' : '';
styletext += (this.fontSize) ? 'font-size:'+this.fontSize+';' : '';
styletext += (this.textAlign) ? 'text-align:'+this.textAlign+';' : 'text-align:center;';
styletext += (color) ? 'color:'+color+';' : '';
styletext += (this.paddingBottom) ? 'padding-bottom:'+this.paddingBottom+';' : '';
this._elem = $('
'+this.text+'
');
if (this.fontFamily) {
this._elem.css('font-family', this.fontFamily);
}
}
return this._elem;
};
$.jqplot.DivTitleRenderer.prototype.pack = function() {
// nothing to do here
};
// Class: $.jqplot.LineRenderer
// The default line renderer for jqPlot, this class has no options beyond the class.
// Draws series as a line.
$.jqplot.LineRenderer = function(){
this.shapeRenderer = new $.jqplot.ShapeRenderer();
this.shadowRenderer = new $.jqplot.ShadowRenderer();
};
// called with scope of series.
$.jqplot.LineRenderer.prototype.init = function(options, plot) {
options = options || {};
var lopts = {highlightMouseOver: options.highlightMouseOver, highlightMouseDown: options.highlightMouseDown, highlightColor: options.highlightColor};
delete (options.highlightMouseOver);
delete (options.highlightMouseDown);
delete (options.highlightColor);
$.extend(true, this.renderer, options);
// set the shape renderer options
var opts = {lineJoin:'round', lineCap:'round', fill:this.fill, isarc:false, strokeStyle:this.color, fillStyle:this.fillColor, lineWidth:this.lineWidth, closePath:this.fill};
this.renderer.shapeRenderer.init(opts);
// set the shadow renderer options
// scale the shadowOffset to the width of the line.
if (this.lineWidth > 2.5) {
var shadow_offset = this.shadowOffset* (1 + (Math.atan((this.lineWidth/2.5))/0.785398163 - 1)*0.6);
// var shadow_offset = this.shadowOffset;
}
// for skinny lines, don't make such a big shadow.
else {
var shadow_offset = this.shadowOffset*Math.atan((this.lineWidth/2.5))/0.785398163;
}
var sopts = {lineJoin:'round', lineCap:'round', fill:this.fill, isarc:false, angle:this.shadowAngle, offset:shadow_offset, alpha:this.shadowAlpha, depth:this.shadowDepth, lineWidth:this.lineWidth, closePath:this.fill};
this.renderer.shadowRenderer.init(sopts);
this._areaPoints = [];
this._boundingBox = [[],[]];
if (!this.isTrendline && this.fill) {
// prop: highlightMouseOver
// True to highlight area on a filled plot when moused over.
// This must be false to enable highlightMouseDown to highlight when clicking on an area on a filled plot.
this.highlightMouseOver = true;
// prop: highlightMouseDown
// True to highlight when a mouse button is pressed over an area on a filled plot.
// This will be disabled if highlightMouseOver is true.
this.highlightMouseDown = false;
// prop: highlightColor
// color to use when highlighting an area on a filled plot.
this.highlightColor = null;
// if user has passed in highlightMouseDown option and not set highlightMouseOver, disable highlightMouseOver
if (lopts.highlightMouseDown && lopts.highlightMouseOver == null) {
lopts.highlightMouseOver = false;
}
$.extend(true, this, {highlightMouseOver: lopts.highlightMouseOver, highlightMouseDown: lopts.highlightMouseDown, highlightColor: lopts.highlightColor});
if (!this.highlightColor) {
this.highlightColor = $.jqplot.computeHighlightColors(this.fillColor);
}
// turn off (disable) the highlighter plugin
if (this.highlighter) {
this.highlighter.show = false;
}
}
if (!this.isTrendline && plot) {
plot.plugins.lineRenderer = {};
plot.postInitHooks.addOnce(postInit);
plot.postDrawHooks.addOnce(postPlotDraw);
plot.eventListenerHooks.addOnce('jqplotMouseMove', handleMove);
plot.eventListenerHooks.addOnce('jqplotMouseDown', handleMouseDown);
plot.eventListenerHooks.addOnce('jqplotMouseUp', handleMouseUp);
plot.eventListenerHooks.addOnce('jqplotClick', handleClick);
plot.eventListenerHooks.addOnce('jqplotRightClick', handleRightClick);
}
};
// Method: setGridData
// converts the user data values to grid coordinates and stores them
// in the gridData array.
// Called with scope of a series.
$.jqplot.LineRenderer.prototype.setGridData = function(plot) {
// recalculate the grid data
var xp = this._xaxis.series_u2p;
var yp = this._yaxis.series_u2p;
var data = this._plotData;
var pdata = this._prevPlotData;
this.gridData = [];
this._prevGridData = [];
for (var i=0; i0; i--) {
gd.push(prev[i-1]);
// this._areaPoints.push(prev[i-1]);
}
if (shadow) {
this.renderer.shadowRenderer.draw(ctx, gd, opts);
}
this._areaPoints = gd;
this.renderer.shapeRenderer.draw(ctx, gd, opts);
}
}
/////////////////////////
// Not filled to zero
////////////////////////
else {
// if stoking line as well as filling, get a copy of line data.
if (fillAndStroke) {
var fasgd = gd.slice(0);
}
// if not stacked, fill down to axis
if (this.index == 0 || !this._stack) {
// var gridymin = this._yaxis.series_u2p(this._yaxis.min) - this.gridBorderWidth / 2;
var gridymin = ctx.canvas.height;
// IE doesn't return new length on unshift
gd.unshift([gd[0][0], gridymin]);
len = gd.length;
gd.push([gd[len - 1][0], gridymin]);
}
// if stacked, fill to line below
else {
var prev = this._prevGridData;
for (var i=prev.length; i>0; i--) {
gd.push(prev[i-1]);
}
}
this._areaPoints = gd;
if (shadow) {
this.renderer.shadowRenderer.draw(ctx, gd, opts);
}
this.renderer.shapeRenderer.draw(ctx, gd, opts);
}
if (fillAndStroke) {
var fasopts = $.extend(true, {}, opts, {fill:false, closePath:false});
this.renderer.shapeRenderer.draw(ctx, fasgd, fasopts);
//////////
// TODO: figure out some way to do shadows nicely
// if (shadow) {
// this.renderer.shadowRenderer.draw(ctx, fasgd, fasopts);
// }
// now draw the markers
if (this.markerRenderer.show) {
for (i=0; i p[0] || xmin == null) {
xmin = p[0];
}
if (ymax < p[1] || ymax == null) {
ymax = p[1];
}
if (xmax < p[0] || xmax == null) {
xmax = p[0];
}
if (ymin > p[1] || ymin == null) {
ymin = p[1];
}
}
this._boundingBox = [[xmin, ymax], [xmax, ymin]];
// now draw the markers
if (this.markerRenderer.show && !fill) {
for (i=0; i object.
$.jqplot.LinearAxisRenderer = function() {
};
// called with scope of axis object.
$.jqplot.LinearAxisRenderer.prototype.init = function(options){
// prop: breakPoints
// EXPERIMENTAL!! Use at your own risk!
// Works only with linear axes and the default tick renderer.
// Array of [start, stop] points to create a broken axis.
// Broken axes have a "jump" in them, which is an immediate
// transition from a smaller value to a larger value.
// Currently, axis ticks MUST be manually assigned if using breakPoints
// by using the axis ticks array option.
this.breakPoints = null;
// prop: breakTickLabel
// Label to use at the axis break if breakPoints are specified.
this.breakTickLabel = "≈";
$.extend(true, this, options);
if (this.breakPoints) {
if (!$.isArray(this.breakPoints)) {
this.breakPoints = null;
}
else if (this.breakPoints.length < 2 || this.breakPoints[1] <= this.breakPoints[0]) {
this.breakPoints = null;
}
}
this.resetDataBounds();
};
// called with scope of axis
$.jqplot.LinearAxisRenderer.prototype.draw = function(ctx) {
if (this.show) {
// populate the axis label and value properties.
// createTicks is a method on the renderer, but
// call it within the scope of the axis.
this.renderer.createTicks.call(this);
// fill a div with axes labels in the right direction.
// Need to pregenerate each axis to get it's bounds and
// position it and the labels correctly on the plot.
var dim=0;
var temp;
// Added for theming.
if (this._elem) {
this._elem.empty();
}
this._elem = $('');
if (this.name == 'xaxis' || this.name == 'x2axis') {
this._elem.width(this._plotDimensions.width);
}
else {
this._elem.height(this._plotDimensions.height);
}
// create a _label object.
this.labelOptions.axis = this.name;
this._label = new this.labelRenderer(this.labelOptions);
var elem;
if (this._label.show) {
elem = this._label.draw(ctx);
elem.appendTo(this._elem);
}
var t = this._ticks;
for (var i=0; i dim) {
dim = temp;
}
}
}
if (lshow) {
w = this._label._elem.outerWidth(true);
h = this._label._elem.outerHeight(true);
}
if (this.name == 'xaxis') {
dim = dim + h;
this._elem.css({'height':dim+'px', left:'0px', bottom:'0px'});
}
else if (this.name == 'x2axis') {
dim = dim + h;
this._elem.css({'height':dim+'px', left:'0px', top:'0px'});
}
else if (this.name == 'yaxis') {
dim = dim + w;
this._elem.css({'width':dim+'px', left:'0px', top:'0px'});
if (lshow && this._label.constructor == $.jqplot.AxisLabelRenderer) {
this._label._elem.css('width', w+'px');
}
}
else {
dim = dim + w;
this._elem.css({'width':dim+'px', right:'0px', top:'0px'});
if (lshow && this._label.constructor == $.jqplot.AxisLabelRenderer) {
this._label._elem.css('width', w+'px');
}
}
}
};
// called with scope of axis
$.jqplot.LinearAxisRenderer.prototype.createTicks = function() {
// we're are operating on an axis here
var ticks = this._ticks;
var userTicks = this.ticks;
var name = this.name;
// databounds were set on axis initialization.
var db = this._dataBounds;
var dim, interval;
var min, max;
var pos1, pos2;
var tt, i;
// get a copy of user's settings for min/max.
var userMin = this.min;
var userMax = this.max;
var userNT = this.numberTicks;
var userTI = this.tickInterval;
// if we already have ticks, use them.
// ticks must be in order of increasing value.
if (userTicks.length) {
// ticks could be 1D or 2D array of [val, val, ,,,] or [[val, label], [val, label], ...] or mixed
for (i=0; i this.breakPoints[0] && ut[0] <= this.breakPoints[1]) {
t.show = false;
t.showGridline = false;
t.label = ut[1];
}
else {
t.label = ut[1];
}
}
else {
t.label = ut[1];
}
t.setTick(ut[0], this.name);
this._ticks.push(t);
}
else {
t.value = ut;
if (this.breakPoints) {
if (ut == this.breakPoints[0]) {
t.label = this.breakTickLabel;
t._breakTick = true;
t.showGridline = false;
t.showMark = false;
}
else if (ut > this.breakPoints[0] && ut <= this.breakPoints[1]) {
t.show = false;
t.showGridline = false;
}
}
t.setTick(ut, this.name);
this._ticks.push(t);
}
}
this.numberTicks = userTicks.length;
this.min = this._ticks[0].value;
this.max = this._ticks[this.numberTicks-1].value;
this.tickInterval = (this.max - this.min) / (this.numberTicks - 1);
}
// we don't have any ticks yet, let's make some!
else {
if (name == 'xaxis' || name == 'x2axis') {
dim = this._plotDimensions.width;
}
else {
dim = this._plotDimensions.height;
}
// if min, max and number of ticks specified, user can't specify interval.
if (!this.autoscale && this.min != null && this.max != null && this.numberTicks != null) {
this.tickInterval = null;
}
// if max, min, and interval specified and interval won't fit, ignore interval.
// if (this.min != null && this.max != null && this.tickInterval != null) {
// if (parseInt((this.max-this.min)/this.tickInterval, 10) != (this.max-this.min)/this.tickInterval) {
// this.tickInterval = null;
// }
// }
min = ((this.min != null) ? this.min : db.min);
max = ((this.max != null) ? this.max : db.max);
// if min and max are same, space them out a bit
if (min == max) {
var adj = 0.05;
if (min > 0) {
adj = Math.max(Math.log(min)/Math.LN10, 0.05);
}
min -= adj;
max += adj;
}
var range = max - min;
var rmin, rmax;
var temp;
// autoscale. Can't autoscale if min or max is supplied.
// Will use numberTicks and tickInterval if supplied. Ticks
// across multiple axes may not line up depending on how
// bars are to be plotted.
if (this.autoscale && this.min == null && this.max == null) {
var rrange, ti, margin;
var forceMinZero = false;
var forceZeroLine = false;
var intervals = {min:null, max:null, average:null, stddev:null};
// if any series are bars, or if any are fill to zero, and if this
// is the axis to fill toward, check to see if we can start axis at zero.
for (var i=0; i vmax) {
vmax = vals[j];
}
}
var dp = (vmax - vmin) / vmax;
// is this sries a bar?
if (s.renderer.constructor == $.jqplot.BarRenderer) {
// if no negative values and could also check range.
if (vmin >= 0 && (s.fillToZero || dp > 0.1)) {
forceMinZero = true;
}
else {
forceMinZero = false;
if (s.fill && s.fillToZero && vmin < 0 && vmax > 0) {
forceZeroLine = true;
}
else {
forceZeroLine = false;
}
}
}
// if not a bar and filling, use appropriate method.
else if (s.fill) {
if (vmin >= 0 && (s.fillToZero || dp > 0.1)) {
forceMinZero = true;
}
else if (vmin < 0 && vmax > 0 && s.fillToZero) {
forceMinZero = false;
forceZeroLine = true;
}
else {
forceMinZero = false;
forceZeroLine = false;
}
}
// if not a bar and not filling, only change existing state
// if it doesn't make sense
else if (vmin < 0) {
forceMinZero = false;
}
}
}
// check if we need make axis min at 0.
if (forceMinZero) {
// compute number of ticks
this.numberTicks = 2 + Math.ceil((dim-(this.tickSpacing-1))/this.tickSpacing);
this.min = 0;
userMin = 0;
// what order is this range?
// what tick interval does that give us?
ti = max/(this.numberTicks-1);
temp = Math.pow(10, Math.abs(Math.floor(Math.log(ti)/Math.LN10)));
if (ti/temp == parseInt(ti/temp, 10)) {
ti += temp;
}
this.tickInterval = Math.ceil(ti/temp) * temp;
this.max = this.tickInterval * (this.numberTicks - 1);
}
// check if we need to make sure there is a tick at 0.
else if (forceZeroLine) {
// compute number of ticks
this.numberTicks = 2 + Math.ceil((dim-(this.tickSpacing-1))/this.tickSpacing);
var ntmin = Math.ceil(Math.abs(min)/range*(this.numberTicks-1));
var ntmax = this.numberTicks - 1 - ntmin;
ti = Math.max(Math.abs(min/ntmin), Math.abs(max/ntmax));
temp = Math.pow(10, Math.abs(Math.floor(Math.log(ti)/Math.LN10)));
this.tickInterval = Math.ceil(ti/temp) * temp;
this.max = this.tickInterval * ntmax;
this.min = -this.tickInterval * ntmin;
}
// if nothing else, do autoscaling which will try to line up ticks across axes.
else {
if (this.numberTicks == null){
if (this.tickInterval) {
this.numberTicks = 3 + Math.ceil(range / this.tickInterval);
}
else {
this.numberTicks = 2 + Math.ceil((dim-(this.tickSpacing-1))/this.tickSpacing);
}
}
if (this.tickInterval == null) {
// get a tick interval
ti = range/(this.numberTicks - 1);
if (ti < 1) {
temp = Math.pow(10, Math.abs(Math.floor(Math.log(ti)/Math.LN10)));
}
else {
temp = 1;
}
this.tickInterval = Math.ceil(ti*temp*this.pad)/temp;
}
else {
temp = 1 / this.tickInterval;
}
// try to compute a nicer, more even tick interval
// temp = Math.pow(10, Math.floor(Math.log(ti)/Math.LN10));
// this.tickInterval = Math.ceil(ti/temp) * temp;
rrange = this.tickInterval * (this.numberTicks - 1);
margin = (rrange - range)/2;
if (this.min == null) {
this.min = Math.floor(temp*(min-margin))/temp;
}
if (this.max == null) {
this.max = this.min + rrange;
}
}
}
// Use the default algorithm which pads each axis to make the chart
// centered nicely on the grid.
else {
rmin = (this.min != null) ? this.min : min - range*(this.padMin - 1);
rmax = (this.max != null) ? this.max : max + range*(this.padMax - 1);
this.min = rmin;
this.max = rmax;
range = this.max - this.min;
if (this.numberTicks == null){
// if tickInterval is specified by user, we will ignore computed maximum.
// max will be equal or greater to fit even # of ticks.
if (this.tickInterval != null) {
this.numberTicks = Math.ceil((this.max - this.min)/this.tickInterval)+1;
this.max = this.min + this.tickInterval*(this.numberTicks-1);
}
else if (dim > 100) {
this.numberTicks = parseInt(3+(dim-100)/75, 10);
}
else {
this.numberTicks = 2;
}
}
if (this.tickInterval == null) {
this.tickInterval = range / (this.numberTicks-1);
}
}
if (this.renderer.constructor == $.jqplot.LinearAxisRenderer) {
// fix for misleading tick display with small range and low precision.
range = this.max - this.min;
// figure out precision
var temptick = new this.tickRenderer(this.tickOptions);
// use the tick formatString or, the default.
var fs = temptick.formatString || $.jqplot.config.defaultTickFormatString;
var fs = fs.match($.jqplot.sprintf.regex)[0];
var precision = 0;
if (fs) {
if (fs.search(/[fFeEgGpP]/) > -1) {
var m = fs.match(/\%\.(\d{0,})?[eEfFgGpP]/);
if (m) {
precision = parseInt(m[1], 10);
}
else {
precision = 6;
}
}
else if (fs.search(/[di]/) > -1) {
precision = 0;
}
// fact will be <= 1;
var fact = Math.pow(10, -precision);
if (this.tickInterval < fact) {
// need to correct underrange
if (userNT == null && userTI == null) {
this.tickInterval = fact;
if (userMax == null && userMin == null) {
// this.min = Math.floor((this._dataBounds.min - this.tickInterval)/fact) * fact;
this.min = Math.floor(this._dataBounds.min/fact) * fact;
if (this.min == this._dataBounds.min) {
this.min = this._dataBounds.min - this.tickInterval;
}
// this.max = Math.ceil((this._dataBounds.max + this.tickInterval)/fact) * fact;
this.max = Math.ceil(this._dataBounds.max/fact) * fact;
if (this.max == this._dataBounds.max) {
this.max = this._dataBounds.max + this.tickInterval;
}
var n = (this.max - this.min)/this.tickInterval;
n = n.toFixed(11);
n = Math.ceil(n);
this.numberTicks = n + 1;
}
else if (userMax == null) {
// add one tick for top of range.
var n = (this._dataBounds.max - this.min) / this.tickInterval;
n = n.toFixed(11);
this.numberTicks = Math.ceil(n) + 2;
this.max = this.min + this.tickInterval * (this.numberTicks-1);
}
else if (userMin == null) {
// add one tick for bottom of range.
var n = (this.max - this._dataBounds.min) / this.tickInterval;
n = n.toFixed(11);
this.numberTicks = Math.ceil(n) + 2;
this.min = this.max - this.tickInterval * (this.numberTicks-1);
}
else {
// calculate a number of ticks so max is within axis scale
this.numberTicks = Math.ceil((userMax - userMin)/this.tickInterval) + 1;
// if user's min and max don't fit evenly in ticks, adjust.
// This takes care of cases such as user min set to 0, max set to 3.5 but tick
// format string set to %d (integer ticks)
this.min = Math.floor(userMin*Math.pow(10, precision))/Math.pow(10, precision);
this.max = Math.ceil(userMax*Math.pow(10, precision))/Math.pow(10, precision);
// this.max = this.min + this.tickInterval*(this.numberTicks-1);
this.numberTicks = Math.ceil((this.max - this.min)/this.tickInterval) + 1;
}
}
}
}
}
for (var i=0; i plot.axes.yaxis.renderer.resetTickValues.call(plot.axes.yaxis, yarr);
//
$.jqplot.LinearAxisRenderer.prototype.resetTickValues = function(opts) {
if ($.isArray(opts) && opts.length == this._ticks.length) {
var t;
for (var i=0; i this.breakPoints[0] && u < this.breakPoints[1]){
u = this.breakPoints[0];
}
if (u <= this.breakPoints[0]) {
return (u - min) * pixellength / unitlength + offmin;
}
else {
return (u - this.breakPoints[1] + this.breakPoints[0] - min) * pixellength / unitlength + offmin;
}
};
if (this.name.charAt(0) == 'x'){
this.series_u2p = function(u){
if (u > this.breakPoints[0] && u < this.breakPoints[1]){
u = this.breakPoints[0];
}
if (u <= this.breakPoints[0]) {
return (u - min) * pixellength / unitlength;
}
else {
return (u - this.breakPoints[1] + this.breakPoints[0] - min) * pixellength / unitlength;
}
};
this.series_p2u = function(p){
return p * unitlength / pixellength + min;
};
}
else {
this.series_u2p = function(u){
if (u > this.breakPoints[0] && u < this.breakPoints[1]){
u = this.breakPoints[0];
}
if (u >= this.breakPoints[1]) {
return (u - max) * pixellength / unitlength;
}
else {
return (u + this.breakPoints[1] - this.breakPoints[0] - max) * pixellength / unitlength;
}
};
this.series_p2u = function(p){
return p * unitlength / pixellength + max;
};
}
}
else {
this.p2u = function(p){
return (p - offmin) * unitlength / pixellength + min;
};
this.u2p = function(u){
return (u - min) * pixellength / unitlength + offmin;
};
if (this.name == 'xaxis' || this.name == 'x2axis'){
this.series_u2p = function(u){
return (u - min) * pixellength / unitlength;
};
this.series_p2u = function(p){
return p * unitlength / pixellength + min;
};
}
else {
this.series_u2p = function(u){
return (u - max) * pixellength / unitlength;
};
this.series_p2u = function(p){
return p * unitlength / pixellength + max;
};
}
}
if (this.show) {
if (this.name == 'xaxis' || this.name == 'x2axis') {
for (i=0; i 0) {
shim = -t._textRenderer.height * Math.cos(-t._textRenderer.angle) / 2;
}
else {
shim = -t.getHeight() + t._textRenderer.height * Math.cos(t._textRenderer.angle) / 2;
}
break;
case 'middle':
// if (t.angle > 0) {
// shim = -t.getHeight()/2 + t._textRenderer.height * Math.sin(-t._textRenderer.angle) / 2;
// }
// else {
// shim = -t.getHeight()/2 - t._textRenderer.height * Math.sin(t._textRenderer.angle) / 2;
// }
shim = -t.getHeight()/2;
break;
default:
shim = -t.getHeight()/2;
break;
}
}
else {
shim = -t.getHeight()/2;
}
var val = this.u2p(t.value) + shim + 'px';
t._elem.css('top', val);
t.pack();
}
}
if (lshow) {
var h = this._label._elem.outerHeight(true);
this._label._elem.css('top', offmax - pixellength/2 - h/2 + 'px');
if (this.name == 'yaxis') {
this._label._elem.css('left', '0px');
}
else {
this._label._elem.css('right', '0px');
}
this._label.pack();
}
}
}
};
// class: $.jqplot.MarkerRenderer
// The default jqPlot marker renderer, rendering the points on the line.
$.jqplot.MarkerRenderer = function(options){
// Group: Properties
// prop: show
// wether or not to show the marker.
this.show = true;
// prop: style
// One of diamond, circle, square, x, plus, dash, filledDiamond, filledCircle, filledSquare
this.style = 'filledCircle';
// prop: lineWidth
// size of the line for non-filled markers.
this.lineWidth = 2;
// prop: size
// Size of the marker (diameter or circle, length of edge of square, etc.)
this.size = 9.0;
// prop: color
// color of marker. Will be set to color of series by default on init.
this.color = '#666666';
// prop: shadow
// wether or not to draw a shadow on the line
this.shadow = true;
// prop: shadowAngle
// Shadow angle in degrees
this.shadowAngle = 45;
// prop: shadowOffset
// Shadow offset from line in pixels
this.shadowOffset = 1;
// prop: shadowDepth
// Number of times shadow is stroked, each stroke offset shadowOffset from the last.
this.shadowDepth = 3;
// prop: shadowAlpha
// Alpha channel transparency of shadow. 0 = transparent.
this.shadowAlpha = '0.07';
// prop: shadowRenderer
// Renderer that will draws the shadows on the marker.
this.shadowRenderer = new $.jqplot.ShadowRenderer();
// prop: shapeRenderer
// Renderer that will draw the marker.
this.shapeRenderer = new $.jqplot.ShapeRenderer();
$.extend(true, this, options);
};
$.jqplot.MarkerRenderer.prototype.init = function(options) {
$.extend(true, this, options);
var sdopt = {angle:this.shadowAngle, offset:this.shadowOffset, alpha:this.shadowAlpha, lineWidth:this.lineWidth, depth:this.shadowDepth, closePath:true};
if (this.style.indexOf('filled') != -1) {
sdopt.fill = true;
}
if (this.style.indexOf('ircle') != -1) {
sdopt.isarc = true;
sdopt.closePath = false;
}
this.shadowRenderer.init(sdopt);
var shopt = {fill:false, isarc:false, strokeStyle:this.color, fillStyle:this.color, lineWidth:this.lineWidth, closePath:true};
if (this.style.indexOf('filled') != -1) {
shopt.fill = true;
}
if (this.style.indexOf('ircle') != -1) {
shopt.isarc = true;
shopt.closePath = false;
}
this.shapeRenderer.init(shopt);
};
$.jqplot.MarkerRenderer.prototype.drawDiamond = function(x, y, ctx, fill, options) {
var stretch = 1.2;
var dx = this.size/2/stretch;
var dy = this.size/2*stretch;
var points = [[x-dx, y], [x, y+dy], [x+dx, y], [x, y-dy]];
if (this.shadow) {
this.shadowRenderer.draw(ctx, points);
}
this.shapeRenderer.draw(ctx, points, options);
};
$.jqplot.MarkerRenderer.prototype.drawPlus = function(x, y, ctx, fill, options) {
var stretch = 1.0;
var dx = this.size/2*stretch;
var dy = this.size/2*stretch;
var points1 = [[x, y-dy], [x, y+dy]];
var points2 = [[x+dx, y], [x-dx, y]];
var opts = $.extend(true, {}, this.options, {closePath:false});
if (this.shadow) {
this.shadowRenderer.draw(ctx, points1, {closePath:false});
this.shadowRenderer.draw(ctx, points2, {closePath:false});
}
this.shapeRenderer.draw(ctx, points1, opts);
this.shapeRenderer.draw(ctx, points2, opts);
};
$.jqplot.MarkerRenderer.prototype.drawX = function(x, y, ctx, fill, options) {
var stretch = 1.0;
var dx = this.size/2*stretch;
var dy = this.size/2*stretch;
var opts = $.extend(true, {}, this.options, {closePath:false});
var points1 = [[x-dx, y-dy], [x+dx, y+dy]];
var points2 = [[x-dx, y+dy], [x+dx, y-dy]];
if (this.shadow) {
this.shadowRenderer.draw(ctx, points1, {closePath:false});
this.shadowRenderer.draw(ctx, points2, {closePath:false});
}
this.shapeRenderer.draw(ctx, points1, opts);
this.shapeRenderer.draw(ctx, points2, opts);
};
$.jqplot.MarkerRenderer.prototype.drawDash = function(x, y, ctx, fill, options) {
var stretch = 1.0;
var dx = this.size/2*stretch;
var dy = this.size/2*stretch;
var points = [[x-dx, y], [x+dx, y]];
if (this.shadow) {
this.shadowRenderer.draw(ctx, points);
}
this.shapeRenderer.draw(ctx, points, options);
};
$.jqplot.MarkerRenderer.prototype.drawLine = function(p1, p2, ctx, fill, options) {
var points = [p1, p2];
if (this.shadow) {
this.shadowRenderer.draw(ctx, points);
}
this.shapeRenderer.draw(ctx, points, options);
};
$.jqplot.MarkerRenderer.prototype.drawSquare = function(x, y, ctx, fill, options) {
var stretch = 1.0;
var dx = this.size/2/stretch;
var dy = this.size/2*stretch;
var points = [[x-dx, y-dy], [x-dx, y+dy], [x+dx, y+dy], [x+dx, y-dy]];
if (this.shadow) {
this.shadowRenderer.draw(ctx, points);
}
this.shapeRenderer.draw(ctx, points, options);
};
$.jqplot.MarkerRenderer.prototype.drawCircle = function(x, y, ctx, fill, options) {
var radius = this.size/2;
var end = 2*Math.PI;
var points = [x, y, radius, 0, end, true];
if (this.shadow) {
this.shadowRenderer.draw(ctx, points);
}
this.shapeRenderer.draw(ctx, points, options);
};
$.jqplot.MarkerRenderer.prototype.draw = function(x, y, ctx, options) {
options = options || {};
// hack here b/c shape renderer uses canvas based color style options
// and marker uses css style names.
if (options.show == null || options.show != false) {
if (options.color && !options.fillStyle) {
options.fillStyle = options.color;
}
if (options.color && !options.strokeStyle) {
options.strokeStyle = options.color;
}
switch (this.style) {
case 'diamond':
this.drawDiamond(x,y,ctx, false, options);
break;
case 'filledDiamond':
this.drawDiamond(x,y,ctx, true, options);
break;
case 'circle':
this.drawCircle(x,y,ctx, false, options);
break;
case 'filledCircle':
this.drawCircle(x,y,ctx, true, options);
break;
case 'square':
this.drawSquare(x,y,ctx, false, options);
break;
case 'filledSquare':
this.drawSquare(x,y,ctx, true, options);
break;
case 'x':
this.drawX(x,y,ctx, true, options);
break;
case 'plus':
this.drawPlus(x,y,ctx, true, options);
break;
case 'dash':
this.drawDash(x,y,ctx, true, options);
break;
case 'line':
this.drawLine(x, y, ctx, false, options);
break;
default:
this.drawDiamond(x,y,ctx, false, options);
break;
}
}
};
// class: $.jqplot.shadowRenderer
// The default jqPlot shadow renderer, rendering shadows behind shapes.
$.jqplot.ShadowRenderer = function(options){
// Group: Properties
// prop: angle
// Angle of the shadow in degrees. Measured counter-clockwise from the x axis.
this.angle = 45;
// prop: offset
// Pixel offset at the given shadow angle of each shadow stroke from the last stroke.
this.offset = 1;
// prop: alpha
// alpha transparency of shadow stroke.
this.alpha = 0.07;
// prop: lineWidth
// width of the shadow line stroke.
this.lineWidth = 1.5;
// prop: lineJoin
// How line segments of the shadow are joined.
this.lineJoin = 'miter';
// prop: lineCap
// how ends of the shadow line are rendered.
this.lineCap = 'round';
// prop; closePath
// whether line path segment is closed upon itself.
this.closePath = false;
// prop: fill
// whether to fill the shape.
this.fill = false;
// prop: depth
// how many times the shadow is stroked. Each stroke will be offset by offset at angle degrees.
this.depth = 3;
this.strokeStyle = 'rgba(0,0,0,0.1)';
// prop: isarc
// wether the shadow is an arc or not.
this.isarc = false;
$.extend(true, this, options);
};
$.jqplot.ShadowRenderer.prototype.init = function(options) {
$.extend(true, this, options);
};
// function: draw
// draws an transparent black (i.e. gray) shadow.
//
// ctx - canvas drawing context
// points - array of points or [x, y, radius, start angle (rad), end angle (rad)]
$.jqplot.ShadowRenderer.prototype.draw = function(ctx, points, options) {
ctx.save();
var opts = (options != null) ? options : {};
var fill = (opts.fill != null) ? opts.fill : this.fill;
var closePath = (opts.closePath != null) ? opts.closePath : this.closePath;
var offset = (opts.offset != null) ? opts.offset : this.offset;
var alpha = (opts.alpha != null) ? opts.alpha : this.alpha;
var depth = (opts.depth != null) ? opts.depth : this.depth;
var isarc = (opts.isarc != null) ? opts.isarc : this.isarc;
ctx.lineWidth = (opts.lineWidth != null) ? opts.lineWidth : this.lineWidth;
ctx.lineJoin = (opts.lineJoin != null) ? opts.lineJoin : this.lineJoin;
ctx.lineCap = (opts.lineCap != null) ? opts.lineCap : this.lineCap;
ctx.strokeStyle = opts.strokeStyle || this.strokeStyle || 'rgba(0,0,0,'+alpha+')';
ctx.fillStyle = opts.fillStyle || this.fillStyle || 'rgba(0,0,0,'+alpha+')';
for (var j=0; j').prependTo(this._elem);
}
else{
tr = $('
').appendTo(this._elem);
}
if (this.showSwatches) {
$('
'+
'
'+
'
').appendTo(tr);
}
if (this.showLabels) {
elem = $('
');
elem.appendTo(tr);
if (this.escapeHtml) {
elem.text(label);
}
else {
elem.html(label);
}
}
tr = null;
elem = null;
};
// called with scope of legend
$.jqplot.TableLegendRenderer.prototype.draw = function() {
var legend = this;
if (this.show) {
var series = this._series;
// make a table. one line label per row.
var ss = 'position:absolute;';
ss += (this.background) ? 'background:'+this.background+';' : '';
ss += (this.border) ? 'border:'+this.border+';' : '';
ss += (this.fontSize) ? 'font-size:'+this.fontSize+';' : '';
ss += (this.fontFamily) ? 'font-family:'+this.fontFamily+';' : '';
ss += (this.textColor) ? 'color:'+this.textColor+';' : '';
ss += (this.marginTop != null) ? 'margin-top:'+this.marginTop+';' : '';
ss += (this.marginBottom != null) ? 'margin-bottom:'+this.marginBottom+';' : '';
ss += (this.marginLeft != null) ? 'margin-left:'+this.marginLeft+';' : '';
ss += (this.marginRight != null) ? 'margin-right:'+this.marginRight+';' : '';
this._elem = $('
');
var pad = false,
reverse = false;
for (var i = 0; i< series.length; i++) {
s = series[i];
if (s._stack || s.renderer.constructor == $.jqplot.BezierCurveRenderer){
reverse = true;
}
if (s.show && s.showLabel) {
var lt = this.labels[i] || s.label.toString();
if (lt) {
var color = s.color;
if (reverse && i < series.length - 1){
pad = true;
}
else if (reverse && i == series.length - 1){
pad = false;
}
this.renderer.addrow.call(this, lt, color, pad, reverse);
pad = true;
}
// let plugins add more rows to legend. Used by trend line plugin.
for (var j=0; j<$.jqplot.addLegendRowHooks.length; j++) {
var item = $.jqplot.addLegendRowHooks[j].call(this, s);
if (item) {
this.renderer.addrow.call(this, item.label, item.color, pad);
pad = true;
}
}
lt = null;
}
}
}
return this._elem;
};
$.jqplot.TableLegendRenderer.prototype.pack = function(offsets) {
if (this.show) {
if (this.placement == 'insideGrid') {
switch (this.location) {
case 'nw':
var a = offsets.left;
var b = offsets.top;
this._elem.css('left', a);
this._elem.css('top', b);
break;
case 'n':
var a = (offsets.left + (this._plotDimensions.width - offsets.right))/2 - this.getWidth()/2;
var b = offsets.top;
this._elem.css('left', a);
this._elem.css('top', b);
break;
case 'ne':
var a = offsets.right;
var b = offsets.top;
this._elem.css({right:a, top:b});
break;
case 'e':
var a = offsets.right;
var b = (offsets.top + (this._plotDimensions.height - offsets.bottom))/2 - this.getHeight()/2;
this._elem.css({right:a, top:b});
break;
case 'se':
var a = offsets.right;
var b = offsets.bottom;
this._elem.css({right:a, bottom:b});
break;
case 's':
var a = (offsets.left + (this._plotDimensions.width - offsets.right))/2 - this.getWidth()/2;
var b = offsets.bottom;
this._elem.css({left:a, bottom:b});
break;
case 'sw':
var a = offsets.left;
var b = offsets.bottom;
this._elem.css({left:a, bottom:b});
break;
case 'w':
var a = offsets.left;
var b = (offsets.top + (this._plotDimensions.height - offsets.bottom))/2 - this.getHeight()/2;
this._elem.css({left:a, top:b});
break;
default: // same as 'se'
var a = offsets.right;
var b = offsets.bottom;
this._elem.css({right:a, bottom:b});
break;
}
}
else if (this.placement == 'outside'){
switch (this.location) {
case 'nw':
var a = this._plotDimensions.width - offsets.left;
var b = offsets.top;
this._elem.css('right', a);
this._elem.css('top', b);
break;
case 'n':
var a = (offsets.left + (this._plotDimensions.width - offsets.right))/2 - this.getWidth()/2;
var b = this._plotDimensions.height - offsets.top;
this._elem.css('left', a);
this._elem.css('bottom', b);
break;
case 'ne':
var a = this._plotDimensions.width - offsets.right;
var b = offsets.top;
this._elem.css({left:a, top:b});
break;
case 'e':
var a = this._plotDimensions.width - offsets.right;
var b = (offsets.top + (this._plotDimensions.height - offsets.bottom))/2 - this.getHeight()/2;
this._elem.css({left:a, top:b});
break;
case 'se':
var a = this._plotDimensions.width - offsets.right;
var b = offsets.bottom;
this._elem.css({left:a, bottom:b});
break;
case 's':
var a = (offsets.left + (this._plotDimensions.width - offsets.right))/2 - this.getWidth()/2;
var b = this._plotDimensions.height - offsets.bottom;
this._elem.css({left:a, top:b});
break;
case 'sw':
var a = this._plotDimensions.width - offsets.left;
var b = offsets.bottom;
this._elem.css({right:a, bottom:b});
break;
case 'w':
var a = this._plotDimensions.width - offsets.left;
var b = (offsets.top + (this._plotDimensions.height - offsets.bottom))/2 - this.getHeight()/2;
this._elem.css({right:a, top:b});
break;
default: // same as 'se'
var a = offsets.right;
var b = offsets.bottom;
this._elem.css({right:a, bottom:b});
break;
}
}
else {
switch (this.location) {
case 'nw':
this._elem.css({left:0, top:offsets.top});
break;
case 'n':
var a = (offsets.left + (this._plotDimensions.width - offsets.right))/2 - this.getWidth()/2;
this._elem.css({left: a, top:offsets.top});
break;
case 'ne':
this._elem.css({right:0, top:offsets.top});
break;
case 'e':
var b = (offsets.top + (this._plotDimensions.height - offsets.bottom))/2 - this.getHeight()/2;
this._elem.css({right:offsets.right, top:b});
break;
case 'se':
this._elem.css({right:offsets.right, bottom:offsets.bottom});
break;
case 's':
var a = (offsets.left + (this._plotDimensions.width - offsets.right))/2 - this.getWidth()/2;
this._elem.css({left: a, bottom:offsets.bottom});
break;
case 'sw':
this._elem.css({left:offsets.left, bottom:offsets.bottom});
break;
case 'w':
var b = (offsets.top + (this._plotDimensions.height - offsets.bottom))/2 - this.getHeight()/2;
this._elem.css({left:offsets.left, top:b});
break;
default: // same as 'se'
this._elem.css({right:offsets.right, bottom:offsets.bottom});
break;
}
}
}
};
/**
* Class: $.jqplot.ThemeEngine
* Theme Engine provides a programatic way to change some of the more
* common jqplot styling options such as fonts, colors and grid options.
* A theme engine instance is created with each plot. The theme engine
* manages a collection of themes which can be modified, added to, or
* applied to the plot.
*
* The themeEngine class is not instantiated directly.
* When a plot is initialized, the current plot options are scanned
* an a default theme named "Default" is created. This theme is
* used as the basis for other themes added to the theme engine and
* is always available.
*
* A theme is a simple javascript object with styling parameters for
* various entities of the plot. A theme has the form:
*
*
* > {
* > _name:f "Default",
* > target: {
* > backgroundColor: "transparent"
* > },
* > legend: {
* > textColor: null,
* > fontFamily: null,
* > fontSize: null,
* > border: null,
* > background: null
* > },
* > title: {
* > textColor: "rgb(102, 102, 102)",
* > fontFamily: "'Trebuchet MS',Arial,Helvetica,sans-serif",
* > fontSize: "19.2px",
* > textAlign: "center"
* > },
* > seriesStyles: {},
* > series: [{
* > color: "#4bb2c5",
* > lineWidth: 2.5,
* > shadow: true,
* > fillColor: "#4bb2c5",
* > showMarker: true,
* > markerOptions: {
* > color: "#4bb2c5",
* > show: true,
* > style: 'filledCircle',
* > lineWidth: 1.5,
* > size: 4,
* > shadow: true
* > }
* > }],
* > grid: {
* > drawGridlines: true,
* > gridLineColor: "#cccccc",
* > gridLineWidth: 1,
* > backgroundColor: "#fffdf6",
* > borderColor: "#999999",
* > borderWidth: 2,
* > shadow: true
* > },
* > axesStyles: {
* > label: {},
* > ticks: {}
* > },
* > axes: {
* > xaxis: {
* > borderColor: "#999999",
* > borderWidth: 2,
* > ticks: {
* > show: true,
* > showGridline: true,
* > showLabel: true,
* > showMark: true,
* > size: 4,
* > textColor: "",
* > whiteSpace: "nowrap",
* > fontSize: "12px",
* > fontFamily: "'Trebuchet MS',Arial,Helvetica,sans-serif"
* > },
* > label: {
* > textColor: "rgb(102, 102, 102)",
* > whiteSpace: "normal",
* > fontSize: "14.6667px",
* > fontFamily: "'Trebuchet MS',Arial,Helvetica,sans-serif",
* > fontWeight: "400"
* > }
* > },
* > yaxis: {
* > borderColor: "#999999",
* > borderWidth: 2,
* > ticks: {
* > show: true,
* > showGridline: true,
* > showLabel: true,
* > showMark: true,
* > size: 4,
* > textColor: "",
* > whiteSpace: "nowrap",
* > fontSize: "12px",
* > fontFamily: "'Trebuchet MS',Arial,Helvetica,sans-serif"
* > },
* > label: {
* > textColor: null,
* > whiteSpace: null,
* > fontSize: null,
* > fontFamily: null,
* > fontWeight: null
* > }
* > },
* > x2axis: {...
* > },
* > ...
* > y9axis: {...
* > }
* > }
* > }
*
* "seriesStyles" is a style object that will be applied to all series in the plot.
* It will forcibly override any styles applied on the individual series. "axesStyles" is
* a style object that will be applied to all axes in the plot. It will also forcibly
* override any styles on the individual axes.
*
* The example shown above has series options for a line series. Options for other
* series types are shown below:
*
* Bar Series:
*
* > {
* > color: "#4bb2c5",
* > seriesColors: ["#4bb2c5", "#EAA228", "#c5b47f", "#579575", "#839557", "#958c12", "#953579", "#4b5de4", "#d8b83f", "#ff5800", "#0085cc", "#c747a3", "#cddf54", "#FBD178", "#26B4E3", "#bd70c7"],
* > lineWidth: 2.5,
* > shadow: true,
* > barPadding: 2,
* > barMargin: 10,
* > barWidth: 15.09375,
* > 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)"]
* > }
*
* Pie Series:
*
* > {
* > seriesColors: ["#4bb2c5", "#EAA228", "#c5b47f", "#579575", "#839557", "#958c12", "#953579", "#4b5de4", "#d8b83f", "#ff5800", "#0085cc", "#c747a3", "#cddf54", "#FBD178", "#26B4E3", "#bd70c7"],
* > padding: 20,
* > sliceMargin: 0,
* > fill: true,
* > shadow: true,
* > startAngle: 0,
* > lineWidth: 2.5,
* > 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)"]
* > }
*
* Funnel Series:
*
* > {
* > color: "#4bb2c5",
* > lineWidth: 2,
* > shadow: true,
* > padding: {
* > top: 20,
* > right: 20,
* > bottom: 20,
* > left: 20
* > },
* > sectionMargin: 6,
* > seriesColors: ["#4bb2c5", "#EAA228", "#c5b47f", "#579575", "#839557", "#958c12", "#953579", "#4b5de4", "#d8b83f", "#ff5800", "#0085cc", "#c747a3", "#cddf54", "#FBD178", "#26B4E3", "#bd70c7"],
* > 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)"]
* > }
*
*/
$.jqplot.ThemeEngine = function(){
// Group: Properties
//
// prop: themes
// hash of themes managed by the theme engine.
// Indexed by theme name.
this.themes = {};
// prop: activeTheme
// Pointer to currently active theme
this.activeTheme=null;
};
// called with scope of plot
$.jqplot.ThemeEngine.prototype.init = function() {
// get the Default theme from the current plot settings.
var th = new $.jqplot.Theme({_name:'Default'});
var n, i;
for (n in th.target) {
if (n == "textColor") {
th.target[n] = this.target.css('color');
}
else {
th.target[n] = this.target.css(n);
}
}
if (this.title.show && this.title._elem) {
for (n in th.title) {
if (n == "textColor") {
th.title[n] = this.title._elem.css('color');
}
else {
th.title[n] = this.title._elem.css(n);
}
}
}
for (n in th.grid) {
th.grid[n] = this.grid[n];
}
if (th.grid.backgroundColor == null && this.grid.background != null) {
th.grid.backgroundColor = this.grid.background;
}
if (this.legend.show && this.legend._elem) {
for (n in th.legend) {
if (n == 'textColor') {
th.legend[n] = this.legend._elem.css('color');
}
else {
th.legend[n] = this.legend._elem.css(n);
}
}
}
var s;
for (i=0; iObject with extended date parsing and formatting capabilities.
* This library borrows many concepts and ideas from the Date Instance
* Methods by Ken Snyder along with some parts of Ken's actual code.
*
*
jsDate takes a different approach by not extending the built-in
* Date Object, improving date parsing, allowing for multiple formatting
* syntaxes and multiple and more easily expandable localization.
*
* @author Chris Leonello
* @date #date#
* @version #VERSION#
* @copyright (c) 2010 Chris Leonello
* jsDate is currently available for use in all personal or commercial projects
* under both the MIT and GPL version 2.0 licenses. This means that you can
* choose the license that best suits your project and use it accordingly.
*
*
Ken's origianl Date Instance Methods and copyright notice:
*
* Ken Snyder (ken d snyder at gmail dot com)
* 2008-09-10
* version 2.0.2 (http://kendsnyder.com/sandbox/date/)
* Creative Commons Attribution License 3.0 (http://creativecommons.org/licenses/by/3.0/)
*
*
* @class
* @name jsDate
* @param {String | Number | Array | Date Object | Options Object} arguments Optional arguments, either a parsable date/time string,
* a JavaScript timestamp, an array of numbers of form [year, month, day, hours, minutes, seconds, milliseconds],
* a Date object, or an options object of form {syntax: "perl", date:some Date} where all options are optional.
*/
var jsDate = function () {
this.syntax = jsDate.config.syntax;
this._type = "jsDate";
this.utcOffset = new Date().getTimezoneOffset * 60000;
this.proxy = new Date();
this.options = {};
this.locale = jsDate.regional.getLocale();
this.formatString = '';
this.defaultCentury = jsDate.config.defaultCentury;
switch ( arguments.length ) {
case 0:
break;
case 1:
// other objects either won't have a _type property or,
// if they do, it shouldn't be set to "jsDate", so
// assume it is an options argument.
if (get_type(arguments[0]) == "[object Object]" && arguments[0]._type != "jsDate") {
var opts = this.options = arguments[0];
this.syntax = opts.syntax || this.syntax;
this.defaultCentury = opts.defaultCentury || this.defaultCentury;
this.proxy = jsDate.createDate(opts.date);
}
else {
this.proxy = jsDate.createDate(arguments[0]);
}
break;
default:
var a = [];
for ( var i=0; i 0 ? 'floor' : 'ceil'](unitDiff));
};
/**
* Get the abbreviated name of the current week day
*
* @returns {String}
*/
jsDate.prototype.getAbbrDayName = function() {
return jsDate.regional[this.locale]["dayNamesShort"][this.proxy.getDay()];
};
/**
* Get the abbreviated name of the current month
*
* @returns {String}
*/
jsDate.prototype.getAbbrMonthName = function() {
return jsDate.regional[this.locale]["monthNamesShort"][this.proxy.getMonth()];
};
/**
* Get UPPER CASE AM or PM for the current time
*
* @returns {String}
*/
jsDate.prototype.getAMPM = function() {
return this.proxy.getHours() >= 12 ? 'PM' : 'AM';
};
/**
* Get lower case am or pm for the current time
*
* @returns {String}
*/
jsDate.prototype.getAmPm = function() {
return this.proxy.getHours() >= 12 ? 'pm' : 'am';
};
/**
* Get the century (19 for 20th Century)
*
* @returns {Integer} Century (19 for 20th century).
*/
jsDate.prototype.getCentury = function() {
return parseInt(this.proxy.getFullYear()/100, 10);
};
/**
* Implements Date functionality
*/
jsDate.prototype.getDate = function() {
return this.proxy.getDate();
};
/**
* Implements Date functionality
*/
jsDate.prototype.getDay = function() {
return this.proxy.getDay();
};
/**
* Get the Day of week 1 (Monday) thru 7 (Sunday)
*
* @returns {Integer} Day of week 1 (Monday) thru 7 (Sunday)
*/
jsDate.prototype.getDayOfWeek = function() {
var dow = this.proxy.getDay();
return dow===0?7:dow;
};
/**
* Get the day of the year
*
* @returns {Integer} 1 - 366, day of the year
*/
jsDate.prototype.getDayOfYear = function() {
var d = this.proxy;
var ms = d - new Date('' + d.getFullYear() + '/1/1 GMT');
ms += d.getTimezoneOffset()*60000;
d = null;
return parseInt(ms/60000/60/24, 10)+1;
};
/**
* Get the name of the current week day
*
* @returns {String}
*/
jsDate.prototype.getDayName = function() {
return jsDate.regional[this.locale]["dayNames"][this.proxy.getDay()];
};
/**
* Get the week number of the given year, starting with the first Sunday as the first week
* @returns {Integer} Week number (13 for the 13th full week of the year).
*/
jsDate.prototype.getFullWeekOfYear = function() {
var d = this.proxy;
var doy = this.getDayOfYear();
var rdow = 6-d.getDay();
var woy = parseInt((doy+rdow)/7, 10);
return woy;
};
/**
* Implements Date functionality
*/
jsDate.prototype.getFullYear = function() {
return this.proxy.getFullYear();
};
/**
* Get the GMT offset in hours and minutes (e.g. +06:30)
*
* @returns {String}
*/
jsDate.prototype.getGmtOffset = function() {
// divide the minutes offset by 60
var hours = this.proxy.getTimezoneOffset() / 60;
// decide if we are ahead of or behind GMT
var prefix = hours < 0 ? '+' : '-';
// remove the negative sign if any
hours = Math.abs(hours);
// add the +/- to the padded number of hours to : to the padded minutes
return prefix + addZeros(Math.floor(hours), 2) + ':' + addZeros((hours % 1) * 60, 2);
};
/**
* Implements Date functionality
*/
jsDate.prototype.getHours = function() {
return this.proxy.getHours();
};
/**
* Get the current hour on a 12-hour scheme
*
* @returns {Integer}
*/
jsDate.prototype.getHours12 = function() {
var hours = this.proxy.getHours();
return hours > 12 ? hours - 12 : (hours == 0 ? 12 : hours);
};
jsDate.prototype.getIsoWeek = function() {
var d = this.proxy;
var woy = d.getWeekOfYear();
var dow1_1 = (new Date('' + d.getFullYear() + '/1/1')).getDay();
// First week is 01 and not 00 as in the case of %U and %W,
// so we add 1 to the final result except if day 1 of the year
// is a Monday (then %W returns 01).
// We also need to subtract 1 if the day 1 of the year is
// Friday-Sunday, so the resulting equation becomes:
var idow = woy + (dow1_1 > 4 || dow1_1 <= 1 ? 0 : 1);
if(idow == 53 && (new Date('' + d.getFullYear() + '/12/31')).getDay() < 4)
{
idow = 1;
}
else if(idow === 0)
{
d = new jsDate(new Date('' + (d.getFullYear()-1) + '/12/31'));
idow = d.getIsoWeek();
}
d = null;
return idow;
};
/**
* Implements Date functionality
*/
jsDate.prototype.getMilliseconds = function() {
return this.proxy.getMilliseconds();
};
/**
* Implements Date functionality
*/
jsDate.prototype.getMinutes = function() {
return this.proxy.getMinutes();
};
/**
* Implements Date functionality
*/
jsDate.prototype.getMonth = function() {
return this.proxy.getMonth();
};
/**
* Get the name of the current month
*
* @returns {String}
*/
jsDate.prototype.getMonthName = function() {
return jsDate.regional[this.locale]["monthNames"][this.proxy.getMonth()];
};
/**
* Get the number of the current month, 1-12
*
* @returns {Integer}
*/
jsDate.prototype.getMonthNumber = function() {
return this.proxy.getMonth() + 1;
};
/**
* Implements Date functionality
*/
jsDate.prototype.getSeconds = function() {
return this.proxy.getSeconds();
};
/**
* Return a proper two-digit year integer
*
* @returns {Integer}
*/
jsDate.prototype.getShortYear = function() {
return this.proxy.getYear() % 100;
};
/**
* Implements Date functionality
*/
jsDate.prototype.getTime = function() {
return this.proxy.getTime();
};
/**
* Get the timezone abbreviation
*
* @returns {String} Abbreviation for the timezone
*/
jsDate.prototype.getTimezoneAbbr = function() {
return this.proxy.toString().replace(/^.*\(([^)]+)\)$/, '$1');
};
/**
* Get the browser-reported name for the current timezone (e.g. MDT, Mountain Daylight Time)
*
* @returns {String}
*/
jsDate.prototype.getTimezoneName = function() {
var match = /(?:\((.+)\)$| ([A-Z]{3}) )/.exec(this.toString());
return match[1] || match[2] || 'GMT' + this.getGmtOffset();
};
/**
* Implements Date functionality
*/
jsDate.prototype.getTimezoneOffset = function() {
return this.proxy.getTimezoneOffset();
};
/**
* Get the week number of the given year, starting with the first Monday as the first week
* @returns {Integer} Week number (13 for the 13th week of the year).
*/
jsDate.prototype.getWeekOfYear = function() {
var doy = this.getDayOfYear();
var rdow = 7 - this.getDayOfWeek();
var woy = parseInt((doy+rdow)/7, 10);
return woy;
};
/**
* Get the current date as a Unix timestamp
*
* @returns {Integer}
*/
jsDate.prototype.getUnix = function() {
return Math.round(this.proxy.getTime() / 1000, 0);
};
/**
* Implements Date functionality
*/
jsDate.prototype.getYear = function() {
return this.proxy.getYear();
};
/**
* Return a date one day ahead (or any other unit)
*
* @param {String} unit Optional, year | month | day | week | hour | minute | second | millisecond
* @returns {jsDate}
*/
jsDate.prototype.next = function(unit) {
unit = unit || 'day';
return this.clone().add(1, unit);
};
/**
* Set the jsDate instance to a new date.
*
* @param {String | Number | Array | Date Object | jsDate Object | Options Object} arguments Optional arguments,
* either a parsable date/time string,
* a JavaScript timestamp, an array of numbers of form [year, month, day, hours, minutes, seconds, milliseconds],
* a Date object, jsDate Object or an options object of form {syntax: "perl", date:some Date} where all options are optional.
*/
jsDate.prototype.set = function() {
switch ( arguments.length ) {
case 0:
this.proxy = new Date();
break;
case 1:
// other objects either won't have a _type property or,
// if they do, it shouldn't be set to "jsDate", so
// assume it is an options argument.
if (get_type(arguments[0]) == "[object Object]" && arguments[0]._type != "jsDate") {
var opts = this.options = arguments[0];
this.syntax = opts.syntax || this.syntax;
this.defaultCentury = opts.defaultCentury || this.defaultCentury;
this.proxy = jsDate.createDate(opts.date);
}
else {
this.proxy = jsDate.createDate(arguments[0]);
}
break;
default:
var a = [];
for ( var i=0; ijsDate attempts to detect locale when loaded and defaults to 'en'.
* If a localization is detected which is not available, jsDate defaults to 'en'.
* Additional localizations can be added after jsDate loads. After adding a localization,
* call the jsDate.regional.getLocale() method. Currently, en, fr and de are defined.
*
*
Localizations must be an object and have the following properties defined: monthNames, monthNamesShort, dayNames, dayNamesShort and Localizations are added like:
*
* jsDate.regional['en'] = {
* monthNames : 'January February March April May June July August September October November December'.split(' '),
* monthNamesShort : 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split(' '),
* dayNames : 'Sunday Monday Tuesday Wednesday Thursday Friday Saturday'.split(' '),
* dayNamesShort : 'Sun Mon Tue Wed Thu Fri Sat'.split(' ')
* };
*
*
After adding localizations, call jsDate.regional.getLocale(); to update the locale setting with the
* new localizations.
*/
jsDate.regional = {
'en': {
monthNames: ['January','February','March','April','May','June','July','August','September','October','November','December'],
monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun','Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
formatString: '%Y-%m-%d %H:%M:%S'
},
'fr': {
monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
monthNamesShort: ['Jan','Fév','Mar','Avr','Mai','Jun','Jul','Aoû','Sep','Oct','Nov','Déc'],
dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
formatString: '%Y-%m-%d %H:%M:%S'
},
'de': {
monthNames: ['Januar','Februar','März','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'],
monthNamesShort: ['Jan','Feb','Mär','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Dez'],
dayNames: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
dayNamesShort: ['So','Mo','Di','Mi','Do','Fr','Sa'],
formatString: '%Y-%m-%d %H:%M:%S'
},
'es': {
monthNames: ['Enero','Febrero','Marzo','Abril','Mayo','Junio', 'Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'],
monthNamesShort: ['Ene','Feb','Mar','Abr','May','Jun', 'Jul','Ago','Sep','Oct','Nov','Dic'],
dayNames: ['Domingo','Lunes','Martes','Miércoles','Jueves','Viernes','Sábado'],
dayNamesShort: ['Dom','Lun','Mar','Mié','Juv','Vie','Sáb'],
formatString: '%Y-%m-%d %H:%M:%S'
},
'ru': {
monthNames: ['Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'],
monthNamesShort: ['Янв','Фев','Мар','Апр','Май','Июн','Июл','Авг','Сен','Окт','Ноя','Дек'],
dayNames: ['воскресенье','понедельник','вторник','среда','четверг','пятница','суббота'],
dayNamesShort: ['вск','пнд','втр','срд','чтв','птн','сбт'],
formatString: '%Y-%m-%d %H:%M:%S'
},
'ar': {
monthNames: ['كانون الثاني', 'شباط', 'آذار', 'نيسان', 'آذار', 'حزيران','تموز', 'آب', 'أيلول', 'تشرين الأول', 'تشرين الثاني', 'كانون الأول'],
monthNamesShort: ['1','2','3','4','5','6','7','8','9','10','11','12'],
dayNames: ['السبت', 'الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة'],
dayNamesShort: ['سبت', 'أحد', 'اثنين', 'ثلاثاء', 'أربعاء', 'خميس', 'جمعة'],
formatString: '%Y-%m-%d %H:%M:%S'
},
'pt': {
monthNames: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'],
dayNames: ['Domingo','Segunda-feira','Terça-feira','Quarta-feira','Quinta-feira','Sexta-feira','Sábado'],
dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','Sáb'],
formatString: '%Y-%m-%d %H:%M:%S'
},
'pt-BR': {
monthNames: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho', 'Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'],
dayNames: ['Domingo','Segunda-feira','Terça-feira','Quarta-feira','Quinta-feira','Sexta-feira','Sábado'],
dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','Sáb'],
formatString: '%Y-%m-%d %H:%M:%S'
}
};
// Set english variants to 'en'
jsDate.regional['en-US'] = jsDate.regional['en-GB'] = jsDate.regional['en'];
/**
* Try to determine the users locale based on the lang attribute of the html page. Defaults to 'en'
* if it cannot figure out a locale of if the locale does not have a localization defined.
* @returns {String} locale
*/
jsDate.regional.getLocale = function () {
var l = jsDate.config.defaultLocale;
if ( document && document.getElementsByTagName('html') && document.getElementsByTagName('html')[0].lang ) {
l = document.getElementsByTagName('html')[0].lang;
if (!jsDate.regional.hasOwnProperty(l)) {
l = jsDate.config.defaultLocale;
}
}
return l;
};
// ms in day
var day = 24 * 60 * 60 * 1000;
// padd a number with zeros
var addZeros = function(num, digits) {
num = String(num);
var i = digits - num.length;
var s = String(Math.pow(10, i)).slice(1);
return s.concat(num);
};
// representations used for calculating differences between dates.
// This borrows heavily from Ken Snyder's work.
var multipliers = {
millisecond: 1,
second: 1000,
minute: 60 * 1000,
hour: 60 * 60 * 1000,
day: day,
week: 7 * day,
month: {
// add a number of months
add: function(d, number) {
// add any years needed (increments of 12)
multipliers.year.add(d, Math[number > 0 ? 'floor' : 'ceil'](number / 12));
// ensure that we properly wrap betwen December and January
var prevMonth = d.getMonth() + (number % 12);
if (prevMonth == 12) {
prevMonth = 0;
d.setYear(d.getFullYear() + 1);
} else if (prevMonth == -1) {
prevMonth = 11;
d.setYear(d.getFullYear() - 1);
}
d.setMonth(prevMonth);
},
// get the number of months between two Date objects (decimal to the nearest day)
diff: function(d1, d2) {
// get the number of years
var diffYears = d1.getFullYear() - d2.getFullYear();
// get the number of remaining months
var diffMonths = d1.getMonth() - d2.getMonth() + (diffYears * 12);
// get the number of remaining days
var diffDays = d1.getDate() - d2.getDate();
// return the month difference with the days difference as a decimal
return diffMonths + (diffDays / 30);
}
},
year: {
// add a number of years
add: function(d, number) {
d.setYear(d.getFullYear() + Math[number > 0 ? 'floor' : 'ceil'](number));
},
// get the number of years between two Date objects (decimal to the nearest day)
diff: function(d1, d2) {
return multipliers.month.diff(d1, d2) / 12;
}
}
};
//
// Alias each multiplier with an 's' to allow 'year' and 'years' for example.
// This comes from Ken Snyders work.
//
for (var unit in multipliers) {
if (unit.substring(unit.length - 1) != 's') { // IE will iterate newly added properties :|
multipliers[unit + 's'] = multipliers[unit];
}
}
//
// take a jsDate instance and a format code and return the formatted value.
// This is a somewhat modified version of Ken Snyder's method.
//
var format = function(d, code, syntax) {
// if shorcut codes are used, recursively expand those.
if (jsDate.formats[syntax]["shortcuts"][code]) {
return jsDate.strftime(d, jsDate.formats[syntax]["shortcuts"][code], syntax);
} else {
// get the format code function and addZeros() argument
var getter = (jsDate.formats[syntax]["codes"][code] || '').split('.');
var nbr = d['get' + getter[0]] ? d['get' + getter[0]]() : '';
if (getter[1]) {
nbr = addZeros(nbr, getter[1]);
}
return nbr;
}
};
/**
* @static
* Static function for convert a date to a string according to a given format. Also acts as namespace for strftime format codes.
*
strftime formatting can be accomplished without creating a jsDate object by calling jsDate.strftime():
* @param {String | Number | Array | jsDate Object | Date Object} date A parsable date string, JavaScript time stamp, Array of form [year, month, day, hours, minutes, seconds, milliseconds], jsDate Object or Date object.
* @param {String} formatString String with embedded date formatting codes.
* See: {@link jsDate.formats}.
* @param {String} syntax Optional syntax to use [default perl].
* @param {String} locale Optional locale to use.
* @returns {String} Formatted representation of the date.
*/
//
// Logic as implemented here is very similar to Ken Snyder's Date Instance Methods.
//
jsDate.strftime = function(d, formatString, syntax, locale) {
var syn = 'perl';
var loc = jsDate.regional.getLocale();
// check if syntax and locale are available or reversed
if (syntax && jsDate.formats.hasOwnProperty(syntax)) {
syn = syntax;
}
else if (syntax && jsDate.regional.hasOwnProperty(syntax)) {
loc = syntax;
}
if (locale && jsDate.formats.hasOwnProperty(locale)) {
syn = locale;
}
else if (locale && jsDate.regional.hasOwnProperty(locale)) {
loc = locale;
}
if (get_type(d) != "[object Object]" || d._type != "jsDate") {
d = new jsDate(d);
d.locale = loc;
}
if (!formatString) {
formatString = d.formatString || jsDate.regional[loc]['formatString'];
}
// default the format string to year-month-day
var source = formatString || '%Y-%m-%d',
result = '',
match;
// replace each format code
while (source.length > 0) {
if (match = source.match(jsDate.formats[syn].codes.matcher)) {
result += source.slice(0, match.index);
result += (match[1] || '') + format(d, match[2], syn);
source = source.slice(match.index + match[0].length);
} else {
result += source;
source = '';
}
}
return result;
};
/**
* @namespace
* Namespace to hold format codes and format shortcuts. "perl" and "php" format codes
* and shortcuts are defined by default. Additional codes and shortcuts can be
* added like:
*
*
* jsDate.formats["perl"] = {
* "codes": {
* matcher: /someregex/,
* Y: "fullYear", // name of "get" method without the "get",
* ..., // more codes
* },
* "shortcuts": {
* F: '%Y-%m-%d',
* ..., // more shortcuts
* }
* };
*
*
*
Additionally, ISO and SQL shortcuts are defined and can be accesses via:
* jsDate.formats.ISO and jsDate.formats.SQL
*/
jsDate.formats = {
ISO:'%Y-%m-%dT%H:%M:%S.%N%G',
SQL:'%Y-%m-%d %H:%M:%S'
};
/**
* Perl format codes and shortcuts for strftime.
*
* A hash (object) of codes where each code must be an array where the first member is
* the name of a Date.prototype or jsDate.prototype function to call
* and optionally a second member indicating the number to pass to addZeros()
*
*
The following format codes are defined:
*
*
* Code Result Description
* == Years ==
* %Y 2008 Four-digit year
* %y 08 Two-digit year
*
* == Months ==
* %m 09 Two-digit month
* %#m 9 One or two-digit month
* %B September Full month name
* %b Sep Abbreviated month name
*
* == Days ==
* %d 05 Two-digit day of month
* %#d 5 One or two-digit day of month
* %e 5 One or two-digit day of month
* %A Sunday Full name of the day of the week
* %a Sun Abbreviated name of the day of the week
* %w 0 Number of the day of the week (0 = Sunday, 6 = Saturday)
*
* == Hours ==
* %H 23 Hours in 24-hour format (two digits)
* %#H 3 Hours in 24-hour integer format (one or two digits)
* %I 11 Hours in 12-hour format (two digits)
* %#I 3 Hours in 12-hour integer format (one or two digits)
* %p PM AM or PM
*
* == Minutes ==
* %M 09 Minutes (two digits)
* %#M 9 Minutes (one or two digits)
*
* == Seconds ==
* %S 02 Seconds (two digits)
* %#S 2 Seconds (one or two digits)
* %s 1206567625723 Unix timestamp (Seconds past 1970-01-01 00:00:00)
*
* == Milliseconds ==
* %N 008 Milliseconds (three digits)
* %#N 8 Milliseconds (one to three digits)
*
* == Timezone ==
* %O 360 difference in minutes between local time and GMT
* %Z Mountain Standard Time Name of timezone as reported by browser
* %G 06:00 Hours and minutes between GMT
*
* == Shortcuts ==
* %F 2008-03-26 %Y-%m-%d
* %T 05:06:30 %H:%M:%S
* %X 05:06:30 %H:%M:%S
* %x 03/26/08 %m/%d/%y
* %D 03/26/08 %m/%d/%y
* %#c Wed Mar 26 15:31:00 2008 %a %b %e %H:%M:%S %Y
* %v 3-Sep-2008 %e-%b-%Y
* %R 15:31 %H:%M
* %r 03:31:00 PM %I:%M:%S %p
*
* == Characters ==
* %n \n Newline
* %t \t Tab
* %% % Percent Symbol
*
*
*
Formatting shortcuts that will be translated into their longer version.
* Be sure that format shortcuts do not refer to themselves: this will cause an infinite loop.
*
*
Format codes and format shortcuts can be redefined after the jsDate
* module is imported.
*
*
Note that if you redefine the whole hash (object), you must supply a "matcher"
* regex for the parser. The default matcher is:
*
* /()%(#?(%|[a-z]))/i
*
*
which corresponds to the Perl syntax used by default.
*
*
By customizing the matcher and format codes, nearly any strftime functionality is possible.
*/
jsDate.formats.perl = {
codes: {
//
// 2-part regex matcher for format codes
//
// first match must be the character before the code (to account for escaping)
// second match must be the format code character(s)
//
matcher: /()%(#?(%|[a-z]))/i,
// year
Y: 'FullYear',
y: 'ShortYear.2',
// month
m: 'MonthNumber.2',
'#m': 'MonthNumber',
B: 'MonthName',
b: 'AbbrMonthName',
// day
d: 'Date.2',
'#d': 'Date',
e: 'Date',
A: 'DayName',
a: 'AbbrDayName',
w: 'Day',
// hours
H: 'Hours.2',
'#H': 'Hours',
I: 'Hours12.2',
'#I': 'Hours12',
p: 'AMPM',
// minutes
M: 'Minutes.2',
'#M': 'Minutes',
// seconds
S: 'Seconds.2',
'#S': 'Seconds',
s: 'Unix',
// milliseconds
N: 'Milliseconds.3',
'#N': 'Milliseconds',
// timezone
O: 'TimezoneOffset',
Z: 'TimezoneName',
G: 'GmtOffset'
},
shortcuts: {
// date
F: '%Y-%m-%d',
// time
T: '%H:%M:%S',
X: '%H:%M:%S',
// local format date
x: '%m/%d/%y',
D: '%m/%d/%y',
// local format extended
'#c': '%a %b %e %H:%M:%S %Y',
// local format short
v: '%e-%b-%Y',
R: '%H:%M',
r: '%I:%M:%S %p',
// tab and newline
t: '\t',
n: '\n',
'%': '%'
}
};
/**
* PHP format codes and shortcuts for strftime.
*
* A hash (object) of codes where each code must be an array where the first member is
* the name of a Date.prototype or jsDate.prototype function to call
* and optionally a second member indicating the number to pass to addZeros()
*
*
The following format codes are defined:
*
*
* Code Result Description
* === Days ===
* %a Sun through Sat An abbreviated textual representation of the day
* %A Sunday - Saturday A full textual representation of the day
* %d 01 to 31 Two-digit day of the month (with leading zeros)
* %e 1 to 31 Day of the month, with a space preceding single digits.
* %j 001 to 366 Day of the year, 3 digits with leading zeros
* %u 1 - 7 (Mon - Sun) ISO-8601 numeric representation of the day of the week
* %w 0 - 6 (Sun - Sat) Numeric representation of the day of the week
*
* === Week ===
* %U 13 Full Week number, starting with the first Sunday as the first week
* %V 01 through 53 ISO-8601:1988 week number, starting with the first week of the year
* with at least 4 weekdays, with Monday being the start of the week
* %W 46 A numeric representation of the week of the year,
* starting with the first Monday as the first week
* === Month ===
* %b Jan through Dec Abbreviated month name, based on the locale
* %B January - December Full month name, based on the locale
* %h Jan through Dec Abbreviated month name, based on the locale (an alias of %b)
* %m 01 - 12 (Jan - Dec) Two digit representation of the month
*
* === Year ===
* %C 19 Two digit century (year/100, truncated to an integer)
* %y 09 for 2009 Two digit year
* %Y 2038 Four digit year
*
* === Time ===
* %H 00 through 23 Two digit representation of the hour in 24-hour format
* %I 01 through 12 Two digit representation of the hour in 12-hour format
* %l 1 through 12 Hour in 12-hour format, with a space preceeding single digits
* %M 00 through 59 Two digit representation of the minute
* %p AM/PM UPPER-CASE 'AM' or 'PM' based on the given time
* %P am/pm lower-case 'am' or 'pm' based on the given time
* %r 09:34:17 PM Same as %I:%M:%S %p
* %R 00:35 Same as %H:%M
* %S 00 through 59 Two digit representation of the second
* %T 21:34:17 Same as %H:%M:%S
* %X 03:59:16 Preferred time representation based on locale, without the date
* %z -0500 or EST Either the time zone offset from UTC or the abbreviation
* %Z -0500 or EST The time zone offset/abbreviation option NOT given by %z
*
* === Time and Date ===
* %D 02/05/09 Same as %m/%d/%y
* %F 2009-02-05 Same as %Y-%m-%d (commonly used in database datestamps)
* %s 305815200 Unix Epoch Time timestamp (same as the time() function)
* %x 02/05/09 Preferred date representation, without the time
*
* === Miscellaneous ===
* %n --- A newline character (\n)
* %t --- A Tab character (\t)
* %% --- A literal percentage character (%)
*
*/
jsDate.formats.php = {
codes: {
//
// 2-part regex matcher for format codes
//
// first match must be the character before the code (to account for escaping)
// second match must be the format code character(s)
//
matcher: /()%((%|[a-z]))/i,
// day
a: 'AbbrDayName',
A: 'DayName',
d: 'Date.2',
e: 'Date',
j: 'DayOfYear.3',
u: 'DayOfWeek',
w: 'Day',
// week
U: 'FullWeekOfYear.2',
V: 'IsoWeek.2',
W: 'WeekOfYear.2',
// month
b: 'AbbrMonthName',
B: 'MonthName',
m: 'MonthNumber.2',
h: 'AbbrMonthName',
// year
C: 'Century.2',
y: 'ShortYear.2',
Y: 'FullYear',
// time
H: 'Hours.2',
I: 'Hours12.2',
l: 'Hours12',
p: 'AMPM',
P: 'AmPm',
M: 'Minutes.2',
S: 'Seconds.2',
s: 'Unix',
O: 'TimezoneOffset',
z: 'GmtOffset',
Z: 'TimezoneAbbr'
},
shortcuts: {
D: '%m/%d/%y',
F: '%Y-%m-%d',
T: '%H:%M:%S',
X: '%H:%M:%S',
x: '%m/%d/%y',
R: '%H:%M',
r: '%I:%M:%S %p',
t: '\t',
n: '\n',
'%': '%'
}
};
//
// Conceptually, the logic implemented here is similar to Ken Snyder's Date Instance Methods.
// I use his idea of a set of parsers which can be regular expressions or functions,
// iterating through those, and then seeing if Date.parse() will create a date.
// The parser expressions and functions are a little different and some bugs have been
// worked out. Also, a lot of "pre-parsing" is done to fix implementation
// variations of Date.parse() between browsers.
//
jsDate.createDate = function(date) {
// if passing in multiple arguments, try Date constructor
if (date == null) {
return new Date();
}
// If the passed value is already a date object, return it
if (date instanceof Date) {
return date;
}
// if (typeof date == 'number') return new Date(date * 1000);
// If the passed value is an integer, interpret it as a javascript timestamp
if (typeof date == 'number') {
return new Date(date);
}
// Before passing strings into Date.parse(), have to normalize them for certain conditions.
// If strings are not formatted staccording to the EcmaScript spec, results from Date parse will be implementation dependent.
//
// For example:
// * FF and Opera assume 2 digit dates are pre y2k, Chome assumes <50 is pre y2k, 50+ is 21st century.
// * Chrome will correctly parse '1984-1-25' into localtime, FF and Opera will not parse.
// * Both FF, Chrome and Opera will parse '1984/1/25' into localtime.
// remove leading and trailing spaces
var parsable = String(date).replace(/^\s*(.+)\s*$/g, '$1');
// replace dahses (-) with slashes (/) in dates like n[nnn]/n[n]/n[nnn]
parsable = parsable.replace(/^([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,4})/, "$1/$2/$3");
/////////
// Need to check for '15-Dec-09' also.
// FF will not parse, but Chrome will.
// Chrome will set date to 2009 as well.
/////////
// first check for 'dd-mmm-yyyy' or 'dd/mmm/yyyy' like '15-Dec-2010'
parsable = parsable.replace(/^(3[01]|[0-2]?\d)[-\/]([a-z]{3,})[-\/](\d{4})/i, "$1 $2 $3");
// Now check for 'dd-mmm-yy' or 'dd/mmm/yy' and normalize years to default century.
var match = parsable.match(/^(3[01]|[0-2]?\d)[-\/]([a-z]{3,})[-\/](\d{2})\D*/i);
if (match && match.length > 3) {
var m3 = parseFloat(match[3]);
var ny = jsDate.config.defaultCentury + m3;
ny = String(ny);
// now replace 2 digit year with 4 digit year
parsable = parsable.replace(/^(3[01]|[0-2]?\d)[-\/]([a-z]{3,})[-\/](\d{2})\D*/i, match[1] +' '+ match[2] +' '+ ny);
}
// Check for '1/19/70 8:14PM'
// where starts with mm/dd/yy or yy/mm/dd and have something after
// Check if 1st postiion is greater than 31, assume it is year.
// Assme all 2 digit years are 1900's.
// Finally, change them into US style mm/dd/yyyy representations.
match = parsable.match(/^([0-9]{1,2})[-\/]([0-9]{1,2})[-\/]([0-9]{1,2})[^0-9]/);
function h1(parsable, match) {
var m1 = parseFloat(match[1]);
var m2 = parseFloat(match[2]);
var m3 = parseFloat(match[3]);
var cent = jsDate.config.defaultCentury;
var ny, nd, nm, str;
if (m1 > 31) { // first number is a year
nd = m3;
nm = m2;
ny = cent + m1;
}
else { // last number is the year
nd = m2;
nm = m1;
ny = cent + m3;
}
str = nm+'/'+nd+'/'+ny;
// now replace 2 digit year with 4 digit year
return parsable.replace(/^([0-9]{1,2})[-\/]([0-9]{1,2})[-\/]([0-9]{1,2})/, str);
}
if (match && match.length > 3) {
parsable = h1(parsable, match);
}
// Now check for '1/19/70' with nothing after and do as above
var match = parsable.match(/^([0-9]{1,2})[-\/]([0-9]{1,2})[-\/]([0-9]{1,2})$/);
if (match && match.length > 3) {
parsable = h1(parsable, match);
}
var i = 0;
var length = jsDate.matchers.length;
var pattern;
var current = parsable;
while (i < length) {
ms = Date.parse(current);
if (!isNaN(ms)) {
return new Date(ms);
}
pattern = jsDate.matchers[i];
if (typeof pattern == 'function') {
obj = pattern.call(jsDate, current);
if (obj instanceof Date) {
return obj;
}
} else {
current = parsable.replace(pattern[0], pattern[1]);
}
i++;
}
return NaN;
};
/**
* @static
* Handy static utility function to return the number of days in a given month.
* @param {Integer} year Year
* @param {Integer} month Month (1-12)
* @returns {Integer} Number of days in the month.
*/
//
// handy utility method Borrowed right from Ken Snyder's Date Instance Mehtods.
//
jsDate.daysInMonth = function(year, month) {
if (month == 2) {
return new Date(year, 1, 29).getDate() == 29 ? 29 : 28;
}
return [undefined,31,undefined,31,30,31,30,31,31,30,31,30,31][month];
};
//
// An Array of regular expressions or functions that will attempt to match the date string.
// Functions are called with scope of a jsDate instance.
//
jsDate.matchers = [
// convert dd.mmm.yyyy to mm/dd/yyyy (world date to US date).
[/(3[01]|[0-2]\d)\s*\.\s*(1[0-2]|0\d)\s*\.\s*([1-9]\d{3})/, '$2/$1/$3'],
// convert yyyy-mm-dd to mm/dd/yyyy (ISO date to US date).
[/([1-9]\d{3})\s*-\s*(1[0-2]|0\d)\s*-\s*(3[01]|[0-2]\d)/, '$2/$3/$1'],
// Handle 12 hour or 24 hour time with milliseconds am/pm and optional date part.
function(str) {
var match = str.match(/^(?:(.+)\s+)?([012]?\d)(?:\s*\:\s*(\d\d))?(?:\s*\:\s*(\d\d(\.\d*)?))?\s*(am|pm)?\s*$/i);
// opt. date hour opt. minute opt. second opt. msec opt. am or pm
if (match) {
if (match[1]) {
var d = this.createDate(match[1]);
if (isNaN(d)) {
return;
}
} else {
var d = new Date();
d.setMilliseconds(0);
}
var hour = parseFloat(match[2]);
if (match[6]) {
hour = match[6].toLowerCase() == 'am' ? (hour == 12 ? 0 : hour) : (hour == 12 ? 12 : hour + 12);
}
d.setHours(hour, parseInt(match[3] || 0, 10), parseInt(match[4] || 0, 10), ((parseFloat(match[5] || 0)) || 0)*1000);
return d;
}
else {
return str;
}
},
// Handle ISO timestamp with time zone.
function(str) {
var match = str.match(/^(?:(.+))[T|\s+]([012]\d)(?:\:(\d\d))(?:\:(\d\d))(?:\.\d+)([\+\-]\d\d\:\d\d)$/i);
if (match) {
if (match[1]) {
var d = this.createDate(match[1]);
if (isNaN(d)) {
return;
}
} else {
var d = new Date();
d.setMilliseconds(0);
}
var hour = parseFloat(match[2]);
d.setHours(hour, parseInt(match[3], 10), parseInt(match[4], 10), parseFloat(match[5])*1000);
return d;
}
else {
return str;
}
},
// Try to match ambiguous strings like 12/8/22.
// Use FF date assumption that 2 digit years are 20th century (i.e. 1900's).
// This may be redundant with pre processing of date already performed.
function(str) {
var match = str.match(/^([0-3]?\d)\s*[-\/.\s]{1}\s*([a-zA-Z]{3,9})\s*[-\/.\s]{1}\s*([0-3]?\d)$/);
if (match) {
var d = new Date();
var cent = jsDate.config.defaultCentury;
var m1 = parseFloat(match[1]);
var m3 = parseFloat(match[3]);
var ny, nd, nm;
if (m1 > 31) { // first number is a year
nd = m3;
ny = cent + m1;
}
else { // last number is the year
nd = m1;
ny = cent + m3;
}
var nm = inArray(match[2], jsDate.regional[this.locale]["monthNamesShort"]);
if (nm == -1) {
nm = inArray(match[2], jsDate.regional[this.locale]["monthNames"]);
}
d.setFullYear(ny, nm, nd);
d.setHours(0,0,0,0);
return d;
}
else {
return str;
}
}
];
//
// I think John Reisig published this method on his blog, ejohn.
//
function inArray( elem, array ) {
if ( array.indexOf ) {
return array.indexOf( elem );
}
for ( var i = 0, length = array.length; i < length; i++ ) {
if ( array[ i ] === elem ) {
return i;
}
}
return -1;
}
//
// Thanks to Kangax, Christian Sciberras and Stack Overflow for this method.
//
function get_type(thing){
if(thing===null) return "[object Null]"; // special case
return Object.prototype.toString.call(thing);
}
$.jsDate = jsDate;
/**
* JavaScript printf/sprintf functions.
*
* This code has been adapted from the publicly available sprintf methods
* by Ash Searle. His original header follows:
*
* This code is unrestricted: you are free to use it however you like.
*
* The functions should work as expected, performing left or right alignment,
* truncating strings, outputting numbers with a required precision etc.
*
* For complex cases, these functions follow the Perl implementations of
* (s)printf, allowing arguments to be passed out-of-order, and to set the
* precision or length of the output based on arguments instead of fixed
* numbers.
*
* See http://perldoc.perl.org/functions/sprintf.html for more information.
*
* Implemented:
* - zero and space-padding
* - right and left-alignment,
* - base X prefix (binary, octal and hex)
* - positive number prefix
* - (minimum) width
* - precision / truncation / maximum width
* - out of order arguments
*
* Not implemented (yet):
* - vector flag
* - size (bytes, words, long-words etc.)
*
* Will not implement:
* - %n or %p (no pass-by-reference in JavaScript)
*
* @version 2007.04.27
* @author Ash Searle
*
* You can see the original work and comments on his blog:
* http://hexmen.com/blog/2007/03/printf-sprintf/
* http://hexmen.com/js/sprintf.js
*/
/**
* @Modifications 2009.05.26
* @author Chris Leonello
*
* Added %p %P specifier
* Acts like %g or %G but will not add more significant digits to the output than present in the input.
* Example:
* Format: '%.3p', Input: 0.012, Output: 0.012
* Format: '%.3g', Input: 0.012, Output: 0.0120
* Format: '%.4p', Input: 12.0, Output: 12.0
* Format: '%.4g', Input: 12.0, Output: 12.00
* Format: '%.4p', Input: 4.321e-5, Output: 4.321e-5
* Format: '%.4g', Input: 4.321e-5, Output: 4.3210e-5
*/
$.jqplot.sprintf = function() {
function pad(str, len, chr, leftJustify) {
var padding = (str.length >= len) ? '' : Array(1 + len - str.length >>> 0).join(chr);
return leftJustify ? str + padding : padding + str;
}
function thousand_separate(value) {
value_str = new String(value);
for (var i=10; i>0; i--) {
if (value_str == (value_str = value_str.replace(/^(\d+)(\d{3})/, "$1"+$.jqplot.sprintf.thousandsSeparator+"$2"))) break;
}
return value_str;
}
function justify(value, prefix, leftJustify, minWidth, zeroPad, htmlSpace) {
var diff = minWidth - value.length;
if (diff > 0) {
var spchar = ' ';
if (htmlSpace) { spchar = ' '; }
if (leftJustify || !zeroPad) {
value = pad(value, minWidth, spchar, leftJustify);
} else {
value = value.slice(0, prefix.length) + pad('', diff, '0', true) + value.slice(prefix.length);
}
}
return value;
}
function formatBaseX(value, base, prefix, leftJustify, minWidth, precision, zeroPad, htmlSpace) {
// Note: casts negative numbers to positive ones
var number = value >>> 0;
prefix = prefix && number && {'2': '0b', '8': '0', '16': '0x'}[base] || '';
value = prefix + pad(number.toString(base), precision || 0, '0', false);
return justify(value, prefix, leftJustify, minWidth, zeroPad, htmlSpace);
}
function formatString(value, leftJustify, minWidth, precision, zeroPad, htmlSpace) {
if (precision != null) {
value = value.slice(0, precision);
}
return justify(value, '', leftJustify, minWidth, zeroPad, htmlSpace);
}
var a = arguments, i = 0, format = a[i++];
return format.replace($.jqplot.sprintf.regex, function(substring, valueIndex, flags, minWidth, _, precision, type) {
if (substring == '%%') { return '%'; }
// parse flags
var leftJustify = false, positivePrefix = '', zeroPad = false, prefixBaseX = false, htmlSpace = false, thousandSeparation = false;
for (var j = 0; flags && j < flags.length; j++) switch (flags.charAt(j)) {
case ' ': positivePrefix = ' '; break;
case '+': positivePrefix = '+'; break;
case '-': leftJustify = true; break;
case '0': zeroPad = true; break;
case '#': prefixBaseX = true; break;
case '&': htmlSpace = true; break;
case '\'': thousandSeparation = true; break;
}
// parameters may be null, undefined, empty-string or real valued
// we want to ignore null, undefined and empty-string values
if (!minWidth) {
minWidth = 0;
}
else if (minWidth == '*') {
minWidth = +a[i++];
}
else if (minWidth.charAt(0) == '*') {
minWidth = +a[minWidth.slice(1, -1)];
}
else {
minWidth = +minWidth;
}
// Note: undocumented perl feature:
if (minWidth < 0) {
minWidth = -minWidth;
leftJustify = true;
}
if (!isFinite(minWidth)) {
throw new Error('$.jqplot.sprintf: (minimum-)width must be finite');
}
if (!precision) {
precision = 'fFeE'.indexOf(type) > -1 ? 6 : (type == 'd') ? 0 : void(0);
}
else if (precision == '*') {
precision = +a[i++];
}
else if (precision.charAt(0) == '*') {
precision = +a[precision.slice(1, -1)];
}
else {
precision = +precision;
}
// grab value using valueIndex if required?
var value = valueIndex ? a[valueIndex.slice(0, -1)] : a[i++];
switch (type) {
case 's': {
if (value == null) {
return '';
}
return formatString(String(value), leftJustify, minWidth, precision, zeroPad, htmlSpace);
}
case 'c': return formatString(String.fromCharCode(+value), leftJustify, minWidth, precision, zeroPad, htmlSpace);
case 'b': return formatBaseX(value, 2, prefixBaseX, leftJustify, minWidth, precision, zeroPad,htmlSpace);
case 'o': return formatBaseX(value, 8, prefixBaseX, leftJustify, minWidth, precision, zeroPad, htmlSpace);
case 'x': return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad, htmlSpace);
case 'X': return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad, htmlSpace).toUpperCase();
case 'u': return formatBaseX(value, 10, prefixBaseX, leftJustify, minWidth, precision, zeroPad, htmlSpace);
case 'i': {
var number = parseInt(+value, 10);
if (isNaN(number)) {
return '';
}
var prefix = number < 0 ? '-' : positivePrefix;
number_str = thousandSeparation ? thousand_separate(String(Math.abs(number))): String(Math.abs(number));
value = prefix + pad(number_str, precision, '0', false);
//value = prefix + pad(String(Math.abs(number)), precision, '0', false);
return justify(value, prefix, leftJustify, minWidth, zeroPad, htmlSpace);
}
case 'd': {
var number = Math.round(+value);
if (isNaN(number)) {
return '';
}
var prefix = number < 0 ? '-' : positivePrefix;
number_str = thousandSeparation ? thousand_separate(String(Math.abs(number))): String(Math.abs(number));
value = prefix + pad(number_str, precision, '0', false);
return justify(value, prefix, leftJustify, minWidth, zeroPad, htmlSpace);
}
case 'e':
case 'E':
case 'f':
case 'F':
case 'g':
case 'G':
{
var number = +value;
if (isNaN(number)) {
return '';
}
var prefix = number < 0 ? '-' : positivePrefix;
var method = ['toExponential', 'toFixed', 'toPrecision']['efg'.indexOf(type.toLowerCase())];
var textTransform = ['toString', 'toUpperCase']['eEfFgG'.indexOf(type) % 2];
number_str = Math.abs(number)[method](precision);
number_str = thousandSeparation ? thousand_separate(number_str): number_str;
value = prefix + number_str;
return justify(value, prefix, leftJustify, minWidth, zeroPad, htmlSpace)[textTransform]();
}
case 'p':
case 'P':
{
// make sure number is a number
var number = +value;
if (isNaN(number)) {
return '';
}
var prefix = number < 0 ? '-' : positivePrefix;
var parts = String(Number(Math.abs(number)).toExponential()).split(/e|E/);
var sd = (parts[0].indexOf('.') != -1) ? parts[0].length - 1 : parts[0].length;
var zeros = (parts[1] < 0) ? -parts[1] - 1 : 0;
if (Math.abs(number) < 1) {
if (sd + zeros <= precision) {
value = prefix + Math.abs(number).toPrecision(sd);
}
else {
if (sd <= precision - 1) {
value = prefix + Math.abs(number).toExponential(sd-1);
}
else {
value = prefix + Math.abs(number).toExponential(precision-1);
}
}
}
else {
var prec = (sd <= precision) ? sd : precision;
value = prefix + Math.abs(number).toPrecision(prec);
}
var textTransform = ['toString', 'toUpperCase']['pP'.indexOf(type) % 2];
return justify(value, prefix, leftJustify, minWidth, zeroPad, htmlSpace)[textTransform]();
}
case 'n': return '';
default: return substring;
}
});
};
$.jqplot.sprintf.thousandsSeparator = ',';
$.jqplot.sprintf.regex = /%%|%(\d+\$)?([-+#0&\' ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([nAscboxXuidfegpEGP])/g;
})(jQuery);