<commit_before>﻿var bar;
var chartCanvas = null;
var g_bChartPreview = false;

function ChartRender() {
	
	this.insertChart = function(chart, activeWorkSheet, width, height, isNewChart, bChartPreview) {
	
		var chartBase64 = null;
		if ( bChartPreview )
			g_bChartPreview = true;
		else
			g_bChartPreview = false;
		if (chart.worksheet && !OfficeExcel.drawingCtxCharts)//выставление контекста для отрисовки
			OfficeExcel.drawingCtxCharts = chart.worksheet.getDrawingContextCharts();
		else if(window["editor"] && !OfficeExcel.drawingCtxCharts)
			OfficeExcel.drawingCtxCharts = new CDrawingContextWord();
		chartCanvas = document.createElement('canvas');
		$(chartCanvas).css('width', width);
		$(chartCanvas).css('height', height);
		$(chartCanvas)[0].height = height;
		$(chartCanvas)[0].width = width;
		
		if ( insertChart(chart, activeWorkSheet, width, height, isNewChart) )
			chartBase64 = chartCanvas.toDataURL();
		
		return chartBase64;
	}
}

var arrBaseColors = [];

function ChartStyleManager() {
	
	var _this = this;
	var bReady = false;
	_this.colorMap = [];
	_this.baseColors = [];
	
	//-----------------------------------------------------------------------------------
	// Methods
	//-----------------------------------------------------------------------------------
	
	_this.init = function() {
		
		_this.colorMap = [];		
		var api_doc = window["editor"];
		var api_sheet = window["Asc"]["editor"];
		var themeColors = [];
		if ( api_sheet )
			themeColors = api_sheet.GuiControlColorsMap;
		else
			themeColors = getDocColors(api_doc);
		
		function getDocColors(api) {
			var _theme  = api.WordControl.m_oLogicDocument.theme;
			var _clrMap = api.WordControl.m_oLogicDocument.clrSchemeMap.color_map;

			var arr_colors = new Array(10);
			var rgba = {R:0, G:0, B:0, A:255};
			// bg1,tx1,bg2,tx2,accent1 - accent6
			var array_colors_types = [6, 15, 7, 16, 0, 1, 2, 3, 4, 5];
			var _count = array_colors_types.length;

			var color = new CUniColor();
			color.color = new CSchemeColor();
			for (var i = 0; i < _count; ++i)
			{
				color.color.id = array_colors_types[i];
				color.Calculate(_theme, _clrMap, rgba);

				var _rgba = color.RGBA;
				arr_colors[i] = new CColor(_rgba.R, _rgba.G, _rgba.B);
			}
			return arr_colors;
		};
		
		
		_this.colorMap[1] = [ "#555555", "#9E9E9E", "#727272", "#464646", "#838383", "#C1C1C1" ];
		_this.colorMap[2] = [ themeColors[4].get_hex(), themeColors[5].get_hex(), themeColors[6].get_hex(), themeColors[7].get_hex(), themeColors[8].get_hex(), themeColors[9].get_hex() ];	
		_this.colorMap[3] = [ themeColors[4].get_hex() ];
		_this.colorMap[4] = [ themeColors[5].get_hex() ];
		_this.colorMap[5] = [ themeColors[6].get_hex() ];
		_this.colorMap[6] = [ themeColors[7].get_hex() ];
		_this.colorMap[7] = [ themeColors[8].get_hex() ];
		_this.colorMap[8] = [ themeColors[9].get_hex() ];
		
		for (var i = 0; i < themeColors.length; i++) {
			_this.baseColors.push(themeColors[i].get_hex());
		}
		
		bReady = true;
	}
	
	_this.isReady = function() {
		return bReady;
	}
	
	_this.getBaseColors = function(styleId) {
		if ( styleId && (typeof(styleId) == 'number') ) {
			if ( styleId % 8 === 0 )		
				return _this.colorMap[8];
			else
				return _this.colorMap[styleId % 8];
		}
		else
			return _this.colorMap[2];
	}
}

