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