(function(){
	"use strict";
	var job = $('#global-job-number').data('job');
	var layoutUrl = '/online/' + job + '/layout.json';
	var activeControls = {};
	var plotObjects = Array();
	var latestSecond = 0;
	var LOCK = false;
	/**
	 * latestSecond следует обнулять при нажатии на кнопки переключения масштаба (interval) контролы типа переключения гильз, мишеней и пр..
	 */

	var refreshIntervalId = 0;

	//
	$('.onlinepage__show').on('click', function() {
		$('.onlinepage__show.active').removeClass('active');
		$(this).addClass('active');
		clearInterval(refreshIntervalId);
		latestSecond = 0;
		$.when(getChunk()).then(
				activateRefresh()
				);
	});

	$('.onlinepage__refresh').on('click', function() {
		$('.onlinepage__refresh.active').removeClass('active');
		$(this).addClass('active');
		clearInterval(refreshIntervalId);
		$.when(getChunk()).then(
				activateRefresh()
				);
	});


	function getChunk() {

		if (!LOCK) {
            LOCK = true;
            // Progress-bar

            // Tags, adding new buttons if needed
            var tagsUrl = '/online/refresh_tags.json?job=' + job;
            var currentTags = [];
            $('#job-controls__group__test_data__tags').children().each(function(i) {
                currentTags.push($(this).data('val'));
            });

            $.ajax({
                url : tagsUrl,
                type : 'GET',
                dataType : 'json'
            }).success(function(jobTags) {
                for (var tag=0; tag<jobTags.length; tag++) {
                    if ($.inArray(jobTags[tag][0], currentTags) === -1) {
                        $('#job-controls__group__test_data__tags').append(
                            '<button class="btn btn-secondary job-controls__test_data__button" data-control="tags" data-val="' + jobTags[tag][0] + '">' + jobTags[tag][1] + '</button>'
                        )
                    }
                }
            });


            /* NOT ACTIVE YET (Может быть, и вовсе не понадобится обновлять список мониторящихся таргетов и метрик)
            // Refresh monitoring controls, adding new buttons if needed

            if (activeControls.tab == 'monitoring') {

                var monitoringRefreshUrl = '/online/refresh_monitoring_controls.json?job=' + job

                $.ajax({
                    url : monitoringRefreshUrl,
                    type : 'GET',
                    dataType : 'json'
                }).success(function(data) {

                    // Targets
                    var jobTargets = data['targets']
                    var currentTargets = []
                    $('#job-controls__group__monitoring__machines').children().each(function(i) {
                        currentTargets.push($(this).data('val'));
                    });

                    for (var target=0; target<jobTargets.length; target++) {
                        if ($.inArray(jobTargets[target][0], currentTargets) == -1) {
                            $('#job-controls__group__monitoring__machines').append(
                                '<button class="btn btn-secondary job-controls__monitoring__button" data-control="machines" data-val="' + jobTargets[target][0] + '">' + jobTargets[target][1] + '</button>'
                            )
                        }
                    }

                    // Metrics
                    var jobMetrics = data['metrics']
                    var currentMetrics = []
                    $('#job-controls__group__monitoring__metrics').children().each(function(i) {
                        currentMetrics.push($(this).data('val'));
                    });

                    for (var metric=0; metric<jobMetrics.length; metric++) {
                        if ($.inArray(jobMetrics[metric], currentMetrics) == -1) {
                            $('#job-controls__group__monitoring__metrics').append(
                                '<button class="btn btn-secondary job-controls__monitoring__button" data-control="metrics" data-val="' + jobMetrics[metric]] + '">' + jobMetrics[metric] + '</button>'
                            )
                        }
                    }

                });
            }
            */


            // Plots
            var limit = $('.onlinepage__show.active').data('limit');
            var params = clone(activeControls); // чтобы не добавлять кал в общие настройки.
            var plot_types = '';
            for (var p=0; p< plotObjects.length; p++) {
                if (plotObjects[p].plotType.startsWith('monitoring')) {
                    plot_types += plotObjects[p].plotType + '@' + plotObjects[p].host + ',';
                } else {
                    plot_types += plotObjects[p].plotType + ',';
                }
            }
            params.plot_types = plot_types;
            params.latest_second = latestSecond;
            params.interval = limit;
            var url = '/online/' + job + '/plot_chunk.json?' + $.param(params);

            $.ajax({
                url: url,
                type: 'GET',
                dataType: 'json',
                async: true,
            }).done(function (newData) {
                $.each(plotObjects, function (i, plot) {
                    try {
                        if (plot.plotType.indexOf('_table') === -1) {

                            var chart = plot.chart;
                            if (plot.plotType.startsWith('monitoring')) {
                                var thisPlotData = newData[plot.plotType + '@' + plot.host]
                            } else {
                                var thisPlotData = newData[plot.plotType]
                            }

                            var series_titles = [];
                            var timestamps = thisPlotData.xAxis;
                            var len = timestamps.length;

                            for (var s = 0; s < chart.series.length; s++) {
                                var serie = chart.series[s];
                                series_titles.push(serie.name);
                                var chunk = thisPlotData.data[serie.name] ? thisPlotData.data[serie.name]['values'] : [];

                                // timelines
                                if (plot.plotType.indexOf('_dist_plot') === -1 && plot.plotType.indexOf('es_vs_') === -1 && plot.plotType.indexOf('_table') === -1) {
                                    var chunkData = [];
                                    var point;
                                	if (latestSecond === 0) { // При переключении интервала
                                        for (var t = 0; t < len && timestamps[t] <= newData.latestSecond; t++) {
                                            point = [thisPlotData.xAxis[t], chunk[t] ? chunk[t] : 0];
                                            chunkData.push(point)
                                        }
                                        chart.series[s].setData(chunkData)
                                    } else { // small chunks
                                        for (var t = 0; t < len && timestamps[t] > latestSecond && timestamps[t] <= newData.latestSecond; t++) {
                                            point = [thisPlotData.xAxis[t], chunk[t] ? chunk[t] : 0];
                                            chunkData.push(point)
                                        }
                                        var previousData = serie.options.data;
                                        var limitedData = previousData.concat(chunkData).slice(-limit);
                                        if (plot.plotType === 'http_timeline_plot') {
                                            console.log(limitedData)
                                        }
                                        serie.setData(limitedData)
                                    }
                                }
                                else { // dists
                                    var serie_data = thisPlotData.data[serie.name]['values'];
                                    chart.xAxis[0].setCategories(thisPlotData['xAxis']['categories']);
                                    chart.series[s].setData(serie_data)
                                }
                            }
                            // new series
                            for (var k in thisPlotData.data) {
                                if (series_titles.indexOf(k) === -1) {
                                    if (plot.plotType.indexOf('_dist_plot') === -1 && plot.plotType.indexOf('es_vs_') === -1) {
                                        var chunk = thisPlotData.data[k].values;
                                        var data = [];
                                        var xData;
                                        if (chart.series[0] !== undefined) {
                                            xData = chart.series[0].xData;
                                        } else {
                                            xData = thisPlotData.xAxis
                                        }
                                        for (var t = 0; t < xData.length; t++) {
                                            var timestamp = xData[t];
                                            data.push([timestamp, chunk[t] ? chunk[t] : 0]);
                                        }
                                        chart.addSeries({
                                            color: thisPlotData.data[k]['color'],
                                            name: thisPlotData.data[k]['name'],
                                            title: thisPlotData.data[k]['name'],
                                            data: data,
                                            type: thisPlotData.data[k]['type'],
                                            yAxis: thisPlotData.data[k]['yAxis'],
                                        }, false);
                                        console.log(chart.series)
                                    }
                                    else { //dists
                                        var serie_data = thisPlotData.data[k];
                                        chart.xAxis[0].setCategories(thisPlotData['xAxis']['categories']);
                                        chart.addSeries({
                                            color: thisPlotData.data[k]['color'],
                                            name: thisPlotData.data[k]['name'],
                                            title: thisPlotData.data[k]['name'],
                                            data: thisPlotData.data[k]['values'],
                                            type: thisPlotData.data[k]['type'],
                                            yAxis: thisPlotData.data[k]['yAxis'],
                                        }, false);
                                    }
                                }
                            }
                            chart.redraw(true);
                        }
                        // TABLES
                        else {
                            //$('#job-plots__'+activeControls.tab+'__'+plot.plotType+plot.host).html('')
                            if (plot.plotType.startsWith('monitoring')) {
                                var thisPlotData = newData[plot.plotType + '@' + plot.host]
                            } else {
                                var thisPlotData = newData[plot.plotType]
                            }
                            _drawTable(thisPlotData, plot.plotType, plot.host, true)
                        }
                    }
                    catch (e) {
                        console.log('errir!', e)
                    }
                });
                if (newData.latestSecond) {
                    latestSecond = newData.latestSecond;
                }
            }).always(function() {
                console.log('releasing lock');
                LOCK = false;
            });
        } else {
		    console.log('chunk refresh locked')
        }
    } // end of getChunk
    function activateRefresh() {
		// refresh cycle
		refreshIntervalId = setInterval( //setTimeout
				function() {
					getChunk();
	        	}, 1000 * parseInt($('.onlinepage__refresh.active').data('refresh'))
	        );
    }
    //$('.onlinepage__refresh.active') ?  :

	// MAIN
	$.getJSON( layoutUrl, function(data) {
		$.when(renderTabPanel( data )).then(
				$.when(getChunk()).then(
						activateRefresh()
						)
				);
	});

	Highcharts.setOptions({
		lang: {
			noData: "Ждём данные.."
		}
	});

	function renderTabPanel( layoutData ) {
		var tabTemplate = _.template($('#tabTemplate').text()),
		panelTemplate = _.template($('#panelTemplate').text());

		var defaults;
		try {
			defaults = JSON.parse('{"' + decodeURI(window.location.hash.substr(1)).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}');
		} catch(e) {
			defaults = {
				tab : layoutData[0].name.replace(/</g, "&lt;").replace(/>/g, "&gt;")
			};
		}
		activeControls = defaults;

		// просмотр чужого пользовательского отчета (которого нет в layout текущего пользователя), например если кто-то поделился ссылкой.
		var tabs = [];
		layoutData.map(function(tab) {
			tabs.push(tab.name)
		});
		if (defaults.tab && tabs.indexOf(defaults.tab) === -1) {
			$.ajax({
				url : '/online/' + job + '/custom_report.json?cur=' + defaults.tab.split("__")[1],
				type : 'GET',
				dataType : 'json',
				async: false
			}).success(function(controls) {
				layoutData.push(controls)
			})
		}

		$('.job-tabpanel__krutilka').remove();
		$.each( layoutData, function( i ) {
			var tab = layoutData[i];
			$('#job-tabpanel__tabs').append(tabTemplate({tab: tab.name.replace(/</g, "&lt;").replace(/>/g, "&gt;"), title: tab.title.replace(/</g, "&lt;").replace(/>/g, "&gt;")}));
			$('#job-tabpanel__panels').append(panelTemplate({tab: tab.name.replace(/</g, "&lt;").replace(/>/g, "&gt;"), title: tab.title.replace(/</g, "&lt;").replace(/>/g, "&gt;")}));
		});


		var customToggleTemplate = _.template($('#customToggleTemplate').text());
        var $curToggleTab = $('#cur-toggle-tab');
		$('#job-tabpanel__tabs').append(customToggleTemplate({}));
		var $curContents = $('#cur-contents');
		$curContents.load('/online/render_custom_report_form?job='+job);
		$curContents.css('position', 'fixed');
		$curContents.css('left', 15);
		$('#cur-toggle-tab').on('shown.bs.dropdown', function () {
			$('#cur-toggle').css('z-index', 1001);
			$('#cur_name').focus()
		});
		$('#cur-toggle-tab').on('hidden.bs.dropdown', function () {
			$('#cur-toggle').css('z-index', 0)
		});


		$('#job-tabpanel__panels').append();

		$('.nav-tabs a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
			activeControls.tab = $(this).data('tab');
			window.location.hash = $.param(activeControls);
			var controls = _.findWhere(layoutData, {name: $(this).data('tab')}).controls;
			renderPanel( $(this).data('tab'), controls );
		});
		
		$('.delete-custom-report').on('click', function(event) {
			var id = $(this).data('id'),
			title = $(this).data('title');
			if (confirm('Удалить пользовательский отчет '+title)) {
				$.get("/api/delete_custom_report?id="+id);
				$("li#job-tabpanel__tab__custom__"+id).remove();
				$('div#job-tabpanel__panel__custom__'+id).remove();
				var togglerOffset = $("li#cur-toggle-tab").offset();
				$('#cur-contents').css('left', -1*togglerOffset.left + 29); // чуть-чуть не заподлицо с панелью
				$('#cur-contents').css('width', ($('div#job-tabpanel__panels').width() - 29).toString() + 'px');
				if (activeControls.tab === 'custom__'+id) {
					activeControls.tab = layoutData[0].name.replace(/</g, "&lt;").replace(/>/g, "&gt;");
					window.location.hash = $.param(activeControls);
					$('.nav-tabs a[href="#job-tabpanel__panel__' + layoutData[0].name.replace(/</g, "&lt;").replace(/>/g, "&gt;") + '"]').tab('show');
				}
			}
			
			event.preventDefault();
		});
		
		$('.nav-tabs a[href="#job-tabpanel__panel__' + defaults['tab'] + '"]').tab('show');
    }
    function renderPanel( tab, controls ) {
		if ($('#job-tabpanel__panel__'+tab).html().trim()==='') {
			
	    	var plot_groups = _.findWhere(controls, {name: 'plot_groups'});
	    	var tags =  _.findWhere(controls, {name: 'tags'});
			var machines = _.findWhere(controls, {name: 'machines'});
			var metrics = _.findWhere(controls, {name: 'metrics'});
			
			// Ищем настройки
			
			var activeMachine = machines ? machines['default'].toString() : '';
			var activeMetrics = metrics ? metrics['default'] : '';
			var activeTag = tags ? tags['default'] : '';
			var activePlotGroup = plot_groups ? plot_groups['default'] : 'main';
				
			var parsedHash;
			try {
				parsedHash = JSON.parse('{"' + decodeURI(window.location.hash.substr(1)).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}');
			} catch(e) {
				parsedHash = {
						tab: tab, 
						tags: activeTag,
						plot_groups: activePlotGroup,
						machines: activeMachine,
						metrics: activeMetrics,
				};
			}
			parsedHash.tab = tab;
			
			if (!('tags' in parsedHash)){
				parsedHash.tags = activeTag;
            }
            if (!('plot_groups' in parsedHash)){
				parsedHash.plot_groups = activePlotGroup;
            }
            if (!parsedHash.machines) {
            	var activeMachine = machines ? machines['default'].toString() : '';
				parsedHash.machines = activeMachine
            }
            if (!('metrics' in parsedHash)){
				parsedHash.metrics = activeMetrics
            }
            activeControls = parsedHash;
			window.location.hash = $.param(activeControls);
			
			// Рендерим кнопки
			
			if (plot_groups && tab.split('__')[0] !== 'custom') {
				renderControls( plot_groups )
			}
			else {
				activeControls.plot_groups = 'main'
			}
			if (tags) {
				renderControls( tags )
			}
			if (machines) {
				renderControls( machines )
			}
			if (metrics) {
				renderControls( metrics )
			}
			
			var plotsContainerTemplate = _.template($('#plotsContainerTemplate').text());
			$('#job-tabpanel__panel__'+tab).append(plotsContainerTemplate({tab: tab}));
			loadPlots();
		} else {
			loadPlots();
		}
    }
    function renderProgressBar(tab) {
		var progressBarTemplate = _.template($('#progressBarTemplate').text());
		var url = '/online/progress_bar.json?job=' + job;
		$.ajax({
			url : url,
			type : 'GET',
			dataType : 'json'
		}).success(function(data) {
			var progress_bar = {'now': latestSecond,
								 'min': data['start'],
								 'max': data['end'],
								 'percentage': 100*((data['end']-data['start'])/latestSecond-data['start']),
								 'nowformatted': latestSecond
								};
			var now = Math.floor(Date.now() / 1000);
			var progress_shift = {'now': now - latestSecond,
								'min': data['start'],
			 					'max': data['end'],
			 					'percentage': 100*((data['end']-data['start'])/now-data['start']),
			 					'nowformatted': latestSecond
					};
			$('#job-tabpanel__panel__'+tab).append(progressBarTemplate({progressShift: progress_shift, progressBar: progress_bar}))
		})
		
	}
	
	function refreshProgressBar() {
		var now = Math.floor(Date.now() / 1000);
		var bar = $('.progress-bar-brand');
		var shift = $('.progress-bar-danger');
		bar.attr('aria-valuenow', latestSecond).css({'width': (100*parseInt(bar.attr('aria-valuenow'))/parseInt(bar.attr('aria-valuemax'))).toString() + '%'});  
		shift.attr('aria-valuenow', now).css({'width': (100*parseInt(shift.attr('aria-valuenow'))/parseInt(shift.attr('aria-valuemax'))).toString() + '%'});
	}
	
	function renderControls( controls ) {
		var controlsTemplate = _.template($('#controlsTemplate').text()),
		buttonTemplate = _.template($('#buttonTemplate').text());
		$('#job-tabpanel__panel__'+activeControls.tab).append(controlsTemplate({tab: activeControls.tab, name: controls.name}));
		_.each(controls.values, function(button) {
			if (controls.name == 'machines') {
				var button_title = button[2] ? button[2] : button[1];
				$('#job-controls__group__'+activeControls.tab+'__'+controls.name).append(buttonTemplate({tab: activeControls.tab, button_name: button[0], button_title: button_title, controls_name: controls.name}))
			}
			else {
				$('#job-controls__group__'+activeControls.tab+'__'+controls.name).append(buttonTemplate({tab: activeControls.tab, button_name: button[0], button_title: button[1], controls_name: controls.name}))
			}
		});
		activateControls( controls )
    }
    function activateControls( controls ) {
		if (controls.name === 'tags') {
			$('#job-controls__group__'+activeControls.tab+'__'+controls.name).find('button[data-val="'+activeControls.tags+'"]').addClass('active')
		}
		if (controls.name === 'machines') {
			$('#job-controls__group__'+activeControls.tab+'__'+controls.name).find('button[data-val="'+activeControls.machines+'"]').addClass('active')
		}
		if (controls.name === 'metrics') {
			$('#job-controls__group__'+activeControls.tab+'__'+controls.name).find('button[data-val="'+activeControls.metrics+'"]').addClass('active')
		}
		if (controls.name === 'plot_groups') {
			$('#job-controls__group__'+activeControls.tab+'__'+controls.name).find('button[data-val="'+activeControls.plot_groups+'"]').addClass('active')
		}
		
		$('#job-controls__group__'+activeControls.tab+'__'+controls.name).find('button').bind('click', function(event) {
			$('#job-controls__group__'+activeControls.tab+'__'+$(this).data('control')).find('button').removeClass('active');
			$(this).addClass('active');
			activeControls[$(this).data('control')] = $(this).data('val');
			window.location.hash = $.param(activeControls);
			//latestSecond = 0;
			clearInterval(refreshIntervalId);
			loadPlots();
			event.preventDefault();
		});
    }
    function loadPlots() {
		var parsedHash = JSON.parse('{"' + decodeURI(window.location.hash.substr(1)).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}');
		activeControls = parsedHash;
		latestSecond = 0;
		$('#b-overload-onlinepage__charts__'+activeControls.tab).html('');
		$.ajax({
            method: 'GET',
            url: '/online/'+job+'/plots_to_show.json?' + $.param(activeControls) + '&latest_second='+latestSecond + '&interval='+$('.onlinepage__show.active').data('limit'),
            dataType: 'json',
            success: function(data) {
            	// Clear previously loaded charts, so they don't ask for chunks;
            	plotObjects = [];
            	for (var c=0; c<Highcharts.charts.length; c++){
            		if (Highcharts.charts[c] !== undefined) {
            			Highcharts.charts[c].destroy()
            		}
        		}
            	activeControls.compress_ratio = data['compress_ratio'];
        		if (!latestSecond || latestSecond > data.latest_second) {
        			latestSecond = data.latest_second
        		}
            	var plotTemplate = _.template($('#plotTemplate').text());
            	for (var plotType in data['plots']) {
            		$('#b-overload-onlinepage__charts__'+activeControls.tab).append(plotTemplate({tab: activeControls.tab, plot_type: plotType.split('@')[0].replace(':','__'), host:plotType.split('@')[1] || ''}));
            		_draw(data['plots'][plotType], plotType.split('@')[0], plotType.split('@')[1] || '');
            	}
            	clearInterval(refreshIntervalId);
        		$.when(getChunk()).then(
        				activateRefresh()
        				);
    		$('#job-plots__compress-ratio__'+activeControls.tab).text(data['compress_ratio'] + ' sec. per dot');
            },
		});
    }
    function clone(obj) {
	    if (null === obj || "object" !== typeof obj) return obj;
	    var copy = obj.constructor();
	    for (var attr in obj) {
	        if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
	    }
	    return copy;
	}
	
	function _draw(data, plotType, host) {
		if (plotType.indexOf('_table') === -1) {
			_drawPlot(data, plotType, host)
		}
		else {
			_drawTable(data, plotType, host, false) 
		}
    }
    function _drawTable(data, plotType, host, refresh) {
		var container = $('#job-plots__'+activeControls.tab+'__'+plotType+host);
		container.addClass('job-plots__table');
		container.html('');

		var title = $('<h4>' + data.title + '</h4>').appendTo(container);
		var table = $('<table class="table table-sm table-striped table-hover"><thead><tr id="table_header__'+activeControls.tab+'__'+plotType+host+'"></tr></thead><tbody></tbody></table>'); //style="font-family: Monaco, Monospace, Courier;"
		var data = data.data;

		container.closest('.job-plots__container').css({
			'height' : 'auto',
			//'font-size' : '120%',
			//'text-align' : 'center'
		});

		data.columns.map(function(col) {
			col.values.map(function(cell, pos) {
				if (cell && data.columns.indexOf(col) > 0 && cell.toString().indexOf(".") > 0) {
					cell = cell.toString().replace('\%', ' \%');
					var fraction = cell.split('.')[1].split(' ')[0];
					while (fraction && fraction.length < 3) {
						fraction = fraction + '0'
					}
					var valueText = cell.split('.')[0] + '.<span style="font-size:80%; opacity: 0.7;">' + fraction + '</span>';
					if (cell.split('.')[1].indexOf(" ") > 0) {
						valueText += ' ' + cell.split('.')[1].split(' ')[1]
					}
				}
				else {
					var valueText = cell.toString().replace(/</g, "&lt;").replace(/>/g, "&gt;")
				}
				
				var text = valueText || cell, weight = cell.weight || col.weight || 'normal', 
				align = cell.align || col.align || 'left', 
				color = cell.color || col.color || '#333', 
				cell = $('<td style="text-align: ' + align + '; font-weight: ' + weight + '; color: ' + color + '">' + text + '</td>'), 
				row = table[0].tBodies[0].rows[pos];
				if (!row) {
					row = table[0].tBodies[0].insertRow(-1);
				}
				cell.appendTo(row);
			});
		});

		table.appendTo(container);
		
		data.header.map(function(th) {
			$('tr#table_header__'+activeControls.tab+'__'+plotType+host).append($('<th style="text-align:'+th.align+';">'+th.title+'</th>'))
		});
		
		if (!refresh) {
			plotObjects.push({
		    	'chart': table,
		    	'plotType': plotType,
		    	'host': host,
		    })
		}
    }
    function _drawPlot(data, plotType, host) {// draw chart
		
		var container = $('#job-plots__'+activeControls.tab+'__'+plotType+host);
		if (data.x.type === 'datetime') {
			container.addClass('job-plots__highcharts__timeline')
		}
	    container.addClass('job-plots__highcharts');
		Highcharts.setOptions({ // This is for all plots, change Date axis to local timezone
            global : {
                useUTC : false
            }
        });
		
	    var xType = data.overrides && data.overrides.xAxis && data.overrides.xAxis.type || data.x.type || 'datetime', 
		hideOnDone = [], overrides = {
			title : {
				text : data.title
			},
			subtitle : {
				text : data.subtitle
			},
			chart: {
				renderTo: 'job-plots__'+activeControls.tab+'__'+plotType+host,
				enabledTracking: true,
				resetZoomButton: {
	                theme: {
	                    fill: 'white',
	                    stroke: 'silver',
	                    r: 0,
	                    states: {
	                        hover: {
	                            fill: '#41739D',
	                            style: {
	                                color: 'white',
	                            }
	                        }
	                    }
	                },
	                relativeTo: 'chart',
	            },
			},
			xAxis : {
				dateTimeLabelFormats : {
					second : "%H:%M:%S"
				},
                labels: {
                	overflow: 'justify',
                },
				endOnTick : false,
				showFirstLabel : true,
				showLastLabel : true,
				startOnTick : false,
				type : xType
			},
			yAxis : [],
			series : []
		}, cfg = {};
		$.each(data.y, function() {
			var group = this, yAxis = {
				showFirstLabel : false,
				showLastLabel : false,
				labels : {
					formatter: function () {
				        if (this.value) {
                            return this.axis.defaultLabelFormatter.call(this) + ' ' + (group.label || '');
                        }
                        else {
				            return '';
                        }
                    }
				},
				title : {
					text : 'TITLE',
				}
			};
			if (this.position === 'right') {
				yAxis.opposite = true;
				yAxis.labels.align = 'right';
				yAxis.labels.x = -12;
				yAxis.labels.y = -4;
				//yAxis.gridLineWidth = 0;
			} else {
				yAxis.opposite = false;
				yAxis.labels.align = 'left';
				yAxis.labels.x = 12;
				yAxis.labels.y = -4;
				//yAxis.gridLineWidth = 0;
			}

			if (group.stacking) {
				overrides.plotOptions = {
					area : {
						stacking : group.stacking
					}
				};
			}

			if ('overrides' in group) {
				yAxis = $.extend(true, yAxis, group.overrides);
			}
			overrides.yAxis.push(yAxis);
		});
		var defaults = _getDefaultConfig();
		cfg = $.extend(true, cfg, defaults, overrides, 'overrides' in data ? data.overrides : {});
		//console.log('cfg', cfg);
		if (plotType.indexOf('_dist_plot') === -1 && plotType.indexOf('es_vs_') === -1) {
			var rendered = new Highcharts.StockChart(cfg);
		} else {
			var rendered = new Highcharts.Chart(cfg);
		}
		
		
	    if (hideOnDone.length) {
			rendered.series.map(function(serie) {
				if ($.inArray(serie.name, hideOnDone) !== -1) {
					serie.hide();
				}
			});
		}
	    
	    container.chart = rendered;
	    plotObjects.push({
	    	'chart': rendered,
	    	'plotType': plotType,
	    	'host': host,
	    })
	    
	} // end of _draw func

	function _getDefaultConfig() {
		var marker = {
			enabled : false,
			states : {
				hover : {
					enabled : false
				}
			}
		};
		return {
			chart : {
				animation : false,
				marginRight : 5,
				marginLeft : 5,
				alignTicks : false,
				zoomType : 'x',
				height: 400,
				reflow: true,
				style: {
	                fontFamily: 'Yandex Sans Text Web'
	            }
			},
			plotOptions : {
				area : {
					lineWidth : 0,
					fillOpacity : 1,
				},
				line : {
					lineWidth : 2,
					zIndex : 1,
					shadow : false
				},
				column : {
				},
				spline : {
					zIndex : 1,
				},
				areaspline : {
					lineWidth : 0,
					fillOpacity : 1,
				},
				series : {
					marker : {
						enabled : false,
						states : {
							hover : {
								enabled : false
							}
						}
					},
					animation : false,
					connectNulls: true,
					turboThreshold : 5000,
					cropThreshold: 5000,
	                states: {
	                    hover: {
	                        enabled: false
	                    }
	                },
				},
			},
			credits : {
				enabled : false,
			},
			navigator: {
	            enabled: false,
	        },
	        navigation: {
	            buttonOptions: {
	                enabled: false,
	            }
	        },
	        rangeSelector: {
	        	enabled: false,
	        },
	        scrollbar: {
	        	enabled: false,
	        },
	        exporting: {
	        	enabled: false,
	        },
			title: {
				style: {
					color: '#2a52be',
	   				fontFamily: '"Yandex Sans Text Web","Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif;',
	   			},
			},
			tooltip : {
				animation : false,
				shared : true,
				hideDelay: 0,
				borderRadius : 4,
				borderWidth : 1,
				borderColor: '#999',
	            shadow: false,
				xDateFormat : '%H:%M:%S',
				crosshairs : {
					width : 1,
					color : '#BBB',
					zIndex: 100
				},
				style: {
           			fontSize: '15px',
           			fontFamily: '"Yandex Sans Text Web", Arial, Helvetica, sans-serif',
	            },
	            useHTML: true,
				formatter: function() {
					var res = '';
					var formattedTime = moment.unix(this.x/1000).format("HH:mm:ss");
					res += '<small style="font-size: 80%;">' + formattedTime +'</small><br>';
					// formatting series values
					res +='<table>';
					$.each(this.points, function(i, point) {
						var ser = '<tr><td><span style="color: ' + this.series.color + ';">' +
						this.series.name.replace(/</g, "&lt;").replace(/>/g, "&gt;") + 
						'</span>' + 
						'<span> : </span></td>' + 
						'<td style="padding-top: 3px;">&emsp;<span style="font-weight: bold; color: #333;">' + 
						this.y.toString().split('.')[0].replace(/\B(?=(\d{3})+(?!\d))/g, "'") + // regexp: thousands delimiter  
						'</span>';
						if (this.y.toString().indexOf(".") > 0) { // pretty fraction part 
							var fraction = this.y.toString().split('.')[1];
							while (fraction && fraction.length < 3) {
								fraction = fraction + '0'
							}
							fraction = fraction.slice(0,3);
							ser += '<span style="font-size: 80%; font-weight: bold;">.' +
							fraction + 
							'</span>'
						}
						ser += '</td></tr>';
						res += ser	
					});
					return res
				}
			},
			legend : {
				//maxHeight: 42,
				enabled: true,
				itemMarginBottom: 5,
				align : 'center',
				verticalAlign : 'bottom',
				itemStyle: {
	                color: '#333',
	                fontWeight: 'bold',
	            },
				borderWidth : 0
			},
			series : []
		};
    }
})();