function ChartPreviewManager() {
	
	var _this = this;
	var bReady = false;	
	var previewGroups = [];
	
	previewGroups[c_oAscChartType.line] = [];
	previewGroups[c_oAscChartType.line][c_oAscChartSubType.normal] = [];
	previewGroups[c_oAscChartType.line][c_oAscChartSubType.stacked] = [];
	previewGroups[c_oAscChartType.line][c_oAscChartSubType.stackedPer] = [];
	
	previewGroups[c_oAscChartType.bar] = [];
	previewGroups[c_oAscChartType.bar][c_oAscChartSubType.normal] = [];
	previewGroups[c_oAscChartType.bar][c_oAscChartSubType.stacked] = [];
	previewGroups[c_oAscChartType.bar][c_oAscChartSubType.stackedPer] = [];
	
	previewGroups[c_oAscChartType.hbar] = [];
	previewGroups[c_oAscChartType.hbar][c_oAscChartSubType.normal] = [];
	previewGroups[c_oAscChartType.hbar][c_oAscChartSubType.stacked] = [];
	previewGroups[c_oAscChartType.hbar][c_oAscChartSubType.stackedPer] = [];
	
	previewGroups[c_oAscChartType.area] = [];
	previewGroups[c_oAscChartType.area][c_oAscChartSubType.normal] = [];
	previewGroups[c_oAscChartType.area][c_oAscChartSubType.stacked] = [];
	previewGroups[c_oAscChartType.area][c_oAscChartSubType.stackedPer] = [];
	
	previewGroups[c_oAscChartType.pie] = [];
	previewGroups[c_oAscChartType.pie][c_oAscChartSubType.normal] = [];
		
	previewGroups[c_oAscChartType.scatter] = [];
	previewGroups[c_oAscChartType.scatter][c_oAscChartSubType.normal] = [];
	
	previewGroups[c_oAscChartType.stock] = [];
	previewGroups[c_oAscChartType.stock][c_oAscChartSubType.normal] = [];
	
	_this.init = function() {
	
		var startTime = new Date();
	
		var api_doc = window["editor"];
		var api_sheet = window["Asc"]["editor"];
		var styleManager = api_doc ? api_doc.chartStyleManager : api_sheet.chartStyleManager;
		var chartRender = new ChartRender();
		
		var preview_w = 50, preview_h = 50;
		
		function createItem(value) {
			return { numFormatStr: "General", isDateTimeFormat: false, value: value };
		}
		
		function fillChartData(chart) {
			
			// Set data
			chart.data = [];
			
			switch (chart.type) {
			
				case c_oAscChartType.line:
					switch (chart.subType) {
						case c_oAscChartSubType.normal:
							chart.data.push( [createItem(2), createItem(1)] );
							chart.data.push( [createItem(3), createItem(2)] );
							chart.data.push( [createItem(2), createItem(3)] );
							chart.data.push( [createItem(3), createItem(2)] );
							break;
						case c_oAscChartSubType.stacked:
							chart.data.push( [createItem(1), createItem(4)] );
							chart.data.push( [createItem(6), createItem(4)] );
							chart.data.push( [createItem(2), createItem(4)] );
							chart.data.push( [createItem(8), createItem(5)] );
							break;
						case c_oAscChartSubType.stackedPer:
							chart.data.push( [createItem(2), createItem(2)] );
							chart.data.push( [createItem(4), createItem(2)] );
							chart.data.push( [createItem(2), createItem(2)] );
							chart.data.push( [createItem(4), createItem(2)] );
							break;
					}
					
					break;
					
				case c_oAscChartType.hbar:
					switch (chart.subType) {
						case c_oAscChartSubType.normal:
							chart.data.push( [createItem(4), createItem(3), createItem(2), createItem(1)] );							
							break;
						case c_oAscChartSubType.stacked:
							chart.data.push( [createItem(4), createItem(5)] );
							chart.data.push( [createItem(3), createItem(4)] );
							chart.data.push( [createItem(2), createItem(3)] );
							chart.data.push( [createItem(1), createItem(2)] );
							break;
						case c_oAscChartSubType.stackedPer:
							chart.data.push( [createItem(7), createItem(7)] );
							chart.data.push( [createItem(5), createItem(6)] );
							chart.data.push( [createItem(3), createItem(5)] );
							chart.data.push( [createItem(1), createItem(4)] );
							break;
					}
					break;
			
				case c_oAscChartType.bar:
					switch (chart.subType) {
						case c_oAscChartSubType.normal:
							chart.data.push( [createItem(1), createItem(2), createItem(3), createItem(4)] );
							break;
						case c_oAscChartSubType.stacked:
							chart.data.push( [createItem(1), createItem(2)] );
							chart.data.push( [createItem(2), createItem(3)] );
							chart.data.push( [createItem(3), createItem(4)] );
							chart.data.push( [createItem(4), createItem(5)] );
							break;
						case c_oAscChartSubType.stackedPer:
							chart.data.push( [createItem(1), createItem(4)] );
							chart.data.push( [createItem(3), createItem(5)] );
							chart.data.push( [createItem(5), createItem(6)] );
							chart.data.push( [createItem(7), createItem(7)] );
							break;
					}
					
					break;
			
				case c_oAscChartType.pie:
					chart.data.push( [createItem(3)] );
					chart.data.push( [createItem(1)] );
					break;
					
				case c_oAscChartType.area:
					switch (chart.subType) {
						case c_oAscChartSubType.normal:
							chart.data.push( [createItem(0), createItem(0)] );
							chart.data.push( [createItem(8), createItem(4)] );
							chart.data.push( [createItem(5), createItem(2)] );
							chart.data.push( [createItem(6), createItem(9)] );
							break;
						case c_oAscChartSubType.stacked:
							chart.data.push( [createItem(0), createItem(4)] );
							chart.data.push( [createItem(8), createItem(4)] );
							chart.data.push( [createItem(5), createItem(4)] );
							chart.data.push( [createItem(11), createItem(4)] );
							break;
						case c_oAscChartSubType.stackedPer:
							chart.data.push( [createItem(0), createItem(4)] );
							chart.data.push( [createItem(4), createItem(4)] );
							chart.data.push( [createItem(1), createItem(4)] );
							chart.data.push( [createItem(16), createItem(4)] );
							break;
					}
					break;
			
				default:
					for (var row = 0; row < maxRow; row++) {
						var values = [];
						for (var col = 0; col < maxCol; col++) {
			
							var item = {};
							item.numFormatStr = "General";
							item.isDateTimeFormat = false;
							item.value = row + col + 1;
							values.push(item);
						}
						chart.data.push(values);
					}
					break;
			}	
		}
		
		for (var chartType in previewGroups) {
			
			var group = [];
			var maxCol = 2, maxRow = 2;
			if (chartType == c_oAscChartType.stock) {
				maxCol = 4;
				maxRow = 3;
			}
				
			for (var style in styleManager.colorMap) {
				
				// Create and minimize properties
				var chart = new CChartData(false);
				chart.xAxis.bShow = chart.xAxis.bGrid = false;
				chart.yAxis.bShow = chart.yAxis.bGrid = false;
				chart.legend.bShow = false;
				
				chart.type = chartType;
				chart.styleId = parseInt(style);
				
				// Build
				switch (chartType) {
					
					case c_oAscChartType.line:
					case c_oAscChartType.bar:
					case c_oAscChartType.hbar:
					case c_oAscChartType.area:
						
						chart.subType = c_oAscChartSubType.normal;
						fillChartData(chart);
						var chartBase64 = chartRender.insertChart( chart, null, preview_w, preview_h, false, true );
						previewGroups[chartType][c_oAscChartSubType.normal][style] = chartBase64;
						
						chart.subType = c_oAscChartSubType.stacked;
						fillChartData(chart);
						var chartBase64 = chartRender.insertChart( chart, null, preview_w, preview_h, false, true );
						previewGroups[chartType][c_oAscChartSubType.stacked][style] = chartBase64;
						
						chart.subType = c_oAscChartSubType.stackedPer;
						fillChartData(chart);
						var chartBase64 = chartRender.insertChart( chart, null, preview_w, preview_h, false, true );
						previewGroups[chartType][c_oAscChartSubType.stackedPer][style] = chartBase64;
					
						break;
						
					case c_oAscChartType.pie:
					case c_oAscChartType.scatter:
					case c_oAscChartType.stock:
					
						chart.subType = c_oAscChartSubType.normal;
						fillChartData(chart);
						var chartBase64 = chartRender.insertChart( chart, null, preview_w, preview_h, false, true );
						previewGroups[chartType][c_oAscChartSubType.normal][style] = chartBase64;
						
						break;
				}				
			}
		}
		bReady = true;
		
		//var endTime = new Date();
		//console.log( "ChartPreviewManager init: " + (endTime.getTime() - startTime.getTime()) );
	}
	
	_this.isReady = function() {
		return bReady;
	}
	
	_this.getChartPreviews = function(chartType, chartSubType) {
		
		if ( chartType && chartSubType && bReady ) {
			var group = previewGroups[chartType][chartSubType];
			var objectGroup = [];
			
			for (var style in group) {
				var chartStyle = new asc_CChartStyle();
				chartStyle.asc_setStyle(style);
				chartStyle.asc_setImageUrl(group[style]);
				objectGroup.push(chartStyle);
			}
			
			return objectGroup;
		}
		else
			null;
	}
}

function OnFormatText(command) {
	frames.message.document.designMode = 'On';
	frames.message.focus();
	frames.message.document.execCommand(command, 0, 0);
	alert(frames.message.document.body.innerHTML);
}

//-----------------------------------------------------------------------------------
// Calculate
//-----------------------------------------------------------------------------------

