]> arthur.barton.de Git - netdata.git/blob - web/dashboard.js
added dark theme; which is now the default;
[netdata.git] / web / dashboard.js
1 // You can set the following variables before loading this script:
2 //
3 // var netdataNoDygraphs = true;                // do not use dygraph
4 // var netdataNoSparklines = true;              // do not use sparkline
5 // var netdataNoPeitys = true;                  // do not use peity
6 // var netdataNoGoogleCharts = true;    // do not use google
7 // var netdataNoMorris = true;                  // do not use morris
8 // var netdataNoEasyPieChart = true;    // do not use easy pie chart
9 // var netdataNoGauge = true;                   // do not use gauge.js
10 // var netdataNoD3 = true;                              // do not use D3
11 // var netdataNoC3 = true;                              // do not use C3
12 // var netdataNoBootstrap = true;               // do not load bootstrap
13 // var netdataDontStart = true;                 // do not start the thread to process the charts
14 //
15 // You can also set the default netdata server, using the following.
16 // When this variable is not set, we assume the page is hosted on your
17 // netdata server already.
18 // var netdataServer = "http://yourhost:19999"; // set your NetData server
19
20 //(function(window, document, undefined) {
21         // fix IE issue with console
22         if(!window.console){ window.console = {log: function(){} }; }
23
24         // global namespace
25         var NETDATA = window.NETDATA || {};
26
27         // ----------------------------------------------------------------------------------------------------------------
28         // Detect the netdata server
29
30         // http://stackoverflow.com/questions/984510/what-is-my-script-src-url
31         // http://stackoverflow.com/questions/6941533/get-protocol-domain-and-port-from-url
32         NETDATA._scriptSource = function() {
33                 var script = null;
34
35                 if(typeof document.currentScript !== 'undefined') {
36                         script = document.currentScript;
37                 }
38                 else {
39                         var all_scripts = document.getElementsByTagName('script');
40                         script = all_scripts[all_scripts.length - 1];
41                 }
42
43                 if (typeof script.getAttribute.length !== 'undefined')
44                         script = script.src;
45                 else
46                         script = script.getAttribute('src', -1);
47
48                 return script;
49         };
50
51         if(typeof netdataServer !== 'undefined')
52                 NETDATA.serverDefault = netdataServer;
53         else {
54                 var s = NETDATA._scriptSource();
55                 NETDATA.serverDefault = s.replace(/\/dashboard.js(\?.*)*$/g, "");
56         }
57
58         if(NETDATA.serverDefault === null)
59                 NETDATA.serverDefault = '';
60         else if(NETDATA.serverDefault.slice(-1) !== '/')
61                 NETDATA.serverDefault += '/';
62
63         // default URLs for all the external files we need
64         // make them RELATIVE so that the whole thing can also be
65         // installed under a web server
66         NETDATA.jQuery                  = NETDATA.serverDefault + 'lib/jquery-1.12.0.min.js';
67         NETDATA.peity_js                = NETDATA.serverDefault + 'lib/jquery.peity.min.js';
68         NETDATA.sparkline_js            = NETDATA.serverDefault + 'lib/jquery.sparkline.min.js';
69         NETDATA.easypiechart_js         = NETDATA.serverDefault + 'lib/jquery.easypiechart.min.js';
70         NETDATA.gauge_js                        = NETDATA.serverDefault + 'lib/gauge.min.js';
71         NETDATA.dygraph_js              = NETDATA.serverDefault + 'lib/dygraph-combined.js';
72         NETDATA.dygraph_smooth_js   = NETDATA.serverDefault + 'lib/dygraph-smooth-plotter.js';
73         NETDATA.raphael_js              = NETDATA.serverDefault + 'lib/raphael-min.js';
74         NETDATA.morris_js               = NETDATA.serverDefault + 'lib/morris.min.js';
75         NETDATA.d3_js                           = NETDATA.serverDefault + 'lib/d3.min.js';
76         NETDATA.c3_js                           = NETDATA.serverDefault + 'lib/c3.min.js';
77         NETDATA.c3_css                          = NETDATA.serverDefault + 'css/c3.min.css';
78         NETDATA.morris_css              = NETDATA.serverDefault + 'css/morris.css';
79         NETDATA.google_js               = 'https://www.google.com/jsapi';
80
81         NETDATA.themes = {
82                 default: {
83                         bootstrap_css: NETDATA.serverDefault + 'css/bootstrap.min.css',
84                         dashboard_css: NETDATA.serverDefault + 'dashboard.css',
85                         background: '#FFFFFF',
86                         foreground: '#000000',
87                         grid: '#DDDDDD',
88                         axis: '#CCCCCC',
89                         colors: [       '#3366CC', '#DC3912',   '#109618', '#FF9900',   '#990099', '#DD4477',
90                                                 '#3B3EAC', '#66AA00',   '#0099C6', '#B82E2E',   '#AAAA11', '#5574A6',
91                                                 '#994499', '#22AA99',   '#6633CC', '#E67300',   '#316395', '#8B0707',
92                                                 '#329262', '#3B3EAC' ],
93                         easypiechart_track: '#f0f0f0',
94                         easypiechart_scale: '#dfe0e0',
95                         gauge_pointer: '#C0C0C0',
96                         gauge_stroke: '#F0F0F0',
97                         gauge_gradient: true
98                 },
99                 slate: {
100                         bootstrap_css: NETDATA.serverDefault + 'css/bootstrap.slate.min.css',
101                         dashboard_css: NETDATA.serverDefault + 'dashboard.slate.css',
102                         background: '#272b30',
103                         foreground: '#C8C8C8',
104                         grid: '#373b40',
105                         axis: '#373b40',
106                         colors: [       '#66AA00', '#FE3912',   '#3366CC', '#D66300',   '#0099C6', '#DDDD00',
107                                                 '#3B3EAC', '#EE9911',   '#BB44CC', '#C83E3E',   '#990099', '#CC7700',
108                                                 '#22AA99', '#109618',   '#6633CC', '#DD4477',   '#316395', '#8B0707',
109                                                 '#329262', '#3B3EFF' ],
110                         easypiechart_track: '#373b40',
111                         easypiechart_scale: '#373b40',
112                         gauge_pointer: '#474b50',
113                         gauge_stroke: '#373b40',
114                         gauge_gradient: false
115                 }
116         };
117
118         if(typeof netdataTheme !== 'undefined' && typeof NETDATA.themes[netdataTheme] !== 'undefined')
119                 NETDATA.themes.current = NETDATA.themes[netdataTheme];
120         else
121                 NETDATA.themes.current = NETDATA.themes.default;
122
123         NETDATA.colors = NETDATA.themes.current.colors;
124
125         // these are the colors Google Charts are using
126         // we have them here to attempt emulate their look and feel on the other chart libraries
127         // http://there4.io/2012/05/02/google-chart-color-list/
128         //NETDATA.colors                = [ '#3366CC', '#DC3912', '#FF9900', '#109618', '#990099', '#3B3EAC', '#0099C6',
129         //                                              '#DD4477', '#66AA00', '#B82E2E', '#316395', '#994499', '#22AA99', '#AAAA11',
130         //                                              '#6633CC', '#E67300', '#8B0707', '#329262', '#5574A6', '#3B3EAC' ];
131
132         // an alternative set
133         // http://www.mulinblog.com/a-color-palette-optimized-for-data-visualization/
134         //                         (blue)     (red)      (orange)   (green)    (pink)     (brown)    (purple)   (yellow)   (gray)
135         //NETDATA.colors                = [ '#5DA5DA', '#F15854', '#FAA43A', '#60BD68', '#F17CB0', '#B2912F', '#B276B2', '#DECF3F', '#4D4D4D' ];
136
137         // ----------------------------------------------------------------------------------------------------------------
138         // the defaults for all charts
139
140         // if the user does not specify any of these, the following will be used
141
142         NETDATA.chartDefaults = {
143                 host: NETDATA.serverDefault,    // the server to get data from
144                 width: '100%',                                  // the chart width - can be null
145                 height: '100%',                                 // the chart height - can be null
146                 min_width: null,                                // the chart minimum width - can be null
147                 library: 'dygraph',                             // the graphing library to use
148                 method: 'average',                              // the grouping method
149                 before: 0,                                              // panning
150                 after: -600,                                    // panning
151                 pixels_per_point: 1,                    // the detail of the chart
152                 fill_luminance: 0.8                             // luminance of colors in solit areas
153         }
154
155         // ----------------------------------------------------------------------------------------------------------------
156         // global options
157
158         NETDATA.options = {
159                 pauseCallback: null,                    // a callback when we are really paused
160
161                 pause: false,                                   // when enabled we don't auto-refresh the charts
162
163                 targets: null,                                  // an array of all the state objects that are
164                                                                                 // currently active (independently of their
165                                                                                 // viewport visibility)
166
167                 updated_dom: true,                              // when true, the DOM has been updated with
168                                                                                 // new elements we have to check.
169
170                 auto_refresher_fast_weight: 0,  // this is the current time in ms, spent
171                                                                                 // rendering charts continiously.
172                                                                                 // used with .current.fast_render_timeframe
173
174                 page_is_visible: true,                  // when true, this page is visible
175
176                 auto_refresher_stop_until: 0,   // timestamp in ms - used internaly, to stop the
177                                                                                 // auto-refresher for some time (when a chart is
178                                                                                 // performing pan or zoom, we need to stop refreshing
179                                                                                 // all other charts, to have the maximum speed for
180                                                                                 // rendering the chart that is panned or zoomed).
181                                                                                 // Used with .current.global_pan_sync_time
182
183                 last_resized: new Date().getTime(), // the timestamp of the last resize request
184
185                 crossDomainAjax: false,                 // enable this to request crossDomain AJAX
186
187                 last_page_scroll: 0,                    // the timestamp the last time the page was scrolled
188
189                 // the current profile
190                 // we may have many...
191                 current: {
192                         pixels_per_point: 1,            // the minimum pixels per point for all charts
193                                                                                 // increase this to speed javascript up
194                                                                                 // each chart library has its own limit too
195                                                                                 // the max of this and the chart library is used
196                                                                                 // the final is calculated every time, so a change
197                                                                                 // here will have immediate effect on the next chart
198                                                                                 // update
199
200                         idle_between_charts: 100,       // ms - how much time to wait between chart updates
201
202                         fast_render_timeframe: 200, // ms - render continously until this time of continious
203                                                                                 // rendering has been reached
204                                                                                 // this setting is used to make it render e.g. 10
205                                                                                 // charts at once, sleep idle_between_charts time
206                                                                                 // and continue for another 10 charts.
207
208                         idle_between_loops: 500,        // ms - if all charts have been updated, wait this
209                                                                                 // time before starting again.
210
211                         idle_parallel_loops: 100,       // ms - the time between parallel refresher updates
212
213                         idle_lost_focus: 500,           // ms - when the window does not have focus, check
214                                                                                 // if focus has been regained, every this time
215
216                         global_pan_sync_time: 1000,     // ms - when you pan or zoon a chart, the background
217                                                                                 // autorefreshing of charts is paused for this amount
218                                                                                 // of time
219
220                         sync_selection_delay: 1500,     // ms - when you pan or zoom a chart, wait this amount
221                                                                                 // of time before setting up synchronized selections
222                                                                                 // on hover.
223
224                         sync_selection: true,           // enable or disable selection sync
225
226                         pan_and_zoom_delay: 50,         // when panning or zooming, how ofter to update the chart
227
228                         sync_pan_and_zoom: true,        // enable or disable pan and zoom sync
229
230                         pan_and_zoom_data_padding: true, // fetch more data for the master chart when panning or zooming
231
232                         update_only_visible: true,      // enable or disable visibility management
233
234                         parallel_refresher: true,       // enable parallel refresh of charts
235
236                         concurrent_refreshes: true,     // when parallel_refresher is enabled, sync also the charts
237
238                         destroy_on_hide: false,         // destroy charts when they are not visible
239
240                         eliminate_zero_dimensions: true, // do not show dimensions with just zeros
241
242                         stop_updates_when_focus_is_lost: true, // boolean - shall we stop auto-refreshes when document does not have user focus
243                         stop_updates_while_resizing: 1000,      // ms - time to stop auto-refreshes while resizing the charts
244
245                         double_click_speed: 500,        // ms - time between clicks / taps to detect double click/tap
246
247                         smooth_plot: true,                      // enable smooth plot, where possible
248
249                         charts_selection_animation_delay: 50, // delay to animate charts when syncing selection
250
251                         color_fill_opacity_line: 1.0,
252                         color_fill_opacity_area: 0.2,
253                         color_fill_opacity_stacked: 0.8,
254
255                         setOptionCallback: function() { ; }
256                 },
257
258                 debug: {
259                         show_boxes:             false,
260                         main_loop:                      false,
261                         focus:                          false,
262                         visibility:             false,
263                         chart_data_url:         false,
264                         chart_errors:           false, // FIXME
265                         chart_timing:           false,
266                         chart_calls:            false,
267                         libraries:                      false,
268                         dygraph:                        false
269                 }
270         }
271
272
273         // ----------------------------------------------------------------------------------------------------------------
274         // local storage options
275
276         NETDATA.localStorage = {
277                 default: {},
278                 current: {},
279                 callback: {} // only used for resetting back to defaults
280         };
281
282         NETDATA.localStorageGet = function(key, def, callback) {
283                 var ret = def;
284
285                 if(typeof NETDATA.localStorage.default[key.toString()] === 'undefined') {
286                         NETDATA.localStorage.default[key.toString()] = def;
287                         NETDATA.localStorage.callback[key.toString()] = callback;
288                 }
289
290                 if(typeof Storage !== "undefined" && typeof localStorage === 'object') {
291                         try {
292                                 // console.log('localStorage: loading "' + key.toString() + '"');
293                                 ret = localStorage.getItem(key.toString());
294                                 if(ret === null || ret === 'undefined') {
295                                         // console.log('localStorage: cannot load it, saving "' + key.toString() + '" with value "' + JSON.stringify(def) + '"');
296                                         localStorage.setItem(key.toString(), JSON.stringify(def));
297                                         ret = def;
298                                 }
299                                 else {
300                                         // console.log('localStorage: got "' + key.toString() + '" with value "' + ret + '"');
301                                         ret = JSON.parse(ret);
302                                         // console.log('localStorage: loaded "' + key.toString() + '" as value ' + ret + ' of type ' + typeof(ret));
303                                 }
304                         }
305                         catch(error) {
306                                 console.log('localStorage: failed to read "' + key.toString() + '", using default: "' + def.toString() + '"');
307                                 ret = def;
308                         }
309                 }
310
311                 if(typeof ret === 'undefined' || ret === 'undefined') {
312                         console.log('localStorage: LOADED UNDEFINED "' + key.toString() + '" as value ' + ret + ' of type ' + typeof(ret));
313                         ret = def;
314                 }
315
316                 NETDATA.localStorage.current[key.toString()] = ret;
317                 return ret;
318         }
319
320         NETDATA.localStorageSet = function(key, value, callback) {
321                 if(typeof value === 'undefined' || value === 'undefined') {
322                         console.log('localStorage: ATTEMPT TO SET UNDEFINED "' + key.toString() + '" as value ' + value + ' of type ' + typeof(value));
323                 }
324
325                 if(typeof NETDATA.localStorage.default[key.toString()] === 'undefined') {
326                         NETDATA.localStorage.default[key.toString()] = value;
327                         NETDATA.localStorage.current[key.toString()] = value;
328                         NETDATA.localStorage.callback[key.toString()] = callback;
329                 }
330
331                 if(typeof Storage !== "undefined" && typeof localStorage === 'object') {
332                         // console.log('localStorage: saving "' + key.toString() + '" with value "' + JSON.stringify(value) + '"');
333                         try {
334                                 localStorage.setItem(key.toString(), JSON.stringify(value));
335                         }
336                         catch(e) {
337                                 console.log('localStorage: failed to save "' + key.toString() + '" with value: "' + value.toString() + '"');
338                         }
339                 }
340
341                 NETDATA.localStorage.current[key.toString()] = value;
342                 return value;
343         }
344
345         NETDATA.localStorageGetRecursive = function(obj, prefix, callback) {
346                 for(var i in obj) {
347                         if(typeof obj[i] === 'object') {
348                                 //console.log('object ' + prefix + '.' + i.toString());
349                                 NETDATA.localStorageGetRecursive(obj[i], prefix + '.' + i.toString(), callback);
350                                 continue;
351                         }
352
353                         obj[i] = NETDATA.localStorageGet(prefix + '.' + i.toString(), obj[i], callback);
354                 }
355         }
356
357         NETDATA.setOption = function(key, value) {
358                 if(key.toString() === 'setOptionCallback') {
359                         if(typeof NETDATA.options.current.setOptionCallback === 'function') {
360                                 NETDATA.options.current[key.toString()] = value;
361                                 NETDATA.options.current.setOptionCallback();
362                         }
363                 }
364                 else if(NETDATA.options.current[key.toString()] !== value) {
365                         var name = 'options.' + key.toString();
366
367                         if(typeof NETDATA.localStorage.default[name.toString()] === 'undefined')
368                                 console.log('localStorage: setOption() on unsaved option: "' + name.toString() + '", value: ' + value);
369
370                         //console.log(NETDATA.localStorage);
371                         //console.log('setOption: setting "' + key.toString() + '" to "' + value + '" of type ' + typeof(value) + ' original type ' + typeof(NETDATA.options.current[key.toString()]));
372                         //console.log(NETDATA.options);
373                         NETDATA.options.current[key.toString()] = NETDATA.localStorageSet(name.toString(), value, null);
374
375                         if(typeof NETDATA.options.current.setOptionCallback === 'function')
376                                 NETDATA.options.current.setOptionCallback();
377                 }
378
379                 return true;
380         }
381
382         NETDATA.getOption = function(key) {
383                 return NETDATA.options.current[key.toString()];
384         }
385
386         // read settings from local storage
387         NETDATA.localStorageGetRecursive(NETDATA.options.current, 'options', null);
388
389         // always start with this option enabled.
390         NETDATA.setOption('stop_updates_when_focus_is_lost', true);
391
392         NETDATA.resetOptions = function() {
393                 for(var i in NETDATA.localStorage.default) {
394                         var a = i.split('.');
395
396                         if(a[0] === 'options') {
397                                 if(a[1] === 'setOptionCallback') continue;
398                                 if(typeof NETDATA.localStorage.default[i] === 'undefined') continue;
399                                 if(NETDATA.options.current[i] === NETDATA.localStorage.default[i]) continue;
400
401                                 NETDATA.setOption(a[1], NETDATA.localStorage.default[i]);
402                         }
403                         else if(a[0] === 'chart_heights') {
404                                 if(typeof NETDATA.localStorage.callback[i] === 'function' && typeof NETDATA.localStorage.default[i] !== 'undefined') {
405                                         NETDATA.localStorage.callback[i](NETDATA.localStorage.default[i]);
406                                 }
407                         }
408                 }
409         }
410
411         // ----------------------------------------------------------------------------------------------------------------
412
413         if(NETDATA.options.debug.main_loop === true)
414                 console.log('welcome to NETDATA');
415
416         NETDATA.onresize = function() {
417                 NETDATA.options.last_resized = new Date().getTime();
418                 NETDATA.onscroll();
419         };
420
421         NETDATA.onscroll = function() {
422                 // console.log('onscroll');
423
424                 NETDATA.options.last_page_scroll = new Date().getTime();
425                 if(NETDATA.options.targets === null) return;
426
427                 // when the user scrolls he sees that we have
428                 // hidden all the not-visible charts
429                 // using this little function we try to switch
430                 // the charts back to visible quickly
431                 var targets = NETDATA.options.targets;
432                 var len = targets.length;
433                 while(len--) targets[len].isVisible();
434         };
435
436         window.onresize = NETDATA.onresize;
437         window.onscroll = NETDATA.onscroll;
438
439         // ----------------------------------------------------------------------------------------------------------------
440         // Error Handling
441
442         NETDATA.errorCodes = {
443                 100: { message: "Cannot load chart library", alert: true },
444                 101: { message: "Cannot load jQuery", alert: true },
445                 402: { message: "Chart library not found", alert: false },
446                 403: { message: "Chart library not enabled/is failed", alert: false },
447                 404: { message: "Chart not found", alert: false }
448         };
449         NETDATA.errorLast = {
450                 code: 0,
451                 message: "",
452                 datetime: 0
453         };
454
455         NETDATA.error = function(code, msg) {
456                 NETDATA.errorLast.code = code;
457                 NETDATA.errorLast.message = msg;
458                 NETDATA.errorLast.datetime = new Date().getTime();
459
460                 console.log("ERROR " + code + ": " + NETDATA.errorCodes[code].message + ": " + msg);
461
462                 if(NETDATA.errorCodes[code].alert)
463                         alert("ERROR " + code + ": " + NETDATA.errorCodes[code].message + ": " + msg);
464         }
465
466         NETDATA.errorReset = function() {
467                 NETDATA.errorLast.code = 0;
468                 NETDATA.errorLast.message = "You are doing fine!";
469                 NETDATA.errorLast.datetime = 0;
470         };
471
472         // ----------------------------------------------------------------------------------------------------------------
473         // Chart Registry
474
475         // When multiple charts need the same chart, we avoid downloading it
476         // multiple times (and having it in browser memory multiple time)
477         // by using this registry.
478
479         // Every time we download a chart definition, we save it here with .add()
480         // Then we try to get it back with .get(). If that fails, we download it.
481
482         NETDATA.chartRegistry = {
483                 charts: {},
484
485                 fixid: function(id) {
486                         return id.replace(/:/g, "_").replace(/\//g, "_");
487                 },
488
489                 add: function(host, id, data) {
490                         host = this.fixid(host);
491                         id   = this.fixid(id);
492
493                         if(typeof this.charts[host] === 'undefined')
494                                 this.charts[host] = {};
495
496                         //console.log('added ' + host + '/' + id);
497                         this.charts[host][id] = data;
498                 },
499
500                 get: function(host, id) {
501                         host = this.fixid(host);
502                         id   = this.fixid(id);
503
504                         if(typeof this.charts[host] === 'undefined')
505                                 return null;
506
507                         if(typeof this.charts[host][id] === 'undefined')
508                                 return null;
509
510                         //console.log('cached ' + host + '/' + id);
511                         return this.charts[host][id];
512                 },
513
514                 downloadAll: function(host, callback) {
515                         while(host.slice(-1) === '/')
516                                 host = host.substring(0, host.length - 1);
517
518                         var self = this;
519
520                         $.ajax({
521                                 url: host + '/api/v1/charts',
522                                 crossDomain: NETDATA.options.crossDomainAjax,
523                                 async: true,
524                                 cache: false
525                         })
526                         .done(function(data) {
527                                 var h = NETDATA.chartRegistry.fixid(host);
528                                 //console.log('downloaded all charts from ' + host + ' (' + h + ')');
529                                 self.charts[h] = data.charts;
530                                 if(typeof callback === 'function')
531                                         callback(data);
532                         })
533                         .fail(function() {
534                                 if(typeof callback === 'function')
535                                         callback(null);
536                         });
537                 }
538         };
539
540         // ----------------------------------------------------------------------------------------------------------------
541         // Global Pan and Zoom on charts
542
543         // Using this structure are synchronize all the charts, so that
544         // when you pan or zoom one, all others are automatically refreshed
545         // to the same timespan.
546
547         NETDATA.globalPanAndZoom = {
548                 seq: 0,                                 // timestamp ms
549                                                                 // every time a chart is panned or zoomed
550                                                                 // we set the timestamp here
551                                                                 // then we use it as a sequence number
552                                                                 // to find if other charts are syncronized
553                                                                 // to this timerange
554
555                 master: null,                   // the master chart (state), to which all others
556                                                                 // are synchronized
557
558                 force_before_ms: null,  // the timespan to sync all other charts 
559                 force_after_ms: null,
560
561                 // set a new master
562                 setMaster: function(state, after, before) {
563                         if(NETDATA.options.current.sync_pan_and_zoom === false)
564                                 return;
565
566                         if(this.master !== null && this.master !== state)
567                                 this.master.resetChart(true, true);
568
569                         var now = new Date().getTime();
570                         this.master = state;
571                         this.seq = now;
572                         this.force_after_ms = after;
573                         this.force_before_ms = before;
574                         NETDATA.options.auto_refresher_stop_until = now + NETDATA.options.current.global_pan_sync_time;
575                 },
576
577                 // clear the master
578                 clearMaster: function() {
579                         if(this.master !== null) {
580                                 var st = this.master;
581                                 this.master = null;
582                                 st.resetChart();
583                         }
584
585                         this.master = null;
586                         this.seq = 0;
587                         this.force_after_ms = null;
588                         this.force_before_ms = null;
589                         NETDATA.options.auto_refresher_stop_until = 0;
590                 },
591
592                 // is the given state the master of the global
593                 // pan and zoom sync?
594                 isMaster: function(state) {
595                         if(this.master === state) return true;
596                         return false;
597                 },
598
599                 // are we currently have a global pan and zoom sync?
600                 isActive: function() {
601                         if(this.master !== null && this.force_before_ms !== null && this.force_after_ms !== null && this.seq !== 0) return true;
602                         return false;
603                 },
604
605                 // check if a chart, other than the master
606                 // needs to be refreshed, due to the global pan and zoom
607                 shouldBeAutoRefreshed: function(state) {
608                         if(this.master === null || this.seq === 0)
609                                 return false;
610
611                         //if(state.needsRecreation())
612                         //      return true;
613
614                         if(state.tm.pan_and_zoom_seq === this.seq)
615                                 return false;
616
617                         return true;
618                 }
619         }
620
621         // ----------------------------------------------------------------------------------------------------------------
622         // dimensions selection
623
624         // FIXME
625         // move color assignment to dimensions, here
626
627         dimensionStatus = function(parent, label, name_div, value_div, color) {
628                 this.enabled = false;
629                 this.parent = parent;
630                 this.label = label;
631                 this.name_div = null;
632                 this.value_div = null;
633                 this.color = NETDATA.themes.current.foreground;
634
635                 if(parent.selected === parent.unselected)
636                         this.selected = true;
637                 else
638                         this.selected = false;
639
640                 this.setOptions(name_div, value_div, color);
641         }
642
643         dimensionStatus.prototype.invalidate = function() {
644                 this.name_div = null;
645                 this.value_div = null;
646                 this.enabled = false;
647         }
648
649         dimensionStatus.prototype.setOptions = function(name_div, value_div, color) {
650                 this.color = color;
651
652                 if(this.name_div != name_div) {
653                         this.name_div = name_div;
654                         this.name_div.title = this.label;
655                         this.name_div.style.color = this.color;
656                         if(this.selected === false)
657                                 this.name_div.className = 'netdata-legend-name not-selected';
658                         else
659                                 this.name_div.className = 'netdata-legend-name selected';
660                 }
661
662                 if(this.value_div != value_div) {
663                         this.value_div = value_div;
664                         this.value_div.title = this.label;
665                         this.value_div.style.color = this.color;
666                         if(this.selected === false)
667                                 this.value_div.className = 'netdata-legend-value not-selected';
668                         else
669                                 this.value_div.className = 'netdata-legend-value selected';
670                 }
671
672                 this.enabled = true;
673                 this.setHandler();
674         }
675
676         dimensionStatus.prototype.setHandler = function() {
677                 if(this.enabled === false) return;
678
679                 var ds = this;
680
681                 // this.name_div.onmousedown = this.value_div.onmousedown = function(e) {
682                 this.name_div.onclick = this.value_div.onclick = function(e) {
683                         e.preventDefault();
684                         if(ds.isSelected()) {
685                                 // this is selected
686                                 if(e.shiftKey === true || e.ctrlKey === true) {
687                                         // control or shift key is pressed -> unselect this (except is none will remain selected, in which case select all)
688                                         ds.unselect();
689
690                                         if(ds.parent.countSelected() === 0)
691                                                 ds.parent.selectAll();
692                                 }
693                                 else {
694                                         // no key is pressed -> select only this (except if it is the only selected already, in which case select all)
695                                         if(ds.parent.countSelected() === 1) {
696                                                 ds.parent.selectAll();
697                                         }
698                                         else {
699                                                 ds.parent.selectNone();
700                                                 ds.select();
701                                         }
702                                 }
703                         }
704                         else {
705                                 // this is not selected
706                                 if(e.shiftKey === true || e.ctrlKey === true) {
707                                         // control or shift key is pressed -> select this too
708                                         ds.select();
709                                 }
710                                 else {
711                                         // no key is pressed -> select only this
712                                         ds.parent.selectNone();
713                                         ds.select();
714                                 }
715                         }
716
717                         ds.parent.state.redrawChart();
718                 }
719         }
720
721         dimensionStatus.prototype.select = function() {
722                 if(this.enabled === false) return;
723
724                 this.name_div.className = 'netdata-legend-name selected';
725                 this.value_div.className = 'netdata-legend-value selected';
726                 this.selected = true;
727         }
728
729         dimensionStatus.prototype.unselect = function() {
730                 if(this.enabled === false) return;
731
732                 this.name_div.className = 'netdata-legend-name not-selected';
733                 this.value_div.className = 'netdata-legend-value hidden';
734                 this.selected = false;
735         }
736
737         dimensionStatus.prototype.isSelected = function() {
738                 return(this.enabled === true && this.selected === true);
739         }
740
741         // ----------------------------------------------------------------------------------------------------------------
742
743         dimensionsVisibility = function(state) {
744                 this.state = state;
745                 this.len = 0;
746                 this.dimensions = {};
747                 this.selected_count = 0;
748                 this.unselected_count = 0;
749         }
750
751         dimensionsVisibility.prototype.dimensionAdd = function(label, name_div, value_div, color) {
752                 if(typeof this.dimensions[label] === 'undefined') {
753                         this.len++;
754                         this.dimensions[label] = new dimensionStatus(this, label, name_div, value_div, color);
755                 }
756                 else
757                         this.dimensions[label].setOptions(name_div, value_div, color);
758
759                 return this.dimensions[label];
760         }
761
762         dimensionsVisibility.prototype.dimensionGet = function(label) {
763                 return this.dimensions[label];
764         }
765
766         dimensionsVisibility.prototype.invalidateAll = function() {
767                 for(var d in this.dimensions)
768                         this.dimensions[d].invalidate();
769         }
770
771         dimensionsVisibility.prototype.selectAll = function() {
772                 for(var d in this.dimensions)
773                         this.dimensions[d].select();
774         }
775
776         dimensionsVisibility.prototype.countSelected = function() {
777                 var i = 0;
778                 for(var d in this.dimensions)
779                         if(this.dimensions[d].isSelected()) i++;
780
781                 return i;
782         }
783
784         dimensionsVisibility.prototype.selectNone = function() {
785                 for(var d in this.dimensions)
786                         this.dimensions[d].unselect();
787         }
788
789         dimensionsVisibility.prototype.selected2BooleanArray = function(array) {
790                 var ret = new Array();
791                 this.selected_count = 0;
792                 this.unselected_count = 0;
793
794                 for(var i = 0, len = array.length; i < len ; i++) {
795                         var ds = this.dimensions[array[i]];
796                         if(typeof ds === 'undefined') {
797                                 // console.log(array[i] + ' is not found');
798                                 ret.push(false);
799                                 continue;
800                         }
801
802                         if(ds.isSelected()) {
803                                 ret.push(true);
804                                 this.selected_count++;
805                         }
806                         else {
807                                 ret.push(false);
808                                 this.unselected_count++;
809                         }
810                 }
811
812                 if(this.selected_count === 0 && this.unselected_count !== 0) {
813                         this.selectAll();
814                         return this.selected2BooleanArray(array);
815                 }
816
817                 return ret;
818         }
819
820
821         // ----------------------------------------------------------------------------------------------------------------
822         // global selection sync
823
824         NETDATA.globalSelectionSync = {
825                 state: null,
826                 dont_sync_before: 0,
827                 last_t: 0,
828                 slaves: [],
829
830                 stop: function() {
831                         if(this.state !== null)
832                                 this.state.globalSelectionSyncStop();
833                 },
834
835                 delay: function() {
836                         if(this.state !== null) {
837                                 this.state.globalSelectionSyncDelay();
838                         }
839                 }
840         };
841
842         // ----------------------------------------------------------------------------------------------------------------
843         // Our state object, where all per-chart values are stored
844
845         chartState = function(element) {
846                 var self = $(element);
847                 this.element = element;
848
849                 // IMPORTANT:
850                 // all private functions should use 'that', instead of 'this'
851                 var that = this;
852
853                 /* error() - private
854                  * show an error instead of the chart
855                  */
856                 var error = function(msg) {
857                         that.element.innerHTML = that.id + ': ' + msg;
858                         that.enabled = false;
859                         that.current = that.pan;
860                 }
861
862                 // GUID - a unique identifier for the chart
863                 this.uuid = NETDATA.guid();
864
865                 // string - the name of chart
866                 this.id = self.data('netdata');
867
868                 // string - the key for localStorage settings
869                 this.settings_id = self.data('id') || null;
870
871                 // the user given dimensions of the element
872                 this.width = self.data('width') || NETDATA.chartDefaults.width;
873                 this.height = self.data('height') || NETDATA.chartDefaults.height;
874
875                 if(this.settings_id !== null) {
876                         this.height = NETDATA.localStorageGet('chart_heights.' + this.settings_id, this.height, function(height) {
877                                 // this is the callback that will be called
878                                 // if and when the user resets all localStorage variables
879                                 // to their defaults
880
881                                 resizeChartToHeight(height);
882                         });
883                 }
884
885                 // string - the netdata server URL, without any path
886                 this.host = self.data('host') || NETDATA.chartDefaults.host;
887
888                 // make sure the host does not end with /
889                 // all netdata API requests use absolute paths
890                 while(this.host.slice(-1) === '/')
891                         this.host = this.host.substring(0, this.host.length - 1);
892
893                 // string - the grouping method requested by the user
894                 this.method = self.data('method') || NETDATA.chartDefaults.method;
895
896                 // the time-range requested by the user
897                 this.after = self.data('after') || NETDATA.chartDefaults.after;
898                 this.before = self.data('before') || NETDATA.chartDefaults.before;
899
900                 // the pixels per point requested by the user
901                 this.pixels_per_point = self.data('pixels-per-point') || 1;
902                 this.points = self.data('points') || null;
903
904                 // the dimensions requested by the user
905                 this.dimensions = self.data('dimensions') || null;
906
907                 // the chart library requested by the user
908                 this.library_name = self.data('chart-library') || NETDATA.chartDefaults.library;
909
910                 // object - the chart library used
911                 this.library = null;
912
913                 // color management
914                 this.colors = null;
915                 this.colors_assigned = {};
916                 this.colors_available = null;
917
918                 // the element already created by the user
919                 this.element_message = null;
920
921                 // the element with the chart
922                 this.element_chart = null;
923
924                 // the element with the legend of the chart (if created by us)
925                 this.element_legend = null;
926                 this.element_legend_childs = {
927                         hidden: null,
928                         title_date: null,
929                         title_time: null,
930                         title_units: null,
931                         nano: null,
932                         nano_options: null,
933                         series: null
934                 };
935
936                 this.chart_url = null;                                          // string - the url to download chart info
937                 this.chart = null;                                                      // object - the chart as downloaded from the server
938
939                 this.title = self.data('title') || null;        // the title of the chart
940                 this.units = self.data('units') || null;        // the units of the chart dimensions
941                 this.append_options = self.data('append-options') || null;      // the units of the chart dimensions
942
943                 this.validated = false;                                         // boolean - has the chart been validated?
944                 this.enabled = true;                                            // boolean - is the chart enabled for refresh?
945                 this.paused = false;                                            // boolean - is the chart paused for any reason?
946                 this.selected = false;                                          // boolean - is the chart shown a selection?
947                 this.debug = false;                                                     // boolean - console.log() debug info about this chart
948
949                 this.netdata_first = 0;                                         // milliseconds - the first timestamp in netdata
950                 this.netdata_last = 0;                                          // milliseconds - the last timestamp in netdata
951                 this.requested_after = null;                            // milliseconds - the timestamp of the request after param
952                 this.requested_before = null;                           // milliseconds - the timestamp of the request before param
953                 this.requested_padding = null;
954                 this.view_after = 0;
955                 this.view_before = 0;
956
957                 this.auto = {
958                         name: 'auto',
959                         autorefresh: true,
960                         force_update_at: 0, // the timestamp to force the update at
961                         force_before_ms: null,
962                         force_after_ms: null
963                 };
964                 this.pan = {
965                         name: 'pan',
966                         autorefresh: false,
967                         force_update_at: 0, // the timestamp to force the update at
968                         force_before_ms: null,
969                         force_after_ms: null
970                 };
971                 this.zoom = {
972                         name: 'zoom',
973                         autorefresh: false,
974                         force_update_at: 0, // the timestamp to force the update at
975                         force_before_ms: null,
976                         force_after_ms: null
977                 };
978
979                 // this is a pointer to one of the sub-classes below
980                 // auto, pan, zoom
981                 this.current = this.auto;
982
983                 // check the requested library is available
984                 // we don't initialize it here - it will be initialized when
985                 // this chart will be first used
986                 if(typeof NETDATA.chartLibraries[that.library_name] === 'undefined') {
987                         NETDATA.error(402, that.library_name);
988                         error('chart library "' + that.library_name + '" is not found');
989                         return;
990                 }
991                 else if(NETDATA.chartLibraries[that.library_name].enabled === false) {
992                         NETDATA.error(403, that.library_name);
993                         error('chart library "' + that.library_name + '" is not enabled');
994                         return;
995                 }
996                 else
997                         that.library = NETDATA.chartLibraries[that.library_name];
998
999                 // milliseconds - the time the last refresh took
1000                 this.refresh_dt_ms = 0;
1001
1002                 // if we need to report the rendering speed
1003                 // find the element that needs to be updated
1004                 var refresh_dt_element_name = self.data('dt-element-name') || null;     // string - the element to print refresh_dt_ms
1005
1006                 if(refresh_dt_element_name !== null)
1007                         this.refresh_dt_element = document.getElementById(refresh_dt_element_name) || null;
1008                 else
1009                         this.refresh_dt_element = null;
1010
1011                 this.dimensions_visibility = new dimensionsVisibility(this);
1012
1013                 this._updating = false;
1014
1015                 // ============================================================================================================
1016                 // PRIVATE FUNCTIONS
1017
1018                 var createDOM = function() {
1019                         if(that.enabled === false) return;
1020
1021                         if(that.element_message !== null) that.element_message.innerHTML = '';
1022                         if(that.element_legend !== null) that.element_legend.innerHTML = '';
1023                         if(that.element_chart !== null) that.element_chart.innerHTML = '';
1024
1025                         that.element.innerHTML = '';
1026
1027                         that.element_message = document.createElement('div');
1028                         that.element_message.className = ' netdata-message hidden';
1029                         that.element.appendChild(that.element_message);
1030
1031                         that.element_chart = document.createElement('div');
1032                         that.element_chart.id = that.library_name + '-' + that.uuid + '-chart';
1033                         that.element.appendChild(that.element_chart);
1034
1035                         if(that.hasLegend() === true) {
1036                                 that.element.className = "netdata-container-with-legend";
1037                                 that.element_chart.className = 'netdata-chart-with-legend-right netdata-' + that.library_name + '-chart-with-legend-right';
1038
1039                                 that.element_legend = document.createElement('div');
1040                                 that.element_legend.className = 'netdata-chart-legend netdata-' + that.library_name + '-legend';
1041                                 that.element.appendChild(that.element_legend);
1042                         }
1043                         else {
1044                                 that.element.className = "netdata-container";
1045                                 that.element_chart.className = ' netdata-chart netdata-' + that.library_name + '-chart';
1046
1047                                 that.element_legend = null;
1048                         }
1049                         that.element_legend_childs.series = null;
1050
1051                         if(typeof(that.width) === 'string')
1052                                 $(that.element).css('width', that.width);
1053                         else if(typeof(that.width) === 'number')
1054                                 $(that.element).css('width', that.width + 'px');
1055
1056                         if(typeof(that.library.aspect_ratio) === 'undefined') {
1057                                 if(typeof(that.height) === 'string')
1058                                         $(that.element).css('height', that.height);
1059                                 else if(typeof(that.height) === 'number')
1060                                         $(that.element).css('height', that.height + 'px');
1061                         }
1062                         else {
1063                                 var w = that.element.offsetWidth;
1064                                 if(w === null || w === 0) {
1065                                         // the div is hidden
1066                                         // this is resize the chart when next viewed
1067                                         that.tm.last_resized = 0;
1068                                 }
1069                                 else
1070                                         $(that.element).css('height', (that.element.offsetWidth * that.library.aspect_ratio / 100).toString() + 'px');
1071                         }
1072
1073                         if(NETDATA.chartDefaults.min_width !== null)
1074                                 $(that.element).css('min-width', NETDATA.chartDefaults.min_width);
1075
1076                         that.tm.last_dom_created = new Date().getTime();
1077
1078                         showLoading();
1079                 }
1080
1081                 /* init() private
1082                  * initialize state viariables
1083                  * destroy all (possibly) created state elements
1084                  * create the basic DOM for a chart
1085                  */
1086                 var init = function() {
1087                         if(that.enabled === false) return;
1088
1089                         that.paused = false;
1090                         that.selected = false;
1091
1092                         that.chart_created = false;                     // boolean - is the library.create() been called?
1093                         that.updates_counter = 0;                       // numeric - the number of refreshes made so far
1094                         that.updates_since_last_unhide = 0;     // numeric - the number of refreshes made since the last time the chart was unhidden
1095                         that.updates_since_last_creation = 0; // numeric - the number of refreshes made since the last time the chart was created
1096
1097                         that.tm = {
1098                                 last_initialized: 0,            // milliseconds - the timestamp it was last initialized
1099                                 last_dom_created: 0,            // milliseconds - the timestamp its DOM was last created
1100                                 last_mode_switch: 0,            // milliseconds - the timestamp it switched modes
1101
1102                                 last_info_downloaded: 0,        // milliseconds - the timestamp we downloaded the chart
1103                                 last_updated: 0,                        // the timestamp the chart last updated with data
1104                                 pan_and_zoom_seq: 0,            // the sequence number of the global synchronization
1105                                                                                         // between chart.
1106                                                                                         // Used with NETDATA.globalPanAndZoom.seq
1107                                 last_visible_check: 0,          // the time we last checked if it is visible
1108                                 last_resized: 0,                        // the time the chart was resized
1109                                 last_hidden: 0,                         // the time the chart was hidden
1110                                 last_unhidden: 0,                       // the time the chart was unhidden
1111                                 last_autorefreshed: 0           // the time the chart was last refreshed
1112                         },
1113
1114                         that.data = null;                               // the last data as downloaded from the netdata server
1115                         that.data_url = 'invalid://';   // string - the last url used to update the chart
1116                         that.data_points = 0;                   // number - the number of points returned from netdata
1117                         that.data_after = 0;                    // milliseconds - the first timestamp of the data
1118                         that.data_before = 0;                   // milliseconds - the last timestamp of the data
1119                         that.data_update_every = 0;             // milliseconds - the frequency to update the data
1120
1121                         that.tm.last_initialized = new Date().getTime();
1122                         createDOM();
1123
1124                         that.setMode('auto');
1125                 }
1126
1127                 var maxMessageFontSize = function() {
1128                         // normally we want a font size, as tall as the element
1129                         var h = that.element_message.clientHeight;
1130
1131                         // but give it some air, 20% let's say, or 5 pixels min
1132                         var lost = Math.max(h * 0.2, 5);
1133                         h -= lost;
1134
1135                         // center the text, verically
1136                         var paddingTop = (lost - 5) / 2;
1137
1138                         // but check the width too
1139                         // it should fit 10 characters in it
1140                         var w = that.element_message.clientWidth / 10;
1141                         if(h > w) {
1142                                 paddingTop += (h - w) / 2;
1143                                 h = w;
1144                         }
1145
1146                         // and don't make it too huge
1147                         // 5% of the screen size is good
1148                         if(h > screen.height / 20) {
1149                                 paddingTop += (h - (screen.height / 20)) / 2;
1150                                 h = screen.height / 20;
1151                         }
1152
1153                         // set it
1154                         that.element_message.style.fontSize = h.toString() + 'px';
1155                         that.element_message.style.paddingTop = paddingTop.toString() + 'px';
1156                 }
1157
1158                 var showMessage = function(msg) {
1159                         that.element_message.className = 'netdata-message';
1160                         that.element_message.innerHTML = msg;
1161                         this.element_message.style.fontSize = 'x-small';
1162                         that.element_message.style.paddingTop = '0px';
1163                         that.___messageHidden___ = undefined;
1164                 }
1165
1166                 var showMessageIcon = function(icon) {
1167                         that.element_message.innerHTML = icon;
1168                         that.element_message.className = 'netdata-message icon';
1169                         maxMessageFontSize();
1170                         that.___messageHidden___ = undefined;
1171                 }
1172
1173                 var hideMessage = function() {
1174                         if(typeof that.___messageHidden___ === 'undefined') {
1175                                 that.___messageHidden___ = true;
1176                                 that.element_message.className = 'netdata-message hidden';
1177                         }
1178                 }
1179
1180                 var showRendering = function() {
1181                         var icon;
1182                         if(that.chart !== null) {
1183                                 if(that.chart.chart_type === 'line')
1184                                         icon = '<i class="fa fa-line-chart"></i>';
1185                                 else
1186                                         icon = '<i class="fa fa-area-chart"></i>';
1187                         }
1188                         else
1189                                 icon = '<i class="fa fa-area-chart"></i>';
1190
1191                         showMessageIcon(icon + ' netdata');
1192                 }
1193
1194                 var showLoading = function() {
1195                         if(that.chart_created === false) {
1196                                 showMessageIcon('<i class="fa fa-refresh"></i> netdata');
1197                                 return true;
1198                         }
1199                         return false;
1200                 }
1201
1202                 var isHidden = function() {
1203                         if(typeof that.___chartIsHidden___ !== 'undefined')
1204                                 return true;
1205
1206                         return false;
1207                 }
1208
1209                 // hide the chart, when it is not visible - called from isVisible()
1210                 var hideChart = function() {
1211                         // hide it, if it is not already hidden
1212                         if(isHidden() === true) return;
1213
1214                         if(that.chart_created === true) {
1215                                 // we should destroy it
1216                                 if(NETDATA.options.current.destroy_on_hide === true) {
1217                                         init();
1218                                 }
1219                                 else {
1220                                         showRendering();
1221                                         that.element_chart.style.display = 'none';
1222                                         if(that.element_legend !== null) that.element_legend.style.display = 'none';
1223                                         that.tm.last_hidden = new Date().getTime();
1224                                 }
1225                         }
1226                         
1227                         that.___chartIsHidden___ = true;
1228                 }
1229
1230                 // unhide the chart, when it is visible - called from isVisible()
1231                 var unhideChart = function() {
1232                         if(isHidden() === false) return;
1233
1234                         that.___chartIsHidden___ = undefined;
1235                         that.updates_since_last_unhide = 0;
1236
1237                         if(that.chart_created === false) {
1238                                 // we need to re-initialize it, to show our background
1239                                 // logo in bootstrap tabs, until the chart loads
1240                                 init();
1241                         }
1242                         else {
1243                                 that.tm.last_unhidden = new Date().getTime();
1244                                 that.element_chart.style.display = '';
1245                                 if(that.element_legend !== null) that.element_legend.style.display = '';
1246                                 resizeChart();
1247                                 hideMessage();
1248                         }
1249                 }
1250
1251                 var canBeRendered = function() {
1252                         if(isHidden() === true || that.isVisible(true) === false)
1253                                 return false;
1254
1255                         return true;
1256                 }
1257
1258                 // https://github.com/petkaantonov/bluebird/wiki/Optimization-killers
1259                 var callChartLibraryUpdateSafely = function(data) {
1260                         var status;
1261
1262                         if(canBeRendered() === false)
1263                                 return false;
1264
1265                         if(NETDATA.options.debug.chart_errors === true)
1266                                 status = that.library.update(that, data);
1267                         else {
1268                                 try {
1269                                         status = that.library.update(that, data);
1270                                 }
1271                                 catch(err) {
1272                                         status = false;
1273                                 }
1274                         }
1275
1276                         if(status === false) {
1277                                 error('chart failed to be updated as ' + that.library_name);
1278                                 return false;
1279                         }
1280
1281                         return true;
1282                 }
1283
1284                 // https://github.com/petkaantonov/bluebird/wiki/Optimization-killers
1285                 var callChartLibraryCreateSafely = function(data) {
1286                         var status;
1287
1288                         if(canBeRendered() === false)
1289                                 return false;
1290
1291                         if(NETDATA.options.debug.chart_errors === true)
1292                                 status = that.library.create(that, data);
1293                         else {
1294                                 try {
1295                                         status = that.library.create(that, data);
1296                                 }
1297                                 catch(err) {
1298                                         status = false;
1299                                 }
1300                         }
1301
1302                         if(status === false) {
1303                                 error('chart failed to be created as ' + that.library_name);
1304                                 return false;
1305                         }
1306
1307                         that.chart_created = true;
1308                         that.updates_since_last_creation = 0;
1309                         return true;
1310                 }
1311
1312                 // ----------------------------------------------------------------------------------------------------------------
1313                 // Chart Resize
1314
1315                 // resizeChart() - private
1316                 // to be called just before the chart library to make sure that
1317                 // a properly sized dom is available
1318                 var resizeChart = function() {
1319                         if(that.isVisible() === true && that.tm.last_resized < NETDATA.options.last_resized) {
1320                                 if(that.chart_created === false) return;
1321
1322                                 if(that.needsRecreation()) {
1323                                         init();
1324                                 }
1325                                 else if(typeof that.library.resize === 'function') {
1326                                         that.library.resize(that);
1327
1328                                         if(that.element_legend_childs.nano !== null && that.element_legend_childs.nano_options !== null)
1329                                                 $(that.element_legend_childs.nano).nanoScroller();
1330
1331                                         maxMessageFontSize();
1332                                 }
1333
1334                                 that.tm.last_resized = new Date().getTime();
1335                         }
1336                 }
1337
1338                 // this is the actual chart resize algorithm
1339                 // it will:
1340                 // - resize the entire container
1341                 // - update the internal states
1342                 // - resize the chart as the div changes height
1343                 // - update the scrollbar of the legend
1344                 var resizeChartToHeight = function(h) {
1345                         // console.log(h);
1346                         that.element.style.height = h;
1347
1348                         if(that.settings_id !== null)
1349                                 NETDATA.localStorageSet('chart_heights.' + that.settings_id, h);
1350
1351                         var now = new Date().getTime();
1352                         NETDATA.options.last_page_scroll = now;
1353                         NETDATA.options.auto_refresher_stop_until = now + NETDATA.options.current.stop_updates_while_resizing;
1354
1355                         // force a resize
1356                         that.tm.last_resized = 0;
1357                         resizeChart();
1358                 };
1359
1360                 this.resizeHandler = function(e) {
1361                         e.preventDefault();
1362
1363                         if(typeof this.event_resize === 'undefined'
1364                                 || this.event_resize.chart_original_w === 'undefined'
1365                                 || this.event_resize.chart_original_h === 'undefined')
1366                                 this.event_resize = {
1367                                         chart_original_w: this.element.clientWidth,
1368                                         chart_original_h: this.element.clientHeight,
1369                                         last: 0
1370                                 };
1371
1372                         if(e.type === 'touchstart') {
1373                                 this.event_resize.mouse_start_x = e.touches.item(0).pageX;
1374                                 this.event_resize.mouse_start_y = e.touches.item(0).pageY;
1375                         }
1376                         else {
1377                                 this.event_resize.mouse_start_x = e.clientX;
1378                                 this.event_resize.mouse_start_y = e.clientY;
1379                         }
1380
1381                         this.event_resize.chart_start_w = this.element.clientWidth;
1382                         this.event_resize.chart_start_h = this.element.clientHeight;
1383                         this.event_resize.chart_last_w = this.element.clientWidth;
1384                         this.event_resize.chart_last_h = this.element.clientHeight;
1385
1386                         var now = new Date().getTime();
1387                         if(now - this.event_resize.last <= NETDATA.options.current.double_click_speed) {
1388                                 // double click / double tap event
1389
1390                                 // the optimal height of the chart
1391                                 // showing the entire legend
1392                                 var optimal = this.event_resize.chart_last_h
1393                                                 + this.element_legend_childs.content.scrollHeight
1394                                                 - this.element_legend_childs.content.clientHeight;
1395
1396                                 // if we are not optimal, be optimal
1397                                 if(this.event_resize.chart_last_h != optimal)
1398                                         resizeChartToHeight(optimal.toString() + 'px');
1399
1400                                 // else if we do not have the original height
1401                                 // reset to the original height
1402                                 else if(this.event_resize.chart_last_h != this.event_resize.chart_original_h)
1403                                         resizeChartToHeight(this.event_resize.chart_original_h.toString() + 'px');
1404                         }
1405                         else {
1406                                 this.event_resize.last = now;
1407
1408                                 // process movement event
1409                                 document.onmousemove =
1410                                 document.ontouchmove =
1411                                 this.element_legend_childs.resize_handler.onmousemove =
1412                                 this.element_legend_childs.resize_handler.ontouchmove =
1413                                         function(e) {
1414                                                 var y = null;
1415
1416                                                 switch(e.type) {
1417                                                         case 'mousemove': y = e.clientY; break;
1418                                                         case 'touchmove': y = e.touches.item(e.touches - 1).pageY; break;
1419                                                 }
1420
1421                                                 if(y !== null) {
1422                                                         var     newH = that.event_resize.chart_start_h + y - that.event_resize.mouse_start_y;
1423
1424                                                         if(newH >= 70 && newH !== that.event_resize.chart_last_h) {
1425                                                                 resizeChartToHeight(newH.toString() + 'px');
1426                                                                 that.event_resize.chart_last_h = newH;
1427                                                         }
1428                                                 }
1429                                         };
1430
1431                                 // process end event
1432                                 document.onmouseup = 
1433                                 document.ontouchend = 
1434                                 this.element_legend_childs.resize_handler.onmouseup =
1435                                 this.element_legend_childs.resize_handler.ontouchend =
1436                                         function(e) {
1437                                                 // remove all the hooks
1438                                                 document.onmouseup =
1439                                                 document.onmousemove =
1440                                                 document.ontouchmove =
1441                                                 document.ontouchend =
1442                                                 that.element_legend_childs.resize_handler.onmousemove =
1443                                                 that.element_legend_childs.resize_handler.ontouchmove =
1444                                                 that.element_legend_childs.resize_handler.onmouseout =
1445                                                 that.element_legend_childs.resize_handler.onmouseup =
1446                                                 that.element_legend_childs.resize_handler.ontouchend =
1447                                                         null;
1448
1449                                                 // allow auto-refreshes
1450                                                 NETDATA.options.auto_refresher_stop_until = 0;
1451                                         };
1452                         }
1453                 }
1454
1455
1456                 var noDataToShow = function() {
1457                         showMessageIcon('<i class="fa fa-warning"></i> empty');
1458                         that.legendUpdateDOM();
1459                         that.tm.last_autorefreshed = new Date().getTime();
1460                         // that.data_update_every = 30 * 1000;
1461                         //that.element_chart.style.display = 'none';
1462                         //if(that.element_legend !== null) that.element_legend.style.display = 'none';
1463                         //that.___chartIsHidden___ = true;
1464                 }
1465
1466                 // ============================================================================================================
1467                 // PUBLIC FUNCTIONS
1468
1469                 this.error = function(msg) {
1470                         error(msg);
1471                 }
1472
1473                 this.setMode = function(m) {
1474                         if(this.current !== null && this.current.name === m) return;
1475
1476                         if(m === 'auto')
1477                                 this.current = this.auto;
1478                         else if(m === 'pan')
1479                                 this.current = this.pan;
1480                         else if(m === 'zoom')
1481                                 this.current = this.zoom;
1482                         else
1483                                 this.current = this.auto;
1484
1485                         this.current.force_update_at = 0;
1486                         this.current.force_before_ms = null;
1487                         this.current.force_after_ms = null;
1488
1489                         this.tm.last_mode_switch = new Date().getTime();
1490                 }
1491
1492                 // ----------------------------------------------------------------------------------------------------------------
1493                 // global selection sync
1494
1495                 // prevent to global selection sync for some time
1496                 this.globalSelectionSyncDelay = function(ms) {
1497                         if(NETDATA.options.current.sync_selection === false)
1498                                 return;
1499
1500                         if(typeof ms === 'number')
1501                                 NETDATA.globalSelectionSync.dont_sync_before = new Date().getTime() + ms;
1502                         else
1503                                 NETDATA.globalSelectionSync.dont_sync_before = new Date().getTime() + NETDATA.options.current.sync_selection_delay;
1504                 }
1505
1506                 // can we globally apply selection sync?
1507                 this.globalSelectionSyncAbility = function() {
1508                         if(NETDATA.options.current.sync_selection === false)
1509                                 return false;
1510
1511                         if(NETDATA.globalSelectionSync.dont_sync_before > new Date().getTime())
1512                                 return false;
1513
1514                         return true;
1515                 }
1516
1517                 this.globalSelectionSyncIsMaster = function() {
1518                         if(NETDATA.globalSelectionSync.state === this)
1519                                 return true;
1520                         else
1521                                 return false;
1522                 }
1523
1524                 // this chart is the master of the global selection sync
1525                 this.globalSelectionSyncBeMaster = function() {
1526                         // am I the master?
1527                         if(this.globalSelectionSyncIsMaster()) {
1528                                 if(this.debug === true)
1529                                         this.log('sync: I am the master already.');
1530
1531                                 return;
1532                         }
1533
1534                         if(NETDATA.globalSelectionSync.state) {
1535                                 if(this.debug === true)
1536                                         this.log('sync: I am not the sync master. Resetting global sync.');
1537
1538                                 this.globalSelectionSyncStop();
1539                         }
1540
1541                         // become the master
1542                         if(this.debug === true)
1543                                 this.log('sync: becoming sync master.');
1544
1545                         this.selected = true;
1546                         NETDATA.globalSelectionSync.state = this;
1547
1548                         // find the all slaves
1549                         var targets = NETDATA.options.targets;
1550                         var len = targets.length;
1551                         while(len--) {
1552                                 st = targets[len];
1553
1554                                 if(st === this) {
1555                                         if(this.debug === true)
1556                                                 st.log('sync: not adding me to sync');
1557                                 }
1558                                 else if(st.globalSelectionSyncIsEligible()) {
1559                                         if(this.debug === true)
1560                                                 st.log('sync: adding to sync as slave');
1561
1562                                         st.globalSelectionSyncBeSlave();
1563                                 }
1564                         }
1565
1566                         // this.globalSelectionSyncDelay(100);
1567                 }
1568
1569                 // can the chart participate to the global selection sync as a slave?
1570                 this.globalSelectionSyncIsEligible = function() {
1571                         if(this.enabled === true
1572                                 && this.library !== null
1573                                 && typeof this.library.setSelection === 'function'
1574                                 && this.isVisible() === true
1575                                 && this.chart_created === true)
1576                                 return true;
1577
1578                         return false;
1579                 }
1580
1581                 // this chart becomes a slave of the global selection sync
1582                 this.globalSelectionSyncBeSlave = function() {
1583                         if(NETDATA.globalSelectionSync.state !== this)
1584                                 NETDATA.globalSelectionSync.slaves.push(this);
1585                 }
1586
1587                 // sync all the visible charts to the given time
1588                 // this is to be called from the chart libraries
1589                 this.globalSelectionSync = function(t) {
1590                         if(this.globalSelectionSyncAbility() === false) {
1591                                 if(this.debug === true)
1592                                         this.log('sync: cannot sync (yet?).');
1593
1594                                 return;
1595                         }
1596
1597                         if(this.globalSelectionSyncIsMaster() === false) {
1598                                 if(this.debug === true)
1599                                         this.log('sync: trying to be sync master.');
1600
1601                                 this.globalSelectionSyncBeMaster();
1602
1603                                 if(this.globalSelectionSyncAbility() === false) {
1604                                         if(this.debug === true)
1605                                                 this.log('sync: cannot sync (yet?).');
1606
1607                                         return;
1608                                 }
1609                         }
1610
1611                         NETDATA.globalSelectionSync.last_t = t;
1612                         $.each(NETDATA.globalSelectionSync.slaves, function(i, st) {
1613                                 st.setSelection(t);
1614                         });
1615                 }
1616
1617                 // stop syncing all charts to the given time
1618                 this.globalSelectionSyncStop = function() {
1619                         if(NETDATA.globalSelectionSync.slaves.length) {
1620                                 if(this.debug === true)
1621                                         this.log('sync: cleaning up...');
1622
1623                                 $.each(NETDATA.globalSelectionSync.slaves, function(i, st) {
1624                                         if(st === that) {
1625                                                 if(that.debug === true)
1626                                                         st.log('sync: not adding me to sync stop');
1627                                         }
1628                                         else {
1629                                                 if(that.debug === true)
1630                                                         st.log('sync: removed slave from sync');
1631
1632                                                 st.clearSelection();
1633                                         }
1634                                 });
1635
1636                                 NETDATA.globalSelectionSync.last_t = 0;
1637                                 NETDATA.globalSelectionSync.slaves = [];
1638                                 NETDATA.globalSelectionSync.state = null;
1639                         }
1640
1641                         this.clearSelection();
1642                 }
1643
1644                 this.setSelection = function(t) {
1645                         if(typeof this.library.setSelection === 'function') {
1646                                 if(this.library.setSelection(this, t) === true)
1647                                         this.selected = true;
1648                                 else
1649                                         this.selected = false;
1650                         }
1651                         else this.selected = true;
1652
1653                         if(this.selected === true && this.debug === true)
1654                                 this.log('selection set to ' + t.toString());
1655
1656                         return this.selected;
1657                 }
1658
1659                 this.clearSelection = function() {
1660                         if(this.selected === true) {
1661                                 if(typeof this.library.clearSelection === 'function') {
1662                                         if(this.library.clearSelection(this) === true)
1663                                                 this.selected = false;
1664                                         else
1665                                                 this.selected = true;
1666                                 }
1667                                 else this.selected = false;
1668
1669                                 if(this.selected === false && this.debug === true)
1670                                         this.log('selection cleared');
1671
1672                                 this.legendReset();
1673                         }
1674
1675                         return this.selected;
1676                 }
1677
1678                 // find if a timestamp (ms) is shown in the current chart
1679                 this.timeIsVisible = function(t) {
1680                         if(t >= this.data_after && t <= this.data_before)
1681                                 return true;
1682                         return false;
1683                 },
1684
1685                 this.calculateRowForTime = function(t) {
1686                         if(this.timeIsVisible(t) === false) return -1;
1687                         return Math.floor((t - this.data_after) / this.data_update_every);
1688                 }
1689
1690                 // ----------------------------------------------------------------------------------------------------------------
1691
1692                 // console logging
1693                 this.log = function(msg) {
1694                         console.log(this.id + ' (' + this.library_name + ' ' + this.uuid + '): ' + msg);
1695                 }
1696
1697                 this.pauseChart = function() {
1698                         if(this.paused === false) {
1699                                 if(this.debug === true)
1700                                         this.log('pauseChart()');
1701
1702                                 this.paused = true;
1703                         }
1704                 }
1705
1706                 this.unpauseChart = function() {
1707                         if(this.paused === true) {
1708                                 if(this.debug === true)
1709                                         this.log('unpauseChart()');
1710
1711                                 this.paused = false;
1712                         }
1713                 }
1714
1715                 this.resetChart = function(dont_clear_master, dont_update) {
1716                         if(this.debug === true)
1717                                 this.log('resetChart(' + dont_clear_master + ', ' + dont_update + ') called');
1718
1719                         if(typeof dont_clear_master === 'undefined')
1720                                 dont_clear_master = false;
1721
1722                         if(typeof dont_update === 'undefined')
1723                                 dont_update = false;
1724
1725                         if(dont_clear_master !== true && NETDATA.globalPanAndZoom.isMaster(this) === true) {
1726                                 if(this.debug === true)
1727                                         this.log('resetChart() diverting to clearMaster().');
1728                                 // this will call us back with master === true
1729                                 NETDATA.globalPanAndZoom.clearMaster();
1730                                 return;
1731                         }
1732
1733                         this.clearSelection();
1734
1735                         this.tm.pan_and_zoom_seq = 0;
1736
1737                         this.setMode('auto');
1738                         this.current.force_update_at = 0;
1739                         this.current.force_before_ms = null;
1740                         this.current.force_after_ms = null;
1741                         this.tm.last_autorefreshed = 0;
1742                         this.paused = false;
1743                         this.selected = false;
1744                         this.enabled = true;
1745                         // this.debug = false;
1746
1747                         // do not update the chart here
1748                         // or the chart will flip-flop when it is the master
1749                         // of a selection sync and another chart becomes
1750                         // the new master
1751
1752                         if(dont_update !== true && this.isVisible() === true) {
1753                                 this.updateChart();
1754                         }
1755                 }
1756
1757                 this.updateChartPanOrZoom = function(after, before) {
1758                         var logme = 'updateChartPanOrZoom(' + after + ', ' + before + '): ';
1759                         var ret = true;
1760
1761                         if(this.debug === true)
1762                                 this.log(logme);
1763
1764                         if(before < after) {
1765                                 this.log(logme + 'flipped parameters, rejecting it.');
1766                                 return false;
1767                         }
1768
1769                         if(typeof this.fixed_min_duration === 'undefined')
1770                                 this.fixed_min_duration = Math.round((this.chartWidth() / 30) * this.chart.update_every * 1000);
1771                         
1772                         var min_duration = this.fixed_min_duration;
1773                         var current_duration = Math.round(this.view_before - this.view_after);
1774
1775                         // round the numbers
1776                         after = Math.round(after);
1777                         before = Math.round(before);
1778
1779                         // align them to update_every
1780                         // stretching them further away
1781                         after -= after % this.data_update_every;
1782                         before += this.data_update_every - (before % this.data_update_every);
1783
1784                         // the final wanted duration
1785                         var wanted_duration = before - after;
1786                         
1787                         // to allow panning, accept just a point below our minimum
1788                         if((current_duration - this.data_update_every) < min_duration)
1789                                 min_duration = current_duration - this.data_update_every;
1790
1791                         // we do it, but we adjust to minimum size and return false
1792                         // when the wanted size is below the current and the minimum
1793                         // and we zoom
1794                         if(wanted_duration < current_duration && wanted_duration < min_duration) {
1795                                 if(this.debug === true)
1796                                         this.log(logme + 'too small: min_duration: ' + (min_duration / 1000).toString() + ', wanted: ' + (wanted_duration / 1000).toString());
1797
1798                                 min_duration = this.fixed_min_duration;
1799
1800                                 var dt = (min_duration - wanted_duration) / 2;
1801                                 before += dt;
1802                                 after -= dt;
1803                                 wanted_duration = before - after;
1804                                 ret = false;
1805                         }
1806
1807                         var tolerance = this.data_update_every * 2;
1808                         var movement = Math.abs(before - this.view_before);
1809
1810                         if(Math.abs(current_duration - wanted_duration) <= tolerance && movement <= tolerance && ret === true) {
1811                                 if(this.debug === true)
1812                                         this.log(logme + 'REJECTING UPDATE: current/min duration: ' + (current_duration / 1000).toString() + '/' + (this.fixed_min_duration / 1000).toString() + ', wanted duration: ' + (wanted_duration / 1000).toString() + ', duration diff: ' + (Math.round(Math.abs(current_duration - wanted_duration) / 1000)).toString() + ', movement: ' + (movement / 1000).toString() + ', tolerance: ' + (tolerance / 1000).toString() + ', returning: ' + false);
1813                                 return false;
1814                         }
1815
1816                         if(this.current.name === 'auto') {
1817                                 this.log(logme + 'caller called me with mode: ' + this.current.name);
1818                                 this.setMode('pan');
1819                         }
1820
1821                         if(this.debug === true)
1822                                 this.log(logme + 'ACCEPTING UPDATE: current/min duration: ' + (current_duration / 1000).toString() + '/' + (this.fixed_min_duration / 1000).toString() + ', wanted duration: ' + (wanted_duration / 1000).toString() + ', duration diff: ' + (Math.round(Math.abs(current_duration - wanted_duration) / 1000)).toString() + ', movement: ' + (movement / 1000).toString() + ', tolerance: ' + (tolerance / 1000).toString() + ', returning: ' + ret);
1823
1824                         this.current.force_update_at = new Date().getTime() + NETDATA.options.current.pan_and_zoom_delay;
1825                         this.current.force_after_ms = after;
1826                         this.current.force_before_ms = before;
1827                         NETDATA.globalPanAndZoom.setMaster(this, after, before);
1828                         return ret;
1829                 }
1830
1831                 this.legendFormatValue = function(value) {
1832                         if(value === null || value === 'undefined') return '-';
1833                         if(typeof value !== 'number') return value;
1834
1835                         var abs = Math.abs(value);
1836                         if(abs >= 1000) return (Math.round(value)).toLocaleString();
1837                         if(abs >= 100 ) return (Math.round(value * 10) / 10).toLocaleString();
1838                         if(abs >= 1   ) return (Math.round(value * 100) / 100).toLocaleString();
1839                         if(abs >= 0.1 ) return (Math.round(value * 1000) / 1000).toLocaleString();
1840                         return (Math.round(value * 10000) / 10000).toLocaleString();
1841                 }
1842
1843                 this.legendSetLabelValue = function(label, value) {
1844                         var series = this.element_legend_childs.series[label];
1845                         if(typeof series === 'undefined') return;
1846                         if(series.value === null && series.user === null) return;
1847
1848                         // if the value has not changed, skip DOM update
1849                         //if(series.last === value) return;
1850
1851                         var s, r;
1852                         if(typeof value === 'number') {
1853                                 var v = Math.abs(value);
1854                                 s = r = this.legendFormatValue(value);
1855
1856                                 if(typeof series.last === 'number') {
1857                                         if(v > series.last) s += '<i class="fa fa-angle-up" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1858                                         else if(v < series.last) s += '<i class="fa fa-angle-down" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1859                                         else s += '<i class="fa fa-angle-left" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1860                                 }
1861                                 else s += '<i class="fa fa-angle-right" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1862                                 series.last = v;
1863                         }
1864                         else {
1865                                 s = r = value;
1866                                 series.last = value;
1867                         }
1868
1869                         if(series.value !== null) series.value.innerHTML = s;
1870                         if(series.user !== null) series.user.innerHTML = r;
1871                 }
1872
1873                 this.legendSetDate = function(ms) {
1874                         if(typeof ms !== 'number') {
1875                                 this.legendShowUndefined();
1876                                 return;
1877                         }
1878
1879                         var d = new Date(ms);
1880
1881                         if(this.element_legend_childs.title_date)
1882                                 this.element_legend_childs.title_date.innerHTML = d.toLocaleDateString();
1883
1884                         if(this.element_legend_childs.title_time)
1885                                 this.element_legend_childs.title_time.innerHTML = d.toLocaleTimeString();
1886
1887                         if(this.element_legend_childs.title_units)
1888                                 this.element_legend_childs.title_units.innerHTML = this.units;
1889                 }
1890
1891                 this.legendShowUndefined = function() {
1892                         if(this.element_legend_childs.title_date)
1893                                 this.element_legend_childs.title_date.innerHTML = '&nbsp;';
1894
1895                         if(this.element_legend_childs.title_time)
1896                                 this.element_legend_childs.title_time.innerHTML = this.chart.name;
1897
1898                         if(this.element_legend_childs.title_units)
1899                                 this.element_legend_childs.title_units.innerHTML = '&nbsp;';
1900
1901                         if(this.data && this.element_legend_childs.series !== null) {
1902                                 var labels = this.data.dimension_names;
1903                                 var i = labels.length;
1904                                 while(i--) {
1905                                         var label = labels[i];
1906
1907                                         if(typeof label === 'undefined') continue;
1908                                         if(typeof this.element_legend_childs.series[label] === 'undefined') continue;
1909                                         this.legendSetLabelValue(label, null);
1910                                 }
1911                         }
1912                 }
1913
1914                 this.legendShowLatestValues = function() {
1915                         if(this.chart === null) return;
1916                         if(this.selected) return;
1917
1918                         if(this.data === null || this.element_legend_childs.series === null) {
1919                                 this.legendShowUndefined();
1920                                 return;
1921                         }
1922
1923                         var show_undefined = true;
1924                         if(Math.abs(this.netdata_last - this.view_before) <= this.data_update_every)
1925                                 show_undefined = false;
1926
1927                         if(show_undefined) {
1928                                 this.legendShowUndefined();
1929                                 return;
1930                         }
1931
1932                         this.legendSetDate(this.view_before);
1933
1934                         var labels = this.data.dimension_names;
1935                         var i = labels.length;
1936                         while(i--) {
1937                                 var label = labels[i];
1938
1939                                 if(typeof label === 'undefined') continue;
1940                                 if(typeof this.element_legend_childs.series[label] === 'undefined') continue;
1941
1942                                 if(show_undefined)
1943                                         this.legendSetLabelValue(label, null);
1944                                 else
1945                                         this.legendSetLabelValue(label, this.data.view_latest_values[i]);
1946                         }
1947                 }
1948
1949                 this.legendReset = function() {
1950                         this.legendShowLatestValues();
1951                 }
1952
1953                 // this should be called just ONCE per dimension per chart
1954                 this._chartDimensionColor = function(label) {
1955                         if(this.colors === null) this.chartColors();
1956
1957                         if(typeof this.colors_assigned[label] === 'undefined') {
1958                                 if(this.colors_available.length === 0) {
1959                                         for(var i = 0, len = NETDATA.themes.current.colors.length; i < len ; i++)
1960                                                 this.colors_available.push(NETDATA.themes.current.colors[i]);
1961                                 }
1962
1963                                 this.colors_assigned[label] = this.colors_available.shift();
1964
1965                                 if(this.debug === true)
1966                                         this.log('label "' + label + '" got color "' + this.colors_assigned[label]);
1967                         }
1968                         else {
1969                                 if(this.debug === true)
1970                                         this.log('label "' + label + '" already has color "' + this.colors_assigned[label] + '"');
1971                         }
1972
1973                         this.colors.push(this.colors_assigned[label]);
1974                         return this.colors_assigned[label];
1975                 }
1976
1977                 this.chartColors = function() {
1978                         if(this.colors !== null) return this.colors;
1979
1980                         this.colors = new Array();
1981                         this.colors_available = new Array();
1982
1983                         var c = $(this.element).data('colors');
1984                         // this.log('read colors: ' + c);
1985                         if(typeof c !== 'undefined' && c !== null) {
1986                                 if(typeof c !== 'string') {
1987                                         this.log('invalid color given: ' + c + ' (give a space separated list of colors)');
1988                                 }
1989                                 else {
1990                                         c = c.split(' ');
1991                                         var added = 0;
1992
1993                                         while(added < 20) {
1994                                                 for(var i = 0, len = c.length; i < len ; i++) {
1995                                                         added++;
1996                                                         this.colors_available.push(c[i]);
1997                                                         // this.log('adding color: ' + c[i]);
1998                                                 }
1999                                         }
2000                                 }
2001                         }
2002
2003                         // push all the standard colors too
2004                         for(var i = 0, len = NETDATA.themes.current.colors.length; i < len ; i++)
2005                                 this.colors_available.push(NETDATA.themes.current.colors[i]);
2006
2007                         return this.colors;
2008                 }
2009
2010                 this.legendUpdateDOM = function() {
2011                         var needed = false;
2012
2013                         // check that the legend DOM is up to date for the downloaded dimensions
2014                         if(typeof this.element_legend_childs.series !== 'object' || this.element_legend_childs.series === null) {
2015                                 // this.log('the legend does not have any series - requesting legend update');
2016                                 needed = true;
2017                         }
2018                         else if(this.data === null) {
2019                                 // this.log('the chart does not have any data - requesting legend update');
2020                                 needed = true;
2021                         }
2022                         else if(typeof this.element_legend_childs.series.labels_key === 'undefined') {
2023                                 needed = true;
2024                         }
2025                         else {
2026                                 var labels = this.data.dimension_names.toString();
2027                                 if(labels !== this.element_legend_childs.series.labels_key) {
2028                                         needed = true;
2029
2030                                         if(this.debug === true)
2031                                                 this.log('NEW LABELS: "' + labels + '" NOT EQUAL OLD LABELS: "' + this.element_legend_childs.series.labels_key + '"');
2032                                 }
2033                         }
2034
2035                         if(needed === false) {
2036                                 // make sure colors available
2037                                 this.chartColors();
2038
2039                                 // do we have to update the current values?
2040                                 // we do this, only when the visible chart is current
2041                                 if(Math.abs(this.netdata_last - this.view_before) <= this.data_update_every) {
2042                                         if(this.debug === true)
2043                                                 this.log('chart is in latest position... updating values on legend...');
2044
2045                                         //var labels = this.data.dimension_names;
2046                                         //var i = labels.length;
2047                                         //while(i--)
2048                                         //      this.legendSetLabelValue(labels[i], this.data.latest_values[i]);
2049                                 }
2050                                 return;
2051                         }
2052                         if(this.colors === null) {
2053                                 // this is the first time we update the chart
2054                                 // let's assign colors to all dimensions
2055                                 if(this.library.track_colors() === true)
2056                                         for(var dim in this.chart.dimensions)
2057                                                 this._chartDimensionColor(this.chart.dimensions[dim].name);
2058                         }
2059                         // we will re-generate the colors for the chart
2060                         // based on the selected dimensions
2061                         this.colors = null;
2062
2063                         if(this.debug === true)
2064                                 this.log('updating Legend DOM');
2065
2066                         // mark all dimensions as invalid
2067                         this.dimensions_visibility.invalidateAll();
2068
2069                         var genLabel = function(state, parent, name, count) {
2070                                 var color = state._chartDimensionColor(name);
2071
2072                                 var user_element = null;
2073                                 var user_id = self.data('show-value-of-' + name + '-at') || null;
2074                                 if(user_id !== null) {
2075                                         user_element = document.getElementById(user_id) || null;
2076                                         if(user_element === null)
2077                                                 me.log('Cannot find element with id: ' + user_id);
2078                                 }
2079
2080                                 state.element_legend_childs.series[name] = {
2081                                         name: document.createElement('span'),
2082                                         value: document.createElement('span'),
2083                                         user: user_element,
2084                                         last: null
2085                                 };
2086
2087                                 var label = state.element_legend_childs.series[name];
2088
2089                                 // create the dimension visibility tracking for this label
2090                                 state.dimensions_visibility.dimensionAdd(name, label.name, label.value, color);
2091
2092                                 var rgb = NETDATA.colorHex2Rgb(color);
2093                                 label.name.innerHTML = '<table class="netdata-legend-name-table-'
2094                                         + state.chart.chart_type
2095                                         + '" style="background-color: '
2096                                         + 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + NETDATA.options.current['color_fill_opacity_' + state.chart.chart_type] + ')'
2097                                         + '"><tr class="netdata-legend-name-tr"><td class="netdata-legend-name-td"></td></tr></table>'
2098
2099                                 var text = document.createTextNode(' ' + name);
2100                                 label.name.appendChild(text);
2101
2102                                 if(count > 0)
2103                                         parent.appendChild(document.createElement('br'));
2104
2105                                 parent.appendChild(label.name);
2106                                 parent.appendChild(label.value);
2107                         };
2108
2109                         var content = document.createElement('div');
2110
2111                         if(this.hasLegend()) {
2112                                 this.element_legend_childs = {
2113                                         content: content,
2114                                         resize_handler: document.createElement('div'),
2115                                         title_date: document.createElement('span'),
2116                                         title_time: document.createElement('span'),
2117                                         title_units: document.createElement('span'),
2118                                         nano: document.createElement('div'),
2119                                         nano_options: {
2120                                                 paneClass: 'netdata-legend-series-pane',
2121                                                 sliderClass: 'netdata-legend-series-slider',
2122                                                 contentClass: 'netdata-legend-series-content',
2123                                                 enabledClass: '__enabled',
2124                                                 flashedClass: '__flashed',
2125                                                 activeClass: '__active',
2126                                                 tabIndex: -1,
2127                                                 alwaysVisible: true,
2128                                                 sliderMinHeight: 10
2129                                         },
2130                                         series: {}
2131                                 };
2132
2133                                 this.element_legend.innerHTML = '';
2134
2135                                 this.element_legend_childs.resize_handler.className += " netdata-legend-resize-handler";
2136                                 this.element_legend_childs.resize_handler.innerHTML = '<i class="fa fa-chevron-up"></i><i class="fa fa-chevron-down"></i>';
2137                                 this.element.appendChild(this.element_legend_childs.resize_handler);
2138
2139                                 // mousedown event
2140                                 this.element_legend_childs.resize_handler.onmousedown =
2141                                         function(e) {
2142                                                 that.resizeHandler(e);
2143                                         };
2144
2145                                 // touchstart event
2146                                 this.element_legend_childs.resize_handler.addEventListener('touchstart', function(e) {
2147                                         that.resizeHandler(e);
2148                                 }, false);
2149
2150                                 this.element_legend_childs.title_date.className += " netdata-legend-title-date";
2151                                 this.element_legend.appendChild(this.element_legend_childs.title_date);
2152
2153                                 this.element_legend.appendChild(document.createElement('br'));
2154
2155                                 this.element_legend_childs.title_time.className += " netdata-legend-title-time";
2156                                 this.element_legend.appendChild(this.element_legend_childs.title_time);
2157
2158                                 this.element_legend.appendChild(document.createElement('br'));
2159
2160                                 this.element_legend_childs.title_units.className += " netdata-legend-title-units";
2161                                 this.element_legend.appendChild(this.element_legend_childs.title_units);
2162
2163                                 this.element_legend.appendChild(document.createElement('br'));
2164
2165                                 this.element_legend_childs.nano.className = 'netdata-legend-series';
2166                                 this.element_legend.appendChild(this.element_legend_childs.nano);
2167
2168                                 content.className = 'netdata-legend-series-content';
2169                                 this.element_legend_childs.nano.appendChild(content);
2170                         }
2171                         else {
2172                                 this.element_legend_childs = {
2173                                         content: content,
2174                                         resize_handler: null,
2175                                         title_date: null,
2176                                         title_time: null,
2177                                         title_units: null,
2178                                         nano: null,
2179                                         nano_options: null,
2180                                         series: {}
2181                                 };
2182                         }
2183
2184                         if(this.data) {
2185                                 this.element_legend_childs.series.labels_key = this.data.dimension_names.toString();
2186                                 if(this.debug === true)
2187                                         this.log('labels from data: "' + this.element_legend_childs.series.labels_key + '"');
2188
2189                                 for(var i = 0, len = this.data.dimension_names.length; i < len ;i++) {
2190                                         genLabel(this, content, this.data.dimension_names[i], i);
2191                                 }
2192                         }
2193                         else {
2194                                 var tmp = new Array();
2195                                 for(var dim in this.chart.dimensions) {
2196                                         tmp.push(this.chart.dimensions[dim].name);
2197                                         genLabel(this, content, this.chart.dimensions[dim].name, i);
2198                                 }
2199                                 this.element_legend_childs.series.labels_key = tmp.toString();
2200                                 if(this.debug === true)
2201                                         this.log('labels from chart: "' + this.element_legend_childs.series.labels_key + '"');
2202                         }
2203
2204                         // create a hidden div to be used for hidding
2205                         // the original legend of the chart library
2206                         var el = document.createElement('div');
2207                         if(this.element_legend !== null)
2208                                 this.element_legend.appendChild(el);
2209                         el.style.display = 'none';
2210
2211                         this.element_legend_childs.hidden = document.createElement('div');
2212                         el.appendChild(this.element_legend_childs.hidden);
2213
2214                         if(this.element_legend_childs.nano !== null && this.element_legend_childs.nano_options !== null)
2215                                 $(this.element_legend_childs.nano).nanoScroller(this.element_legend_childs.nano_options);
2216
2217                         this.legendShowLatestValues();
2218                 }
2219
2220                 this.hasLegend = function() {
2221                         if(typeof this.___hasLegendCache___ !== 'undefined')
2222                                 return this.___hasLegendCache___;
2223
2224                         var leg = false;
2225                         if(this.library && this.library.legend(this) === 'right-side') {
2226                                 var legend = $(this.element).data('legend') || 'yes';
2227                                 if(legend === 'yes') leg = true;
2228                         }
2229
2230                         this.___hasLegendCache___ = leg;
2231                         return leg;
2232                 }
2233
2234                 this.legendWidth = function() {
2235                         return (this.hasLegend())?140:0;
2236                 }
2237
2238                 this.legendHeight = function() {
2239                         return $(this.element).height();
2240                 }
2241
2242                 this.chartWidth = function() {
2243                         return $(this.element).width() - this.legendWidth();
2244                 }
2245
2246                 this.chartHeight = function() {
2247                         return $(this.element).height();
2248                 }
2249
2250                 this.chartPixelsPerPoint = function() {
2251                         // force an options provided detail
2252                         var px = this.pixels_per_point;
2253
2254                         if(this.library && px < this.library.pixels_per_point(this))
2255                                 px = this.library.pixels_per_point(this);
2256
2257                         if(px < NETDATA.options.current.pixels_per_point)
2258                                 px = NETDATA.options.current.pixels_per_point;
2259
2260                         return px;
2261                 }
2262
2263                 this.needsRecreation = function() {
2264                         return (
2265                                         this.chart_created === true
2266                                         && this.library
2267                                         && this.library.autoresize() === false
2268                                         && this.tm.last_resized < NETDATA.options.last_resized
2269                                 );
2270                 }
2271
2272                 this.chartURL = function() {
2273                         var after, before, points_multiplier = 1;
2274                         if(NETDATA.globalPanAndZoom.isActive() && NETDATA.globalPanAndZoom.isMaster(this) === false) {
2275                                 this.tm.pan_and_zoom_seq = NETDATA.globalPanAndZoom.seq;
2276
2277                                 after = Math.round(NETDATA.globalPanAndZoom.force_after_ms / 1000);
2278                                 before = Math.round(NETDATA.globalPanAndZoom.force_before_ms / 1000);
2279                                 this.view_after = after * 1000;
2280                                 this.view_before = before * 1000;
2281
2282                                 this.requested_padding = null;
2283                                 points_multiplier = 1;
2284                         }
2285                         else if(this.current.force_before_ms !== null && this.current.force_after_ms !== null) {
2286                                 this.tm.pan_and_zoom_seq = 0;
2287
2288                                 before = Math.round(this.current.force_before_ms / 1000);
2289                                 after  = Math.round(this.current.force_after_ms / 1000);
2290                                 this.view_after = after * 1000;
2291                                 this.view_before = before * 1000;
2292
2293                                 if(NETDATA.options.current.pan_and_zoom_data_padding === true) {
2294                                         this.requested_padding = Math.round((before - after) / 2);
2295                                         after -= this.requested_padding;
2296                                         before += this.requested_padding;
2297                                         this.requested_padding *= 1000;
2298                                         points_multiplier = 2;
2299                                 }
2300
2301                                 this.current.force_before_ms = null;
2302                                 this.current.force_after_ms = null;
2303                         }
2304                         else {
2305                                 this.tm.pan_and_zoom_seq = 0;
2306
2307                                 before = this.before;
2308                                 after  = this.after;
2309                                 this.view_after = after * 1000;
2310                                 this.view_before = before * 1000;
2311
2312                                 this.requested_padding = null;
2313                                 points_multiplier = 1;
2314                         }
2315
2316                         this.requested_after = after * 1000;
2317                         this.requested_before = before * 1000;
2318
2319                         this.data_points = this.points || Math.round(this.chartWidth() / this.chartPixelsPerPoint());
2320
2321                         // build the data URL
2322                         this.data_url = this.host + this.chart.data_url;
2323                         this.data_url += "&format="  + this.library.format();
2324                         this.data_url += "&points="  + (this.data_points * points_multiplier).toString();
2325                         this.data_url += "&group="   + this.method;
2326                         this.data_url += "&options=" + this.library.options(this);
2327                         this.data_url += '|jsonwrap';
2328
2329                         if(NETDATA.options.current.eliminate_zero_dimensions === true)
2330                                 this.data_url += '|nonzero';
2331
2332                         if(this.append_options !== null)
2333                                 this.data_url += '|' + this.append_options.toString();
2334
2335                         if(after)
2336                                 this.data_url += "&after="  + after.toString();
2337
2338                         if(before)
2339                                 this.data_url += "&before=" + before.toString();
2340
2341                         if(this.dimensions)
2342                                 this.data_url += "&dimensions=" + this.dimensions;
2343
2344                         if(NETDATA.options.debug.chart_data_url === true || this.debug === true)
2345                                 this.log('chartURL(): ' + this.data_url + ' WxH:' + this.chartWidth() + 'x' + this.chartHeight() + ' points: ' + this.data_points + ' library: ' + this.library_name);
2346                 }
2347
2348                 this.redrawChart = function() {
2349                         if(this.data !== null)
2350                                 this.updateChartWithData(this.data);
2351                 }
2352
2353                 this.updateChartWithData = function(data) {
2354                         if(this.debug === true)
2355                                 this.log('updateChartWithData() called.');
2356
2357                         this._updating = false;
2358
2359                         // this may force the chart to be re-created
2360                         resizeChart();
2361
2362                         this.data = data;
2363                         this.updates_counter++;
2364                         this.updates_since_last_unhide++;
2365                         this.updates_since_last_creation++;
2366
2367                         var started = new Date().getTime();
2368
2369                         // if the result is JSON, find the latest update-every
2370                         this.data_update_every = data.view_update_every * 1000;
2371                         this.data_after = data.after * 1000;
2372                         this.data_before = data.before * 1000;
2373                         this.netdata_first = data.first_entry * 1000;
2374                         this.netdata_last = data.last_entry * 1000;
2375                         this.data_points = data.points;
2376                         data.state = this;
2377
2378                         if(NETDATA.options.current.pan_and_zoom_data_padding === true && this.requested_padding !== null) {
2379                                 if(this.view_after < this.data_after) {
2380                                         // console.log('adusting view_after from ' + this.view_after + ' to ' + this.data_after);
2381                                         this.view_after = this.data_after;
2382                                 }
2383                                 
2384                                 if(this.view_before > this.data_before) {
2385                                         // console.log('adusting view_before from ' + this.view_before + ' to ' + this.data_before);
2386                                         this.view_before = this.data_before;
2387                                 }
2388                         }
2389                         else {
2390                                 this.view_after = this.data_after;
2391                                 this.view_before = this.data_before;
2392                         }
2393
2394                         if(this.debug === true) {
2395                                 this.log('UPDATE No ' + this.updates_counter + ' COMPLETED');
2396
2397                                 if(this.current.force_after_ms)
2398                                         this.log('STATUS: forced    : ' + (this.current.force_after_ms / 1000).toString() + ' - ' + (this.current.force_before_ms / 1000).toString());
2399                                 else
2400                                         this.log('STATUS: forced    : unset');
2401
2402                                 this.log('STATUS: requested : ' + (this.requested_after / 1000).toString() + ' - ' + (this.requested_before / 1000).toString());
2403                                 this.log('STATUS: downloaded: ' + (this.data_after / 1000).toString() + ' - ' + (this.data_before / 1000).toString());
2404                                 this.log('STATUS: rendered  : ' + (this.view_after / 1000).toString() + ' - ' + (this.view_before / 1000).toString());
2405                                 this.log('STATUS: points    : ' + (this.data_points).toString());
2406                         }
2407
2408                         if(this.data_points === 0) {
2409                                 noDataToShow();
2410                                 return;
2411                         }
2412
2413                         if(this.updates_since_last_creation >= this.library.max_updates_to_recreate()) {
2414                                 if(this.debug === true)
2415                                         this.log('max updates of ' + this.updates_since_last_creation.toString() + ' reached. Forcing re-generation.');
2416
2417                                 this.chart_created = false;
2418                         }
2419
2420                         // check and update the legend
2421                         this.legendUpdateDOM();
2422
2423                         if(this.chart_created === true
2424                                 && typeof this.library.update === 'function') {
2425
2426                                 if(this.debug === true)
2427                                         this.log('updating chart...');
2428
2429                                 if(callChartLibraryUpdateSafely(data) === false)
2430                                         return;
2431                         }
2432                         else {
2433                                 if(this.debug === true)
2434                                         this.log('creating chart...');
2435
2436                                 if(callChartLibraryCreateSafely(data) === false)
2437                                         return;
2438                         }
2439                         hideMessage();
2440                         this.legendShowLatestValues();
2441                         if(this.selected === true)
2442                                 NETDATA.globalSelectionSync.stop();
2443
2444                         // update the performance counters
2445                         var now = new Date().getTime();
2446                         this.tm.last_updated = now;
2447
2448                         // don't update last_autorefreshed if this chart is
2449                         // forced to be updated with global PanAndZoom
2450                         if(NETDATA.globalPanAndZoom.isActive())
2451                                 this.tm.last_autorefreshed = 0;
2452                         else {
2453                                 if(NETDATA.options.current.parallel_refresher === true && NETDATA.options.current.concurrent_refreshes)
2454                                         this.tm.last_autorefreshed = Math.round(now / this.data_update_every) * this.data_update_every;
2455                                 else
2456                                         this.tm.last_autorefreshed = now;
2457                         }
2458
2459                         this.refresh_dt_ms = now - started;
2460                         NETDATA.options.auto_refresher_fast_weight += this.refresh_dt_ms;
2461
2462                         if(this.refresh_dt_element !== null)
2463                                 this.refresh_dt_element.innerHTML = this.refresh_dt_ms.toString();
2464                 }
2465
2466                 this.updateChart = function(callback) {
2467                         if(this.debug === true)
2468                                 this.log('updateChart() called.');
2469
2470                         if(this._updating === true) {
2471                                 if(this.debug === true)
2472                                         this.log('I am already updating...');
2473
2474                                 if(typeof callback === 'function') callback();
2475                                 return false;
2476                         }
2477
2478                         // due to late initialization of charts and libraries
2479                         // we need to check this too
2480                         if(this.enabled === false) {
2481                                 if(this.debug === true)
2482                                         this.log('I am not enabled');
2483
2484                                 if(typeof callback === 'function') callback();
2485                                 return false;
2486                         }
2487
2488                         if(canBeRendered() === false) {
2489                                 if(typeof callback === 'function') callback();
2490                                 return false;
2491                         }
2492
2493                         if(this.chart === null) {
2494                                 this.getChart(function() { that.updateChart(callback); });
2495                                 return false;
2496                         }
2497
2498                         if(this.library.initialized === false) {
2499                                 if(this.library.enabled === true) {
2500                                         this.library.initialize(function() { that.updateChart(callback); });
2501                                         return false;
2502                                 }
2503                                 else {
2504                                         error('chart library "' + this.library_name + '" is not available.');
2505                                         if(typeof callback === 'function') callback();
2506                                         return false;
2507                                 }
2508                         }
2509
2510                         this.clearSelection();
2511                         this.chartURL();
2512
2513                         if(this.debug === true)
2514                                 this.log('updating from ' + this.data_url);
2515
2516                         this._updating = true;
2517
2518                         this.xhr = $.ajax( {
2519                                 url: this.data_url,
2520                                 crossDomain: NETDATA.options.crossDomainAjax,
2521                                 cache: false,
2522                                 async: true
2523                         })
2524                         .success(function(data) {
2525                                 if(that.debug === true)
2526                                         that.log('data received. updating chart.');
2527
2528                                 that.updateChartWithData(data);
2529                         })
2530                         .fail(function() {
2531                                 error('data download failed for url: ' + that.data_url);
2532                         })
2533                         .always(function() {
2534                                 this._updating = false;
2535                                 if(typeof callback === 'function') callback();
2536                         });
2537
2538                         return true;
2539                 }
2540
2541                 this.isVisible = function(nocache) {
2542                         if(typeof nocache === 'undefined')
2543                                 nocache = false;
2544
2545                         // this.log('last_visible_check: ' + this.tm.last_visible_check + ', last_page_scroll: ' + NETDATA.options.last_page_scroll);
2546
2547                         // caching - we do not evaluate the charts visibility
2548                         // if the page has not been scrolled since the last check
2549                         if(nocache === false && this.tm.last_visible_check > NETDATA.options.last_page_scroll)
2550                                 return this.___isVisible___;
2551
2552                         this.tm.last_visible_check = new Date().getTime();
2553
2554                         var wh = window.innerHeight;
2555                         var x = this.element.getBoundingClientRect();
2556                         var ret = 0;
2557                         var tolerance = 0;
2558
2559                         if(x.width === 0 || x.height === 0) {
2560                                 hideChart();
2561                                 this.___isVisible___ = false;
2562                                 return this.___isVisible___;
2563                         }
2564
2565                         if(x.top < 0 && -x.top > x.height) {
2566                                 // the chart is entirely above
2567                                 ret = -x.top - x.height;
2568                         }
2569                         else if(x.top > wh) {
2570                                 // the chart is entirely below
2571                                 ret = x.top - wh;
2572                         }
2573
2574                         if(ret > tolerance) {
2575                                 // the chart is too far
2576
2577                                 hideChart();
2578                                 this.___isVisible___ = false;
2579                                 return this.___isVisible___;
2580                         }
2581                         else {
2582                                 // the chart is inside or very close
2583
2584                                 unhideChart();
2585                                 this.___isVisible___ = true;
2586                                 return this.___isVisible___;
2587                         }
2588                 }
2589
2590                 this.isAutoRefreshed = function() {
2591                         return (this.current.autorefresh);
2592                 }
2593
2594                 this.canBeAutoRefreshed = function() {
2595                         now = new Date().getTime();
2596
2597                         if(this.enabled === false) {
2598                                 if(this.debug === true)
2599                                         this.log('I am not enabled');
2600
2601                                 return false;
2602                         }
2603
2604                         if(this.library === null || this.library.enabled === false) {
2605                                 error('charting library "' + this.library_name + '" is not available');
2606                                 if(this.debug === true)
2607                                         this.log('My chart library ' + this.library_name + ' is not available');
2608
2609                                 return false;
2610                         }
2611
2612                         if(this.isVisible() === false) {
2613                                 if(NETDATA.options.debug.visibility === true || this.debug === true)
2614                                         this.log('I am not visible');
2615
2616                                 return false;
2617                         }
2618
2619                         if(this.current.force_update_at !== 0 && this.current.force_update_at < now) {
2620                                 if(this.debug === true)
2621                                         this.log('timed force update detected - allowing this update');
2622
2623                                 this.current.force_update_at = 0;
2624                                 return true;
2625                         }
2626
2627                         if(this.isAutoRefreshed() === true) {
2628                                 // allow the first update, even if the page is not visible
2629                                 if(this.updates_counter && this.updates_since_last_unhide && NETDATA.options.page_is_visible === false) {
2630                                         if(NETDATA.options.debug.focus === true || this.debug === true)
2631                                                 this.log('canBeAutoRefreshed(): page does not have focus');
2632
2633                                         return false;
2634                                 }
2635
2636                                 if(this.needsRecreation() === true) {
2637                                         if(this.debug === true)
2638                                                 this.log('canBeAutoRefreshed(): needs re-creation.');
2639
2640                                         return true;
2641                                 }
2642
2643                                 // options valid only for autoRefresh()
2644                                 if(NETDATA.options.auto_refresher_stop_until === 0 || NETDATA.options.auto_refresher_stop_until < now) {
2645                                         if(NETDATA.globalPanAndZoom.isActive()) {
2646                                                 if(NETDATA.globalPanAndZoom.shouldBeAutoRefreshed(this)) {
2647                                                         if(this.debug === true)
2648                                                                 this.log('canBeAutoRefreshed(): global panning: I need an update.');
2649
2650                                                         return true;
2651                                                 }
2652                                                 else {
2653                                                         if(this.debug === true)
2654                                                                 this.log('canBeAutoRefreshed(): global panning: I am already up to date.');
2655
2656                                                         return false;
2657                                                 }
2658                                         }
2659
2660                                         if(this.selected === true) {
2661                                                 if(this.debug === true)
2662                                                         this.log('canBeAutoRefreshed(): I have a selection in place.');
2663
2664                                                 return false;
2665                                         }
2666
2667                                         if(this.paused === true) {
2668                                                 if(this.debug === true)
2669                                                         this.log('canBeAutoRefreshed(): I am paused.');
2670
2671                                                 return false;
2672                                         }
2673
2674                                         if(now - this.tm.last_autorefreshed >= this.data_update_every) {
2675                                                 if(this.debug === true)
2676                                                         this.log('canBeAutoRefreshed(): It is time to update me.');
2677
2678                                                 return true;
2679                                         }
2680                                 }
2681                         }
2682
2683                         return false;
2684                 }
2685
2686                 this.autoRefresh = function(callback) {
2687                         if(this.canBeAutoRefreshed() === true) {
2688                                 this.updateChart(callback);
2689                         }
2690                         else {
2691                                 if(typeof callback !== 'undefined')
2692                                         callback();
2693                         }
2694                 }
2695
2696                 this._defaultsFromDownloadedChart = function(chart) {
2697                         this.chart = chart;
2698                         this.chart_url = chart.url;
2699                         this.data_update_every = chart.update_every * 1000;
2700                         this.data_points = Math.round(this.chartWidth() / this.chartPixelsPerPoint());
2701                         this.tm.last_info_downloaded = new Date().getTime();
2702
2703                         if(this.title === null)
2704                                 this.title = chart.title;
2705
2706                         if(this.units === null)
2707                                 this.units = chart.units;
2708                 }
2709
2710                 // fetch the chart description from the netdata server
2711                 this.getChart = function(callback) {
2712                         this.chart = NETDATA.chartRegistry.get(this.host, this.id);
2713                         if(this.chart) {
2714                                 this._defaultsFromDownloadedChart(this.chart);
2715                                 if(typeof callback === 'function') callback();
2716                         }
2717                         else {
2718                                 this.chart_url = "/api/v1/chart?chart=" + this.id;
2719
2720                                 if(this.debug === true)
2721                                         this.log('downloading ' + this.chart_url);
2722
2723                                 $.ajax( {
2724                                         url:  this.host + this.chart_url,
2725                                         crossDomain: NETDATA.options.crossDomainAjax,
2726                                         cache: false,
2727                                         async: true
2728                                 })
2729                                 .done(function(chart) {
2730                                         chart.url = that.chart_url;
2731                                         that._defaultsFromDownloadedChart(chart);
2732                                         NETDATA.chartRegistry.add(that.host, that.id, chart);
2733                                 })
2734                                 .fail(function() {
2735                                         NETDATA.error(404, that.chart_url);
2736                                         error('chart not found on url "' + that.chart_url + '"');
2737                                 })
2738                                 .always(function() {
2739                                         if(typeof callback === 'function') callback();
2740                                 });
2741                         }
2742                 }
2743
2744                 // ============================================================================================================
2745                 // INITIALIZATION
2746
2747                 init();
2748         }
2749
2750         NETDATA.resetAllCharts = function(state) {
2751                 // first clear the global selection sync
2752                 // to make sure no chart is in selected state
2753                 state.globalSelectionSyncStop();
2754
2755                 // there are 2 possibilities here
2756                 // a. state is the global Pan and Zoom master
2757                 // b. state is not the global Pan and Zoom master
2758                 var master = true;
2759                 if(NETDATA.globalPanAndZoom.isMaster(state) === false)
2760                         master = false;
2761
2762                 // clear the global Pan and Zoom
2763                 // this will also refresh the master
2764                 // and unblock any charts currently mirroring the master
2765                 NETDATA.globalPanAndZoom.clearMaster();
2766
2767                 // if we were not the master, reset our status too
2768                 // this is required because most probably the mouse
2769                 // is over this chart, blocking it from autorefreshing
2770                 if(master === false && (state.paused === true || state.selected === true))
2771                         state.resetChart();
2772         }
2773
2774         // get or create a chart state, given a DOM element
2775         NETDATA.chartState = function(element) {
2776                 var state = $(element).data('netdata-state-object') || null;
2777                 if(state === null) {
2778                         state = new chartState(element);
2779                         $(element).data('netdata-state-object', state);
2780                 }
2781                 return state;
2782         }
2783
2784         // ----------------------------------------------------------------------------------------------------------------
2785         // Library functions
2786
2787         // Load a script without jquery
2788         // This is used to load jquery - after it is loaded, we use jquery
2789         NETDATA._loadjQuery = function(callback) {
2790                 if(typeof jQuery === 'undefined') {
2791                         if(NETDATA.options.debug.main_loop === true)
2792                                 console.log('loading ' + NETDATA.jQuery);
2793
2794                         var script = document.createElement('script');
2795                         script.type = 'text/javascript';
2796                         script.async = true;
2797                         script.src = NETDATA.jQuery;
2798
2799                         // script.onabort = onError;
2800                         script.onerror = function(err, t) { NETDATA.error(101, NETDATA.jQuery); };
2801                         if(typeof callback === "function")
2802                                 script.onload = callback;
2803
2804                         var s = document.getElementsByTagName('script')[0];
2805                         s.parentNode.insertBefore(script, s);
2806                 }
2807                 else if(typeof callback === "function")
2808                         callback();
2809         }
2810
2811         NETDATA._loadCSS = function(filename) {
2812                 // don't use jQuery here
2813                 // styles are loaded before jQuery
2814                 // to eliminate showing an unstyled page to the user
2815
2816                 var fileref = document.createElement("link");
2817                 fileref.setAttribute("rel", "stylesheet");
2818                 fileref.setAttribute("type", "text/css");
2819                 fileref.setAttribute("href", filename);
2820
2821                 if (typeof fileref !== 'undefined')
2822                         document.getElementsByTagName("head")[0].appendChild(fileref);
2823         }
2824
2825         NETDATA.colorHex2Rgb = function(hex) {
2826                 // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
2827                 var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
2828                         hex = hex.replace(shorthandRegex, function(m, r, g, b) {
2829                         return r + r + g + g + b + b;
2830                 });
2831
2832                 var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
2833                 return result ? {
2834                         r: parseInt(result[1], 16),
2835                         g: parseInt(result[2], 16),
2836                         b: parseInt(result[3], 16)
2837                 } : null;
2838         }
2839
2840         NETDATA.colorLuminance = function(hex, lum) {
2841                 // validate hex string
2842                 hex = String(hex).replace(/[^0-9a-f]/gi, '');
2843                 if (hex.length < 6)
2844                         hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
2845
2846                 lum = lum || 0;
2847
2848                 // convert to decimal and change luminosity
2849                 var rgb = "#", c, i;
2850                 for (i = 0; i < 3; i++) {
2851                         c = parseInt(hex.substr(i*2,2), 16);
2852                         c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
2853                         rgb += ("00"+c).substr(c.length);
2854                 }
2855
2856                 return rgb;
2857         }
2858
2859         NETDATA.guid = function() {
2860                 function s4() {
2861                         return Math.floor((1 + Math.random()) * 0x10000)
2862                                         .toString(16)
2863                                         .substring(1);
2864                         }
2865
2866                         return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
2867         }
2868
2869         NETDATA.zeropad = function(x) {
2870                 if(x > -10 && x < 10) return '0' + x.toString();
2871                 else return x.toString();
2872         }
2873
2874         // user function to signal us the DOM has been
2875         // updated.
2876         NETDATA.updatedDom = function() {
2877                 NETDATA.options.updated_dom = true;
2878         }
2879
2880         NETDATA.ready = function(callback) {
2881                 NETDATA.options.pauseCallback = callback;
2882         }
2883
2884         NETDATA.pause = function(callback) {
2885                 if(NETDATA.options.pause === true)
2886                         callback();
2887                 else
2888                         NETDATA.options.pauseCallback = callback;
2889         }
2890
2891         NETDATA.unpause = function() {
2892                 NETDATA.options.pauseCallback = null;
2893                 NETDATA.options.updated_dom = true;
2894                 NETDATA.options.pause = false;
2895         }
2896
2897         // ----------------------------------------------------------------------------------------------------------------
2898
2899         // this is purely sequencial charts refresher
2900         // it is meant to be autonomous
2901         NETDATA.chartRefresherNoParallel = function(index) {
2902                 if(NETDATA.options.debug.mail_loop === true)
2903                         console.log('NETDATA.chartRefresherNoParallel(' + index + ')');
2904
2905                 if(NETDATA.options.updated_dom === true) {
2906                         // the dom has been updated
2907                         // get the dom parts again
2908                         NETDATA.parseDom(NETDATA.chartRefresher);
2909                         return;
2910                 }
2911                 if(index >= NETDATA.options.targets.length) {
2912                         if(NETDATA.options.debug.main_loop === true)
2913                                 console.log('waiting to restart main loop...');
2914
2915                         NETDATA.options.auto_refresher_fast_weight = 0;
2916
2917                         setTimeout(function() {
2918                                 NETDATA.chartRefresher();
2919                         }, NETDATA.options.current.idle_between_loops);
2920                 }
2921                 else {
2922                         var state = NETDATA.options.targets[index];
2923
2924                         if(NETDATA.options.auto_refresher_fast_weight < NETDATA.options.current.fast_render_timeframe) {
2925                                 if(NETDATA.options.debug.main_loop === true)
2926                                         console.log('fast rendering...');
2927
2928                                 state.autoRefresh(function() {
2929                                         NETDATA.chartRefresherNoParallel(++index);
2930                                 });
2931                         }
2932                         else {
2933                                 if(NETDATA.options.debug.main_loop === true) console.log('waiting for next refresh...');
2934                                 NETDATA.options.auto_refresher_fast_weight = 0;
2935
2936                                 setTimeout(function() {
2937                                         state.autoRefresh(function() {
2938                                                 NETDATA.chartRefresherNoParallel(++index);
2939                                         });
2940                                 }, NETDATA.options.current.idle_between_charts);
2941                         }
2942                 }
2943         }
2944
2945         // this is part of the parallel refresher
2946         // its cause is to refresh sequencially all the charts
2947         // that depend on chart library initialization
2948         // it will call the parallel refresher back
2949         // as soon as it sees a chart that its chart library
2950         // is initialized
2951         NETDATA.chartRefresher_unitialized = function() {
2952                 if(NETDATA.options.updated_dom === true) {
2953                         // the dom has been updated
2954                         // get the dom parts again
2955                         NETDATA.parseDom(NETDATA.chartRefresher);
2956                         return;
2957                 }
2958
2959                 if(NETDATA.options.sequencial.length === 0)
2960                         NETDATA.chartRefresher();
2961                 else {
2962                         var state = NETDATA.options.sequencial.pop();
2963                         if(state.library.initialized === true)
2964                                 NETDATA.chartRefresher();
2965                         else
2966                                 state.autoRefresh(NETDATA.chartRefresher_unitialized);
2967                 }
2968         }
2969
2970         NETDATA.chartRefresherWaitTime = function() {
2971                 return NETDATA.options.current.idle_parallel_loops;
2972         }
2973
2974         // the default refresher
2975         // it will create 2 sets of charts:
2976         // - the ones that can be refreshed in parallel
2977         // - the ones that depend on something else
2978         // the first set will be executed in parallel
2979         // the second will be given to NETDATA.chartRefresher_unitialized()
2980         NETDATA.chartRefresher = function() {
2981                 if(NETDATA.options.pause === true) {
2982                         // console.log('auto-refresher is paused');
2983                         setTimeout(NETDATA.chartRefresher,
2984                                 NETDATA.chartRefresherWaitTime());
2985                         return;
2986                 }
2987
2988                 if(typeof NETDATA.options.pauseCallback === 'function') {
2989                         // console.log('auto-refresher is calling pauseCallback');
2990                         NETDATA.options.pause = true;
2991                         NETDATA.options.pauseCallback();
2992                         NETDATA.chartRefresher();
2993                         return;
2994                 }
2995
2996                 if(NETDATA.options.current.parallel_refresher === false) {
2997                         NETDATA.chartRefresherNoParallel(0);
2998                         return;
2999                 }
3000
3001                 if(NETDATA.options.updated_dom === true) {
3002                         // the dom has been updated
3003                         // get the dom parts again
3004                         NETDATA.parseDom(NETDATA.chartRefresher);
3005                         return;
3006                 }
3007
3008                 var parallel = new Array();
3009                 var targets = NETDATA.options.targets;
3010                 var len = targets.length;
3011                 while(len--) {
3012                         if(targets[len].isVisible() === false)
3013                                 continue;
3014
3015                         var state = targets[len];
3016                         if(state.library.initialized === false) {
3017                                 if(state.library.enabled === true) {
3018                                         state.library.initialize(NETDATA.chartRefresher);
3019                                         return;
3020                                 }
3021                                 else {
3022                                         state.error('chart library "' + state.library_name + '" is not enabled.');
3023                                 }
3024                         }
3025
3026                         parallel.unshift(state);
3027                 }
3028
3029                 if(parallel.length > 0) {
3030                         var parallel_jobs = parallel.length;
3031
3032                         // this will execute the jobs in parallel
3033                         $(parallel).each(function() {
3034                                 this.autoRefresh(function() {
3035                                         parallel_jobs--;
3036
3037                                         if(parallel_jobs === 0) {
3038                                                 setTimeout(NETDATA.chartRefresher,
3039                                                         NETDATA.chartRefresherWaitTime());
3040                                         }
3041                                 });
3042                         })
3043                 }
3044                 else {
3045                         setTimeout(NETDATA.chartRefresher,
3046                                 NETDATA.chartRefresherWaitTime());
3047                 }
3048         }
3049
3050         NETDATA.parseDom = function(callback) {
3051                 NETDATA.options.last_page_scroll = new Date().getTime();
3052                 NETDATA.options.updated_dom = false;
3053
3054                 var targets = $('div[data-netdata]'); //.filter(':visible');
3055
3056                 if(NETDATA.options.debug.main_loop === true)
3057                         console.log('DOM updated - there are ' + targets.length + ' charts on page.');
3058
3059                 NETDATA.options.targets = new Array();
3060                 var len = targets.length;
3061                 while(len--) {
3062                         // the initialization will take care of sizing
3063                         // and the "loading..." message
3064                         NETDATA.options.targets.push(NETDATA.chartState(targets[len]));
3065                 }
3066
3067                 if(typeof callback === 'function') callback();
3068         }
3069
3070         // this is the main function - where everything starts
3071         NETDATA.start = function() {
3072                 // this should be called only once
3073
3074                 NETDATA.options.page_is_visible = true;
3075
3076                 $(window).blur(function() {
3077                         if(NETDATA.options.current.stop_updates_when_focus_is_lost === true) {
3078                                 NETDATA.options.page_is_visible = false;
3079                                 if(NETDATA.options.debug.focus === true)
3080                                         console.log('Lost Focus!');
3081                         }
3082                 });
3083
3084                 $(window).focus(function() {
3085                         if(NETDATA.options.current.stop_updates_when_focus_is_lost === true) {
3086                                 NETDATA.options.page_is_visible = true;
3087                                 if(NETDATA.options.debug.focus === true)
3088                                         console.log('Focus restored!');
3089                         }
3090                 });
3091
3092                 if(typeof document.hasFocus === 'function' && !document.hasFocus()) {
3093                         if(NETDATA.options.current.stop_updates_when_focus_is_lost === true) {
3094                                 NETDATA.options.page_is_visible = false;
3095                                 if(NETDATA.options.debug.focus === true)
3096                                         console.log('Document has no focus!');
3097                         }
3098                 }
3099
3100                 // bootstrap tab switching
3101                 $('a[data-toggle="tab"]').on('shown.bs.tab', NETDATA.onscroll);
3102
3103                 // bootstrap modal switching
3104                 $('.modal').on('hidden.bs.modal', NETDATA.onscroll);
3105                 $('.modal').on('shown.bs.modal', NETDATA.onscroll);
3106                 
3107                 NETDATA.parseDom(NETDATA.chartRefresher);
3108         }
3109
3110         // ----------------------------------------------------------------------------------------------------------------
3111         // peity
3112
3113         NETDATA.peityInitialize = function(callback) {
3114                 if(typeof netdataNoPeitys === 'undefined' || !netdataNoPeitys) {
3115                         $.ajax({
3116                                 url: NETDATA.peity_js,
3117                                 cache: true,
3118                                 dataType: "script"
3119                         })
3120                         .done(function() {
3121                                 NETDATA.registerChartLibrary('peity', NETDATA.peity_js);
3122                         })
3123                         .fail(function() {
3124                                 NETDATA.chartLibraries.peity.enabled = false;
3125                                 NETDATA.error(100, NETDATA.peity_js);
3126                         })
3127                         .always(function() {
3128                                 if(typeof callback === "function")
3129                                         callback();
3130                         });
3131                 }
3132                 else {
3133                         NETDATA.chartLibraries.peity.enabled = false;
3134                         if(typeof callback === "function")
3135                                 callback();
3136                 }
3137         };
3138
3139         NETDATA.peityChartUpdate = function(state, data) {
3140                 state.peity_instance.innerHTML = data.result;
3141
3142                 if(state.peity_options.stroke !== state.chartColors()[0]) {
3143                         state.peity_options.stroke = state.chartColors()[0];
3144                         if(state.chart.chart_type === 'line')
3145                                 state.peity_options.fill = NETDATA.themes.current.background;
3146                         else
3147                                 state.peity_options.fill = NETDATA.colorLuminance(state.chartColors()[0], NETDATA.chartDefaults.fill_luminance);
3148                 }
3149
3150                 $(state.peity_instance).peity('line', state.peity_options);
3151                 return true;
3152         }
3153
3154         NETDATA.peityChartCreate = function(state, data) {
3155                 state.peity_instance = document.createElement('div');
3156                 state.element_chart.appendChild(state.peity_instance);
3157
3158                 var self = $(state.element);
3159                 state.peity_options = {
3160                         stroke: NETDATA.themes.current.foreground,
3161                         strokeWidth: self.data('peity-strokewidth') || 1,
3162                         width: state.chartWidth(),
3163                         height: state.chartHeight(),
3164                         fill: NETDATA.themes.current.foreground
3165                 };
3166
3167                 NETDATA.peityChartUpdate(state, data);
3168                 return true;
3169         }
3170
3171         // ----------------------------------------------------------------------------------------------------------------
3172         // sparkline
3173
3174         NETDATA.sparklineInitialize = function(callback) {
3175                 if(typeof netdataNoSparklines === 'undefined' || !netdataNoSparklines) {
3176                         $.ajax({
3177                                 url: NETDATA.sparkline_js,
3178                                 cache: true,
3179                                 dataType: "script"
3180                         })
3181                         .done(function() {
3182                                 NETDATA.registerChartLibrary('sparkline', NETDATA.sparkline_js);
3183                         })
3184                         .fail(function() {
3185                                 NETDATA.chartLibraries.sparkline.enabled = false;
3186                                 NETDATA.error(100, NETDATA.sparkline_js);
3187                         })
3188                         .always(function() {
3189                                 if(typeof callback === "function")
3190                                         callback();
3191                         });
3192                 }
3193                 else {
3194                         NETDATA.chartLibraries.sparkline.enabled = false;
3195                         if(typeof callback === "function") 
3196                                 callback();
3197                 }
3198         };
3199
3200         NETDATA.sparklineChartUpdate = function(state, data) {
3201                 state.sparkline_options.width = state.chartWidth();
3202                 state.sparkline_options.height = state.chartHeight();
3203
3204                 $(state.element_chart).sparkline(data.result, state.sparkline_options);
3205                 return true;
3206         }
3207
3208         NETDATA.sparklineChartCreate = function(state, data) {
3209                 var self = $(state.element);
3210                 var type = self.data('sparkline-type') || 'line';
3211                 var lineColor = self.data('sparkline-linecolor') || state.chartColors()[0];
3212                 var fillColor = self.data('sparkline-fillcolor') || (state.chart.chart_type === 'line')?NETDATA.themes.current.background:NETDATA.colorLuminance(lineColor, NETDATA.chartDefaults.fill_luminance);
3213                 var chartRangeMin = self.data('sparkline-chartrangemin') || undefined;
3214                 var chartRangeMax = self.data('sparkline-chartrangemax') || undefined;
3215                 var composite = self.data('sparkline-composite') || undefined;
3216                 var enableTagOptions = self.data('sparkline-enabletagoptions') || undefined;
3217                 var tagOptionPrefix = self.data('sparkline-tagoptionprefix') || undefined;
3218                 var tagValuesAttribute = self.data('sparkline-tagvaluesattribute') || undefined;
3219                 var disableHiddenCheck = self.data('sparkline-disablehiddencheck') || undefined;
3220                 var defaultPixelsPerValue = self.data('sparkline-defaultpixelspervalue') || undefined;
3221                 var spotColor = self.data('sparkline-spotcolor') || undefined;
3222                 var minSpotColor = self.data('sparkline-minspotcolor') || undefined;
3223                 var maxSpotColor = self.data('sparkline-maxspotcolor') || undefined;
3224                 var spotRadius = self.data('sparkline-spotradius') || undefined;
3225                 var valueSpots = self.data('sparkline-valuespots') || undefined;
3226                 var highlightSpotColor = self.data('sparkline-highlightspotcolor') || undefined;
3227                 var highlightLineColor = self.data('sparkline-highlightlinecolor') || undefined;
3228                 var lineWidth = self.data('sparkline-linewidth') || undefined;
3229                 var normalRangeMin = self.data('sparkline-normalrangemin') || undefined;
3230                 var normalRangeMax = self.data('sparkline-normalrangemax') || undefined;
3231                 var drawNormalOnTop = self.data('sparkline-drawnormalontop') || undefined;
3232                 var xvalues = self.data('sparkline-xvalues') || undefined;
3233                 var chartRangeClip = self.data('sparkline-chartrangeclip') || undefined;
3234                 var xvalues = self.data('sparkline-xvalues') || undefined;
3235                 var chartRangeMinX = self.data('sparkline-chartrangeminx') || undefined;
3236                 var chartRangeMaxX = self.data('sparkline-chartrangemaxx') || undefined;
3237                 var disableInteraction = self.data('sparkline-disableinteraction') || false;
3238                 var disableTooltips = self.data('sparkline-disabletooltips') || false;
3239                 var disableHighlight = self.data('sparkline-disablehighlight') || false;
3240                 var highlightLighten = self.data('sparkline-highlightlighten') || 1.4;
3241                 var highlightColor = self.data('sparkline-highlightcolor') || undefined;
3242                 var tooltipContainer = self.data('sparkline-tooltipcontainer') || undefined;
3243                 var tooltipClassname = self.data('sparkline-tooltipclassname') || undefined;
3244                 var tooltipFormat = self.data('sparkline-tooltipformat') || undefined;
3245                 var tooltipPrefix = self.data('sparkline-tooltipprefix') || undefined;
3246                 var tooltipSuffix = self.data('sparkline-tooltipsuffix') || ' ' + state.units;
3247                 var tooltipSkipNull = self.data('sparkline-tooltipskipnull') || true;
3248                 var tooltipValueLookups = self.data('sparkline-tooltipvaluelookups') || undefined;
3249                 var tooltipFormatFieldlist = self.data('sparkline-tooltipformatfieldlist') || undefined;
3250                 var tooltipFormatFieldlistKey = self.data('sparkline-tooltipformatfieldlistkey') || undefined;
3251                 var numberFormatter = self.data('sparkline-numberformatter') || function(n){ return n.toFixed(2); };
3252                 var numberDigitGroupSep = self.data('sparkline-numberdigitgroupsep') || undefined;
3253                 var numberDecimalMark = self.data('sparkline-numberdecimalmark') || undefined;
3254                 var numberDigitGroupCount = self.data('sparkline-numberdigitgroupcount') || undefined;
3255                 var animatedZooms = self.data('sparkline-animatedzooms') || false;
3256
3257                 state.sparkline_options = {
3258                         type: type,
3259                         lineColor: lineColor,
3260                         fillColor: fillColor,
3261                         chartRangeMin: chartRangeMin,
3262                         chartRangeMax: chartRangeMax,
3263                         composite: composite,
3264                         enableTagOptions: enableTagOptions,
3265                         tagOptionPrefix: tagOptionPrefix,
3266                         tagValuesAttribute: tagValuesAttribute,
3267                         disableHiddenCheck: disableHiddenCheck,
3268                         defaultPixelsPerValue: defaultPixelsPerValue,
3269                         spotColor: spotColor,
3270                         minSpotColor: minSpotColor,
3271                         maxSpotColor: maxSpotColor,
3272                         spotRadius: spotRadius,
3273                         valueSpots: valueSpots,
3274                         highlightSpotColor: highlightSpotColor,
3275                         highlightLineColor: highlightLineColor,
3276                         lineWidth: lineWidth,
3277                         normalRangeMin: normalRangeMin,
3278                         normalRangeMax: normalRangeMax,
3279                         drawNormalOnTop: drawNormalOnTop,
3280                         xvalues: xvalues,
3281                         chartRangeClip: chartRangeClip,
3282                         chartRangeMinX: chartRangeMinX,
3283                         chartRangeMaxX: chartRangeMaxX,
3284                         disableInteraction: disableInteraction,
3285                         disableTooltips: disableTooltips,
3286                         disableHighlight: disableHighlight,
3287                         highlightLighten: highlightLighten,
3288                         highlightColor: highlightColor,
3289                         tooltipContainer: tooltipContainer,
3290                         tooltipClassname: tooltipClassname,
3291                         tooltipChartTitle: state.title,
3292                         tooltipFormat: tooltipFormat,
3293                         tooltipPrefix: tooltipPrefix,
3294                         tooltipSuffix: tooltipSuffix,
3295                         tooltipSkipNull: tooltipSkipNull,
3296                         tooltipValueLookups: tooltipValueLookups,
3297                         tooltipFormatFieldlist: tooltipFormatFieldlist,
3298                         tooltipFormatFieldlistKey: tooltipFormatFieldlistKey,
3299                         numberFormatter: numberFormatter,
3300                         numberDigitGroupSep: numberDigitGroupSep,
3301                         numberDecimalMark: numberDecimalMark,
3302                         numberDigitGroupCount: numberDigitGroupCount,
3303                         animatedZooms: animatedZooms,
3304                         width: state.chartWidth(),
3305                         height: state.chartHeight()
3306                 };
3307
3308                 $(state.element_chart).sparkline(data.result, state.sparkline_options);
3309                 return true;
3310         };
3311
3312         // ----------------------------------------------------------------------------------------------------------------
3313         // dygraph
3314
3315         NETDATA.dygraph = {
3316                 smooth: false
3317         };
3318
3319         NETDATA.dygraphSetSelection = function(state, t) {
3320                 if(typeof state.dygraph_instance !== 'undefined') {
3321                         var r = state.calculateRowForTime(t);
3322                         if(r !== -1)
3323                                 state.dygraph_instance.setSelection(r);
3324                         else {
3325                                 state.dygraph_instance.clearSelection();
3326                                 state.legendShowUndefined();
3327                         }
3328                 }
3329
3330                 return true;
3331         };
3332
3333         NETDATA.dygraphClearSelection = function(state, t) {
3334                 if(typeof state.dygraph_instance !== 'undefined') {
3335                         state.dygraph_instance.clearSelection();
3336                 }
3337                 return true;
3338         };
3339
3340         NETDATA.dygraphSmoothInitialize = function(callback) {
3341                 $.ajax({
3342                         url: NETDATA.dygraph_smooth_js,
3343                         cache: true,
3344                         dataType: "script"
3345                 })
3346                 .done(function() {
3347                         NETDATA.dygraph.smooth = true;
3348                         smoothPlotter.smoothing = 0.3;
3349                 })
3350                 .fail(function() {
3351                         NETDATA.dygraph.smooth = false;
3352                 })
3353                 .always(function() {
3354                         if(typeof callback === "function")
3355                                 callback();
3356                 });
3357         }
3358
3359         NETDATA.dygraphInitialize = function(callback) {
3360                 if(typeof netdataNoDygraphs === 'undefined' || !netdataNoDygraphs) {
3361                         $.ajax({
3362                                 url: NETDATA.dygraph_js,
3363                                 cache: true,
3364                                 dataType: "script"
3365                         })
3366                         .done(function() {
3367                                 NETDATA.registerChartLibrary('dygraph', NETDATA.dygraph_js);
3368                         })
3369                         .fail(function() {
3370                                 NETDATA.chartLibraries.dygraph.enabled = false;
3371                                 NETDATA.error(100, NETDATA.dygraph_js);
3372                         })
3373                         .always(function() {
3374                                 if(NETDATA.chartLibraries.dygraph.enabled === true && NETDATA.options.current.smooth_plot === true)
3375                                         NETDATA.dygraphSmoothInitialize(callback);
3376                                 else if(typeof callback === "function")
3377                                         callback();
3378                         });
3379                 }
3380                 else {
3381                         NETDATA.chartLibraries.dygraph.enabled = false;
3382                         if(typeof callback === "function")
3383                                 callback();
3384                 }
3385         };
3386
3387         NETDATA.dygraphChartUpdate = function(state, data) {
3388                 var dygraph = state.dygraph_instance;
3389
3390                 if(typeof dygraph === 'undefined')
3391                         return NETDATA.dygraphChartCreate(state, data);
3392
3393                 // when the chart is not visible, and hidden
3394                 // if there is a window resize, dygraph detects
3395                 // its element size as 0x0.
3396                 // this will make it re-appear properly
3397
3398                 if(state.tm.last_unhidden > state.dygraph_last_rendered)
3399                         dygraph.resize();
3400
3401                 var options = {
3402                                 file: data.result.data,
3403                                 colors: state.chartColors(),
3404                                 labels: data.result.labels,
3405                                 labelsDivWidth: state.chartWidth() - 70,
3406                                 visibility: state.dimensions_visibility.selected2BooleanArray(state.data.dimension_names)
3407                 };
3408
3409                 if(state.dygraph_force_zoom === true) {
3410                         if(NETDATA.options.debug.dygraph === true || state.debug === true)
3411                                 state.log('dygraphChartUpdate() forced zoom update');
3412
3413                         options.dateWindow = (state.requested_padding !== null)?[ state.view_after, state.view_before ]:null;
3414                         options.valueRange = null;
3415                         options.isZoomedIgnoreProgrammaticZoom = true;
3416                         state.dygraph_force_zoom = false;
3417                 }
3418                 else if(state.current.name !== 'auto') {
3419                         if(NETDATA.options.debug.dygraph === true || state.debug === true)
3420                                 state.log('dygraphChartUpdate() loose update');
3421                 }
3422                 else {
3423                         if(NETDATA.options.debug.dygraph === true || state.debug === true)
3424                                 state.log('dygraphChartUpdate() strict update');
3425
3426                         options.dateWindow = (state.requested_padding !== null)?[ state.view_after, state.view_before ]:null;
3427                         options.valueRange = null;
3428                         options.isZoomedIgnoreProgrammaticZoom = true;
3429                 }
3430
3431                 if(state.dygraph_smooth_eligible === true) {
3432                         if((NETDATA.options.current.smooth_plot === true && state.dygraph_options.plotter !== smoothPlotter)
3433                                 || (NETDATA.options.current.smooth_plot === false && state.dygraph_options.plotter === smoothPlotter)) {
3434                                 NETDATA.dygraphChartCreate(state, data);
3435                                 return;
3436                         }
3437                 }
3438
3439                 dygraph.updateOptions(options);
3440
3441                 state.dygraph_last_rendered = new Date().getTime();
3442                 return true;
3443         };
3444
3445         NETDATA.dygraphChartCreate = function(state, data) {
3446                 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3447                         state.log('dygraphChartCreate()');
3448
3449                 var self = $(state.element);
3450
3451                 var chart_type = state.chart.chart_type;
3452                 if(chart_type === 'stacked' && data.dimensions === 1) chart_type = 'area';
3453                 chart_type = self.data('dygraph-type') || chart_type;
3454
3455                 var smooth = (chart_type === 'line' && !NETDATA.chartLibraries.dygraph.isSparkline(state))?true:false;
3456                 smooth = self.data('dygraph-smooth') || smooth;
3457
3458                 if(NETDATA.dygraph.smooth === false)
3459                         smooth = false;
3460
3461                 var strokeWidth = (chart_type === 'stacked')?0.1:((smooth)?1.5:0.7)
3462                 var highlightCircleSize = (NETDATA.chartLibraries.dygraph.isSparkline(state))?3:4;
3463
3464                 state.dygraph_options = {
3465                         colors: self.data('dygraph-colors') || state.chartColors(),
3466
3467                         // leave a few pixels empty on the right of the chart
3468                         rightGap: self.data('dygraph-rightgap') || 5,
3469                         showRangeSelector: self.data('dygraph-showrangeselector') || false,
3470                         showRoller: self.data('dygraph-showroller') || false,
3471
3472                         title: self.data('dygraph-title') || state.title,
3473                         titleHeight: self.data('dygraph-titleheight') || 19,
3474
3475                         legend: self.data('dygraph-legend') || 'always', // 'onmouseover',
3476                         labels: data.result.labels,
3477                         labelsDiv: self.data('dygraph-labelsdiv') || state.element_legend_childs.hidden,
3478                         labelsDivStyles: self.data('dygraph-labelsdivstyles') || { 'fontSize':'1px' },
3479                         labelsDivWidth: self.data('dygraph-labelsdivwidth') || state.chartWidth() - 70,
3480                         labelsSeparateLines: self.data('dygraph-labelsseparatelines') || true,
3481                         labelsShowZeroValues: self.data('dygraph-labelsshowzerovalues') || true,
3482                         labelsKMB: false,
3483                         labelsKMG2: false,
3484                         showLabelsOnHighlight: self.data('dygraph-showlabelsonhighlight') || true,
3485                         hideOverlayOnMouseOut: self.data('dygraph-hideoverlayonmouseout') || true,
3486
3487                         ylabel: state.units,
3488                         yLabelWidth: self.data('dygraph-ylabelwidth') || 12,
3489
3490                         // the function to plot the chart
3491                         plotter: null,
3492
3493                         // The width of the lines connecting data points. This can be used to increase the contrast or some graphs.
3494                         strokeWidth: self.data('dygraph-strokewidth') || strokeWidth,
3495                         strokePattern: self.data('dygraph-strokepattern') || undefined,
3496
3497                         // The size of the dot to draw on each point in pixels (see drawPoints). A dot is always drawn when a point is "isolated",
3498                         // i.e. there is a missing point on either side of it. This also controls the size of those dots.
3499                         drawPoints: self.data('dygraph-drawpoints') || false,
3500
3501                         // Draw points at the edges of gaps in the data. This improves visibility of small data segments or other data irregularities.
3502                         drawGapEdgePoints: self.data('dygraph-drawgapedgepoints') || true,
3503
3504                         connectSeparatedPoints: self.data('dygraph-connectseparatedpoints') || false,
3505                         pointSize: self.data('dygraph-pointsize') || 1,
3506
3507                         // enabling this makes the chart with little square lines
3508                         stepPlot: self.data('dygraph-stepplot') || false,
3509
3510                         // Draw a border around graph lines to make crossing lines more easily distinguishable. Useful for graphs with many lines.
3511                         strokeBorderColor: self.data('dygraph-strokebordercolor') || NETDATA.themes.current.background,
3512                         strokeBorderWidth: self.data('dygraph-strokeborderwidth') || (chart_type === 'stacked')?0.0:0.0,
3513
3514                         fillGraph: self.data('dygraph-fillgraph') || (chart_type === 'area' || chart_type === 'stacked')?true:false,
3515                         fillAlpha: self.data('dygraph-fillalpha') || (chart_type === 'stacked')?NETDATA.options.current.color_fill_opacity_stacked:NETDATA.options.current.color_fill_opacity_area,
3516                         stackedGraph: self.data('dygraph-stackedgraph') || (chart_type === 'stacked')?true:false,
3517                         stackedGraphNaNFill: self.data('dygraph-stackedgraphnanfill') || 'none',
3518
3519                         drawAxis: self.data('dygraph-drawaxis') || true,
3520                         axisLabelFontSize: self.data('dygraph-axislabelfontsize') || 10,
3521                         axisLineColor: self.data('dygraph-axislinecolor') || NETDATA.themes.current.axis,
3522                         axisLineWidth: self.data('dygraph-axislinewidth') || 0.3,
3523
3524                         drawGrid: self.data('dygraph-drawgrid') || true,
3525                         drawXGrid: self.data('dygraph-drawxgrid') || undefined,
3526                         drawYGrid: self.data('dygraph-drawygrid') || undefined,
3527                         gridLinePattern: self.data('dygraph-gridlinepattern') || null,
3528                         gridLineWidth: self.data('dygraph-gridlinewidth') || 0.3,
3529                         gridLineColor: self.data('dygraph-gridlinecolor') || NETDATA.themes.current.grid,
3530
3531                         maxNumberWidth: self.data('dygraph-maxnumberwidth') || 8,
3532                         sigFigs: self.data('dygraph-sigfigs') || null,
3533                         digitsAfterDecimal: self.data('dygraph-digitsafterdecimal') || 2,
3534                         valueFormatter: self.data('dygraph-valueformatter') || function(x){ return x.toFixed(2); },
3535
3536                         highlightCircleSize: self.data('dygraph-highlightcirclesize') || highlightCircleSize,
3537                         highlightSeriesOpts: self.data('dygraph-highlightseriesopts') || null, // TOO SLOW: { strokeWidth: 1.5 },
3538                         highlightSeriesBackgroundAlpha: self.data('dygraph-highlightseriesbackgroundalpha') || null, // TOO SLOW: (chart_type === 'stacked')?0.7:0.5,
3539
3540                         pointClickCallback: self.data('dygraph-pointclickcallback') || undefined,
3541                         visibility: state.dimensions_visibility.selected2BooleanArray(state.data.dimension_names),
3542                         axes: {
3543                                 x: {
3544                                         pixelsPerLabel: 50,
3545                                         ticker: Dygraph.dateTicker,
3546                                         axisLabelFormatter: function (d, gran) {
3547                                                 return NETDATA.zeropad(d.getHours()) + ":" + NETDATA.zeropad(d.getMinutes()) + ":" + NETDATA.zeropad(d.getSeconds());
3548                                         },
3549                                         valueFormatter: function (ms) {
3550                                                 var d = new Date(ms);
3551                                                 return d.toLocaleDateString() + ' ' + d.toLocaleTimeString();
3552                                                 // return NETDATA.zeropad(d.getHours()) + ":" + NETDATA.zeropad(d.getMinutes()) + ":" + NETDATA.zeropad(d.getSeconds());
3553                                         }
3554                                 },
3555                                 y: {
3556                                         pixelsPerLabel: 15,
3557                                         valueFormatter: function (x) {
3558                                                 // we format legends with the state object
3559                                                 // no need to do anything here
3560                                                 // return (Math.round(x*100) / 100).toLocaleString();
3561                                                 // return state.legendFormatValue(x);
3562                                                 return x;
3563                                         }
3564                                 }
3565                         },
3566                         legendFormatter: function(data) {
3567                                 var elements = state.element_legend_childs;
3568
3569                                 // if the hidden div is not there
3570                                 // we are not managing the legend
3571                                 if(elements.hidden === null) return;
3572
3573                                 if (typeof data.x !== 'undefined') {
3574                                         state.legendSetDate(data.x);
3575                                         var i = data.series.length;
3576                                         while(i--) {
3577                                                 var series = data.series[i];
3578                                                 if(!series.isVisible) continue;
3579                                                 state.legendSetLabelValue(series.label, series.y);
3580                                         }
3581                                 }
3582
3583                                 return '';
3584                         },
3585                         drawCallback: function(dygraph, is_initial) {
3586                                 if(state.current.name !== 'auto' && state.dygraph_user_action === true) {
3587                                         state.dygraph_user_action = false;
3588
3589                                         var x_range = dygraph.xAxisRange();
3590                                         var after = Math.round(x_range[0]);
3591                                         var before = Math.round(x_range[1]);
3592
3593                                         if(NETDATA.options.debug.dygraph === true)
3594                                                 state.log('dygraphDrawCallback(dygraph, ' + is_initial + '): ' + (after / 1000).toString() + ' - ' + (before / 1000).toString());
3595
3596                                         if(before <= state.netdata_last && after >= state.netdata_first)
3597                                                 state.updateChartPanOrZoom(after, before);
3598                                 }
3599                         },
3600                         zoomCallback: function(minDate, maxDate, yRanges) {
3601                                 if(NETDATA.options.debug.dygraph === true)
3602                                         state.log('dygraphZoomCallback()');
3603
3604                                 state.globalSelectionSyncStop();
3605                                 state.globalSelectionSyncDelay();
3606                                 state.setMode('zoom');
3607
3608                                 // refresh it to the greatest possible zoom level
3609                                 state.dygraph_user_action = true;
3610                                 state.dygraph_force_zoom = true;
3611                                 state.updateChartPanOrZoom(minDate, maxDate);
3612                         },
3613                         highlightCallback: function(event, x, points, row, seriesName) {
3614                                 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3615                                         state.log('dygraphHighlightCallback()');
3616
3617                                 state.pauseChart();
3618
3619                                 // there is a bug in dygraph when the chart is zoomed enough
3620                                 // the time it thinks is selected is wrong
3621                                 // here we calculate the time t based on the row number selected
3622                                 // which is ok
3623                                 var t = state.data_after + row * state.data_update_every;
3624                                 // console.log('row = ' + row + ', x = ' + x + ', t = ' + t + ' ' + ((t === x)?'SAME':(Math.abs(x-t)<=state.data_update_every)?'SIMILAR':'DIFFERENT') + ', rows in db: ' + state.data_points + ' visible(x) = ' + state.timeIsVisible(x) + ' visible(t) = ' + state.timeIsVisible(t) + ' r(x) = ' + state.calculateRowForTime(x) + ' r(t) = ' + state.calculateRowForTime(t) + ' range: ' + state.data_after + ' - ' + state.data_before + ' real: ' + state.data.after + ' - ' + state.data.before + ' every: ' + state.data_update_every);
3625
3626                                 state.globalSelectionSync(x);
3627
3628                                 // fix legend zIndex using the internal structures of dygraph legend module
3629                                 // this works, but it is a hack!
3630                                 // state.dygraph_instance.plugins_[0].plugin.legend_div_.style.zIndex = 10000;
3631                         },
3632                         unhighlightCallback: function(event) {
3633                                 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3634                                         state.log('dygraphUnhighlightCallback()');
3635
3636                                 state.unpauseChart();
3637                                 state.globalSelectionSyncStop();
3638                         },
3639                         interactionModel : {
3640                                 mousedown: function(event, dygraph, context) {
3641                                         if(NETDATA.options.debug.dygraph === true || state.debug === true)
3642                                                 state.log('interactionModel.mousedown()');
3643
3644                                         state.dygraph_user_action = true;
3645                                         state.globalSelectionSyncStop();
3646
3647                                         if(NETDATA.options.debug.dygraph === true)
3648                                                 state.log('dygraphMouseDown()');
3649
3650                                         // Right-click should not initiate a zoom.
3651                                         if(event.button && event.button === 2) return;
3652
3653                                         context.initializeMouseDown(event, dygraph, context);
3654
3655                                         if(event.button && event.button === 1) {
3656                                                 if (event.altKey || event.shiftKey) {
3657                                                         state.setMode('pan');
3658                                                         state.globalSelectionSyncDelay();
3659                                                         Dygraph.startPan(event, dygraph, context);
3660                                                 }
3661                                                 else {
3662                                                         state.setMode('zoom');
3663                                                         state.globalSelectionSyncDelay();
3664                                                         Dygraph.startZoom(event, dygraph, context);
3665                                                 }
3666                                         }
3667                                         else {
3668                                                 if (event.altKey || event.shiftKey) {
3669                                                         state.setMode('zoom');
3670                                                         state.globalSelectionSyncDelay();
3671                                                         Dygraph.startZoom(event, dygraph, context);
3672                                                 }
3673                                                 else {
3674                                                         state.setMode('pan');
3675                                                         state.globalSelectionSyncDelay();
3676                                                         Dygraph.startPan(event, dygraph, context);
3677                                                 }
3678                                         }
3679                                 },
3680                                 mousemove: function(event, dygraph, context) {
3681                                         if(NETDATA.options.debug.dygraph === true || state.debug === true)
3682                                                 state.log('interactionModel.mousemove()');
3683
3684                                         if(context.isPanning) {
3685                                                 state.dygraph_user_action = true;
3686                                                 state.globalSelectionSyncStop();
3687                                                 state.globalSelectionSyncDelay();
3688                                                 state.setMode('pan');
3689                                                 Dygraph.movePan(event, dygraph, context);
3690                                         }
3691                                         else if(context.isZooming) {
3692                                                 state.dygraph_user_action = true;
3693                                                 state.globalSelectionSyncStop();
3694                                                 state.globalSelectionSyncDelay();
3695                                                 state.setMode('zoom');
3696                                                 Dygraph.moveZoom(event, dygraph, context);
3697                                         }
3698                                 },
3699                                 mouseup: function(event, dygraph, context) {
3700                                         if(NETDATA.options.debug.dygraph === true || state.debug === true)
3701                                                 state.log('interactionModel.mouseup()');
3702
3703                                         if (context.isPanning) {
3704                                                 state.dygraph_user_action = true;
3705                                                 state.globalSelectionSyncDelay();
3706                                                 Dygraph.endPan(event, dygraph, context);
3707                                         }
3708                                         else if (context.isZooming) {
3709                                                 state.dygraph_user_action = true;
3710                                                 state.globalSelectionSyncDelay();
3711                                                 Dygraph.endZoom(event, dygraph, context);
3712                                         }
3713                                 },
3714                                 click: function(event, dygraph, context) {
3715                                         if(NETDATA.options.debug.dygraph === true || state.debug === true)
3716                                                 state.log('interactionModel.click()');
3717
3718                                         event.preventDefault();
3719                                 },
3720                                 dblclick: function(event, dygraph, context) {
3721                                         if(NETDATA.options.debug.dygraph === true || state.debug === true)
3722                                                 state.log('interactionModel.dblclick()');
3723                                         NETDATA.resetAllCharts(state);
3724                                 },
3725                                 mousewheel: function(event, dygraph, context) {
3726                                         if(NETDATA.options.debug.dygraph === true || state.debug === true)
3727                                                 state.log('interactionModel.mousewheel()');
3728
3729                                         // Take the offset of a mouse event on the dygraph canvas and
3730                                         // convert it to a pair of percentages from the bottom left. 
3731                                         // (Not top left, bottom is where the lower value is.)
3732                                         function offsetToPercentage(g, offsetX, offsetY) {
3733                                                 // This is calculating the pixel offset of the leftmost date.
3734                                                 var xOffset = g.toDomCoords(g.xAxisRange()[0], null)[0];
3735                                                 var yar0 = g.yAxisRange(0);
3736
3737                                                 // This is calculating the pixel of the higest value. (Top pixel)
3738                                                 var yOffset = g.toDomCoords(null, yar0[1])[1];
3739
3740                                                 // x y w and h are relative to the corner of the drawing area,
3741                                                 // so that the upper corner of the drawing area is (0, 0).
3742                                                 var x = offsetX - xOffset;
3743                                                 var y = offsetY - yOffset;
3744
3745                                                 // This is computing the rightmost pixel, effectively defining the
3746                                                 // width.
3747                                                 var w = g.toDomCoords(g.xAxisRange()[1], null)[0] - xOffset;
3748
3749                                                 // This is computing the lowest pixel, effectively defining the height.
3750                                                 var h = g.toDomCoords(null, yar0[0])[1] - yOffset;
3751
3752                                                 // Percentage from the left.
3753                                                 var xPct = w === 0 ? 0 : (x / w);
3754                                                 // Percentage from the top.
3755                                                 var yPct = h === 0 ? 0 : (y / h);
3756
3757                                                 // The (1-) part below changes it from "% distance down from the top"
3758                                                 // to "% distance up from the bottom".
3759                                                 return [xPct, (1-yPct)];
3760                                         }
3761
3762                                         // Adjusts [x, y] toward each other by zoomInPercentage%
3763                                         // Split it so the left/bottom axis gets xBias/yBias of that change and
3764                                         // tight/top gets (1-xBias)/(1-yBias) of that change.
3765                                         //
3766                                         // If a bias is missing it splits it down the middle.
3767                                         function zoomRange(g, zoomInPercentage, xBias, yBias) {
3768                                                 xBias = xBias || 0.5;
3769                                                 yBias = yBias || 0.5;
3770
3771                                                 function adjustAxis(axis, zoomInPercentage, bias) {
3772                                                         var delta = axis[1] - axis[0];
3773                                                         var increment = delta * zoomInPercentage;
3774                                                         var foo = [increment * bias, increment * (1-bias)];
3775
3776                                                         return [ axis[0] + foo[0], axis[1] - foo[1] ];
3777                                                 }
3778
3779                                                 var yAxes = g.yAxisRanges();
3780                                                 var newYAxes = [];
3781                                                 for (var i = 0; i < yAxes.length; i++) {
3782                                                         newYAxes[i] = adjustAxis(yAxes[i], zoomInPercentage, yBias);
3783                                                 }
3784
3785                                                 return adjustAxis(g.xAxisRange(), zoomInPercentage, xBias);
3786                                         }
3787
3788                                         if(event.altKey || event.shiftKey) {
3789                                                 state.dygraph_user_action = true;
3790
3791                                                 state.globalSelectionSyncStop();
3792                                                 state.globalSelectionSyncDelay();
3793
3794                                                 // http://dygraphs.com/gallery/interaction-api.js
3795                                                 var normal = (event.detail) ? event.detail * -1 : event.wheelDelta / 40;
3796                                                 var percentage = normal / 50;
3797
3798                                                 if (!(event.offsetX && event.offsetY)){
3799                                                         event.offsetX = event.layerX - event.target.offsetLeft;
3800                                                         event.offsetY = event.layerY - event.target.offsetTop;
3801                                                 }
3802
3803                                                 var percentages = offsetToPercentage(dygraph, event.offsetX, event.offsetY);
3804                                                 var xPct = percentages[0];
3805                                                 var yPct = percentages[1];
3806
3807                                                 var new_x_range = zoomRange(dygraph, percentage, xPct, yPct);
3808
3809                                                 var after = new_x_range[0];
3810                                                 var before = new_x_range[1];
3811
3812                                                 var first = state.netdata_first + state.data_update_every;
3813                                                 var last = state.netdata_last + state.data_update_every;
3814
3815                                                 if(before > last) {
3816                                                         after -= (before - last);
3817                                                         before = last;
3818                                                 }
3819                                                 if(after < first) {
3820                                                         after = first;
3821                                                 }
3822
3823                                                 state.setMode('zoom');
3824                                                 if(state.updateChartPanOrZoom(after, before) === true)
3825                                                         dygraph.updateOptions({ dateWindow: [ after, before ] });
3826
3827                                                 event.preventDefault();
3828                                         }
3829                                 },
3830                                 touchstart: function(event, dygraph, context) {
3831                                         if(NETDATA.options.debug.dygraph === true || state.debug === true)
3832                                                 state.log('interactionModel.touchstart()');
3833
3834                                         state.dygraph_user_action = true;
3835                                         state.setMode('zoom');
3836                                         state.pauseChart();
3837
3838                                         Dygraph.defaultInteractionModel.touchstart(event, dygraph, context);
3839
3840                                         // we overwrite the touch directions at the end, to overwrite
3841                                         // the internal default of dygraphs
3842                                         context.touchDirections = { x: true, y: false };
3843
3844                                         state.dygraph_last_touch_start = new Date().getTime();
3845                                         state.dygraph_last_touch_move = 0;
3846
3847                                         if(typeof event.touches[0].pageX === 'number')
3848                                                 state.dygraph_last_touch_page_x = event.touches[0].pageX;
3849                                         else
3850                                                 state.dygraph_last_touch_page_x = 0;
3851                                 },
3852                                 touchmove: function(event, dygraph, context) {
3853                                         if(NETDATA.options.debug.dygraph === true || state.debug === true)
3854                                                 state.log('interactionModel.touchmove()');
3855
3856                                         state.dygraph_user_action = true;
3857                                         Dygraph.defaultInteractionModel.touchmove(event, dygraph, context);
3858
3859                                         state.dygraph_last_touch_move = new Date().getTime();
3860                                 },
3861                                 touchend: function(event, dygraph, context) {
3862                                         if(NETDATA.options.debug.dygraph === true || state.debug === true)
3863                                                 state.log('interactionModel.touchend()');
3864
3865                                         state.dygraph_user_action = true;
3866                                         Dygraph.defaultInteractionModel.touchend(event, dygraph, context);
3867
3868                                         // if it didn't move, it is a selection
3869                                         if(state.dygraph_last_touch_move === 0 && state.dygraph_last_touch_page_x !== 0) {
3870                                                 // internal api of dygraphs
3871                                                 var pct = (state.dygraph_last_touch_page_x - (dygraph.plotter_.area.x + state.element.getBoundingClientRect().left)) / dygraph.plotter_.area.w;
3872                                                 var t = Math.round(state.data_after + (state.data_before - state.data_after) * pct);
3873                                                 if(NETDATA.dygraphSetSelection(state, t) === true)
3874                                                         state.globalSelectionSync(t);
3875                                         }
3876
3877                                         // if it was double tap within double click time, reset the charts
3878                                         var now = new Date().getTime();
3879                                         if(typeof state.dygraph_last_touch_end !== 'undefined') {
3880                                                 if(state.dygraph_last_touch_move === 0) {
3881                                                         var dt = now - state.dygraph_last_touch_end;
3882                                                         if(dt <= NETDATA.options.current.double_click_speed)
3883                                                                 NETDATA.resetAllCharts(state);
3884                                                 }
3885                                         }
3886
3887                                         // remember the timestamp of the last touch end
3888                                         state.dygraph_last_touch_end = now;
3889                                 }
3890                         }
3891                 };
3892
3893                 if(NETDATA.chartLibraries.dygraph.isSparkline(state)) {
3894                         state.dygraph_options.drawGrid = false;
3895                         state.dygraph_options.drawAxis = false;
3896                         state.dygraph_options.title = undefined;
3897                         state.dygraph_options.units = undefined;
3898                         state.dygraph_options.ylabel = undefined;
3899                         state.dygraph_options.yLabelWidth = 0;
3900                         state.dygraph_options.labelsDivWidth = 120;
3901                         state.dygraph_options.labelsDivStyles.width = '120px';
3902                         state.dygraph_options.labelsSeparateLines = true;
3903                         state.dygraph_options.rightGap = 0;
3904                 }
3905
3906                 if(smooth === true) {
3907                         state.dygraph_smooth_eligible = true;
3908
3909                         if(NETDATA.options.current.smooth_plot === true)
3910                                 state.dygraph_options.plotter = smoothPlotter;
3911                 }
3912                 else state.dygraph_smooth_eligible = false;
3913
3914                 state.dygraph_instance = new Dygraph(state.element_chart,
3915                         data.result.data, state.dygraph_options);
3916
3917                 state.dygraph_force_zoom = false;
3918                 state.dygraph_user_action = false;
3919                 state.dygraph_last_rendered = new Date().getTime();
3920                 return true;
3921         };
3922
3923         // ----------------------------------------------------------------------------------------------------------------
3924         // morris
3925
3926         NETDATA.morrisInitialize = function(callback) {
3927                 if(typeof netdataNoMorris === 'undefined' || !netdataNoMorris) {
3928
3929                         // morris requires raphael
3930                         if(!NETDATA.chartLibraries.raphael.initialized) {
3931                                 if(NETDATA.chartLibraries.raphael.enabled) {
3932                                         NETDATA.raphaelInitialize(function() {
3933                                                 NETDATA.morrisInitialize(callback);
3934                                         });
3935                                 }
3936                                 else {
3937                                         NETDATA.chartLibraries.morris.enabled = false;
3938                                         if(typeof callback === "function")
3939                                                 callback();
3940                                 }
3941                         }
3942                         else {
3943                                 NETDATA._loadCSS(NETDATA.morris_css);
3944
3945                                 $.ajax({
3946                                         url: NETDATA.morris_js,
3947                                         cache: true,
3948                                         dataType: "script"
3949                                 })
3950                                 .done(function() {
3951                                         NETDATA.registerChartLibrary('morris', NETDATA.morris_js);
3952                                 })
3953                                 .fail(function() {
3954                                         NETDATA.chartLibraries.morris.enabled = false;
3955                                         NETDATA.error(100, NETDATA.morris_js);
3956                                 })
3957                                 .always(function() {
3958                                         if(typeof callback === "function")
3959                                                 callback();
3960                                 });
3961                         }
3962                 }
3963                 else {
3964                         NETDATA.chartLibraries.morris.enabled = false;
3965                         if(typeof callback === "function")
3966                                 callback();
3967                 }
3968         };
3969
3970         NETDATA.morrisChartUpdate = function(state, data) {
3971                 state.morris_instance.setData(data.result.data);
3972                 return true;
3973         };
3974
3975         NETDATA.morrisChartCreate = function(state, data) {
3976
3977                 state.morris_options = {
3978                                 element: state.element_chart.id,
3979                                 data: data.result.data,
3980                                 xkey: 'time',
3981                                 ykeys: data.dimension_names,
3982                                 labels: data.dimension_names,
3983                                 lineWidth: 2,
3984                                 pointSize: 3,
3985                                 smooth: true,
3986                                 hideHover: 'auto',
3987                                 parseTime: true,
3988                                 continuousLine: false,
3989                                 behaveLikeLine: false
3990                 };
3991
3992                 if(state.chart.chart_type === 'line')
3993                         state.morris_instance = new Morris.Line(state.morris_options);
3994
3995                 else if(state.chart.chart_type === 'area') {
3996                         state.morris_options.behaveLikeLine = true;
3997                         state.morris_instance = new Morris.Area(state.morris_options);
3998                 }
3999                 else // stacked
4000                         state.morris_instance = new Morris.Area(state.morris_options);
4001                 
4002                 return true;
4003         };
4004
4005         // ----------------------------------------------------------------------------------------------------------------
4006         // raphael
4007
4008         NETDATA.raphaelInitialize = function(callback) {
4009                 if(typeof netdataStopRaphael === 'undefined' || !netdataStopRaphael) {
4010                         $.ajax({
4011                                 url: NETDATA.raphael_js,
4012                                 cache: true,
4013                                 dataType: "script"
4014                         })
4015                         .done(function() {
4016                                 NETDATA.registerChartLibrary('raphael', NETDATA.raphael_js);
4017                         })
4018                         .fail(function() {
4019                                 NETDATA.chartLibraries.raphael.enabled = false;
4020                                 NETDATA.error(100, NETDATA.raphael_js);
4021                         })
4022                         .always(function() {
4023                                 if(typeof callback === "function")
4024                                         callback();
4025                         });
4026                 }
4027                 else {
4028                         NETDATA.chartLibraries.raphael.enabled = false;
4029                         if(typeof callback === "function")
4030                                 callback();
4031                 }
4032         };
4033
4034         NETDATA.raphaelChartUpdate = function(state, data) {
4035                 $(state.element_chart).raphael(data.result, {
4036                         width: state.chartWidth(),
4037                         height: state.chartHeight()
4038                 });
4039
4040                 return false;
4041         };
4042
4043         NETDATA.raphaelChartCreate = function(state, data) {
4044                 $(state.element_chart).raphael(data.result, {
4045                         width: state.chartWidth(),
4046                         height: state.chartHeight()
4047                 });
4048
4049                 return false;
4050         };
4051
4052         // ----------------------------------------------------------------------------------------------------------------
4053         // C3
4054
4055         NETDATA.c3Initialize = function(callback) {
4056                 if(typeof netdataNoC3 === 'undefined' || !netdataNoC3) {
4057
4058                         // C3 requires D3
4059                         if(!NETDATA.chartLibraries.d3.initialized) {
4060                                 if(NETDATA.chartLibraries.d3.enabled) {
4061                                         NETDATA.d3Initialize(function() {
4062                                                 NETDATA.c3Initialize(callback);
4063                                         });
4064                                 }
4065                                 else {
4066                                         NETDATA.chartLibraries.c3.enabled = false;
4067                                         if(typeof callback === "function")
4068                                                 callback();
4069                                 }
4070                         }
4071                         else {
4072                                 NETDATA._loadCSS(NETDATA.c3_css);
4073
4074                                 $.ajax({
4075                                         url: NETDATA.c3_js,
4076                                         cache: true,
4077                                         dataType: "script"
4078                                 })
4079                                 .done(function() {
4080                                         NETDATA.registerChartLibrary('c3', NETDATA.c3_js);
4081                                 })
4082                                 .fail(function() {
4083                                         NETDATA.chartLibraries.c3.enabled = false;
4084                                         NETDATA.error(100, NETDATA.c3_js);
4085                                 })
4086                                 .always(function() {
4087                                         if(typeof callback === "function")
4088                                                 callback();
4089                                 });
4090                         }
4091                 }
4092                 else {
4093                         NETDATA.chartLibraries.c3.enabled = false;
4094                         if(typeof callback === "function")
4095                                 callback();
4096                 }
4097         };
4098
4099         NETDATA.c3ChartUpdate = function(state, data) {
4100                 state.c3_instance.destroy();
4101                 return NETDATA.c3ChartCreate(state, data);
4102
4103                 //state.c3_instance.load({
4104                 //      rows: data.result,
4105                 //      unload: true
4106                 //});
4107
4108                 //return true;
4109         };
4110
4111         NETDATA.c3ChartCreate = function(state, data) {
4112
4113                 state.element_chart.id = 'c3-' + state.uuid;
4114                 // console.log('id = ' + state.element_chart.id);
4115
4116                 state.c3_instance = c3.generate({
4117                         bindto: '#' + state.element_chart.id,
4118                         size: {
4119                                 width: state.chartWidth(),
4120                                 height: state.chartHeight()
4121                         },
4122                         color: {
4123                                 pattern: state.chartColors()
4124                         },
4125                         data: {
4126                                 x: 'time',
4127                                 rows: data.result,
4128                                 type: (state.chart.chart_type === 'line')?'spline':'area-spline'
4129                         },
4130                         axis: {
4131                                 x: {
4132                                         type: 'timeseries',
4133                                         tick: {
4134                                                 format: function(x) {
4135                                                         return NETDATA.zeropad(x.getHours()) + ":" + NETDATA.zeropad(x.getMinutes()) + ":" + NETDATA.zeropad(x.getSeconds());
4136                                                 }
4137                                         }
4138                                 }
4139                         },
4140                         grid: {
4141                                 x: {
4142                                         show: true
4143                                 },
4144                                 y: {
4145                                         show: true
4146                                 }
4147                         },
4148                         point: {
4149                                 show: false
4150                         },
4151                         line: {
4152                                 connectNull: false
4153                         },
4154                         transition: {
4155                                 duration: 0
4156                         },
4157                         interaction: {
4158                                 enabled: true
4159                         }
4160                 });
4161
4162                 // console.log(state.c3_instance);
4163
4164                 return true;
4165         };
4166
4167         // ----------------------------------------------------------------------------------------------------------------
4168         // D3
4169
4170         NETDATA.d3Initialize = function(callback) {
4171                 if(typeof netdataStopD3 === 'undefined' || !netdataStopD3) {
4172                         $.ajax({
4173                                 url: NETDATA.d3_js,
4174                                 cache: true,
4175                                 dataType: "script"
4176                         })
4177                         .done(function() {
4178                                 NETDATA.registerChartLibrary('d3', NETDATA.d3_js);
4179                         })
4180                         .fail(function() {
4181                                 NETDATA.chartLibraries.d3.enabled = false;
4182                                 NETDATA.error(100, NETDATA.d3_js);
4183                         })
4184                         .always(function() {
4185                                 if(typeof callback === "function")
4186                                         callback();
4187                         });
4188                 }
4189                 else {
4190                         NETDATA.chartLibraries.d3.enabled = false;
4191                         if(typeof callback === "function")
4192                                 callback();
4193                 }
4194         };
4195
4196         NETDATA.d3ChartUpdate = function(state, data) {
4197                 return false;
4198         };
4199
4200         NETDATA.d3ChartCreate = function(state, data) {
4201                 return false;
4202         };
4203
4204         // ----------------------------------------------------------------------------------------------------------------
4205         // google charts
4206
4207         NETDATA.googleInitialize = function(callback) {
4208                 if(typeof netdataNoGoogleCharts === 'undefined' || !netdataNoGoogleCharts) {
4209                         $.ajax({
4210                                 url: NETDATA.google_js,
4211                                 cache: true,
4212                                 dataType: "script"
4213                         })
4214                         .done(function() {
4215                                 NETDATA.registerChartLibrary('google', NETDATA.google_js);
4216                                 google.load('visualization', '1.1', {
4217                                         'packages': ['corechart', 'controls'],
4218                                         'callback': callback
4219                                 });
4220                         })
4221                         .fail(function() {
4222                                 NETDATA.chartLibraries.google.enabled = false;
4223                                 NETDATA.error(100, NETDATA.google_js);
4224                                 if(typeof callback === "function")
4225                                         callback();
4226                         });
4227                 }
4228                 else {
4229                         NETDATA.chartLibraries.google.enabled = false;
4230                         if(typeof callback === "function")
4231                                 callback();
4232                 }
4233         };
4234
4235         NETDATA.googleChartUpdate = function(state, data) {
4236                 var datatable = new google.visualization.DataTable(data.result);
4237                 state.google_instance.draw(datatable, state.google_options);
4238                 return true;
4239         };
4240
4241         NETDATA.googleChartCreate = function(state, data) {
4242                 var datatable = new google.visualization.DataTable(data.result);
4243
4244                 state.google_options = {
4245                         colors: state.chartColors(),
4246
4247                         // do not set width, height - the chart resizes itself
4248                         //width: state.chartWidth(),
4249                         //height: state.chartHeight(),
4250                         lineWidth: 1,
4251                         title: state.title,
4252                         fontSize: 11,
4253                         hAxis: {
4254                         //      title: "Time of Day",
4255                         //      format:'HH:mm:ss',
4256                                 viewWindowMode: 'maximized',
4257                                 slantedText: false,
4258                                 format:'HH:mm:ss',
4259                                 textStyle: {
4260                                         fontSize: 9
4261                                 },
4262                                 gridlines: {
4263                                         color: '#EEE'
4264                                 }
4265                         },
4266                         vAxis: {
4267                                 title: state.units,
4268                                 viewWindowMode: 'pretty',
4269                                 minValue: -0.1,
4270                                 maxValue: 0.1,
4271                                 direction: 1,
4272                                 textStyle: {
4273                                         fontSize: 9
4274                                 },
4275                                 gridlines: {
4276                                         color: '#EEE'
4277                                 }
4278                         },
4279                         chartArea: {
4280                                 width: '65%',
4281                                 height: '80%'
4282                         },
4283                         focusTarget: 'category',
4284                         annotation: {
4285                                 '1': {
4286                                         style: 'line'
4287                                 }
4288                         },
4289                         pointsVisible: 0,
4290                         titlePosition: 'out',
4291                         titleTextStyle: {
4292                                 fontSize: 11
4293                         },
4294                         tooltip: {
4295                                 isHtml: false,
4296                                 ignoreBounds: true,
4297                                 textStyle: {
4298                                         fontSize: 9
4299                                 }
4300                         },
4301                         curveType: 'function',
4302                         areaOpacity: 0.3,
4303                         isStacked: false
4304                 };
4305
4306                 switch(state.chart.chart_type) {
4307                         case "area":
4308                                 state.google_options.vAxis.viewWindowMode = 'maximized';
4309                                 state.google_options.areaOpacity = NETDATA.options.current.color_fill_opacity_area;
4310                                 state.google_instance = new google.visualization.AreaChart(state.element_chart);
4311                                 break;
4312
4313                         case "stacked":
4314                                 state.google_options.isStacked = true;
4315                                 state.google_options.areaOpacity = NETDATA.options.current.color_fill_opacity_stacked;
4316                                 state.google_options.vAxis.viewWindowMode = 'maximized';
4317                                 state.google_options.vAxis.minValue = null;
4318                                 state.google_options.vAxis.maxValue = null;
4319                                 state.google_instance = new google.visualization.AreaChart(state.element_chart);
4320                                 break;
4321
4322                         default:
4323                         case "line":
4324                                 state.google_options.lineWidth = 2;
4325                                 state.google_instance = new google.visualization.LineChart(state.element_chart);
4326                                 break;
4327                 }
4328
4329                 state.google_instance.draw(datatable, state.google_options);
4330                 return true;
4331         };
4332
4333         // ----------------------------------------------------------------------------------------------------------------
4334
4335         NETDATA.percentFromValueMax = function(value, max) {
4336                 if(value === null) value = 0;
4337                 if(max < value) max = value;
4338                 
4339                 var pcent = 0;
4340                 if(max !== 0) {
4341                         pcent = Math.round(value * 100 / max);
4342                         if(pcent === 0 && value > 0) pcent = 1;
4343                 }
4344
4345                 return pcent;
4346         }
4347
4348         // ----------------------------------------------------------------------------------------------------------------
4349         // easy-pie-chart
4350
4351         NETDATA.easypiechartInitialize = function(callback) {
4352                 if(typeof netdataNoEasyPieChart === 'undefined' || !netdataNoEasyPieChart) {
4353                         $.ajax({
4354                                 url: NETDATA.easypiechart_js,
4355                                 cache: true,
4356                                 dataType: "script"
4357                         })
4358                                 .done(function() {
4359                                         NETDATA.registerChartLibrary('easypiechart', NETDATA.easypiechart_js);
4360                                 })
4361                                 .fail(function() {
4362                                         NETDATA.chartLibraries.easypiechart.enabled = false;
4363                                         NETDATA.error(100, NETDATA.easypiechart_js);
4364                                 })
4365                                 .always(function() {
4366                                         if(typeof callback === "function")
4367                                                 callback();
4368                                 })
4369                 }
4370                 else {
4371                         NETDATA.chartLibraries.easypiechart.enabled = false;
4372                         if(typeof callback === "function")
4373                                 callback();
4374                 }
4375         };
4376
4377         NETDATA.easypiechartClearSelection = function(state) {
4378                 if(typeof state.easyPieChartEvent !== 'undefined') {
4379                         if(state.easyPieChartEvent.timer !== null)
4380                                 clearTimeout(state.easyPieChartEvent.timer);
4381
4382                         state.easyPieChartEvent.timer = null;
4383                 }
4384
4385                 if(state.isAutoRefreshed() === true && state.data !== null) {
4386                         NETDATA.easypiechartChartUpdate(state, state.data);
4387                 }
4388                 else {
4389                         state.easyPieChartLabel.innerHTML = state.legendFormatValue(null);
4390                         state.easyPieChart_instance.update(0);
4391                 }
4392                 state.easyPieChart_instance.enableAnimation();
4393
4394                 return true;
4395         };
4396
4397         NETDATA.easypiechartSetSelection = function(state, t) {
4398                 if(state.timeIsVisible(t) !== true)
4399                         return NETDATA.easypiechartClearSelection(state);
4400
4401                 var slot = state.calculateRowForTime(t);
4402                 if(slot < 0 || slot >= state.data.result.length)
4403                         return NETDATA.easypiechartClearSelection(state);
4404
4405                 if(typeof state.easyPieChartEvent === 'undefined') {
4406                         state.easyPieChartEvent = {
4407                                 timer: null,
4408                                 value: 0,
4409                                 pcent: 0,
4410                         };
4411                 }
4412
4413                 var value = state.data.result[state.data.result.length - 1 - slot];
4414                 var max = (state.easyPieChartMax === null)?state.data.max:state.easyPieChartMax;
4415                 var pcent = NETDATA.percentFromValueMax(value, max);
4416
4417                 state.easyPieChartEvent.value = value;
4418                 state.easyPieChartEvent.pcent = pcent;
4419                 state.easyPieChartLabel.innerHTML = state.legendFormatValue(value);
4420
4421                 if(state.easyPieChartEvent.timer === null) {
4422                         state.easyPieChart_instance.disableAnimation();
4423
4424                         state.easyPieChartEvent.timer = setTimeout(function() {
4425                                 state.easyPieChartEvent.timer = null;
4426                                 state.easyPieChart_instance.update(state.easyPieChartEvent.pcent);
4427                         }, NETDATA.options.current.charts_selection_animation_delay);
4428                 }
4429
4430                 return true;
4431         };
4432
4433         NETDATA.easypiechartChartUpdate = function(state, data) {
4434                 var value, max, pcent;
4435
4436                 if(NETDATA.globalPanAndZoom.isActive() === true || state.isAutoRefreshed() === false) {
4437                         value = null;
4438                         max = 0;
4439                         pcent = 0;
4440                 }
4441                 else {
4442                         value = data.result[0];
4443                         max = (state.easyPieChartMax === null)?data.max:state.easyPieChartMax;
4444                         pcent = NETDATA.percentFromValueMax(value, max);
4445                 }
4446
4447                 state.easyPieChartLabel.innerHTML = state.legendFormatValue(value);
4448                 state.easyPieChart_instance.update(pcent);
4449                 return true;
4450         };
4451
4452         NETDATA.easypiechartChartCreate = function(state, data) {
4453                 var self = $(state.element);
4454                 var chart = $(state.element_chart);
4455
4456                 var value = data.result[0];
4457                 var max = self.data('easypiechart-max-value') || null;
4458                 var adjust = self.data('easypiechart-adjust') || null;
4459                 
4460                 if(max === null) {
4461                         max = data.max;
4462                         state.easyPieChartMax = null;
4463                 }
4464                 else
4465                         state.easyPieChartMax = max;
4466
4467                 var pcent = NETDATA.percentFromValueMax(value, max);
4468
4469                 chart.data('data-percent', pcent);
4470
4471                 var size;
4472                 switch(adjust) {
4473                         case 'width': size = state.chartHeight(); break;
4474                         case 'min': size = Math.min(state.chartWidth(), state.chartHeight()); break;
4475                         case 'max': size = Math.max(state.chartWidth(), state.chartHeight()); break;
4476                         case 'height':
4477                         default: size = state.chartWidth(); break;
4478                 }
4479                 state.element.style.width = size + 'px';
4480                 state.element.style.height = size + 'px';
4481
4482                 var stroke = Math.floor(size / 22);
4483                 if(stroke < 3) stroke = 2;
4484
4485                 var valuefontsize = Math.floor((size * 2 / 3) / 5);
4486                 var valuetop = Math.round((size - valuefontsize - (size / 40)) / 2);
4487                 state.easyPieChartLabel = document.createElement('span');
4488                 state.easyPieChartLabel.className = 'easyPieChartLabel';
4489                 state.easyPieChartLabel.innerHTML = state.legendFormatValue(value);
4490                 state.easyPieChartLabel.style.fontSize = valuefontsize + 'px';
4491                 state.easyPieChartLabel.style.top = valuetop.toString() + 'px';
4492                 state.element_chart.appendChild(state.easyPieChartLabel);
4493
4494                 var titlefontsize = Math.round(valuefontsize * 1.6 / 3);
4495                 var titletop = Math.round(valuetop - (titlefontsize * 2) - (size / 40));
4496                 state.easyPieChartTitle = document.createElement('span');
4497                 state.easyPieChartTitle.className = 'easyPieChartTitle';
4498                 state.easyPieChartTitle.innerHTML = state.title;
4499                 state.easyPieChartTitle.style.fontSize = titlefontsize + 'px';
4500                 state.easyPieChartTitle.style.lineHeight = titlefontsize + 'px';
4501                 state.easyPieChartTitle.style.top = titletop.toString() + 'px';
4502                 state.element_chart.appendChild(state.easyPieChartTitle);
4503
4504                 var unitfontsize = Math.round(titlefontsize * 0.9);
4505                 var unittop = Math.round(valuetop + (valuefontsize + unitfontsize) + (size / 40));
4506                 state.easyPieChartUnits = document.createElement('span');
4507                 state.easyPieChartUnits.className = 'easyPieChartUnits';
4508                 state.easyPieChartUnits.innerHTML = state.units;
4509                 state.easyPieChartUnits.style.fontSize = unitfontsize + 'px';
4510                 state.easyPieChartUnits.style.top = unittop.toString() + 'px';
4511                 state.element_chart.appendChild(state.easyPieChartUnits);
4512
4513                 chart.easyPieChart({
4514                         barColor: self.data('easypiechart-barcolor') || state.chartColors()[0], //'#ef1e25',
4515                         trackColor: self.data('easypiechart-trackcolor') || NETDATA.themes.current.easypiechart_track,
4516                         scaleColor: self.data('easypiechart-scalecolor') || NETDATA.themes.current.easypiechart_scale,
4517                         scaleLength: self.data('easypiechart-scalelength') || 5,
4518                         lineCap: self.data('easypiechart-linecap') || 'round',
4519                         lineWidth: self.data('easypiechart-linewidth') || stroke,
4520                         trackWidth: self.data('easypiechart-trackwidth') || undefined,
4521                         size: self.data('easypiechart-size') || size,
4522                         rotate: self.data('easypiechart-rotate') || 0,
4523                         animate: self.data('easypiechart-rotate') || {duration: 500, enabled: true},
4524                         easing: self.data('easypiechart-easing') || undefined
4525                 });
4526                 
4527                 // when we just re-create the chart
4528                 // do not animate the first update
4529                 var animate = true;
4530                 if(typeof state.easyPieChart_instance !== 'undefined')
4531                         animate = false;
4532
4533                 state.easyPieChart_instance = chart.data('easyPieChart');
4534                 if(animate === false) state.easyPieChart_instance.disableAnimation();
4535                 state.easyPieChart_instance.update(pcent);
4536                 if(animate === false) state.easyPieChart_instance.enableAnimation();
4537                 return true;
4538         };
4539
4540         // ----------------------------------------------------------------------------------------------------------------
4541         // gauge.js
4542
4543         NETDATA.gaugeInitialize = function(callback) {
4544                 if(typeof netdataNoGauge === 'undefined' || !netdataNoGauge) {
4545                         $.ajax({
4546                                 url: NETDATA.gauge_js,
4547                                 cache: true,
4548                                 dataType: "script"
4549                         })
4550                                 .done(function() {
4551                                         NETDATA.registerChartLibrary('gauge', NETDATA.gauge_js);
4552                                 })
4553                                 .fail(function() {
4554                                         NETDATA.chartLibraries.gauge.enabled = false;
4555                                         NETDATA.error(100, NETDATA.gauge_js);
4556                                 })
4557                                 .always(function() {
4558                                         if(typeof callback === "function")
4559                                                 callback();
4560                                 })
4561                 }
4562                 else {
4563                         NETDATA.chartLibraries.gauge.enabled = false;
4564                         if(typeof callback === "function")
4565                                 callback();
4566                 }
4567         };
4568
4569         NETDATA.gaugeAnimation = function(state, status) {
4570                 var speed = 32;
4571
4572                 if(typeof status === 'boolean' && status === false)
4573                         speed = 1000000000;
4574                 else if(typeof status === 'number')
4575                         speed = status;
4576                 
4577                 state.gauge_instance.animationSpeed = speed;
4578                 state.___gaugeOld__.speed = speed;
4579         }
4580
4581         NETDATA.gaugeSet = function(state, value, min, max) {
4582                 if(typeof value !== 'number') value = 0;
4583                 if(typeof min !== 'number') min = 0;
4584                 if(typeof max !== 'number') max = 0;
4585                 if(value > max) max = value;
4586                 if(value < min) min = value;
4587                 if(min > max) {
4588                         var t = min;
4589                         min = max;
4590                         max = t;
4591                 }
4592                 else if(min == max)
4593                         max = min + 1;
4594
4595                 // gauge.js has an issue if the needle
4596                 // is smaller than min or larger than max
4597                 // when we set the new values
4598                 // the needle will go crazy
4599
4600                 // to prevent it, we always feed it
4601                 // with a percentage, so that the needle
4602                 // is always between min and max
4603                 var pcent = (value - min) * 100 / (max - min);
4604
4605                 // these should never happen
4606                 if(pcent < 0) pcent = 0;
4607                 if(pcent > 100) pcent = 100;
4608
4609                 state.gauge_instance.set(pcent);
4610
4611                 state.___gaugeOld__.value = value;
4612                 state.___gaugeOld__.min = min;
4613                 state.___gaugeOld__.max = max;
4614         };
4615
4616         NETDATA.gaugeSetLabels = function(state, value, min, max) {
4617                 if(state.___gaugeOld__.valueLabel !== value) {
4618                         state.___gaugeOld__.valueLabel = value;
4619                         state.gaugeChartLabel.innerHTML = state.legendFormatValue(value);
4620                 }
4621                 if(state.___gaugeOld__.minLabel !== min) {
4622                         state.___gaugeOld__.minLabel = min;
4623                         state.gaugeChartMin.innerHTML = state.legendFormatValue(min);
4624                 }
4625                 if(state.___gaugeOld__.maxLabel !== max) {
4626                         state.___gaugeOld__.maxLabel = max;
4627                         state.gaugeChartMax.innerHTML = state.legendFormatValue(max);
4628                 }
4629         };
4630
4631         NETDATA.gaugeClearSelection = function(state) {
4632                 if(typeof state.gaugeEvent !== 'undefined') {
4633                         if(state.gaugeEvent.timer !== null)
4634                                 clearTimeout(state.gaugeEvent.timer);
4635
4636                         state.gaugeEvent.timer = null;
4637                 }
4638
4639                 if(state.isAutoRefreshed() === true && state.data !== null) {
4640                         NETDATA.gaugeChartUpdate(state, state.data);
4641                 }
4642                 else {
4643                         NETDATA.gaugeAnimation(state, false);
4644                         NETDATA.gaugeSet(state, null, null, null);
4645                         NETDATA.gaugeSetLabels(state, null, null, null);
4646                 }
4647
4648                 NETDATA.gaugeAnimation(state, true);
4649                 return true;
4650         };
4651
4652         NETDATA.gaugeSetSelection = function(state, t) {
4653                 if(state.timeIsVisible(t) !== true)
4654                         return NETDATA.gaugeClearSelection(state);
4655
4656                 var slot = state.calculateRowForTime(t);
4657                 if(slot < 0 || slot >= state.data.result.length)
4658                         return NETDATA.gaugeClearSelection(state);
4659
4660                 if(typeof state.gaugeEvent === 'undefined') {
4661                         state.gaugeEvent = {
4662                                 timer: null,
4663                                 value: 0,
4664                                 min: 0,
4665                                 max: 0
4666                         };
4667                 }
4668
4669                 var value = state.data.result[state.data.result.length - 1 - slot];
4670                 var max = (state.gaugeMax === null)?state.data.max:state.gaugeMax;
4671                 var min = 0;
4672
4673                 state.gaugeEvent.value = value;
4674                 state.gaugeEvent.max = max;
4675                 state.gaugeEvent.min = min;
4676                 NETDATA.gaugeSetLabels(state, value, min, max);
4677
4678                 if(state.gaugeEvent.timer === null) {
4679                         NETDATA.gaugeAnimation(state, false);
4680
4681                         state.gaugeEvent.timer = setTimeout(function() {
4682                                 state.gaugeEvent.timer = null;
4683                                 NETDATA.gaugeSet(state, state.gaugeEvent.value, state.gaugeEvent.min, state.gaugeEvent.max);
4684                         }, NETDATA.options.current.charts_selection_animation_delay);
4685                 }
4686
4687                 return true;
4688         };
4689
4690         NETDATA.gaugeChartUpdate = function(state, data) {
4691                 var value, min, max;
4692
4693                 if(NETDATA.globalPanAndZoom.isActive() === true || state.isAutoRefreshed() === false) {
4694                         value = 0;
4695                         min = 0;
4696                         max = 1;
4697                         NETDATA.gaugeSetLabels(state, null, null, null);
4698                 }
4699                 else {
4700                         value = data.result[0];
4701                         min = 0;
4702                         max = (state.gaugeMax === null)?data.max:state.gaugeMax;
4703                         if(value > max) max = value;
4704                         NETDATA.gaugeSetLabels(state, value, min, max);
4705                 }
4706
4707                 NETDATA.gaugeSet(state, value, min, max);
4708                 return true;
4709         };
4710
4711         NETDATA.gaugeChartCreate = function(state, data) {
4712                 var self = $(state.element);
4713                 var chart = $(state.element_chart);
4714
4715                 var value = data.result[0];
4716                 var max = self.data('gauge-max-value') || null;
4717                 var adjust = self.data('gauge-adjust') || null;
4718                 var pointerColor = self.data('gauge-pointer-color') || NETDATA.themes.current.gauge_pointer;
4719                 var strokeColor = self.data('gauge-stroke-color') || NETDATA.themes.current.gauge_stroke;
4720                 var startColor = self.data('gauge-start-color') || state.chartColors()[0];
4721                 var stopColor = self.data('gauge-stop-color') || void 0;
4722                 var generateGradient = self.data('gauge-generate-gradient') || false;
4723
4724                 if(max === null) {
4725                         max = data.max;
4726                         state.gaugeMax = null;
4727                 }
4728                 else
4729                         state.gaugeMax = max;
4730
4731                 var width = state.chartWidth(), height = state.chartHeight(); //, ratio = 1.5;
4732                 //switch(adjust) {
4733                 //      case 'width': width = height * ratio; break;
4734                 //      case 'height':
4735                 //      default: height = width / ratio; break;
4736                 //}
4737                 //state.element.style.width = width.toString() + 'px';
4738                 //state.element.style.height = height.toString() + 'px';
4739
4740                 var lum_d = 0.05;
4741
4742                 var options = {
4743                         lines: 12,                                      // The number of lines to draw
4744                         angle: 0.15,                            // The length of each line
4745                         lineWidth: 0.44,                        // 0.44 The line thickness
4746                         pointer: {
4747                                 length: 0.8,                    // 0.9 The radius of the inner circle
4748                                 strokeWidth: 0.035,             // The rotation offset
4749                                 color: pointerColor             // Fill color
4750                         },
4751                         colorStart: startColor,         // Colors
4752                         colorStop: stopColor,           // just experiment with them
4753                         strokeColor: strokeColor,       // to see which ones work best for you
4754                         limitMax: true,
4755                         generateGradient: generateGradient,
4756                         gradientType: 0
4757                 };
4758
4759                 if(generateGradient === false && NETDATA.themes.current.gauge_gradient === true) {
4760                         options.percentColors = [
4761                                 [0.0, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 0))],
4762                                 [0.1, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 1))],
4763                                 [0.2, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 2))],
4764                                 [0.3, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 3))],
4765                                 [0.4, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 4))],
4766                                 [0.5, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 5))],
4767                                 [0.6, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 6))],
4768                                 [0.7, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 7))],
4769                                 [0.8, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 8))],
4770                                 [0.9, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 9))],
4771                                 [1.0, NETDATA.colorLuminance(startColor, 0.0)]];
4772                 }
4773
4774                 state.gauge_canvas = document.createElement('canvas');
4775                 state.gauge_canvas.id = 'gauge-' + state.uuid + '-canvas';
4776                 state.gauge_canvas.className = 'gaugeChart';
4777                 state.gauge_canvas.width  = width;
4778                 state.gauge_canvas.height = height;
4779                 state.element_chart.appendChild(state.gauge_canvas);
4780
4781                 var valuefontsize = Math.floor(height / 6);
4782                 var valuetop = Math.round((height - valuefontsize - (height / 6)) / 2);
4783                 state.gaugeChartLabel = document.createElement('span');
4784                 state.gaugeChartLabel.className = 'gaugeChartLabel';
4785                 state.gaugeChartLabel.style.fontSize = valuefontsize + 'px';
4786                 state.gaugeChartLabel.style.top = valuetop.toString() + 'px';
4787                 state.element_chart.appendChild(state.gaugeChartLabel);
4788
4789                 var titlefontsize = Math.round(valuefontsize / 2);
4790                 var titletop = 0;
4791                 state.gaugeChartTitle = document.createElement('span');
4792                 state.gaugeChartTitle.className = 'gaugeChartTitle';
4793                 state.gaugeChartTitle.innerHTML = state.title;
4794                 state.gaugeChartTitle.style.fontSize = titlefontsize + 'px';
4795                 state.gaugeChartTitle.style.lineHeight = titlefontsize + 'px';
4796                 state.gaugeChartTitle.style.top = titletop.toString() + 'px';
4797                 state.element_chart.appendChild(state.gaugeChartTitle);
4798
4799                 var unitfontsize = Math.round(titlefontsize * 0.9);
4800                 state.gaugeChartUnits = document.createElement('span');
4801                 state.gaugeChartUnits.className = 'gaugeChartUnits';
4802                 state.gaugeChartUnits.innerHTML = state.units;
4803                 state.gaugeChartUnits.style.fontSize = unitfontsize + 'px';
4804                 state.element_chart.appendChild(state.gaugeChartUnits);
4805
4806                 state.gaugeChartMin = document.createElement('span');
4807                 state.gaugeChartMin.className = 'gaugeChartMin';
4808                 state.gaugeChartMin.style.fontSize = Math.round(valuefontsize * 0.75).toString() + 'px';
4809                 state.element_chart.appendChild(state.gaugeChartMin);
4810
4811                 state.gaugeChartMax = document.createElement('span');
4812                 state.gaugeChartMax.className = 'gaugeChartMax';
4813                 state.gaugeChartMax.style.fontSize = Math.round(valuefontsize * 0.75).toString() + 'px';
4814                 state.element_chart.appendChild(state.gaugeChartMax);
4815
4816                 // when we just re-create the chart
4817                 // do not animate the first update
4818                 var animate = true;
4819                 if(typeof state.gauge_instance !== 'undefined')
4820                         animate = false;
4821
4822                 state.gauge_instance = new Gauge(state.gauge_canvas).setOptions(options); // create sexy gauge!
4823
4824                 state.___gaugeOld__ = {
4825                         value: value,
4826                         min: 0,
4827                         max: max,
4828                         valueLabel: null,
4829                         minLabel: null,
4830                         maxLabel: null
4831                 };
4832                 
4833                 // we will always feed a percentage
4834                 state.gauge_instance.minValue = 0;
4835                 state.gauge_instance.maxValue = 100;
4836
4837                 NETDATA.gaugeAnimation(state, animate);
4838                 NETDATA.gaugeSet(state, value, 0, max);
4839                 NETDATA.gaugeSetLabels(state, value, 0, max);
4840                 NETDATA.gaugeAnimation(state, true);
4841                 return true;
4842         };
4843
4844         // ----------------------------------------------------------------------------------------------------------------
4845         // Charts Libraries Registration
4846
4847         NETDATA.chartLibraries = {
4848                 "dygraph": {
4849                         initialize: NETDATA.dygraphInitialize,
4850                         create: NETDATA.dygraphChartCreate,
4851                         update: NETDATA.dygraphChartUpdate,
4852                         resize: function(state) {
4853                                 if(typeof state.dygraph_instance.resize === 'function')
4854                                         state.dygraph_instance.resize();
4855                         },
4856                         setSelection: NETDATA.dygraphSetSelection,
4857                         clearSelection:  NETDATA.dygraphClearSelection,
4858                         initialized: false,
4859                         enabled: true,
4860                         format: function(state) { return 'json'; },
4861                         options: function(state) { return 'ms|flip'; },
4862                         legend: function(state) {
4863                                 if(this.isSparkline(state) === false)
4864                                         return 'right-side';
4865                                 else
4866                                         return null;
4867                         },
4868                         autoresize: function(state) { return true; },
4869                         max_updates_to_recreate: function(state) { return 5000; },
4870                         track_colors: function(state) { return true; },
4871                         pixels_per_point: function(state) {
4872                                 if(this.isSparkline(state) === false)
4873                                         return 3;
4874                                 else
4875                                         return 2;
4876                         },
4877
4878                         isSparkline: function(state) {
4879                                 if(typeof state.dygraph_sparkline === 'undefined') {
4880                                         var t = $(state.element).data('dygraph-theme');
4881                                         if(t === 'sparkline')
4882                                                 state.dygraph_sparkline = true;
4883                                         else
4884                                                 state.dygraph_sparkline = false;
4885                                 }
4886                                 return state.dygraph_sparkline;
4887                         }
4888                 },
4889                 "sparkline": {
4890                         initialize: NETDATA.sparklineInitialize,
4891                         create: NETDATA.sparklineChartCreate,
4892                         update: NETDATA.sparklineChartUpdate,
4893                         resize: null,
4894                         setSelection: undefined, // function(state, t) { return true; },
4895                         clearSelection: undefined, // function(state) { return true; },
4896                         initialized: false,
4897                         enabled: true,
4898                         format: function(state) { return 'array'; },
4899                         options: function(state) { return 'flip|abs'; },
4900                         legend: function(state) { return null; },
4901                         autoresize: function(state) { return false; },
4902                         max_updates_to_recreate: function(state) { return 5000; },
4903                         track_colors: function(state) { return false; },
4904                         pixels_per_point: function(state) { return 3; }
4905                 },
4906                 "peity": {
4907                         initialize: NETDATA.peityInitialize,
4908                         create: NETDATA.peityChartCreate,
4909                         update: NETDATA.peityChartUpdate,
4910                         resize: null,
4911                         setSelection: undefined, // function(state, t) { return true; },
4912                         clearSelection: undefined, // function(state) { return true; },
4913                         initialized: false,
4914                         enabled: true,
4915                         format: function(state) { return 'ssvcomma'; },
4916                         options: function(state) { return 'null2zero|flip|abs'; },
4917                         legend: function(state) { return null; },
4918                         autoresize: function(state) { return false; },
4919                         max_updates_to_recreate: function(state) { return 5000; },
4920                         track_colors: function(state) { return false; },
4921                         pixels_per_point: function(state) { return 3; }
4922                 },
4923                 "morris": {
4924                         initialize: NETDATA.morrisInitialize,
4925                         create: NETDATA.morrisChartCreate,
4926                         update: NETDATA.morrisChartUpdate,
4927                         resize: null,
4928                         setSelection: undefined, // function(state, t) { return true; },
4929                         clearSelection: undefined, // function(state) { return true; },
4930                         initialized: false,
4931                         enabled: true,
4932                         format: function(state) { return 'json'; },
4933                         options: function(state) { return 'objectrows|ms'; },
4934                         legend: function(state) { return null; },
4935                         autoresize: function(state) { return false; },
4936                         max_updates_to_recreate: function(state) { return 50; },
4937                         track_colors: function(state) { return false; },
4938                         pixels_per_point: function(state) { return 15; }
4939                 },
4940                 "google": {
4941                         initialize: NETDATA.googleInitialize,
4942                         create: NETDATA.googleChartCreate,
4943                         update: NETDATA.googleChartUpdate,
4944                         resize: null,
4945                         setSelection: undefined, //function(state, t) { return true; },
4946                         clearSelection: undefined, //function(state) { return true; },
4947                         initialized: false,
4948                         enabled: true,
4949                         format: function(state) { return 'datatable'; },
4950                         options: function(state) { return ''; },
4951                         legend: function(state) { return null; },
4952                         autoresize: function(state) { return false; },
4953                         max_updates_to_recreate: function(state) { return 300; },
4954                         track_colors: function(state) { return false; },
4955                         pixels_per_point: function(state) { return 4; }
4956                 },
4957                 "raphael": {
4958                         initialize: NETDATA.raphaelInitialize,
4959                         create: NETDATA.raphaelChartCreate,
4960                         update: NETDATA.raphaelChartUpdate,
4961                         resize: null,
4962                         setSelection: undefined, // function(state, t) { return true; },
4963                         clearSelection: undefined, // function(state) { return true; },
4964                         initialized: false,
4965                         enabled: true,
4966                         format: function(state) { return 'json'; },
4967                         options: function(state) { return ''; },
4968                         legend: function(state) { return null; },
4969                         autoresize: function(state) { return false; },
4970                         max_updates_to_recreate: function(state) { return 5000; },
4971                         track_colors: function(state) { return false; },
4972                         pixels_per_point: function(state) { return 3; }
4973                 },
4974                 "c3": {
4975                         initialize: NETDATA.c3Initialize,
4976                         create: NETDATA.c3ChartCreate,
4977                         update: NETDATA.c3ChartUpdate,
4978                         resize: null,
4979                         setSelection: undefined, // function(state, t) { return true; },
4980                         clearSelection: undefined, // function(state) { return true; },
4981                         initialized: false,
4982                         enabled: true,
4983                         format: function(state) { return 'csvjsonarray'; },
4984                         options: function(state) { return 'milliseconds'; },
4985                         legend: function(state) { return null; },
4986                         autoresize: function(state) { return false; },
4987                         max_updates_to_recreate: function(state) { return 5000; },
4988                         track_colors: function(state) { return false; },
4989                         pixels_per_point: function(state) { return 15; }
4990                 },
4991                 "d3": {
4992                         initialize: NETDATA.d3Initialize,
4993                         create: NETDATA.d3ChartCreate,
4994                         update: NETDATA.d3ChartUpdate,
4995                         resize: null,
4996                         setSelection: undefined, // function(state, t) { return true; },
4997                         clearSelection: undefined, // function(state) { return true; },
4998                         initialized: false,
4999                         enabled: true,
5000                         format: function(state) { return 'json'; },
5001                         options: function(state) { return ''; },
5002                         legend: function(state) { return null; },
5003                         autoresize: function(state) { return false; },
5004                         max_updates_to_recreate: function(state) { return 5000; },
5005                         track_colors: function(state) { return false; },
5006                         pixels_per_point: function(state) { return 3; }
5007                 },
5008                 "easypiechart": {
5009                         initialize: NETDATA.easypiechartInitialize,
5010                         create: NETDATA.easypiechartChartCreate,
5011                         update: NETDATA.easypiechartChartUpdate,
5012                         resize: null,
5013                         setSelection: NETDATA.easypiechartSetSelection,
5014                         clearSelection: NETDATA.easypiechartClearSelection,
5015                         initialized: false,
5016                         enabled: true,
5017                         format: function(state) { return 'array'; },
5018                         options: function(state) { return 'absolute'; },
5019                         legend: function(state) { return null; },
5020                         autoresize: function(state) { return false; },
5021                         max_updates_to_recreate: function(state) { return 5000; },
5022                         track_colors: function(state) { return true; },
5023                         pixels_per_point: function(state) { return 3; },
5024                         aspect_ratio: 100
5025                 },
5026                 "gauge": {
5027                         initialize: NETDATA.gaugeInitialize,
5028                         create: NETDATA.gaugeChartCreate,
5029                         update: NETDATA.gaugeChartUpdate,
5030                         resize: null,
5031                         setSelection: NETDATA.gaugeSetSelection,
5032                         clearSelection: NETDATA.gaugeClearSelection,
5033                         initialized: false,
5034                         enabled: true,
5035                         format: function(state) { return 'array'; },
5036                         options: function(state) { return 'absolute'; },
5037                         legend: function(state) { return null; },
5038                         autoresize: function(state) { return false; },
5039                         max_updates_to_recreate: function(state) { return 5000; },
5040                         track_colors: function(state) { return true; },
5041                         pixels_per_point: function(state) { return 3; },
5042                         aspect_ratio: 70
5043                 }
5044         };
5045
5046         NETDATA.registerChartLibrary = function(library, url) {
5047                 if(NETDATA.options.debug.libraries === true)
5048                         console.log("registering chart library: " + library);
5049
5050                 NETDATA.chartLibraries[library].url = url;
5051                 NETDATA.chartLibraries[library].initialized = true;
5052                 NETDATA.chartLibraries[library].enabled = true;
5053         }
5054
5055         // ----------------------------------------------------------------------------------------------------------------
5056         // Start up
5057
5058         NETDATA.requiredJs = [
5059                 {
5060                         url: NETDATA.serverDefault + 'lib/bootstrap.min.js',
5061                         isAlreadyLoaded: function() {
5062                                 if(typeof $().emulateTransitionEnd == 'function')
5063                                         return true;
5064                                 else {
5065                                         if(typeof netdataNoBootstrap !== 'undefined' && netdataNoBootstrap)
5066                                                 return true;
5067                                         else
5068                                                 return false;
5069                                 }
5070                         }
5071                 },
5072                 {
5073                         url: NETDATA.serverDefault + 'lib/jquery.nanoscroller.min.js',
5074                         isAlreadyLoaded: function() { return false; }
5075                 },
5076                 {
5077                         url: NETDATA.serverDefault + 'lib/bootstrap-toggle.min.js',
5078                         isAlreadyLoaded: function() { return false; }
5079                 }
5080         ];
5081
5082         NETDATA.requiredCSS = [
5083                 {
5084                         url: NETDATA.themes.current.bootstrap_css,
5085                         isAlreadyLoaded: function() {
5086                                 if(typeof netdataNoBootstrap !== 'undefined' && netdataNoBootstrap)
5087                                         return true;
5088                                 else
5089                                         return false;
5090                         }
5091                 },
5092                 {
5093                         url: NETDATA.serverDefault + 'css/font-awesome.min.css',
5094                         isAlreadyLoaded: function() { return false; }
5095                 },
5096                 {
5097                         url: NETDATA.themes.current.dashboard_css,
5098                         isAlreadyLoaded: function() { return false; }
5099                 },
5100                 {
5101                         url: NETDATA.serverDefault + 'css/bootstrap-toggle.min.css',
5102                         isAlreadyLoaded: function() { return false; }
5103                 }
5104         ];
5105
5106         NETDATA.loadRequiredJs = function(index, callback) {
5107                 if(index >= NETDATA.requiredJs.length)  {
5108                         if(typeof callback === 'function')
5109                                 callback();
5110                         return;
5111                 }
5112
5113                 if(NETDATA.requiredJs[index].isAlreadyLoaded()) {
5114                         NETDATA.loadRequiredJs(++index, callback);
5115                         return;
5116                 }
5117
5118                 if(NETDATA.options.debug.main_loop === true)
5119                         console.log('loading ' + NETDATA.requiredJs[index].url);
5120
5121                 $.ajax({
5122                         url: NETDATA.requiredJs[index].url,
5123                         cache: true,
5124                         dataType: "script"
5125                 })
5126                 .success(function() {
5127                         if(NETDATA.options.debug.main_loop === true)
5128                                 console.log('loaded ' + NETDATA.requiredJs[index].url);
5129
5130                         NETDATA.loadRequiredJs(++index, callback);
5131                 })
5132                 .fail(function() {
5133                         alert('Cannot load required JS library: ' + NETDATA.requiredJs[index].url);
5134                 })
5135         }
5136
5137         NETDATA.loadRequiredCSS = function(index) {
5138                 if(index >= NETDATA.requiredCSS.length)
5139                         return;
5140
5141                 if(NETDATA.requiredCSS[index].isAlreadyLoaded()) {
5142                         NETDATA.loadRequiredCSS(++index);
5143                         return;
5144                 }
5145
5146                 if(NETDATA.options.debug.main_loop === true)
5147                         console.log('loading ' + NETDATA.requiredCSS[index].url);
5148
5149                 NETDATA._loadCSS(NETDATA.requiredCSS[index].url);
5150                 NETDATA.loadRequiredCSS(++index);
5151         }
5152
5153         NETDATA.errorReset();
5154         NETDATA.loadRequiredCSS(0);
5155
5156         NETDATA._loadjQuery(function() {
5157                 NETDATA.loadRequiredJs(0, function() {
5158                         if(typeof netdataDontStart === 'undefined' || !netdataDontStart) {
5159                                 if(NETDATA.options.debug.main_loop === true)
5160                                         console.log('starting chart refresh thread');
5161
5162                                 NETDATA.start();
5163                         }
5164                 });
5165         });
5166
5167         // window.NETDATA = NETDATA;
5168 // })(window, document);