// ==ClosureCompiler==
// @compilation_level SIMPLE_OPTIMIZATIONS
/**
* @license Highcharts JS v1.2.5 (2010-04-13)
*
* (c) 2010 Torstein Hønsi
*
* License: www.highcharts.com/license
*/
/*
* Roadmap
*
* 2.0 (summer 2010)
* - Rewritten rendering engine to SVG/VML
* - Save as image
* - Print chart - open in a popup and call window.print.
* - Improvements to the toolbar object to allow the two above
*
* 2.1 (summer/autumn 2010)
* - Logarithmic axis
* - Built-in table parser
* - Base value for column, bar and area series
* - Automatic margin size based on axis label size and legend. Anti-collision logic for labels.
* - Floating columns and bars
* - Candlestick charts
* - Stock charts?
* - Radar charts?
*
* 2.2 (autumn 2010)
* - Improve pies: shadow, better dataLabels, 3D view.
*
*/
(function() {
// encapsulated variables
var
// abstracts to make compiled code smaller
undefined,
doc = document,
win = window,
math = Math,
mathRound = math.round,
mathFloor = math.floor,
mathMax = math.max,
mathAbs = math.abs,
mathCos = math.cos,
mathSin = math.sin,
// some variables
userAgent = navigator.userAgent,
isIE = /msie/i.test(userAgent) && !win.opera,
isWebKit = /AppleWebKit/.test(userAgent),
styleTag,
canvasCounter = 0,
colorCounter,
symbolCounter,
symbolSizes = {},
idCounter = 0,
timeFactor = 1, // 1 = JavaScript time, 1000 = Unix time
garbageBin,
// some constants for frequently used strings
DIV = 'div',
ABSOLUTE = 'absolute',
RELATIVE = 'relative',
HIDDEN = 'hidden',
HIGHCHARTS_HIDDEN = 'highcharts-' + HIDDEN,
VISIBLE = 'visible',
PX = 'px',
// time methods, changed based on whether or not UTC is used
makeTime,
getMinutes,
getHours,
getDay,
getDate,
getMonth,
getFullYear,
setMinutes,
setHours,
setDate,
setMonth,
setFullYear,
// check for a custom HighchartsAdapter defined prior to this file
globalAdapter = win.HighchartsAdapter,
adapter = globalAdapter || {},
// Utility functions. If the HighchartsAdapter is not defined, adapter is an empty object
// and all the utility functions will be null. In that case they are populated by the
// default adapters below.
each = adapter.each,
grep = adapter.grep,
map = adapter.map,
merge = adapter.merge,
hyphenate = adapter.hyphenate,
addEvent = adapter.addEvent,
fireEvent = adapter.fireEvent,
animate = adapter.animate,
getAjax = adapter.getAjax,
// lookup over the types and the associated classes
seriesTypes = {};
// the jQuery adapter
if (!globalAdapter && win.jQuery) {
var jQ = jQuery;
each = function(arr, fn) {
for (var i = 0, len = arr.length; i < len; i++) {
if (fn.call(arr[i], arr[i], i, arr) === false) {
return i;
}
}
};
grep = jQ.grep;
map = function(arr, fn){
//return jQuery.map(arr, fn);
var results = [];
for (var i = 0, len = arr.length; i < len; i++) {
results[i] = fn.call(arr[i], arr[i], i, arr);
}
return results;
}
merge = function(){
var args = arguments;
return jQ.extend(true, null, args[0], args[1], args[2], args[3]);
}
hyphenate = function (str){
return str.replace(/([A-Z])/g, function(a, b){ return '-'+ b.toLowerCase() });
}
addEvent = function (el, event, fn){
jQ(el).bind(event, fn);
}
fireEvent = function(el, type, eventArguments, defaultFunction) {
var event = jQ.Event(type),
detachedType = 'detached'+ type;
extend(event, eventArguments);
// Prevent jQuery from triggering the object method that is named the
// same as the event. For example, if the event is 'select', jQuery
// attempts calling el.select and it goes into a loop.
if (el[type]) {
el[detachedType] = el[type];
el[type] = null;
}
// trigger it
jQ(el).trigger(event);
// attach the method
if (el[detachedType]) {
el[type] = el[detachedType];
el[detachedType] = null;
}
if (defaultFunction && !event.isDefaultPrevented()) {
defaultFunction(event);
}
}
animate = function (el, params, options) {
jQ(el).animate(params, options);
}
getAjax = function (url, callback) {
jQ.get(url, null, callback);
}
jQ.extend( jQ.easing, {
easeOutQuad: function (x, t, b, c, d) {
return -c *(t/=d)*(t-2) + b;
}
});
// the MooTools adapter
} else if (!globalAdapter && win.MooTools) {
each = $each;
map = function (arr, fn){
return arr.map(fn);
}
grep = function(arr, fn) {
return arr.filter(fn)
}
merge = $merge;
hyphenate = function (str){
return str.hyphenate();
}
addEvent = function (el, type, fn) {
// if the addEvent method is not defined, el is a custom Highcharts object
// like series or point
if (!el.addEvent) {
if (el.nodeName) el = $(el); // a dynamically generated node
else extend(el, new Events()); // a custom object
}
el.addEvent(type, fn);
}
fireEvent = function(el, event, eventArguments, defaultFunction) {
// create an event object that keeps all functions
event = new Event({
type: event,
target: el
});
event = extend (event, eventArguments);
// override the preventDefault function to be able to use
// this for custom events
event.preventDefault = function() {
defaultFunction = null;
}
// if fireEvent is not available on the object, there hasn't been added
// any events to it above
if (el.fireEvent) el.fireEvent(event.type, event);
// fire the default if it is passed and it is not prevented above
if (defaultFunction) defaultFunction(event);
}
animate = function (el, params, options){
var myEffect = new Fx.Morph($(el), extend(options, {
transition: Fx.Transitions.Quad.easeInOut
}));
myEffect.start(params);
}
getAjax = function (url, callback) {
(new Request({
url: url,
method: 'get',
onSuccess: callback
})).send();
}
}
/**
* Check if an element is an array, and if not, make it into an array. Like
* MooTools' $.splat.
*/
function splat(obj) {
if (!obj || obj.constructor != Array) obj = [obj];
return obj;
}
/**
* Returns true if the object is not null or undefined. Like MooTools' $.defined.
* @param {Object} obj
*/
function defined (obj) {
return obj !== undefined && obj !== null;
}
/**
* Return the first value that is defined. Like MooTools' $.pick.
*/
function pick() {
var args = arguments,
i,
arg;
for (i = 0; i < args.length; i++) {
arg = args[i];
if (defined(arg)) return arg;
};
}
/**
* Dynamically add a CSS rule to the page
* @param {String} selector
* @param {Object} declaration
* @param {Boolean} print Whether to add the styles only to print media. IE only.
*/
function addCSSRule(selector, declaration, print) {
var key,
serialized = '',
styleSheets,
last,
media = print ? 'print' : '',
createStyleTag = function(print) {
return createElement(
'style', {
type: 'text/css',
media: print ? 'print' : ''
},
null,
doc.getElementsByTagName('HEAD')[0]
);
};
// add the style tag the first time
if (!styleTag) styleTag = createStyleTag();
// serialize the declaration
for (key in declaration)
serialized += hyphenate(key) +':'+ declaration[key] + ';';
if (!isIE) { // create a text node in the style tag
styleTag.appendChild(
doc.createTextNode(
selector + " {" + serialized + "}\n"
)
);
} else { // get the last stylesheet and add rules
var styleSheets = doc.styleSheets,
index,
styleSheet;
if (print) { // only in IE for now
createStyleTag(true);
}
index = styleSheets.length - 1;
while (index >= 0 && styleSheets[index].media != media) index--;
styleSheet = styleSheets[index];
styleSheet.addRule(selector, serialized);
}
}
/**
* Extend an object with the members of another
* @param {Object} a The object to be extended
* @param {Object} b The object to add to the first one
*/
function extend(a, b) {
if (!a) a = {};
for (var n in b) a[n] = b[n];
return a;
}
/**
* Merge the default options with custom options and return the new options structure
* @param {Object} options The new custom options
*/
function setOptions(options) {
defaultOptions = merge(defaultOptions, options);
// apply UTC
setTimeMethods();
return defaultOptions;
}
/**
* Discard an element by moving it to the bin and delete
* @param {Object} The HTML node to discard
*/
function discardElement(element) {
// create a garbage bin element, not part of the DOM
if (!garbageBin) garbageBin = createElement(DIV);
// move the node and empty bin
if (element) garbageBin.appendChild(element);
garbageBin.innerHTML = '';
}
var defaultFont = 'normal 12px "Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif',
defaultLabelOptions = {
enabled: true,
// rotation: 0,
align: 'center',
x: 0,
y: 15,
/*formatter: function() {
return this.value;
},*/
style: {
color: '#666',
font: defaultFont.replace('12px', '11px')
//'10px bold "Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif'
}
},
defaultOptions = {
colors: ['#4572A7', '#AA4643', '#89A54E', '#80699B', '#3D96AE',
'#DB843D', '#92A8CD', '#A47D7C', '#B5CA92'],
symbols: ['circle', 'diamond', 'square', 'triangle', 'triangle-down'],
lang: {
loading: 'Loading...',
months: ['January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December'],
weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
decimalPoint: '.',
resetZoom: 'Reset zoom',
resetZoomTitle: 'Reset zoom level 1:1',
thousandsSep: ','
},
global: {
useUTC: true
},
chart: {
//alignTicks: false,
//className: null,
/*events: {
* load,
* selection
* },
*/
margin: [50, 50, 60, 80],
borderColor: '#4572A7',
//borderWidth: 0,
borderRadius: 5,
defaultSeriesType: 'line',
ignoreHiddenSeries: true,
//inverted: false,
//shadow: false,
//style: {},
//backgroundColor: null,
//plotBackgroundColor: null,
plotBorderColor: '#C0C0C0'
//plotBorderWidth: 0,
//plotShadow: false,
//zoomType: ''
},
title: {
text: 'Chart title',
style: {
textAlign: 'center',
color: '#3E576F',
font: defaultFont.replace('12px', '16px'),
margin: '10px 0 0 0'
}
},
subtitle: {
text: '',
style: {
textAlign: 'center',
color: '#6D869F',
font: defaultFont,
margin: 0
}
},
plotOptions: {
line: { // base series options
allowPointSelect: false,
//allowDrag: false, // point dragging - not yet implemented
//dragType: 'y',
showCheckbox: false,
animation: true,
//cursor: 'default',
//enableMouseTracking: true,
events: {},
lineWidth: 2,
shadow: true,
// stacking: null,
marker: {
enabled: true,
symbol: 'auto',
lineWidth: 0,
radius: 4,
lineColor: '#FFFFFF',
fillColor: 'auto',
states: { // states for a single point
hover: {
//radius: base + 2
},
select: {
fillColor: '#FFFFFF',
lineColor: 'auto',
lineWidth: 2
}
}
},
point: {
events: {}
},
dataLabels: merge(defaultLabelOptions, {
enabled: false,
y: -6,
formatter: function() {
return this.y;
}
}),
//pointStart: 0,
//pointInterval: 1,
showInLegend: true,
states: { // states for the entire series
hover: {
//enabled: false,
lineWidth: 3,
marker: {
// lineWidth: base + 1,
// radius: base + 1
}
},
select: {
marker: {}
}
}
}
},
labels: {
//items: [],
style: {
position: ABSOLUTE,
color: '#3E576F',
font: defaultFont
}
},
legend: {
enabled: true,
layout: 'horizontal',
labelFormatter: function() {
return this.name
},
//borderWidth: 0,
borderColor: '#909090',
borderRadius: 5,
shadow: true,
//backgroundColor: null,
style: {
bottom: '10px',
left: '80px',
padding: '5px'
},
itemStyle: {
listStyle: 'none',
margin: 0,
padding: '0 2em 0 0', // make room for the checkbox
font: defaultFont,
cursor: 'pointer',
color: '#3E576F',
position: RELATIVE // to allow absolute placement of the checkboxes
},
itemHoverStyle: {
color: '#000'
},
itemHiddenStyle: {
color: '#CCC'
},
itemCheckboxStyle: {
position: ABSOLUTE,
right: 0
},
//reversed: false, // docs
symbolWidth: 16,
symbolPadding: 5
},
loading: {
hideDuration: 100,
labelStyle: {
font: defaultFont.replace('normal', 'bold'),
position: RELATIVE,
top: '1em'
},
showDuration: 100,
style: {
position: ABSOLUTE,
backgroundColor: 'white',
opacity: 0.5,
textAlign: 'center'
}
},
tooltip: {
enabled: true,
formatter: function() {
var pThis = this,
series = pThis.series,
xAxis = series.xAxis,
x = pThis.x;
return ''+ (pThis.point.name || series.name) +'
'+
(defined(x) ?
'X value: '+ (xAxis && xAxis.options.type == 'datetime' ?
dateFormat('%Y-%m-%d %H:%M:%S', x) : x) +'
':
'')+
'Y value: '+ pThis.y;
},
backgroundColor: 'rgba(255, 255, 255, .85)',
borderWidth: 2,
borderRadius: 5,
shadow: true,
snap: 10,
style: {
color: '#333333',
font: defaultFont,
fontSize: '9pt',
padding: '5px',
whiteSpace: 'nowrap'
}
},
toolbar: {
itemStyle: {
color: '#4572A7',
cursor: 'pointer',
margin: '20px',
font: defaultFont
}
},
credits: {
enabled: true,
text: 'Highcharts.com',
href: 'http://www.highcharts.com',
style: {
position: ABSOLUTE,
right: '10px',
bottom: '5px',
color: '#999',
textDecoration: 'none',
font: defaultFont.replace('12px', '10px')
},
target: '_self'
}
};
// Axis defaults
//defaultOptions.xAxis = merge(defaultOptions.axis);
var defaultXAxisOptions = {
// alternateGridColor: null,
// categories: [],
dateTimeLabelFormats: {
second: '%H:%M:%S',
minute: '%H:%M',
hour: '%H:%M',
day: '%e. %b',
week: '%e. %b',
month: '%b \'%y',
year: '%Y'
},
endOnTick: false,
gridLineColor: '#C0C0C0',
// gridLineWidth: 0,
// reversed: false,
labels: defaultLabelOptions,
lineColor: '#C0D0E0',
lineWidth: 1,
max: null,
min: null,
maxZoom: null,
minorGridLineColor: '#E0E0E0',
minorGridLineWidth: 1,
minorTickColor: '#A0A0A0',
//minorTickInterval: null,
minorTickLength: 2,
minorTickPosition: 'outside', // inside or outside
minorTickWidth: 1,
//plotBands: [],
//plotLines: [],
//reversed: false,
showFirstLabel: true,
showLastLabel: false,
startOfWeek: 1,
startOnTick: false,
tickColor: '#C0D0E0',
tickInterval: 'auto',
tickLength: 5,
tickmarkPlacement: 'between', // on or between
tickPixelInterval: 100,
tickPosition: 'outside',
tickWidth: 1,
title: {
enabled: false,
text: 'X-values',
align: 'middle', // low, middle or high
margin: 35,
//rotation: 0,
//side: 'outside',
style: {
color: '#6D869F',
font: defaultFont.replace('normal', 'bold')
}
},
type: 'linear' // linear or datetime
},
defaultYAxisOptions = merge(defaultXAxisOptions, {
endOnTick: true,
gridLineWidth: 1,
tickPixelInterval: 72,
showLastLabel: true,
labels: {
align: 'right',
x: -8,
y: 3
},
lineWidth: 0,
maxPadding: 0.05,
minPadding: 0.05,
startOnTick: true,
tickWidth: 0,
title: {
enabled: true,
margin: 40,
rotation: 270,
text: 'Y-values'
}
}),
defaultLeftAxisOptions = {
labels: {
align: 'right',
x: -8,
y: 3
},
title: {
rotation: 270
}
},
defaultRightAxisOptions = {
labels: {
align: 'left',
x: 8,
y: 3
},
title: {
rotation: 90
}
},
defaultBottomAxisOptions = { // horizontal axis
labels: {
align: 'center',
x: 0,
y: 14
},
title: {
rotation: 0
}
},
defaultTopAxisOptions = merge(defaultBottomAxisOptions, {
labels: {
y: -5
}
});
// Series defaults
var defaultPlotOptions = defaultOptions.plotOptions,
defaultSeriesOptions = defaultPlotOptions.line;
//defaultPlotOptions.line = merge(defaultSeriesOptions);
defaultPlotOptions.spline = merge(defaultSeriesOptions);
defaultPlotOptions.scatter = merge(defaultSeriesOptions, {
//dragType: 'xy', // n/a
lineWidth: 0,
states: {
hover: {
lineWidth: 0
}
}
});
defaultPlotOptions.area = merge(defaultSeriesOptions, {
// lineColor: null, // overrides color, but lets fillColor be unaltered
// fillOpacity: .75,
fillColor: 'auto'
});
defaultPlotOptions.areaspline = merge(defaultPlotOptions.area);
defaultPlotOptions.column = merge(defaultSeriesOptions, {
borderColor: '#FFFFFF',
borderWidth: 1,
borderRadius: 0,
groupPadding: 0.2,
pointPadding: 0.1,
states: {
hover: {
brightness: 0.1,
shadow: false
},
select: {
color: '#C0C0C0',
borderColor: '#000000',
shadow: false
}
}
});
defaultPlotOptions.bar = merge(defaultPlotOptions.column, {
dataLabels: {
align: 'left',
x: 5,
y: 0
}
});
defaultPlotOptions.pie = merge(defaultSeriesOptions, {
//dragType: '', // n/a
borderColor: '#FFFFFF',
borderWidth: 1,
center: ['50%', '50%'],
legendType: 'point',
size: '90%',
slicedOffset: 10,
states: {
hover: {
brightness: 0.1,
shadow: false
}
}
});
// set the default time methods
setTimeMethods();
// class-like inheritance
function extendClass(parent, members) {
var object = function(){};
object.prototype = new parent();
extend(object.prototype, members);
return object;
}
/*
function reverseArray(arr) {
var reversed = [];
for (var i = arr.length - 1; i >= 0; i--)
reversed.push( arr[i]);
return reversed;
}
*/
// return a deep value without throwing an error
/*function deepStructure(obj, path) {
// split the path into an array
path = path.split('.'), i = 0;
// recursively set obj to the path
while (path[i] && obj) obj = obj[path[i++]];
if (i == path.length) return obj;
}*/
/**
* Create a color from a string or configuration object
* @param {Object} val
*/
function setColor(val, ctx) {
if (typeof val == 'string') {
return val;
} else if (val.linearGradient) {
var gradient = ctx.createLinearGradient.apply(ctx, val.linearGradient);
each (val.stops, function(stop) {
gradient.addColorStop(stop[0], stop[1]);
});
return gradient;
}
}
var Color = function(input) {
var rgba = [], result;
function parse(input) {
// rgba
if((result = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(input)))
rgba = [parseInt(result[1]), parseInt(result[2]), parseInt(result[3]), parseFloat(result[4])];
// hex
else if((result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(input)))
rgba = [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16), 1];
}
function get() {
// it's NaN if gradient colors on a column chart
if (rgba && !isNaN(rgba[0])) return 'rgba('+ rgba.join(',') +')';
else return input;
}
function brighten(alpha) {
if (typeof alpha == 'number' && alpha != 0) {
for (var i = 0; i < 3; i++) {
rgba[i] += parseInt(alpha * 255);
if (rgba[i] < 0) rgba[i] = 0;
if (rgba[i] > 255) rgba[i] = 255;
}
}
return this;
}
function setOpacity(alpha) {
rgba[3] = alpha;
return this;
}
parse(input);
// public methods
return {
get: get,
brighten: brighten,
setOpacity: setOpacity
};
};
//defaultMarkers = ['circle'];
function createElement (tag, attribs, styles, parent, nopad) {
var el = doc.createElement(tag);
if (attribs) extend(el, attribs);
if (nopad) setStyles(el, {padding: 0, border: 'none', margin: 0});
if (styles) setStyles(el, styles);
if (parent) parent.appendChild(el);
return el;
};
function setStyles (el, styles) {
//for (var x in styles) el.style[x] = styles[x];
if (isIE) {
if (styles.opacity !== undefined)
styles.filter = 'alpha(opacity='+ (styles.opacity * 100) +')';
}
extend(el.style, styles);
};
/**
* Format a number and return a string based on input settings
* @param {Number} number The input number to format
* @param {Number} decimals The amount of decimals
* @param {String} decPoint The decimal point, defaults to the one given in the lang options
* @param {String} thousandsSep The thousands separator, defaults to the one given in the lang options
*/
function numberFormat (number, decimals, decPoint, thousandsSep) {
var lang = defaultOptions.lang,
// http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_number_format/
n = number, c = isNaN(decimals = mathAbs(decimals)) ? 2 : decimals,
d = decPoint === undefined ? lang.decimalPoint : decPoint,
t = thousandsSep === undefined ? lang.thousandsSep : thousandsSep, s = n < 0 ? "-" : "",
i = parseInt(n = mathAbs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) +
(c ? d + mathAbs(n - i).toFixed(c).slice(2) : "");
};
/**
* Based on http://www.php.net/manual/en/function.strftime.php
* @param {String} format
* @param {Number} timestamp
* @param {Boolean} capitalize
*/
function dateFormat(format, timestamp, capitalize) {
function pad (number) {
return number.toString().replace(/^([0-9])$/, '0$1');
}
if (!defined(timestamp)) return 'Invalid date';
var date = new Date(timestamp * timeFactor),
// get the basic time values
hours = date[getHours](),
day = date[getDay](),
dayOfMonth = date[getDate](),
month = date[getMonth](),
fullYear = date[getFullYear](),
lang = defaultOptions.lang,
langWeekdays = lang.weekdays,
langMonths = lang.months,
// list all format keys
replacements = {
// Day
'a': langWeekdays[day].substr(0, 3), // Short weekday, like 'Mon'
'A': langWeekdays[day], // Long weekday, like 'Monday'
'd': pad(dayOfMonth), // Two digit day of the month, 01 to 31
'e': dayOfMonth, // Day of the month, 1 through 31
// Week (none implemented)
// Month
'b': langMonths[month].substr(0, 3), // Short month, like 'Jan'
'B': langMonths[month], // Long month, like 'January'
'm': pad(month + 1), // Two digit month number, 01 through 12
// Year
'y': fullYear.toString().substr(2, 2), // Two digits year, like 09 for 2009
'Y': fullYear, // Four digits year, like 2009
// Time
'H': pad(hours), // Two digits hours in 24h format, 00 through 23
'I': pad((hours % 12) || 12), // Two digits hours in 12h format, 00 through 11
'l': (hours % 12) || 12, // Hours in 12h format, 1 through 12
'M': pad(date[getMinutes]()), // Two digits minutes, 00 through 59
'p': hours < 12 ? 'AM' : 'PM', // Upper case AM or PM
'P': hours < 12 ? 'am' : 'pm', // Lower case AM or PM
'S': pad(date.getSeconds()) // Two digits seconds, 00 through 59
};
// do the replaces
for (var key in replacements) format = format.replace('%'+ key, replacements[key]);
// Optionally capitalize the string and return
return capitalize ? format.substr(0, 1).toUpperCase() + format.substr(1) : format;
};
/**
* Set the time methods globally based on the useUTC option. Time method can be either
* local time or UTC (default).
*/
function setTimeMethods() {
var useUTC = defaultOptions.global.useUTC;
makeTime = useUTC ? Date.UTC : function(year, month, date, hours, minutes, seconds) {
return new Date(
year,
month,
pick(date, 1),
pick(hours, 0),
pick(minutes, 0),
pick(seconds, 0)
).getTime();
};
getMinutes = useUTC ? 'getUTCMinutes' : 'getMinutes';
getHours = useUTC ? 'getUTCHours' : 'getHours';
getDay = useUTC ? 'getUTCDay' : 'getDay';
getDate = useUTC ? 'getUTCDate' : 'getDate';
getMonth = useUTC ? 'getUTCMonth' : 'getMonth';
getFullYear = useUTC ? 'getUTCFullYear' : 'getFullYear';
setMinutes = useUTC ? 'setUTCMinutes' : 'setMinutes';
setHours = useUTC ? 'setUTCHours' : 'setHours';
setDate = useUTC ? 'setUTCDate' : 'setDate';
setMonth = useUTC ? 'setUTCMonth' : 'setMonth';
setFullYear = useUTC ? 'setUTCFullYear' : 'setFullYear';
};
/**
* Return the absolute page position of an element
* @param {Object} el
*/
function getPosition (el) {
var p = { x: el.offsetLeft, y: el.offsetTop };
while (el.offsetParent) {
el = el.offsetParent;
p.x += el.offsetLeft;
p.y += el.offsetTop;
if (el != doc.body && el != doc.documentElement) {
p.x -= el.scrollLeft;
p.y -= el.scrollTop;
}
}
return p;
}
var Layer = function (name, appendTo, props, styles) {
var layer = this,
div,
appendToStyle = appendTo.style;
props = extend({
className: 'highcharts-'+ name
}, props);
styles = extend({
width: appendToStyle.width, //appendTo.offsetWidth + PX,
height: appendToStyle.height, //appendTo.offsetHeight + PX,
position: ABSOLUTE,
top: 0,
left: 0,
margin: 0,
padding: 0,
border: 'none'
}, styles);
div = createElement(DIV, props, styles, appendTo);
extend(layer, {
div: div,
width: parseInt(styles.width),
height: parseInt(styles.height)
});
// initial SVG string
layer.svg = isIE ? '' : ''+
'';
// append it again for Chrome to update
if (isWebKit) this.div.appendChild(svgObject);
}
}
},
clear: function() {
var layer = this,
div = this.div,
childNodes = div.childNodes,
node;
if (layer.ctx) layer.ctx.clearRect(0, 0, layer.width, layer.height);
if (layer.svgObject) {
discardElement(layer.svgObject);
layer.svgObject = null;
layer.svg = layer.basicSvg;
}
// remove all spans
for (var i = childNodes.length - 1; i >= 0; i--) {
node = childNodes[i];
if (/(SPAN|IMG)/.test(node.tagName)) discardElement(node);
}
},
hide: function() {
setStyles (this.div, {
display: 'none'
})
//jQuery(this.div).fadeOut(250);
// A possible way to fade out in IE would be to get all the shapes
// in the layer and change the opacities of their FillColor and StrokeColor
/*var shapes = this.div.getElementsByTagName('shape');
each (shapes, function(shape) {
//shape.style.filter = 'alpha(opacity=59)';
})
var layer = this;
setTimeout(function() {
layer.div.style.visibility = HIDDEN
}, 2000);*/
},
show: function() {
setStyles (this.div, {
display: ''
})
//jQuery(this.div).fadeIn(50);
},
/**
* Discard layer DOM elements and null the reference
*/
destroy: function() {
discardElement(this.div);
return null;
}
};
function Chart (options) {
/**
* Add a series dynamically after time
*
* @param {Object} options The config options
* @param {Boolean} redraw Whether to redraw the chart after adding. Defaults to true.
*
* @return {Object} series The newly created series object
*/
function addSeries(options, redraw) {
var series;
redraw = pick(redraw, true); // defaults to true
fireEvent(chart, 'addSeries', { options: options }, function() {
series = initSeries(options);
series.isDirty = true;
chart.isDirty = true; // the series array is out of sync with the display
if (redraw) chart.redraw();
});
return series;
};
/**
* Redraw legend, axes or series based on updated data
*/
function redraw() {
var redrawLegend = chart.isDirty;
// handle updated data in the series
each (series, function(serie) {
if (serie.isDirty) { // prepare the data so axis can read it
serie.cleanData();
serie.getSegments();
if (serie.options.legendType == 'point') redrawLegend = true;
}
});
// reset maxTicks
maxTicks = null;
if (hasCartesianSeries) {
// set axes scales
each (axes, function(axis) {
axis.setScale();
})
adjustTickAmounts();
// redraw axes
each (axes, function(axis) {
if (axis.isDirty) axis.redraw();
})
}
// redraw affected series
each (series, function(serie) {
if (serie.isDirty && serie.visible) serie.redraw();
});
// handle added or removed series
if (redrawLegend) { // series or pie points are added or removed
// draw legend graphics
if (legend && legend.renderHTML) {
legend.renderHTML(true);
legend.drawGraphics(true);
}
chart.isDirty = false;
}
// hide tooltip and hover states
if (tracker && tracker.resetTracker) tracker.resetTracker();
// fire the event
fireEvent(chart, 'redraw');
}
/**
* Initialize an individual series, called internally before render time
*/
function initSeries(options) {
var type = options.type || optionsChart.defaultSeriesType,
typeClass = seriesTypes[type],
serie,
hasRendered = chart.hasRendered;
// an inverted chart can't take a column series and vice versa
if (hasRendered) {
if (inverted && type == 'column') typeClass = BarSeries;
else if (!inverted && type == 'bar') typeClass = ColumnSeries;
}
serie = new typeClass();
serie.init(chart, options);
// set internal chart properties
if (!hasRendered && serie.inverted) inverted = true;
if (serie.isCartesian) hasCartesianSeries = serie.isCartesian;
series.push(serie);
return serie;
}
/**
* Dim the chart and show a loading text or symbol
*/
function showLoading() {
var loadingOptions = options.loading;
// create the layer at the first call
if (!loadingLayer) {
loadingLayer = createElement(DIV, {
className: 'highcharts-loading'
}, extend(loadingOptions.style, {
left: marginLeft + PX,
top: marginTop + PX,
width: plotWidth + PX,
height: plotHeight + PX,
zIndex: 10,
display: 'none'
}), container);
createElement('span', {
innerHTML: options.lang.loading
}, loadingOptions.labelStyle, loadingLayer);
}
// show it
setStyles(loadingLayer, { display: '' });
animate(loadingLayer, {
opacity: loadingOptions.style.opacity
}, {
duration: loadingOptions.showDuration
});
}
/**
* Hide the loading layer
*/
function hideLoading() {
animate(loadingLayer, {
opacity: 0
}, {
duration: options.loading.hideDuration,
complete: function() {
setStyles(loadingLayer, { display: 'none' });
}
});
}
/**
* Get an axis, series or point object by id.
* @param id {String} The id as given in the configuration options
*/
function get(id) {
var i,
j,
match,
data;
// search axes
for (i = 0; i < axes.length; i++) {
if (axes[i].options.id == id) return axes[i];
}
// search series
for (i = 0; i < series.length; i++) {
if (series[i].options.id == id) return series[i];
}
// search points
for (i = 0; i < series.length; i++) {
data = series[i].data;
for (j = 0; j < data.length; j++) {
if (data[j].id == id) return data[j];
}
}
return null;
}
/**
* Update the chart's position after it has been moved, to match
* the mouse positions with the chart
*/
function updatePosition() {
var container = doc.getElementById(containerId);
if (container) {
position = getPosition(container);
}
}
/**
* Create the Axis instances based on the config options
*/
function getAxes() {
var xAxisOptions = options.xAxis || {},
yAxisOptions = options.yAxis || {},
axis;
// make sure the options are arrays and add some members
xAxisOptions = splat(xAxisOptions);
each(xAxisOptions, function(axis, i) {
axis.index = i;
axis.isX = true;
});
yAxisOptions = splat(yAxisOptions);
each(yAxisOptions, function(axis, i) {
axis.index = i;
});
// concatenate all axis options into one array
axes = xAxisOptions.concat(yAxisOptions);
// loop the options and construct axis objects
chart.xAxis = [];
chart.yAxis = [];
axes = map (axes, function(axisOptions) {
axis = new Axis(chart, axisOptions);
chart[axis.isXAxis ? 'xAxis' : 'yAxis'].push(axis);
return axis;
});
adjustTickAmounts();
};
/**
* Adjust all axes tick amounts
*/
function adjustTickAmounts() {
if (optionsChart.alignTicks !== false) each (axes, function(axis) {
axis.adjustTickAmount();
});
}
/**
* Get the currently selected points from all series
*/
function getSelectedPoints() {
var points = [];
each(series, function(serie) {
points = points.concat( grep( serie.data, function(point) {
return point.selected;
}));
});
return points;
};
/**
* Get the currently selected series
*/
function getSelectedSeries() {
return grep (series, function (serie) {
return serie.selected;
});
}
/**
* Zoom into a given portion of the chart given by axis coordinates
* @param {Object} event
*/
function zoom(event) {
var lang = defaultOptions.lang;
// add button to reset selection
chart.toolbar.add('zoom', lang.resetZoom, lang.resetZoomTitle, function() {
//zoom(false);
fireEvent(chart, 'selection', { resetSelection: true }, zoom);
chart.toolbar.remove('zoom');
});
// if zoom is called with no arguments, reset the axes
if (!event || event.resetSelection) each(axes, function(axis) {
axis.setExtremes(null, null, false);
});
// else, zoom in on all axes
else {
each (event.xAxis.concat(event.yAxis), function(axisData) {
var axis = axisData.axis;
// don't zoom more than maxZoom
if (chart.tracker[axis.isXAxis ? 'zoomX' : 'zoomY'])
axis.setExtremes(axisData.min, axisData.max, false);
});
}
// redraw chart
redraw();
}
/**
* Function: (private) showTitle
*
* Show the title and subtitle of the chart
*/
function showTitle () {
var title = options.title,
subtitle = options.subtitle;
if (!chart.titleLayer) {
var titleLayer = new Layer('title-layer', container, null, {
zIndex: 2
});
// title
if (title && title.text) createElement('h2', {
className: 'highcharts-title',
innerHTML: title.text
}, title.style, titleLayer.div);
// subtitle
if (subtitle && subtitle.text) createElement('h3', {
className: 'highcharts-subtitle',
innerHTML: subtitle.text
}, subtitle.style, titleLayer.div);
chart.titleLayer = titleLayer;
}
}
/**
* Load graphics and data required to draw the chart
*/
function checkResources() {
var allLoaded = true;
for (var n in chart.resources) {
if (!chart.resources[n]) allLoaded = false;
}
if (allLoaded) resourcesLoaded();
};
/**
* Prepare for first rendering after all data are loaded
*/
function resourcesLoaded() {
getAxes();
// Prepare for the axis sizes
each(series, function(serie) {
serie.translate();
serie.setTooltipPoints();
/*if (options.tooltip.enabled) */ serie.createArea();
});
chart.render = render;
setTimeout(function() { // IE(7) needs timeout
render();
fireEvent(chart, 'load');
}, 0);
}
/**
* Get the containing element, determine the size and create the inner container
* div to hold the chart
*/
function getContainer() {
renderTo = optionsChart.renderTo;
containerId = 'highcharts-'+ idCounter++;
if (typeof renderTo == 'string') {
renderTo = doc.getElementById(renderTo);
}
// remove previous chart
renderTo.innerHTML = '';
// If the container doesn't have an offsetWidth, it has or is a child of a node
// that has display:none. We need to temporarily move it out to a visible
// state to determine the size, else the legend and tooltips won't render
// properly
if (!renderTo.offsetWidth) {
renderToClone = renderTo.cloneNode(0);
setStyles(renderToClone, {
position: ABSOLUTE,
top: '-9999px',
display: ''
});
doc.body.appendChild(renderToClone);
}
// get the width and height
var renderToOffsetHeight = (renderToClone || renderTo).offsetHeight;
chartWidth = optionsChart.width || (renderToClone || renderTo).offsetWidth || 600;
chartHeight = optionsChart.height ||
// the offsetHeight of an empty container is 0 in standard browsers, but 19 in IE7:
(renderToOffsetHeight > marginTop + marginBottom ? renderToOffsetHeight : 0) ||
400;
// create the inner container
container = createElement(DIV, {
className: 'highcharts-container' +
(optionsChart.className ? ' '+ optionsChart.className : ''),
id: containerId
}, extend({
position: RELATIVE,
overflow: HIDDEN,
width: chartWidth + PX,
height: chartHeight + PX,
textAlign: 'left'
}, optionsChart.style),
renderToClone || renderTo
);
}
/**
* Render all graphics for the chart
*/
function render () {
var mgn,
div,
i,
labels = options.labels,
credits = options.credits;
// Chart area
mgn = 2 * (optionsChart.borderWidth || 0) + (optionsChart.shadow ? 8 : 0);
backgroundLayer.drawRect(mgn / 2, mgn / 2, chartWidth - mgn, chartHeight - mgn,
optionsChart.borderColor, optionsChart.borderWidth, optionsChart.borderRadius,
optionsChart.backgroundColor, optionsChart.shadow);
// Plot background
backgroundLayer.drawRect(
marginLeft,
marginTop,
plotWidth,
plotHeight,
null,
null,
null,
optionsChart.plotBackgroundColor,
null,
plotBackground
);
// Plot area border
(new Layer('plot-border', container, null, {
zIndex: 4 // in front of grid lines and graphs, behind axis lines
})).drawRect(
marginLeft,
marginTop,
plotWidth,
plotHeight,
optionsChart.plotBorderColor,
optionsChart.plotBorderWidth,
null,
null,
optionsChart.plotShadow
);
// Printing CSS for IE
if (isIE) addCSSRule('.highcharts-image-map', { display: 'none' }, 'print');
// Axes
if (hasCartesianSeries) each(axes, function(axis) {
axis.render();
});
// Title
showTitle();
// Labels
if (labels.items) each (labels.items, function () {
var attributes = extend({ className: 'highcharts-label' }, this.attributes);
plotLayer.drawHtml(this.html, attributes, extend(labels.style, this.style));
});
// The series
each (series, function(serie) {
serie.render();
});
// Legend
legend = chart.legend = new Legend(chart);
// Toolbar (don't redraw)
if (!chart.toolbar) chart.toolbar = Toolbar(chart);
// Credits
if (credits.enabled && !chart.credits)
chart.credits = createElement('a', {
className: 'highcharts-credits',
href: credits.href,
innerHTML: credits.text,
target: credits.target
}, extend(credits.style, {
zIndex: 8
}), container);
// Set flag
chart.hasRendered = true;
// If the chart was rendered outside the top container, put it back in
if (renderToClone) {
renderTo.appendChild(container);
discardElement(renderToClone);
updatePosition()
}
};
/**
* Clean up memory usage
*/
function destroy() {
/**
* Clear certain attributes from the element
* @param {Object} d
*/
function purge(d) {
var a = d.attributes, i, l, n;
if (a) {
l = a.length;
for (i = l - 1; i >= 0; i -= 1) {
n = a[i].name;
try {
//if (typeof d[n] != 'object' && !/^(width|height)$/.test(n)) {
if (typeof d[n] == 'function') {
d[n] = null;
}
} catch (e) {
// IE/excanvas produces errors on some of the properties
}
}
}
a = d.childNodes;
if (a) {
l = a.length;
for (i = l - 1; i >= 0; i--) {
var node = d.childNodes[i];
purge(node);
if (!node.childNodes.length) discardElement(node);
}
}
}
// destroy each series
each (series, function(serie) {
serie.destroy();
});
series = [];
purge(container);
};
/**
* Create a new axis object
* @param {Object} chart
* @param {Object} options
*/
function Axis (chart, options) {
/**
* Set the options by merging the inheritance line
*/
function setOptions() {
options = merge(
isXAxis ? defaultXAxisOptions : defaultYAxisOptions,
//defaultOptions[isXAxis ? 'xAxis' : 'yAxis'],
horiz ?
(opposite ? defaultTopAxisOptions : defaultBottomAxisOptions) :
(opposite ? defaultRightAxisOptions : defaultLeftAxisOptions),
options
);
};
/**
* Get the minimum and maximum for the series of each axis
*/
function getSeriesExtremes() {
var stack = [],
run;
// reset dataMin and dataMax in case we're redrawing
dataMin = dataMax = null;
// get an overview of what series are associated with this axis
associatedSeries = [];
each(series, function(serie) {
run = false;
// match this axis against the series' given or implicated axis
each(['xAxis', 'yAxis'], function(strAxis) {
if (
// we're in the right x or y dimension, and...
(strAxis == 'xAxis' && isXAxis || strAxis == 'yAxis' && !isXAxis) && (
// the axis number is given in the options and matches this axis index, or
(serie.options[strAxis] == options.index) ||
// the axis index is not given
(serie.options[strAxis] === undefined && options.index == 0)
)
) {
serie[strAxis] = axis;
associatedSeries.push(serie);
// the series is visible, run the min/max detection
run = true;
}
});
// ignore hidden series if opted
if (!serie.visible && optionsChart.ignoreHiddenSeries) run = false;
if (run) {
var stacking;
if (!isXAxis) {
stacking = serie.options.stacking;
usePercentage = stacking == 'percent';
// create a stack for this particular series type
if (stacking) {
var typeStack = stack[serie.type] || [];
stack[serie.type] = typeStack;
}
if (usePercentage) {
dataMin = 0;
dataMax = 99;
}
}
if (serie.isCartesian) { // line, column etc. need axes, pie doesn't
each(serie.data, function(point, i) {
var pointX = point.x,
pointY = point.y;
// initial values
if (dataMin === null) {
// start out with the first point
dataMin = dataMax = point[xOrY];
}
// x axis
if (isXAxis) {
if (pointX > dataMax) dataMax = pointX;
else if (pointX < dataMin) dataMin = pointX;
}
// y axis
else if (defined(pointY)) {
if (stacking)
typeStack[pointX] = typeStack[pointX] ? typeStack[pointX] + pointY : pointY;
var stackedPoint = typeStack ? typeStack[pointX] : pointY;
if (!usePercentage) {
if (stackedPoint > dataMax) dataMax = stackedPoint;
else if (stackedPoint < dataMin) dataMin = stackedPoint;
}
if (stacking) stacks[serie.type][pointX] = {
total: stackedPoint,
cum: stackedPoint
};
}
});
// For column, areas and bars, set the minimum automatically to zero
// and prevent that minPadding is added in setScale
if (!isXAxis && /(area|column|bar)/.test(serie.type)) {
if (dataMin >= 0) {
dataMin = 0;
ignoreMinPadding = true;
} else if (dataMax < 0) {
dataMax = 0;
ignoreMaxPadding = true;
}
}
}
}
});
};
/**
* Translate from axis value to pixel position on the chart, or back
*
*/
function translate(val, backwards, cvsCoord) {
var sign = 1,
cvsOffset = 0,
returnValue;
if (cvsCoord) {
sign *= -1; // canvas coordinates inverts the value
cvsOffset = axisLength;
}
if (reversed) { // reversed axis
sign *= -1;
cvsOffset -= sign * axisLength;
}
if (backwards) { // reverse translation
if (reversed) val = axisLength - val;
returnValue = val / transA + min; // from chart pixel to value
} else { // normal translation
returnValue = sign * (val - min) * transA + cvsOffset; // from value to chart pixel
}
return returnValue;
};
/**
* Add a single line across the plot
*/
function drawPlotLine(value, color, width) {
if (width) {
var x1,
y1,
x2,
y2,
translatedValue = translate(value),
skip;
x1 = x2 = translatedValue + transB;
y1 = y2 = chartHeight - translatedValue - transB;
if (horiz) { // horizontal axis, vertical plot line
y1 = marginTop;
y2 = chartHeight - marginBottom;
if (x1 < marginLeft || x1 > marginLeft + plotWidth) skip = true;
} else { // vertical axis, horizontal plot line
x1 = marginLeft;
x2 = chartWidth - marginRight;
if (y1 < marginTop || y1 > marginTop + plotHeight) skip = true;
}
if (!skip) gridLayer.drawLine(x1, y1, x2, y2, color, width);
}
};
/**
* Add a masked band across the plot
* @param {Number} from chart axis value
* @param {Number} to chart axis value
* @param {String} color
*/
function drawPlotBand(from, to, color) {
// keep within plot area
from = mathMax(from, min);
to = Math.min(to, max);
var width = (to - from) * transA;
drawPlotLine(from + (to - from) / 2, color, width);
}
/**
* Add a tick mark an a label
*/
function addTick(pos, tickPos, color, width, len, withLabel, index) {
var x1, y1, x2, y2, str, labelOptions = options.labels;
// negate the length
if (tickPos == 'inside') len = -len;
if (opposite) len = -len;
// set the initial positions
x1 = x2 = translate(pos + tickmarkOffset) + transB;
y1 = y2 = chartHeight - translate(pos + tickmarkOffset) - transB;
if (horiz) {
y1 = chartHeight - marginBottom - (opposite ? plotHeight : 0) + offset;
y2 = y1 + len;
} else {
x1 = marginLeft + (opposite ? plotWidth : 0) + offset;
x2 = x1 - len;
}
if (width) axisLayer.drawLine(x1, y1, x2, y2, color, width);
// write the label
if (withLabel && labelOptions.enabled) {
str = labelFormatter.call({
index: index,
isFirst: pos == tickPositions[0],
isLast: pos == tickPositions[tickPositions.length - 1],
value: (categories && categories[pos] ? categories[pos] : pos)
});
if (str || str === 0) axisLayer.addText(
str,
x1 + labelOptions.x - (tickmarkOffset && horiz ? tickmarkOffset * transA * (reversed ? -1 : 1) : 0),
y1 + labelOptions.y - (tickmarkOffset && !horiz ? tickmarkOffset * transA * (reversed ? 1 : -1) : 0),
labelOptions.style,
labelOptions.rotation,
labelOptions.align
);
}
};
/**
* Take an interval and normalize it to multiples of 1, 2, 2.5 and 5
* @param {Number} interval
*/
function normalizeTickInterval(interval, multiples) {
var normalized,
allowDecimals = pick(options.allowDecimals, true);
// round to a tenfold of 1, 2, 2.5 or 5
magnitude = multiples ? 1 : math.pow(10, mathFloor(math.log(interval) / math.LN10));
normalized = interval / magnitude;
// multiples for a linear scale
if (!multiples) multiples = [1, 2, 2.5, 5, 10];
// normalize the interval to the nearest multiple
for (var i = 0; i < multiples.length; i++) {
interval = multiples[i];
if (normalized <= (multiples[i] + (multiples[i+1] || multiples[i])) / 2) {
break;
}
}
// multiply back to the correct magnitude
interval *= magnitude;
return interval;
};
/**
* Set the tick positions to a time unit that makes sense, for example
* on the first of each month or on every Monday.
*/
function setDateTimeTickPositions() {
tickPositions = [];
var useUTC = defaultOptions.global.useUTC,
oneSecond = 1000 / timeFactor,
oneMinute = 60000 / timeFactor,
oneHour = 3600000 / timeFactor,
oneDay = 24 * 3600000 / timeFactor,
oneWeek = 7 * 24 * 3600000 / timeFactor,
oneMonth = 30 * 24 * 3600000 / timeFactor,
oneYear = 31556952000 / timeFactor,
units = [[
'second', // unit name
oneSecond, // fixed incremental unit
[1, 2, 5, 10, 15, 30] // allowed multiples
], [
'minute', // unit name
oneMinute, // fixed incremental unit
[1, 2, 5, 10, 15, 30] // allowed multiples
], [
'hour', // unit name
oneHour, // fixed incremental unit
[1, 2, 3, 4, 6, 8, 12] // allowed multiples
], [
'day', // unit name
oneDay, // fixed incremental unit
[1, 2] // allowed multiples
], [
'week', // unit name
oneWeek, // fixed incremental unit
[1, 2] // allowed multiples
], [
'month',
oneMonth,
[1, 2, 3, 4, 6]
], [
'year',
oneYear,
null
]],
unit = units[6], // default unit is years
interval = unit[1],
multiples = unit[2];
// loop through the units to find the one that best fits the tickInterval
for (var i = 0; i < units.length; i++) {
unit = units[i];
interval = unit[1];
multiples = unit[2];
if (units[i+1]) {
// lessThan is in the middle between the highest multiple and the next unit.
var lessThan = (interval * multiples[multiples.length - 1] +
units[i + 1][1]) / 2;
// break and keep the current unit
if (tickInterval <= lessThan) break;
}
}
// prevent 2.5 years intervals, though 25, 250 etc. are allowed
if (interval == oneYear && tickInterval < 5 * interval)
multiples = [1, 2, 5];
// get the minimum value by flooring the date
var multitude = normalizeTickInterval(tickInterval / interval, multiples),
minYear, // used in months and years as a basis for Date.UTC()
minDate = new Date(min * timeFactor);
minDate.setMilliseconds(0);
if (interval >= oneSecond) // second
minDate.setSeconds(interval >= oneMinute ? 0 :
multitude * mathFloor(minDate.getSeconds() / multitude));
if (interval >= oneMinute) // minute
minDate[setMinutes](interval >= oneHour ? 0 :
multitude * mathFloor(minDate[getMinutes]() / multitude));
if (interval >= oneHour) // hour
minDate[setHours](interval >= oneDay ? 0 :
multitude * mathFloor(minDate[getHours]() / multitude));
if (interval >= oneDay) // day
minDate[setDate](interval >= oneMonth ? 1 :
multitude * mathFloor(minDate[getDate]() / multitude));
if (interval >= oneMonth) { // month
minDate[setMonth](interval >= oneYear ? 0 :
multitude * mathFloor(minDate[getMonth]() / multitude));
minYear = minDate[getFullYear]();
}
if (interval >= oneYear) { // year
minYear -= minYear % multitude;
minDate[setFullYear](minYear);
}
// week is a special case that runs outside the hierarchy
if (interval == oneWeek) {
// get start of current week, independent of multitude
minDate[setDate](minDate[getDate]() - minDate[getDay]() +
options.startOfWeek);
}
// get tick positions
var i = 1, // prevent crash just in case
time = minDate.getTime() / timeFactor,
minYear = minDate[getFullYear](),
minMonth = minDate[getMonth](),
minDateDate = minDate[getDate]();
// iterate and add tick positions at appropriate values
while (time < max && i < plotWidth) {
tickPositions.push(time);
// if the interval is years, use Date.UTC to increase years
if (interval == oneYear) {
time = makeTime(minYear + i * multitude, 0) / timeFactor;
// if the interval is months, use Date.UTC to increase months
} else if (interval == oneMonth) {
time = makeTime(minYear, minMonth + i * multitude) / timeFactor;
// if we're using global time, the interval is not fixed as it jumps
// one hour at the DST crossover
} else if (!useUTC && (interval == oneDay || interval == oneWeek)) {
time = makeTime(minYear, minMonth, minDateDate +
i * multitude * (interval == oneDay ? 1 : 7));
// else, the interval is fixed and we use simple addition
} else {
time += interval * multitude;
}
i++;
}
// push the last time
tickPositions.push(time);
// dynamic label formatter
if (!options.labels.formatter) labelFormatter = function() {
return dateFormat(options.dateTimeLabelFormats[unit[0]], this.value, 1);
}
}
/**
* Set the tick positions of a linear axis to round values like whole tens or every five.
*/
function setLinearTickPositions() {
var correctFloat = function(num) { // JS round off float errors
var invMag = (magnitude < 1 ? mathRound(1 / magnitude) : 1) * 10;
return mathRound(num * invMag) / invMag
},
i,
roundedMin = mathFloor(min / tickInterval) * tickInterval,
roundedMax = math.ceil(max / tickInterval) * tickInterval;
// default extreme ticks when axis does not start and end on a tick
//firstTickPosition = roundedMin + tickInterval,
//lastTickPosition = roundedMax - tickInterval,
//invMag = (magnitude < 1 ? 1 / magnitude : 1) * 10; // round off JS float errors;
tickPositions = [];
// populate the intermediate values
// todo: round off float errors occur here!
i = correctFloat(roundedMin);
while (i <= roundedMax) {
//for (i = roundedMin; i <= roundedMax; i += tickInterval) {
//i = mathRound(i * invMag) / invMag
tickPositions.push(i);
i = correctFloat(i + tickInterval);
}
// pad categorised axis to nearest half unit
if (categories) {
min -= 0.5;
max += 0.5;
}
// dynamic label formatter
if (!labelFormatter) labelFormatter = function() {
return this.value;
}
};
/**
* Set the tick positions to round values and optionally extend the extremes
* to the nearest tick
*/
function setTickPositions() {
if (isDatetimeAxis) setDateTimeTickPositions();
else setLinearTickPositions();
// reset min/max or remove extremes based on start/end on tick
var roundedMin = tickPositions[0],
roundedMax = tickPositions[tickPositions.length - 1];
if (options.startOnTick) {
min = roundedMin;
} else if (min > roundedMin) {
tickPositions.shift();
}
if (options.endOnTick) {
max = roundedMax;
} else if (max < roundedMax) {
tickPositions.pop();
}
}
/**
* When using multiple axes, adjust the number of ticks to match the highest
* number of ticks in that group
*/
function adjustTickAmount() {
if (!isDatetimeAxis && !categories) { // only apply to linear scale
var oldTickAmount = tickAmount,
calculatedTickAmount = tickPositions.length;
// set the axis-level tickAmount to use below
tickAmount = maxTicks[xOrY];
if (calculatedTickAmount < tickAmount) {
while (tickPositions.length < tickAmount)
tickPositions.push(tickPositions[tickPositions.length - 1] + tickInterval);
transA *= (calculatedTickAmount - 1) / (tickAmount - 1);
}
if (defined(oldTickAmount) && tickAmount != oldTickAmount) axis.isDirty = true;
}
};
/**
* Set the scale based on data min and max, user set min and max or options
*/
function setScale() {
var length,
type,
i,
total,
oldMin = min,
oldMax = max,
maxZoom = options.maxZoom,
zoomOffset;
// get data extremes if needed
getSeriesExtremes();
// initial min and max from the extreme data values
min = pick(userSetMin, options.min, dataMin);
max = pick(userSetMax, options.max, dataMax);
// maxZoom exceeded, just center the selection
if (max - min < maxZoom) {
zoomOffset = (maxZoom - max + min) / 2;
// if min and max options have been set, don't go beyond it
min = mathMax(min - zoomOffset, pick(options.min, min - zoomOffset));
max = math.min(min + maxZoom, pick(options.max, min + maxZoom));
}
// pad the values to get clear of the chart's edges
if (!categories && !usePercentage) {
length = (max - min) || 1;
if (!defined(options.min) && minPadding && (dataMin < 0 || !ignoreMinPadding))
min -= length * minPadding;
if (!defined(options.max) && maxPadding && (dataMax > 0 || !ignoreMaxPadding))
max += length * maxPadding;
}
// tickInterval
if (categories || min == max) tickInterval = 1;
else tickInterval = options.tickInterval == 'auto' ?
(max - min) * options.tickPixelInterval / axisLength :
options.tickInterval;
if (!isDatetimeAxis && options.tickInterval == 'auto') // linear
tickInterval = normalizeTickInterval(tickInterval);
// minorTickInterval
minorTickInterval = (options.minorTickInterval == 'auto' && tickInterval) ?
tickInterval / 5 : options.minorTickInterval;
// get fixed positions based on tickInterval
setTickPositions();
// the translation factor used in translate function
transA = axisLength / ((max - min) || 1);
// record the greatest number of ticks for multi axis
if (!maxTicks) maxTicks = { // first call, or maxTicks have been reset after a zoom operation
x: 0,
y: 0
};
if (!isDatetimeAxis && tickPositions.length > maxTicks[xOrY])
maxTicks[xOrY] = tickPositions.length;
// reset stacks
//if (!isXAxis) for (type in stacks) each (stacks[type], function(stack, i) {
if (!isXAxis) for (type in stacks) for (i in stacks[type]) {
stacks[type][i].cum = stacks[type][i].total;
}
// mark as dirty
axis.isDirty = (min != oldMin || max != oldMax);
};
/**
* Set the extremes and optionally redraw
* @param {Number} newMin
* @param {Number} newMax
* @param {Boolean} redraw
*
*/
function setExtremes(newMin, newMax, redraw) {
redraw = pick(redraw, true); // defaults to true
fireEvent(axis, 'setExtremes', { // fire an event to enable syncing of multiple charts
min: newMin,
max: newMax
}, function() { // the default event handler
// make sure categorized axes are not exceeded
if (categories) {
if (newMin < 0) newMin = 0;
if (newMax > categories.length - 1) newMax = categories.length - 1;
}
// set the new values
//userSetMin = pick(newMin, min);
//userSetMax = pick(newMax, max);
//if (defined(newMin)) userSetMin = newMin;
//if (defined(newMax)) userSetMax = newMax;
// this fails on zooming when a series is hidden and ignoreHiddenSeries is true
//userSetMin = pick(newMin, options.min, dataMin);
//userSetMax = pick(newMax, options.max, dataMax);
userSetMin = newMin;
userSetMax = newMax;
// redraw
if (redraw) chart.redraw();
});
};
/**
* Set new axis categories and optionally redraw
* @param {Array} newCategories
* @param {Boolean} doRedraw
*/
function setCategories(newCategories, doRedraw) {
categories = newCategories;
if (pick(doRedraw, true)) redraw();
};
/* *
* Reset min and max and set the scale again from data min and max
* /
function reset() {
//min = max = tickInterval = minorTickInterval = tickPositions = null;
setScale();
}*/
/**
* Get the actual axis extremes
*/
function getExtremes() {
return {
min: min,
max: max,
dataMin: dataMin,
dataMax: dataMax
}
}
/**
* Add a plot band or plot line after render time
*
* @param item {Object} The plotBand or plotLine configuration object
*/
function addPlotBandOrLine(item) {
var isLine = item.width,
collection = isLine ? plotLines : plotBands;
collection.push(item);
if (isLine) drawPlotLine(item.value, item.color, item.width);
else drawPlotBand(item.from, item.to, item.color);
}
/**
* Remove a plot band or plot line from the chart by id
* @param {Object} id
*/
function removePlotBandOrLine(id) {
each ([plotBands, plotLines], function(collection) {
for (var i = 0; i < collection.length; i++) {
if (collection[i].id == id) {
collection.splice(i, 1);
break;
}
}
});
render();
}
/**
* Redraw the axis to reflect changes in the data or axis extremes
*/
function redraw() {
// hide tooltip and hover states
if (tracker.resetTracker) tracker.resetTracker();
// render the axis
render();
// mark associated series as dirty and ready for redraw
each (associatedSeries, function(series) {
series.isDirty = true;
});
}
function render() {
var axisTitle = options.title,
alternateGridColor = options.alternateGridColor,
minorTickWidth = options.minorTickWidth,
lineWidth = options.lineWidth,
lineLeft,
lineTop,
tickmarkPos,
hasData = associatedSeries.length && defined(min) && defined(max);
// clear the axis layers before new grid and ticks are drawn
axisLayer.clear();
gridLayer.clear();
// return if there's no series on this axis
//if (!associatedSeries.length || !defined(min) || !defined(max)) return;
// If the series has data draw the ticks. Else only the line and title
if (hasData) {
// alternate grid color
if (alternateGridColor) {
each(tickPositions, function(pos, i) {
if (i % 2 == 0 && pos < max) {
drawPlotBand(
pos,
tickPositions[i + 1] !== undefined ? tickPositions[i + 1] : max,
alternateGridColor
);
}
});
}
// custom plot bands (behind grid lines)
each (plotBands, function(plotBand) {
drawPlotBand(plotBand.from, plotBand.to, plotBand.color);
});
// minor grid lines
if (minorTickInterval && !categories) for (var i = min; i <= max; i += minorTickInterval) {
drawPlotLine(i, options.minorGridLineColor, options.minorGridLineWidth);
if (minorTickWidth) addTick(
i,
options.minorTickPosition,
options.minorTickColor,
minorTickWidth,
options.minorTickLength
);
}
// grid lines and tick marks
each(tickPositions, function(pos, index) {
tickmarkPos = pos + tickmarkOffset;
// add the grid line
drawPlotLine(tickmarkPos, options.gridLineColor, options.gridLineWidth);
// add the tick mark
addTick(
pos,
options.tickPosition,
options.tickColor,
options.tickWidth,
options.tickLength,
!((pos == min && !options.showFirstLabel) || (pos == max && !options.showLastLabel)),
index
);
});
// custom plot lines (in front of grid lines)
each (plotLines, function(plotLine) {
drawPlotLine(plotLine.value, plotLine.color, plotLine.width);
});
} // end if hasData
// axis line
if (lineWidth) {
lineLeft = marginLeft + (opposite ? plotWidth : 0) + offset;
lineTop = chartHeight - marginBottom - (opposite ? plotHeight : 0) + offset;
axisLayer.drawLine(
horiz ?
marginLeft:
lineLeft,
horiz ?
lineTop:
marginTop,
horiz ?
chartWidth - marginRight :
lineLeft,
horiz ?
lineTop:
chartHeight - marginBottom,
options.lineColor,
lineWidth
);
}
// title
if (axisTitle && axisTitle.enabled && axisTitle.text) {
// compute anchor points for each of the title align options
var margin = horiz ?
marginLeft : marginTop,
length = horiz ? plotWidth : plotHeight;
// the position in the length direction of the axis
var alongAxis = {
low: margin + (horiz ? 0 : length),
middle: margin + length / 2,
high: margin + (horiz ? length : 0)
}[axisTitle.align];
// the position in the perpendicular direction of the axis
var offAxis = (horiz ? marginTop + plotHeight : marginLeft) +
(horiz ? 1 : -1) * // horizontal axis reverses the margin
(opposite ? -1 : 1) * // so does opposite axes
axisTitle.margin
- (isIE ? parseInt(
axisTitle.style.fontSize || axisTitle.style.font.replace(/^[a-z ]+/, '')
) / 3 : 0); // preliminary fix for vml's centerline
axisLayer.addText(
axisTitle.text,
horiz ?
alongAxis:
offAxis + (opposite ? plotWidth : 0) + offset, // x
horiz ?
offAxis - (opposite ? plotHeight : 0) + offset:
alongAxis, // y
axisTitle.style,
axisTitle.rotation || 0,
{ low: 'left', middle: 'center', high: 'right' }[axisTitle.align]
);
}
// stroke tick labels and title
axisLayer.strokeText();
axis.isDirty = false;
};
// Run Axis
var isXAxis = options.isX,
opposite = options.opposite, // needed in setOptions
horiz = inverted ? !isXAxis : isXAxis,
stacks = {
bar: {},
column: {},
area: {},
areaspline: {}
};
setOptions(); // do the merging
var axis = this,
isDatetimeAxis = options.type == 'datetime',
offset = options.offset || 0,
xOrY = isXAxis ? 'x' : 'y',
axisLength = horiz ? plotWidth : plotHeight,
transA, // translation factor
transB = horiz ? marginLeft : marginBottom, // translation addend
axisLayer = new Layer('axis-layer', container, null, { zIndex: 7}), /* The
axis layer is in front of the series because the axis line must hide
graphs and bars. Grid lines are drawn on the grid layer. */
gridLayer = new Layer('grid-layer', container, null, { zIndex: 1 }),
dataMin,
dataMax,
associatedSeries,
userSetMin,
userSetMax,
max = null,
min = null,
minPadding = options.minPadding,
maxPadding = options.maxPadding,
ignoreMinPadding, // can be set to true by a column or bar series
ignoreMaxPadding,
usePercentage,
events = options.events,
eventType,
plotBands = options.plotBands || [],
plotLines = options.plotLines || [],
tickInterval,
minorTickInterval,
magnitude,
tickPositions, // array containing predefined positions
tickAmount,
zoom = 1,
//var axisLabelsLayer = new Layer((horiz ? 'x' : 'y') +'-axis-labels');
labelFormatter = options.labels.formatter, // can be overwritten by dynamic format
// column plots are always categorized
categories = options.categories || (isXAxis && chart.columnCount),
reversed = options.reversed,
tickmarkOffset = (categories && options.tickmarkPlacement == 'between') ? 0.5 : 0;
//var hasWrittenTitle;
// inverted charts have reversed xAxes as default
if (inverted && isXAxis && reversed === undefined) reversed = true;
// negate offset
if (!opposite) offset *= -1;
if (horiz) offset *= -1;
// expose some variables
extend (axis, {
addPlotBand: addPlotBandOrLine,
addPlotLine: addPlotBandOrLine,
adjustTickAmount: adjustTickAmount,
categories: categories,
getExtremes: getExtremes,
isXAxis: isXAxis,
options: options,
render: render,
setExtremes: setExtremes,
setScale: setScale,
setCategories: setCategories,
translate: translate,
redraw: redraw,
removePlotBand: removePlotBandOrLine,
removePlotLine: removePlotBandOrLine,
//reset: reset,
reversed: reversed,
stacks: stacks
});
// register event listeners
for (eventType in events) {
addEvent(axis, eventType, events[eventType]);
}
// set min and max
setScale();
}; // end Axis
function Toolbar(chart) {
var toolbarLayer, buttons = {};
toolbarLayer = new Layer('toolbar', container, null, {
zIndex: 1004,
width: 'auto',
height: 'auto'
});
function add(id, text, title, fn) {
if (!buttons[id]) {
var button = createElement(DIV, {
innerHTML: text,
title: title,
onclick: fn
}, extend(options.toolbar.itemStyle, {
zIndex: 1003
}), toolbarLayer.div);
buttons[id] = button;
}
}
function remove(id) {
discardElement(buttons[id]);
buttons[id] = null;
}
// public
return {
add: add,
remove: remove
}
};
function MouseTracker (chart, options) {
/**
* Get the currently hovered point
*/
function getActivePoint() {
return activePoint;
};
/**
* Add IE support for pageX and pageY
* @param {Object} e The event object in standard browsers
*/
function normalizeMouseEvent(e) {
// common IE normalizing
e = e || win.event;
if (!e.target) e.target = e.srcElement;
// pageX and pageY
if (!e.pageX)
e.pageX = e.clientX + (doc.documentElement.scrollLeft || doc.body.scrollLeft);
if (!e.pageY)
e.pageY = e.clientY + (doc.documentElement.scrollTop || doc.body.scrollTop);
return e;
}
/**
* Get the click position in terms of axis values.
*
* @param {Object} e A mouse event
*/
function getMouseCoordinates(e) {
var coordinates = {
xAxis: [],
yAxis: []
};
each (axes, function(axis, i) {
var translate = axis.translate,
isXAxis = axis.isXAxis,
isHorizontal = inverted ? !isXAxis : isXAxis;
coordinates[isXAxis ? 'xAxis' : 'yAxis'].push({
axis: axis,
value: translate(
isHorizontal ?
e.pageX - position.x - marginLeft :
plotHeight - e.pageY + position.y + marginTop ,
true
)
})
});
return coordinates;
}
/* *
* Drop a point after dragging to change it's value
*
* @todo:
* - x dimension
* /
function dropDragPoint() {
if (hasDragged && dragPoint) {
var yAxis = dragPointCoordinates.yAxis,
i = 0;
// identify the point's yAxis
for (i; i < yAxis.length; i++) {
if (yAxis[i].axis == dragPoint.series.yAxis) {
break;
}
}
// update the point
dragPoint.update(yAxis[i].value);
dragPoint = null;
}
}
*/
/**
* Set the JS events on the container element
*/
function setDOMEvents () {
imagemap.onmousedown = function(e) {
e = normalizeMouseEvent(e);
// record the start position
if (e.preventDefault) e.preventDefault();
chart.mouseIsDown = mouseIsDown = true;
mouseDownX = e.pageX;
mouseDownY = e.pageY;
// make a selection
if (hasCartesianSeries && (zoomX || zoomY)) {
if (!selectionMarker) selectionMarker = createElement(DIV, null, {
position: ABSOLUTE,
border: 'none',
background: '#4572A7',
opacity: 0.25,
width: zoomHor ? 0 : plotWidth + PX,
height: zoomVert ? 0 : plotHeight + PX
});
plotLayer.div.appendChild(selectionMarker);
}
// drag a point
/* else if (activePoint && e.target.tagName == 'AREA') {
var seriesOptions = activePoint.series.options,
dragType = seriesOptions.dragType;
if (seriesOptions.allowDrag) {
allowXDrag = /x/.test(dragType);
allowYDrag = /y/.test(dragType);
}
// define the point
if (allowXDrag || allowYDrag) dragPoint = activePoint;
}
*/
};
// Use native browser event for this one. It's faster, and MooTools
// doesn't use clientX and clientY.
imagemap.onmousemove = function(e) {
e = normalizeMouseEvent(e);
e.returnValue = false;
if (mouseIsDown) { // make selection
// determine if the mouse has moved more than 10px
hasDragged = Math.sqrt(
Math.pow(mouseDownX - e.pageX, 2) +
Math.pow(mouseDownY - e.pageY, 2)
) > 10;
// adjust the width of the selection marker
if (zoomHor) {
var xSize = e.pageX - mouseDownX;
setStyles(selectionMarker, {
width: mathAbs(xSize) + PX,
left: ((xSize > 0 ? 0 : xSize)
+ mouseDownX - position.x - marginLeft) + PX
});
}
// adjust the height of the selection marker
if (zoomVert) {
var ySize = e.pageY - mouseDownY;
setStyles(selectionMarker, {
height: mathAbs(ySize) + PX,
top: ((ySize > 0 ? 0 : ySize) +
+ mouseDownY - position.y - marginTop) + PX
});
}
/* Removed to prevent bloating. Can be added as a separate component later.
// drag a point
if (hasDragged && dragPoint) {
// draw the hover point
dragPoint.series.drawPointState(dragPoint, 'hover');
// record the coordinates
dragPointCoordinates = getMouseCoordinates(e);
if (allowXDrag) {
// update the plot coordinates
dragPoint.plotX = e.pageX - position.x - marginLeft;
// get the tooltip text and refresh the tooltip
dragPoint.x = dragPoint.series.xAxis.translate(
dragPoint.plotX,
true
);
}
if (allowYDrag) {
// update the plot coordinates
dragPoint.plotY = e.pageY - position.y - marginTop;
// get the tooltip text and refresh the tooltip
dragPoint.y = dragPoint.series.yAxis.translate(
plotHeight - dragPoint.plotY,
true
);
}
// adjust height for columns
dragPoint.h = (dragPoint.yBottom || dragPoint.y0) - dragPoint.plotY;
dragPoint.setTooltipText();
tooltip.refresh(dragPoint, dragPoint.series);
}
*/
} else {
// show the tooltip
onmousemove(e);
}
return false;
};
imagemap.onmouseup = function() {
var selectionIsMade;
if (selectionMarker) {
var selectionData = {
xAxis: [],
yAxis: []
},
selectionLeft = selectionMarker.offsetLeft,
selectionTop = selectionMarker.offsetTop,
selectionWidth = selectionMarker.offsetWidth,
selectionHeight = selectionMarker.offsetHeight;
// a selection has been made
if (hasDragged) {
// record each axis' min and max
each (axes, function(axis, i) {
var translate = axis.translate,
isXAxis = axis.isXAxis,
isHorizontal = inverted ? !isXAxis : isXAxis,
selectionMin = translate(
isHorizontal ?
selectionLeft :
plotHeight - selectionTop - selectionHeight,
true
),
selectionMax = translate(
isHorizontal ?
selectionLeft + selectionWidth :
plotHeight - selectionTop,
true
);
selectionData[isXAxis ? 'xAxis' : 'yAxis'].push({
axis: axis,
min: math.min(selectionMin, selectionMax), // for reversed axes
max: mathMax(selectionMin, selectionMax)
});
});
fireEvent(chart, 'selection', selectionData, zoom);
selectionIsMade = true;
}
discardElement(selectionMarker);
selectionMarker = null;
}
chart.mouseIsDown = mouseIsDown = hasDragged = false;
/*
else {
dropDragPoint();
}*/
};
// MooTools 1.2.4 doesn't handle this 'mouseleave' in IE
imagemap.onmouseout = function(e) {
e = e || win.event;
var related = e.relatedTarget || e.toElement;
// check that the mouse has really left the imagemap
if (related && related != trackerImage && related.tagName != 'AREA') {
// reset the tracker
resetTracker();
// if the user is pushing a point, drop it
//dropDragPoint();
// reset mouseIsDown and hasDragged
chart.mouseIsDown = mouseIsDown = hasDragged = false;
}
}
// MooTools 1.2.3 doesn't fire this in IE when using addEvent
imagemap.onclick = function(e) {
e = normalizeMouseEvent(e);
e.cancelBubble = true; // IE specific
if (!hasDragged) {
if (activePoint && e.target.tagName == 'AREA') {
var plotX = activePoint.plotX,
plotY = activePoint.plotY;
// add page position info
extend(activePoint, {
pageX: position.x + marginLeft +
(inverted ? plotWidth - plotY : plotX),
pageY: position.y + marginTop +
(inverted ? plotHeight - plotX : plotY)
});
// the series click event
fireEvent(chart.hoverSeries, 'click', extend(e, {
point: activePoint
}));
// the point click event
activePoint.firePointEvent('click', e);
} else {
extend (e, getMouseCoordinates(e));
// fire a click event in the chart
fireEvent(chart, 'click', e);
}
}
// reset mouseIsDown and hasDragged
//chart.mouseIsDown = mouseIsDown = hasDragged = false;
hasDragged = false;
};
};
/**
* Refresh the tooltip on mouse move
*/
function onmousemove (e) {
var point = chart.hoverPoint,
series = chart.hoverSeries;
if (series) {
// get the point
if (!point) point = series.tooltipPoints[
inverted ?
e.pageY - position.y - marginTop :
e.pageX - position.x - marginLeft
];
// a new point is hovered, refresh the tooltip
if (point && point != activePoint) {
// trigger the events
if (activePoint) activePoint.firePointEvent('mouseOut');
point.firePointEvent('mouseOver');
// refresh the tooltip
if (tooltip) tooltip.refresh(point);
activePoint = point;
}
}
};
/**
* Create the image map that listens for mouseovers
*/
function createImageMap () {
var id = 'highchartsMap'+ canvasCounter++;
chart.imagemap = imagemap = createElement('map', {
name: id,
id: id,
className: 'highcharts-image-map'
}, null, container);
// Append the image to the image map to allow events to
// bubble up
trackerImage = createElement('img', {
useMap: '#'+ id
}, {
width: plotWidth + PX,
height: plotHeight + PX,
left: marginLeft + PX,
top: marginTop + PX,
opacity: 0,
border: 'none',
position: ABSOLUTE,
// Workaround: if not clipped, the left axis will flicker in
// IE8 when hovering the chart
clip: 'rect(1px,'+ plotWidth +'px,'+ plotHeight +'px,1px)',
zIndex: 9
}, imagemap);
// Blank image for modern browsers. IE doesn't need a valid
// image for the image map to work, and fails in SSL mode
// if it's present.
if (!isIE) trackerImage.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==';
};
/**
* Reset the tracking by hiding the tooltip, the hover series state and the hover point
*/
function resetTracker() {
// hide the tooltip
if (tooltip) tooltip.hide();
// hide the hovered series and point
if (chart.hoverSeries) {
chart.hoverSeries.setState();
chart.hoverSeries = null;
activePoint = null;
}
}
/**
* Bring a specific area to the front so that the user can follow a line. The
* legend area should always stay on top. Series tracker areas are brought to the
* top after the legend area.
* @param {Object} area The area DOM element
*/
function insertAtFront(area) {
var before = 0,
i,
childNodes = imagemap.childNodes;
for (i = 0; i < childNodes.length; i++) {
if (childNodes[i].isLegendArea) {
before = i + 1;
break;
}
}
imagemap.insertBefore(area, childNodes[before]);
}
//if (!options.enabled) return;
// Run MouseTracker
var activePoint,
mouseDownX,
mouseDownY,
hasDragged,
selectionMarker,
/*dragPoint,
dragPointCoordinates,
allowXDrag,
allowYDrag,*/
zoomType = optionsChart.zoomType,
zoomX = /x/.test(zoomType),
zoomY = /y/.test(zoomType),
zoomHor = zoomX && !inverted || zoomY && inverted,
zoomVert = zoomY && !inverted || zoomX && inverted;
// public
createImageMap();
if (options.enabled) chart.tooltip = tooltip = Tooltip(options);
setDOMEvents();
// set the fixed interval ticking for the smooth tooltip
setInterval(function() {
if (tooltipTick) tooltipTick();
}, 32);
// expose properties
extend (this, {
insertAtFront: insertAtFront,
zoomX: zoomX,
zoomY: zoomY,
resetTracker: resetTracker
});
};
/**
* The overview of the chart's series
* @param {Object} chart
*/
var Legend = function(chart) {
// already existing
//if (chart.legend) return;
var options = chart.options.legend;
if (!options.enabled) return;
var li,
layout = options.layout,
symbolWidth = options.symbolWidth,
dom,
topRule = '#'+ container.id +' .highcharts-legend li', // apply once for each chart
allItems = [],
legendLayer = new Layer('legend', container, null, { zIndex: 7 }),
legendArea,
series = chart.series,
reversedLegend = options.reversed;
// Don't use Layer prototype because this needs to sit above the chart in zIndex
this.dom = dom = createElement(DIV, {
className: 'highcharts-legend highcharts-legend-'+ layout,
innerHTML: '