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