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