function calcGutter(axis,min,max,ymin,ymax,isSkip,isFormatCell) {
	var scale = bar.scale
	if(undefined == scale)
		scale = [max, min]
	if ('scatter' == bar.type) {
		bar.scale = OfficeExcel.getScale(false, bar,min,max,ymin,ymax);
		bar.xScale = OfficeExcel.getScale(true, bar,min,max,ymin,ymax);
	}
}
//ширины самих линий графика
function calcWidthGraph() {
	
	if ( !chartCanvas )
		return;
	
	var trueWidth = parseInt(chartCanvas.width) - bar._chartGutter._left - bar._chartGutter._right;
	var trueHeight = parseInt(chartCanvas.height) - bar._chartGutter._top - bar._chartGutter._bottom;
	
	if ('bar' == bar.type || 'hbar' == bar.type) {
		var mainKoff = 0.43;
		var data = bar.data[0];
		var lengthOfData = bar.data.length;
		if (bar._otherProps._type == 'accumulative' && 'bar' == bar.type || bar._otherProps._autoGrouping == 'stackedPer' || bar._otherProps._autoGrouping == 'stacked') {
			data = bar.data;
			//lengthOfData = 1;
			mainKoff = 0.597;
		}
		else if (1 == data.length) {
			mainKoff = 0.597;
		}
		else if (2 == data.length) {
			mainKoff = 0.43;
		}
		else {
			var tempKoff = 0.188;
			for (var j = 2; j < data.length; j++) {
				mainKoff = mainKoff - tempKoff / (j);
				if(mainKoff < 0.05)
					break;
				if(mainKoff - tempKoff / (j+1) < 0)
					tempKoff = tempKoff/10;
			}
		}


		var pointKoff = 1 - Math.abs(mainKoff);
		if ('hbar' == bar.type)
			bar._otherProps._vmargin = ((trueHeight - trueHeight * pointKoff) / 2) / (lengthOfData);
		else
			bar._otherProps._hmargin = ((trueWidth - trueWidth * pointKoff) / 2) / lengthOfData;
	}
	else if('line' == bar.type)
	{
		var lengthOfData = bar.data[0].length;
		var widthChart = (trueWidth/lengthOfData)*(lengthOfData - 1) + 5;
		
		bar._otherProps._hmargin = (trueWidth - widthChart) / 2;
	}
	else {
		var pointKoff = 1 - 1 / (bar.data[0].length)
		bar._otherProps._hmargin = (trueWidth - trueWidth * pointKoff) / 2;
	}
	if(bar._otherProps._filled == true)
		bar._otherProps._hmargin = 0;

}

function calcAllMargin(isFormatCell,isformatCellScOy,minX,maxX,minY,maxY, chart) {
	var scale = 1;
	if(OfficeExcel && OfficeExcel.drawingCtxCharts)
		scale = OfficeExcel.drawingCtxCharts.scaleFactor;
	var context = OfficeExcel.drawingCtxCharts;
	
	if (typeof (bar.data[0]) == 'object') {
		var arrMin = [];
		var arrMax = [];
		for (var j = 0; j < bar.data.length; j++) {
			min = Math.min.apply(null, bar.data[j]);
			max = Math.max.apply(null, bar.data[j]);
			arrMin[j] = min;
			arrMax[j] = max;
		}
		var min = Math.min.apply(null, arrMin);
		var max = Math.max.apply(null, arrMax);
	}
	else {
		var min = Math.min.apply(null, bar.data);
		var max = Math.max.apply(null, bar.data);
	}
	
	if(isNaN(max))
		max = bar._otherProps._ymax;
	if(isNaN(min))
		min = bar._otherProps._ymin;
	
	var left = 0;
	var standartMargin = 14;
	bar.context.font = '13px Arial';
	
	//для определении ширины текста(подписи оси OY), необходимо получить scale
	var tempScale;
	if(!bar.scale && bar.type != "pie")
	{
		if(bar.type == 'hbar' && bar._otherProps._autoGrouping == 'stackedPer')
		{
			for (i=0; i<bar.data.length; ++i) {
				if (typeof(bar.data[i]) == 'object') {
					var value = Number(OfficeExcel.array_max(bar.data[i], true));
				} else {
					var value = Number(Math.abs(bar.data[i]));
				}

				bar.max = Math.max(Math.abs(bar.max), Math.abs(value));
			}

			tempScale = OfficeExcel.getScale(bar.max);
		}
		else
			tempScale = OfficeExcel.getScale(Math.abs(parseFloat(chart.max)),bar,chart.min,chart.max);
		
		if(bar.type == 'bar')
			bar.min = bar._otherProps._ymin;
		else if(bar.type == 'hbar')
		{
			bar._otherProps._background_grid_autofit_numvlines = tempScale.length;
			bar._otherProps._background_grid_autofit_numhlines = bar.data.length;
		}
	}
	else
		tempScale = bar.scale;

	if(tempScale != undefined && tempScale[tempScale.length -1] != undefined && bar._otherProps._ylabels != false)
	{
		//left = bar.context.measureText(bar.scale[bar.scale.length -1]).width;
		var tempArr = [];
		for (var j = 0; j < tempScale.length; j++) {
			if(bar.type == 'hbar')
				tempArr[j] = bar.context.measureText(tempScale[j]).width
			else if(bar.type == 'scatter')
				tempArr[j] = bar.context.measureText(OfficeExcel.numToFormatText(tempScale[j],isformatCellScOy)).width
			else
				tempArr[j] = bar.context.measureText(OfficeExcel.numToFormatText(tempScale[j],isFormatCell)).width
		}
		if((bar.type == 'hbar' && min < 0 )|| ( bar.type == 'scatter' && bar._otherProps._type != 'burse2' && minX < 0))
			left = 0
		else
		{
			left = Math.max.apply(null,tempArr) + 5;
			if(bar._otherProps._autoGrouping == 'stackedPer')
				left += 12;//width '%'
		}
	}

	if(bar.type == 'pie')
	{
		var left = 0;
		var bottom = 0;
		var right = 0;
		var top = 0;
	}
	else
	{
		if (bar._yAxisTitle._align == 'rev')
		{
			var font = getFontProperties("yTitle");
			var axisTitleProp = getMaxPropertiesText(context,font, bar._yAxisTitle._text);
			var heigthText = (context.getHeightText()/0.75);
			//прибавляем высоту текста названия + стандартный маргин 
			left += heigthText + 12;
		}
		else if (bar._yAxisTitle._align == 'hor')
			left += 95;
		else if (bar._yAxisTitle._align == 'ver')
			left += 0;

		var right = 0;
		var top = 0;
		var bottom = 0;
		if (bar._xAxisTitle._text != '')
		{
			var font = getFontProperties("xTitle");
			var axisTitleProp = getMaxPropertiesText(context,font, bar._xAxisTitle._text);
			var heigthText = (context.getHeightText()/0.75);
			//прибавляем высоту текста названия + стандартный маргин 
			bottom += heigthText + 14;
		}
		if ((min >= 0 || bar.type == 'hbar') &&  bar._otherProps._xlabels)
		{
			bottom +=20;
		}
		if(bar._xAxisTitle._text == '' && (min >= 0 || bar.type == 'hbar') &&  bar._otherProps._xlabels)
			bottom += 7;
	}
	
	//+высота названия диаграммы
	if (bar._chartTitle._text != null && bar._chartTitle._text != '')
	{
		var font = getFontProperties("title");
		var axisTitleProp = getMaxPropertiesText(context,font, bar._chartTitle._text);
		var heigthText = (context.getHeightText()/0.75);
		//прибавляем высоту текста названия + стандартный маргин 
		top += heigthText + 7;
	}
	//+ высота легенды
	if(bar._otherProps._key_halign == 'top' || bar._otherProps._key_halign == 'bottom')
	{
		var font = getFontProperties("key");
		var props = getMaxPropertiesText(context,font,bar._otherProps._key);
		var heigthTextKey = (context.getHeightText()/0.75);
		var kF = 1;
		if(bar.type == 'pie')
			kF = 2;
		if(bar._otherProps._key_halign == 'top')
			top += (heigthTextKey + 7)*kF;
		else
			bottom += (heigthTextKey + 7)*kF;
	}
	//+ ширина легенды
	if (bar._otherProps._key_halign == 'left' || bar._otherProps._key_halign == 'right')
	{
		var widthLine = 28;
		//находим ширину текста легенды(то есть её максимального элемента), в дальнейшем будем возвращать ширину автофигуры
		var font = getFontProperties("key");
		var widthText = getMaxPropertiesText(context,font,bar._otherProps._key);
		var widthKey = widthText.width/scale + 2 + widthLine;
		//в MSExcel справа от легенды всегда остаётся такой маргин 
		if(bar._otherProps._key_halign == 'left')
			left += widthKey + 7;
		else
			right += widthKey + 7;
	}
	
	if(bottom == 0)
		bottom = standartMargin;
	var standartMarginTop = standartMargin;
	if(bar.type == 'pie' && bar._otherProps._key_halign == 'top')
		standartMarginTop = 0;
	bar._chartGutter._left = (left)*scale + standartMargin;
	bar._chartGutter._right = (standartMargin + right)*scale;
	bar._chartGutter._top = (standartMarginTop + top)*scale;
	bar._chartGutter._bottom = (bottom)*scale;
}

