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