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