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