]> arthur.barton.de Git - netdata.git/blob - web/dashboard.js
reference to error function of state, fixed
[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.error = function(msg) {
1321                         error(msg);
1322                 }
1323
1324                 this.setMode = function(m) {
1325                         if(this.current !== null && this.current.name === m) return;
1326
1327                         if(m === 'auto')
1328                                 this.current = this.auto;
1329                         else if(m === 'pan')
1330                                 this.current = this.pan;
1331                         else if(m === 'zoom')
1332                                 this.current = this.zoom;
1333                         else
1334                                 this.current = this.auto;
1335
1336                         this.current.force_update_at = 0;
1337                         this.current.force_before_ms = null;
1338                         this.current.force_after_ms = null;
1339
1340                         this.tm.last_mode_switch = new Date().getTime();
1341                 }
1342
1343                 // ----------------------------------------------------------------------------------------------------------------
1344                 // global selection sync
1345
1346                 // prevent to global selection sync for some time
1347                 this.globalSelectionSyncDelay = function(ms) {
1348                         if(NETDATA.options.current.sync_selection === false)
1349                                 return;
1350
1351                         if(typeof ms === 'number')
1352                                 NETDATA.globalSelectionSync.dont_sync_before = new Date().getTime() + ms;
1353                         else
1354                                 NETDATA.globalSelectionSync.dont_sync_before = new Date().getTime() + NETDATA.options.current.sync_selection_delay;
1355                 }
1356
1357                 // can we globally apply selection sync?
1358                 this.globalSelectionSyncAbility = function() {
1359                         if(NETDATA.options.current.sync_selection === false)
1360                                 return false;
1361
1362                         if(NETDATA.globalSelectionSync.dont_sync_before > new Date().getTime())
1363                                 return false;
1364
1365                         return true;
1366                 }
1367
1368                 this.globalSelectionSyncIsMaster = function() {
1369                         if(NETDATA.globalSelectionSync.state === this)
1370                                 return true;
1371                         else
1372                                 return false;
1373                 }
1374
1375                 // this chart is the master of the global selection sync
1376                 this.globalSelectionSyncBeMaster = function() {
1377                         // am I the master?
1378                         if(this.globalSelectionSyncIsMaster()) {
1379                                 if(this.debug === true)
1380                                         this.log('sync: I am the master already.');
1381
1382                                 return;
1383                         }
1384
1385                         if(NETDATA.globalSelectionSync.state) {
1386                                 if(this.debug === true)
1387                                         this.log('sync: I am not the sync master. Resetting global sync.');
1388
1389                                 this.globalSelectionSyncStop();
1390                         }
1391
1392                         // become the master
1393                         if(this.debug === true)
1394                                 this.log('sync: becoming sync master.');
1395
1396                         this.selected = true;
1397                         NETDATA.globalSelectionSync.state = this;
1398
1399                         // find the all slaves
1400                         var targets = NETDATA.options.targets;
1401                         var len = targets.length;
1402                         while(len--) {
1403                                 st = targets[len];
1404
1405                                 if(st === this) {
1406                                         if(this.debug === true)
1407                                                 st.log('sync: not adding me to sync');
1408                                 }
1409                                 else if(st.globalSelectionSyncIsEligible()) {
1410                                         if(this.debug === true)
1411                                                 st.log('sync: adding to sync as slave');
1412
1413                                         st.globalSelectionSyncBeSlave();
1414                                 }
1415                         }
1416
1417                         // this.globalSelectionSyncDelay(100);
1418                 }
1419
1420                 // can the chart participate to the global selection sync as a slave?
1421                 this.globalSelectionSyncIsEligible = function() {
1422                         if(this.enabled === true
1423                                 && this.library !== null
1424                                 && typeof this.library.setSelection === 'function'
1425                                 && this.isVisible() === true
1426                                 && this.chart_created === true)
1427                                 return true;
1428
1429                         return false;
1430                 }
1431
1432                 // this chart becomes a slave of the global selection sync
1433                 this.globalSelectionSyncBeSlave = function() {
1434                         if(NETDATA.globalSelectionSync.state !== this)
1435                                 NETDATA.globalSelectionSync.slaves.push(this);
1436                 }
1437
1438                 // sync all the visible charts to the given time
1439                 // this is to be called from the chart libraries
1440                 this.globalSelectionSync = function(t) {
1441                         if(this.globalSelectionSyncAbility() === false) {
1442                                 if(this.debug === true)
1443                                         this.log('sync: cannot sync (yet?).');
1444
1445                                 return;
1446                         }
1447
1448                         if(this.globalSelectionSyncIsMaster() === false) {
1449                                 if(this.debug === true)
1450                                         this.log('sync: trying to be sync master.');
1451
1452                                 this.globalSelectionSyncBeMaster();
1453
1454                                 if(this.globalSelectionSyncAbility() === false) {
1455                                         if(this.debug === true)
1456                                                 this.log('sync: cannot sync (yet?).');
1457
1458                                         return;
1459                                 }
1460                         }
1461
1462                         NETDATA.globalSelectionSync.last_t = t;
1463                         $.each(NETDATA.globalSelectionSync.slaves, function(i, st) {
1464                                 st.setSelection(t);
1465                         });
1466                 }
1467
1468                 // stop syncing all charts to the given time
1469                 this.globalSelectionSyncStop = function() {
1470                         if(NETDATA.globalSelectionSync.slaves.length) {
1471                                 if(this.debug === true)
1472                                         this.log('sync: cleaning up...');
1473
1474                                 $.each(NETDATA.globalSelectionSync.slaves, function(i, st) {
1475                                         if(st === that) {
1476                                                 if(that.debug === true)
1477                                                         st.log('sync: not adding me to sync stop');
1478                                         }
1479                                         else {
1480                                                 if(that.debug === true)
1481                                                         st.log('sync: removed slave from sync');
1482
1483                                                 st.clearSelection();
1484                                         }
1485                                 });
1486
1487                                 NETDATA.globalSelectionSync.last_t = 0;
1488                                 NETDATA.globalSelectionSync.slaves = [];
1489                                 NETDATA.globalSelectionSync.state = null;
1490                         }
1491
1492                         this.clearSelection();
1493                 }
1494
1495                 this.setSelection = function(t) {
1496                         if(typeof this.library.setSelection === 'function') {
1497                                 if(this.library.setSelection(this, t) === true)
1498                                         this.selected = true;
1499                                 else
1500                                         this.selected = false;
1501                         }
1502                         else this.selected = true;
1503
1504                         if(this.selected === true && this.debug === true)
1505                                 this.log('selection set to ' + t.toString());
1506
1507                         return this.selected;
1508                 }
1509
1510                 this.clearSelection = function() {
1511                         if(this.selected === true) {
1512                                 if(typeof this.library.clearSelection === 'function') {
1513                                         if(this.library.clearSelection(this) === true)
1514                                                 this.selected = false;
1515                                         else
1516                                                 this.selected = true;
1517                                 }
1518                                 else this.selected = false;
1519
1520                                 if(this.selected === false && this.debug === true)
1521                                         this.log('selection cleared');
1522
1523                                 this.legendReset();
1524                         }
1525
1526                         return this.selected;
1527                 }
1528
1529                 // find if a timestamp (ms) is shown in the current chart
1530                 this.timeIsVisible = function(t) {
1531                         if(t >= this.data_after && t <= this.data_before)
1532                                 return true;
1533                         return false;
1534                 },
1535
1536                 this.calculateRowForTime = function(t) {
1537                         if(this.timeIsVisible(t) === false) return -1;
1538                         return Math.floor((t - this.data_after) / this.data_update_every);
1539                 }
1540
1541                 // ----------------------------------------------------------------------------------------------------------------
1542
1543                 // console logging
1544                 this.log = function(msg) {
1545                         console.log(this.id + ' (' + this.library_name + ' ' + this.uuid + '): ' + msg);
1546                 }
1547
1548                 this.pauseChart = function() {
1549                         if(this.paused === false) {
1550                                 if(this.debug === true)
1551                                         this.log('paused');
1552
1553                                 this.paused = true;
1554                         }
1555                 }
1556
1557                 this.unpauseChart = function() {
1558                         if(this.paused) {
1559                                 if(this.debug === true)
1560                                         this.log('unpaused');
1561
1562                                 this.paused = false;
1563                         }
1564                 }
1565
1566                 this.resetChart = function() {
1567                         if(NETDATA.globalPanAndZoom.isMaster(this) && this.isVisible())
1568                                 NETDATA.globalPanAndZoom.clearMaster();
1569
1570                         this.tm.pan_and_zoom_seq = 0;
1571
1572                         this.clearSelection();
1573
1574                         this.setMode('auto');
1575                         this.current.force_update_at = 0;
1576                         this.current.force_before_ms = null;
1577                         this.current.force_after_ms = null;
1578                         this.tm.last_autorefreshed = 0;
1579                         this.paused = false;
1580                         this.selected = false;
1581                         this.enabled = true;
1582                         this.debug = false;
1583
1584                         // do not update the chart here
1585                         // or the chart will flip-flop when it is the master
1586                         // of a selection sync and another chart becomes
1587                         // the new master
1588                         if(NETDATA.options.current.sync_pan_and_zoom === false && this.isVisible() === true)
1589                                 this.updateChart();
1590                 }
1591
1592                 this.updateChartPanOrZoom = function(after, before) {
1593                         if(before < after) return false;
1594
1595                         var min_duration = Math.round((this.chartWidth() / 30 * this.chart.update_every * 1000));
1596
1597                         if(this.debug === true)
1598                                 this.log('requested duration of ' + ((before - after) / 1000).toString() + ' (' + after + ' - ' + before + '), minimum ' + min_duration / 1000);
1599
1600                         if((before - after) < min_duration) return false;
1601
1602                         var current_duration = this.data_before - this.data_after;
1603                         var wanted_duration = before - after;
1604                         var tolerance = this.data_update_every * 2;
1605                         var movement = Math.abs(before - this.data_before);
1606
1607                         if(this.debug === true)
1608                                 this.log('current duration: ' + current_duration / 1000 + ', wanted duration: ' + wanted_duration / 1000 + ', movement: ' + movement / 1000 + ', tolerance: ' + tolerance / 1000);
1609
1610                         if(Math.abs(current_duration - wanted_duration) <= tolerance && movement <= tolerance) {
1611                                 if(this.debug === true)
1612                                         this.log('IGNORED');
1613
1614                                 return false;
1615                         }
1616
1617                         if(this.current.name === 'auto') {
1618                                 this.setMode('pan');
1619
1620                                 if(this.debug === true)
1621                                         this.log('updateChartPanOrZoom(): caller did not set proper mode');
1622                         }
1623
1624                         this.current.force_update_at = new Date().getTime() + NETDATA.options.current.pan_and_zoom_delay;
1625                         this.current.force_after_ms = after;
1626                         this.current.force_before_ms = before;
1627                         NETDATA.globalPanAndZoom.setMaster(this, after, before);
1628                         return true;
1629                 }
1630
1631                 this.legendFormatValue = function(value) {
1632                         if(value === null || value === 'undefined') return '-';
1633                         if(typeof value !== 'number') return value;
1634
1635                         var abs = Math.abs(value);
1636                         if(abs >= 1) return (Math.round(value * 100) / 100).toLocaleString();
1637                         if(abs >= 0.1) return (Math.round(value * 1000) / 1000).toLocaleString();
1638                         return (Math.round(value * 10000) / 10000).toLocaleString();
1639                 }
1640
1641                 this.legendSetLabelValue = function(label, value) {
1642                         var series = this.element_legend_childs.series[label];
1643                         if(typeof series === 'undefined') return;
1644                         if(series.value === null && series.user === null) return;
1645
1646                         // if the value has not changed, skip DOM update
1647                         //if(series.last === value) return;
1648
1649                         var s, r;
1650                         if(typeof value === 'number') {
1651                                 var v = Math.abs(value);
1652                                 s = r = this.legendFormatValue(value);
1653
1654                                 if(typeof series.last === 'number') {
1655                                         if(v > series.last) s += '<i class="fa fa-angle-up" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1656                                         else if(v < series.last) s += '<i class="fa fa-angle-down" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1657                                         else s += '<i class="fa fa-angle-left" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1658                                 }
1659                                 else s += '<i class="fa fa-angle-right" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1660                                 series.last = v;
1661                         }
1662                         else {
1663                                 s = r = value;
1664                                 series.last = value;
1665                         }
1666
1667                         if(series.value !== null) series.value.innerHTML = s;
1668                         if(series.user !== null) series.user.innerHTML = r;
1669                 }
1670
1671                 this.legendSetDate = function(ms) {
1672                         if(typeof ms !== 'number') {
1673                                 this.legendShowUndefined();
1674                                 return;
1675                         }
1676
1677                         var d = new Date(ms);
1678
1679                         if(this.element_legend_childs.title_date)
1680                                 this.element_legend_childs.title_date.innerHTML = d.toLocaleDateString();
1681
1682                         if(this.element_legend_childs.title_time)
1683                                 this.element_legend_childs.title_time.innerHTML = d.toLocaleTimeString();
1684
1685                         if(this.element_legend_childs.title_units)
1686                                 this.element_legend_childs.title_units.innerHTML = this.chart.units;
1687                 }
1688
1689                 this.legendShowUndefined = function() {
1690                         if(this.element_legend_childs.title_date)
1691                                 this.element_legend_childs.title_date.innerHTML = '&nbsp;';
1692
1693                         if(this.element_legend_childs.title_time)
1694                                 this.element_legend_childs.title_time.innerHTML = this.chart.name;
1695
1696                         if(this.element_legend_childs.title_units)
1697                                 this.element_legend_childs.title_units.innerHTML = '&nbsp;';
1698
1699                         if(this.data && this.element_legend_childs.series !== null) {
1700                                 var labels = this.data.dimension_names;
1701                                 var i = labels.length;
1702                                 while(i--) {
1703                                         var label = labels[i];
1704
1705                                         if(typeof label === 'undefined') continue;
1706                                         if(typeof this.element_legend_childs.series[label] === 'undefined') continue;
1707                                         this.legendSetLabelValue(label, null);
1708                                 }
1709                         }
1710                 }
1711
1712                 this.legendShowLatestValues = function() {
1713                         if(this.chart === null) return;
1714                         if(this.selected) return;
1715
1716                         if(this.data === null || this.element_legend_childs.series === null) {
1717                                 this.legendShowUndefined();
1718                                 return;
1719                         }
1720
1721                         var show_undefined = true;
1722                         if(Math.abs(this.data.last_entry - this.data.before) <= this.data.view_update_every)
1723                                 show_undefined = false;
1724
1725                         if(show_undefined) {
1726                                 this.legendShowUndefined();
1727                                 return;
1728                         }
1729
1730                         this.legendSetDate(this.data.before * 1000);
1731
1732                         var labels = this.data.dimension_names;
1733                         var i = labels.length;
1734                         while(i--) {
1735                                 var label = labels[i];
1736
1737                                 if(typeof label === 'undefined') continue;
1738                                 if(typeof this.element_legend_childs.series[label] === 'undefined') continue;
1739
1740                                 if(show_undefined)
1741                                         this.legendSetLabelValue(label, null);
1742                                 else
1743                                         this.legendSetLabelValue(label, this.data.view_latest_values[i]);
1744                         }
1745                 }
1746
1747                 this.legendReset = function() {
1748                         this.legendShowLatestValues();
1749                 }
1750
1751                 // this should be called just ONCE per dimension per chart
1752                 this._chartDimensionColor = function(label) {
1753                         if(this.colors === null) this.chartColors();
1754
1755                         if(typeof this.colors_assigned[label] === 'undefined') {
1756                                 if(this.colors_available.length === 0) {
1757                                         for(var i = 0, len = NETDATA.colors.length; i < len ; i++)
1758                                                 this.colors_available.push(NETDATA.colors[i]);
1759                                 }
1760
1761                                 this.colors_assigned[label] = this.colors_available.shift();
1762
1763                                 if(this.debug === true)
1764                                         this.log('label "' + label + '" got color "' + this.colors_assigned[label]);
1765                         }
1766                         else {
1767                                 if(this.debug === true)
1768                                         this.log('label "' + label + '" already has color "' + this.colors_assigned[label] + '"');
1769                         }
1770
1771                         this.colors.push(this.colors_assigned[label]);
1772                         return this.colors_assigned[label];
1773                 }
1774
1775                 this.chartColors = function() {
1776                         if(this.colors !== null) return this.colors;
1777
1778                         this.colors = new Array();
1779                         this.colors_available = new Array();
1780                         // this.colors_assigned = {};
1781
1782                         var c = $(this.element).data('colors');
1783                         if(typeof c !== 'undefined' && c !== null) {
1784                                 if(typeof c !== 'string') {
1785                                         this.log('invalid color given: ' + c + ' (give a space separated list of colors)');
1786                                 }
1787                                 else {
1788                                         c = c.split(' ');
1789                                         for(var i = 0, len = c.length; i < len ; i++)
1790                                                 this.colors_available.push(c[i]);
1791                                 }
1792                         }
1793
1794                         // push all the standard colors too
1795                         for(var i = 0, len = NETDATA.colors.length; i < len ; i++)
1796                                 this.colors_available.push(NETDATA.colors[i]);
1797
1798                         return this.colors;
1799                 }
1800
1801                 this.legendUpdateDOM = function() {
1802                         var needed = false;
1803
1804                         // check that the legend DOM is up to date for the downloaded dimensions
1805                         if(typeof this.element_legend_childs.series !== 'object' || this.element_legend_childs.series === null) {
1806                                 // this.log('the legend does not have any series - requesting legend update');
1807                                 needed = true;
1808                         }
1809                         else if(this.data === null) {
1810                                 // this.log('the chart does not have any data - requesting legend update');
1811                                 needed = true;
1812                         }
1813                         else if(typeof this.element_legend_childs.series.labels_key === 'undefined') {
1814                                 needed = true;
1815                         }
1816                         else {
1817                                 var labels = this.data.dimension_names.toString();
1818                                 if(labels !== this.element_legend_childs.series.labels_key) {
1819                                         needed = true;
1820
1821                                         if(this.debug === true)
1822                                                 this.log('NEW LABELS: "' + labels + '" NOT EQUAL OLD LABELS: "' + this.element_legend_childs.series.labels_key + '"');
1823                                 }
1824                         }
1825
1826                         if(needed === false) {
1827                                 // make sure colors available
1828                                 this.chartColors();
1829
1830                                 // do we have to update the current values?
1831                                 // we do this, only when the visible chart is current
1832                                 if(Math.abs(this.data.last_entry - this.data.before) <= this.data.view_update_every) {
1833                                         if(this.debug === true)
1834                                                 this.log('chart in running... updating values on legend...');
1835
1836                                         //var labels = this.data.dimension_names;
1837                                         //var i = labels.length;
1838                                         //while(i--)
1839                                         //      this.legendSetLabelValue(labels[i], this.data.latest_values[i]);
1840                                 }
1841                                 return;
1842                         }
1843                         if(this.colors === null) {
1844                                 // this is the first time we update the chart
1845                                 // let's assign colors to all dimensions
1846                                 if(this.library.track_colors() === true)
1847                                         for(var dim in this.chart.dimensions)
1848                                                 this._chartDimensionColor(this.chart.dimensions[dim].name);
1849                         }
1850                         // we will re-generate the colors for the chart
1851                         this.colors = null;
1852
1853                         if(this.debug === true)
1854                                 this.log('updating Legend DOM');
1855
1856                         // mark all dimensions as invalid
1857                         this.dimensions_visibility.invalidateAll();
1858
1859                         var genLabel = function(state, parent, name, count) {
1860                                 var color = state._chartDimensionColor(name);
1861
1862                                 var user_element = null;
1863                                 var user_id = self.data('show-value-of-' + name + '-at') || null;
1864                                 if(user_id !== null) {
1865                                         user_element = document.getElementById(user_id) || null;
1866                                         if(user_element === null)
1867                                                 me.log('Cannot find element with id: ' + user_id);
1868                                 }
1869
1870                                 state.element_legend_childs.series[name] = {
1871                                         name: document.createElement('span'),
1872                                         value: document.createElement('span'),
1873                                         user: user_element,
1874                                         last: null
1875                                 };
1876
1877                                 var label = state.element_legend_childs.series[name];
1878
1879                                 // create the dimension visibility tracking for this label
1880                                 var ds = state.dimensions_visibility.dimensionAdd(name, label.name, label.value, color);
1881
1882                                 var rgb = NETDATA.colorHex2Rgb(color);
1883                                 label.name.innerHTML = '<table class="netdata-legend-name-table-'
1884                                         + state.chart.chart_type
1885                                         + '" style="background-color: '
1886                                         + 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + NETDATA.options.current['color_fill_opacity_' + state.chart.chart_type] + ')'
1887                                         + '"><tr class="netdata-legend-name-tr"><td class="netdata-legend-name-td"></td></tr></table>'
1888
1889                                 var text = document.createTextNode(' ' + name);
1890                                 label.name.appendChild(text);
1891
1892                                 if(count > 0)
1893                                         parent.appendChild(document.createElement('br'));
1894
1895                                 parent.appendChild(label.name);
1896                                 parent.appendChild(label.value);
1897                         };
1898
1899                         var content = document.createElement('div');
1900
1901                         if(this.hasLegend()) {
1902                                 this.element_legend_childs = {
1903                                         content: content,
1904                                         resize_handler: document.createElement('div'),
1905                                         title_date: document.createElement('span'),
1906                                         title_time: document.createElement('span'),
1907                                         title_units: document.createElement('span'),
1908                                         nano: document.createElement('div'),
1909                                         nano_options: {
1910                                                 paneClass: 'netdata-legend-series-pane',
1911                                                 sliderClass: 'netdata-legend-series-slider',
1912                                                 contentClass: 'netdata-legend-series-content',
1913                                                 enabledClass: '__enabled',
1914                                                 flashedClass: '__flashed',
1915                                                 activeClass: '__active',
1916                                                 tabIndex: -1,
1917                                                 alwaysVisible: true,
1918                                                 sliderMinHeight: 10
1919                                         },
1920                                         series: {}
1921                                 };
1922
1923                                 this.element_legend.innerHTML = '';
1924
1925                                 this.element_legend_childs.resize_handler.className += " netdata-legend-resize-handler";
1926                                 this.element_legend_childs.resize_handler.innerHTML = '<i class="fa fa-chevron-up"></i><i class="fa fa-chevron-down"></i>';
1927                                 this.element.appendChild(this.element_legend_childs.resize_handler);
1928
1929                                 // mousedown event
1930                                 this.element_legend_childs.resize_handler.onmousedown =
1931                                         function(e) {
1932                                                 that.resizeHandler(e);
1933                                         };
1934
1935                                 // touchstart event
1936                                 this.element_legend_childs.resize_handler.addEventListener('touchstart', function(e) {
1937                                         that.resizeHandler(e);
1938                                 }, false);
1939
1940                                 this.element_legend_childs.title_date.className += " netdata-legend-title-date";
1941                                 this.element_legend.appendChild(this.element_legend_childs.title_date);
1942
1943                                 this.element_legend.appendChild(document.createElement('br'));
1944
1945                                 this.element_legend_childs.title_time.className += " netdata-legend-title-time";
1946                                 this.element_legend.appendChild(this.element_legend_childs.title_time);
1947
1948                                 this.element_legend.appendChild(document.createElement('br'));
1949
1950                                 this.element_legend_childs.title_units.className += " netdata-legend-title-units";
1951                                 this.element_legend.appendChild(this.element_legend_childs.title_units);
1952
1953                                 this.element_legend.appendChild(document.createElement('br'));
1954
1955                                 this.element_legend_childs.nano.className = 'netdata-legend-series';
1956                                 this.element_legend.appendChild(this.element_legend_childs.nano);
1957
1958                                 content.className = 'netdata-legend-series-content';
1959                                 this.element_legend_childs.nano.appendChild(content);
1960                         }
1961                         else {
1962                                 this.element_legend_childs = {
1963                                         content: content,
1964                                         resize_handler: null,
1965                                         title_date: null,
1966                                         title_time: null,
1967                                         title_units: null,
1968                                         nano: null,
1969                                         nano_options: null,
1970                                         series: {}
1971                                 };
1972                         }
1973
1974                         if(this.data) {
1975                                 this.element_legend_childs.series.labels_key = this.data.dimension_names.toString();
1976                                 if(this.debug === true)
1977                                         this.log('labels from data: "' + this.element_legend_childs.series.labels_key + '"');
1978
1979                                 for(var i = 0, len = this.data.dimension_names.length; i < len ;i++) {
1980                                         genLabel(this, content, this.data.dimension_names[i], i);
1981                                 }
1982                         }
1983                         else {
1984                                 var tmp = new Array();
1985                                 for(var dim in this.chart.dimensions) {
1986                                         tmp.push(this.chart.dimensions[dim].name);
1987                                         genLabel(this, content, this.chart.dimensions[dim].name, i);
1988                                 }
1989                                 this.element_legend_childs.series.labels_key = tmp.toString();
1990                                 if(this.debug === true)
1991                                         this.log('labels from chart: "' + this.element_legend_childs.series.labels_key + '"');
1992                         }
1993
1994                         // create a hidden div to be used for hidding
1995                         // the original legend of the chart library
1996                         var el = document.createElement('div');
1997                         if(this.element_legend !== null)
1998                                 this.element_legend.appendChild(el);
1999                         el.style.display = 'none';
2000
2001                         this.element_legend_childs.hidden = document.createElement('div');
2002                         el.appendChild(this.element_legend_childs.hidden);
2003
2004                         if(this.element_legend_childs.nano !== null && this.element_legend_childs.nano_options !== null)
2005                                 $(this.element_legend_childs.nano).nanoScroller(this.element_legend_childs.nano_options);
2006
2007                         this.legendShowLatestValues();
2008                 }
2009
2010                 this.hasLegend = function() {
2011                         if(typeof this.___hasLegendCache___ !== 'undefined')
2012                                 return this.___hasLegendCache___;
2013
2014                         var leg = false;
2015                         if(this.library && this.library.legend(this) === 'right-side') {
2016                                 var legend = $(this.element).data('legend') || 'yes';
2017                                 if(legend === 'yes') leg = true;
2018                         }
2019
2020                         this.___hasLegendCache___ = leg;
2021                         return leg;
2022                 }
2023
2024                 this.legendWidth = function() {
2025                         return (this.hasLegend())?140:0;
2026                 }
2027
2028                 this.legendHeight = function() {
2029                         return $(this.element).height();
2030                 }
2031
2032                 this.chartWidth = function() {
2033                         return $(this.element).width() - this.legendWidth();
2034                 }
2035
2036                 this.chartHeight = function() {
2037                         return $(this.element).height();
2038                 }
2039
2040                 this.chartPixelsPerPoint = function() {
2041                         // force an options provided detail
2042                         var px = this.pixels_per_point;
2043
2044                         if(this.library && px < this.library.pixels_per_point(this))
2045                                 px = this.library.pixels_per_point(this);
2046
2047                         if(px < NETDATA.options.current.pixels_per_point)
2048                                 px = NETDATA.options.current.pixels_per_point;
2049
2050                         return px;
2051                 }
2052
2053                 this.needsRecreation = function() {
2054                         return (
2055                                         this.chart_created === true
2056                                         && this.library
2057                                         && this.library.autoresize() === false
2058                                         && this.tm.last_resized < NETDATA.options.last_resized
2059                                 );
2060                 }
2061
2062                 this.chartURL = function() {
2063                         var before;
2064                         var after;
2065                         if(NETDATA.globalPanAndZoom.isActive()) {
2066                                 after = Math.round(NETDATA.globalPanAndZoom.force_after_ms / 1000);
2067                                 before = Math.round(NETDATA.globalPanAndZoom.force_before_ms / 1000);
2068                                 this.tm.pan_and_zoom_seq = NETDATA.globalPanAndZoom.seq;
2069                         }
2070                         else {
2071                                 before = this.current.force_before_ms !== null ? Math.round(this.current.force_before_ms / 1000) : this.before;
2072                                 after  = this.current.force_after_ms  !== null ? Math.round(this.current.force_after_ms / 1000) : this.after;
2073                                 this.tm.pan_and_zoom_seq = 0;
2074                         }
2075
2076                         this.requested_after = after * 1000;
2077                         this.requested_before = before * 1000;
2078
2079                         this.data_points = this.points || Math.round(this.chartWidth() / this.chartPixelsPerPoint());
2080
2081                         // build the data URL
2082                         this.data_url = this.chart.data_url;
2083                         this.data_url += "&format="  + this.library.format();
2084                         this.data_url += "&points="  + this.data_points.toString();
2085                         this.data_url += "&group="   + this.method;
2086                         this.data_url += "&options=" + this.library.options();
2087                         this.data_url += '|jsonwrap';
2088
2089                         if(NETDATA.options.current.eliminate_zero_dimensions === true)
2090                                 this.data_url += '|nonzero';
2091
2092                         if(after)
2093                                 this.data_url += "&after="  + after.toString();
2094
2095                         if(before)
2096                                 this.data_url += "&before=" + before.toString();
2097
2098                         if(this.dimensions)
2099                                 this.data_url += "&dimensions=" + this.dimensions;
2100
2101                         if(NETDATA.options.debug.chart_data_url === true || this.debug === true)
2102                                 this.log('chartURL(): ' + this.data_url + ' WxH:' + this.chartWidth() + 'x' + this.chartHeight() + ' points: ' + this.data_points + ' library: ' + this.library_name);
2103                 }
2104
2105                 this.redrawChart = function() {
2106                         if(this.data !== null)
2107                                 this.updateChartWithData(this.data);
2108                 }
2109
2110                 this.updateChartWithData = function(data) {
2111                         if(this.debug === true)
2112                                 this.log('got data from netdata server');
2113
2114                         // this may force the chart to be re-created
2115                         resizeChart();
2116
2117                         this.data = data;
2118                         this.updates_counter++;
2119
2120                         var started = new Date().getTime();
2121
2122                         // if the result is JSON, find the latest update-every
2123                         if(typeof data === 'object') {
2124                                 if(typeof data.view_update_every !== 'undefined')
2125                                         this.data_update_every = data.view_update_every * 1000;
2126
2127                                 if(typeof data.after !== 'undefined')
2128                                         this.data_after = data.after * 1000;
2129
2130                                 if(typeof data.before !== 'undefined')
2131                                         this.data_before = data.before * 1000;
2132
2133                                 if(typeof data.first_entry !== 'undefined')
2134                                         this.netdata_first = data.first_entry * 1000;
2135
2136                                 if(typeof data.last_entry !== 'undefined')
2137                                         this.netdata_last = data.last_entry * 1000;
2138
2139                                 if(typeof data.points !== 'undefined')
2140                                         this.data_points = data.points;
2141
2142                                 data.state = this;
2143                         }
2144
2145                         if(this.debug === true) {
2146                                 this.log('UPDATE No ' + this.updates_counter + ' COMPLETED');
2147
2148                                 if(this.current.force_after_ms)
2149                                         this.log('STATUS: forced   : ' + (this.current.force_after_ms / 1000).toString() + ' - ' + (this.current.force_before_ms / 1000).toString());
2150                                 else
2151                                         this.log('STATUS: forced: unset');
2152
2153                                 this.log('STATUS: requested: ' + (this.requested_after / 1000).toString() + ' - ' + (this.requested_before / 1000).toString());
2154                                 this.log('STATUS: rendered : ' + (this.data_after / 1000).toString() + ' - ' + (this.data_before / 1000).toString());
2155                                 this.log('STATUS: points   : ' + (this.data_points).toString());
2156                         }
2157
2158                         if(this.data_points === 0) {
2159                                 noDataToShow();
2160                                 return;
2161                         }
2162
2163                         if(this.updates_since_last_creation >= this.library.max_updates_to_recreate()) {
2164                                 if(this.debug === true)
2165                                         this.log('max updates of ' + this.updates_since_last_creation.toString() + ' reached. Forcing re-generation.');
2166
2167                                 this.chart_created = false;
2168                         }
2169
2170                         // check and update the legend
2171                         this.legendUpdateDOM();
2172
2173                         if(this.chart_created === true
2174                                 && typeof this.library.update === 'function') {
2175
2176                                 if(this.debug === true)
2177                                         this.log('updating chart...');
2178
2179                                 this.updates_since_last_creation++;
2180                                 if(NETDATA.options.debug.chart_errors === true) {
2181                                         this.library.update(this, data);
2182                                 }
2183                                 else {
2184                                         try {
2185                                                 this.library.update(this, data);
2186                                         }
2187                                         catch(err) {
2188                                                 error('chart failed to be updated as ' + this.library_name);
2189                                         }
2190                                 }
2191                         }
2192                         else {
2193                                 if(this.debug === true)
2194                                         this.log('creating chart...');
2195
2196                                 if(NETDATA.options.debug.chart_errors === true) {
2197                                         this.library.create(this, data);
2198                                         this.chart_created = true;
2199                                         this.updates_since_last_creation = 0;
2200                                 }
2201                                 else {
2202                                         try {
2203                                                 this.library.create(this, data);
2204                                                 this.chart_created = true;
2205                                                 this.updates_since_last_creation = 0;
2206                                         }
2207                                         catch(err) {
2208                                                 error('chart failed to be created as ' + this.library_name);
2209                                         }
2210                                 }
2211                         }
2212                         hideMessage();
2213                         this.legendShowLatestValues();
2214                         NETDATA.globalSelectionSync.stop();
2215
2216                         // update the performance counters
2217                         var now = new Date().getTime();
2218                         this.tm.last_updated = now;
2219
2220                         // don't update last_autorefreshed if this chart is
2221                         // forced to be updated with global PanAndZoom
2222                         if(NETDATA.globalPanAndZoom.isActive())
2223                                 this.tm.last_autorefreshed = 0;
2224                         else {
2225                                 if(NETDATA.options.current.parallel_refresher === true && NETDATA.options.current.concurrent_refreshes)
2226                                         this.tm.last_autorefreshed = Math.round(now / this.data_update_every) * this.data_update_every;
2227                                 else
2228                                         this.tm.last_autorefreshed = now;
2229                         }
2230
2231                         this.refresh_dt_ms = now - started;
2232                         NETDATA.options.auto_refresher_fast_weight += this.refresh_dt_ms;
2233
2234                         if(this.refresh_dt_element !== null)
2235                                 this.refresh_dt_element.innerHTML = this.refresh_dt_ms.toString();
2236                 }
2237
2238                 this.updateChart = function(callback) {
2239                         // due to late initialization of charts and libraries
2240                         // we need to check this too
2241                         if(this.enabled === false) {
2242                                 if(this.debug === true)
2243                                         this.log('I am not enabled');
2244
2245                                 if(typeof callback === 'function') callback();
2246                                 return false;
2247                         }
2248
2249                         if(this.chart === null) {
2250                                 this.getChart(function() { that.updateChart(callback); });
2251                                 return;
2252                         }
2253
2254                         if(this.library.initialized === false) {
2255                                 if(this.library.enabled === true) {
2256                                         this.library.initialize(function() { that.updateChart(callback); });
2257                                         return;
2258                                 }
2259                                 else {
2260                                         error('chart library "' + this.library_name + '" is not available.');
2261                                         if(typeof callback === 'function') callback();
2262                                         return false;
2263                                 }
2264                         }
2265
2266                         this.clearSelection();
2267                         this.chartURL();
2268
2269                         if(this.debug === true)
2270                                 this.log('updating from ' + this.data_url);
2271
2272                         this.xhr = $.ajax( {
2273                                 url: this.data_url,
2274                                 crossDomain: NETDATA.options.crossDomainAjax,
2275                                 cache: false,
2276                                 async: true
2277                         })
2278                         .success(function(data) {
2279                                 if(that.debug === true)
2280                                         that.log('data received. updating chart.');
2281
2282                                 that.updateChartWithData(data);
2283                         })
2284                         .fail(function() {
2285                                 error('data download failed for url: ' + that.data_url);
2286                         })
2287                         .always(function() {
2288                                 if(typeof callback === 'function') callback();
2289                         });
2290                 }
2291
2292                 this.isVisible = function() {
2293                         // this.log('last_visible_check: ' + this.tm.last_visible_check + ', last_page_scroll: ' + NETDATA.options.last_page_scroll);
2294
2295                         // caching - we do not evaluate the charts visibility
2296                         // if the page has not been scrolled since the last check
2297                         if(this.tm.last_visible_check > NETDATA.options.last_page_scroll) {
2298                                 if(this.debug === true)
2299                                         this.log('isVisible: ' + this.___isVisible___);
2300
2301                                 return this.___isVisible___;
2302                         }
2303
2304                         this.tm.last_visible_check = new Date().getTime();
2305
2306                         var wh = window.innerHeight;
2307                         var x = this.element.getBoundingClientRect();
2308                         var ret = 0;
2309                         var tolerance = 0;
2310
2311                         if(x.top < 0 && -x.top > x.height) {
2312                                 // the chart is entirely above
2313                                 ret = -x.top - x.height;
2314                         }
2315                         else if(x.top > wh) {
2316                                 // the chart is entirely below
2317                                 ret = x.top - wh;
2318                         }
2319
2320                         if(ret > tolerance) {
2321                                 // the chart is too far
2322
2323                                 hideChart();
2324                                 this.___isVisible___ = false;
2325
2326                                 if(this.debug === true)
2327                                         this.log('isVisible: ' + this.___isVisible___);
2328
2329                                 return this.___isVisible___;
2330                         }
2331                         else {
2332                                 // the chart is inside or very close
2333
2334                                 unhideChart();
2335                                 this.___isVisible___ = true;
2336
2337                                 if(this.debug === true)
2338                                         this.log('isVisible: ' + this.___isVisible___);
2339
2340                                 return this.___isVisible___;
2341                         }
2342                 }
2343
2344                 this.isAutoRefreshed = function() {
2345                         return (this.current.autorefresh);
2346                 }
2347
2348                 this.canBeAutoRefreshed = function() {
2349                         now = new Date().getTime();
2350
2351                         if(this.enabled === false) {
2352                                 if(this.debug === true)
2353                                         this.log('I am not enabled');
2354
2355                                 return false;
2356                         }
2357
2358                         if(this.library === null || this.library.enabled === false) {
2359                                 error('charting library "' + this.library_name + '" is not available');
2360                                 if(this.debug === true)
2361                                         this.log('My chart library ' + this.library_name + ' is not available');
2362
2363                                 return false;
2364                         }
2365
2366                         if(this.isVisible() === false) {
2367                                 if(NETDATA.options.debug.visibility === true || this.debug === true)
2368                                         this.log('I am not visible');
2369
2370                                 return false;
2371                         }
2372
2373                         if(this.current.force_update_at !== 0 && this.current.force_update_at < now) {
2374                                 if(this.debug === true)
2375                                         this.log('timed force update detected - allowing this update');
2376
2377                                 this.current.force_update_at = 0;
2378                                 return true;
2379                         }
2380
2381                         if(this.isAutoRefreshed() === true) {
2382                                 // allow the first update, even if the page is not visible
2383                                 if(this.updates_counter && NETDATA.options.page_is_visible === false) {
2384                                         if(NETDATA.options.debug.focus === true || this.debug === true)
2385                                                 this.log('canBeAutoRefreshed(): page does not have focus');
2386
2387                                         return false;
2388                                 }
2389
2390                                 if(this.needsRecreation() === true) {
2391                                         if(this.debug === true)
2392                                                 this.log('canBeAutoRefreshed(): needs re-creation.');
2393
2394                                         return true;
2395                                 }
2396
2397                                 // options valid only for autoRefresh()
2398                                 if(NETDATA.options.auto_refresher_stop_until === 0 || NETDATA.options.auto_refresher_stop_until < now) {
2399                                         if(NETDATA.globalPanAndZoom.isActive()) {
2400                                                 if(NETDATA.globalPanAndZoom.shouldBeAutoRefreshed(this)) {
2401                                                         if(this.debug === true)
2402                                                                 this.log('canBeAutoRefreshed(): global panning: I need an update.');
2403
2404                                                         return true;
2405                                                 }
2406                                                 else {
2407                                                         if(this.debug === true)
2408                                                                 this.log('canBeAutoRefreshed(): global panning: I am already up to date.');
2409
2410                                                         return false;
2411                                                 }
2412                                         }
2413
2414                                         if(this.selected === true) {
2415                                                 if(this.debug === true)
2416                                                         this.log('canBeAutoRefreshed(): I have a selection in place.');
2417
2418                                                 return false;
2419                                         }
2420
2421                                         if(this.paused === true) {
2422                                                 if(this.debug === true)
2423                                                         this.log('canBeAutoRefreshed(): I am paused.');
2424
2425                                                 return false;
2426                                         }
2427
2428                                         if(now - this.tm.last_autorefreshed >= this.data_update_every) {
2429                                                 if(this.debug === true)
2430                                                         this.log('canBeAutoRefreshed(): It is time to update me.');
2431
2432                                                 return true;
2433                                         }
2434                                 }
2435                         }
2436
2437                         return false;
2438                 }
2439
2440                 this.autoRefresh = function(callback) {
2441                         if(this.canBeAutoRefreshed() === true) {
2442                                 this.updateChart(callback);
2443                         }
2444                         else {
2445                                 if(typeof callback !== 'undefined')
2446                                         callback();
2447                         }
2448                 }
2449
2450                 this._defaultsFromDownloadedChart = function(chart) {
2451                         this.chart = chart;
2452                         this.chart_url = chart.url;
2453                         this.data_update_every = chart.update_every * 1000;
2454                         this.data_points = Math.round(this.chartWidth() / this.chartPixelsPerPoint());
2455                         this.tm.last_info_downloaded = new Date().getTime();
2456                 }
2457
2458                 // fetch the chart description from the netdata server
2459                 this.getChart = function(callback) {
2460                         this.chart = NETDATA.chartRegistry.get(this.host, this.id);
2461                         if(this.chart) {
2462                                 this._defaultsFromDownloadedChart(this.chart);
2463                                 if(typeof callback === 'function') callback();
2464                         }
2465                         else {
2466                                 this.chart_url = this.host + "/api/v1/chart?chart=" + this.id;
2467
2468                                 if(this.debug === true)
2469                                         this.log('downloading ' + this.chart_url);
2470
2471                                 $.ajax( {
2472                                         url:  this.chart_url,
2473                                         crossDomain: NETDATA.options.crossDomainAjax,
2474                                         cache: false,
2475                                         async: true
2476                                 })
2477                                 .done(function(chart) {
2478                                         chart.url = that.chart_url;
2479                                         chart.data_url = (that.host + chart.data_url);
2480                                         that._defaultsFromDownloadedChart(chart);
2481                                         NETDATA.chartRegistry.add(that.host, that.id, chart);
2482                                 })
2483                                 .fail(function() {
2484                                         NETDATA.error(404, that.chart_url);
2485                                         error('chart not found on url "' + that.chart_url + '"');
2486                                 })
2487                                 .always(function() {
2488                                         if(typeof callback === 'function') callback();
2489                                 });
2490                         }
2491                 }
2492
2493                 // ============================================================================================================
2494                 // INITIALIZATION
2495
2496                 init();
2497         }
2498
2499         // get or create a chart state, given a DOM element
2500         NETDATA.chartState = function(element) {
2501                 var state = $(element).data('netdata-state-object') || null;
2502                 if(state === null) {
2503                         state = new chartState(element);
2504                         $(element).data('netdata-state-object', state);
2505                 }
2506                 return state;
2507         }
2508
2509         // ----------------------------------------------------------------------------------------------------------------
2510         // Library functions
2511
2512         // Load a script without jquery
2513         // This is used to load jquery - after it is loaded, we use jquery
2514         NETDATA._loadjQuery = function(callback) {
2515                 if(typeof jQuery === 'undefined') {
2516                         if(NETDATA.options.debug.main_loop === true)
2517                                 console.log('loading ' + NETDATA.jQuery);
2518
2519                         var script = document.createElement('script');
2520                         script.type = 'text/javascript';
2521                         script.async = true;
2522                         script.src = NETDATA.jQuery;
2523
2524                         // script.onabort = onError;
2525                         script.onerror = function(err, t) { NETDATA.error(101, NETDATA.jQuery); };
2526                         if(typeof callback === "function")
2527                                 script.onload = callback;
2528
2529                         var s = document.getElementsByTagName('script')[0];
2530                         s.parentNode.insertBefore(script, s);
2531                 }
2532                 else if(typeof callback === "function")
2533                         callback();
2534         }
2535
2536         NETDATA._loadCSS = function(filename) {
2537                 // don't use jQuery here
2538                 // styles are loaded before jQuery
2539                 // to eliminate showing an unstyled page to the user
2540
2541                 var fileref = document.createElement("link");
2542                 fileref.setAttribute("rel", "stylesheet");
2543                 fileref.setAttribute("type", "text/css");
2544                 fileref.setAttribute("href", filename);
2545
2546                 if (typeof fileref !== 'undefined')
2547                         document.getElementsByTagName("head")[0].appendChild(fileref);
2548         }
2549
2550         NETDATA.colorHex2Rgb = function(hex) {
2551                 // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
2552                 var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
2553                         hex = hex.replace(shorthandRegex, function(m, r, g, b) {
2554                         return r + r + g + g + b + b;
2555                 });
2556
2557                 var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
2558                 return result ? {
2559                         r: parseInt(result[1], 16),
2560                         g: parseInt(result[2], 16),
2561                         b: parseInt(result[3], 16)
2562                 } : null;
2563         }
2564
2565         NETDATA.colorLuminance = function(hex, lum) {
2566                 // validate hex string
2567                 hex = String(hex).replace(/[^0-9a-f]/gi, '');
2568                 if (hex.length < 6)
2569                         hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
2570
2571                 lum = lum || 0;
2572
2573                 // convert to decimal and change luminosity
2574                 var rgb = "#", c, i;
2575                 for (i = 0; i < 3; i++) {
2576                         c = parseInt(hex.substr(i*2,2), 16);
2577                         c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
2578                         rgb += ("00"+c).substr(c.length);
2579                 }
2580
2581                 return rgb;
2582         }
2583
2584         NETDATA.guid = function() {
2585                 function s4() {
2586                         return Math.floor((1 + Math.random()) * 0x10000)
2587                                         .toString(16)
2588                                         .substring(1);
2589                         }
2590
2591                         return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
2592         }
2593
2594         NETDATA.zeropad = function(x) {
2595                 if(x > -10 && x < 10) return '0' + x.toString();
2596                 else return x.toString();
2597         }
2598
2599         // user function to signal us the DOM has been
2600         // updated.
2601         NETDATA.updatedDom = function() {
2602                 NETDATA.options.updated_dom = true;
2603         }
2604
2605         NETDATA.ready = function(callback) {
2606                 NETDATA.options.readyCallback = callback;
2607         }
2608
2609         NETDATA.pause = function(callback) {
2610                 NETDATA.options.pauseCallback = callback;
2611         }
2612
2613         NETDATA.unpause = function() {
2614                 NETDATA.options.pauseCallback = null;
2615                 NETDATA.options.updated_dom = true;
2616                 NETDATA.options.pause = false;
2617         }
2618
2619         // ----------------------------------------------------------------------------------------------------------------
2620
2621         // this is purely sequencial charts refresher
2622         // it is meant to be autonomous
2623         NETDATA.chartRefresherNoParallel = function(index) {
2624                 if(NETDATA.options.debug.mail_loop === true)
2625                         console.log('NETDATA.chartRefresherNoParallel(' + index + ')');
2626
2627                 if(NETDATA.options.updated_dom === true) {
2628                         // the dom has been updated
2629                         // get the dom parts again
2630                         NETDATA.parseDom(NETDATA.chartRefresher);
2631                         return;
2632                 }
2633                 if(index >= NETDATA.options.targets.length) {
2634                         if(NETDATA.options.debug.main_loop === true)
2635                                 console.log('waiting to restart main loop...');
2636
2637                         NETDATA.options.auto_refresher_fast_weight = 0;
2638
2639                         setTimeout(function() {
2640                                 NETDATA.chartRefresher();
2641                         }, NETDATA.options.current.idle_between_loops);
2642                 }
2643                 else {
2644                         var state = NETDATA.options.targets[index];
2645
2646                         if(NETDATA.options.auto_refresher_fast_weight < NETDATA.options.current.fast_render_timeframe) {
2647                                 if(NETDATA.options.debug.main_loop === true)
2648                                         console.log('fast rendering...');
2649
2650                                 state.autoRefresh(function() {
2651                                         NETDATA.chartRefresherNoParallel(++index);
2652                                 });
2653                         }
2654                         else {
2655                                 if(NETDATA.options.debug.main_loop === true) console.log('waiting for next refresh...');
2656                                 NETDATA.options.auto_refresher_fast_weight = 0;
2657
2658                                 setTimeout(function() {
2659                                         state.autoRefresh(function() {
2660                                                 NETDATA.chartRefresherNoParallel(++index);
2661                                         });
2662                                 }, NETDATA.options.current.idle_between_charts);
2663                         }
2664                 }
2665         }
2666
2667         // this is part of the parallel refresher
2668         // its cause is to refresh sequencially all the charts
2669         // that depend on chart library initialization
2670         // it will call the parallel refresher back
2671         // as soon as it sees a chart that its chart library
2672         // is initialized
2673         NETDATA.chartRefresher_unitialized = function() {
2674                 if(NETDATA.options.updated_dom === true) {
2675                         // the dom has been updated
2676                         // get the dom parts again
2677                         NETDATA.parseDom(NETDATA.chartRefresher);
2678                         return;
2679                 }
2680
2681                 if(NETDATA.options.sequencial.length === 0)
2682                         NETDATA.chartRefresher();
2683                 else {
2684                         var state = NETDATA.options.sequencial.pop();
2685                         if(state.library.initialized === true)
2686                                 NETDATA.chartRefresher();
2687                         else
2688                                 state.autoRefresh(NETDATA.chartRefresher_unitialized);
2689                 }
2690         }
2691
2692         NETDATA.chartRefresherWaitTime = function() {
2693                 return NETDATA.options.current.idle_parallel_loops;
2694         }
2695
2696         // the default refresher
2697         // it will create 2 sets of charts:
2698         // - the ones that can be refreshed in parallel
2699         // - the ones that depend on something else
2700         // the first set will be executed in parallel
2701         // the second will be given to NETDATA.chartRefresher_unitialized()
2702         NETDATA.chartRefresher = function() {
2703                 if(NETDATA.options.pause === true) {
2704                         // console.log('auto-refresher is paused');
2705                         setTimeout(NETDATA.chartRefresher,
2706                                 NETDATA.chartRefresherWaitTime());
2707                         return;
2708                 }
2709
2710                 if(typeof NETDATA.options.pauseCallback === 'function') {
2711                         // console.log('auto-refresher is calling pauseCallback');
2712                         NETDATA.options.pause = true;
2713                         NETDATA.options.pauseCallback();
2714                         NETDATA.chartRefresher();
2715                         return;
2716                 }
2717
2718                 if(NETDATA.options.current.parallel_refresher === false) {
2719                         NETDATA.chartRefresherNoParallel(0);
2720                         return;
2721                 }
2722
2723                 if(NETDATA.options.updated_dom === true) {
2724                         // the dom has been updated
2725                         // get the dom parts again
2726                         NETDATA.parseDom(NETDATA.chartRefresher);
2727                         return;
2728                 }
2729
2730                 var parallel = new Array();
2731                 var targets = NETDATA.options.targets;
2732                 var len = targets.length;
2733                 while(len--) {
2734                         if(targets[len].isVisible() === false)
2735                                 continue;
2736
2737                         var state = targets[len];
2738                         if(state.library.initialized === false) {
2739                                 if(state.library.enabled === true) {
2740                                         state.library.initialize(NETDATA.chartRefresher);
2741                                         return;
2742                                 }
2743                                 else {
2744                                         state.error('chart library "' + state.library_name + '" is not enabled.');
2745                                 }
2746                         }
2747
2748                         parallel.unshift(state);
2749                 }
2750
2751                 if(parallel.length > 0) {
2752                         var parallel_jobs = parallel.length;
2753
2754                         // this will execute the jobs in parallel
2755                         $(parallel).each(function() {
2756                                 this.autoRefresh(function() {
2757                                         parallel_jobs--;
2758
2759                                         if(parallel_jobs === 0) {
2760                                                 setTimeout(NETDATA.chartRefresher,
2761                                                         NETDATA.chartRefresherWaitTime());
2762                                         }
2763                                 });
2764                         })
2765                 }
2766                 else {
2767                         setTimeout(NETDATA.chartRefresher,
2768                                 NETDATA.chartRefresherWaitTime());
2769                 }
2770         }
2771
2772         NETDATA.parseDom = function(callback) {
2773                 NETDATA.options.last_page_scroll = new Date().getTime();
2774                 NETDATA.options.updated_dom = false;
2775
2776                 var targets = $('div[data-netdata]').filter(':visible');
2777
2778                 if(NETDATA.options.debug.main_loop === true)
2779                         console.log('DOM updated - there are ' + targets.length + ' charts on page.');
2780
2781                 NETDATA.options.targets = new Array();
2782                 var len = targets.length;
2783                 while(len--) {
2784                         // the initialization will take care of sizing
2785                         // and the "loading..." message
2786                         NETDATA.options.targets.push(NETDATA.chartState(targets[len]));
2787                 }
2788
2789                 if(typeof callback === 'function') callback();
2790         }
2791
2792         // this is the main function - where everything starts
2793         NETDATA.start = function() {
2794                 // this should be called only once
2795
2796                 NETDATA.options.page_is_visible = true;
2797
2798                 $(window).blur(function() {
2799                         if(NETDATA.options.current.stop_updates_when_focus_is_lost === true) {
2800                                 NETDATA.options.page_is_visible = false;
2801                                 if(NETDATA.options.debug.focus === true)
2802                                         console.log('Lost Focus!');
2803                         }
2804                 });
2805
2806                 $(window).focus(function() {
2807                         if(NETDATA.options.current.stop_updates_when_focus_is_lost === true) {
2808                                 NETDATA.options.page_is_visible = true;
2809                                 if(NETDATA.options.debug.focus === true)
2810                                         console.log('Focus restored!');
2811                         }
2812                 });
2813
2814                 if(typeof document.hasFocus === 'function' && !document.hasFocus()) {
2815                         if(NETDATA.options.current.stop_updates_when_focus_is_lost === true) {
2816                                 NETDATA.options.page_is_visible = false;
2817                                 if(NETDATA.options.debug.focus === true)
2818                                         console.log('Document has no focus!');
2819                         }
2820                 }
2821
2822                 NETDATA.parseDom(NETDATA.chartRefresher);
2823         }
2824
2825         // ----------------------------------------------------------------------------------------------------------------
2826         // peity
2827
2828         NETDATA.peityInitialize = function(callback) {
2829                 if(typeof netdataNoPeitys === 'undefined' || !netdataNoPeitys) {
2830                         $.ajax({
2831                                 url: NETDATA.peity_js,
2832                                 cache: true,
2833                                 dataType: "script"
2834                         })
2835                         .done(function() {
2836                                 NETDATA.registerChartLibrary('peity', NETDATA.peity_js);
2837                         })
2838                         .fail(function() {
2839                                 NETDATA.chartLibraries.peity.enabled = false;
2840                                 NETDATA.error(100, NETDATA.peity_js);
2841                         })
2842                         .always(function() {
2843                                 if(typeof callback === "function")
2844                                         callback();
2845                         });
2846                 }
2847                 else {
2848                         NETDATA.chartLibraries.peity.enabled = false;
2849                         if(typeof callback === "function")
2850                                 callback();
2851                 }
2852         };
2853
2854         NETDATA.peityChartUpdate = function(state, data) {
2855                 state.peity_instance.innerHTML = data.result;
2856
2857                 if(state.peity_options.stroke !== state.chartColors()[0]) {
2858                         state.peity_options.stroke = state.chartColors()[0];
2859                         if(state.chart.chart_type === 'line')
2860                                 state.peity_options.fill = '#FFF';
2861                         else
2862                                 state.peity_options.fill = NETDATA.colorLuminance(state.chartColors()[0], NETDATA.chartDefaults.fill_luminance);
2863                 }
2864
2865                 $(state.peity_instance).peity('line', state.peity_options);
2866         }
2867
2868         NETDATA.peityChartCreate = function(state, data) {
2869                 state.peity_instance = document.createElement('div');
2870                 state.element_chart.appendChild(state.peity_instance);
2871
2872                 var self = $(state.element);
2873                 state.peity_options = {
2874                         stroke: '#000',
2875                         strokeWidth: self.data('peity-strokewidth') || 1,
2876                         width: state.chartWidth(),
2877                         height: state.chartHeight(),
2878                         fill: '#000'
2879                 };
2880
2881                 NETDATA.peityChartUpdate(state, data);
2882         }
2883
2884         // ----------------------------------------------------------------------------------------------------------------
2885         // sparkline
2886
2887         NETDATA.sparklineInitialize = function(callback) {
2888                 if(typeof netdataNoSparklines === 'undefined' || !netdataNoSparklines) {
2889                         $.ajax({
2890                                 url: NETDATA.sparkline_js,
2891                                 cache: true,
2892                                 dataType: "script"
2893                         })
2894                         .done(function() {
2895                                 NETDATA.registerChartLibrary('sparkline', NETDATA.sparkline_js);
2896                         })
2897                         .fail(function() {
2898                                 NETDATA.chartLibraries.sparkline.enabled = false;
2899                                 NETDATA.error(100, NETDATA.sparkline_js);
2900                         })
2901                         .always(function() {
2902                                 if(typeof callback === "function")
2903                                         callback();
2904                         });
2905                 }
2906                 else {
2907                         NETDATA.chartLibraries.sparkline.enabled = false;
2908                         if(typeof callback === "function") 
2909                                 callback();
2910                 }
2911         };
2912
2913         NETDATA.sparklineChartUpdate = function(state, data) {
2914                 state.sparkline_options.width = state.chartWidth();
2915                 state.sparkline_options.height = state.chartHeight();
2916
2917                 $(state.element_chart).sparkline(data.result, state.sparkline_options);
2918         }
2919
2920         NETDATA.sparklineChartCreate = function(state, data) {
2921                 var self = $(state.element);
2922                 var type = self.data('sparkline-type') || 'line';
2923                 var lineColor = self.data('sparkline-linecolor') || state.chartColors()[0];
2924                 var fillColor = self.data('sparkline-fillcolor') || (state.chart.chart_type === 'line')?'#FFF':NETDATA.colorLuminance(lineColor, NETDATA.chartDefaults.fill_luminance);
2925                 var chartRangeMin = self.data('sparkline-chartrangemin') || undefined;
2926                 var chartRangeMax = self.data('sparkline-chartrangemax') || undefined;
2927                 var composite = self.data('sparkline-composite') || undefined;
2928                 var enableTagOptions = self.data('sparkline-enabletagoptions') || undefined;
2929                 var tagOptionPrefix = self.data('sparkline-tagoptionprefix') || undefined;
2930                 var tagValuesAttribute = self.data('sparkline-tagvaluesattribute') || undefined;
2931                 var disableHiddenCheck = self.data('sparkline-disablehiddencheck') || undefined;
2932                 var defaultPixelsPerValue = self.data('sparkline-defaultpixelspervalue') || undefined;
2933                 var spotColor = self.data('sparkline-spotcolor') || undefined;
2934                 var minSpotColor = self.data('sparkline-minspotcolor') || undefined;
2935                 var maxSpotColor = self.data('sparkline-maxspotcolor') || undefined;
2936                 var spotRadius = self.data('sparkline-spotradius') || undefined;
2937                 var valueSpots = self.data('sparkline-valuespots') || undefined;
2938                 var highlightSpotColor = self.data('sparkline-highlightspotcolor') || undefined;
2939                 var highlightLineColor = self.data('sparkline-highlightlinecolor') || undefined;
2940                 var lineWidth = self.data('sparkline-linewidth') || undefined;
2941                 var normalRangeMin = self.data('sparkline-normalrangemin') || undefined;
2942                 var normalRangeMax = self.data('sparkline-normalrangemax') || undefined;
2943                 var drawNormalOnTop = self.data('sparkline-drawnormalontop') || undefined;
2944                 var xvalues = self.data('sparkline-xvalues') || undefined;
2945                 var chartRangeClip = self.data('sparkline-chartrangeclip') || undefined;
2946                 var xvalues = self.data('sparkline-xvalues') || undefined;
2947                 var chartRangeMinX = self.data('sparkline-chartrangeminx') || undefined;
2948                 var chartRangeMaxX = self.data('sparkline-chartrangemaxx') || undefined;
2949                 var disableInteraction = self.data('sparkline-disableinteraction') || false;
2950                 var disableTooltips = self.data('sparkline-disabletooltips') || false;
2951                 var disableHighlight = self.data('sparkline-disablehighlight') || false;
2952                 var highlightLighten = self.data('sparkline-highlightlighten') || 1.4;
2953                 var highlightColor = self.data('sparkline-highlightcolor') || undefined;
2954                 var tooltipContainer = self.data('sparkline-tooltipcontainer') || undefined;
2955                 var tooltipClassname = self.data('sparkline-tooltipclassname') || undefined;
2956                 var tooltipFormat = self.data('sparkline-tooltipformat') || undefined;
2957                 var tooltipPrefix = self.data('sparkline-tooltipprefix') || undefined;
2958                 var tooltipSuffix = self.data('sparkline-tooltipsuffix') || ' ' + state.chart.units;
2959                 var tooltipSkipNull = self.data('sparkline-tooltipskipnull') || true;
2960                 var tooltipValueLookups = self.data('sparkline-tooltipvaluelookups') || undefined;
2961                 var tooltipFormatFieldlist = self.data('sparkline-tooltipformatfieldlist') || undefined;
2962                 var tooltipFormatFieldlistKey = self.data('sparkline-tooltipformatfieldlistkey') || undefined;
2963                 var numberFormatter = self.data('sparkline-numberformatter') || function(n){ return n.toFixed(2); };
2964                 var numberDigitGroupSep = self.data('sparkline-numberdigitgroupsep') || undefined;
2965                 var numberDecimalMark = self.data('sparkline-numberdecimalmark') || undefined;
2966                 var numberDigitGroupCount = self.data('sparkline-numberdigitgroupcount') || undefined;
2967                 var animatedZooms = self.data('sparkline-animatedzooms') || false;
2968
2969                 state.sparkline_options = {
2970                         type: type,
2971                         lineColor: lineColor,
2972                         fillColor: fillColor,
2973                         chartRangeMin: chartRangeMin,
2974                         chartRangeMax: chartRangeMax,
2975                         composite: composite,
2976                         enableTagOptions: enableTagOptions,
2977                         tagOptionPrefix: tagOptionPrefix,
2978                         tagValuesAttribute: tagValuesAttribute,
2979                         disableHiddenCheck: disableHiddenCheck,
2980                         defaultPixelsPerValue: defaultPixelsPerValue,
2981                         spotColor: spotColor,
2982                         minSpotColor: minSpotColor,
2983                         maxSpotColor: maxSpotColor,
2984                         spotRadius: spotRadius,
2985                         valueSpots: valueSpots,
2986                         highlightSpotColor: highlightSpotColor,
2987                         highlightLineColor: highlightLineColor,
2988                         lineWidth: lineWidth,
2989                         normalRangeMin: normalRangeMin,
2990                         normalRangeMax: normalRangeMax,
2991                         drawNormalOnTop: drawNormalOnTop,
2992                         xvalues: xvalues,
2993                         chartRangeClip: chartRangeClip,
2994                         chartRangeMinX: chartRangeMinX,
2995                         chartRangeMaxX: chartRangeMaxX,
2996                         disableInteraction: disableInteraction,
2997                         disableTooltips: disableTooltips,
2998                         disableHighlight: disableHighlight,
2999                         highlightLighten: highlightLighten,
3000                         highlightColor: highlightColor,
3001                         tooltipContainer: tooltipContainer,
3002                         tooltipClassname: tooltipClassname,
3003                         tooltipChartTitle: state.chart.title,
3004                         tooltipFormat: tooltipFormat,
3005                         tooltipPrefix: tooltipPrefix,
3006                         tooltipSuffix: tooltipSuffix,
3007                         tooltipSkipNull: tooltipSkipNull,
3008                         tooltipValueLookups: tooltipValueLookups,
3009                         tooltipFormatFieldlist: tooltipFormatFieldlist,
3010                         tooltipFormatFieldlistKey: tooltipFormatFieldlistKey,
3011                         numberFormatter: numberFormatter,
3012                         numberDigitGroupSep: numberDigitGroupSep,
3013                         numberDecimalMark: numberDecimalMark,
3014                         numberDigitGroupCount: numberDigitGroupCount,
3015                         animatedZooms: animatedZooms,
3016                         width: state.chartWidth(),
3017                         height: state.chartHeight()
3018                 };
3019
3020                 $(state.element_chart).sparkline(data.result, state.sparkline_options);
3021         };
3022
3023         // ----------------------------------------------------------------------------------------------------------------
3024         // dygraph
3025
3026         NETDATA.dygraph = {
3027                 smooth: false
3028         };
3029
3030         NETDATA.dygraphSetSelection = function(state, t) {
3031                 if(typeof state.dygraph_instance !== 'undefined') {
3032                         var r = state.calculateRowForTime(t);
3033                         if(r !== -1)
3034                                 state.dygraph_instance.setSelection(r);
3035                         else {
3036                                 state.dygraph_instance.clearSelection();
3037                                 state.legendShowUndefined();
3038                         }
3039                 }
3040
3041                 return true;
3042         }
3043
3044         NETDATA.dygraphClearSelection = function(state, t) {
3045                 if(typeof state.dygraph_instance !== 'undefined') {
3046                         state.dygraph_instance.clearSelection();
3047                 }
3048                 return true;
3049         }
3050
3051         NETDATA.dygraphSmoothInitialize = function(callback) {
3052                 $.ajax({
3053                         url: NETDATA.dygraph_smooth_js,
3054                         cache: true,
3055                         dataType: "script"
3056                 })
3057                 .done(function() {
3058                         NETDATA.dygraph.smooth = true;
3059                         smoothPlotter.smoothing = 0.3;
3060                 })
3061                 .fail(function() {
3062                         NETDATA.dygraph.smooth = false;
3063                 })
3064                 .always(function() {
3065                         if(typeof callback === "function")
3066                                 callback();
3067                 });
3068         }
3069
3070         NETDATA.dygraphInitialize = function(callback) {
3071                 if(typeof netdataNoDygraphs === 'undefined' || !netdataNoDygraphs) {
3072                         $.ajax({
3073                                 url: NETDATA.dygraph_js,
3074                                 cache: true,
3075                                 dataType: "script"
3076                         })
3077                         .done(function() {
3078                                 NETDATA.registerChartLibrary('dygraph', NETDATA.dygraph_js);
3079                         })
3080                         .fail(function() {
3081                                 NETDATA.chartLibraries.dygraph.enabled = false;
3082                                 NETDATA.error(100, NETDATA.dygraph_js);
3083                         })
3084                         .always(function() {
3085                                 if(NETDATA.chartLibraries.dygraph.enabled === true && NETDATA.options.current.smooth_plot === true)
3086                                         NETDATA.dygraphSmoothInitialize(callback);
3087                                 else if(typeof callback === "function")
3088                                         callback();
3089                         });
3090                 }
3091                 else {
3092                         NETDATA.chartLibraries.dygraph.enabled = false;
3093                         if(typeof callback === "function")
3094                                 callback();
3095                 }
3096         };
3097
3098         NETDATA.dygraphChartUpdate = function(state, data) {
3099                 var dygraph = state.dygraph_instance;
3100
3101                 if(typeof dygraph === 'undefined')
3102                         NETDATA.dygraphChartCreate(state, data);
3103
3104                 // when the chart is not visible, and hidden
3105                 // if there is a window resize, dygraph detects
3106                 // its element size as 0x0.
3107                 // this will make it re-appear properly
3108
3109                 if(state.tm.last_unhidden > state.dygraph_last_rendered)
3110                         dygraph.resize();
3111
3112                 var options = {
3113                                 file: data.result.data,
3114                                 colors: state.chartColors(),
3115                                 labels: data.result.labels,
3116                                 labelsDivWidth: state.chartWidth() - 70,
3117                                 visibility: state.dimensions_visibility.selected2BooleanArray(state.data.dimension_names)
3118                 }
3119
3120                 if(state.current.name === 'pan') {
3121                         if(NETDATA.options.debug.dygraph === true || state.debug === true)
3122                                 state.log('dygraphChartUpdate() loose update');
3123                 }
3124                 else {
3125                         if(NETDATA.options.debug.dygraph === true || state.debug === true)
3126                                 state.log('dygraphChartUpdate() strict update');
3127
3128                         options.dateWindow = null;
3129                         options.valueRange = null;
3130                 }
3131
3132                 if(state.dygraph_smooth_eligible === true) {
3133                         if((NETDATA.options.current.smooth_plot === true && state.dygraph_options.plotter !== smoothPlotter)
3134                                 || (NETDATA.options.current.smooth_plot === false && state.dygraph_options.plotter === smoothPlotter)) {
3135                                 NETDATA.dygraphChartCreate(state, data);
3136                                 return;
3137                         }
3138                 }
3139
3140                 dygraph.updateOptions(options);
3141                 state.dygraph_last_rendered = new Date().getTime();
3142         };
3143
3144         NETDATA.dygraphChartCreate = function(state, data) {
3145                 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3146                         state.log('dygraphChartCreate()');
3147
3148                 var self = $(state.element);
3149
3150                 var chart_type = state.chart.chart_type;
3151                 if(chart_type === 'stacked' && data.dimensions === 1) chart_type = 'area';
3152                 chart_type = self.data('dygraph-type') || chart_type;
3153
3154                 var smooth = (chart_type === 'line' && !NETDATA.chartLibraries.dygraph.isSparkline(state))?true:false;
3155                 smooth = self.data('dygraph-smooth') || smooth;
3156
3157                 if(NETDATA.dygraph.smooth === false)
3158                         smooth = false;
3159
3160                 var strokeWidth = (chart_type === 'stacked')?0.1:((smooth)?1.5:0.7)
3161                 var highlightCircleSize = (NETDATA.chartLibraries.dygraph.isSparkline(state))?3:4;
3162
3163                 state.dygraph_options = {
3164                         colors: self.data('dygraph-colors') || state.chartColors(),
3165
3166                         // leave a few pixels empty on the right of the chart
3167                         rightGap: self.data('dygraph-rightgap') || 5,
3168                         showRangeSelector: self.data('dygraph-showrangeselector') || false,
3169                         showRoller: self.data('dygraph-showroller') || false,
3170
3171                         title: self.data('dygraph-title') || state.chart.title,
3172                         titleHeight: self.data('dygraph-titleheight') || 19,
3173
3174                         legend: self.data('dygraph-legend') || 'always', // 'onmouseover',
3175                         labels: data.result.labels,
3176                         labelsDiv: self.data('dygraph-labelsdiv') || state.element_legend_childs.hidden,
3177                         labelsDivStyles: self.data('dygraph-labelsdivstyles') || { 'fontSize':'1px' },
3178                         labelsDivWidth: self.data('dygraph-labelsdivwidth') || state.chartWidth() - 70,
3179                         labelsSeparateLines: self.data('dygraph-labelsseparatelines') || true,
3180                         labelsShowZeroValues: self.data('dygraph-labelsshowzerovalues') || true,
3181                         labelsKMB: false,
3182                         labelsKMG2: false,
3183                         showLabelsOnHighlight: self.data('dygraph-showlabelsonhighlight') || true,
3184                         hideOverlayOnMouseOut: self.data('dygraph-hideoverlayonmouseout') || true,
3185
3186                         ylabel: state.chart.units,
3187                         yLabelWidth: self.data('dygraph-ylabelwidth') || 12,
3188
3189                         // the function to plot the chart
3190                         plotter: null,
3191
3192                         // The width of the lines connecting data points. This can be used to increase the contrast or some graphs.
3193                         strokeWidth: self.data('dygraph-strokewidth') || strokeWidth,
3194                         strokePattern: self.data('dygraph-strokepattern') || undefined,
3195
3196                         // The size of the dot to draw on each point in pixels (see drawPoints). A dot is always drawn when a point is "isolated",
3197                         // i.e. there is a missing point on either side of it. This also controls the size of those dots.
3198                         drawPoints: self.data('dygraph-drawpoints') || false,
3199
3200                         // Draw points at the edges of gaps in the data. This improves visibility of small data segments or other data irregularities.
3201                         drawGapEdgePoints: self.data('dygraph-drawgapedgepoints') || true,
3202
3203                         connectSeparatedPoints: self.data('dygraph-connectseparatedpoints') || false,
3204                         pointSize: self.data('dygraph-pointsize') || 1,
3205
3206                         // enabling this makes the chart with little square lines
3207                         stepPlot: self.data('dygraph-stepplot') || false,
3208
3209                         // Draw a border around graph lines to make crossing lines more easily distinguishable. Useful for graphs with many lines.
3210                         strokeBorderColor: self.data('dygraph-strokebordercolor') || 'white',
3211                         strokeBorderWidth: self.data('dygraph-strokeborderwidth') || (chart_type === 'stacked')?0.0:0.0,
3212
3213                         fillGraph: self.data('dygraph-fillgraph') || (chart_type === 'area' || chart_type === 'stacked')?true:false,
3214                         fillAlpha: self.data('dygraph-fillalpha') || (chart_type === 'stacked')?NETDATA.options.current.color_fill_opacity_stacked:NETDATA.options.current.color_fill_opacity_area,
3215                         stackedGraph: self.data('dygraph-stackedgraph') || (chart_type === 'stacked')?true:false,
3216                         stackedGraphNaNFill: self.data('dygraph-stackedgraphnanfill') || 'none',
3217
3218                         drawAxis: self.data('dygraph-drawaxis') || true,
3219                         axisLabelFontSize: self.data('dygraph-axislabelfontsize') || 10,
3220                         axisLineColor: self.data('dygraph-axislinecolor') || '#CCC',
3221                         axisLineWidth: self.data('dygraph-axislinewidth') || 0.3,
3222
3223                         drawGrid: self.data('dygraph-drawgrid') || true,
3224                         drawXGrid: self.data('dygraph-drawxgrid') || undefined,
3225                         drawYGrid: self.data('dygraph-drawygrid') || undefined,
3226                         gridLinePattern: self.data('dygraph-gridlinepattern') || null,
3227                         gridLineWidth: self.data('dygraph-gridlinewidth') || 0.3,
3228                         gridLineColor: self.data('dygraph-gridlinecolor') || '#DDD',
3229
3230                         maxNumberWidth: self.data('dygraph-maxnumberwidth') || 8,
3231                         sigFigs: self.data('dygraph-sigfigs') || null,
3232                         digitsAfterDecimal: self.data('dygraph-digitsafterdecimal') || 2,
3233                         valueFormatter: self.data('dygraph-valueformatter') || function(x){ return x.toFixed(2); },
3234
3235                         highlightCircleSize: self.data('dygraph-highlightcirclesize') || highlightCircleSize,
3236                         highlightSeriesOpts: self.data('dygraph-highlightseriesopts') || null, // TOO SLOW: { strokeWidth: 1.5 },
3237                         highlightSeriesBackgroundAlpha: self.data('dygraph-highlightseriesbackgroundalpha') || null, // TOO SLOW: (chart_type === 'stacked')?0.7:0.5,
3238
3239                         pointClickCallback: self.data('dygraph-pointclickcallback') || undefined,
3240                         visibility: state.dimensions_visibility.selected2BooleanArray(state.data.dimension_names),
3241                         axes: {
3242                                 x: {
3243                                         pixelsPerLabel: 50,
3244                                         ticker: Dygraph.dateTicker,
3245                                         axisLabelFormatter: function (d, gran) {
3246                                                 return NETDATA.zeropad(d.getHours()) + ":" + NETDATA.zeropad(d.getMinutes()) + ":" + NETDATA.zeropad(d.getSeconds());
3247                                         },
3248                                         valueFormatter: function (ms) {
3249                                                 var d = new Date(ms);
3250                                                 return d.toLocaleDateString() + ' ' + d.toLocaleTimeString();
3251                                                 // return NETDATA.zeropad(d.getHours()) + ":" + NETDATA.zeropad(d.getMinutes()) + ":" + NETDATA.zeropad(d.getSeconds());
3252                                         }
3253                                 },
3254                                 y: {
3255                                         pixelsPerLabel: 15,
3256                                         valueFormatter: function (x) {
3257                                                 // we format legends with the state object
3258                                                 // no need to do anything here
3259                                                 // return (Math.round(x*100) / 100).toLocaleString();
3260                                                 // return state.legendFormatValue(x);
3261                                                 return x;
3262                                         }
3263                                 }
3264                         },
3265                         legendFormatter: function(data) {
3266                                 var g = data.dygraph;
3267                                 var html;
3268                                 var elements = state.element_legend_childs;
3269
3270                                 // if the hidden div is not there
3271                                 // we are not managing the legend
3272                                 if(elements.hidden === null) return;
3273
3274                                 if (typeof data.x === 'undefined') {
3275                                         //state.legendReset();
3276                                 }
3277                                 else {
3278                                         state.legendSetDate(data.x);
3279                                         var i = data.series.length;
3280                                         while(i--) {
3281                                                 var series = data.series[i];
3282                                                 if(!series.isVisible) continue;
3283                                                 state.legendSetLabelValue(series.label, series.y);
3284                                         }
3285                                 }
3286
3287                                 return '';
3288                         },
3289                         drawCallback: function(dygraph, is_initial) {
3290                                 if(state.current.name !== 'auto') {
3291                                         if(NETDATA.options.debug.dygraph === true)
3292                                                 state.log('dygraphDrawCallback()');
3293
3294                                         var first = state.data.first_entry * 1000;
3295                                         var last = state.data.last_entry * 1000;
3296
3297                                         var x_range = dygraph.xAxisRange();
3298                                         var after = Math.round(x_range[0]);
3299                                         var before = Math.round(x_range[1]);
3300
3301                                         if(before <= last && after >= first)
3302                                                 state.updateChartPanOrZoom(after, before);
3303                                 }
3304                         },
3305                         zoomCallback: function(minDate, maxDate, yRanges) {
3306                                 if(NETDATA.options.debug.dygraph === true)
3307                                         state.log('dygraphZoomCallback()');
3308
3309                                 state.globalSelectionSyncStop();
3310                                 state.globalSelectionSyncDelay();
3311
3312                                 if(state.updateChartPanOrZoom(minDate, maxDate) == false) {
3313                                         // we should not zoom that much
3314                                         state.dygraph_instance.updateOptions({
3315                                                 dateWindow: null,
3316                                                 valueRange: null
3317                                         });
3318                                 }
3319                         },
3320                         highlightCallback: function(event, x, points, row, seriesName) {
3321                                 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3322                                         state.log('dygraphHighlightCallback()');
3323
3324                                 state.pauseChart();
3325
3326                                 // there is a bug in dygraph when the chart is zoomed enough
3327                                 // the time it thinks is selected is wrong
3328                                 // here we calculate the time t based on the row number selected
3329                                 // which is ok
3330                                 var t = state.data_after + row * state.data_update_every;
3331                                 // 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);
3332
3333                                 state.globalSelectionSync(t);
3334
3335                                 // fix legend zIndex using the internal structures of dygraph legend module
3336                                 // this works, but it is a hack!
3337                                 // state.dygraph_instance.plugins_[0].plugin.legend_div_.style.zIndex = 10000;
3338                         },
3339                         unhighlightCallback: function(event) {
3340                                 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3341                                         state.log('dygraphUnhighlightCallback()');
3342
3343                                 state.unpauseChart();
3344                                 state.globalSelectionSyncStop();
3345                         },
3346                         interactionModel : {
3347                                 mousedown: function(event, dygraph, context) {
3348                                         if(NETDATA.options.debug.dygraph === true || state.debug === true)
3349                                                 state.log('interactionModel.mousedown()');
3350
3351                                         state.globalSelectionSyncStop();
3352
3353                                         if(NETDATA.options.debug.dygraph === true)
3354                                                 state.log('dygraphMouseDown()');
3355
3356                                         // Right-click should not initiate a zoom.
3357                                         if(event.button && event.button === 2) return;
3358
3359                                         context.initializeMouseDown(event, dygraph, context);
3360
3361                                         if(event.button && event.button === 1) {
3362                                                 if (event.altKey || event.shiftKey) {
3363                                                         state.setMode('pan');
3364                                                         state.globalSelectionSyncDelay();
3365                                                         Dygraph.startPan(event, dygraph, context);
3366                                                 }
3367                                                 else {
3368                                                         state.setMode('zoom');
3369                                                         state.globalSelectionSyncDelay();
3370                                                         Dygraph.startZoom(event, dygraph, context);
3371                                                 }
3372                                         }
3373                                         else {
3374                                                 if (event.altKey || event.shiftKey) {
3375                                                         state.setMode('zoom');
3376                                                         state.globalSelectionSyncDelay();
3377                                                         Dygraph.startZoom(event, dygraph, context);
3378                                                 }
3379                                                 else {
3380                                                         state.setMode('pan');
3381                                                         state.globalSelectionSyncDelay();
3382                                                         Dygraph.startPan(event, dygraph, context);
3383                                                 }
3384                                         }
3385                                 },
3386                                 mousemove: function(event, dygraph, context) {
3387                                         if(NETDATA.options.debug.dygraph === true || state.debug === true)
3388                                                 state.log('interactionModel.mousemove()');
3389
3390                                         if(context.isPanning) {
3391                                                 state.globalSelectionSyncStop();
3392                                                 state.globalSelectionSyncDelay();
3393                                                 state.setMode('pan');
3394                                                 Dygraph.movePan(event, dygraph, context);
3395                                         }
3396                                         else if(context.isZooming) {
3397                                                 state.globalSelectionSyncStop();
3398                                                 state.globalSelectionSyncDelay();
3399                                                 state.setMode('zoom');
3400                                                 Dygraph.moveZoom(event, dygraph, context);
3401                                         }
3402                                 },
3403                                 mouseup: function(event, dygraph, context) {
3404                                         if(NETDATA.options.debug.dygraph === true || state.debug === true)
3405                                                 state.log('interactionModel.mouseup()');
3406
3407                                         if (context.isPanning) {
3408                                                 state.globalSelectionSyncDelay();
3409                                                 Dygraph.endPan(event, dygraph, context);
3410                                         }
3411                                         else if (context.isZooming) {
3412                                                 state.globalSelectionSyncDelay();
3413                                                 Dygraph.endZoom(event, dygraph, context);
3414                                         }
3415                                 },
3416                                 click: function(event, dygraph, context) {
3417                                         if(NETDATA.options.debug.dygraph === true || state.debug === true)
3418                                                 state.log('interactionModel.click()');
3419
3420                                         event.preventDefault();
3421                                 },
3422                                 dblclick: function(event, dygraph, context) {
3423                                         if(NETDATA.options.debug.dygraph === true || state.debug === true)
3424                                                 state.log('interactionModel.dblclick()');
3425
3426                                         state.globalSelectionSyncStop();
3427                                         NETDATA.globalPanAndZoom.clearMaster();
3428                                         state.resetChart();
3429                                 },
3430                                 mousewheel: function(event, dygraph, context) {
3431                                         if(NETDATA.options.debug.dygraph === true || state.debug === true)
3432                                                 state.log('interactionModel.mousewheel()');
3433
3434                                         // Take the offset of a mouse event on the dygraph canvas and
3435                                         // convert it to a pair of percentages from the bottom left. 
3436                                         // (Not top left, bottom is where the lower value is.)
3437                                         function offsetToPercentage(g, offsetX, offsetY) {
3438                                                 // This is calculating the pixel offset of the leftmost date.
3439                                                 var xOffset = g.toDomCoords(g.xAxisRange()[0], null)[0];
3440                                                 var yar0 = g.yAxisRange(0);
3441
3442                                                 // This is calculating the pixel of the higest value. (Top pixel)
3443                                                 var yOffset = g.toDomCoords(null, yar0[1])[1];
3444
3445                                                 // x y w and h are relative to the corner of the drawing area,
3446                                                 // so that the upper corner of the drawing area is (0, 0).
3447                                                 var x = offsetX - xOffset;
3448                                                 var y = offsetY - yOffset;
3449
3450                                                 // This is computing the rightmost pixel, effectively defining the
3451                                                 // width.
3452                                                 var w = g.toDomCoords(g.xAxisRange()[1], null)[0] - xOffset;
3453
3454                                                 // This is computing the lowest pixel, effectively defining the height.
3455                                                 var h = g.toDomCoords(null, yar0[0])[1] - yOffset;
3456
3457                                                 // Percentage from the left.
3458                                                 var xPct = w === 0 ? 0 : (x / w);
3459                                                 // Percentage from the top.
3460                                                 var yPct = h === 0 ? 0 : (y / h);
3461
3462                                                 // The (1-) part below changes it from "% distance down from the top"
3463                                                 // to "% distance up from the bottom".
3464                                                 return [xPct, (1-yPct)];
3465                                         }
3466
3467                                         // Adjusts [x, y] toward each other by zoomInPercentage%
3468                                         // Split it so the left/bottom axis gets xBias/yBias of that change and
3469                                         // tight/top gets (1-xBias)/(1-yBias) of that change.
3470                                         //
3471                                         // If a bias is missing it splits it down the middle.
3472                                         function zoomRange(g, zoomInPercentage, xBias, yBias) {
3473                                                 xBias = xBias || 0.5;
3474                                                 yBias = yBias || 0.5;
3475
3476                                                 function adjustAxis(axis, zoomInPercentage, bias) {
3477                                                         var delta = axis[1] - axis[0];
3478                                                         var increment = delta * zoomInPercentage;
3479                                                         var foo = [increment * bias, increment * (1-bias)];
3480
3481                                                         return [ axis[0] + foo[0], axis[1] - foo[1] ];
3482                                                 }
3483
3484                                                 var yAxes = g.yAxisRanges();
3485                                                 var newYAxes = [];
3486                                                 for (var i = 0; i < yAxes.length; i++) {
3487                                                         newYAxes[i] = adjustAxis(yAxes[i], zoomInPercentage, yBias);
3488                                                 }
3489
3490                                                 return adjustAxis(g.xAxisRange(), zoomInPercentage, xBias);
3491                                         }
3492
3493                                         if(event.altKey || event.shiftKey) {
3494                                                 state.globalSelectionSyncStop();
3495                                                 state.globalSelectionSyncDelay();
3496
3497                                                 // http://dygraphs.com/gallery/interaction-api.js
3498                                                 var normal = (event.detail) ? event.detail * -1 : event.wheelDelta / 40;
3499                                                 var percentage = normal / 50;
3500
3501                                                 if (!(event.offsetX && event.offsetY)){
3502                                                         event.offsetX = event.layerX - event.target.offsetLeft;
3503                                                         event.offsetY = event.layerY - event.target.offsetTop;
3504                                                 }
3505
3506                                                 var percentages = offsetToPercentage(dygraph, event.offsetX, event.offsetY);
3507                                                 var xPct = percentages[0];
3508                                                 var yPct = percentages[1];
3509
3510                                                 var new_x_range = zoomRange(dygraph, percentage, xPct, yPct);
3511
3512                                                 var after = new_x_range[0];
3513                                                 var before = new_x_range[1];
3514
3515                                                 var first = (state.data.first_entry + state.data.view_update_every) * 1000;
3516                                                 var last = (state.data.last_entry + state.data.view_update_every) * 1000;
3517
3518                                                 if(before > last) {
3519                                                         after -= (before - last);
3520                                                         before = last;
3521                                                 }
3522                                                 if(after < first) {
3523                                                         after = first;
3524                                                 }
3525
3526                                                 state.setMode('zoom');
3527                                                 if(state.updateChartPanOrZoom(after, before) === true)
3528                                                         dygraph.updateOptions({ dateWindow: [ after, before ] });
3529
3530                                                 event.preventDefault();
3531                                         }
3532                                 },
3533                                 touchstart: function(event, dygraph, context) {
3534                                         if(NETDATA.options.debug.dygraph === true || state.debug === true)
3535                                                 state.log('interactionModel.touchstart()');
3536
3537                                         state.setMode('zoom');
3538                                         state.pauseChart();
3539
3540                                         Dygraph.defaultInteractionModel.touchstart(event, dygraph, context);
3541
3542                                         // we overwrite the touch directions at the end, to overwrite
3543                                         // the internal default of dygraphs
3544                                         context.touchDirections = { x: true, y: false };
3545
3546                                         state.dygraph_last_touch_start = new Date().getTime();
3547                                         state.dygraph_last_touch_move = 0;
3548
3549                                         if(typeof event.touches[0].pageX === 'number')
3550                                                 state.dygraph_last_touch_page_x = event.touches[0].pageX;
3551                                         else
3552                                                 state.dygraph_last_touch_page_x = 0;
3553                                 },
3554                                 touchmove: function(event, dygraph, context) {
3555                                         if(NETDATA.options.debug.dygraph === true || state.debug === true)
3556                                                 state.log('interactionModel.touchmove()');
3557
3558                                         Dygraph.defaultInteractionModel.touchmove(event, dygraph, context);
3559
3560                                         state.dygraph_last_touch_move = new Date().getTime();
3561                                 },
3562                                 touchend: function(event, dygraph, context) {
3563                                         if(NETDATA.options.debug.dygraph === true || state.debug === true)
3564                                                 state.log('interactionModel.touchend()');
3565
3566                                         Dygraph.defaultInteractionModel.touchend(event, dygraph, context);
3567
3568                                         // if it didn't move, it is a selection
3569                                         if(state.dygraph_last_touch_move === 0 && state.dygraph_last_touch_page_x !== 0) {
3570                                                 // internal api of dygraphs
3571                                                 var pct = (state.dygraph_last_touch_page_x - (dygraph.plotter_.area.x + state.element.getBoundingClientRect().left)) / dygraph.plotter_.area.w;
3572                                                 var t = Math.round(state.data_after + (state.data_before - state.data_after) * pct);
3573                                                 if(NETDATA.dygraphSetSelection(state, t) === true)
3574                                                         state.globalSelectionSync(t);
3575                                         }
3576
3577                                         // if it was double tap within double click time, reset the charts
3578                                         var now = new Date().getTime();
3579                                         if(typeof state.dygraph_last_touch_end !== 'undefined') {
3580                                                 if(state.dygraph_last_touch_move === 0) {
3581                                                         var dt = now - state.dygraph_last_touch_end;
3582                                                         if(dt <= NETDATA.options.current.double_click_speed) {
3583                                                                 state.globalSelectionSyncStop();
3584                                                                 NETDATA.globalPanAndZoom.clearMaster();
3585                                                                 state.resetChart();
3586                                                         }
3587                                                 }
3588                                         }
3589
3590                                         // remember the timestamp of the last touch end
3591                                         state.dygraph_last_touch_end = now;
3592                                 }
3593                         }
3594                 };
3595
3596                 if(NETDATA.chartLibraries.dygraph.isSparkline(state)) {
3597                         state.dygraph_options.drawGrid = false;
3598                         state.dygraph_options.drawAxis = false;
3599                         state.dygraph_options.title = undefined;
3600                         state.dygraph_options.units = undefined;
3601                         state.dygraph_options.ylabel = undefined;
3602                         state.dygraph_options.yLabelWidth = 0;
3603                         state.dygraph_options.labelsDivWidth = 120;
3604                         state.dygraph_options.labelsDivStyles.width = '120px';
3605                         state.dygraph_options.labelsSeparateLines = true;
3606                         state.dygraph_options.rightGap = 0;
3607                 }
3608
3609                 if(smooth === true) {
3610                         state.dygraph_smooth_eligible = true;
3611
3612                         if(NETDATA.options.current.smooth_plot === true)
3613                                 state.dygraph_options.plotter = smoothPlotter;
3614                 }
3615                 else state.dygraph_smooth_eligible = false;
3616
3617                 state.dygraph_instance = new Dygraph(state.element_chart,
3618                         data.result.data, state.dygraph_options);
3619
3620                 state.dygraph_last_rendered = new Date().getTime();
3621         };
3622
3623         // ----------------------------------------------------------------------------------------------------------------
3624         // morris
3625
3626         NETDATA.morrisInitialize = function(callback) {
3627                 if(typeof netdataNoMorris === 'undefined' || !netdataNoMorris) {
3628
3629                         // morris requires raphael
3630                         if(!NETDATA.chartLibraries.raphael.initialized) {
3631                                 if(NETDATA.chartLibraries.raphael.enabled) {
3632                                         NETDATA.raphaelInitialize(function() {
3633                                                 NETDATA.morrisInitialize(callback);
3634                                         });
3635                                 }
3636                                 else {
3637                                         NETDATA.chartLibraries.morris.enabled = false;
3638                                         if(typeof callback === "function")
3639                                                 callback();
3640                                 }
3641                         }
3642                         else {
3643                                 NETDATA._loadCSS(NETDATA.morris_css);
3644
3645                                 $.ajax({
3646                                         url: NETDATA.morris_js,
3647                                         cache: true,
3648                                         dataType: "script"
3649                                 })
3650                                 .done(function() {
3651                                         NETDATA.registerChartLibrary('morris', NETDATA.morris_js);
3652                                 })
3653                                 .fail(function() {
3654                                         NETDATA.chartLibraries.morris.enabled = false;
3655                                         NETDATA.error(100, NETDATA.morris_js);
3656                                 })
3657                                 .always(function() {
3658                                         if(typeof callback === "function")
3659                                                 callback();
3660                                 });
3661                         }
3662                 }
3663                 else {
3664                         NETDATA.chartLibraries.morris.enabled = false;
3665                         if(typeof callback === "function")
3666                                 callback();
3667                 }
3668         };
3669
3670         NETDATA.morrisChartUpdate = function(state, data) {
3671                 state.morris_instance.setData(data.result.data);
3672         };
3673
3674         NETDATA.morrisChartCreate = function(state, data) {
3675
3676                 state.morris_options = {
3677                                 element: state.element_chart.id,
3678                                 data: data.result.data,
3679                                 xkey: 'time',
3680                                 ykeys: data.dimension_names,
3681                                 labels: data.dimension_names,
3682                                 lineWidth: 2,
3683                                 pointSize: 3,
3684                                 smooth: true,
3685                                 hideHover: 'auto',
3686                                 parseTime: true,
3687                                 continuousLine: false,
3688                                 behaveLikeLine: false
3689                 };
3690
3691                 if(state.chart.chart_type === 'line')
3692                         state.morris_instance = new Morris.Line(state.morris_options);
3693
3694                 else if(state.chart.chart_type === 'area') {
3695                         state.morris_options.behaveLikeLine = true;
3696                         state.morris_instance = new Morris.Area(state.morris_options);
3697                 }
3698                 else // stacked
3699                         state.morris_instance = new Morris.Area(state.morris_options);
3700         };
3701
3702         // ----------------------------------------------------------------------------------------------------------------
3703         // raphael
3704
3705         NETDATA.raphaelInitialize = function(callback) {
3706                 if(typeof netdataStopRaphael === 'undefined' || !netdataStopRaphael) {
3707                         $.ajax({
3708                                 url: NETDATA.raphael_js,
3709                                 cache: true,
3710                                 dataType: "script"
3711                         })
3712                         .done(function() {
3713                                 NETDATA.registerChartLibrary('raphael', NETDATA.raphael_js);
3714                         })
3715                         .fail(function() {
3716                                 NETDATA.chartLibraries.raphael.enabled = false;
3717                                 NETDATA.error(100, NETDATA.raphael_js);
3718                         })
3719                         .always(function() {
3720                                 if(typeof callback === "function")
3721                                         callback();
3722                         });
3723                 }
3724                 else {
3725                         NETDATA.chartLibraries.raphael.enabled = false;
3726                         if(typeof callback === "function")
3727                                 callback();
3728                 }
3729         };
3730
3731         NETDATA.raphaelChartUpdate = function(state, data) {
3732                 $(state.element_chart).raphael(data.result, {
3733                         width: state.chartWidth(),
3734                         height: state.chartHeight()
3735                 })
3736         };
3737
3738         NETDATA.raphaelChartCreate = function(state, data) {
3739                 $(state.element_chart).raphael(data.result, {
3740                         width: state.chartWidth(),
3741                         height: state.chartHeight()
3742                 })
3743         };
3744
3745         // ----------------------------------------------------------------------------------------------------------------
3746         // google charts
3747
3748         NETDATA.googleInitialize = function(callback) {
3749                 if(typeof netdataNoGoogleCharts === 'undefined' || !netdataNoGoogleCharts) {
3750                         $.ajax({
3751                                 url: NETDATA.google_js,
3752                                 cache: true,
3753                                 dataType: "script"
3754                         })
3755                         .done(function() {
3756                                 NETDATA.registerChartLibrary('google', NETDATA.google_js);
3757                                 google.load('visualization', '1.1', {
3758                                         'packages': ['corechart', 'controls'],
3759                                         'callback': callback
3760                                 });
3761                         })
3762                         .fail(function() {
3763                                 NETDATA.chartLibraries.google.enabled = false;
3764                                 NETDATA.error(100, NETDATA.google_js);
3765                                 if(typeof callback === "function")
3766                                         callback();
3767                         });
3768                 }
3769                 else {
3770                         NETDATA.chartLibraries.google.enabled = false;
3771                         if(typeof callback === "function")
3772                                 callback();
3773                 }
3774         };
3775
3776         NETDATA.googleChartUpdate = function(state, data) {
3777                 var datatable = new google.visualization.DataTable(data.result);
3778                 state.google_instance.draw(datatable, state.google_options);
3779         };
3780
3781         NETDATA.googleChartCreate = function(state, data) {
3782                 var datatable = new google.visualization.DataTable(data.result);
3783
3784                 state.google_options = {
3785                         colors: state.chartColors(),
3786
3787                         // do not set width, height - the chart resizes itself
3788                         //width: state.chartWidth(),
3789                         //height: state.chartHeight(),
3790                         lineWidth: 1,
3791                         title: state.chart.title,
3792                         fontSize: 11,
3793                         hAxis: {
3794                         //      title: "Time of Day",
3795                         //      format:'HH:mm:ss',
3796                                 viewWindowMode: 'maximized',
3797                                 slantedText: false,
3798                                 format:'HH:mm:ss',
3799                                 textStyle: {
3800                                         fontSize: 9
3801                                 },
3802                                 gridlines: {
3803                                         color: '#EEE'
3804                                 }
3805                         },
3806                         vAxis: {
3807                                 title: state.chart.units,
3808                                 viewWindowMode: 'pretty',
3809                                 minValue: -0.1,
3810                                 maxValue: 0.1,
3811                                 direction: 1,
3812                                 textStyle: {
3813                                         fontSize: 9
3814                                 },
3815                                 gridlines: {
3816                                         color: '#EEE'
3817                                 }
3818                         },
3819                         chartArea: {
3820                                 width: '65%',
3821                                 height: '80%'
3822                         },
3823                         focusTarget: 'category',
3824                         annotation: {
3825                                 '1': {
3826                                         style: 'line'
3827                                 }
3828                         },
3829                         pointsVisible: 0,
3830                         titlePosition: 'out',
3831                         titleTextStyle: {
3832                                 fontSize: 11
3833                         },
3834                         tooltip: {
3835                                 isHtml: false,
3836                                 ignoreBounds: true,
3837                                 textStyle: {
3838                                         fontSize: 9
3839                                 }
3840                         },
3841                         curveType: 'function',
3842                         areaOpacity: 0.3,
3843                         isStacked: false
3844                 };
3845
3846                 switch(state.chart.chart_type) {
3847                         case "area":
3848                                 state.google_options.vAxis.viewWindowMode = 'maximized';
3849                                 state.google_options.areaOpacity = NETDATA.options.current.color_fill_opacity_area;
3850                                 state.google_instance = new google.visualization.AreaChart(state.element_chart);
3851                                 break;
3852
3853                         case "stacked":
3854                                 state.google_options.isStacked = true;
3855                                 state.google_options.areaOpacity = NETDATA.options.current.color_fill_opacity_stacked;
3856                                 state.google_options.vAxis.viewWindowMode = 'maximized';
3857                                 state.google_options.vAxis.minValue = null;
3858                                 state.google_options.vAxis.maxValue = null;
3859                                 state.google_instance = new google.visualization.AreaChart(state.element_chart);
3860                                 break;
3861
3862                         default:
3863                         case "line":
3864                                 state.google_options.lineWidth = 2;
3865                                 state.google_instance = new google.visualization.LineChart(state.element_chart);
3866                                 break;
3867                 }
3868
3869                 state.google_instance.draw(datatable, state.google_options);
3870         };
3871
3872         // ----------------------------------------------------------------------------------------------------------------
3873         // easy-pie-chart
3874
3875         NETDATA.easypiechartInitialize = function(callback) {
3876                 if(typeof netdataNoEasyPieChart === 'undefined' || !netdataNoEasyPieChart) {
3877                         $.ajax({
3878                                 url: NETDATA.easypiechart_js,
3879                                 cache: true,
3880                                 dataType: "script"
3881                         })
3882                                 .done(function() {
3883                                         NETDATA.registerChartLibrary('easypiechart', NETDATA.easypiechart_js);
3884                                 })
3885                                 .fail(function() {
3886                                         NETDATA.error(100, NETDATA.easypiechart_js);
3887                                 })
3888                                 .always(function() {
3889                                         if(typeof callback === "function")
3890                                                 callback();
3891                                 })
3892                 }
3893                 else {
3894                         NETDATA.chartLibraries.easypiechart.enabled = false;
3895                         if(typeof callback === "function")
3896                                 callback();
3897                 }
3898         };
3899
3900         NETDATA.easypiechartChartUpdate = function(state, data) {
3901
3902                 state.easypiechart_instance.update();
3903         };
3904
3905         NETDATA.easypiechartChartCreate = function(state, data) {
3906                 var self = $(state.element);
3907
3908                 var value = 10;
3909                 var pcent = 10;
3910
3911                 $(state.element_chart).data('data-percent', pcent);
3912                 data.element_chart.innerHTML = value.toString();
3913
3914                 state.easypiechart_instance = new EasyPieChart(state.element_chart, {
3915                         barColor: self.data('easypiechart-barcolor') || '#ef1e25',
3916                         trackColor: self.data('easypiechart-trackcolor') || '#f2f2f2',
3917                         scaleColor: self.data('easypiechart-scalecolor') || '#dfe0e0',
3918                         scaleLength: self.data('easypiechart-scalelength') || 5,
3919                         lineCap: self.data('easypiechart-linecap') || 'round',
3920                         lineWidth: self.data('easypiechart-linewidth') || 3,
3921                         trackWidth: self.data('easypiechart-trackwidth') || undefined,
3922                         size: self.data('easypiechart-size') || Math.min(state.chartWidth(), state.chartHeight()),
3923                         rotate: self.data('easypiechart-rotate') || 0,
3924                         animate: self.data('easypiechart-rotate') || {duration: 0, enabled: false},
3925                         easing: self.data('easypiechart-easing') || undefined
3926                 })
3927         };
3928
3929         // ----------------------------------------------------------------------------------------------------------------
3930         // Charts Libraries Registration
3931
3932         NETDATA.chartLibraries = {
3933                 "dygraph": {
3934                         initialize: NETDATA.dygraphInitialize,
3935                         create: NETDATA.dygraphChartCreate,
3936                         update: NETDATA.dygraphChartUpdate,
3937                         resize: function(state) {
3938                                 if(typeof state.dygraph_instance.resize === 'function')
3939                                         state.dygraph_instance.resize();
3940                         },
3941                         setSelection: NETDATA.dygraphSetSelection,
3942                         clearSelection:  NETDATA.dygraphClearSelection,
3943                         initialized: false,
3944                         enabled: true,
3945                         format: function(state) { return 'json'; },
3946                         options: function(state) { return 'ms|flip'; },
3947                         legend: function(state) {
3948                                 if(this.isSparkline(state) === false)
3949                                         return 'right-side';
3950                                 else
3951                                         return null;
3952                         },
3953                         autoresize: function(state) { return true; },
3954                         max_updates_to_recreate: function(state) { return 5000; },
3955                         track_colors: function(state) { return true; },
3956                         pixels_per_point: function(state) {
3957                                 if(this.isSparkline(state) === false)
3958                                         return 3;
3959                                 else
3960                                         return 2;
3961                         },
3962
3963                         isSparkline: function(state) {
3964                                 if(typeof state.dygraph_sparkline === 'undefined') {
3965                                         var t = $(state.element).data('dygraph-theme');
3966                                         if(t === 'sparkline')
3967                                                 state.dygraph_sparkline = true;
3968                                         else
3969                                                 state.dygraph_sparkline = false;
3970                                 }
3971                                 return state.dygraph_sparkline;
3972                         }
3973                 },
3974                 "sparkline": {
3975                         initialize: NETDATA.sparklineInitialize,
3976                         create: NETDATA.sparklineChartCreate,
3977                         update: NETDATA.sparklineChartUpdate,
3978                         resize: null,
3979                         setSelection: function(t) { return true; },
3980                         clearSelection: function() { return true; },
3981                         initialized: false,
3982                         enabled: true,
3983                         format: function(state) { return 'array'; },
3984                         options: function(state) { return 'flip|abs'; },
3985                         legend: function(state) { return null; },
3986                         autoresize: function(state) { return false; },
3987                         max_updates_to_recreate: function(state) { return 5000; },
3988                         track_colors: function(state) { return false; },
3989                         pixels_per_point: function(state) { return 3; }
3990                 },
3991                 "peity": {
3992                         initialize: NETDATA.peityInitialize,
3993                         create: NETDATA.peityChartCreate,
3994                         update: NETDATA.peityChartUpdate,
3995                         resize: null,
3996                         setSelection: function(t) { return true; },
3997                         clearSelection: function() { return true; },
3998                         initialized: false,
3999                         enabled: true,
4000                         format: function(state) { return 'ssvcomma'; },
4001                         options: function(state) { return 'null2zero|flip|abs'; },
4002                         legend: function(state) { return null; },
4003                         autoresize: function(state) { return false; },
4004                         max_updates_to_recreate: function(state) { return 5000; },
4005                         track_colors: function(state) { return false; },
4006                         pixels_per_point: function(state) { return 3; }
4007                 },
4008                 "morris": {
4009                         initialize: NETDATA.morrisInitialize,
4010                         create: NETDATA.morrisChartCreate,
4011                         update: NETDATA.morrisChartUpdate,
4012                         resize: null,
4013                         setSelection: function(t) { return true; },
4014                         clearSelection: function() { return true; },
4015                         initialized: false,
4016                         enabled: true,
4017                         format: function(state) { return 'json'; },
4018                         options: function(state) { return 'objectrows|ms'; },
4019                         legend: function(state) { return null; },
4020                         autoresize: function(state) { return false; },
4021                         max_updates_to_recreate: function(state) { return 50; },
4022                         track_colors: function(state) { return false; },
4023                         pixels_per_point: function(state) { return 15; }
4024                 },
4025                 "google": {
4026                         initialize: NETDATA.googleInitialize,
4027                         create: NETDATA.googleChartCreate,
4028                         update: NETDATA.googleChartUpdate,
4029                         resize: null,
4030                         setSelection: function(t) { return true; },
4031                         clearSelection: function() { return true; },
4032                         initialized: false,
4033                         enabled: true,
4034                         format: function(state) { return 'datatable'; },
4035                         options: function(state) { return ''; },
4036                         legend: function(state) { return null; },
4037                         autoresize: function(state) { return false; },
4038                         max_updates_to_recreate: function(state) { return 300; },
4039                         track_colors: function(state) { return false; },
4040                         pixels_per_point: function(state) { return 4; }
4041                 },
4042                 "raphael": {
4043                         initialize: NETDATA.raphaelInitialize,
4044                         create: NETDATA.raphaelChartCreate,
4045                         update: NETDATA.raphaelChartUpdate,
4046                         resize: null,
4047                         setSelection: function(t) { return true; },
4048                         clearSelection: function() { return true; },
4049                         initialized: false,
4050                         enabled: true,
4051                         format: function(state) { return 'json'; },
4052                         options: function(state) { return ''; },
4053                         legend: function(state) { return null; },
4054                         autoresize: function(state) { return false; },
4055                         max_updates_to_recreate: function(state) { return 5000; },
4056                         track_colors: function(state) { return false; },
4057                         pixels_per_point: function(state) { return 3; }
4058                 },
4059                 "easypiechart": {
4060                         initialize: NETDATA.easypiechartInitialize,
4061                         create: NETDATA.easypiechartChartCreate,
4062                         update: NETDATA.easypiechartChartUpdate,
4063                         resize: null,
4064                         setSelection: function(t) { return true; },
4065                         clearSelection: function() { return true; },
4066                         initialized: false,
4067                         enabled: true,
4068                         format: function(state) { return 'json'; },
4069                         options: function(state) { return ''; },
4070                         legend: function(state) { return null; },
4071                         autoresize: function(state) { return false; },
4072                         max_updates_to_recreate: function(state) { return 5000; },
4073                         track_colors: function(state) { return false; },
4074                         pixels_per_point: function(state) { return 3; }
4075                 }
4076         };
4077
4078         NETDATA.registerChartLibrary = function(library, url) {
4079                 if(NETDATA.options.debug.libraries === true)
4080                         console.log("registering chart library: " + library);
4081
4082                 NETDATA.chartLibraries[library].url = url;
4083                 NETDATA.chartLibraries[library].initialized = true;
4084                 NETDATA.chartLibraries[library].enabled = true;
4085         }
4086
4087         // ----------------------------------------------------------------------------------------------------------------
4088         // Start up
4089
4090         NETDATA.requiredJs = [
4091                 {
4092                         url: NETDATA.serverDefault + 'lib/bootstrap.min.js',
4093                         isAlreadyLoaded: function() {
4094                                 if(typeof $().emulateTransitionEnd == 'function')
4095                                         return true;
4096                                 else {
4097                                         if(typeof netdataNoBootstrap !== 'undefined' && netdataNoBootstrap)
4098                                                 return true;
4099                                         else
4100                                                 return false;
4101                                 }
4102                         }
4103                 },
4104                 {
4105                         url: NETDATA.serverDefault + 'lib/jquery.nanoscroller.min.js',
4106                         isAlreadyLoaded: function() { return false; }
4107                 },
4108                 {
4109                         url: NETDATA.serverDefault + 'lib/bootstrap-toggle.min.js',
4110                         isAlreadyLoaded: function() { return false; }
4111                 }
4112         ];
4113
4114         NETDATA.requiredCSS = [
4115                 {
4116                         url: NETDATA.serverDefault + 'css/bootstrap.min.css',
4117                         isAlreadyLoaded: function() {
4118                                 if(typeof netdataNoBootstrap !== 'undefined' && netdataNoBootstrap)
4119                                         return true;
4120                                 else
4121                                         return false;
4122                         }
4123                 },
4124                 {
4125                         url: NETDATA.serverDefault + 'css/font-awesome.min.css',
4126                         isAlreadyLoaded: function() { return false; }
4127                 },
4128                 {
4129                         url: NETDATA.dashboard_css,
4130                         isAlreadyLoaded: function() { return false; }
4131                 },
4132                 {
4133                         url: NETDATA.serverDefault + 'css/bootstrap-toggle.min.css',
4134                         isAlreadyLoaded: function() { return false; }
4135                 }
4136         ];
4137
4138         NETDATA.loadRequiredJs = function(index, callback) {
4139                 if(index >= NETDATA.requiredJs.length)  {
4140                         if(typeof callback === 'function')
4141                                 callback();
4142                         return;
4143                 }
4144
4145                 if(NETDATA.requiredJs[index].isAlreadyLoaded()) {
4146                         NETDATA.loadRequiredJs(++index, callback);
4147                         return;
4148                 }
4149
4150                 if(NETDATA.options.debug.main_loop === true)
4151                         console.log('loading ' + NETDATA.requiredJs[index].url);
4152
4153                 $.ajax({
4154                         url: NETDATA.requiredJs[index].url,
4155                         cache: true,
4156                         dataType: "script"
4157                 })
4158                 .success(function() {
4159                         if(NETDATA.options.debug.main_loop === true)
4160                                 console.log('loaded ' + NETDATA.requiredJs[index].url);
4161
4162                         NETDATA.loadRequiredJs(++index, callback);
4163                 })
4164                 .fail(function() {
4165                         alert('Cannot load required JS library: ' + NETDATA.requiredJs[index].url);
4166                 })
4167         }
4168
4169         NETDATA.loadRequiredCSS = function(index) {
4170                 if(index >= NETDATA.requiredCSS.length)
4171                         return;
4172
4173                 if(NETDATA.requiredCSS[index].isAlreadyLoaded()) {
4174                         NETDATA.loadRequiredCSS(++index);
4175                         return;
4176                 }
4177
4178                 if(NETDATA.options.debug.main_loop === true)
4179                         console.log('loading ' + NETDATA.requiredCSS[index].url);
4180
4181                 NETDATA._loadCSS(NETDATA.requiredCSS[index].url);
4182                 NETDATA.loadRequiredCSS(++index);
4183         }
4184
4185         NETDATA.errorReset();
4186         NETDATA.loadRequiredCSS(0);
4187
4188         NETDATA._loadjQuery(function() {
4189                 NETDATA.loadRequiredJs(0, function() {
4190                         if(typeof netdataDontStart === 'undefined' || !netdataDontStart) {
4191                                 if(NETDATA.options.debug.main_loop === true)
4192                                         console.log('starting chart refresh thread');
4193
4194                                 NETDATA.start();
4195                         }
4196
4197                         if(typeof NETDATA.options.readyCallback === 'function')
4198                                 NETDATA.options.readyCallback();
4199                 });
4200         });
4201
4202         // window.NETDATA = NETDATA;
4203 // })(window, document);