//-----------------------------------------------------------------------------------
// Draw 
//-----------------------------------------------------------------------------------

function checkDataRange(type,subType,dataRange,isRows,worksheet) {
	var columns = false;
	var rows = false;
	if(isRows)
		rows = true;
	else
		columns = true;
	
	//проверка максимального дипазона
	var maxSeries = 255; 
	var minStockVal = 4;
	var bbox = {
		c1: dataRange.first.col,
		c2: dataRange.last.col,
		r1: dataRange.first.row,
		r2: dataRange.last.row
	}
	if(((type == 'Area' || type == 'Line' || type == 'Bar' || type == 'HBar') && ((columns && ((bbox.c2 - bbox.c1 + 1) > maxSeries || (bbox.r2 - bbox.r1 + 1) > gc_nMaxRow)) || (rows && ((bbox.c2 - bbox.c1 + 1) > gc_nMaxRow || (bbox.r2 - bbox.r1 + 1) > maxSeries)))))
	{
		worksheet.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.DataRangeError, c_oAscError.Level.NoCritical)
		return false;
	}
	else if((type == 'Pie') && ((bbox.c2 - bbox.c1 + 1) > maxSeries || (bbox.r2 - bbox.r1 + 1) > maxSeries))
	{
		worksheet.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.DataRangeError, c_oAscError.Level.NoCritical)
		return false;
	}
	else if (((type == 'Scatter' || type == 'Stock') && ((columns && ((bbox.c2 - bbox.c1 ) > maxSeries || (bbox.r2 - bbox.r1) > gc_nMaxRow)) || (rows && ((bbox.c2 - bbox.c1) > gc_nMaxRow || (bbox.r2 - bbox.r1) > maxSeries)))))
	{
		worksheet.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.DataRangeError, c_oAscError.Level.NoCritical)
		return false;
	}
	else if(type == 'Stock')
	{
		if(((columns && ((bbox.c2 - bbox.c1 +1) == minStockVal && (bbox.r2 - bbox.r1 + 1) >= minStockVal)) || (rows && ((bbox.r2 - bbox.r1 + 1) == minStockVal && (bbox.c2 - bbox.c1 + 1) >= minStockVal))))
			return true;
		else
		{
			worksheet.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.StockChartError, c_oAscError.Level.NoCritical)
			return false;
		}
	}
	else
		return true;
}

function formulaToRange(formula, worksheet) {
	var range = null;
	if ( formula && worksheet ) {
		var ref3D = parserHelp.is3DRef(formula, 0);
		if ( !ref3D[0] )
			range = worksheet.getRange2(formula.toUpperCase());
		else {
			var resultRef = parserHelp.parse3DRef(formula);
			if ( null !== resultRef ) {
				var ws = worksheet.workbook.getWorksheetByName(resultRef.sheet);
				if ( ws )
					range = ws.getRange2(resultRef.range);
			}
		}
	}
	return range;
}

