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