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