Added more updates
[soho-sigint.git] / client-freqwatch / Chart.js / src / Chart.Core.js
1 /*!
2  * Chart.js
3  * http://chartjs.org/
4  * Version: {{ version }}
5  *
6  * Copyright 2015 Nick Downie
7  * Released under the MIT license
8  * https://github.com/nnnick/Chart.js/blob/master/LICENSE.md
9  */
10
11
12 (function(){
13
14         "use strict";
15
16         //Declare root variable - window in the browser, global on the server
17         var root = this,
18                 previous = root.Chart;
19
20         //Occupy the global variable of Chart, and create a simple base class
21         var Chart = function(context){
22                 var chart = this;
23                 this.canvas = context.canvas;
24
25                 this.ctx = context;
26
27                 //Variables global to the chart
28                 var computeDimension = function(element,dimension)
29                 {
30                         if (element['offset'+dimension])
31                         {
32                                 return element['offset'+dimension];
33                         }
34                         else
35                         {
36                                 return document.defaultView.getComputedStyle(element).getPropertyValue(dimension);
37                         }
38                 };
39
40                 var width = this.width = computeDimension(context.canvas,'Width') || context.canvas.width;
41                 var height = this.height = computeDimension(context.canvas,'Height') || context.canvas.height;
42
43                 // Firefox requires this to work correctly
44                 context.canvas.width  = width;
45                 context.canvas.height = height;
46
47                 width = this.width = context.canvas.width;
48                 height = this.height = context.canvas.height;
49                 this.aspectRatio = this.width / this.height;
50                 //High pixel density displays - multiply the size of the canvas height/width by the device pixel ratio, then scale.
51                 helpers.retinaScale(this);
52
53                 return this;
54         };
55         //Globally expose the defaults to allow for user updating/changing
56         Chart.defaults = {
57                 global: {
58                         // Boolean - Whether to animate the chart
59                         animation: true,
60
61                         // Number - Number of animation steps
62                         animationSteps: 60,
63
64                         // String - Animation easing effect
65                         animationEasing: "easeOutQuart",
66
67                         // Boolean - If we should show the scale at all
68                         showScale: true,
69
70                         // Boolean - If we want to override with a hard coded scale
71                         scaleOverride: false,
72
73                         // ** Required if scaleOverride is true **
74                         // Number - The number of steps in a hard coded scale
75                         scaleSteps: null,
76                         // Number - The value jump in the hard coded scale
77                         scaleStepWidth: null,
78                         // Number - The scale starting value
79                         scaleStartValue: null,
80
81                         // String - Colour of the scale line
82                         scaleLineColor: "rgba(0,0,0,.1)",
83
84                         // Number - Pixel width of the scale line
85                         scaleLineWidth: 1,
86
87                         // Boolean - Whether to show labels on the scale
88                         scaleShowLabels: true,
89
90                         // Interpolated JS string - can access value
91                         scaleLabel: "<%=value%>",
92
93                         // Boolean - Whether the scale should stick to integers, and not show any floats even if drawing space is there
94                         scaleIntegersOnly: true,
95
96                         // Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
97                         scaleBeginAtZero: false,
98
99                         // String - Scale label font declaration for the scale label
100                         scaleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
101
102                         // Number - Scale label font size in pixels
103                         scaleFontSize: 12,
104
105                         // String - Scale label font weight style
106                         scaleFontStyle: "normal",
107
108                         // String - Scale label font colour
109                         scaleFontColor: "#666",
110
111                         // Boolean - whether or not the chart should be responsive and resize when the browser does.
112                         responsive: false,
113
114                         // Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
115                         maintainAspectRatio: true,
116
117                         // Boolean - Determines whether to draw tooltips on the canvas or not - attaches events to touchmove & mousemove
118                         showTooltips: true,
119
120                         // Boolean - Determines whether to draw built-in tooltip or call custom tooltip function
121                         customTooltips: false,
122
123                         // Array - Array of string names to attach tooltip events
124                         tooltipEvents: ["mousemove", "touchstart", "touchmove", "mouseout"],
125
126                         // String - Tooltip background colour
127                         tooltipFillColor: "rgba(0,0,0,0.8)",
128
129                         // String - Tooltip label font declaration for the scale label
130                         tooltipFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
131
132                         // Number - Tooltip label font size in pixels
133                         tooltipFontSize: 14,
134
135                         // String - Tooltip font weight style
136                         tooltipFontStyle: "normal",
137
138                         // String - Tooltip label font colour
139                         tooltipFontColor: "#fff",
140
141                         // String - Tooltip title font declaration for the scale label
142                         tooltipTitleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
143
144                         // Number - Tooltip title font size in pixels
145                         tooltipTitleFontSize: 14,
146
147                         // String - Tooltip title font weight style
148                         tooltipTitleFontStyle: "bold",
149
150                         // String - Tooltip title font colour
151                         tooltipTitleFontColor: "#fff",
152
153                         // Number - pixel width of padding around tooltip text
154                         tooltipYPadding: 6,
155
156                         // Number - pixel width of padding around tooltip text
157                         tooltipXPadding: 6,
158
159                         // Number - Size of the caret on the tooltip
160                         tooltipCaretSize: 8,
161
162                         // Number - Pixel radius of the tooltip border
163                         tooltipCornerRadius: 6,
164
165                         // Number - Pixel offset from point x to tooltip edge
166                         tooltipXOffset: 10,
167
168                         // String - Template string for single tooltips
169                         tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>",
170
171                         // String - Template string for single tooltips
172                         multiTooltipTemplate: "<%= value %>",
173
174                         // String - Colour behind the legend colour block
175                         multiTooltipKeyBackground: '#fff',
176
177                         // Function - Will fire on animation progression.
178                         onAnimationProgress: function(){},
179
180                         // Function - Will fire on animation completion.
181                         onAnimationComplete: function(){}
182
183                 }
184         };
185
186         //Create a dictionary of chart types, to allow for extension of existing types
187         Chart.types = {};
188
189         //Global Chart helpers object for utility methods and classes
190         var helpers = Chart.helpers = {};
191
192                 //-- Basic js utility methods
193         var each = helpers.each = function(loopable,callback,self){
194                         var additionalArgs = Array.prototype.slice.call(arguments, 3);
195                         // Check to see if null or undefined firstly.
196                         if (loopable){
197                                 if (loopable.length === +loopable.length){
198                                         var i;
199                                         for (i=0; i<loopable.length; i++){
200                                                 callback.apply(self,[loopable[i], i].concat(additionalArgs));
201                                         }
202                                 }
203                                 else{
204                                         for (var item in loopable){
205                                                 callback.apply(self,[loopable[item],item].concat(additionalArgs));
206                                         }
207                                 }
208                         }
209                 },
210                 clone = helpers.clone = function(obj){
211                         var objClone = {};
212                         each(obj,function(value,key){
213                                 if (obj.hasOwnProperty(key)){
214                                         objClone[key] = value;
215                                 }
216                         });
217                         return objClone;
218                 },
219                 extend = helpers.extend = function(base){
220                         each(Array.prototype.slice.call(arguments,1), function(extensionObject) {
221                                 each(extensionObject,function(value,key){
222                                         if (extensionObject.hasOwnProperty(key)){
223                                                 base[key] = value;
224                                         }
225                                 });
226                         });
227                         return base;
228                 },
229                 merge = helpers.merge = function(base,master){
230                         //Merge properties in left object over to a shallow clone of object right.
231                         var args = Array.prototype.slice.call(arguments,0);
232                         args.unshift({});
233                         return extend.apply(null, args);
234                 },
235                 indexOf = helpers.indexOf = function(arrayToSearch, item){
236                         if (Array.prototype.indexOf) {
237                                 return arrayToSearch.indexOf(item);
238                         }
239                         else{
240                                 for (var i = 0; i < arrayToSearch.length; i++) {
241                                         if (arrayToSearch[i] === item) return i;
242                                 }
243                                 return -1;
244                         }
245                 },
246                 where = helpers.where = function(collection, filterCallback){
247                         var filtered = [];
248
249                         helpers.each(collection, function(item){
250                                 if (filterCallback(item)){
251                                         filtered.push(item);
252                                 }
253                         });
254
255                         return filtered;
256                 },
257                 findNextWhere = helpers.findNextWhere = function(arrayToSearch, filterCallback, startIndex){
258                         // Default to start of the array
259                         if (!startIndex){
260                                 startIndex = -1;
261                         }
262                         for (var i = startIndex + 1; i < arrayToSearch.length; i++) {
263                                 var currentItem = arrayToSearch[i];
264                                 if (filterCallback(currentItem)){
265                                         return currentItem;
266                                 }
267                         }
268                 },
269                 findPreviousWhere = helpers.findPreviousWhere = function(arrayToSearch, filterCallback, startIndex){
270                         // Default to end of the array
271                         if (!startIndex){
272                                 startIndex = arrayToSearch.length;
273                         }
274                         for (var i = startIndex - 1; i >= 0; i--) {
275                                 var currentItem = arrayToSearch[i];
276                                 if (filterCallback(currentItem)){
277                                         return currentItem;
278                                 }
279                         }
280                 },
281                 inherits = helpers.inherits = function(extensions){
282                         //Basic javascript inheritance based on the model created in Backbone.js
283                         var parent = this;
284                         var ChartElement = (extensions && extensions.hasOwnProperty("constructor")) ? extensions.constructor : function(){ return parent.apply(this, arguments); };
285
286                         var Surrogate = function(){ this.constructor = ChartElement;};
287                         Surrogate.prototype = parent.prototype;
288                         ChartElement.prototype = new Surrogate();
289
290                         ChartElement.extend = inherits;
291
292                         if (extensions) extend(ChartElement.prototype, extensions);
293
294                         ChartElement.__super__ = parent.prototype;
295
296                         return ChartElement;
297                 },
298                 noop = helpers.noop = function(){},
299                 uid = helpers.uid = (function(){
300                         var id=0;
301                         return function(){
302                                 return "chart-" + id++;
303                         };
304                 })(),
305                 warn = helpers.warn = function(str){
306                         //Method for warning of errors
307                         if (window.console && typeof window.console.warn === "function") console.warn(str);
308                 },
309                 amd = helpers.amd = (typeof define === 'function' && define.amd),
310                 //-- Math methods
311                 isNumber = helpers.isNumber = function(n){
312                         return !isNaN(parseFloat(n)) && isFinite(n);
313                 },
314                 max = helpers.max = function(array){
315                         return Math.max.apply( Math, array );
316                 },
317                 min = helpers.min = function(array){
318                         return Math.min.apply( Math, array );
319                 },
320                 cap = helpers.cap = function(valueToCap,maxValue,minValue){
321                         if(isNumber(maxValue)) {
322                                 if( valueToCap > maxValue ) {
323                                         return maxValue;
324                                 }
325                         }
326                         else if(isNumber(minValue)){
327                                 if ( valueToCap < minValue ){
328                                         return minValue;
329                                 }
330                         }
331                         return valueToCap;
332                 },
333                 getDecimalPlaces = helpers.getDecimalPlaces = function(num){
334                         if (num%1!==0 && isNumber(num)){
335                                 var s = num.toString();
336                                 if(s.indexOf("e-") < 0){
337                                         // no exponent, e.g. 0.01
338                                         return s.split(".")[1].length;
339                                 }
340                                 else if(s.indexOf(".") < 0) {
341                                         // no decimal point, e.g. 1e-9
342                                         return parseInt(s.split("e-")[1]);
343                                 }
344                                 else {
345                                         // exponent and decimal point, e.g. 1.23e-9
346                                         var parts = s.split(".")[1].split("e-");
347                                         return parts[0].length + parseInt(parts[1]);
348                                 }
349                         }
350                         else {
351                                 return 0;
352                         }
353                 },
354                 toRadians = helpers.radians = function(degrees){
355                         return degrees * (Math.PI/180);
356                 },
357                 // Gets the angle from vertical upright to the point about a centre.
358                 getAngleFromPoint = helpers.getAngleFromPoint = function(centrePoint, anglePoint){
359                         var distanceFromXCenter = anglePoint.x - centrePoint.x,
360                                 distanceFromYCenter = anglePoint.y - centrePoint.y,
361                                 radialDistanceFromCenter = Math.sqrt( distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
362
363
364                         var angle = Math.PI * 2 + Math.atan2(distanceFromYCenter, distanceFromXCenter);
365
366                         //If the segment is in the top left quadrant, we need to add another rotation to the angle
367                         if (distanceFromXCenter < 0 && distanceFromYCenter < 0){
368                                 angle += Math.PI*2;
369                         }
370
371                         return {
372                                 angle: angle,
373                                 distance: radialDistanceFromCenter
374                         };
375                 },
376                 aliasPixel = helpers.aliasPixel = function(pixelWidth){
377                         return (pixelWidth % 2 === 0) ? 0 : 0.5;
378                 },
379                 splineCurve = helpers.splineCurve = function(FirstPoint,MiddlePoint,AfterPoint,t){
380                         //Props to Rob Spencer at scaled innovation for his post on splining between points
381                         //http://scaledinnovation.com/analytics/splines/aboutSplines.html
382                         var d01=Math.sqrt(Math.pow(MiddlePoint.x-FirstPoint.x,2)+Math.pow(MiddlePoint.y-FirstPoint.y,2)),
383                                 d12=Math.sqrt(Math.pow(AfterPoint.x-MiddlePoint.x,2)+Math.pow(AfterPoint.y-MiddlePoint.y,2)),
384                                 fa=t*d01/(d01+d12),// scaling factor for triangle Ta
385                                 fb=t*d12/(d01+d12);
386                         return {
387                                 inner : {
388                                         x : MiddlePoint.x-fa*(AfterPoint.x-FirstPoint.x),
389                                         y : MiddlePoint.y-fa*(AfterPoint.y-FirstPoint.y)
390                                 },
391                                 outer : {
392                                         x: MiddlePoint.x+fb*(AfterPoint.x-FirstPoint.x),
393                                         y : MiddlePoint.y+fb*(AfterPoint.y-FirstPoint.y)
394                                 }
395                         };
396                 },
397                 calculateOrderOfMagnitude = helpers.calculateOrderOfMagnitude = function(val){
398                         return Math.floor(Math.log(val) / Math.LN10);
399                 },
400                 calculateScaleRange = helpers.calculateScaleRange = function(valuesArray, drawingSize, textSize, startFromZero, integersOnly){
401
402                         //Set a minimum step of two - a point at the top of the graph, and a point at the base
403                         var minSteps = 2,
404                                 maxSteps = Math.floor(drawingSize/(textSize * 1.5)),
405                                 skipFitting = (minSteps >= maxSteps);
406
407                         var maxValue = max(valuesArray),
408                                 minValue = min(valuesArray);
409
410                         // We need some degree of separation here to calculate the scales if all the values are the same
411                         // Adding/minusing 0.5 will give us a range of 1.
412                         if (maxValue === minValue){
413                                 maxValue += 0.5;
414                                 // So we don't end up with a graph with a negative start value if we've said always start from zero
415                                 if (minValue >= 0.5 && !startFromZero){
416                                         minValue -= 0.5;
417                                 }
418                                 else{
419                                         // Make up a whole number above the values
420                                         maxValue += 0.5;
421                                 }
422                         }
423
424                         var     valueRange = Math.abs(maxValue - minValue),
425                                 rangeOrderOfMagnitude = calculateOrderOfMagnitude(valueRange),
426                                 graphMax = Math.ceil(maxValue / (1 * Math.pow(10, rangeOrderOfMagnitude))) * Math.pow(10, rangeOrderOfMagnitude),
427                                 graphMin = (startFromZero) ? 0 : Math.floor(minValue / (1 * Math.pow(10, rangeOrderOfMagnitude))) * Math.pow(10, rangeOrderOfMagnitude),
428                                 graphRange = graphMax - graphMin,
429                                 stepValue = Math.pow(10, rangeOrderOfMagnitude),
430                                 numberOfSteps = Math.round(graphRange / stepValue);
431
432                         //If we have more space on the graph we'll use it to give more definition to the data
433                         while((numberOfSteps > maxSteps || (numberOfSteps * 2) < maxSteps) && !skipFitting) {
434                                 if(numberOfSteps > maxSteps){
435                                         stepValue *=2;
436                                         numberOfSteps = Math.round(graphRange/stepValue);
437                                         // Don't ever deal with a decimal number of steps - cancel fitting and just use the minimum number of steps.
438                                         if (numberOfSteps % 1 !== 0){
439                                                 skipFitting = true;
440                                         }
441                                 }
442                                 //We can fit in double the amount of scale points on the scale
443                                 else{
444                                         //If user has declared ints only, and the step value isn't a decimal
445                                         if (integersOnly && rangeOrderOfMagnitude >= 0){
446                                                 //If the user has said integers only, we need to check that making the scale more granular wouldn't make it a float
447                                                 if(stepValue/2 % 1 === 0){
448                                                         stepValue /=2;
449                                                         numberOfSteps = Math.round(graphRange/stepValue);
450                                                 }
451                                                 //If it would make it a float break out of the loop
452                                                 else{
453                                                         break;
454                                                 }
455                                         }
456                                         //If the scale doesn't have to be an int, make the scale more granular anyway.
457                                         else{
458                                                 stepValue /=2;
459                                                 numberOfSteps = Math.round(graphRange/stepValue);
460                                         }
461
462                                 }
463                         }
464
465                         if (skipFitting){
466                                 numberOfSteps = minSteps;
467                                 stepValue = graphRange / numberOfSteps;
468                         }
469
470                         return {
471                                 steps : numberOfSteps,
472                                 stepValue : stepValue,
473                                 min : graphMin,
474                                 max     : graphMin + (numberOfSteps * stepValue)
475                         };
476
477                 },
478                 /* jshint ignore:start */
479                 // Blows up jshint errors based on the new Function constructor
480                 //Templating methods
481                 //Javascript micro templating by John Resig - source at http://ejohn.org/blog/javascript-micro-templating/
482                 template = helpers.template = function(templateString, valuesObject){
483
484                         // If templateString is function rather than string-template - call the function for valuesObject
485
486                         if(templateString instanceof Function){
487                                 return templateString(valuesObject);
488                         }
489
490                         var cache = {};
491                         function tmpl(str, data){
492                                 // Figure out if we're getting a template, or if we need to
493                                 // load the template - and be sure to cache the result.
494                                 var fn = !/\W/.test(str) ?
495                                 cache[str] = cache[str] :
496
497                                 // Generate a reusable function that will serve as a template
498                                 // generator (and which will be cached).
499                                 new Function("obj",
500                                         "var p=[],print=function(){p.push.apply(p,arguments);};" +
501
502                                         // Introduce the data as local variables using with(){}
503                                         "with(obj){p.push('" +
504
505                                         // Convert the template into pure JavaScript
506                                         str
507                                                 .replace(/[\r\t\n]/g, " ")
508                                                 .split("<%").join("\t")
509                                                 .replace(/((^|%>)[^\t]*)'/g, "$1\r")
510                                                 .replace(/\t=(.*?)%>/g, "',$1,'")
511                                                 .split("\t").join("');")
512                                                 .split("%>").join("p.push('")
513                                                 .split("\r").join("\\'") +
514                                         "');}return p.join('');"
515                                 );
516
517                                 // Provide some basic currying to the user
518                                 return data ? fn( data ) : fn;
519                         }
520                         return tmpl(templateString,valuesObject);
521                 },
522                 /* jshint ignore:end */
523                 generateLabels = helpers.generateLabels = function(templateString,numberOfSteps,graphMin,stepValue){
524                         var labelsArray = new Array(numberOfSteps);
525                         if (templateString){
526                                 each(labelsArray,function(val,index){
527                                         labelsArray[index] = template(templateString,{value: (graphMin + (stepValue*(index+1)))});
528                                 });
529                         }
530                         return labelsArray;
531                 },
532                 //--Animation methods
533                 //Easing functions adapted from Robert Penner's easing equations
534                 //http://www.robertpenner.com/easing/
535                 easingEffects = helpers.easingEffects = {
536                         linear: function (t) {
537                                 return t;
538                         },
539                         easeInQuad: function (t) {
540                                 return t * t;
541                         },
542                         easeOutQuad: function (t) {
543                                 return -1 * t * (t - 2);
544                         },
545                         easeInOutQuad: function (t) {
546                                 if ((t /= 1 / 2) < 1){
547                                         return 1 / 2 * t * t;
548                                 }
549                                 return -1 / 2 * ((--t) * (t - 2) - 1);
550                         },
551                         easeInCubic: function (t) {
552                                 return t * t * t;
553                         },
554                         easeOutCubic: function (t) {
555                                 return 1 * ((t = t / 1 - 1) * t * t + 1);
556                         },
557                         easeInOutCubic: function (t) {
558                                 if ((t /= 1 / 2) < 1){
559                                         return 1 / 2 * t * t * t;
560                                 }
561                                 return 1 / 2 * ((t -= 2) * t * t + 2);
562                         },
563                         easeInQuart: function (t) {
564                                 return t * t * t * t;
565                         },
566                         easeOutQuart: function (t) {
567                                 return -1 * ((t = t / 1 - 1) * t * t * t - 1);
568                         },
569                         easeInOutQuart: function (t) {
570                                 if ((t /= 1 / 2) < 1){
571                                         return 1 / 2 * t * t * t * t;
572                                 }
573                                 return -1 / 2 * ((t -= 2) * t * t * t - 2);
574                         },
575                         easeInQuint: function (t) {
576                                 return 1 * (t /= 1) * t * t * t * t;
577                         },
578                         easeOutQuint: function (t) {
579                                 return 1 * ((t = t / 1 - 1) * t * t * t * t + 1);
580                         },
581                         easeInOutQuint: function (t) {
582                                 if ((t /= 1 / 2) < 1){
583                                         return 1 / 2 * t * t * t * t * t;
584                                 }
585                                 return 1 / 2 * ((t -= 2) * t * t * t * t + 2);
586                         },
587                         easeInSine: function (t) {
588                                 return -1 * Math.cos(t / 1 * (Math.PI / 2)) + 1;
589                         },
590                         easeOutSine: function (t) {
591                                 return 1 * Math.sin(t / 1 * (Math.PI / 2));
592                         },
593                         easeInOutSine: function (t) {
594                                 return -1 / 2 * (Math.cos(Math.PI * t / 1) - 1);
595                         },
596                         easeInExpo: function (t) {
597                                 return (t === 0) ? 1 : 1 * Math.pow(2, 10 * (t / 1 - 1));
598                         },
599                         easeOutExpo: function (t) {
600                                 return (t === 1) ? 1 : 1 * (-Math.pow(2, -10 * t / 1) + 1);
601                         },
602                         easeInOutExpo: function (t) {
603                                 if (t === 0){
604                                         return 0;
605                                 }
606                                 if (t === 1){
607                                         return 1;
608                                 }
609                                 if ((t /= 1 / 2) < 1){
610                                         return 1 / 2 * Math.pow(2, 10 * (t - 1));
611                                 }
612                                 return 1 / 2 * (-Math.pow(2, -10 * --t) + 2);
613                         },
614                         easeInCirc: function (t) {
615                                 if (t >= 1){
616                                         return t;
617                                 }
618                                 return -1 * (Math.sqrt(1 - (t /= 1) * t) - 1);
619                         },
620                         easeOutCirc: function (t) {
621                                 return 1 * Math.sqrt(1 - (t = t / 1 - 1) * t);
622                         },
623                         easeInOutCirc: function (t) {
624                                 if ((t /= 1 / 2) < 1){
625                                         return -1 / 2 * (Math.sqrt(1 - t * t) - 1);
626                                 }
627                                 return 1 / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1);
628                         },
629                         easeInElastic: function (t) {
630                                 var s = 1.70158;
631                                 var p = 0;
632                                 var a = 1;
633                                 if (t === 0){
634                                         return 0;
635                                 }
636                                 if ((t /= 1) == 1){
637                                         return 1;
638                                 }
639                                 if (!p){
640                                         p = 1 * 0.3;
641                                 }
642                                 if (a < Math.abs(1)) {
643                                         a = 1;
644                                         s = p / 4;
645                                 } else{
646                                         s = p / (2 * Math.PI) * Math.asin(1 / a);
647                                 }
648                                 return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p));
649                         },
650                         easeOutElastic: function (t) {
651                                 var s = 1.70158;
652                                 var p = 0;
653                                 var a = 1;
654                                 if (t === 0){
655                                         return 0;
656                                 }
657                                 if ((t /= 1) == 1){
658                                         return 1;
659                                 }
660                                 if (!p){
661                                         p = 1 * 0.3;
662                                 }
663                                 if (a < Math.abs(1)) {
664                                         a = 1;
665                                         s = p / 4;
666                                 } else{
667                                         s = p / (2 * Math.PI) * Math.asin(1 / a);
668                                 }
669                                 return a * Math.pow(2, -10 * t) * Math.sin((t * 1 - s) * (2 * Math.PI) / p) + 1;
670                         },
671                         easeInOutElastic: function (t) {
672                                 var s = 1.70158;
673                                 var p = 0;
674                                 var a = 1;
675                                 if (t === 0){
676                                         return 0;
677                                 }
678                                 if ((t /= 1 / 2) == 2){
679                                         return 1;
680                                 }
681                                 if (!p){
682                                         p = 1 * (0.3 * 1.5);
683                                 }
684                                 if (a < Math.abs(1)) {
685                                         a = 1;
686                                         s = p / 4;
687                                 } else {
688                                         s = p / (2 * Math.PI) * Math.asin(1 / a);
689                                 }
690                                 if (t < 1){
691                                         return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p));}
692                                 return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p) * 0.5 + 1;
693                         },
694                         easeInBack: function (t) {
695                                 var s = 1.70158;
696                                 return 1 * (t /= 1) * t * ((s + 1) * t - s);
697                         },
698                         easeOutBack: function (t) {
699                                 var s = 1.70158;
700                                 return 1 * ((t = t / 1 - 1) * t * ((s + 1) * t + s) + 1);
701                         },
702                         easeInOutBack: function (t) {
703                                 var s = 1.70158;
704                                 if ((t /= 1 / 2) < 1){
705                                         return 1 / 2 * (t * t * (((s *= (1.525)) + 1) * t - s));
706                                 }
707                                 return 1 / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);
708                         },
709                         easeInBounce: function (t) {
710                                 return 1 - easingEffects.easeOutBounce(1 - t);
711                         },
712                         easeOutBounce: function (t) {
713                                 if ((t /= 1) < (1 / 2.75)) {
714                                         return 1 * (7.5625 * t * t);
715                                 } else if (t < (2 / 2.75)) {
716                                         return 1 * (7.5625 * (t -= (1.5 / 2.75)) * t + 0.75);
717                                 } else if (t < (2.5 / 2.75)) {
718                                         return 1 * (7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375);
719                                 } else {
720                                         return 1 * (7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375);
721                                 }
722                         },
723                         easeInOutBounce: function (t) {
724                                 if (t < 1 / 2){
725                                         return easingEffects.easeInBounce(t * 2) * 0.5;
726                                 }
727                                 return easingEffects.easeOutBounce(t * 2 - 1) * 0.5 + 1 * 0.5;
728                         }
729                 },
730                 //Request animation polyfill - http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
731                 requestAnimFrame = helpers.requestAnimFrame = (function(){
732                         return window.requestAnimationFrame ||
733                                 window.webkitRequestAnimationFrame ||
734                                 window.mozRequestAnimationFrame ||
735                                 window.oRequestAnimationFrame ||
736                                 window.msRequestAnimationFrame ||
737                                 function(callback) {
738                                         return window.setTimeout(callback, 1000 / 60);
739                                 };
740                 })(),
741                 cancelAnimFrame = helpers.cancelAnimFrame = (function(){
742                         return window.cancelAnimationFrame ||
743                                 window.webkitCancelAnimationFrame ||
744                                 window.mozCancelAnimationFrame ||
745                                 window.oCancelAnimationFrame ||
746                                 window.msCancelAnimationFrame ||
747                                 function(callback) {
748                                         return window.clearTimeout(callback, 1000 / 60);
749                                 };
750                 })(),
751                 animationLoop = helpers.animationLoop = function(callback,totalSteps,easingString,onProgress,onComplete,chartInstance){
752
753                         var currentStep = 0,
754                                 easingFunction = easingEffects[easingString] || easingEffects.linear;
755
756                         var animationFrame = function(){
757                                 currentStep++;
758                                 var stepDecimal = currentStep/totalSteps;
759                                 var easeDecimal = easingFunction(stepDecimal);
760
761                                 callback.call(chartInstance,easeDecimal,stepDecimal, currentStep);
762                                 onProgress.call(chartInstance,easeDecimal,stepDecimal);
763                                 if (currentStep < totalSteps){
764                                         chartInstance.animationFrame = requestAnimFrame(animationFrame);
765                                 } else{
766                                         onComplete.apply(chartInstance);
767                                 }
768                         };
769                         requestAnimFrame(animationFrame);
770                 },
771                 //-- DOM methods
772                 getRelativePosition = helpers.getRelativePosition = function(evt){
773                         var mouseX, mouseY;
774                         var e = evt.originalEvent || evt,
775                                 canvas = evt.currentTarget || evt.srcElement,
776                                 boundingRect = canvas.getBoundingClientRect();
777
778                         if (e.touches){
779                                 mouseX = e.touches[0].clientX - boundingRect.left;
780                                 mouseY = e.touches[0].clientY - boundingRect.top;
781
782                         }
783                         else{
784                                 mouseX = e.clientX - boundingRect.left;
785                                 mouseY = e.clientY - boundingRect.top;
786                         }
787
788                         return {
789                                 x : mouseX,
790                                 y : mouseY
791                         };
792
793                 },
794                 addEvent = helpers.addEvent = function(node,eventType,method){
795                         if (node.addEventListener){
796                                 node.addEventListener(eventType,method);
797                         } else if (node.attachEvent){
798                                 node.attachEvent("on"+eventType, method);
799                         } else {
800                                 node["on"+eventType] = method;
801                         }
802                 },
803                 removeEvent = helpers.removeEvent = function(node, eventType, handler){
804                         if (node.removeEventListener){
805                                 node.removeEventListener(eventType, handler, false);
806                         } else if (node.detachEvent){
807                                 node.detachEvent("on"+eventType,handler);
808                         } else{
809                                 node["on" + eventType] = noop;
810                         }
811                 },
812                 bindEvents = helpers.bindEvents = function(chartInstance, arrayOfEvents, handler){
813                         // Create the events object if it's not already present
814                         if (!chartInstance.events) chartInstance.events = {};
815
816                         each(arrayOfEvents,function(eventName){
817                                 chartInstance.events[eventName] = function(){
818                                         handler.apply(chartInstance, arguments);
819                                 };
820                                 addEvent(chartInstance.chart.canvas,eventName,chartInstance.events[eventName]);
821                         });
822                 },
823                 unbindEvents = helpers.unbindEvents = function (chartInstance, arrayOfEvents) {
824                         each(arrayOfEvents, function(handler,eventName){
825                                 removeEvent(chartInstance.chart.canvas, eventName, handler);
826                         });
827                 },
828                 getMaximumWidth = helpers.getMaximumWidth = function(domNode){
829                         var container = domNode.parentNode,
830                             padding = parseInt(getStyle(container, 'padding-left')) + parseInt(getStyle(container, 'padding-right'));
831                         // TODO = check cross browser stuff with this.
832                         return container.clientWidth - padding;
833                 },
834                 getMaximumHeight = helpers.getMaximumHeight = function(domNode){
835                         var container = domNode.parentNode,
836                             padding = parseInt(getStyle(container, 'padding-bottom')) + parseInt(getStyle(container, 'padding-top'));
837                         // TODO = check cross browser stuff with this.
838                         return container.clientHeight - padding;
839                 },
840                 getStyle = helpers.getStyle = function (el, property) {
841                         return el.currentStyle ?
842                                 el.currentStyle[property] :
843                                 document.defaultView.getComputedStyle(el, null).getPropertyValue(property);
844                 },
845                 getMaximumSize = helpers.getMaximumSize = helpers.getMaximumWidth, // legacy support
846                 retinaScale = helpers.retinaScale = function(chart){
847                         var ctx = chart.ctx,
848                                 width = chart.canvas.width,
849                                 height = chart.canvas.height;
850
851                         if (window.devicePixelRatio) {
852                                 ctx.canvas.style.width = width + "px";
853                                 ctx.canvas.style.height = height + "px";
854                                 ctx.canvas.height = height * window.devicePixelRatio;
855                                 ctx.canvas.width = width * window.devicePixelRatio;
856                                 ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
857                         }
858                 },
859                 //-- Canvas methods
860                 clear = helpers.clear = function(chart){
861                         chart.ctx.clearRect(0,0,chart.width,chart.height);
862                 },
863                 fontString = helpers.fontString = function(pixelSize,fontStyle,fontFamily){
864                         return fontStyle + " " + pixelSize+"px " + fontFamily;
865                 },
866                 longestText = helpers.longestText = function(ctx,font,arrayOfStrings){
867                         ctx.font = font;
868                         var longest = 0;
869                         each(arrayOfStrings,function(string){
870                                 var textWidth = ctx.measureText(string).width;
871                                 longest = (textWidth > longest) ? textWidth : longest;
872                         });
873                         return longest;
874                 },
875                 drawRoundedRectangle = helpers.drawRoundedRectangle = function(ctx,x,y,width,height,radius){
876                         ctx.beginPath();
877                         ctx.moveTo(x + radius, y);
878                         ctx.lineTo(x + width - radius, y);
879                         ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
880                         ctx.lineTo(x + width, y + height - radius);
881                         ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
882                         ctx.lineTo(x + radius, y + height);
883                         ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
884                         ctx.lineTo(x, y + radius);
885                         ctx.quadraticCurveTo(x, y, x + radius, y);
886                         ctx.closePath();
887                 };
888
889
890         //Store a reference to each instance - allowing us to globally resize chart instances on window resize.
891         //Destroy method on the chart will remove the instance of the chart from this reference.
892         Chart.instances = {};
893
894         Chart.Type = function(data,options,chart){
895                 this.options = options;
896                 this.chart = chart;
897                 this.id = uid();
898                 //Add the chart instance to the global namespace
899                 Chart.instances[this.id] = this;
900
901                 // Initialize is always called when a chart type is created
902                 // By default it is a no op, but it should be extended
903                 if (options.responsive){
904                         this.resize();
905                 }
906                 this.initialize.call(this,data);
907         };
908
909         //Core methods that'll be a part of every chart type
910         extend(Chart.Type.prototype,{
911                 initialize : function(){return this;},
912                 clear : function(){
913                         clear(this.chart);
914                         return this;
915                 },
916                 stop : function(){
917                         // Stops any current animation loop occuring
918                         Chart.animationService.cancelAnimation(this);
919                         return this;
920                 },
921                 resize : function(callback){
922                         this.stop();
923                         var canvas = this.chart.canvas,
924                                 newWidth = getMaximumWidth(this.chart.canvas),
925                                 newHeight = this.options.maintainAspectRatio ? newWidth / this.chart.aspectRatio : getMaximumHeight(this.chart.canvas);
926
927                         canvas.width = this.chart.width = newWidth;
928                         canvas.height = this.chart.height = newHeight;
929
930                         retinaScale(this.chart);
931
932                         if (typeof callback === "function"){
933                                 callback.apply(this, Array.prototype.slice.call(arguments, 1));
934                         }
935                         return this;
936                 },
937                 reflow : noop,
938                 render : function(reflow){
939                         if (reflow){
940                                 this.reflow();
941                         }
942                         
943                         if (this.options.animation && !reflow){
944                                 var animation = new Chart.Animation();
945                                 animation.numSteps = this.options.animationSteps;
946                                 animation.easing = this.options.animationEasing;
947                                 
948                                 // render function
949                                 animation.render = function(chartInstance, animationObject) {
950                                         var easingFunction = helpers.easingEffects[animationObject.easing];
951                                         var stepDecimal = animationObject.currentStep / animationObject.numSteps;
952                                         var easeDecimal = easingFunction(stepDecimal);
953                                         
954                                         chartInstance.draw(easeDecimal, stepDecimal, animationObject.currentStep);
955                                 };
956                                 
957                                 // user events
958                                 animation.onAnimationProgress = this.options.onAnimationProgress;
959                                 animation.onAnimationComplete = this.options.onAnimationComplete;
960                                 
961                                 Chart.animationService.addAnimation(this, animation);
962                         }
963                         else{
964                                 this.draw();
965                                 this.options.onAnimationComplete.call(this);
966                         }
967                         return this;
968                 },
969                 generateLegend : function(){
970                         return template(this.options.legendTemplate,this);
971                 },
972                 destroy : function(){
973                         this.clear();
974                         unbindEvents(this, this.events);
975                         var canvas = this.chart.canvas;
976
977                         // Reset canvas height/width attributes starts a fresh with the canvas context
978                         canvas.width = this.chart.width;
979                         canvas.height = this.chart.height;
980
981                         // < IE9 doesn't support removeProperty
982                         if (canvas.style.removeProperty) {
983                                 canvas.style.removeProperty('width');
984                                 canvas.style.removeProperty('height');
985                         } else {
986                                 canvas.style.removeAttribute('width');
987                                 canvas.style.removeAttribute('height');
988                         }
989
990                         delete Chart.instances[this.id];
991                 },
992                 showTooltip : function(ChartElements, forceRedraw){
993                         // Only redraw the chart if we've actually changed what we're hovering on.
994                         if (typeof this.activeElements === 'undefined') this.activeElements = [];
995
996                         var isChanged = (function(Elements){
997                                 var changed = false;
998
999                                 if (Elements.length !== this.activeElements.length){
1000                                         changed = true;
1001                                         return changed;
1002                                 }
1003
1004                                 each(Elements, function(element, index){
1005                                         if (element !== this.activeElements[index]){
1006                                                 changed = true;
1007                                         }
1008                                 }, this);
1009                                 return changed;
1010                         }).call(this, ChartElements);
1011
1012                         if (!isChanged && !forceRedraw){
1013                                 return;
1014                         }
1015                         else{
1016                                 this.activeElements = ChartElements;
1017                         }
1018                         this.draw();
1019                         if(this.options.customTooltips){
1020                                 this.options.customTooltips(false);
1021                         }
1022                         if (ChartElements.length > 0){
1023                                 // If we have multiple datasets, show a MultiTooltip for all of the data points at that index
1024                                 if (this.datasets && this.datasets.length > 1) {
1025                                         var dataArray,
1026                                                 dataIndex;
1027
1028                                         for (var i = this.datasets.length - 1; i >= 0; i--) {
1029                                                 dataArray = this.datasets[i].points || this.datasets[i].bars || this.datasets[i].segments;
1030                                                 dataIndex = indexOf(dataArray, ChartElements[0]);
1031                                                 if (dataIndex !== -1){
1032                                                         break;
1033                                                 }
1034                                         }
1035                                         var tooltipLabels = [],
1036                                                 tooltipColors = [],
1037                                                 medianPosition = (function(index) {
1038
1039                                                         // Get all the points at that particular index
1040                                                         var Elements = [],
1041                                                                 dataCollection,
1042                                                                 xPositions = [],
1043                                                                 yPositions = [],
1044                                                                 xMax,
1045                                                                 yMax,
1046                                                                 xMin,
1047                                                                 yMin;
1048                                                         helpers.each(this.datasets, function(dataset){
1049                                                                 dataCollection = dataset.points || dataset.bars || dataset.segments;
1050                                                                 if (dataCollection[dataIndex] && dataCollection[dataIndex].hasValue()){
1051                                                                         Elements.push(dataCollection[dataIndex]);
1052                                                                 }
1053                                                         });
1054
1055                                                         helpers.each(Elements, function(element) {
1056                                                                 xPositions.push(element.x);
1057                                                                 yPositions.push(element.y);
1058
1059
1060                                                                 //Include any colour information about the element
1061                                                                 tooltipLabels.push(helpers.template(this.options.multiTooltipTemplate, element));
1062                                                                 tooltipColors.push({
1063                                                                         fill: element._saved.fillColor || element.fillColor,
1064                                                                         stroke: element._saved.strokeColor || element.strokeColor
1065                                                                 });
1066
1067                                                         }, this);
1068
1069                                                         yMin = min(yPositions);
1070                                                         yMax = max(yPositions);
1071
1072                                                         xMin = min(xPositions);
1073                                                         xMax = max(xPositions);
1074
1075                                                         return {
1076                                                                 x: (xMin > this.chart.width/2) ? xMin : xMax,
1077                                                                 y: (yMin + yMax)/2
1078                                                         };
1079                                                 }).call(this, dataIndex);
1080
1081                                         new Chart.MultiTooltip({
1082                                                 x: medianPosition.x,
1083                                                 y: medianPosition.y,
1084                                                 xPadding: this.options.tooltipXPadding,
1085                                                 yPadding: this.options.tooltipYPadding,
1086                                                 xOffset: this.options.tooltipXOffset,
1087                                                 fillColor: this.options.tooltipFillColor,
1088                                                 textColor: this.options.tooltipFontColor,
1089                                                 fontFamily: this.options.tooltipFontFamily,
1090                                                 fontStyle: this.options.tooltipFontStyle,
1091                                                 fontSize: this.options.tooltipFontSize,
1092                                                 titleTextColor: this.options.tooltipTitleFontColor,
1093                                                 titleFontFamily: this.options.tooltipTitleFontFamily,
1094                                                 titleFontStyle: this.options.tooltipTitleFontStyle,
1095                                                 titleFontSize: this.options.tooltipTitleFontSize,
1096                                                 cornerRadius: this.options.tooltipCornerRadius,
1097                                                 labels: tooltipLabels,
1098                                                 legendColors: tooltipColors,
1099                                                 legendColorBackground : this.options.multiTooltipKeyBackground,
1100                                                 title: ChartElements[0].label,
1101                                                 chart: this.chart,
1102                                                 ctx: this.chart.ctx,
1103                                                 custom: this.options.customTooltips
1104                                         }).draw();
1105
1106                                 } else {
1107                                         each(ChartElements, function(Element) {
1108                                                 var tooltipPosition = Element.tooltipPosition();
1109                                                 new Chart.Tooltip({
1110                                                         x: Math.round(tooltipPosition.x),
1111                                                         y: Math.round(tooltipPosition.y),
1112                                                         xPadding: this.options.tooltipXPadding,
1113                                                         yPadding: this.options.tooltipYPadding,
1114                                                         fillColor: this.options.tooltipFillColor,
1115                                                         textColor: this.options.tooltipFontColor,
1116                                                         fontFamily: this.options.tooltipFontFamily,
1117                                                         fontStyle: this.options.tooltipFontStyle,
1118                                                         fontSize: this.options.tooltipFontSize,
1119                                                         caretHeight: this.options.tooltipCaretSize,
1120                                                         cornerRadius: this.options.tooltipCornerRadius,
1121                                                         text: template(this.options.tooltipTemplate, Element),
1122                                                         chart: this.chart,
1123                                                         custom: this.options.customTooltips
1124                                                 }).draw();
1125                                         }, this);
1126                                 }
1127                         }
1128                         return this;
1129                 },
1130                 toBase64Image : function(){
1131                         return this.chart.canvas.toDataURL.apply(this.chart.canvas, arguments);
1132                 }
1133         });
1134
1135         Chart.Type.extend = function(extensions){
1136
1137                 var parent = this;
1138
1139                 var ChartType = function(){
1140                         return parent.apply(this,arguments);
1141                 };
1142
1143                 //Copy the prototype object of the this class
1144                 ChartType.prototype = clone(parent.prototype);
1145                 //Now overwrite some of the properties in the base class with the new extensions
1146                 extend(ChartType.prototype, extensions);
1147
1148                 ChartType.extend = Chart.Type.extend;
1149
1150                 if (extensions.name || parent.prototype.name){
1151
1152                         var chartName = extensions.name || parent.prototype.name;
1153                         //Assign any potential default values of the new chart type
1154
1155                         //If none are defined, we'll use a clone of the chart type this is being extended from.
1156                         //I.e. if we extend a line chart, we'll use the defaults from the line chart if our new chart
1157                         //doesn't define some defaults of their own.
1158
1159                         var baseDefaults = (Chart.defaults[parent.prototype.name]) ? clone(Chart.defaults[parent.prototype.name]) : {};
1160
1161                         Chart.defaults[chartName] = extend(baseDefaults,extensions.defaults);
1162
1163                         Chart.types[chartName] = ChartType;
1164
1165                         //Register this new chart type in the Chart prototype
1166                         Chart.prototype[chartName] = function(data,options){
1167                                 var config = merge(Chart.defaults.global, Chart.defaults[chartName], options || {});
1168                                 return new ChartType(data,config,this);
1169                         };
1170                 } else{
1171                         warn("Name not provided for this chart, so it hasn't been registered");
1172                 }
1173                 return parent;
1174         };
1175
1176         Chart.Element = function(configuration){
1177                 extend(this,configuration);
1178                 this.initialize.apply(this,arguments);
1179                 this.save();
1180         };
1181         extend(Chart.Element.prototype,{
1182                 initialize : function(){},
1183                 restore : function(props){
1184                         if (!props){
1185                                 extend(this,this._saved);
1186                         } else {
1187                                 each(props,function(key){
1188                                         this[key] = this._saved[key];
1189                                 },this);
1190                         }
1191                         return this;
1192                 },
1193                 save : function(){
1194                         this._saved = clone(this);
1195                         delete this._saved._saved;
1196                         return this;
1197                 },
1198                 update : function(newProps){
1199                         each(newProps,function(value,key){
1200                                 this._saved[key] = this[key];
1201                                 this[key] = value;
1202                         },this);
1203                         return this;
1204                 },
1205                 transition : function(props,ease){
1206                         each(props,function(value,key){
1207                                 this[key] = ((value - this._saved[key]) * ease) + this._saved[key];
1208                         },this);
1209                         return this;
1210                 },
1211                 tooltipPosition : function(){
1212                         return {
1213                                 x : this.x,
1214                                 y : this.y
1215                         };
1216                 },
1217                 hasValue: function(){
1218                         return isNumber(this.value);
1219                 }
1220         });
1221
1222         Chart.Element.extend = inherits;
1223
1224
1225         Chart.Point = Chart.Element.extend({
1226                 display: true,
1227                 inRange: function(chartX,chartY){
1228                         var hitDetectionRange = this.hitDetectionRadius + this.radius;
1229                         return ((Math.pow(chartX-this.x, 2)+Math.pow(chartY-this.y, 2)) < Math.pow(hitDetectionRange,2));
1230                 },
1231                 draw : function(){
1232                         if (this.display){
1233                                 var ctx = this.ctx;
1234                                 ctx.beginPath();
1235
1236                                 ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2);
1237                                 ctx.closePath();
1238
1239                                 ctx.strokeStyle = this.strokeColor;
1240                                 ctx.lineWidth = this.strokeWidth;
1241
1242                                 ctx.fillStyle = this.fillColor;
1243
1244                                 ctx.fill();
1245                                 ctx.stroke();
1246                         }
1247
1248
1249                         //Quick debug for bezier curve splining
1250                         //Highlights control points and the line between them.
1251                         //Handy for dev - stripped in the min version.
1252
1253                         // ctx.save();
1254                         // ctx.fillStyle = "black";
1255                         // ctx.strokeStyle = "black"
1256                         // ctx.beginPath();
1257                         // ctx.arc(this.controlPoints.inner.x,this.controlPoints.inner.y, 2, 0, Math.PI*2);
1258                         // ctx.fill();
1259
1260                         // ctx.beginPath();
1261                         // ctx.arc(this.controlPoints.outer.x,this.controlPoints.outer.y, 2, 0, Math.PI*2);
1262                         // ctx.fill();
1263
1264                         // ctx.moveTo(this.controlPoints.inner.x,this.controlPoints.inner.y);
1265                         // ctx.lineTo(this.x, this.y);
1266                         // ctx.lineTo(this.controlPoints.outer.x,this.controlPoints.outer.y);
1267                         // ctx.stroke();
1268
1269                         // ctx.restore();
1270
1271
1272
1273                 }
1274         });
1275
1276         Chart.Arc = Chart.Element.extend({
1277                 inRange : function(chartX,chartY){
1278
1279                         var pointRelativePosition = helpers.getAngleFromPoint(this, {
1280                                 x: chartX,
1281                                 y: chartY
1282                         });
1283
1284                         //Check if within the range of the open/close angle
1285                         var betweenAngles = (pointRelativePosition.angle >= this.startAngle && pointRelativePosition.angle <= this.endAngle),
1286                                 withinRadius = (pointRelativePosition.distance >= this.innerRadius && pointRelativePosition.distance <= this.outerRadius);
1287
1288                         return (betweenAngles && withinRadius);
1289                         //Ensure within the outside of the arc centre, but inside arc outer
1290                 },
1291                 tooltipPosition : function(){
1292                         var centreAngle = this.startAngle + ((this.endAngle - this.startAngle) / 2),
1293                                 rangeFromCentre = (this.outerRadius - this.innerRadius) / 2 + this.innerRadius;
1294                         return {
1295                                 x : this.x + (Math.cos(centreAngle) * rangeFromCentre),
1296                                 y : this.y + (Math.sin(centreAngle) * rangeFromCentre)
1297                         };
1298                 },
1299                 draw : function(animationPercent){
1300
1301                         var easingDecimal = animationPercent || 1;
1302
1303                         var ctx = this.ctx;
1304
1305                         ctx.beginPath();
1306
1307                         ctx.arc(this.x, this.y, this.outerRadius, this.startAngle, this.endAngle);
1308
1309                         ctx.arc(this.x, this.y, this.innerRadius, this.endAngle, this.startAngle, true);
1310
1311                         ctx.closePath();
1312                         ctx.strokeStyle = this.strokeColor;
1313                         ctx.lineWidth = this.strokeWidth;
1314
1315                         ctx.fillStyle = this.fillColor;
1316
1317                         ctx.fill();
1318                         ctx.lineJoin = 'bevel';
1319
1320                         if (this.showStroke){
1321                                 ctx.stroke();
1322                         }
1323                 }
1324         });
1325
1326         Chart.Rectangle = Chart.Element.extend({
1327                 draw : function(){
1328                         var ctx = this.ctx,
1329                                 halfWidth = this.width/2,
1330                                 leftX = this.x - halfWidth,
1331                                 rightX = this.x + halfWidth,
1332                                 top = this.base - (this.base - this.y),
1333                                 halfStroke = this.strokeWidth / 2;
1334
1335                         // Canvas doesn't allow us to stroke inside the width so we can
1336                         // adjust the sizes to fit if we're setting a stroke on the line
1337                         if (this.showStroke){
1338                                 leftX += halfStroke;
1339                                 rightX -= halfStroke;
1340                                 top += halfStroke;
1341                         }
1342
1343                         ctx.beginPath();
1344
1345                         ctx.fillStyle = this.fillColor;
1346                         ctx.strokeStyle = this.strokeColor;
1347                         ctx.lineWidth = this.strokeWidth;
1348
1349                         // It'd be nice to keep this class totally generic to any rectangle
1350                         // and simply specify which border to miss out.
1351                         ctx.moveTo(leftX, this.base);
1352                         ctx.lineTo(leftX, top);
1353                         ctx.lineTo(rightX, top);
1354                         ctx.lineTo(rightX, this.base);
1355                         ctx.fill();
1356                         if (this.showStroke){
1357                                 ctx.stroke();
1358                         }
1359                 },
1360                 height : function(){
1361                         return this.base - this.y;
1362                 },
1363                 inRange : function(chartX,chartY){
1364                         return (chartX >= this.x - this.width/2 && chartX <= this.x + this.width/2) && (chartY >= this.y && chartY <= this.base);
1365                 }
1366         });
1367
1368         Chart.Animation = Chart.Element.extend({
1369                 currentStep: null, // the current animation step
1370                 numSteps: 60, // default number of steps
1371                 easing: "", // the easing to use for this animation
1372                 render: null, // render function used by the animation service
1373                 
1374                 onAnimationProgress: null, // user specified callback to fire on each step of the animation 
1375                 onAnimationComplete: null, // user specified callback to fire when the animation finishes
1376         });
1377         
1378         Chart.Tooltip = Chart.Element.extend({
1379                 draw : function(){
1380
1381                         var ctx = this.chart.ctx;
1382
1383                         ctx.font = fontString(this.fontSize,this.fontStyle,this.fontFamily);
1384
1385                         this.xAlign = "center";
1386                         this.yAlign = "above";
1387
1388                         //Distance between the actual element.y position and the start of the tooltip caret
1389                         var caretPadding = this.caretPadding = 2;
1390
1391                         var tooltipWidth = ctx.measureText(this.text).width + 2*this.xPadding,
1392                                 tooltipRectHeight = this.fontSize + 2*this.yPadding,
1393                                 tooltipHeight = tooltipRectHeight + this.caretHeight + caretPadding;
1394
1395                         if (this.x + tooltipWidth/2 >this.chart.width){
1396                                 this.xAlign = "left";
1397                         } else if (this.x - tooltipWidth/2 < 0){
1398                                 this.xAlign = "right";
1399                         }
1400
1401                         if (this.y - tooltipHeight < 0){
1402                                 this.yAlign = "below";
1403                         }
1404
1405
1406                         var tooltipX = this.x - tooltipWidth/2,
1407                                 tooltipY = this.y - tooltipHeight;
1408
1409                         ctx.fillStyle = this.fillColor;
1410
1411                         // Custom Tooltips
1412                         if(this.custom){
1413                                 this.custom(this);
1414                         }
1415                         else{
1416                                 switch(this.yAlign)
1417                                 {
1418                                 case "above":
1419                                         //Draw a caret above the x/y
1420                                         ctx.beginPath();
1421                                         ctx.moveTo(this.x,this.y - caretPadding);
1422                                         ctx.lineTo(this.x + this.caretHeight, this.y - (caretPadding + this.caretHeight));
1423                                         ctx.lineTo(this.x - this.caretHeight, this.y - (caretPadding + this.caretHeight));
1424                                         ctx.closePath();
1425                                         ctx.fill();
1426                                         break;
1427                                 case "below":
1428                                         tooltipY = this.y + caretPadding + this.caretHeight;
1429                                         //Draw a caret below the x/y
1430                                         ctx.beginPath();
1431                                         ctx.moveTo(this.x, this.y + caretPadding);
1432                                         ctx.lineTo(this.x + this.caretHeight, this.y + caretPadding + this.caretHeight);
1433                                         ctx.lineTo(this.x - this.caretHeight, this.y + caretPadding + this.caretHeight);
1434                                         ctx.closePath();
1435                                         ctx.fill();
1436                                         break;
1437                                 }
1438
1439                                 switch(this.xAlign)
1440                                 {
1441                                 case "left":
1442                                         tooltipX = this.x - tooltipWidth + (this.cornerRadius + this.caretHeight);
1443                                         break;
1444                                 case "right":
1445                                         tooltipX = this.x - (this.cornerRadius + this.caretHeight);
1446                                         break;
1447                                 }
1448
1449                                 drawRoundedRectangle(ctx,tooltipX,tooltipY,tooltipWidth,tooltipRectHeight,this.cornerRadius);
1450
1451                                 ctx.fill();
1452
1453                                 ctx.fillStyle = this.textColor;
1454                                 ctx.textAlign = "center";
1455                                 ctx.textBaseline = "middle";
1456                                 ctx.fillText(this.text, tooltipX + tooltipWidth/2, tooltipY + tooltipRectHeight/2);
1457                         }
1458                 }
1459         });
1460
1461         Chart.MultiTooltip = Chart.Element.extend({
1462                 initialize : function(){
1463                         this.font = fontString(this.fontSize,this.fontStyle,this.fontFamily);
1464
1465                         this.titleFont = fontString(this.titleFontSize,this.titleFontStyle,this.titleFontFamily);
1466
1467                         this.height = (this.labels.length * this.fontSize) + ((this.labels.length-1) * (this.fontSize/2)) + (this.yPadding*2) + this.titleFontSize *1.5;
1468
1469                         this.ctx.font = this.titleFont;
1470
1471                         var titleWidth = this.ctx.measureText(this.title).width,
1472                                 //Label has a legend square as well so account for this.
1473                                 labelWidth = longestText(this.ctx,this.font,this.labels) + this.fontSize + 3,
1474                                 longestTextWidth = max([labelWidth,titleWidth]);
1475
1476                         this.width = longestTextWidth + (this.xPadding*2);
1477
1478
1479                         var halfHeight = this.height/2;
1480
1481                         //Check to ensure the height will fit on the canvas
1482                         if (this.y - halfHeight < 0 ){
1483                                 this.y = halfHeight;
1484                         } else if (this.y + halfHeight > this.chart.height){
1485                                 this.y = this.chart.height - halfHeight;
1486                         }
1487
1488                         //Decide whether to align left or right based on position on canvas
1489                         if (this.x > this.chart.width/2){
1490                                 this.x -= this.xOffset + this.width;
1491                         } else {
1492                                 this.x += this.xOffset;
1493                         }
1494
1495
1496                 },
1497                 getLineHeight : function(index){
1498                         var baseLineHeight = this.y - (this.height/2) + this.yPadding,
1499                                 afterTitleIndex = index-1;
1500
1501                         //If the index is zero, we're getting the title
1502                         if (index === 0){
1503                                 return baseLineHeight + this.titleFontSize/2;
1504                         } else{
1505                                 return baseLineHeight + ((this.fontSize*1.5*afterTitleIndex) + this.fontSize/2) + this.titleFontSize * 1.5;
1506                         }
1507
1508                 },
1509                 draw : function(){
1510                         // Custom Tooltips
1511                         if(this.custom){
1512                                 this.custom(this);
1513                         }
1514                         else{
1515                                 drawRoundedRectangle(this.ctx,this.x,this.y - this.height/2,this.width,this.height,this.cornerRadius);
1516                                 var ctx = this.ctx;
1517                                 ctx.fillStyle = this.fillColor;
1518                                 ctx.fill();
1519                                 ctx.closePath();
1520
1521                                 ctx.textAlign = "left";
1522                                 ctx.textBaseline = "middle";
1523                                 ctx.fillStyle = this.titleTextColor;
1524                                 ctx.font = this.titleFont;
1525
1526                                 ctx.fillText(this.title,this.x + this.xPadding, this.getLineHeight(0));
1527
1528                                 ctx.font = this.font;
1529                                 helpers.each(this.labels,function(label,index){
1530                                         ctx.fillStyle = this.textColor;
1531                                         ctx.fillText(label,this.x + this.xPadding + this.fontSize + 3, this.getLineHeight(index + 1));
1532
1533                                         //A bit gnarly, but clearing this rectangle breaks when using explorercanvas (clears whole canvas)
1534                                         //ctx.clearRect(this.x + this.xPadding, this.getLineHeight(index + 1) - this.fontSize/2, this.fontSize, this.fontSize);
1535                                         //Instead we'll make a white filled block to put the legendColour palette over.
1536
1537                                         ctx.fillStyle = this.legendColorBackground;
1538                                         ctx.fillRect(this.x + this.xPadding, this.getLineHeight(index + 1) - this.fontSize/2, this.fontSize, this.fontSize);
1539
1540                                         ctx.fillStyle = this.legendColors[index].fill;
1541                                         ctx.fillRect(this.x + this.xPadding, this.getLineHeight(index + 1) - this.fontSize/2, this.fontSize, this.fontSize);
1542
1543
1544                                 },this);
1545                         }
1546                 }
1547         });
1548
1549         Chart.Scale = Chart.Element.extend({
1550                 initialize : function(){
1551                         this.fit();
1552                 },
1553                 buildYLabels : function(){
1554                         this.yLabels = [];
1555
1556                         var stepDecimalPlaces = getDecimalPlaces(this.stepValue);
1557
1558                         for (var i=0; i<=this.steps; i++){
1559                                 this.yLabels.push(template(this.templateString,{value:(this.min + (i * this.stepValue)).toFixed(stepDecimalPlaces)}));
1560                         }
1561                         this.yLabelWidth = (this.display && this.showLabels) ? longestText(this.ctx,this.font,this.yLabels) + 10 : 0;
1562                 },
1563                 addXLabel : function(label){
1564                         this.xLabels.push(label);
1565                         this.valuesCount++;
1566                         this.fit();
1567                 },
1568                 removeXLabel : function(){
1569                         this.xLabels.shift();
1570                         this.valuesCount--;
1571                         this.fit();
1572                 },
1573                 // Fitting loop to rotate x Labels and figure out what fits there, and also calculate how many Y steps to use
1574                 fit: function(){
1575                         // First we need the width of the yLabels, assuming the xLabels aren't rotated
1576
1577                         // To do that we need the base line at the top and base of the chart, assuming there is no x label rotation
1578                         this.startPoint = (this.display) ? this.fontSize : 0;
1579                         this.endPoint = (this.display) ? this.height - (this.fontSize * 1.5) - 5 : this.height; // -5 to pad labels
1580
1581                         // Apply padding settings to the start and end point.
1582                         this.startPoint += this.padding;
1583                         this.endPoint -= this.padding;
1584
1585                         // Cache the starting endpoint, excluding the space for x labels
1586                         var cachedEndPoint = this.endPoint;
1587
1588                         // Cache the starting height, so can determine if we need to recalculate the scale yAxis
1589                         var cachedHeight = this.endPoint - this.startPoint,
1590                                 cachedYLabelWidth;
1591
1592                         // Build the current yLabels so we have an idea of what size they'll be to start
1593                         /*
1594                          *      This sets what is returned from calculateScaleRange as static properties of this class:
1595                          *
1596                                 this.steps;
1597                                 this.stepValue;
1598                                 this.min;
1599                                 this.max;
1600                          *
1601                          */
1602                         this.calculateYRange(cachedHeight);
1603
1604                         // With these properties set we can now build the array of yLabels
1605                         // and also the width of the largest yLabel
1606                         this.buildYLabels();
1607
1608                         this.calculateXLabelRotation();
1609
1610                         while((cachedHeight > this.endPoint - this.startPoint)){
1611                                 cachedHeight = this.endPoint - this.startPoint;
1612                                 cachedYLabelWidth = this.yLabelWidth;
1613
1614                                 this.calculateYRange(cachedHeight);
1615                                 this.buildYLabels();
1616
1617                                 // Only go through the xLabel loop again if the yLabel width has changed
1618                                 if (cachedYLabelWidth < this.yLabelWidth){
1619                                         this.endPoint = cachedEndPoint;
1620                                         this.calculateXLabelRotation();
1621                                 }
1622                         }
1623
1624                 },
1625                 calculateXLabelRotation : function(){
1626                         //Get the width of each grid by calculating the difference
1627                         //between x offsets between 0 and 1.
1628
1629                         this.ctx.font = this.font;
1630
1631                         var firstWidth = this.ctx.measureText(this.xLabels[0]).width,
1632                                 lastWidth = this.ctx.measureText(this.xLabels[this.xLabels.length - 1]).width,
1633                                 firstRotated,
1634                                 lastRotated;
1635
1636
1637                         this.xScalePaddingRight = lastWidth/2 + 3;
1638                         this.xScalePaddingLeft = (firstWidth/2 > this.yLabelWidth) ? firstWidth/2 : this.yLabelWidth;
1639
1640                         this.xLabelRotation = 0;
1641                         if (this.display){
1642                                 var originalLabelWidth = longestText(this.ctx,this.font,this.xLabels),
1643                                         cosRotation,
1644                                         firstRotatedWidth;
1645                                 this.xLabelWidth = originalLabelWidth;
1646                                 //Allow 3 pixels x2 padding either side for label readability
1647                                 var xGridWidth = Math.floor(this.calculateX(1) - this.calculateX(0)) - 6;
1648
1649                                 //Max label rotate should be 90 - also act as a loop counter
1650                                 while ((this.xLabelWidth > xGridWidth && this.xLabelRotation === 0) || (this.xLabelWidth > xGridWidth && this.xLabelRotation <= 90 && this.xLabelRotation > 0)){
1651                                         cosRotation = Math.cos(toRadians(this.xLabelRotation));
1652
1653                                         firstRotated = cosRotation * firstWidth;
1654                                         lastRotated = cosRotation * lastWidth;
1655
1656                                         // We're right aligning the text now.
1657                                         if (firstRotated + this.fontSize / 2 > this.yLabelWidth){
1658                                                 this.xScalePaddingLeft = firstRotated + this.fontSize / 2;
1659                                         }
1660                                         this.xScalePaddingRight = this.fontSize/2;
1661
1662
1663                                         this.xLabelRotation++;
1664                                         this.xLabelWidth = cosRotation * originalLabelWidth;
1665
1666                                 }
1667                                 if (this.xLabelRotation > 0){
1668                                         this.endPoint -= Math.sin(toRadians(this.xLabelRotation))*originalLabelWidth + 3;
1669                                 }
1670                         }
1671                         else{
1672                                 this.xLabelWidth = 0;
1673                                 this.xScalePaddingRight = this.padding;
1674                                 this.xScalePaddingLeft = this.padding;
1675                         }
1676
1677                 },
1678                 // Needs to be overidden in each Chart type
1679                 // Otherwise we need to pass all the data into the scale class
1680                 calculateYRange: noop,
1681                 drawingArea: function(){
1682                         return this.startPoint - this.endPoint;
1683                 },
1684                 calculateY : function(value){
1685                         var scalingFactor = this.drawingArea() / (this.min - this.max);
1686                         return this.endPoint - (scalingFactor * (value - this.min));
1687                 },
1688                 calculateX : function(index){
1689                         var isRotated = (this.xLabelRotation > 0),
1690                                 // innerWidth = (this.offsetGridLines) ? this.width - offsetLeft - this.padding : this.width - (offsetLeft + halfLabelWidth * 2) - this.padding,
1691                                 innerWidth = this.width - (this.xScalePaddingLeft + this.xScalePaddingRight),
1692                                 valueWidth = innerWidth/Math.max((this.valuesCount - ((this.offsetGridLines) ? 0 : 1)), 1),
1693                                 valueOffset = (valueWidth * index) + this.xScalePaddingLeft;
1694
1695                         if (this.offsetGridLines){
1696                                 valueOffset += (valueWidth/2);
1697                         }
1698
1699                         return Math.round(valueOffset);
1700                 },
1701                 update : function(newProps){
1702                         helpers.extend(this, newProps);
1703                         this.fit();
1704                 },
1705                 draw : function(){
1706                         var ctx = this.ctx,
1707                                 yLabelGap = (this.endPoint - this.startPoint) / this.steps,
1708                                 xStart = Math.round(this.xScalePaddingLeft);
1709                         if (this.display){
1710                                 ctx.fillStyle = this.textColor;
1711                                 ctx.font = this.font;
1712                                 each(this.yLabels,function(labelString,index){
1713                                         var yLabelCenter = this.endPoint - (yLabelGap * index),
1714                                                 linePositionY = Math.round(yLabelCenter),
1715                                                 drawHorizontalLine = this.showHorizontalLines;
1716
1717                                         ctx.textAlign = "right";
1718                                         ctx.textBaseline = "middle";
1719                                         if (this.showLabels){
1720                                                 ctx.fillText(labelString,xStart - 10,yLabelCenter);
1721                                         }
1722
1723                                         // This is X axis, so draw it
1724                                         if (index === 0 && !drawHorizontalLine){
1725                                                 drawHorizontalLine = true;
1726                                         }
1727
1728                                         if (drawHorizontalLine){
1729                                                 ctx.beginPath();
1730                                         }
1731
1732                                         if (index > 0){
1733                                                 // This is a grid line in the centre, so drop that
1734                                                 ctx.lineWidth = this.gridLineWidth;
1735                                                 ctx.strokeStyle = this.gridLineColor;
1736                                         } else {
1737                                                 // This is the first line on the scale
1738                                                 ctx.lineWidth = this.lineWidth;
1739                                                 ctx.strokeStyle = this.lineColor;
1740                                         }
1741
1742                                         linePositionY += helpers.aliasPixel(ctx.lineWidth);
1743
1744                                         if(drawHorizontalLine){
1745                                                 ctx.moveTo(xStart, linePositionY);
1746                                                 ctx.lineTo(this.width, linePositionY);
1747                                                 ctx.stroke();
1748                                                 ctx.closePath();
1749                                         }
1750
1751                                         ctx.lineWidth = this.lineWidth;
1752                                         ctx.strokeStyle = this.lineColor;
1753                                         ctx.beginPath();
1754                                         ctx.moveTo(xStart - 5, linePositionY);
1755                                         ctx.lineTo(xStart, linePositionY);
1756                                         ctx.stroke();
1757                                         ctx.closePath();
1758
1759                                 },this);
1760
1761                                 each(this.xLabels,function(label,index){
1762                                         var xPos = this.calculateX(index) + aliasPixel(this.lineWidth),
1763                                                 // Check to see if line/bar here and decide where to place the line
1764                                                 linePos = this.calculateX(index - (this.offsetGridLines ? 0.5 : 0)) + aliasPixel(this.lineWidth),
1765                                                 isRotated = (this.xLabelRotation > 0),
1766                                                 drawVerticalLine = this.showVerticalLines;
1767
1768                                         // This is Y axis, so draw it
1769                                         if (index === 0 && !drawVerticalLine){
1770                                                 drawVerticalLine = true;
1771                                         }
1772
1773                                         if (drawVerticalLine){
1774                                                 ctx.beginPath();
1775                                         }
1776
1777                                         if (index > 0){
1778                                                 // This is a grid line in the centre, so drop that
1779                                                 ctx.lineWidth = this.gridLineWidth;
1780                                                 ctx.strokeStyle = this.gridLineColor;
1781                                         } else {
1782                                                 // This is the first line on the scale
1783                                                 ctx.lineWidth = this.lineWidth;
1784                                                 ctx.strokeStyle = this.lineColor;
1785                                         }
1786
1787                                         if (drawVerticalLine){
1788                                                 ctx.moveTo(linePos,this.endPoint);
1789                                                 ctx.lineTo(linePos,this.startPoint - 3);
1790                                                 ctx.stroke();
1791                                                 ctx.closePath();
1792                                         }
1793
1794
1795                                         ctx.lineWidth = this.lineWidth;
1796                                         ctx.strokeStyle = this.lineColor;
1797
1798
1799                                         // Small lines at the bottom of the base grid line
1800                                         ctx.beginPath();
1801                                         ctx.moveTo(linePos,this.endPoint);
1802                                         ctx.lineTo(linePos,this.endPoint + 5);
1803                                         ctx.stroke();
1804                                         ctx.closePath();
1805
1806                                         ctx.save();
1807                                         ctx.translate(xPos,(isRotated) ? this.endPoint + 12 : this.endPoint + 8);
1808                                         ctx.rotate(toRadians(this.xLabelRotation)*-1);
1809                                         ctx.font = this.font;
1810                                         ctx.textAlign = (isRotated) ? "right" : "center";
1811                                         ctx.textBaseline = (isRotated) ? "middle" : "top";
1812                                         ctx.fillText(label, 0, 0);
1813                                         ctx.restore();
1814                                 },this);
1815
1816                         }
1817                 }
1818
1819         });
1820
1821         Chart.RadialScale = Chart.Element.extend({
1822                 initialize: function(){
1823                         this.size = min([this.height, this.width]);
1824                         this.drawingArea = (this.display) ? (this.size/2) - (this.fontSize/2 + this.backdropPaddingY) : (this.size/2);
1825                 },
1826                 calculateCenterOffset: function(value){
1827                         // Take into account half font size + the yPadding of the top value
1828                         var scalingFactor = this.drawingArea / (this.max - this.min);
1829
1830                         return (value - this.min) * scalingFactor;
1831                 },
1832                 update : function(){
1833                         if (!this.lineArc){
1834                                 this.setScaleSize();
1835                         } else {
1836                                 this.drawingArea = (this.display) ? (this.size/2) - (this.fontSize/2 + this.backdropPaddingY) : (this.size/2);
1837                         }
1838                         this.buildYLabels();
1839                 },
1840                 buildYLabels: function(){
1841                         this.yLabels = [];
1842
1843                         var stepDecimalPlaces = getDecimalPlaces(this.stepValue);
1844
1845                         for (var i=0; i<=this.steps; i++){
1846                                 this.yLabels.push(template(this.templateString,{value:(this.min + (i * this.stepValue)).toFixed(stepDecimalPlaces)}));
1847                         }
1848                 },
1849                 getCircumference : function(){
1850                         return ((Math.PI*2) / this.valuesCount);
1851                 },
1852                 setScaleSize: function(){
1853                         /*
1854                          * Right, this is really confusing and there is a lot of maths going on here
1855                          * The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9
1856                          *
1857                          * Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif
1858                          *
1859                          * Solution:
1860                          *
1861                          * We assume the radius of the polygon is half the size of the canvas at first
1862                          * at each index we check if the text overlaps.
1863                          *
1864                          * Where it does, we store that angle and that index.
1865                          *
1866                          * After finding the largest index and angle we calculate how much we need to remove
1867                          * from the shape radius to move the point inwards by that x.
1868                          *
1869                          * We average the left and right distances to get the maximum shape radius that can fit in the box
1870                          * along with labels.
1871                          *
1872                          * Once we have that, we can find the centre point for the chart, by taking the x text protrusion
1873                          * on each side, removing that from the size, halving it and adding the left x protrusion width.
1874                          *
1875                          * This will mean we have a shape fitted to the canvas, as large as it can be with the labels
1876                          * and position it in the most space efficient manner
1877                          *
1878                          * https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif
1879                          */
1880
1881
1882                         // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width.
1883                         // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points
1884                         var largestPossibleRadius = min([(this.height/2 - this.pointLabelFontSize - 5), this.width/2]),
1885                                 pointPosition,
1886                                 i,
1887                                 textWidth,
1888                                 halfTextWidth,
1889                                 furthestRight = this.width,
1890                                 furthestRightIndex,
1891                                 furthestRightAngle,
1892                                 furthestLeft = 0,
1893                                 furthestLeftIndex,
1894                                 furthestLeftAngle,
1895                                 xProtrusionLeft,
1896                                 xProtrusionRight,
1897                                 radiusReductionRight,
1898                                 radiusReductionLeft,
1899                                 maxWidthRadius;
1900                         this.ctx.font = fontString(this.pointLabelFontSize,this.pointLabelFontStyle,this.pointLabelFontFamily);
1901                         for (i=0;i<this.valuesCount;i++){
1902                                 // 5px to space the text slightly out - similar to what we do in the draw function.
1903                                 pointPosition = this.getPointPosition(i, largestPossibleRadius);
1904                                 textWidth = this.ctx.measureText(template(this.templateString, { value: this.labels[i] })).width + 5;
1905                                 if (i === 0 || i === this.valuesCount/2){
1906                                         // If we're at index zero, or exactly the middle, we're at exactly the top/bottom
1907                                         // of the radar chart, so text will be aligned centrally, so we'll half it and compare
1908                                         // w/left and right text sizes
1909                                         halfTextWidth = textWidth/2;
1910                                         if (pointPosition.x + halfTextWidth > furthestRight) {
1911                                                 furthestRight = pointPosition.x + halfTextWidth;
1912                                                 furthestRightIndex = i;
1913                                         }
1914                                         if (pointPosition.x - halfTextWidth < furthestLeft) {
1915                                                 furthestLeft = pointPosition.x - halfTextWidth;
1916                                                 furthestLeftIndex = i;
1917                                         }
1918                                 }
1919                                 else if (i < this.valuesCount/2) {
1920                                         // Less than half the values means we'll left align the text
1921                                         if (pointPosition.x + textWidth > furthestRight) {
1922                                                 furthestRight = pointPosition.x + textWidth;
1923                                                 furthestRightIndex = i;
1924                                         }
1925                                 }
1926                                 else if (i > this.valuesCount/2){
1927                                         // More than half the values means we'll right align the text
1928                                         if (pointPosition.x - textWidth < furthestLeft) {
1929                                                 furthestLeft = pointPosition.x - textWidth;
1930                                                 furthestLeftIndex = i;
1931                                         }
1932                                 }
1933                         }
1934
1935                         xProtrusionLeft = furthestLeft;
1936
1937                         xProtrusionRight = Math.ceil(furthestRight - this.width);
1938
1939                         furthestRightAngle = this.getIndexAngle(furthestRightIndex);
1940
1941                         furthestLeftAngle = this.getIndexAngle(furthestLeftIndex);
1942
1943                         radiusReductionRight = xProtrusionRight / Math.sin(furthestRightAngle + Math.PI/2);
1944
1945                         radiusReductionLeft = xProtrusionLeft / Math.sin(furthestLeftAngle + Math.PI/2);
1946
1947                         // Ensure we actually need to reduce the size of the chart
1948                         radiusReductionRight = (isNumber(radiusReductionRight)) ? radiusReductionRight : 0;
1949                         radiusReductionLeft = (isNumber(radiusReductionLeft)) ? radiusReductionLeft : 0;
1950
1951                         this.drawingArea = largestPossibleRadius - (radiusReductionLeft + radiusReductionRight)/2;
1952
1953                         //this.drawingArea = min([maxWidthRadius, (this.height - (2 * (this.pointLabelFontSize + 5)))/2])
1954                         this.setCenterPoint(radiusReductionLeft, radiusReductionRight);
1955
1956                 },
1957                 setCenterPoint: function(leftMovement, rightMovement){
1958
1959                         var maxRight = this.width - rightMovement - this.drawingArea,
1960                                 maxLeft = leftMovement + this.drawingArea;
1961
1962                         this.xCenter = (maxLeft + maxRight)/2;
1963                         // Always vertically in the centre as the text height doesn't change
1964                         this.yCenter = (this.height/2);
1965                 },
1966
1967                 getIndexAngle : function(index){
1968                         var angleMultiplier = (Math.PI * 2) / this.valuesCount;
1969                         // Start from the top instead of right, so remove a quarter of the circle
1970
1971                         return index * angleMultiplier - (Math.PI/2);
1972                 },
1973                 getPointPosition : function(index, distanceFromCenter){
1974                         var thisAngle = this.getIndexAngle(index);
1975                         return {
1976                                 x : (Math.cos(thisAngle) * distanceFromCenter) + this.xCenter,
1977                                 y : (Math.sin(thisAngle) * distanceFromCenter) + this.yCenter
1978                         };
1979                 },
1980                 draw: function(){
1981                         if (this.display){
1982                                 var ctx = this.ctx;
1983                                 each(this.yLabels, function(label, index){
1984                                         // Don't draw a centre value
1985                                         if (index > 0){
1986                                                 var yCenterOffset = index * (this.drawingArea/this.steps),
1987                                                         yHeight = this.yCenter - yCenterOffset,
1988                                                         pointPosition;
1989
1990                                                 // Draw circular lines around the scale
1991                                                 if (this.lineWidth > 0){
1992                                                         ctx.strokeStyle = this.lineColor;
1993                                                         ctx.lineWidth = this.lineWidth;
1994
1995                                                         if(this.lineArc){
1996                                                                 ctx.beginPath();
1997                                                                 ctx.arc(this.xCenter, this.yCenter, yCenterOffset, 0, Math.PI*2);
1998                                                                 ctx.closePath();
1999                                                                 ctx.stroke();
2000                                                         } else{
2001                                                                 ctx.beginPath();
2002                                                                 for (var i=0;i<this.valuesCount;i++)
2003                                                                 {
2004                                                                         pointPosition = this.getPointPosition(i, this.calculateCenterOffset(this.min + (index * this.stepValue)));
2005                                                                         if (i === 0){
2006                                                                                 ctx.moveTo(pointPosition.x, pointPosition.y);
2007                                                                         } else {
2008                                                                                 ctx.lineTo(pointPosition.x, pointPosition.y);
2009                                                                         }
2010                                                                 }
2011                                                                 ctx.closePath();
2012                                                                 ctx.stroke();
2013                                                         }
2014                                                 }
2015                                                 if(this.showLabels){
2016                                                         ctx.font = fontString(this.fontSize,this.fontStyle,this.fontFamily);
2017                                                         if (this.showLabelBackdrop){
2018                                                                 var labelWidth = ctx.measureText(label).width;
2019                                                                 ctx.fillStyle = this.backdropColor;
2020                                                                 ctx.fillRect(
2021                                                                         this.xCenter - labelWidth/2 - this.backdropPaddingX,
2022                                                                         yHeight - this.fontSize/2 - this.backdropPaddingY,
2023                                                                         labelWidth + this.backdropPaddingX*2,
2024                                                                         this.fontSize + this.backdropPaddingY*2
2025                                                                 );
2026                                                         }
2027                                                         ctx.textAlign = 'center';
2028                                                         ctx.textBaseline = "middle";
2029                                                         ctx.fillStyle = this.fontColor;
2030                                                         ctx.fillText(label, this.xCenter, yHeight);
2031                                                 }
2032                                         }
2033                                 }, this);
2034
2035                                 if (!this.lineArc){
2036                                         ctx.lineWidth = this.angleLineWidth;
2037                                         ctx.strokeStyle = this.angleLineColor;
2038                                         for (var i = this.valuesCount - 1; i >= 0; i--) {
2039                                                 if (this.angleLineWidth > 0){
2040                                                         var outerPosition = this.getPointPosition(i, this.calculateCenterOffset(this.max));
2041                                                         ctx.beginPath();
2042                                                         ctx.moveTo(this.xCenter, this.yCenter);
2043                                                         ctx.lineTo(outerPosition.x, outerPosition.y);
2044                                                         ctx.stroke();
2045                                                         ctx.closePath();
2046                                                 }
2047                                                 // Extra 3px out for some label spacing
2048                                                 var pointLabelPosition = this.getPointPosition(i, this.calculateCenterOffset(this.max) + 5);
2049                                                 ctx.font = fontString(this.pointLabelFontSize,this.pointLabelFontStyle,this.pointLabelFontFamily);
2050                                                 ctx.fillStyle = this.pointLabelFontColor;
2051
2052                                                 var labelsCount = this.labels.length,
2053                                                         halfLabelsCount = this.labels.length/2,
2054                                                         quarterLabelsCount = halfLabelsCount/2,
2055                                                         upperHalf = (i < quarterLabelsCount || i > labelsCount - quarterLabelsCount),
2056                                                         exactQuarter = (i === quarterLabelsCount || i === labelsCount - quarterLabelsCount);
2057                                                 if (i === 0){
2058                                                         ctx.textAlign = 'center';
2059                                                 } else if(i === halfLabelsCount){
2060                                                         ctx.textAlign = 'center';
2061                                                 } else if (i < halfLabelsCount){
2062                                                         ctx.textAlign = 'left';
2063                                                 } else {
2064                                                         ctx.textAlign = 'right';
2065                                                 }
2066
2067                                                 // Set the correct text baseline based on outer positioning
2068                                                 if (exactQuarter){
2069                                                         ctx.textBaseline = 'middle';
2070                                                 } else if (upperHalf){
2071                                                         ctx.textBaseline = 'bottom';
2072                                                 } else {
2073                                                         ctx.textBaseline = 'top';
2074                                                 }
2075
2076                                                 ctx.fillText(this.labels[i], pointLabelPosition.x, pointLabelPosition.y);
2077                                         }
2078                                 }
2079                         }
2080                 }
2081         });
2082
2083         Chart.animationService = {
2084                 frameDuration: 17,
2085                 animations: [],
2086                 dropFrames: 0,
2087                 addAnimation: function(chartInstance, animationObject) {
2088                         for (var index = 0; index < this.animations.length; ++ index){
2089                                 if (this.animations[index].chartInstance === chartInstance){
2090                                         // replacing an in progress animation
2091                                         this.animations[index].animationObject = animationObject;
2092                                         return;
2093                                 }
2094                         }
2095                         
2096                         this.animations.push({
2097                                 chartInstance: chartInstance,
2098                                 animationObject: animationObject
2099                         });
2100
2101                         // If there are no animations queued, manually kickstart a digest, for lack of a better word
2102                         if (this.animations.length == 1) {
2103                                 helpers.requestAnimFrame.call(window, this.digestWrapper);
2104                         }
2105                 },
2106                 // Cancel the animation for a given chart instance
2107                 cancelAnimation: function(chartInstance) {
2108                         var index = helpers.findNextWhere(this.animations, function(animationWrapper) {
2109                                 return animationWrapper.chartInstance === chartInstance;
2110                         });
2111                         
2112                         if (index)
2113                         {
2114                                 this.animations.splice(index, 1);
2115                         }
2116                 },
2117                 // calls startDigest with the proper context
2118                 digestWrapper: function() {
2119                         Chart.animationService.startDigest.call(Chart.animationService);
2120                 },
2121                 startDigest: function() {
2122
2123                         var startTime = Date.now();
2124                         var framesToDrop = 0;
2125
2126                         if(this.dropFrames > 1){
2127                                 framesToDrop = Math.floor(this.dropFrames);
2128                                 this.dropFrames -= framesToDrop;
2129                         }
2130
2131                         for (var i = 0; i < this.animations.length; i++) {
2132
2133                                 if (this.animations[i].animationObject.currentStep === null){
2134                                         this.animations[i].animationObject.currentStep = 0;
2135                                 }
2136
2137                                 this.animations[i].animationObject.currentStep += 1 + framesToDrop;
2138                                 if(this.animations[i].animationObject.currentStep > this.animations[i].animationObject.numSteps){
2139                                         this.animations[i].animationObject.currentStep = this.animations[i].animationObject.numSteps;
2140                                 }
2141                                 
2142                                 this.animations[i].animationObject.render(this.animations[i].chartInstance, this.animations[i].animationObject);
2143                                 
2144                                 if (this.animations[i].animationObject.currentStep == this.animations[i].animationObject.numSteps){
2145                                         // executed the last frame. Remove the animation.
2146                                         this.animations.splice(i, 1);
2147                                         // Keep the index in place to offset the splice
2148                                         i--;
2149                                 }
2150                         }
2151
2152                         var endTime = Date.now();
2153                         var delay = endTime - startTime - this.frameDuration;
2154                         var frameDelay = delay / this.frameDuration;
2155
2156                         if(frameDelay > 1){
2157                                 this.dropFrames += frameDelay;
2158                         }
2159
2160                         // Do we have more stuff to animate?
2161                         if (this.animations.length > 0){
2162                                 helpers.requestAnimFrame.call(window, this.digestWrapper);
2163                         }
2164                 }
2165         };
2166
2167         // Attach global event to resize each chart instance when the browser resizes
2168         helpers.addEvent(window, "resize", (function(){
2169                 // Basic debounce of resize function so it doesn't hurt performance when resizing browser.
2170                 var timeout;
2171                 return function(){
2172                         clearTimeout(timeout);
2173                         timeout = setTimeout(function(){
2174                                 each(Chart.instances,function(instance){
2175                                         // If the responsive flag is set in the chart instance config
2176                                         // Cascade the resize event down to the chart.
2177                                         if (instance.options.responsive){
2178                                                 instance.resize(instance.render, true);
2179                                         }
2180                                 });
2181                         }, 50);
2182                 };
2183         })());
2184
2185
2186         if (amd) {
2187                 define(function(){
2188                         return Chart;
2189                 });
2190         } else if (typeof module === 'object' && module.exports) {
2191                 module.exports = Chart;
2192         }
2193
2194         root.Chart = Chart;
2195
2196         Chart.noConflict = function(){
2197                 root.Chart = previous;
2198                 return Chart;
2199         };
2200
2201 }).call(this);