function insertChart(chart, activeWorkSheet, width, height, isNewChart) {
	var isSeries = false;
	var formatCell = 'General';
	var formatCellScOy = 'General';
	
	var api_doc = window["editor"];
	var api_sheet = window["Asc"]["editor"];
	var styleManager = api_doc ? api_doc.chartStyleManager : api_sheet.chartStyleManager;
	
	arrBaseColors = styleManager.getBaseColors( parseInt(chart.styleId) );
	if(chart.series && chart.series.length !=0)
	{
		isSeries = true;
		var series = chart.series;
		//var ws = chart.worksheet;
		var ws = chart.range.intervalObject.worksheet;
		var arrValues = [];
		var max = 0;
		var min = 0; 
		var minY = 0;
		var maxY = 0;
		var isSkip = [];
		var skipSeries = [];
		
		var isEn = false;
		var isEnY = false;
		
		if (chart.type == 'Scatter' && series[0].xVal.Formula != null)//в случае точечной диаграммы отдельная обработка
		{
			var isEnY = false
			for(l = 0; l < series.length; ++l)
			{
				var n = 0;
				
				arrValues[l] = [];
				var formula = formulaToRange(series[l].Val.Formula,ws);
				var xFormula = formulaToRange(series[l].xVal.Formula,ws);
				
				var firstCol = formula.first.col;<commit_msg>добавил условие для обработки серий<commit_after>﻿var bar;
var chartCanvas = null;
var g_bChartPreview = false;

function ChartRender() {
	
	this.insertChart = function(chart, activeWorkSheet, width, height, isNewChart, bChartPreview) {
	
		var chartBase64 = null;
		if ( bChartPreview )
			g_bChartPreview = true;
		else
			g_bChartPreview = false;
		if (chart.worksheet && !OfficeExcel.drawingCtxCharts)//выставление контекста для отрисовки
			OfficeExcel.drawingCtxCharts = chart.worksheet.getDrawingContextCharts();
		else if(window["editor"] && !OfficeExcel.drawingCtxCharts)
			OfficeExcel.drawingCtxCharts = new CDrawingContextWord();
		chartCanvas = document.createElement('canvas');
		$(chartCanvas).css('width', width);
		$(chartCanvas).css('height', height);
		$(chartCanvas)[0].height = height;
		$(chartCanvas)[0].width = width;
		
		if ( insertChart(chart, activeWorkSheet, width, height, isNewChart) )
			chartBase64 = chartCanvas.toDataURL();
		
		return chartBase64;
	}
}

var arrBaseColors = [];

function ChartStyleManager() {
	
	var _this = this;
	var bReady = false;
	_this.colorMap = [];
	_this.baseColors = [];
	
	//-----------------------------------------------------------------------------------
	// Methods
	//-----------------------------------------------------------------------------------
	
	_this.init = function() {
		
		_this.colorMap = [];		
		var api_doc = window["editor"];
		var api_sheet = window["Asc"]["editor"];
		var themeColors = [];
		if ( api_sheet )
			themeColors = api_sheet.GuiControlColorsMap;
		else
			themeColors = getDocColors(api_doc);
		
		function getDocColors(api) {
			var _theme  = api.WordControl.m_oLogicDocument.theme;
			var _clrMap = api.WordControl.m_oLogicDocument.clrSchemeMap.color_map;

			var arr_colors = new Array(10);
			var rgba = {R:0, G:0, B:0, A:255};
			// bg1,tx1,bg2,tx2,accent1 - accent6
			var array_colors_types = [6, 15, 7, 16, 0, 1, 2, 3, 4, 5];
			var _count = array_colors_types.length;

			var color = new CUniColor();
			color.color = new CSchemeColor();
			for (var i = 0; i < _count; ++i)
			{
				color.color.id = array_colors_types[i];
				color.Calculate(_theme, _clrMap, rgba);

				var _rgba = color.RGBA;
				arr_colors[i] = new CColor(_rgba.R, _rgba.G, _rgba.B);
			}
			return arr_colors;
		};
		
		
		_this.colorMap[1] = [ "#555555", "#9E9E9E", "#727272", "#464646", "#838383", "#C1C1C1" ];
		_this.colorMap[2] = [ themeColors[4].get_hex(), themeColors[5].get_hex(), themeColors[6].get_hex(), themeColors[7].get_hex(), themeColors[8].get_hex(), themeColors[9].get_hex() ];	
		_this.colorMap[3] = [ themeColors[4].get_hex() ];
		_this.colorMap[4] = [ themeColors[5].get_hex() ];
		_this.colorMap[5] = [ themeColors[6].get_hex() ];
		_this.colorMap[6] = [ themeColors[7].get_hex() ];
		_this.colorMap[7] = [ themeColors[8].get_hex() ];
		_this.colorMap[8] = [ themeColors[9].get_hex() ];
		
		for (var i = 0; i < themeColors.length; i++) {
			_this.baseColors.push(themeColors[i].get_hex());
		}
		
		bReady = true;
	}
	
	_this.isReady = function() {
		return bReady;
	}
	
	_this.getBaseColors = function(styleId) {
		if ( styleId && (typeof(styleId) == 'number') ) {
			if ( styleId % 8 === 0 )		
				return _this.colorMap[8];
			else
				return _this.colorMap[styleId % 8];
		}
		else
			return _this.colorMap[2];
	}
}

function ChartPreviewManager() {
	
	var _this = this;
	var bReady = false;	
	var previewGroups = [];
	
	previewGroups[c_oAscChartType.line] = [];
	previewGroups[c_oAscChartType.line][c_oAscChartSubType.normal] = [];
	previewGroups[c_oAscChartType.line][c_oAscChartSubType.stacked] = [];
	previewGroups[c_oAscChartType.line][c_oAscChartSubType.stackedPer] = [];
	
	previewGroups[c_oAscChartType.bar] = [];
	previewGroups[c_oAscChartType.bar][c_oAscChartSubType.normal] = [];
	previewGroups[c_oAscChartType.bar][c_oAscChartSubType.stacked] = [];
	previewGroups[c_oAscChartType.bar][c_oAscChartSubType.stackedPer] = [];
	
	previewGroups[c_oAscChartType.hbar] = [];
	previewGroups[c_oAscChartType.hbar][c_oAscChartSubType.normal] = [];
	previewGroups[c_oAscChartType.hbar][c_oAscChartSubType.stacked] = [];
	previewGroups[c_oAscChartType.hbar][c_oAscChartSubType.stackedPer] = [];
	
	previewGroups[c_oAscChartType.area] = [];
	previewGroups[c_oAscChartType.area][c_oAscChartSubType.normal] = [];
	previewGroups[c_oAscChartType.area][c_oAscChartSubType.stacked] = [];
	previewGroups[c_oAscChartType.area][c_oAscChartSubType.stackedPer] = [];
	
	previewGroups[c_oAscChartType.pie] = [];
	previewGroups[c_oAscChartType.pie][c_oAscChartSubType.normal] = [];
		
	previewGroups[c_oAscChartType.scatter] = [];
	previewGroups[c_oAscChartType.scatter][c_oAscChartSubType.normal] = [];
	
	previewGroups[c_oAscChartType.stock] = [];
	previewGroups[c_oAscChartType.stock][c_oAscChartSubType.normal] = [];
	
	_this.init = function() {
	
		var startTime = new Date();
	
		var api_doc = window["editor"];
		var api_sheet = window["Asc"]["editor"];
		var styleManager = api_doc ? api_doc.chartStyleManager : api_sheet.chartStyleManager;
		var chartRender = new ChartRender();
		
		var preview_w = 50, preview_h = 50;
		
		function createItem(value) {
			return { numFormatStr: "General", isDateTimeFormat: false, value: value };
		}
		
		function fillChartData(chart) {
			
			// Set data
			chart.data = [];
			
			switch (chart.type) {
			
				case c_oAscChartType.line:
					switch (chart.subType) {
						case c_oAscChartSubType.normal:
							chart.data.push( [createItem(2), createItem(1)] );
							chart.data.push( [createItem(3), createItem(2)] );
							chart.data.push( [createItem(2), createItem(3)] );
							chart.data.push( [createItem(3), createItem(2)] );
							break;
						case c_oAscChartSubType.stacked:
							chart.data.push( [createItem(1), createItem(4)] );
							chart.data.push( [createItem(6), createItem(4)] );
							chart.data.push( [createItem(2), createItem(4)] );
							chart.data.push( [createItem(8), createItem(5)] );
							break;
						case c_oAscChartSubType.stackedPer:
							chart.data.push( [createItem(2), createItem(2)] );
							chart.data.push( [createItem(4), createItem(2)] );
							chart.data.push( [createItem(2), createItem(2)] );
							chart.data.push( [createItem(4), createItem(2)] );
							break;
					}
					
					break;
					
				case c_oAscChartType.hbar:
					switch (chart.subType) {
						case c_oAscChartSubType.normal:
							chart.data.push( [createItem(4), createItem(3), createItem(2), createItem(1)] );							
							break;
						case c_oAscChartSubType.stacked:
							chart.data.push( [createItem(4), createItem(5)] );
							chart.data.push( [createItem(3), createItem(4)] );
							chart.data.push( [createItem(2), createItem(3)] );
							chart.data.push( [createItem(1), createItem(2)] );
							break;
						case c_oAscChartSubType.stackedPer:
							chart.data.push( [createItem(7), createItem(7)] );
							chart.data.push( [createItem(5), createItem(6)] );
							chart.data.push( [createItem(3), createItem(5)] );
							chart.data.push( [createItem(1), createItem(4)] );
							break;
					}
					break;
			
				case c_oAscChartType.bar:
					switch (chart.subType) {
						case c_oAscChartSubType.normal:
							chart.data.push( [createItem(1), createItem(2), createItem(3), createItem(4)] );
							break;
						case c_oAscChartSubType.stacked:
							chart.data.push( [createItem(1), createItem(2)] );
							chart.data.push( [createItem(2), createItem(3)] );
							chart.data.push( [createItem(3), createItem(4)] );
							chart.data.push( [createItem(4), createItem(5)] );
							break;
						case c_oAscChartSubType.stackedPer:
							chart.data.push( [createItem(1), createItem(4)] );
							chart.data.push( [createItem(3), createItem(5)] );
							chart.data.push( [createItem(5), createItem(6)] );
							chart.data.push( [createItem(7), createItem(7)] );
							break;
					}
					
					break;
			
				case c_oAscChartType.pie:
					chart.data.push( [createItem(3)] );
					chart.data.push( [createItem(1)] );
					break;
					
				case c_oAscChartType.area:
					switch (chart.subType) {
						case c_oAscChartSubType.normal:
							chart.data.push( [createItem(0), createItem(0)] );
							chart.data.push( [createItem(8), createItem(4)] );
							chart.data.push( [createItem(5), createItem(2)] );
							chart.data.push( [createItem(6), createItem(9)] );
							break;
						case c_oAscChartSubType.stacked:
							chart.data.push( [createItem(0), createItem(4)] );
							chart.data.push( [createItem(8), createItem(4)] );
							chart.data.push( [createItem(5), createItem(4)] );
							chart.data.push( [createItem(11), createItem(4)] );
							break;
						case c_oAscChartSubType.stackedPer:
							chart.data.push( [createItem(0), createItem(4)] );
							chart.data.push( [createItem(4), createItem(4)] );
							chart.data.push( [createItem(1), createItem(4)] );
							chart.data.push( [createItem(16), createItem(4)] );
							break;
					}
					break;
			
				default:
					for (var row = 0; row < maxRow; row++) {
						var values = [];
						for (var col = 0; col < maxCol; col++) {
			
							var item = {};
							item.numFormatStr = "General";
							item.isDateTimeFormat = false;
							item.value = row + col + 1;
							values.push(item);
						}
						chart.data.push(values);
					}
					break;
			}	
		}
		
		for (var chartType in previewGroups) {
			
			var group = [];
			var maxCol = 2, maxRow = 2;
			if (chartType == c_oAscChartType.stock) {
				maxCol = 4;
				maxRow = 3;
			}
				
			for (var style in styleManager.colorMap) {
				
				// Create and minimize properties
				var chart = new CChartData(false);
				chart.xAxis.bShow = chart.xAxis.bGrid = false;
				chart.yAxis.bShow = chart.yAxis.bGrid = false;
				chart.legend.bShow = false;
				
				chart.type = chartType;
				chart.styleId = parseInt(style);
				
				// Build
				switch (chartType) {
					
					case c_oAscChartType.line:
					case c_oAscChartType.bar:
					case c_oAscChartType.hbar:
					case c_oAscChartType.area:
						
						chart.subType = c_oAscChartSubType.normal;
						fillChartData(chart);
						var chartBase64 = chartRender.insertChart( chart, null, preview_w, preview_h, false, true );
						previewGroups[chartType][c_oAscChartSubType.normal][style] = chartBase64;
						
						chart.subType = c_oAscChartSubType.stacked;
						fillChartData(chart);
						var chartBase64 = chartRender.insertChart( chart, null, preview_w, preview_h, false, true );
						previewGroups[chartType][c_oAscChartSubType.stacked][style] = chartBase64;
						
						chart.subType = c_oAscChartSubType.stackedPer;
						fillChartData(chart);
						var chartBase64 = chartRender.insertChart( chart, null, preview_w, preview_h, false, true );
						previewGroups[chartType][c_oAscChartSubType.stackedPer][style] = chartBase64;
					
						break;
						
					case c_oAscChartType.pie:
					case c_oAscChartType.scatter:
					case c_oAscChartType.stock:
					
						chart.subType = c_oAscChartSubType.normal;
						fillChartData(chart);
						var chartBase64 = chartRender.insertChart( chart, null, preview_w, preview_h, false, true );
						previewGroups[chartType][c_oAscChartSubType.normal][style] = chartBase64;
						
						break;
				}				
			}
		}
		bReady = true;
		
		//var endTime = new Date();
		//console.log( "ChartPreviewManager init: " + (endTime.getTime() - startTime.getTime()) );
	}
	
	_this.isReady = function() {
		return bReady;
	}
	
	_this.getChartPreviews = function(chartType, chartSubType) {
		
		if ( chartType && chartSubType && bReady ) {
			var group = previewGroups[chartType][chartSubType];
			var objectGroup = [];
			
			for (var style in group) {
				var chartStyle = new asc_CChartStyle();
				chartStyle.asc_setStyle(style);
				chartStyle.asc_setImageUrl(group[style]);
				objectGroup.push(chartStyle);
			}
			
			return objectGroup;
		}
		else
			null;
	}
}

function OnFormatText(command) {
	frames.message.document.designMode = 'On';
	frames.message.focus();
	frames.message.document.execCommand(command, 0, 0);
	alert(frames.message.document.body.innerHTML);
}

//-----------------------------------------------------------------------------------
// Calculate
//-----------------------------------------------------------------------------------

function calcGutter(axis,min,max,ymin,ymax,isSkip,isFormatCell) {
	var scale = bar.scale
	if(undefined == scale)
		scale = [max, min]
	if ('scatter' == bar.type) {
		bar.scale = OfficeExcel.getScale(false, bar,min,max,ymin,ymax);
		bar.xScale = OfficeExcel.getScale(true, bar,min,max,ymin,ymax);
	}
}
//ширины самих линий графика
function calcWidthGraph() {
	
	if ( !chartCanvas )
		return;
	
	var trueWidth = parseInt(chartCanvas.width) - bar._chartGutter._left - bar._chartGutter._right;
	var trueHeight = parseInt(chartCanvas.height) - bar._chartGutter._top - bar._chartGutter._bottom;
	
	if ('bar' == bar.type || 'hbar' == bar.type) {
		var mainKoff = 0.43;
		var data = bar.data[0];
		var lengthOfData = bar.data.length;
		if (bar._otherProps._type == 'accumulative' && 'bar' == bar.type || bar._otherProps._autoGrouping == 'stackedPer' || bar._otherProps._autoGrouping == 'stacked') {
			data = bar.data;
			//lengthOfData = 1;
			mainKoff = 0.597;
		}
		else if (1 == data.length) {
			mainKoff = 0.597;
		}
		else if (2 == data.length) {
			mainKoff = 0.43;
		}
		else {
			var tempKoff = 0.188;
			for (var j = 2; j < data.length; j++) {
				mainKoff = mainKoff - tempKoff / (j);
				if(mainKoff < 0.05)
					break;
				if(mainKoff - tempKoff / (j+1) < 0)
					tempKoff = tempKoff/10;
			}
		}


		var pointKoff = 1 - Math.abs(mainKoff);
		if ('hbar' == bar.type)
			bar._otherProps._vmargin = ((trueHeight - trueHeight * pointKoff) / 2) / (lengthOfData);
		else
			bar._otherProps._hmargin = ((trueWidth - trueWidth * pointKoff) / 2) / lengthOfData;
	}
	else if('line' == bar.type)
	{
		var lengthOfData = bar.data[0].length;
		var widthChart = (trueWidth/lengthOfData)*(lengthOfData - 1) + 5;
		
		bar._otherProps._hmargin = (trueWidth - widthChart) / 2;
	}
	else {
		var pointKoff = 1 - 1 / (bar.data[0].length)
		bar._otherProps._hmargin = (trueWidth - trueWidth * pointKoff) / 2;
	}
	if(bar._otherProps._filled == true)
		bar._otherProps._hmargin = 0;

}

function calcAllMargin(isFormatCell,isformatCellScOy,minX,maxX,minY,maxY, chart) {
	var scale = 1;
	if(OfficeExcel && OfficeExcel.drawingCtxCharts)
		scale = OfficeExcel.drawingCtxCharts.scaleFactor;
	var context = OfficeExcel.drawingCtxCharts;
	
	if (typeof (bar.data[0]) == 'object') {
		var arrMin = [];
		var arrMax = [];
		for (var j = 0; j < bar.data.length; j++) {
			min = Math.min.apply(null, bar.data[j]);
			max = Math.max.apply(null, bar.data[j]);
			arrMin[j] = min;
			arrMax[j] = max;
		}
		var min = Math.min.apply(null, arrMin);
		var max = Math.max.apply(null, arrMax);
	}
	else {
		var min = Math.min.apply(null, bar.data);
		var max = Math.max.apply(null, bar.data);
	}
	
	if(isNaN(max))
		max = bar._otherProps._ymax;
	if(isNaN(min))
		min = bar._otherProps._ymin;
	
	var left = 0;
	var standartMargin = 14;
	bar.context.font = '13px Arial';
	
	//для определении ширины текста(подписи оси OY), необходимо получить scale
	var tempScale;
	if(!bar.scale && bar.type != "pie")
	{
		if(bar.type == 'hbar' && bar._otherProps._autoGrouping == 'stackedPer')
		{
			for (i=0; i<bar.data.length; ++i) {
				if (typeof(bar.data[i]) == 'object') {
					var value = Number(OfficeExcel.array_max(bar.data[i], true));
				} else {
					var value = Number(Math.abs(bar.data[i]));
				}

				bar.max = Math.max(Math.abs(bar.max), Math.abs(value));
			}

			tempScale = OfficeExcel.getScale(bar.max);
		}
		else
			tempScale = OfficeExcel.getScale(Math.abs(parseFloat(chart.max)),bar,chart.min,chart.max);
		
		if(bar.type == 'bar')
			bar.min = bar._otherProps._ymin;
		else if(bar.type == 'hbar')
		{
			bar._otherProps._background_grid_autofit_numvlines = tempScale.length;
			bar._otherProps._background_grid_autofit_numhlines = bar.data.length;
		}
	}
	else
		tempScale = bar.scale;

	if(tempScale != undefined && tempScale[tempScale.length -1] != undefined && bar._otherProps._ylabels != false)
	{
		//left = bar.context.measureText(bar.scale[bar.scale.length -1]).width;
		var tempArr = [];
		for (var j = 0; j < tempScale.length; j++) {
			if(bar.type == 'hbar')
				tempArr[j] = bar.context.measureText(tempScale[j]).width
			else if(bar.type == 'scatter')
				tempArr[j] = bar.context.measureText(OfficeExcel.numToFormatText(tempScale[j],isformatCellScOy)).width
			else
				tempArr[j] = bar.context.measureText(OfficeExcel.numToFormatText(tempScale[j],isFormatCell)).width
		}
		if((bar.type == 'hbar' && min < 0 )|| ( bar.type == 'scatter' && bar._otherProps._type != 'burse2' && minX < 0))
			left = 0
		else
		{
			left = Math.max.apply(null,tempArr) + 5;
			if(bar._otherProps._autoGrouping == 'stackedPer')
				left += 12;//width '%'
		}
	}

	if(bar.type == 'pie')
	{
		var left = 0;
		var bottom = 0;
		var right = 0;
		var top = 0;
	}
	else
	{
		if (bar._yAxisTitle._align == 'rev')
		{
			var font = getFontProperties("yTitle");
			var axisTitleProp = getMaxPropertiesText(context,font, bar._yAxisTitle._text);
			var heigthText = (context.getHeightText()/0.75);
			//прибавляем высоту текста названия + стандартный маргин 
			left += heigthText + 12;
		}
		else if (bar._yAxisTitle._align == 'hor')
			left += 95;
		else if (bar._yAxisTitle._align == 'ver')
			left += 0;

		var right = 0;
		var top = 0;
		var bottom = 0;
		if (bar._xAxisTitle._text != '')
		{
			var font = getFontProperties("xTitle");
			var axisTitleProp = getMaxPropertiesText(context,font, bar._xAxisTitle._text);
			var heigthText = (context.getHeightText()/0.75);
			//прибавляем высоту текста названия + стандартный маргин 
			bottom += heigthText + 14;
		}
		if ((min >= 0 || bar.type == 'hbar') &&  bar._otherProps._xlabels)
		{
			bottom +=20;
		}
		if(bar._xAxisTitle._text == '' && (min >= 0 || bar.type == 'hbar') &&  bar._otherProps._xlabels)
			bottom += 7;
	}
	
	//+высота названия диаграммы
	if (bar._chartTitle._text != null && bar._chartTitle._text != '')
	{
		var font = getFontProperties("title");
		var axisTitleProp = getMaxPropertiesText(context,font, bar._chartTitle._text);
		var heigthText = (context.getHeightText()/0.75);
		//прибавляем высоту текста названия + стандартный маргин 
		top += heigthText + 7;
	}
	//+ высота легенды
	if(bar._otherProps._key_halign == 'top' || bar._otherProps._key_halign == 'bottom')
	{
		var font = getFontProperties("key");
		var props = getMaxPropertiesText(context,font,bar._otherProps._key);
		var heigthTextKey = (context.getHeightText()/0.75);
		var kF = 1;
		if(bar.type == 'pie')
			kF = 2;
		if(bar._otherProps._key_halign == 'top')
			top += (heigthTextKey + 7)*kF;
		else
			bottom += (heigthTextKey + 7)*kF;
	}
	//+ ширина легенды
	if (bar._otherProps._key_halign == 'left' || bar._otherProps._key_halign == 'right')
	{
		var widthLine = 28;
		//находим ширину текста легенды(то есть её максимального элемента), в дальнейшем будем возвращать ширину автофигуры
		var font = getFontProperties("key");
		var widthText = getMaxPropertiesText(context,font,bar._otherProps._key);
		var widthKey = widthText.width/scale + 2 + widthLine;
		//в MSExcel справа от легенды всегда остаётся такой маргин 
		if(bar._otherProps._key_halign == 'left')
			left += widthKey + 7;
		else
			right += widthKey + 7;
	}
	
	if(bottom == 0)
		bottom = standartMargin;
	var standartMarginTop = standartMargin;
	if(bar.type == 'pie' && bar._otherProps._key_halign == 'top')
		standartMarginTop = 0;
	bar._chartGutter._left = (left)*scale + standartMargin;
	bar._chartGutter._right = (standartMargin + right)*scale;
	bar._chartGutter._top = (standartMarginTop + top)*scale;
	bar._chartGutter._bottom = (bottom)*scale;
}

//-----------------------------------------------------------------------------------
// Draw 
//-----------------------------------------------------------------------------------

function checkDataRange(type,subType,dataRange,isRows,worksheet) {
	var columns = false;
	var rows = false;
	if(isRows)
		rows = true;
	else
		columns = true;
	
	//проверка максимального дипазона
	var maxSeries = 255; 
	var minStockVal = 4;
	var bbox = {
		c1: dataRange.first.col,
		c2: dataRange.last.col,
		r1: dataRange.first.row,
		r2: dataRange.last.row
	}
	if(((type == 'Area' || type == 'Line' || type == 'Bar' || type == 'HBar') && ((columns && ((bbox.c2 - bbox.c1 + 1) > maxSeries || (bbox.r2 - bbox.r1 + 1) > gc_nMaxRow)) || (rows && ((bbox.c2 - bbox.c1 + 1) > gc_nMaxRow || (bbox.r2 - bbox.r1 + 1) > maxSeries)))))
	{
		worksheet.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.DataRangeError, c_oAscError.Level.NoCritical)
		return false;
	}
	else if((type == 'Pie') && ((bbox.c2 - bbox.c1 + 1) > maxSeries || (bbox.r2 - bbox.r1 + 1) > maxSeries))
	{
		worksheet.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.DataRangeError, c_oAscError.Level.NoCritical)
		return false;
	}
	else if (((type == 'Scatter' || type == 'Stock') && ((columns && ((bbox.c2 - bbox.c1 ) > maxSeries || (bbox.r2 - bbox.r1) > gc_nMaxRow)) || (rows && ((bbox.c2 - bbox.c1) > gc_nMaxRow || (bbox.r2 - bbox.r1) > maxSeries)))))
	{
		worksheet.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.DataRangeError, c_oAscError.Level.NoCritical)
		return false;
	}
	else if(type == 'Stock')
	{
		if(((columns && ((bbox.c2 - bbox.c1 +1) == minStockVal && (bbox.r2 - bbox.r1 + 1) >= minStockVal)) || (rows && ((bbox.r2 - bbox.r1 + 1) == minStockVal && (bbox.c2 - bbox.c1 + 1) >= minStockVal))))
			return true;
		else
		{
			worksheet.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.StockChartError, c_oAscError.Level.NoCritical)
			return false;
		}
	}
	else
		return true;
}

