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