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