function formulaToRange(formula, worksheet) {
	var range = null;
	if ( formula && worksheet ) {
		var ref3D = parserHelp.is3DRef(formula, 0);
		if ( !ref3D[0] )
			range = worksheet.getRange2(formula.toUpperCase());
		else {
			var resultRef = parserHelp.parse3DRef(formula);
			if ( null !== resultRef ) {
				var ws = worksheet.workbook.getWorksheetByName(resultRef.sheet);
				if ( ws )
					range = ws.getRange2(resultRef.range);
			}
		}
	}
	return range;
}

function insertChart(chart, activeWorkSheet, width, height, isNewChart) {
	var isSeries = false;
	var formatCell = 'General';
	var formatCellScOy = 'General';
	
	var api_doc = window["editor"];
	var api_sheet = window["Asc"]["editor"];
	var styleManager = api_doc ? api_doc.chartStyleManager : api_sheet.chartStyleManager;
	
	arrBaseColors = styleManager.getBaseColors( parseInt(chart.styleId) );
	if(chart.series && chart.series.length !=0 && window["Asc"]["editor"])
	{
		isSeries = true;
		var series = chart.series;
		//var ws = chart.worksheet;
		var ws = chart.range.intervalObject.worksheet;
		var arrValues = [];
		var max = 0;
		var min = 0; 
		var minY = 0;
		var maxY = 0;
		var isSkip = [];
		var skipSeries = [];
		
		var isEn = false;
		var isEnY = false;
		
		if (chart.type == 'Scatter' && series[0].xVal.Formula != null)//в случае точечной диаграммы отдельная обработка
		{
			var isEnY = false
			for(l = 0; l < series.length; ++l)
			{
				var n = 0;
				
				arrValues[l] = [];
				var formula = formulaToRange(series[l].Val.Formula,ws);
				var xFormula = formulaToRange(series[l].xVal.Formula,ws);
				
				var firstCol = formula.first.col;
{'fraction_non_alphanumeric': 0.1713553348285806, 'fraction_numerical': 0.016148670297981418, 'mean_word_length': 3.196110065429775, 'pattern_counts': {'":': 0, '<': 29, '<?xml version=': 0, '>': 31, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '319202', 'n_tokens_mistral': 20075, 'n_tokens_neox': 16943, 'n_words': 3026}